Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion apps/backend/api-key/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
"compile": "bun build --compile --minify --sourcemap --bytecode ./src/index.ts --outfile server",
"lint": "biome check .",
"fix-lint": "biome check --fix .",
"format": "biome format ."
"format": "biome format .",
"test": "bun test test/"
},
"dependencies": {
"@elysiajs/cors": "catalog:backend",
Expand Down
6 changes: 0 additions & 6 deletions apps/backend/api-key/src/middleware/api-key-auth.ts

This file was deleted.

135 changes: 20 additions & 115 deletions apps/backend/api-key/src/middleware/auth.ts
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,
Comment on lines +19 to +23

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 security Revoked Keys Stay Cached

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.

ttl: 5,
}),
);
50 changes: 0 additions & 50 deletions apps/backend/api-key/src/middleware/cookie-auth.ts

This file was deleted.

128 changes: 128 additions & 0 deletions apps/backend/api-key/test/auth-smoke.test.ts
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");
});
});
1 change: 1 addition & 0 deletions apps/backend/api-key/tests/setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
// Test preload placeholder (was referenced by bunfig.toml).
5 changes: 3 additions & 2 deletions apps/backend/logs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"cleanup": "bun run scripts/cleanup.ts",
"lint": "biome check .",
"fix-lint": "biome check --fix .",
"format": "biome format ."
"format": "biome format .",
"test": "bun test test/"
},
"dependencies": {
"@clickhouse/client": "catalog:backend",
Expand All @@ -38,7 +39,7 @@
"pg": "catalog:db",
"@reloop/db": "workspace:*",
"@reloop/cache": "workspace:*",
"@reloop/apikey": "workspace:*",
"@reloop/auth": "workspace:*",
"@reloop/bus": "workspace:*",
"@paralleldrive/cuid2": "catalog:backend",
"evlog": "catalog:backend"
Expand Down
6 changes: 0 additions & 6 deletions apps/backend/logs/src/middleware/api-key-auth.ts

This file was deleted.

Loading