-
Notifications
You must be signed in to change notification settings - Fork 0
refactor(auth): migrate plain-session batch B to shared plugin (#51) #60
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,121 +1,26 @@ | ||
| import { createId } from "@paralleldrive/cuid2"; | ||
| import { | ||
| createAuthPlugin, | ||
| SESSION_CACHE_REDIS_PREFIX, | ||
| } from "@reloop/auth/middleware"; | ||
| import { RedisCache } from "@reloop/cache/redis-client"; | ||
| import { Elysia } from "elysia"; | ||
| import { log } from "evlog"; | ||
| import { useLogger } from "evlog/elysia"; | ||
| import { validateApiKey } from "./api-key-auth"; | ||
| import { validateSession } from "./cookie-auth"; | ||
| import { apiKeyConfig } from "../api-key.config"; | ||
|
|
||
| if (process.env.NODE_ENV !== "production") { | ||
| if (apiKeyConfig.NODE_ENV !== "production") { | ||
| process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; | ||
| } | ||
|
|
||
| export const authMiddleware = new Elysia({ name: "auth-middleware" }).macro({ | ||
| cookieAuth: { | ||
| async resolve({ status, request: { headers } }) { | ||
| try { | ||
| const log = useLogger(); | ||
| const cookie = headers.get("cookie"); | ||
| const sessionResult = await validateSession(cookie); | ||
| const sessionRedis = new RedisCache( | ||
| SESSION_CACHE_REDIS_PREFIX, | ||
| 5, | ||
| apiKeyConfig.REDIS_URL, | ||
| ); | ||
|
|
||
| if (sessionResult) { | ||
| const traceId = `req_${createId()}`; | ||
| log.set({ | ||
| traceId, | ||
| user: sessionResult.userId, | ||
| organizationId: sessionResult.organizationId, | ||
| }); | ||
| return { ...sessionResult, traceId }; | ||
| } | ||
| return status(401, { message: "Authentication required" }); | ||
| } catch (e) { | ||
| log.error({ | ||
| ...{ | ||
| error: e instanceof Error ? e.message : "Unknown error", | ||
| stack: e instanceof Error ? e.stack : undefined, | ||
| }, | ||
| message: "Authentication error", | ||
| }); | ||
| return status(401, { message: "Authentication failed" }); | ||
| } | ||
| }, | ||
| }, | ||
| apiKeyAuth: { | ||
| async resolve({ status, request: { headers } }) { | ||
| try { | ||
| const log = useLogger(); | ||
| const apiKey = headers.get("x-api-key"); | ||
| const apiKeyResult = await validateApiKey(apiKey); | ||
| if (apiKeyResult) { | ||
| const traceId = `req_${createId()}`; | ||
| log.set({ | ||
| traceId, | ||
| user: apiKeyResult.userId, | ||
| organizationId: apiKeyResult.organizationId, | ||
| }); | ||
| return { ...apiKeyResult, traceId }; | ||
| } | ||
| return status(401, { message: "Authentication required" }); | ||
| } catch (e) { | ||
| log.error({ | ||
| ...{ | ||
| error: e instanceof Error ? e.message : "Unknown error", | ||
| stack: e instanceof Error ? e.stack : undefined, | ||
| }, | ||
| message: "Authentication error", | ||
| }); | ||
| return status(401, { message: "Authentication failed" }); | ||
| } | ||
| }, | ||
| detail: { | ||
| security: [{ apiKey: [] }], | ||
| }, | ||
| }, | ||
| auth: { | ||
| async resolve({ status, request: { headers } }) { | ||
| try { | ||
| const apiKey = | ||
| headers.get("x-api-key") || | ||
| headers.get("authorization")?.replace("Bearer ", ""); | ||
| const cookie = headers.get("cookie"); | ||
| const log = useLogger(); | ||
| const apiKeyResult = await validateApiKey(apiKey); | ||
| if (apiKeyResult) { | ||
| const traceId = `req_${createId()}`; | ||
| log.set({ | ||
| traceId, | ||
| service: "api-key", | ||
| user: apiKeyResult.userId, | ||
| organizationId: apiKeyResult.organizationId, | ||
| }); | ||
| log.info("API key authentication successful"); | ||
| return { ...apiKeyResult, traceId }; | ||
| } | ||
| const sessionResult = await validateSession(cookie); | ||
| if (sessionResult) { | ||
| const traceId = `req_${createId()}`; | ||
| log.set({ | ||
| traceId, | ||
| service: "api-key", | ||
| user: sessionResult.userId, | ||
| organizationId: sessionResult.organizationId, | ||
| }); | ||
| log.info("Session authentication successful"); | ||
| return { ...sessionResult, traceId }; | ||
| } | ||
| return status(401, { message: "Authentication required" }); | ||
| } catch (e) { | ||
| log.error({ | ||
| ...{ | ||
| error: e instanceof Error ? e.message : "Unknown error", | ||
| stack: e instanceof Error ? e.stack : undefined, | ||
| }, | ||
| message: "Authentication error", | ||
| }); | ||
| return status(401, { message: "Authentication failed" }); | ||
| } | ||
| }, | ||
| detail: { | ||
| security: [{ apiKey: [] }], | ||
| }, | ||
| }, | ||
| }); | ||
| /** Batch B migration: shared auth plugin (fail-closed org via `auth`). */ | ||
| export const authMiddleware = new Elysia({ name: "auth-middleware" }).use( | ||
| createAuthPlugin({ | ||
| baseUrl: apiKeyConfig.BASE_URL, | ||
| redis: sessionRedis, | ||
| ttl: 5, | ||
| }), | ||
| ); | ||
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| /** | ||
| * Smoke: webhook batch-A migration onto @reloop/auth/middleware. | ||
| */ | ||
| import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test"; | ||
| import { randomBytes } from "node:crypto"; | ||
| import { | ||
| API_KEY_PREFIX, | ||
| getApiKeyCacheKey, | ||
| hashApiKey, | ||
| } from "@reloop/auth/apikey"; | ||
| import { | ||
| createAuthPlugin, | ||
| type AuthContext, | ||
| } from "@reloop/auth/middleware"; | ||
| import { Elysia } from "elysia"; | ||
|
|
||
| class MemoryRedis { | ||
| private store = new Map<string, string>(); | ||
| constructor(private prefix = "reloop-session") {} | ||
| private full(k: string) { | ||
| return `${this.prefix}:${k}`; | ||
| } | ||
| async get<T>(key: string): Promise<T | undefined> { | ||
| const raw = this.store.get(this.full(key)); | ||
| if (raw === undefined) return undefined; | ||
| try { | ||
| return JSON.parse(raw) as T; | ||
| } catch { | ||
| return raw as unknown as T; | ||
| } | ||
| } | ||
| async set(key: string, value: unknown): Promise<void> { | ||
| this.store.set( | ||
| this.full(key), | ||
| typeof value === "string" ? value : JSON.stringify(value), | ||
| ); | ||
| } | ||
| async delete(key: string): Promise<void> { | ||
| this.store.delete(this.full(key)); | ||
| } | ||
| } | ||
|
|
||
| const sessions = new Map< | ||
| string, | ||
| { userId: string; activeOrganizationId?: string | null } | ||
| >(); | ||
| let fakeAuth: ReturnType<Elysia["listen"]> | null = null; | ||
| let baseUrl = ""; | ||
|
|
||
| beforeAll(async () => { | ||
| const app = new Elysia().get("/api/auth/v1/get-session", ({ request, set }) => { | ||
| const cookie = request.headers.get("cookie") ?? ""; | ||
| const match = cookie.match(/reloop\.session_token=([^.;]+)/); | ||
| const token = match?.[1]; | ||
| if (!token || !sessions.has(token)) { | ||
| set.status = 200; | ||
| return null; | ||
| } | ||
| const s = sessions.get(token)!; | ||
| return { | ||
| user: { | ||
| id: s.userId, | ||
| activeOrganizationId: s.activeOrganizationId ?? null, | ||
| }, | ||
| }; | ||
| }); | ||
| fakeAuth = app.listen(0); | ||
| baseUrl = `http://127.0.0.1:${fakeAuth.server?.port}`; | ||
| }); | ||
| afterAll(() => fakeAuth?.stop()); | ||
| beforeEach(() => sessions.clear()); | ||
|
|
||
| function app(redis: MemoryRedis) { | ||
| return new Elysia() | ||
| .use(createAuthPlugin({ baseUrl, redis, ttl: 5 })) | ||
| .get( | ||
| "/protected", | ||
| ({ userId, organizationId, authType }) => ({ | ||
| userId, | ||
| organizationId, | ||
| authType, | ||
| }), | ||
| { auth: true }, | ||
| ); | ||
| } | ||
|
|
||
| describe("api-key batch-B smoke", () => { | ||
| test("session with org → 200", async () => { | ||
| const redis = new MemoryRedis(); | ||
| sessions.set("tok", { | ||
| userId: "u1", | ||
| activeOrganizationId: "org-1", | ||
| }); | ||
| const res = await app(redis).handle( | ||
| new Request("http://localhost/protected", { | ||
| headers: { cookie: "reloop.session_token=tok.sig" }, | ||
| }), | ||
| ); | ||
| expect(res.status).toBe(200); | ||
| const body = (await res.json()) as AuthContext; | ||
| expect(body.organizationId).toBe("org-1"); | ||
| expect(body.authType).toBe("session"); | ||
| }); | ||
|
|
||
| test("no credentials → 401", async () => { | ||
| const res = await app(new MemoryRedis()).handle( | ||
| new Request("http://localhost/protected"), | ||
| ); | ||
| expect(res.status).toBe(401); | ||
| }); | ||
|
|
||
| test("api key → 200", async () => { | ||
| const redis = new MemoryRedis(); | ||
| const raw = `${API_KEY_PREFIX}_${randomBytes(12).toString("base64url")}`; | ||
| await redis.set(getApiKeyCacheKey(hashApiKey(raw)), { | ||
| userId: "ku", | ||
| organizationId: "ko", | ||
| apiKeyId: "kid", | ||
| }); | ||
| const res = await app(redis).handle( | ||
| new Request("http://localhost/protected", { | ||
| headers: { "x-api-key": raw }, | ||
| }), | ||
| ); | ||
| expect(res.status).toBe(200); | ||
| expect(((await res.json()) as AuthContext).authType).toBe("apikey"); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| // Test preload placeholder (was referenced by bunfig.toml). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This passes the session-scoped Redis cache into the shared auth plugin, and that same Redis object is used for API-key validation. If API-key revocation or eviction still targets the old API-key cache namespace, a key cached through this path is read back from
reloop-session:apikey:v1:*and can keep authenticating until the API-key cache TTL expires.