Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2ac2ad16b |
@@ -19,6 +19,7 @@
|
||||
"@minecraft-account-manager/network": "*",
|
||||
"d3-geo": "^3.1.1",
|
||||
"drizzle-orm": "^0.45.1",
|
||||
"jose": "^6.2.12",
|
||||
"leaflet": "^1.9.4",
|
||||
"next": "^16.3.4",
|
||||
"next-auth": "^4.24.13",
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { afterEach, beforeAll, beforeEach, expect, it, vi } from "vitest";
|
||||
import { exportJWK, generateKeyPair, SignJWT } from "jose";
|
||||
const auth = vi.hoisted(() => ({ session: vi.fn() }));
|
||||
vi.mock("next-auth", () => ({ getServerSession: auth.session }));
|
||||
vi.mock("@/lib/auth/admin-auth", () => ({ adminAuthOptions: {}, requiredAdminRole: "ops" }));
|
||||
const issuer = "https://sso.example/realms/operators";
|
||||
let signed: string;
|
||||
const fetcher = vi.fn();
|
||||
beforeAll(async () => {
|
||||
const keys = await generateKeyPair("RS256");
|
||||
const jwks = { keys: [{ ...await exportJWK(keys.publicKey), kid: "whoami-key", alg: "RS256" }] };
|
||||
fetcher.mockImplementation(async () => Response.json(jwks));
|
||||
signed = await new SignJWT({ resource_access: { portal: { roles: ["ops"] } }, name: "Not exposed", email: "private@example.test" })
|
||||
.setProtectedHeader({ alg: "RS256", kid: "whoami-key" }).setIssuer(issuer).setAudience("portal")
|
||||
.setSubject("machine-subject").setExpirationTime("5m").sign(keys.privateKey);
|
||||
});
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("KEYCLOAK_ISSUER_URL", issuer);
|
||||
vi.stubEnv("KEYCLOAK_CLIENT_ID", "portal");
|
||||
vi.stubGlobal("fetch", fetcher);
|
||||
});
|
||||
afterEach(() => { auth.session.mockReset(); vi.unstubAllEnvs(); vi.unstubAllGlobals(); });
|
||||
|
||||
import { GET as get } from "./route";
|
||||
function request(authorization?: string) {
|
||||
return new Request("https://portal.example/api/admin/whoami", { headers: authorization === undefined ? {} : { authorization } });
|
||||
}
|
||||
it("returns only a safe machine identity through real bearer verification", async () => {
|
||||
auth.session.mockResolvedValue({ user: { roles: ["ops"] } });
|
||||
const response = await get(request(`Bearer ${signed}`));
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
expect(await response.json()).toEqual({ authenticationMethod: "bearer", subject: "machine-subject", name: null, email: null });
|
||||
expect(auth.session).not.toHaveBeenCalled();
|
||||
});
|
||||
it("returns the existing browser identity without roles or session internals", async () => {
|
||||
auth.session.mockResolvedValue({ user: { name: "Admin", email: "admin@example.test", roles: ["ops"], image: "private-image" }, expires: "private-expiry" });
|
||||
const response = await get(request());
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
expect(await response.json()).toEqual({ authenticationMethod: "session", subject: null, name: "Admin", email: "admin@example.test" });
|
||||
});
|
||||
it.each([401, 403, 503])("returns a safe %s problem for browser auth failures", async (status) => {
|
||||
if (status === 503) auth.session.mockRejectedValue(new Error("private-session-error"));
|
||||
else auth.session.mockResolvedValue(status === 401 ? null : { user: { roles: [] } });
|
||||
const response = await get(request());
|
||||
expect(response.status).toBe(status);
|
||||
expect(response.headers.get("content-type")).toBe("application/problem+json");
|
||||
expect(response.headers.get("www-authenticate")).toBe(status === 401 ? 'Bearer realm="admin-api"' : null);
|
||||
expect(await response.json()).toMatchObject({ status, instance: "/api/admin/whoami" });
|
||||
});
|
||||
it("never falls back to browser auth for a supplied invalid token", async () => {
|
||||
auth.session.mockResolvedValue({ user: { roles: ["ops"] } });
|
||||
const response = await get(request("Bearer invalid"));
|
||||
expect(response.status).toBe(401);
|
||||
expect(auth.session).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
import { authorizeAdminApi } from "@/lib/auth/admin-api-auth";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const authorization = await authorizeAdminApi(request);
|
||||
if (authorization.response) return authorization.response;
|
||||
return Response.json(authorization.identity, { headers: { "cache-control": "no-store" } });
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { afterEach, beforeAll, beforeEach, expect, it, vi } from "vitest";
|
||||
import { exportJWK, generateKeyPair, SignJWT } from "jose";
|
||||
const auth = vi.hoisted(() => ({ session: vi.fn() }));
|
||||
vi.mock("next-auth", () => ({ getServerSession: auth.session }));
|
||||
vi.mock("@/lib/auth/admin-auth", () => ({ adminAuthOptions: {}, requiredAdminRole: "ops" }));
|
||||
import { GET as list, POST } from "./route";
|
||||
import { GET as detail } from "./[id]/route";
|
||||
import { GET as messages } from "./[id]/messages/route";
|
||||
const issuer = "https://sso.example/realms/operators";
|
||||
const guildId = "100000000000000001";
|
||||
const forumId = "100000000000000002";
|
||||
const threadId = "100000000000000009";
|
||||
const context = { params: Promise.resolve({ id: threadId }) };
|
||||
const thread = { id: threadId, guild_id: guildId, parent_id: forumId, type: 11, name: "Suggestion", owner_id: "100000000000000003", applied_tags: [], message_count: 0, thread_metadata: { archived: false, locked: false } };
|
||||
let signed: string;
|
||||
let roleless: string;
|
||||
let jwks: unknown;
|
||||
const fetcher = vi.fn();
|
||||
beforeAll(async () => {
|
||||
const keys = await generateKeyPair("RS256");
|
||||
jwks = { keys: [{ ...await exportJWK(keys.publicKey), kid: "suggestions-key", alg: "RS256" }] };
|
||||
const sign = (roles: string[]) => new SignJWT({ resource_access: { portal: { roles } }, realm_access: { roles: ["ops"] } })
|
||||
.setProtectedHeader({ alg: "RS256", kid: "suggestions-key" }).setIssuer(issuer).setAudience("portal")
|
||||
.setSubject("machine-subject").setExpirationTime("5m").sign(keys.privateKey);
|
||||
signed = await sign(["ops"]);
|
||||
roleless = await sign([]);
|
||||
});
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("KEYCLOAK_ISSUER_URL", issuer);
|
||||
vi.stubEnv("KEYCLOAK_CLIENT_ID", "portal");
|
||||
vi.stubEnv("DISCORD_BOT_TOKEN", "test-only-bot-token");
|
||||
vi.stubEnv("DISCORD_GUILD_ID", guildId);
|
||||
vi.stubEnv("DISCORD_SUGGESTIONS_FORUM_ID", forumId);
|
||||
auth.session.mockResolvedValue({ user: { roles: ["ops"] } });
|
||||
fetcher.mockImplementation(async (input: string) => {
|
||||
if (input === `${issuer}/protocol/openid-connect/certs`) return Response.json(jwks);
|
||||
const path = String(input).replace("https://discord.com/api/v10", "");
|
||||
if (path === `/channels/${forumId}`) return Response.json({ id: forumId, guild_id: guildId, type: 15, available_tags: [] });
|
||||
if (path === `/guilds/${guildId}/threads/active`) return Response.json({ threads: [] });
|
||||
if (path === `/channels/${threadId}`) return Response.json(thread);
|
||||
if (path === `/channels/${threadId}/messages/${threadId}`) return new Response(null, { status: 404 });
|
||||
if (path === `/channels/${threadId}/messages?limit=25`) return Response.json([]);
|
||||
throw new Error("Unexpected transport request");
|
||||
});
|
||||
vi.stubGlobal("fetch", fetcher);
|
||||
});
|
||||
afterEach(() => { vi.resetAllMocks(); vi.unstubAllEnvs(); vi.unstubAllGlobals(); });
|
||||
function request(token: string) {
|
||||
return new Request("https://portal.example/api/suggestions", { headers: { authorization: `Bearer ${token}` } });
|
||||
}
|
||||
it.each([list, detail, messages])("accepts signed machine credentials on each read route", async (handler) => {
|
||||
const response = await handler(request(signed), context);
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
expect(auth.session).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([list, detail, messages])("denies invalid or role-less bearer credentials even with an admin session and cached data", async (handler) => {
|
||||
expect((await handler(request(signed), context)).status).toBe(200);
|
||||
fetcher.mockClear();
|
||||
expect((await handler(request("invalid"), context)).status).toBe(401);
|
||||
expect((await handler(request(roleless), context)).status).toBe(403);
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
expect(auth.session).not.toHaveBeenCalled();
|
||||
});
|
||||
it("does not enable writes for machine identities", async () => {
|
||||
const response = await POST(request(signed));
|
||||
expect(response.status).toBe(405);
|
||||
expect(response.headers.get("allow")).toBe("GET, HEAD");
|
||||
expect(auth.session).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -8,6 +8,19 @@ import { GET as messages } from "./[id]/messages/route";
|
||||
const context = { params: Promise.resolve({ id: "100000000000000009" }) };
|
||||
|
||||
const request = () => new Request("https://portal.example/api/suggestions");
|
||||
it.each(["Bearer invalid", "Basic invalid", "", "Bearer", "Bearer a, Bearer b"])("rejects supplied authorization %j without session fallback", async (authorization) => {
|
||||
auth.session.mockResolvedValue({ user: { roles: ["ops"] } });
|
||||
const fetcher = vi.fn();
|
||||
vi.stubGlobal("fetch", fetcher);
|
||||
const response = await GET(new Request(request(), { headers: { authorization } }));
|
||||
expect(response.status).toBe(401);
|
||||
expect(response.headers.get("www-authenticate")).toBe('Bearer realm="admin-api"');
|
||||
expect(response.headers.get("content-type")).toBe("application/problem+json");
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
expect(await response.json()).toMatchObject({ type: "urn:error:unauthorized", status: 401, instance: "/api/suggestions" });
|
||||
expect(auth.session).not.toHaveBeenCalled();
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
afterEach(() => { vi.resetAllMocks(); vi.unstubAllGlobals(); vi.unstubAllEnvs(); });
|
||||
it("serves suggestions to the existing admin session using runtime env configuration", async () => {
|
||||
auth.session.mockResolvedValue({ user: { roles: ["ops"] } });
|
||||
@@ -68,4 +81,5 @@ it("rejects unauthenticated readers with a JSON problem instead of a redirect",
|
||||
expect(response.status).toBe(401);
|
||||
expect(response.headers.get("content-type")).toBe("application/problem+json");
|
||||
expect(response.headers.get("location")).toBeNull();
|
||||
expect(response.headers.get("www-authenticate")).toBe('Bearer realm="admin-api"');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import { afterEach, beforeAll, beforeEach, expect, it, vi } from "vitest";
|
||||
import { exportJWK, generateKeyPair, SignJWT, type JWTPayload } from "jose";
|
||||
|
||||
const auth = vi.hoisted(() => ({ session: vi.fn() }));
|
||||
vi.mock("next-auth", () => ({ getServerSession: auth.session }));
|
||||
vi.mock("./admin-auth", () => ({ adminAuthOptions: {}, requiredAdminRole: "ops" }));
|
||||
const issuer = "https://sso.example/realms/operators";
|
||||
const audience = "portal-admin";
|
||||
let keys: Awaited<ReturnType<typeof generateKeyPair>>;
|
||||
let jwks: { keys: unknown[] };
|
||||
let authorize: typeof import("./admin-api-auth").authorizeAdminApi;
|
||||
const fetcher = vi.fn();
|
||||
|
||||
beforeAll(async () => {
|
||||
keys = await generateKeyPair("RS256");
|
||||
jwks = { keys: [{ ...await exportJWK(keys.publicKey), kid: "test-key", alg: "RS256", use: "sig" }] };
|
||||
});
|
||||
beforeEach(async () => {
|
||||
vi.resetModules();
|
||||
vi.stubEnv("KEYCLOAK_ISSUER_URL", issuer);
|
||||
vi.stubEnv("KEYCLOAK_CLIENT_ID", audience);
|
||||
vi.stubEnv("KEYCLOAK_CLIENT_SECRET", ""); // Machine verification needs no client secret.
|
||||
auth.session.mockResolvedValue({ user: { name: "Browser Admin", email: "admin@example.test", roles: ["ops"] } });
|
||||
fetcher.mockImplementation(async () => Response.json(jwks));
|
||||
vi.stubGlobal("fetch", fetcher);
|
||||
authorize = (await import("./admin-api-auth")).authorizeAdminApi;
|
||||
});
|
||||
afterEach(() => { vi.useRealTimers(); vi.resetAllMocks(); vi.unstubAllGlobals(); vi.unstubAllEnvs(); });
|
||||
|
||||
async function token(overrides: JWTPayload = {}, header: Record<string, unknown> = {}) {
|
||||
return new SignJWT({
|
||||
iss: issuer, aud: audience, sub: "machine-subject", exp: Math.floor(Date.now() / 1000) + 300,
|
||||
resource_access: { [audience]: { roles: ["ops"] } },
|
||||
...overrides,
|
||||
}).setProtectedHeader({ alg: "RS256", kid: "test-key", ...header }).sign(keys.privateKey);
|
||||
}
|
||||
function request(bearer: string) {
|
||||
return new Request("https://portal.example/api/admin/whoami", { headers: { authorization: `Bearer ${bearer}` } });
|
||||
}
|
||||
async function rejected(bearer: string, status = 401) {
|
||||
const result = await authorize(request(bearer));
|
||||
expect(result.identity).toBeUndefined();
|
||||
expect(result.response?.status).toBe(status);
|
||||
expect(result.response?.headers.get("content-type")).toBe("application/problem+json");
|
||||
expect(result.response?.headers.get("cache-control")).toBe("no-store");
|
||||
expect(result.response?.headers.get("www-authenticate")).toBe(status === 401 ? 'Bearer realm="admin-api"' : null);
|
||||
expect(await result.response?.json()).toMatchObject({ status, instance: "/api/admin/whoami" });
|
||||
expect(auth.session).not.toHaveBeenCalled();
|
||||
}
|
||||
|
||||
it("verifies real RS256 signatures and caches only the configured issuer JWKS", async () => {
|
||||
const signed = await token({ email: "private@example.test", name: "Private", arbitrary: "private" }, { jku: "https://attacker.example/keys" });
|
||||
for (let i = 0; i < 2; i++) {
|
||||
expect(await authorize(request(signed))).toEqual({ identity: {
|
||||
authenticationMethod: "bearer", subject: "machine-subject", name: null, email: null,
|
||||
} });
|
||||
}
|
||||
expect(auth.session).not.toHaveBeenCalled();
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
expect(String(fetcher.mock.calls[0]?.[0])).toBe(`${issuer}/protocol/openid-connect/certs`);
|
||||
expect(fetcher.mock.calls[0]?.[1]).toMatchObject({ redirect: "manual", method: "GET" });
|
||||
});
|
||||
it("accepts an audience list and case-insensitive bearer scheme", async () => {
|
||||
const signed = await token({ aud: ["other", audience] });
|
||||
const req = new Request(request(signed), { headers: { authorization: `bEaReR ${signed}` } });
|
||||
expect((await authorize(req)).identity?.subject).toBe("machine-subject");
|
||||
});
|
||||
it.each([
|
||||
["expired", { exp: 1 }], ["missing expiry", { exp: undefined }],
|
||||
["missing subject", { sub: undefined }], ["empty subject", { sub: "" }], ["blank subject", { sub: " " }],
|
||||
["future nbf", { nbf: 9999999999 }], ["wrong issuer", { iss: "https://attacker.example" }],
|
||||
["wrong audience", { aud: "another-client" }], ["missing audience", { aud: undefined }],
|
||||
] satisfies [string, JWTPayload][])("rejects %s despite an available privileged browser session", async (_name, claims) => {
|
||||
await rejected(await token(claims));
|
||||
});
|
||||
it("rejects tampering with a signed payload", async () => {
|
||||
const parts = (await token()).split(".");
|
||||
const payload = JSON.parse(Buffer.from(parts[1]!, "base64url").toString());
|
||||
parts[1] = Buffer.from(JSON.stringify({ ...payload, sub: "tampered" })).toString("base64url");
|
||||
await rejected(parts.join("."));
|
||||
});
|
||||
it.each([
|
||||
undefined, {}, { [audience]: { roles: [] } }, { another: { roles: ["ops"] } },
|
||||
{ [audience]: { roles: "ops" } }, { [audience]: { roles: ["player"] } },
|
||||
])("requires the configured client role, never a realm role (%j)", async (resource_access) => {
|
||||
await rejected(await token({ resource_access, realm_access: { roles: ["ops"] } }), 403);
|
||||
});
|
||||
it("rejects HS256 algorithm confusion", async () => {
|
||||
const signed = await new SignJWT({ iss: issuer, aud: audience, sub: "machine", exp: 9999999999 })
|
||||
.setProtectedHeader({ alg: "HS256", kid: "test-key" }).sign(new TextEncoder().encode("test-only-key-with-at-least-32-bytes"));
|
||||
await rejected(signed);
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
it("rejects an otherwise valid but non-allowlisted asymmetric algorithm", async () => {
|
||||
const ec = await generateKeyPair("ES256");
|
||||
fetcher.mockImplementation(async () => Response.json({ keys: [{ ...await exportJWK(ec.publicKey), kid: "ec-key" }] }));
|
||||
const signed = await new SignJWT({ iss: issuer, aud: audience, sub: "machine", exp: 9999999999 })
|
||||
.setProtectedHeader({ alg: "ES256", kid: "ec-key" }).sign(ec.privateKey);
|
||||
await rejected(signed);
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
it("rejects an unknown signing key", async () => { await rejected(await token({}, { kid: "unknown" })); });
|
||||
it("rejects a signature from an untrusted key even when its kid matches", async () => {
|
||||
const other = await generateKeyPair("RS256");
|
||||
const signed = await new SignJWT({ iss: issuer, aud: audience, sub: "machine", exp: 9999999999 })
|
||||
.setProtectedHeader({ alg: "RS256", kid: "test-key" }).sign(other.privateKey);
|
||||
await rejected(signed);
|
||||
});
|
||||
it("coalesces concurrent JWKS reads and refreshes rotated keys after cooldown", async () => {
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
const signed = await token();
|
||||
const results = await Promise.all(Array.from({ length: 8 }, () => authorize(request(signed))));
|
||||
expect(results.every((result) => result.identity?.subject === "machine-subject")).toBe(true);
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
const rotated = await generateKeyPair("RS256");
|
||||
fetcher.mockImplementation(async () => Response.json({ keys: [{ ...await exportJWK(rotated.publicKey), kid: "rotated-key", alg: "RS256" }] }));
|
||||
const next = await new SignJWT({ iss: issuer, aud: audience, sub: "machine", exp: Math.floor(Date.now() / 1000) + 300, resource_access: { [audience]: { roles: ["ops"] } } })
|
||||
.setProtectedHeader({ alg: "RS256", kid: "rotated-key" }).sign(rotated.privateKey);
|
||||
await rejected(next);
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
vi.setSystemTime(Date.now() + 31_000);
|
||||
expect((await authorize(request(next))).identity?.subject).toBe("machine");
|
||||
expect(fetcher).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it.each(["redirect", "non-JSON", "invalid JWKS", "HTTP failure"])("fails closed on a %s JWKS response", async (kind) => {
|
||||
fetcher.mockImplementation(async () => {
|
||||
if (kind === "redirect") return new Response(null, { status: 302, headers: { location: "https://attacker.example/keys" } });
|
||||
if (kind === "non-JSON") return new Response("private malformed response");
|
||||
if (kind === "invalid JWKS") return Response.json({ keys: "private malformed keys" });
|
||||
return new Response("private upstream failure", { status: 500 });
|
||||
});
|
||||
await rejected(await token(), 503);
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("fails closed and sanitizes a JWKS transport outage", async () => {
|
||||
fetcher.mockRejectedValue(new Error("private network details"));
|
||||
const result = await authorize(request(await token()));
|
||||
expect(result.response?.status).toBe(503);
|
||||
expect(await result.response?.text()).not.toContain("private");
|
||||
expect(auth.session).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(["", "http://sso.example/realms/operators", "not a URL", `${issuer}?query=1`, "https://user:password@sso.example/realm"])("fails closed on unsafe/missing issuer configuration %s", async (value) => {
|
||||
vi.stubEnv("KEYCLOAK_ISSUER_URL", value);
|
||||
await rejected(await token(), 503);
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
it("fails closed on missing client ID", async () => {
|
||||
vi.stubEnv("KEYCLOAK_CLIENT_ID", "");
|
||||
await rejected(await token(), 503);
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([null, { user: {} }, { user: { roles: ["player"] } }])("preserves missing/unauthorized browser behavior (%j)", async (session) => {
|
||||
auth.session.mockResolvedValue(session);
|
||||
const result = await authorize(new Request("https://portal.example/api/admin/whoami"));
|
||||
expect(result.response?.status).toBe(session ? 403 : 401);
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
it("preserves browser identity without requiring machine configuration", async () => {
|
||||
vi.stubEnv("KEYCLOAK_ISSUER_URL", "");
|
||||
expect(await authorize(new Request("https://portal.example/api/admin/whoami"))).toEqual({ identity: {
|
||||
authenticationMethod: "session", subject: null, name: "Browser Admin", email: "admin@example.test",
|
||||
} });
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { getServerSession } from "next-auth";
|
||||
import { createRemoteJWKSet, errors, jwtVerify } from "jose";
|
||||
import { problemDetails } from "@minecraft-account-manager/contracts";
|
||||
import { problemInstance, problemResponse } from "@/lib/problem-response";
|
||||
import { adminAuthOptions, requiredAdminRole } from "./admin-auth";
|
||||
|
||||
export type AdminApiIdentity = {
|
||||
authenticationMethod: "session" | "bearer";
|
||||
subject: string | null;
|
||||
name: string | null;
|
||||
email: string | null;
|
||||
};
|
||||
type Authorization = { identity: AdminApiIdentity; response?: never } | { response: Response; identity?: never };
|
||||
|
||||
function failure(request: Request, status: 401 | 403 | 503): Authorization {
|
||||
const problems = {
|
||||
401: ["unauthorized", "Authentication required", "Supply valid administrator credentials."],
|
||||
403: ["forbidden", "Administrator role required", "This API is restricted to administrators."],
|
||||
503: ["admin-auth-unavailable", "Authentication unavailable", "Administrator authentication is temporarily unavailable."],
|
||||
} as const;
|
||||
const [code, title, detail] = problems[status];
|
||||
const response = problemResponse(problemDetails(`urn:error:${code}`, title, status, detail, problemInstance(request)));
|
||||
if (status === 401) response.headers.set("www-authenticate", 'Bearer realm="admin-api"');
|
||||
return { response };
|
||||
}
|
||||
|
||||
// One bounded, process-local resolver. jose coalesces fetches and refreshes rotated keys.
|
||||
let remote: { issuer: string; keys: ReturnType<typeof createRemoteJWKSet> } | undefined;
|
||||
function bearerConfiguration() {
|
||||
const issuer = process.env.KEYCLOAK_ISSUER_URL?.trim() ?? "";
|
||||
const audience = process.env.KEYCLOAK_CLIENT_ID?.trim() ?? "";
|
||||
const url = new URL(issuer);
|
||||
if (!audience || url.protocol !== "https:" || url.username || url.password || url.search || url.hash) {
|
||||
throw new Error("Invalid administrator authentication configuration");
|
||||
}
|
||||
if (!remote || remote.issuer !== issuer) {
|
||||
// Never discover a key URL from untrusted token claims or headers (jku/x5u/iss).
|
||||
const jwksUrl = new URL(`${issuer.replace(/\/$/, "")}/protocol/openid-connect/certs`);
|
||||
remote = { issuer, keys: createRemoteJWKSet(jwksUrl, {
|
||||
timeoutDuration: 5_000, cooldownDuration: 30_000, cacheMaxAge: 600_000,
|
||||
}) };
|
||||
}
|
||||
return { issuer, audience, keys: remote.keys };
|
||||
}
|
||||
function record(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
async function authorizeBearer(request: Request): Promise<Authorization> {
|
||||
const match = /^Bearer +([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$/i.exec(request.headers.get("authorization") ?? "");
|
||||
if (!match) return failure(request, 401);
|
||||
let configuration: ReturnType<typeof bearerConfiguration>;
|
||||
try {
|
||||
configuration = bearerConfiguration();
|
||||
} catch {
|
||||
return failure(request, 503);
|
||||
}
|
||||
try {
|
||||
const { issuer, audience, keys } = configuration;
|
||||
const { payload } = await jwtVerify(match[1]!, keys, {
|
||||
issuer, audience, algorithms: ["RS256"], requiredClaims: ["exp", "sub"],
|
||||
});
|
||||
if (typeof payload.sub !== "string" || !payload.sub.trim()) return failure(request, 401);
|
||||
const access = payload.resource_access;
|
||||
const client = record(access) && Object.hasOwn(access, audience) ? access[audience] : undefined;
|
||||
const roles = record(client) ? client.roles : undefined;
|
||||
if (!Array.isArray(roles) || !roles.includes(requiredAdminRole)) return failure(request, 403);
|
||||
return { identity: { authenticationMethod: "bearer", subject: payload.sub, name: null, email: null } };
|
||||
} catch (error) {
|
||||
// Verification failures are invalid credentials; transport/configuration failures are unavailable.
|
||||
const invalid = error instanceof errors.JWTClaimValidationFailed || error instanceof errors.JWTExpired
|
||||
|| error instanceof errors.JWSInvalid || error instanceof errors.JWTInvalid
|
||||
|| error instanceof errors.JWSSignatureVerificationFailed || error instanceof errors.JOSEAlgNotAllowed
|
||||
|| error instanceof errors.JWKSNoMatchingKey || error instanceof errors.JOSENotSupported;
|
||||
return failure(request, invalid ? 401 : 503);
|
||||
}
|
||||
}
|
||||
|
||||
/** API-only authorization; never use bearer tokens to authorize browser actions. */
|
||||
export async function authorizeAdminApi(request: Request): Promise<Authorization> {
|
||||
// Presence, including an empty/unsupported header, is authoritative. Never fall back.
|
||||
if (request.headers.has("authorization")) return authorizeBearer(request);
|
||||
try {
|
||||
const session = await getServerSession(adminAuthOptions);
|
||||
if (!session) return failure(request, 401);
|
||||
const roles = (session.user as { roles?: unknown } | undefined)?.roles;
|
||||
if (!Array.isArray(roles) || !roles.includes(requiredAdminRole)) return failure(request, 403);
|
||||
return { identity: {
|
||||
authenticationMethod: "session", subject: null,
|
||||
name: session.user?.name ?? null, email: session.user?.email ?? null,
|
||||
} };
|
||||
} catch {
|
||||
return failure(request, 503);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { getServerSession } from "next-auth";
|
||||
import { problemDetails } from "@minecraft-account-manager/contracts";
|
||||
import { adminAuthOptions, requiredAdminRole } from "@/lib/auth/admin-auth";
|
||||
import { authorizeAdminApi } from "@/lib/auth/admin-api-auth";
|
||||
import { problemInstance, problemResponse } from "@/lib/problem-response";
|
||||
import { createSuggestionsClient, SuggestionsError } from "./suggestions";
|
||||
|
||||
@@ -17,11 +16,9 @@ function getClient() {
|
||||
}
|
||||
|
||||
export async function suggestionsApi(request: Request, operation: (client: Client) => Promise<unknown>) {
|
||||
const authorization = await authorizeAdminApi(request);
|
||||
if (authorization.response) return authorization.response;
|
||||
try {
|
||||
const session = await getServerSession(adminAuthOptions);
|
||||
if (!session) throw new SuggestionsError(401, "unauthorized", "Sign in as an administrator.");
|
||||
const roles = (session.user as { roles?: unknown } | undefined)?.roles;
|
||||
if (!Array.isArray(roles) || !roles.includes(requiredAdminRole)) throw new SuggestionsError(403, "forbidden", "This API is restricted to administrators.");
|
||||
return Response.json(await operation(getClient()), { headers: { "cache-control": "no-store" } });
|
||||
} catch (error) {
|
||||
const safe = error instanceof SuggestionsError ? error : new SuggestionsError(503, "discord-unavailable", "Discord suggestions are unavailable.");
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
# Admin API authentication
|
||||
|
||||
Implemented for `GET /api/admin/whoami` and the read-only [suggestions API](admin-suggestions-api.md). The shared guard is `apps/web/src/lib/auth/admin-api-auth.ts`. This is not browser token login, a general admin mutation API, or the Velocity admission credential mechanism. Browser pages, privileged server actions, RCON, and Velocity authentication are unchanged. OpenAPI publication is separate work (US-026).
|
||||
|
||||
## Credential selection
|
||||
|
||||
- **No Authorization header:** use the existing NextAuth administrator session and its configured role check. Player sessions do not qualify. Existing browser realm/client role behavior remains intact.
|
||||
- **Any Authorization header supplied:** exclusively use bearer authentication. Empty, malformed, duplicated/combined, unsupported, expired, or otherwise invalid credentials never fall back to a browser session, including a privileged session cookie.
|
||||
- The bearer scheme is case-insensitive. Send one compact signed JWT, not a client secret, bot token, or refresh token.
|
||||
|
||||
## Machine verification
|
||||
|
||||
The web application directly depends on `jose` 6. Verification uses real cryptographic signature checking, not decoded-token role extraction:
|
||||
|
||||
- Only **RS256** is accepted.
|
||||
- `iss` must exactly equal the trimmed `KEYCLOAK_ISSUER_URL` configuration.
|
||||
- `aud` must contain `KEYCLOAK_CLIENT_ID` (a string or audience array is supported). `azp` does not substitute for `aud`.
|
||||
- `exp` and a nonblank string `sub` are required. Expired tokens and future `nbf` are rejected with no added clock tolerance.
|
||||
- The required role (configured `KEYCLOAK_REQUIRED_ROLE`, default `minecraft-account-manager-admin`) must appear in `resource_access[KEYCLOAK_CLIENT_ID].roles`. Realm roles or roles for other clients are not accepted.
|
||||
- The configured issuer must be HTTPS with no embedded credentials, query, or fragment. Keys come only from `<issuer-without-final-slash>/protocol/openid-connect/certs`; token `iss`, `jku`, and `x5u` never select a key URL. Redirects are not followed.
|
||||
|
||||
One bounded, process-local remote JWKS resolver caches keys for ten minutes, coalesces concurrent fetches, permits refresh for unknown keys after a 30-second cooldown, and bounds each network fetch to five seconds. A changed configured issuer replaces the resolver. Replicas do not share the cache. Key rotation can temporarily reject a new key during cooldown; removed keys may remain usable until the cache refreshes. Access-token validity is local JWT verification, not per-request revocation/introspection. Use suitably short token lifetimes and synchronized clocks.
|
||||
|
||||
`KEYCLOAK_CLIENT_SECRET` is not needed for machine verification. This implementation does not obtain tokens or alter identity-provider clients, role/audience mappers, credentials, or deployments. See [OIDC setup](admin-oidc-keycloak-setup.md) for the distinct browser configuration.
|
||||
|
||||
## Safe identity endpoint
|
||||
|
||||
`GET /api/admin/whoami` authenticates and checks administrator permission before returning JSON with `Cache-Control: no-store`:
|
||||
|
||||
```json
|
||||
{
|
||||
"authenticationMethod": "bearer",
|
||||
"subject": "machine-subject",
|
||||
"name": null,
|
||||
"email": null
|
||||
}
|
||||
```
|
||||
|
||||
For browser sessions, `authenticationMethod` is `session`, `subject` is `null` (the existing session does not expose it), and `name`/`email` are the existing session values or `null`. Machine profile claims are not returned. No raw token, role list, session expiry, key material, client secret, or arbitrary claims are exposed. This endpoint requires no Discord or database access.
|
||||
|
||||
## Failures
|
||||
|
||||
All guard failures use RFC 9457 `application/problem+json`, `Cache-Control: no-store`, a matching HTTP/body status, and a request-path instance. There are no sign-in redirects or token/error-detail logs.
|
||||
|
||||
| Status | Type | Meaning |
|
||||
| --- | --- | --- |
|
||||
| 401 | `urn:error:unauthorized` | Missing session or invalid supplied credentials; includes `WWW-Authenticate: Bearer realm="admin-api"`. |
|
||||
| 403 | `urn:error:forbidden` | Authenticated identity lacks the required permission. |
|
||||
| 503 | `urn:error:admin-auth-unavailable` | Invalid/missing machine configuration, JWKS transport/format failure, or browser session service failure. |
|
||||
|
||||
Authentication is checked before suggestions cache access or Discord requests. Valid machine credentials do not enable writes: suggestions write methods remain 405. Errors do not reveal credentials, raw claims, upstream response bodies, or exception messages.
|
||||
|
||||
## Verification and rollout boundary
|
||||
|
||||
Focused coverage lives in:
|
||||
|
||||
- `apps/web/src/lib/auth/admin-api-auth.test.ts`: real signed JWTs, controlled JWKS HTTP transport (not mocked `jwtVerify`), validation failures, client-role isolation, configuration/network safety, caching, concurrent reads, and rotation.
|
||||
- `apps/web/src/app/api/admin/whoami/route.test.ts`: safe identity projection and guard failures through the route.
|
||||
- `apps/web/src/app/api/suggestions/{route,machine-auth}.test.ts`: browser regression, bearer precedence, all three read routes, cache authorization, and read-only behavior.
|
||||
|
||||
Run from the source repository:
|
||||
|
||||
```sh
|
||||
npm test --workspace @minecraft-account-manager/web -- src/lib/auth/admin-api-auth.test.ts src/app/api/admin/whoami/route.test.ts src/app/api/suggestions
|
||||
npm test
|
||||
npm run lint
|
||||
npm run typecheck
|
||||
npm run build
|
||||
npm run velocity:build
|
||||
```
|
||||
|
||||
### Test-first implementation evidence (US-025)
|
||||
|
||||
The following runs were observed against the local implementation; no commit or publication is part of this task:
|
||||
|
||||
| Slice / focused test arguments after `npm test --workspace @minecraft-account-manager/web --` | Red before implementation | Green after implementation |
|
||||
| --- | --- | --- |
|
||||
| `src/app/api/suggestions/route.test.ts` | 6 failures: supplied headers fell through to the browser path (503 instead of 401), and missing-session 401 lacked the challenge. | 21 passing after shared-guard integration. |
|
||||
| `src/lib/auth/admin-api-auth.test.ts` | 15 failures: valid signed tokens were rejected; client-role and unavailable-service responses were not implemented. | 53 passing with the suggestions regression suite after actual JWT/JWKS verification. |
|
||||
| `src/app/api/admin/whoami/route.test.ts` | 6 explicit route-absence assertion failures (suite ran without a broken module import). | 59 passing across all three suites after adding the route; route discovery then refactored to a direct import. |
|
||||
|
||||
Additional integration/resilience regression coverage brought the focused suite to **72 passing tests**: every suggestions read route, authorization before cached reads, unchanged write denial, untrusted signing keys, algorithm restrictions, concurrent JWKS fetching, key rotation, malformed upstream responses, and redirect refusal. Negative-token tests use an available privileged browser session to verify that invalid bearer credentials never fall back. The tests sign actual JWTs and exercise `jose` verification against controlled transport responses; `jwtVerify` is never mocked.
|
||||
|
||||
Full local verification passed: `npm test` (**252 tests**, including 214 web tests), `npm run lint` (zero errors; two existing navigation warnings in unchanged `map-view-toggle.tsx`), `npm run typecheck`, `npm run build` (whoami emitted as a dynamic route), and `npm run velocity:build` (`clean test shadowJar`, Java 17). The unrelated `next-env.d.ts` addition generated by Next.js during the build was removed to keep the source diff scoped.
|
||||
|
||||
Security scan: `semgrep scan --config p/typescript --config p/jwt --metrics=off` on the shared guard, suggestions wrapper, and whoami implementation completed with **74 rules, three files, zero findings**. The initial `--config auto --metrics=off` invocation was rejected by Semgrep; the explicit-rule run is the successful result. This is scoped static-analysis evidence, not a complete security audit.
|
||||
|
||||
Offline tests do not establish live Keycloak audience/role issuance, JWKS reachability, or production authorization. Production deployment remains separately gated. After explicit release approval, verify machine whoami and suggestions reads, rejection of an unauthorized identity, and browser session access using approved credential handling (never token values in chat, command arguments, or logs).
|
||||
@@ -1,6 +1,6 @@
|
||||
# Admin OIDC setup
|
||||
|
||||
The admin console will use Keycloak OIDC and JWT-backed Auth.js sessions, following the established pattern in the sibling Retro application.
|
||||
The admin console uses Keycloak OIDC and JWT-backed NextAuth sessions.
|
||||
|
||||
## Application environment
|
||||
|
||||
@@ -21,4 +21,10 @@ Allow exact callback and logout URLs for each environment. Avoid wildcard origin
|
||||
|
||||
Create the realm role `minecraft-account-manager-admin` and assign it directly or through an admin group. Ensure realm roles are emitted in `realm_access.roles`.
|
||||
|
||||
The admin console will reject sign-in when the required role is absent, even when Keycloak authentication itself succeeds.
|
||||
The admin console rejects sign-in when the required role is absent, even when Keycloak authentication itself succeeds. Existing browser sign-in accepts realm or configured-client roles; this behavior is unchanged.
|
||||
|
||||
## Read-only machine API access
|
||||
|
||||
The [admin API guard](admin-api-authentication.md) independently verifies signed Keycloak access tokens. Machine tokens must include `KEYCLOAK_CLIENT_ID` in `aud` and `KEYCLOAK_REQUIRED_ROLE` in `resource_access[KEYCLOAK_CLIENT_ID].roles`. A realm role alone is **not** sufficient for bearer access. The identity provider must emit both the portal audience and this client role; a token's `azp` is not an audience substitute.
|
||||
|
||||
Verification uses the HTTPS issuer's `/protocol/openid-connect/certs` JWKS endpoint and RS256 only. It does not use `KEYCLOAK_CLIENT_SECRET`, exchange tokens, or create a browser session. Browser client configuration above remains required for interactive SSO. Provisioning or changing machine clients, role/audience mappers, credentials, and production deployment requires separate operational approval; this source implementation performs none of those operations.
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
# Admin suggestions API
|
||||
|
||||
The portal provides a read-only view of one Discord **forum channel**, using the existing NextAuth admin session and configured Keycloak role. Player sessions and Discord bot credentials are not accepted as API credentials. Sign in at `/admin/login` first; same-origin browser calls send the session cookie. Unattended machine authentication is not provided.
|
||||
The portal provides a read-only view of one Discord **forum channel**, using the existing NextAuth admin session or a verified Keycloak machine bearer token. Player sessions and Discord bot credentials are not accepted as API credentials. Browser users sign in at `/admin/login`; same-origin calls send the session cookie. Machine clients use `Authorization: Bearer <access-token>` with the configured portal audience and **client** role. See [Admin API authentication](admin-api-authentication.md) for verification rules, safe identity checks, and failure behavior.
|
||||
|
||||
## Portal interface
|
||||
|
||||
Open `/admin/suggestions` from the administrator navigation. The idea desk lists active or archived forum posts with tags, status, approximate message counts, author IDs, timestamps, and Discord links. Select a title to open `/admin/suggestions/:id`, read the starter post and its reaction counts, and page through discussion newest-first. The starter is not duplicated in the discussion view.
|
||||
|
||||
The UI uses these same session-protected GET endpoints, not a second integration. Both pages independently check admin access before rendering; the APIs recheck it on every read. Expired/unauthorized API access offers an admin sign-in link. Loading, empty/deleted content, missing-text, and retryable failure states are explicit. Changing status aborts obsolete requests, and pagination restores keyboard focus to the page indicator. Text is rendered literally with React escaping, never as HTML or interpreted Discord Markdown. No bot token, forum configuration value, reply input, vote button, or moderation control is added to the client bundle.
|
||||
The UI uses these same admin-protected GET endpoints with its browser session, not a second integration. Both pages independently check admin access before rendering; the APIs recheck it on every read. Expired/unauthorized API access offers an admin sign-in link. Loading, empty/deleted content, missing-text, and retryable failure states are explicit. Changing status aborts obsolete requests, and pagination restores keyboard focus to the page indicator. Text is rendered literally with React escaping, never as HTML or interpreted Discord Markdown. No bot token, forum configuration value, reply input, vote button, or moderation control is added to the client bundle.
|
||||
|
||||
Pagination history is page-local and resets when switching status or leaving the page. Reload the browser to refresh a view; upstream reads may use the documented 30-second cache. The real forum ID is still configured only through GitOps, not the UI or source.
|
||||
|
||||
@@ -37,8 +37,9 @@ Suggestion fields: `id`, `title`, `authorId`, `createdAt`, `archived`, `locked`,
|
||||
|
||||
Errors use RFC 9457 `application/problem+json`, HTTP-matching `status`, stable `urn:error:*` types, and safe details:
|
||||
|
||||
- `401 unauthorized`: no admin session; no redirect.
|
||||
- `403 forbidden`: session lacks the required role.
|
||||
- `401 unauthorized`: no admin session or invalid supplied credentials; no redirect; includes `WWW-Authenticate: Bearer realm="admin-api"`.
|
||||
- `403 forbidden`: verified identity lacks the required role (configured-client role for bearer tokens).
|
||||
- `503 admin-auth-unavailable`: authentication configuration, browser session service, or JWKS service unavailable; no session fallback for supplied credentials.
|
||||
- `400 invalid-request`: invalid ID, cursor, limit, status, or list/message query parameter.
|
||||
- `404 suggestion-not-found`: inaccessible/deleted thread, or thread outside the configured forum.
|
||||
- `405 method-not-allowed`: writes are unsupported; `Allow: GET, HEAD`.
|
||||
|
||||
Generated
+10
@@ -44,6 +44,7 @@
|
||||
"@minecraft-account-manager/network": "*",
|
||||
"d3-geo": "^3.1.1",
|
||||
"drizzle-orm": "^0.45.1",
|
||||
"jose": "^6.2.12",
|
||||
"leaflet": "^1.9.4",
|
||||
"next": "^16.3.4",
|
||||
"next-auth": "^4.24.13",
|
||||
@@ -70,6 +71,15 @@
|
||||
"vitest": "^4.1.0"
|
||||
}
|
||||
},
|
||||
"apps/web/node_modules/jose": {
|
||||
"version": "6.2.12",
|
||||
"resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz",
|
||||
"integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/panva"
|
||||
}
|
||||
},
|
||||
"node_modules/@alloc/quick-lru": {
|
||||
"version": "5.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz",
|
||||
|
||||
Reference in New Issue
Block a user