Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+60
@@ -0,0 +1,60 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({ createAuditEvent: vi.fn() }));
|
||||
vi.mock("@hivegrid/db/admin-sso.server", () => ({ appendPreauthAdminSsoAuditEvent: vi.fn() }));
|
||||
vi.mock("@hivegrid/db/rls-context.server", () => ({ getRlsExecutionContext: vi.fn() }));
|
||||
vi.mock("~/utils/server/IpUtils", () => ({ getTrustedClientIpOrNull: vi.fn(() => "192.0.2.1") }));
|
||||
|
||||
import { appendPreauthAdminSsoAuditEvent } from "@hivegrid/db/admin-sso.server";
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
|
||||
import { writeAdminSsoAuditEvent } from "./audit.server";
|
||||
|
||||
describe("Admin SSO audit RLS boundary", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getRlsExecutionContext).mockReturnValue(null);
|
||||
});
|
||||
|
||||
it("uses the narrow platform append capability before an operator identity exists", async () => {
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.sso.failure",
|
||||
request: new Request("https://admin.example.test/auth/admin/callback", { headers: { "user-agent": "test-agent" } }),
|
||||
meta: { stage: "claims" },
|
||||
});
|
||||
|
||||
expect(appendPreauthAdminSsoAuditEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: "admin.login.sso.failure",
|
||||
actorType: "admin",
|
||||
sourceModule: "admin-sso",
|
||||
outcome: "failure",
|
||||
})
|
||||
);
|
||||
expect(createAuditEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the regular operator-scoped chain once app.user_id is bound", async () => {
|
||||
vi.mocked(getRlsExecutionContext).mockReturnValue({ userId: "admin_1" });
|
||||
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.sso.success",
|
||||
actorAdminUserId: "admin_1",
|
||||
});
|
||||
|
||||
expect(createAuditEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: "admin.login.sso.success",
|
||||
actorId: "admin_1",
|
||||
outcome: "success",
|
||||
})
|
||||
);
|
||||
expect(appendPreauthAdminSsoAuditEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps audit failures non-blocking for the login flow", async () => {
|
||||
vi.mocked(appendPreauthAdminSsoAuditEvent).mockRejectedValueOnce(new Error("database unavailable"));
|
||||
|
||||
await expect(writeAdminSsoAuditEvent({ action: "admin.login.sso.failure" })).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
+14
-4
@@ -6,7 +6,10 @@
|
||||
* `@hivegrid/db/audit-events.server` which already handles redaction.
|
||||
*/
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { appendPreauthAdminSsoAuditEvent } from "@hivegrid/db/admin-sso.server";
|
||||
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { getTrustedClientIpOrNull } from "~/utils/server/IpUtils";
|
||||
|
||||
export type AdminSsoAuditAction =
|
||||
| "admin.login.sso.success"
|
||||
@@ -27,8 +30,7 @@ export type AdminSsoAuditInput = {
|
||||
|
||||
function clientMeta(request: Request | undefined): { ip: string | null; userAgent: string | null } {
|
||||
if (!request) return { ip: null, userAgent: null };
|
||||
const fwd = request.headers.get("x-forwarded-for") ?? "";
|
||||
const ip = fwd.split(",")[0]?.trim() || request.headers.get("x-real-ip") || null;
|
||||
const ip = getTrustedClientIpOrNull(request);
|
||||
const userAgent = request.headers.get("user-agent") || null;
|
||||
return { ip, userAgent };
|
||||
}
|
||||
@@ -36,17 +38,25 @@ function clientMeta(request: Request | undefined): { ip: string | null; userAgen
|
||||
export async function writeAdminSsoAuditEvent(input: AdminSsoAuditInput): Promise<void> {
|
||||
const { ip, userAgent } = clientMeta(input.request);
|
||||
try {
|
||||
await createAuditEvent({
|
||||
const auditInput = {
|
||||
action: input.action,
|
||||
actorType: "admin",
|
||||
actorId: input.actorAdminUserId ?? null,
|
||||
sourceModule: "admin-sso",
|
||||
outcome: input.action.endsWith(".failure") ? "failure" : "success",
|
||||
dataSensitivity: "internal",
|
||||
metadata: {
|
||||
ssoSubjectId: input.ssoSubjectId ?? null,
|
||||
ip,
|
||||
userAgent,
|
||||
...input.meta,
|
||||
} as unknown as Prisma.InputJsonValue,
|
||||
});
|
||||
} as const;
|
||||
if (getRlsExecutionContext()?.userId) {
|
||||
await createAuditEvent(auditInput);
|
||||
} else {
|
||||
await appendPreauthAdminSsoAuditEvent(auditInput);
|
||||
}
|
||||
} catch {
|
||||
// Audit failures must never block the auth flow. The DB-level error
|
||||
// already lands in Sentry via the audit-events boundary.
|
||||
|
||||
+40
-30
@@ -1,32 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { extractAdminSsoClaims, hasAllowedAdminGroup, isAllowedAdminGroup, mapGroupsToRole } from "./claims.server";
|
||||
|
||||
describe("mapGroupsToRole", () => {
|
||||
it("maps hivegrid-admin to super_admin", () => {
|
||||
expect(mapGroupsToRole(["hivegrid-admin"])).toBe("super_admin");
|
||||
});
|
||||
|
||||
it("maps hivegrid-staff to staff", () => {
|
||||
expect(mapGroupsToRole(["hivegrid-staff"])).toBe("staff");
|
||||
});
|
||||
|
||||
it("prefers super_admin when both groups are present", () => {
|
||||
expect(mapGroupsToRole(["hivegrid-staff", "hivegrid-admin"])).toBe("super_admin");
|
||||
});
|
||||
|
||||
it("returns null for an unknown group", () => {
|
||||
expect(mapGroupsToRole(["random-group"])).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for an empty list", () => {
|
||||
expect(mapGroupsToRole([])).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for null/undefined input", () => {
|
||||
expect(mapGroupsToRole(undefined)).toBeNull();
|
||||
expect(mapGroupsToRole(null)).toBeNull();
|
||||
});
|
||||
});
|
||||
import { extractAdminSsoClaims, hasAllowedAdminGroup, isAllowedAdminGroup } from "./claims.server";
|
||||
|
||||
describe("isAllowedAdminGroup / hasAllowedAdminGroup", () => {
|
||||
it("recognizes the two allowlisted groups", () => {
|
||||
@@ -44,6 +17,12 @@ describe("isAllowedAdminGroup / hasAllowedAdminGroup", () => {
|
||||
it("returns true when at least one allowed group is present", () => {
|
||||
expect(hasAllowedAdminGroup(["other", "hivegrid-staff"])).toBe(true);
|
||||
});
|
||||
|
||||
it("treats both allowed groups identically as access gates", () => {
|
||||
expect(hasAllowedAdminGroup(["hivegrid-admin"])).toBe(true);
|
||||
expect(hasAllowedAdminGroup(["hivegrid-staff"])).toBe(true);
|
||||
expect(hasAllowedAdminGroup(["hivegrid-staff", "hivegrid-admin"])).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractAdminSsoClaims", () => {
|
||||
@@ -53,6 +32,7 @@ describe("extractAdminSsoClaims", () => {
|
||||
email_verified: true,
|
||||
name: "Admin Person",
|
||||
groups: ["hivegrid-admin"],
|
||||
amr: ["pwd", "mfa"],
|
||||
};
|
||||
|
||||
it("extracts and normalizes a valid claim set", () => {
|
||||
@@ -64,6 +44,7 @@ describe("extractAdminSsoClaims", () => {
|
||||
expect(result.claims.name).toBe("Admin Person");
|
||||
expect(result.claims.groups).toEqual(["hivegrid-admin"]);
|
||||
expect(result.claims.emailVerified).toBe(true);
|
||||
expect(result.claims.authenticationMethods).toEqual(["pwd", "mfa"]);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -97,11 +78,18 @@ describe("extractAdminSsoClaims", () => {
|
||||
if (!result.ok) expect(result.reason).toBe("email-not-verified");
|
||||
});
|
||||
|
||||
it("treats missing email_verified as true (Authentik does not always emit it)", () => {
|
||||
it("rejects a missing email_verified claim", () => {
|
||||
const claims = { ...validClaims } as Record<string, unknown>;
|
||||
delete claims.email_verified;
|
||||
const result = extractAdminSsoClaims(claims);
|
||||
expect(result.ok).toBe(true);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.reason).toBe("email-not-verified");
|
||||
});
|
||||
|
||||
it("rejects malformed truthy email_verified claims", () => {
|
||||
const result = extractAdminSsoClaims({ ...validClaims, email_verified: "true" });
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.reason).toBe("email-not-verified");
|
||||
});
|
||||
|
||||
it("filters non-string entries from groups", () => {
|
||||
@@ -110,6 +98,28 @@ describe("extractAdminSsoClaims", () => {
|
||||
if (result.ok) expect(result.claims.groups).toEqual(["hivegrid-admin", "ok"]);
|
||||
});
|
||||
|
||||
it("canonicalizes duplicate groups emitted by overlapping Authentik scope mappings", () => {
|
||||
const result = extractAdminSsoClaims({
|
||||
...validClaims,
|
||||
groups: ["authentik Admins", "sogo-users", "hivegrid-admin", "authentik Admins", "sogo-users", "hivegrid-admin"],
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(result.claims.groups).toEqual(["authentik Admins", "sogo-users", "hivegrid-admin"]);
|
||||
}
|
||||
});
|
||||
|
||||
it("extracts only string authentication methods and defaults missing amr to an empty list", () => {
|
||||
const filtered = extractAdminSsoClaims({ ...validClaims, amr: ["pwd", null, 7, "mfa"] });
|
||||
expect(filtered.ok).toBe(true);
|
||||
if (filtered.ok) expect(filtered.claims.authenticationMethods).toEqual(["pwd", "mfa"]);
|
||||
|
||||
const missing = extractAdminSsoClaims({ ...validClaims, amr: undefined });
|
||||
expect(missing.ok).toBe(true);
|
||||
if (missing.ok) expect(missing.claims.authenticationMethods).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns missing-sub for null claims", () => {
|
||||
const result = extractAdminSsoClaims(null);
|
||||
expect(result.ok).toBe(false);
|
||||
|
||||
+14
-31
@@ -1,39 +1,23 @@
|
||||
/**
|
||||
* Phase 09 Task #82 — OIDC ID-token claim extraction + group→role mapping.
|
||||
*
|
||||
* The "role" returned here is the *current* AdminUser identity layer in the
|
||||
* HiveGrid boilerplate. Today the only durable AdminUser concept is "exists
|
||||
* or not"; the spec adds two granular roles (`super_admin`, `staff`) that
|
||||
* we persist as `ssoGroups` snapshots while we wait for the permissions
|
||||
* matrix to grow first-class role columns. Callers should treat the role
|
||||
* as advisory + future-proof.
|
||||
* OIDC ID-token claim extraction and the narrow Authentik access gate.
|
||||
* Authentik groups never map to HiveGrid roles. They only decide whether an
|
||||
* already prepared AdminUser may enter the subject-binding flow.
|
||||
*/
|
||||
|
||||
export type AuthentikGroup = "hivegrid-admin" | "hivegrid-staff";
|
||||
export type AdminSsoRole = "super_admin" | "staff";
|
||||
|
||||
export const ADMIN_GROUP: AuthentikGroup = "hivegrid-admin";
|
||||
export const STAFF_GROUP: AuthentikGroup = "hivegrid-staff";
|
||||
|
||||
export const ALLOWED_ADMIN_GROUPS: readonly AuthentikGroup[] = [ADMIN_GROUP, STAFF_GROUP];
|
||||
|
||||
/**
|
||||
* Highest-priority-wins mapping. If a user is in BOTH groups they get
|
||||
* super_admin (admins are a strict superset of staff for our purposes).
|
||||
*/
|
||||
export function mapGroupsToRole(groups: readonly string[] | undefined | null): AdminSsoRole | null {
|
||||
if (!groups || groups.length === 0) return null;
|
||||
if (groups.includes(ADMIN_GROUP)) return "super_admin";
|
||||
if (groups.includes(STAFF_GROUP)) return "staff";
|
||||
return null;
|
||||
}
|
||||
|
||||
export type AdminSsoClaims = {
|
||||
readonly subject: string;
|
||||
readonly email: string;
|
||||
readonly emailVerified: boolean;
|
||||
readonly name: string;
|
||||
readonly groups: readonly string[];
|
||||
readonly authenticationMethods: readonly string[];
|
||||
};
|
||||
|
||||
export type ClaimExtractionResult =
|
||||
@@ -58,18 +42,18 @@ export function extractAdminSsoClaims(idTokenClaims: Record<string, unknown> | n
|
||||
if (!email) {
|
||||
return { ok: false, reason: "missing-email" };
|
||||
}
|
||||
// Spec security note: "email_verified=true prüfen". If the claim is
|
||||
// absent we treat it as `true` only when the IdP is the trusted
|
||||
// Authentik provider (which mints `email_verified` for SSO accounts);
|
||||
// if it is present and false, reject.
|
||||
const emailVerifiedClaim = idTokenClaims.email_verified;
|
||||
const emailVerified = emailVerifiedClaim === undefined ? true : emailVerifiedClaim === true;
|
||||
// The IdP must assert verification explicitly. Missing, malformed, and
|
||||
// false claims all fail closed so a claim-mapping regression cannot bind
|
||||
// an unverified operator identity.
|
||||
const emailVerified = idTokenClaims.email_verified === true;
|
||||
if (!emailVerified) {
|
||||
return { ok: false, reason: "email-not-verified" };
|
||||
}
|
||||
const rawGroups = idTokenClaims.groups;
|
||||
const groups: string[] = Array.isArray(rawGroups)
|
||||
? rawGroups.filter((g): g is string => typeof g === "string" && g.length > 0)
|
||||
const groups: string[] = Array.isArray(rawGroups) ? [...new Set(rawGroups.filter((g): g is string => typeof g === "string" && g.length > 0))] : [];
|
||||
const rawAuthenticationMethods = idTokenClaims.amr;
|
||||
const authenticationMethods: string[] = Array.isArray(rawAuthenticationMethods)
|
||||
? rawAuthenticationMethods.filter((method): method is string => typeof method === "string" && method.length > 0)
|
||||
: [];
|
||||
const nameFromClaim = typeof idTokenClaims.name === "string" ? idTokenClaims.name.trim() : "";
|
||||
const preferredName = typeof idTokenClaims.preferred_username === "string" ? idTokenClaims.preferred_username.trim() : "";
|
||||
@@ -82,14 +66,13 @@ export function extractAdminSsoClaims(idTokenClaims: Record<string, unknown> | n
|
||||
emailVerified,
|
||||
name,
|
||||
groups,
|
||||
authenticationMethods,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience guard: pass-through that throws (or returns a Response) when
|
||||
* the user has no allowed group. Kept here so the JIT-provisioning logic
|
||||
* stays focused on the DB upsert.
|
||||
* Convenience guard for Authentik's coarse admin-login allowlist.
|
||||
*/
|
||||
export function isAllowedAdminGroup(group: string): group is AuthentikGroup {
|
||||
return ALLOWED_ADMIN_GROUPS.includes(group as AuthentikGroup);
|
||||
|
||||
+46
@@ -6,6 +6,7 @@ describe("readAdminSsoEnv", () => {
|
||||
AUTHENTIK_ISSUER_URL: "https://auth.example.test/application/o/hivegrid-admin-panel/",
|
||||
AUTHENTIK_ADMIN_CLIENT_ID: "hivegrid-admin-panel",
|
||||
AUTHENTIK_ADMIN_CLIENT_SECRET: "shh",
|
||||
AUTHENTIK_ADMIN_JIT_DATABASE_URL: "postgresql://hivegrid_authentik_jit:secret@db.example.test:5432/hivegrid",
|
||||
AUTHENTIK_ADMIN_REDIRECT_URI: "https://admin.example.test/auth/admin/callback",
|
||||
};
|
||||
|
||||
@@ -30,9 +31,53 @@ describe("readAdminSsoEnv", () => {
|
||||
expect(message).toContain("AUTHENTIK_ISSUER_URL");
|
||||
expect(message).toContain("AUTHENTIK_ADMIN_CLIENT_ID");
|
||||
expect(message).toContain("AUTHENTIK_ADMIN_CLIENT_SECRET");
|
||||
expect(message).toContain("AUTHENTIK_ADMIN_JIT_DATABASE_URL");
|
||||
expect(message).toContain("AUTHENTIK_ADMIN_REDIRECT_URI");
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects non-TLS remote endpoints and URL credentials", () => {
|
||||
expect(() => readAdminSsoEnv({ ...baseEnv, AUTHENTIK_ISSUER_URL: "http://auth.example.test/issuer" })).toThrowError(
|
||||
/must use HTTPS/,
|
||||
);
|
||||
expect(() => readAdminSsoEnv({ ...baseEnv, AUTHENTIK_ISSUER_URL: "https://user:password@auth.example.test/issuer" })).toThrowError(
|
||||
/must not contain URL credentials/,
|
||||
);
|
||||
});
|
||||
|
||||
it("requires the exact callback path and a same-origin logout redirect", () => {
|
||||
expect(() => readAdminSsoEnv({ ...baseEnv, AUTHENTIK_ADMIN_REDIRECT_URI: "https://admin.example.test/wrong" })).toThrowError(
|
||||
/exact \/auth\/admin\/callback path/,
|
||||
);
|
||||
expect(() =>
|
||||
readAdminSsoEnv({
|
||||
...baseEnv,
|
||||
AUTHENTIK_ADMIN_POST_LOGOUT_REDIRECT_URI: "https://evil.example.test/login?logged_out=1",
|
||||
}),
|
||||
).toThrowError(/must use the admin callback origin/);
|
||||
});
|
||||
|
||||
it("requires the prepared-admin binding capability to use its dedicated login role", () => {
|
||||
expect(() =>
|
||||
readAdminSsoEnv({
|
||||
...baseEnv,
|
||||
AUTHENTIK_ADMIN_JIT_DATABASE_URL: "postgresql://hivegrid_app:secret@db.example.test:5432/hivegrid",
|
||||
}),
|
||||
).toThrowError(/must authenticate as hivegrid_authentik_jit/);
|
||||
});
|
||||
|
||||
it("permits HTTP only for loopback development", () => {
|
||||
expect(
|
||||
readAdminSsoEnv({
|
||||
...baseEnv,
|
||||
AUTHENTIK_ISSUER_URL: "http://127.0.0.1:9000/application/o/hivegrid-admin-panel/",
|
||||
AUTHENTIK_ADMIN_REDIRECT_URI: "http://localhost:3000/auth/admin/callback",
|
||||
}),
|
||||
).toMatchObject({
|
||||
issuerUrl: "http://127.0.0.1:9000/application/o/hivegrid-admin-panel/",
|
||||
redirectUri: "http://localhost:3000/auth/admin/callback",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("isAdminSsoConfigured", () => {
|
||||
@@ -42,6 +87,7 @@ describe("isAdminSsoConfigured", () => {
|
||||
AUTHENTIK_ISSUER_URL: "https://auth.example.test/",
|
||||
AUTHENTIK_ADMIN_CLIENT_ID: "id",
|
||||
AUTHENTIK_ADMIN_CLIENT_SECRET: "secret",
|
||||
AUTHENTIK_ADMIN_JIT_DATABASE_URL: "postgresql://hivegrid_authentik_jit:secret@db.example.test:5432/hivegrid",
|
||||
AUTHENTIK_ADMIN_REDIRECT_URI: "https://admin.example.test/auth/admin/callback",
|
||||
})
|
||||
).toBe(true);
|
||||
|
||||
+62
-2
@@ -11,17 +11,19 @@
|
||||
* page rather than a 500.
|
||||
*/
|
||||
import { Issuer, type Client } from "openid-client";
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
export type AdminSsoEnv = {
|
||||
readonly issuerUrl: string;
|
||||
readonly clientId: string;
|
||||
readonly clientSecret: string;
|
||||
readonly bindingDatabaseUrl: string;
|
||||
readonly redirectUri: string;
|
||||
readonly postLogoutRedirectUri?: string;
|
||||
};
|
||||
|
||||
export class AdminSsoConfigError extends Error {
|
||||
readonly code: "missing-env" | "discovery-failed" | "client-init-failed";
|
||||
readonly code: "missing-env" | "invalid-env" | "discovery-failed" | "client-init-failed";
|
||||
|
||||
constructor(code: AdminSsoConfigError["code"], message: string, options?: { cause?: unknown }) {
|
||||
super(message, options);
|
||||
@@ -39,6 +41,9 @@ export function readAdminSsoEnv(env: Record<string, string | undefined> = proces
|
||||
const issuerUrl = env.AUTHENTIK_ISSUER_URL?.trim();
|
||||
const clientId = env.AUTHENTIK_ADMIN_CLIENT_ID?.trim();
|
||||
const clientSecret = env.AUTHENTIK_ADMIN_CLIENT_SECRET?.trim();
|
||||
// The env key and database role retain their deployed legacy names. The
|
||||
// capability itself binds prepared identities and never creates AdminUsers.
|
||||
const bindingDatabaseUrl = env.AUTHENTIK_ADMIN_JIT_DATABASE_URL?.trim();
|
||||
const redirectUri = env.AUTHENTIK_ADMIN_REDIRECT_URI?.trim();
|
||||
const postLogoutRedirectUri = env.AUTHENTIK_ADMIN_POST_LOGOUT_REDIRECT_URI?.trim();
|
||||
|
||||
@@ -46,21 +51,74 @@ export function readAdminSsoEnv(env: Record<string, string | undefined> = proces
|
||||
if (!issuerUrl) missing.push("AUTHENTIK_ISSUER_URL");
|
||||
if (!clientId) missing.push("AUTHENTIK_ADMIN_CLIENT_ID");
|
||||
if (!clientSecret) missing.push("AUTHENTIK_ADMIN_CLIENT_SECRET");
|
||||
if (!bindingDatabaseUrl) missing.push("AUTHENTIK_ADMIN_JIT_DATABASE_URL");
|
||||
if (!redirectUri) missing.push("AUTHENTIK_ADMIN_REDIRECT_URI");
|
||||
|
||||
if (missing.length > 0) {
|
||||
throw new AdminSsoConfigError("missing-env", `Admin SSO env is incomplete: missing ${missing.join(", ")}`);
|
||||
}
|
||||
|
||||
const issuer = validateAdminSsoUrl("AUTHENTIK_ISSUER_URL", issuerUrl as string);
|
||||
const redirect = validateAdminSsoUrl("AUTHENTIK_ADMIN_REDIRECT_URI", redirectUri as string);
|
||||
validateAuthentikBindingDatabaseUrl(bindingDatabaseUrl as string);
|
||||
if (issuer.search || issuer.hash) {
|
||||
throw new AdminSsoConfigError("invalid-env", "AUTHENTIK_ISSUER_URL must not include query parameters or a fragment.");
|
||||
}
|
||||
if (redirect.pathname !== "/auth/admin/callback" || redirect.search || redirect.hash) {
|
||||
throw new AdminSsoConfigError("invalid-env", "AUTHENTIK_ADMIN_REDIRECT_URI must target the exact /auth/admin/callback path.");
|
||||
}
|
||||
if (postLogoutRedirectUri) {
|
||||
const postLogout = validateAdminSsoUrl("AUTHENTIK_ADMIN_POST_LOGOUT_REDIRECT_URI", postLogoutRedirectUri);
|
||||
if (postLogout.origin !== redirect.origin || postLogout.hash) {
|
||||
throw new AdminSsoConfigError(
|
||||
"invalid-env",
|
||||
"AUTHENTIK_ADMIN_POST_LOGOUT_REDIRECT_URI must use the admin callback origin and must not include a fragment.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
issuerUrl: issuerUrl as string,
|
||||
clientId: clientId as string,
|
||||
clientSecret: clientSecret as string,
|
||||
bindingDatabaseUrl: bindingDatabaseUrl as string,
|
||||
redirectUri: redirectUri as string,
|
||||
postLogoutRedirectUri: postLogoutRedirectUri || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function validateAuthentikBindingDatabaseUrl(value: string): void {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
throw new AdminSsoConfigError("invalid-env", "AUTHENTIK_ADMIN_JIT_DATABASE_URL must be a valid PostgreSQL URL.");
|
||||
}
|
||||
if (!new Set(["postgres:", "postgresql:"]).has(url.protocol) || url.username !== "hivegrid_authentik_jit" || !url.password || url.pathname === "/") {
|
||||
throw new AdminSsoConfigError(
|
||||
"invalid-env",
|
||||
"AUTHENTIK_ADMIN_JIT_DATABASE_URL must authenticate as hivegrid_authentik_jit and select a database.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function validateAdminSsoUrl(name: string, value: string): URL {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
throw new AdminSsoConfigError("invalid-env", `${name} must be an absolute URL.`);
|
||||
}
|
||||
const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
|
||||
if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
|
||||
throw new AdminSsoConfigError("invalid-env", `${name} must use HTTPS outside loopback development.`);
|
||||
}
|
||||
if (url.username || url.password) {
|
||||
throw new AdminSsoConfigError("invalid-env", `${name} must not contain URL credentials.`);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true iff SSO is configured (i.e. all required env vars are set).
|
||||
* Used by the login UI to decide whether to render the SSO button.
|
||||
@@ -81,7 +139,9 @@ function envFingerprint(env: AdminSsoEnv): string {
|
||||
// Fingerprint identifies whether we need to re-init when env changes
|
||||
// (mostly relevant for tests; in production env is static for the
|
||||
// lifetime of the process).
|
||||
return `${env.issuerUrl}|${env.clientId}|${env.redirectUri}`;
|
||||
const secretFingerprint = createHash("sha256").update(env.clientSecret).digest("base64url");
|
||||
const bindingFingerprint = createHash("sha256").update(env.bindingDatabaseUrl).digest("base64url");
|
||||
return `${env.issuerUrl}|${env.clientId}|${env.redirectUri}|${secretFingerprint}|${bindingFingerprint}`;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -8,6 +8,7 @@ export { AdminSsoConfigError, getAdminSsoClient, isAdminSsoConfigured, readAdmin
|
||||
export {
|
||||
ADMIN_SSO_CHALLENGE_COOKIE,
|
||||
ADMIN_SSO_CHALLENGE_TTL_MS,
|
||||
LOCAL_ADMIN_SSO_CHALLENGE_COOKIE,
|
||||
clearAdminSsoChallengeCookie,
|
||||
consumeAdminSsoChallenge,
|
||||
createAdminSsoChallenge,
|
||||
@@ -20,18 +21,7 @@ export {
|
||||
extractAdminSsoClaims,
|
||||
hasAllowedAdminGroup,
|
||||
isAllowedAdminGroup,
|
||||
mapGroupsToRole,
|
||||
type AdminSsoClaims,
|
||||
type AdminSsoRole,
|
||||
type AuthentikGroup,
|
||||
type ClaimExtractionResult,
|
||||
} from "./claims.server";
|
||||
export {
|
||||
ADMIN_SSO_PROVIDER,
|
||||
JitProvisioningError,
|
||||
jitProvisionAdmin,
|
||||
type JitProvisionedAdmin,
|
||||
type JitProvisioningDbClient,
|
||||
type JitProvisioningInput,
|
||||
type JitProvisioningResult,
|
||||
} from "./jit-provisioning.server";
|
||||
-201
@@ -1,201 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { AdminSsoClaims } from "./claims.server";
|
||||
import { ADMIN_SSO_PROVIDER, jitProvisionAdmin, type JitProvisioningDbClient } from "./jit-provisioning.server";
|
||||
|
||||
type AdminRecord = {
|
||||
userId: string;
|
||||
ssoProvider: string | null;
|
||||
ssoSubjectId: string | null;
|
||||
ssoGroups: string[];
|
||||
lastSsoLoginAt: Date | null;
|
||||
};
|
||||
|
||||
type UserRecord = { id: string; email: string; firstName: string; lastName: string };
|
||||
|
||||
function buildFakeDb() {
|
||||
const adminRows = new Map<string, AdminRecord>();
|
||||
const userRows = new Map<string, UserRecord>();
|
||||
let userCounter = 0;
|
||||
|
||||
const db: JitProvisioningDbClient = {
|
||||
adminUser: {
|
||||
findUnique: vi.fn(async (args) => {
|
||||
const { ssoProvider, ssoSubjectId } = args.where.ssoProvider_ssoSubjectId;
|
||||
for (const row of adminRows.values()) {
|
||||
if (row.ssoProvider === ssoProvider && row.ssoSubjectId === ssoSubjectId) {
|
||||
return { userId: row.userId, ssoProvider: row.ssoProvider, ssoSubjectId: row.ssoSubjectId, ssoGroups: row.ssoGroups, lastSsoLoginAt: row.lastSsoLoginAt };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}),
|
||||
update: vi.fn(async (args) => {
|
||||
const existing = adminRows.get(args.where.userId);
|
||||
if (!existing) {
|
||||
const err = new Error("record not found") as Error & { code?: string };
|
||||
err.code = "P2025";
|
||||
throw err;
|
||||
}
|
||||
const updated: AdminRecord = {
|
||||
...existing,
|
||||
ssoProvider: args.data.ssoProvider ?? existing.ssoProvider,
|
||||
ssoSubjectId: args.data.ssoSubjectId ?? existing.ssoSubjectId,
|
||||
ssoGroups: args.data.ssoGroups ?? existing.ssoGroups,
|
||||
lastSsoLoginAt: args.data.lastSsoLoginAt ?? existing.lastSsoLoginAt,
|
||||
};
|
||||
adminRows.set(args.where.userId, updated);
|
||||
return updated;
|
||||
}),
|
||||
create: vi.fn(async (args) => {
|
||||
const row: AdminRecord = {
|
||||
userId: args.data.userId,
|
||||
ssoProvider: args.data.ssoProvider,
|
||||
ssoSubjectId: args.data.ssoSubjectId,
|
||||
ssoGroups: [...args.data.ssoGroups],
|
||||
lastSsoLoginAt: args.data.lastSsoLoginAt,
|
||||
};
|
||||
adminRows.set(row.userId, row);
|
||||
return row;
|
||||
}),
|
||||
},
|
||||
user: {
|
||||
findUnique: vi.fn(async (args) => {
|
||||
for (const u of userRows.values()) {
|
||||
if (u.email === args.where.email) return { id: u.id, email: u.email };
|
||||
}
|
||||
return null;
|
||||
}),
|
||||
update: vi.fn(async (args) => {
|
||||
const existing = userRows.get(args.where.id);
|
||||
if (!existing) throw new Error(`user ${args.where.id} missing`);
|
||||
const updated: UserRecord = {
|
||||
...existing,
|
||||
firstName: args.data.firstName ?? existing.firstName,
|
||||
lastName: args.data.lastName ?? existing.lastName,
|
||||
};
|
||||
userRows.set(args.where.id, updated);
|
||||
return updated;
|
||||
}),
|
||||
create: vi.fn(async (args) => {
|
||||
userCounter += 1;
|
||||
const id = `user_${userCounter}`;
|
||||
const row: UserRecord = {
|
||||
id,
|
||||
email: args.data.email,
|
||||
firstName: args.data.firstName,
|
||||
lastName: args.data.lastName,
|
||||
};
|
||||
userRows.set(id, row);
|
||||
return { id: row.id, email: row.email };
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
return { db, adminRows, userRows };
|
||||
}
|
||||
|
||||
function buildClaims(overrides: Partial<AdminSsoClaims> = {}): AdminSsoClaims {
|
||||
return {
|
||||
subject: "authentik-sub-1",
|
||||
email: "admin@example.test",
|
||||
emailVerified: true,
|
||||
name: "Admin Person",
|
||||
groups: ["hivegrid-admin"],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("jitProvisionAdmin", () => {
|
||||
let env: ReturnType<typeof buildFakeDb>;
|
||||
|
||||
beforeEach(() => {
|
||||
env = buildFakeDb();
|
||||
});
|
||||
|
||||
it("creates User+AdminUser for a brand new hivegrid-admin claim and returns super_admin", async () => {
|
||||
const result = await jitProvisionAdmin({ claims: buildClaims() }, env.db);
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(result.admin.role).toBe("super_admin");
|
||||
expect(result.admin.created).toBe(true);
|
||||
expect(result.admin.email).toBe("admin@example.test");
|
||||
}
|
||||
expect(env.adminRows.size).toBe(1);
|
||||
expect(env.userRows.size).toBe(1);
|
||||
const admin = [...env.adminRows.values()][0]!;
|
||||
expect(admin.ssoProvider).toBe(ADMIN_SSO_PROVIDER);
|
||||
expect(admin.ssoSubjectId).toBe("authentik-sub-1");
|
||||
expect(admin.ssoGroups).toEqual(["hivegrid-admin"]);
|
||||
});
|
||||
|
||||
it("maps hivegrid-staff to staff role", async () => {
|
||||
const result = await jitProvisionAdmin({ claims: buildClaims({ groups: ["hivegrid-staff"] }) }, env.db);
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) expect(result.admin.role).toBe("staff");
|
||||
});
|
||||
|
||||
it("rejects an unknown-group claim with forbidden-group", async () => {
|
||||
const result = await jitProvisionAdmin({ claims: buildClaims({ groups: ["random"] }) }, env.db);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.reason).toBe("forbidden-group");
|
||||
expect(env.adminRows.size).toBe(0);
|
||||
expect(env.userRows.size).toBe(0);
|
||||
});
|
||||
|
||||
it("rejects an empty-group claim with forbidden-group", async () => {
|
||||
const result = await jitProvisionAdmin({ claims: buildClaims({ groups: [] }) }, env.db);
|
||||
expect(result.ok).toBe(false);
|
||||
});
|
||||
|
||||
it("updates the existing SSO admin and refreshes groups + lastSsoLoginAt", async () => {
|
||||
// Seed: first login creates the admin.
|
||||
const t0 = new Date("2026-01-01T00:00:00Z");
|
||||
await jitProvisionAdmin({ claims: buildClaims(), now: t0 }, env.db);
|
||||
const admin = [...env.adminRows.values()][0]!;
|
||||
expect(admin.lastSsoLoginAt).toEqual(t0);
|
||||
|
||||
// Second login with same sub but new groups + later timestamp.
|
||||
const t1 = new Date("2026-02-01T00:00:00Z");
|
||||
const result = await jitProvisionAdmin(
|
||||
{ claims: buildClaims({ groups: ["hivegrid-staff"] }), now: t1 },
|
||||
env.db,
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(result.admin.created).toBe(false);
|
||||
// Role re-syncs from current group membership (Authentik = source of truth).
|
||||
expect(result.admin.role).toBe("staff");
|
||||
}
|
||||
const refreshed = [...env.adminRows.values()][0]!;
|
||||
expect(refreshed.ssoGroups).toEqual(["hivegrid-staff"]);
|
||||
expect(refreshed.lastSsoLoginAt).toEqual(t1);
|
||||
// No new user row.
|
||||
expect(env.userRows.size).toBe(1);
|
||||
});
|
||||
|
||||
it("links an existing email-matched legacy admin by attaching SSO fields", async () => {
|
||||
// Seed legacy admin (no SSO fields).
|
||||
env.userRows.set("legacy_1", { id: "legacy_1", email: "admin@example.test", firstName: "Old", lastName: "Admin" });
|
||||
env.adminRows.set("legacy_1", { userId: "legacy_1", ssoProvider: null, ssoSubjectId: null, ssoGroups: [], lastSsoLoginAt: null });
|
||||
|
||||
const result = await jitProvisionAdmin({ claims: buildClaims() }, env.db);
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(result.admin.userId).toBe("legacy_1");
|
||||
expect(result.admin.linkedExisting).toBe(true);
|
||||
expect(result.admin.created).toBe(false);
|
||||
}
|
||||
const admin = env.adminRows.get("legacy_1")!;
|
||||
expect(admin.ssoProvider).toBe(ADMIN_SSO_PROVIDER);
|
||||
expect(admin.ssoSubjectId).toBe("authentik-sub-1");
|
||||
expect(env.userRows.size).toBe(1); // no duplicate user
|
||||
});
|
||||
|
||||
it("creates an AdminUser when a legacy User exists but has no AdminUser row", async () => {
|
||||
env.userRows.set("legacy_2", { id: "legacy_2", email: "admin@example.test", firstName: "X", lastName: "Y" });
|
||||
// Note: no AdminUser row pre-existing.
|
||||
const result = await jitProvisionAdmin({ claims: buildClaims() }, env.db);
|
||||
expect(result.ok).toBe(true);
|
||||
expect(env.adminRows.size).toBe(1);
|
||||
expect(env.adminRows.get("legacy_2")?.ssoSubjectId).toBe("authentik-sub-1");
|
||||
});
|
||||
});
|
||||
-225
@@ -1,225 +0,0 @@
|
||||
/**
|
||||
* Phase 09 Task #82 — JIT-provisioning for Admin SSO.
|
||||
*
|
||||
* Lookup order:
|
||||
* 1. AdminUser by (ssoProvider, ssoSubjectId)
|
||||
* 2. AdminUser by linked User.email (case-insensitive) — legacy linking
|
||||
* 3. New User + AdminUser if at least one allowed group is in claims
|
||||
*
|
||||
* Idempotent under concurrent logins thanks to the unique
|
||||
* (ssoProvider, ssoSubjectId) constraint added in migration
|
||||
* 20260517161240_09_admin_user_sso_fields.
|
||||
*/
|
||||
import { randomBytes } from "node:crypto";
|
||||
import type { AdminSsoClaims, AdminSsoRole } from "./claims.server";
|
||||
import { hasAllowedAdminGroup, mapGroupsToRole } from "./claims.server";
|
||||
|
||||
export const ADMIN_SSO_PROVIDER = "authentik";
|
||||
|
||||
export type JitProvisioningInput = {
|
||||
readonly claims: AdminSsoClaims;
|
||||
readonly now?: Date;
|
||||
};
|
||||
|
||||
export type JitProvisionedAdmin = {
|
||||
readonly userId: string;
|
||||
readonly email: string;
|
||||
readonly role: AdminSsoRole;
|
||||
readonly created: boolean;
|
||||
readonly linkedExisting: boolean;
|
||||
};
|
||||
|
||||
export type JitProvisioningResult =
|
||||
| { readonly ok: true; readonly admin: JitProvisionedAdmin }
|
||||
| { readonly ok: false; readonly reason: "forbidden-group" };
|
||||
|
||||
export class JitProvisioningError extends Error {
|
||||
readonly reason: "forbidden-group";
|
||||
constructor(reason: "forbidden-group", message: string) {
|
||||
super(message);
|
||||
this.name = "JitProvisioningError";
|
||||
this.reason = reason;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrow Prisma-shaped surface used by jitProvisionAdmin. Defining it as a
|
||||
* structural type rather than importing PrismaClient keeps this module
|
||||
* unit-testable with a hand-rolled fake.
|
||||
*/
|
||||
export type JitProvisioningDbClient = {
|
||||
adminUser: {
|
||||
findUnique: (args: { where: { ssoProvider_ssoSubjectId: { ssoProvider: string; ssoSubjectId: string } } }) =>
|
||||
| Promise<({ userId: string } & AdminSsoUserRecord) | null>;
|
||||
update: (args: {
|
||||
where: { userId: string };
|
||||
data: {
|
||||
ssoProvider?: string;
|
||||
ssoSubjectId?: string;
|
||||
ssoGroups?: string[];
|
||||
lastSsoLoginAt?: Date;
|
||||
};
|
||||
}) => Promise<{ userId: string } & AdminSsoUserRecord>;
|
||||
create: (args: {
|
||||
data: {
|
||||
userId: string;
|
||||
ssoProvider: string;
|
||||
ssoSubjectId: string;
|
||||
ssoGroups: string[];
|
||||
lastSsoLoginAt: Date;
|
||||
};
|
||||
}) => Promise<{ userId: string } & AdminSsoUserRecord>;
|
||||
};
|
||||
user: {
|
||||
findUnique: (args: { where: { email: string } }) => Promise<{ id: string; email: string } | null>;
|
||||
update: (args: { where: { id: string }; data: { firstName?: string; lastName?: string } }) => Promise<unknown>;
|
||||
create: (args: {
|
||||
data: {
|
||||
email: string;
|
||||
passwordHash: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
active: boolean;
|
||||
};
|
||||
}) => Promise<{ id: string; email: string }>;
|
||||
};
|
||||
};
|
||||
|
||||
type AdminSsoUserRecord = {
|
||||
ssoProvider: string | null;
|
||||
ssoSubjectId: string | null;
|
||||
ssoGroups: string[];
|
||||
lastSsoLoginAt: Date | null;
|
||||
};
|
||||
|
||||
function splitName(fullName: string): { firstName: string; lastName: string } {
|
||||
const cleaned = fullName.trim();
|
||||
if (!cleaned) return { firstName: "", lastName: "" };
|
||||
const parts = cleaned.split(/\s+/);
|
||||
if (parts.length === 1) return { firstName: parts[0]!, lastName: "" };
|
||||
return { firstName: parts[0]!, lastName: parts.slice(1).join(" ") };
|
||||
}
|
||||
|
||||
/**
|
||||
* Random throw-away password hash — placeholder so the User row can satisfy
|
||||
* the existing non-null `passwordHash` constraint. SSO-only users never use
|
||||
* it; they always authenticate through Authentik. Stored as an opaque
|
||||
* 32-byte token prefixed to make the source obvious in audits.
|
||||
*/
|
||||
function generateSsoOnlyPasswordHash(): string {
|
||||
return `sso-only!${randomBytes(32).toString("hex")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* JIT-provision (or refresh) an AdminUser based on a verified Authentik
|
||||
* claim bundle.
|
||||
*/
|
||||
export async function jitProvisionAdmin(
|
||||
input: JitProvisioningInput,
|
||||
db: JitProvisioningDbClient
|
||||
): Promise<JitProvisioningResult> {
|
||||
const { claims } = input;
|
||||
const role = mapGroupsToRole(claims.groups);
|
||||
if (!role || !hasAllowedAdminGroup(claims.groups)) {
|
||||
return { ok: false, reason: "forbidden-group" };
|
||||
}
|
||||
const now = input.now ?? new Date();
|
||||
const email = claims.email.toLowerCase();
|
||||
|
||||
// (1) Existing SSO-linked admin?
|
||||
const existingBySso = await db.adminUser.findUnique({
|
||||
where: { ssoProvider_ssoSubjectId: { ssoProvider: ADMIN_SSO_PROVIDER, ssoSubjectId: claims.subject } },
|
||||
});
|
||||
if (existingBySso) {
|
||||
await db.adminUser.update({
|
||||
where: { userId: existingBySso.userId },
|
||||
data: {
|
||||
ssoGroups: [...claims.groups],
|
||||
lastSsoLoginAt: now,
|
||||
},
|
||||
});
|
||||
const { firstName, lastName } = splitName(claims.name);
|
||||
if (firstName || lastName) {
|
||||
await db.user.update({ where: { id: existingBySso.userId }, data: { firstName, lastName } });
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
admin: {
|
||||
userId: existingBySso.userId,
|
||||
email,
|
||||
role,
|
||||
created: false,
|
||||
linkedExisting: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// (2) Legacy admin matched by email — attach SSO fields.
|
||||
const existingUserByEmail = await db.user.findUnique({ where: { email } });
|
||||
if (existingUserByEmail) {
|
||||
const updated = await db.adminUser.update({
|
||||
where: { userId: existingUserByEmail.id },
|
||||
data: {
|
||||
ssoProvider: ADMIN_SSO_PROVIDER,
|
||||
ssoSubjectId: claims.subject,
|
||||
ssoGroups: [...claims.groups],
|
||||
lastSsoLoginAt: now,
|
||||
},
|
||||
}).catch(async (err) => {
|
||||
// If the user exists but has no AdminUser row, create one.
|
||||
// Prisma's `update` throws P2025 for record-not-found.
|
||||
const code = (err as { code?: string }).code;
|
||||
if (code !== "P2025") throw err;
|
||||
return db.adminUser.create({
|
||||
data: {
|
||||
userId: existingUserByEmail.id,
|
||||
ssoProvider: ADMIN_SSO_PROVIDER,
|
||||
ssoSubjectId: claims.subject,
|
||||
ssoGroups: [...claims.groups],
|
||||
lastSsoLoginAt: now,
|
||||
},
|
||||
});
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
admin: {
|
||||
userId: updated.userId,
|
||||
email,
|
||||
role,
|
||||
created: false,
|
||||
linkedExisting: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// (3) Brand-new user + admin from SSO.
|
||||
const { firstName, lastName } = splitName(claims.name);
|
||||
const newUser = await db.user.create({
|
||||
data: {
|
||||
email,
|
||||
passwordHash: generateSsoOnlyPasswordHash(),
|
||||
firstName: firstName || "Admin",
|
||||
lastName: lastName || "User",
|
||||
active: true,
|
||||
},
|
||||
});
|
||||
await db.adminUser.create({
|
||||
data: {
|
||||
userId: newUser.id,
|
||||
ssoProvider: ADMIN_SSO_PROVIDER,
|
||||
ssoSubjectId: claims.subject,
|
||||
ssoGroups: [...claims.groups],
|
||||
lastSsoLoginAt: now,
|
||||
},
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
admin: {
|
||||
userId: newUser.id,
|
||||
email,
|
||||
role,
|
||||
created: true,
|
||||
linkedExisting: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { testWebConfig } = vi.hoisted(() => ({
|
||||
testWebConfig: {
|
||||
nodeEnv: "test" as string,
|
||||
cryptoSecret: "test-crypto-secret-do-not-use-in-prod",
|
||||
sessionSecret: "test-session-secret-do-not-use-in-prod",
|
||||
routing: {
|
||||
appBaseDomain: "example.test",
|
||||
webAppHost: "app.example.test",
|
||||
adminAppHost: "admin.example.test",
|
||||
apiHost: "api.example.test",
|
||||
protocol: "https" as "http" | "https",
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/config", async () => {
|
||||
const actual = await vi.importActual<typeof import("@hivegrid/config")>("@hivegrid/config");
|
||||
return {
|
||||
...actual,
|
||||
loadRequiredWebConfig: () => testWebConfig,
|
||||
};
|
||||
});
|
||||
|
||||
import {
|
||||
ADMIN_SSO_ID_TOKEN_COOKIE,
|
||||
clearIdTokenCookie,
|
||||
LOCAL_ADMIN_SSO_ID_TOKEN_COOKIE,
|
||||
readIdTokenFromRequest,
|
||||
serializeIdTokenCookie,
|
||||
} from "./logout.server";
|
||||
|
||||
const SECRET = "test-secret-do-not-use-in-prod";
|
||||
|
||||
function requestWithCookie(pair: string): Request {
|
||||
return new Request("https://admin.example.test/auth/admin/logout", { headers: { cookie: pair } });
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
testWebConfig.nodeEnv = "test";
|
||||
testWebConfig.routing.protocol = "https";
|
||||
testWebConfig.routing.appBaseDomain = "example.test";
|
||||
});
|
||||
|
||||
describe("admin SSO id-token cookie", () => {
|
||||
it("uses a host-prefixed HTTPS cookie without a Domain attribute", () => {
|
||||
const cookie = serializeIdTokenCookie("id-token-value", { secret: SECRET });
|
||||
|
||||
expect(cookie).toContain(`${ADMIN_SSO_ID_TOKEN_COOKIE}=`);
|
||||
expect(cookie).toContain("Path=/");
|
||||
expect(cookie).toContain("HttpOnly");
|
||||
expect(cookie).toContain("SameSite=Lax");
|
||||
expect(cookie).toContain("Secure");
|
||||
expect(cookie).not.toContain("Domain=");
|
||||
});
|
||||
|
||||
it("round-trips a valid signed id token", () => {
|
||||
const pair = serializeIdTokenCookie("id-token-value", { secret: SECRET }).split(";")[0] ?? "";
|
||||
|
||||
expect(readIdTokenFromRequest(requestWithCookie(pair), { secret: SECRET })).toBe("id-token-value");
|
||||
});
|
||||
|
||||
it("rejects tampering", () => {
|
||||
const pair = serializeIdTokenCookie("id-token-value", { secret: SECRET }).split(";")[0] ?? "";
|
||||
|
||||
expect(readIdTokenFromRequest(requestWithCookie(`${pair}tampered`), { secret: SECRET })).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores a legacy parent-domain cookie on HTTPS", () => {
|
||||
const pair = serializeIdTokenCookie("id-token-value", { secret: SECRET })
|
||||
.split(";")[0]
|
||||
?.replace(ADMIN_SSO_ID_TOKEN_COOKIE, LOCAL_ADMIN_SSO_ID_TOKEN_COOKIE);
|
||||
|
||||
expect(readIdTokenFromRequest(requestWithCookie(pair ?? ""), { secret: SECRET })).toBeNull();
|
||||
});
|
||||
|
||||
it("does not let a legacy cookie shadow the host-prefixed id token", () => {
|
||||
const securePair = serializeIdTokenCookie("id-token-value", { secret: SECRET }).split(";")[0] ?? "";
|
||||
const request = requestWithCookie(`${LOCAL_ADMIN_SSO_ID_TOKEN_COOKIE}=attacker; ${securePair}`);
|
||||
|
||||
expect(readIdTokenFromRequest(request, { secret: SECRET })).toBe("id-token-value");
|
||||
});
|
||||
|
||||
it("clears the exact secure cookie scope", () => {
|
||||
const cookie = clearIdTokenCookie();
|
||||
|
||||
expect(cookie).toContain(`${ADMIN_SSO_ID_TOKEN_COOKIE}=`);
|
||||
expect(cookie).toContain("Path=/");
|
||||
expect(cookie).toContain("Max-Age=0");
|
||||
expect(cookie).toContain("Secure");
|
||||
expect(cookie).not.toContain("Domain=");
|
||||
});
|
||||
|
||||
it("uses a distinct localhost-compatible fallback on local HTTP", () => {
|
||||
testWebConfig.nodeEnv = "development";
|
||||
testWebConfig.routing.protocol = "http";
|
||||
testWebConfig.routing.appBaseDomain = "localhost:3000";
|
||||
|
||||
const cookie = serializeIdTokenCookie("id-token-value", { secret: SECRET });
|
||||
const pair = cookie.split(";")[0] ?? "";
|
||||
|
||||
expect(cookie).toContain(`${LOCAL_ADMIN_SSO_ID_TOKEN_COOKIE}=`);
|
||||
expect(cookie).not.toContain(ADMIN_SSO_ID_TOKEN_COOKIE);
|
||||
expect(cookie).not.toContain("Secure");
|
||||
expect(cookie).not.toContain("Domain=");
|
||||
expect(readIdTokenFromRequest(new Request("http://localhost:3000/auth/admin/logout", { headers: { cookie: pair } }), { secret: SECRET })).toBe(
|
||||
"id-token-value"
|
||||
);
|
||||
});
|
||||
});
|
||||
+31
-11
@@ -2,16 +2,16 @@
|
||||
* Phase 09 Task #82 — Admin-SSO logout helpers.
|
||||
*
|
||||
* Stores the raw OIDC `id_token` in a separate HMAC-signed HttpOnly
|
||||
* cookie (scoped to /auth/admin) so that /auth/admin/logout can supply
|
||||
* cookie (scoped to the dedicated admin host) so that /auth/admin/logout can supply
|
||||
* `id_token_hint` for RP-initiated logout without bloating the main
|
||||
* session cookie or persisting tokens in the DB.
|
||||
*/
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { loadRequiredWebConfig, resolveHostOnlyCookiePolicy } from "@hivegrid/config";
|
||||
|
||||
export const ADMIN_SSO_ID_TOKEN_COOKIE = "hivegrid_admin_sso_id_token";
|
||||
export const ADMIN_SSO_ID_TOKEN_TTL_MS = 12 * 60 * 60 * 1000; // mirror app-session lifetime
|
||||
const COOKIE_PATH = "/auth/admin";
|
||||
export const ADMIN_SSO_ID_TOKEN_COOKIE = "__Host-hivegrid_admin_sso_id_token";
|
||||
export const LOCAL_ADMIN_SSO_ID_TOKEN_COOKIE = "hivegrid_admin_sso_id_token";
|
||||
export const ADMIN_SSO_ID_TOKEN_TTL_MS = 15 * 60 * 1000; // bounded to the absolute AdminUser session lifetime
|
||||
|
||||
function getSigningSecret(override?: string): string {
|
||||
if (override) return override;
|
||||
@@ -27,19 +27,33 @@ function sign(payload: string, secret: string): string {
|
||||
return createHmac("sha256", secret).update(payload).digest("base64url");
|
||||
}
|
||||
|
||||
function getCookiePolicy() {
|
||||
const webConfig = loadRequiredWebConfig();
|
||||
// `__Host-` requires Path=/. The dedicated admin hostname is the narrowest
|
||||
// safe scope that preserves the browser-enforced no-Domain guarantee.
|
||||
return resolveHostOnlyCookiePolicy({
|
||||
nodeEnv: webConfig.nodeEnv,
|
||||
routing: webConfig.routing,
|
||||
secureName: ADMIN_SSO_ID_TOKEN_COOKIE,
|
||||
localName: LOCAL_ADMIN_SSO_ID_TOKEN_COOKIE,
|
||||
maxAge: Math.ceil(ADMIN_SSO_ID_TOKEN_TTL_MS / 1000),
|
||||
});
|
||||
}
|
||||
|
||||
export function serializeIdTokenCookie(idToken: string, opts: { secret?: string } = {}): string {
|
||||
const secret = getSigningSecret(opts.secret);
|
||||
const sig = sign(idToken, secret);
|
||||
const value = `${Buffer.from(idToken, "utf8").toString("base64url")}.${sig}`;
|
||||
const maxAge = Math.ceil(ADMIN_SSO_ID_TOKEN_TTL_MS / 1000);
|
||||
const attrs = [`${ADMIN_SSO_ID_TOKEN_COOKIE}=${value}`, `Path=${COOKIE_PATH}`, "HttpOnly", "SameSite=Lax", `Max-Age=${maxAge}`];
|
||||
if (process.env.NODE_ENV !== "test") attrs.push("Secure");
|
||||
const policy = getCookiePolicy();
|
||||
const attrs = [`${policy.name}=${value}`, `Path=${policy.path}`, "HttpOnly", "SameSite=Lax", `Max-Age=${policy.maxAge}`];
|
||||
if (policy.secure) attrs.push("Secure");
|
||||
return attrs.join("; ");
|
||||
}
|
||||
|
||||
export function clearIdTokenCookie(): string {
|
||||
const attrs = [`${ADMIN_SSO_ID_TOKEN_COOKIE}=`, `Path=${COOKIE_PATH}`, "HttpOnly", "SameSite=Lax", "Max-Age=0"];
|
||||
if (process.env.NODE_ENV !== "test") attrs.push("Secure");
|
||||
const policy = getCookiePolicy();
|
||||
const attrs = [`${policy.name}=`, `Path=${policy.path}`, "HttpOnly", "SameSite=Lax", "Max-Age=0"];
|
||||
if (policy.secure) attrs.push("Secure");
|
||||
return attrs.join("; ");
|
||||
}
|
||||
|
||||
@@ -55,7 +69,13 @@ function readCookie(request: Request, name: string): string | null {
|
||||
}
|
||||
|
||||
export function readIdTokenFromRequest(request: Request, opts: { secret?: string } = {}): string | null {
|
||||
const value = readCookie(request, ADMIN_SSO_ID_TOKEN_COOKIE);
|
||||
let cookieName: string;
|
||||
try {
|
||||
cookieName = getCookiePolicy().name;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const value = readCookie(request, cookieName);
|
||||
if (!value) return null;
|
||||
const dot = value.lastIndexOf(".");
|
||||
if (dot <= 0) return null;
|
||||
|
||||
+86
-5
@@ -1,9 +1,32 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { testWebConfig } = vi.hoisted(() => ({
|
||||
testWebConfig: {
|
||||
nodeEnv: "test" as string,
|
||||
routing: {
|
||||
appBaseDomain: "example.test",
|
||||
webAppHost: "app.example.test",
|
||||
adminAppHost: "admin.example.test",
|
||||
apiHost: "api.example.test",
|
||||
protocol: "https" as "http" | "https",
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/config", async () => {
|
||||
const actual = await vi.importActual<typeof import("@hivegrid/config")>("@hivegrid/config");
|
||||
return {
|
||||
...actual,
|
||||
loadRequiredWebConfig: () => testWebConfig,
|
||||
};
|
||||
});
|
||||
|
||||
import {
|
||||
ADMIN_SSO_CHALLENGE_COOKIE,
|
||||
ADMIN_SSO_CHALLENGE_TTL_MS,
|
||||
consumeAdminSsoChallenge,
|
||||
createAdminSsoChallenge,
|
||||
LOCAL_ADMIN_SSO_CHALLENGE_COOKIE,
|
||||
serializeAdminSsoChallengeCookie,
|
||||
} from "./state.server";
|
||||
|
||||
@@ -14,12 +37,18 @@ function cookieValue(cookie: string): string {
|
||||
return head.slice(`${ADMIN_SSO_CHALLENGE_COOKIE}=`.length);
|
||||
}
|
||||
|
||||
function requestWithCookie(value: string): Request {
|
||||
function requestWithCookie(value: string, name = ADMIN_SSO_CHALLENGE_COOKIE): Request {
|
||||
return new Request("https://admin.example.test/auth/admin/callback", {
|
||||
headers: { cookie: `${ADMIN_SSO_CHALLENGE_COOKIE}=${value}` },
|
||||
headers: { cookie: `${name}=${value}` },
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
testWebConfig.nodeEnv = "test";
|
||||
testWebConfig.routing.protocol = "https";
|
||||
testWebConfig.routing.appBaseDomain = "example.test";
|
||||
});
|
||||
|
||||
describe("createAdminSsoChallenge", () => {
|
||||
it("produces distinct state, nonce and codeVerifier for each invocation", () => {
|
||||
const a = createAdminSsoChallenge({ secret: SECRET });
|
||||
@@ -38,11 +67,27 @@ describe("createAdminSsoChallenge", () => {
|
||||
expect(payload.codeChallenge).not.toBe(payload.codeVerifier);
|
||||
});
|
||||
|
||||
it("emits an HttpOnly, Path-scoped cookie", () => {
|
||||
it("emits a host-prefixed cookie on HTTPS without a Domain attribute", () => {
|
||||
const { cookie } = createAdminSsoChallenge({ secret: SECRET });
|
||||
expect(cookie).toContain(`${ADMIN_SSO_CHALLENGE_COOKIE}=`);
|
||||
expect(cookie).toMatch(/HttpOnly/);
|
||||
expect(cookie).toMatch(/Path=\/auth\/admin/);
|
||||
expect(cookie).toMatch(/Path=\//);
|
||||
expect(cookie).toMatch(/SameSite=Lax/);
|
||||
expect(cookie).toMatch(/Secure/);
|
||||
expect(cookie).not.toMatch(/Domain=/);
|
||||
});
|
||||
|
||||
it("uses a distinct localhost-compatible name on local HTTP", () => {
|
||||
testWebConfig.nodeEnv = "development";
|
||||
testWebConfig.routing.protocol = "http";
|
||||
testWebConfig.routing.appBaseDomain = "localhost:3000";
|
||||
|
||||
const { cookie } = createAdminSsoChallenge({ secret: SECRET });
|
||||
|
||||
expect(cookie).toContain(`${LOCAL_ADMIN_SSO_CHALLENGE_COOKIE}=`);
|
||||
expect(cookie).not.toContain(ADMIN_SSO_CHALLENGE_COOKIE);
|
||||
expect(cookie).not.toContain("Secure");
|
||||
expect(cookie).not.toContain("Domain=");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -70,6 +115,26 @@ describe("consumeAdminSsoChallenge", () => {
|
||||
if (!result.ok) expect(result.reason).toBe("missing");
|
||||
});
|
||||
|
||||
it("ignores a legacy parent-domain cookie on HTTPS", () => {
|
||||
const { cookie } = createAdminSsoChallenge({ secret: SECRET });
|
||||
const result = consumeAdminSsoChallenge(requestWithCookie(cookieValue(cookie), LOCAL_ADMIN_SSO_CHALLENGE_COOKIE), { secret: SECRET });
|
||||
|
||||
expect(result).toEqual({ ok: false, reason: "missing" });
|
||||
});
|
||||
|
||||
it("does not let a legacy cookie shadow the host-prefixed challenge", () => {
|
||||
const { payload, cookie } = createAdminSsoChallenge({ secret: SECRET });
|
||||
const value = cookieValue(cookie);
|
||||
const request = new Request("https://admin.example.test/auth/admin/callback", {
|
||||
headers: { cookie: `${LOCAL_ADMIN_SSO_CHALLENGE_COOKIE}=attacker; ${ADMIN_SSO_CHALLENGE_COOKIE}=${value}` },
|
||||
});
|
||||
|
||||
const result = consumeAdminSsoChallenge(request, { secret: SECRET });
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) expect(result.payload.state).toBe(payload.state);
|
||||
});
|
||||
|
||||
it("rejects a cookie with a tampered signature", () => {
|
||||
const { cookie } = createAdminSsoChallenge({ secret: SECRET });
|
||||
const value = cookieValue(cookie);
|
||||
@@ -96,6 +161,22 @@ describe("consumeAdminSsoChallenge", () => {
|
||||
if (!result.ok) expect(result.reason).toBe("expired");
|
||||
});
|
||||
|
||||
it("rejects a challenge dated implausibly far in the future", () => {
|
||||
const now = Date.now();
|
||||
const { payload } = createAdminSsoChallenge({ secret: SECRET, now: () => now + 5 * 60 * 1000 });
|
||||
const cookie = serializeAdminSsoChallengeCookie(payload, SECRET);
|
||||
const result = consumeAdminSsoChallenge(requestWithCookie(cookieValue(cookie)), { secret: SECRET, now: () => now });
|
||||
expect(result).toEqual({ ok: false, reason: "malformed" });
|
||||
});
|
||||
|
||||
it("rejects a signed payload whose PKCE verifier and challenge do not match", () => {
|
||||
const { payload } = createAdminSsoChallenge({ secret: SECRET });
|
||||
const inconsistent = { ...payload, codeChallenge: "A".repeat(43) };
|
||||
const cookie = serializeAdminSsoChallengeCookie(inconsistent, SECRET);
|
||||
const result = consumeAdminSsoChallenge(requestWithCookie(cookieValue(cookie)), { secret: SECRET });
|
||||
expect(result).toEqual({ ok: false, reason: "malformed" });
|
||||
});
|
||||
|
||||
it("rejects a malformed cookie value", () => {
|
||||
const result = consumeAdminSsoChallenge(requestWithCookie("garbage"), { secret: SECRET });
|
||||
expect(result.ok).toBe(false);
|
||||
|
||||
+66
-30
@@ -2,7 +2,7 @@
|
||||
* Phase 09 Task #82 — PKCE / state / nonce challenge persistence.
|
||||
*
|
||||
* Stores the tuple { state, nonce, codeVerifier, createdAt } in an
|
||||
* HMAC-signed HttpOnly cookie scoped to /auth/admin. The cookie is
|
||||
* HMAC-signed HttpOnly cookie scoped to the dedicated admin host. The cookie is
|
||||
* single-use: `consumeAdminSsoChallenge()` returns the payload and emits a
|
||||
* `Set-Cookie` header that clears it.
|
||||
*
|
||||
@@ -17,12 +17,13 @@
|
||||
* server-side (cookie Max-Age is best-effort; clients lie).
|
||||
*/
|
||||
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { loadRequiredWebConfig, resolveHostOnlyCookiePolicy } from "@hivegrid/config";
|
||||
import { generators } from "openid-client";
|
||||
|
||||
export const ADMIN_SSO_CHALLENGE_COOKIE = "hivegrid_admin_sso_challenge";
|
||||
export const ADMIN_SSO_CHALLENGE_COOKIE = "__Host-hivegrid_admin_sso_challenge";
|
||||
export const LOCAL_ADMIN_SSO_CHALLENGE_COOKIE = "hivegrid_admin_sso_challenge";
|
||||
export const ADMIN_SSO_CHALLENGE_TTL_MS = 10 * 60 * 1000;
|
||||
const COOKIE_PATH = "/auth/admin";
|
||||
const ADMIN_SSO_CHALLENGE_CLOCK_SKEW_MS = 60 * 1000;
|
||||
const PAYLOAD_VERSION = "v1";
|
||||
|
||||
export type AdminSsoChallengePayload = {
|
||||
@@ -58,6 +59,19 @@ function getSigningSecret(override?: string): string {
|
||||
return secret;
|
||||
}
|
||||
|
||||
function getCookiePolicy() {
|
||||
const webConfig = loadRequiredWebConfig();
|
||||
// `__Host-` requires Path=/. The dedicated admin hostname is the narrowest
|
||||
// safe scope that preserves the browser-enforced no-Domain guarantee.
|
||||
return resolveHostOnlyCookiePolicy({
|
||||
nodeEnv: webConfig.nodeEnv,
|
||||
routing: webConfig.routing,
|
||||
secureName: ADMIN_SSO_CHALLENGE_COOKIE,
|
||||
localName: LOCAL_ADMIN_SSO_CHALLENGE_COOKIE,
|
||||
maxAge: Math.ceil(ADMIN_SSO_CHALLENGE_TTL_MS / 1000),
|
||||
});
|
||||
}
|
||||
|
||||
function base64UrlEncode(buf: Buffer | string): string {
|
||||
const b = typeof buf === "string" ? Buffer.from(buf, "utf8") : buf;
|
||||
return b.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
||||
@@ -105,15 +119,9 @@ export function serializeAdminSsoChallengeCookie(payload: AdminSsoChallengePaylo
|
||||
const body = base64UrlEncode(JSON.stringify({ v: PAYLOAD_VERSION, p: payload }));
|
||||
const sig = sign(body, secret);
|
||||
const value = `${body}.${sig}`;
|
||||
const maxAgeSeconds = Math.ceil(ADMIN_SSO_CHALLENGE_TTL_MS / 1000);
|
||||
const attributes = [
|
||||
`${ADMIN_SSO_CHALLENGE_COOKIE}=${value}`,
|
||||
`Path=${COOKIE_PATH}`,
|
||||
"HttpOnly",
|
||||
"SameSite=Lax",
|
||||
`Max-Age=${maxAgeSeconds}`,
|
||||
];
|
||||
if (process.env.NODE_ENV !== "test") {
|
||||
const policy = getCookiePolicy();
|
||||
const attributes = [`${policy.name}=${value}`, `Path=${policy.path}`, "HttpOnly", "SameSite=Lax", `Max-Age=${policy.maxAge}`];
|
||||
if (policy.secure) {
|
||||
attributes.push("Secure");
|
||||
}
|
||||
return attributes.join("; ");
|
||||
@@ -123,14 +131,9 @@ export function serializeAdminSsoChallengeCookie(payload: AdminSsoChallengePaylo
|
||||
* Returns a `Set-Cookie` header that clears the challenge cookie.
|
||||
*/
|
||||
export function clearAdminSsoChallengeCookie(): string {
|
||||
const attributes = [
|
||||
`${ADMIN_SSO_CHALLENGE_COOKIE}=`,
|
||||
`Path=${COOKIE_PATH}`,
|
||||
"HttpOnly",
|
||||
"SameSite=Lax",
|
||||
"Max-Age=0",
|
||||
];
|
||||
if (process.env.NODE_ENV !== "test") {
|
||||
const policy = getCookiePolicy();
|
||||
const attributes = [`${policy.name}=`, `Path=${policy.path}`, "HttpOnly", "SameSite=Lax", "Max-Age=0"];
|
||||
if (policy.secure) {
|
||||
attributes.push("Secure");
|
||||
}
|
||||
return attributes.join("; ");
|
||||
@@ -153,11 +156,14 @@ function readCookieValue(request: Request, name: string): string | null {
|
||||
* Always returns a `clearCookie` header that the caller must include on
|
||||
* the redirect response so the cookie cannot be replayed.
|
||||
*/
|
||||
export function consumeAdminSsoChallenge(
|
||||
request: Request,
|
||||
options: { now?: () => number; secret?: string } = {}
|
||||
): ConsumeResult {
|
||||
const value = readCookieValue(request, ADMIN_SSO_CHALLENGE_COOKIE);
|
||||
export function consumeAdminSsoChallenge(request: Request, options: { now?: () => number; secret?: string } = {}): ConsumeResult {
|
||||
let cookieName: string;
|
||||
try {
|
||||
cookieName = getCookiePolicy().name;
|
||||
} catch {
|
||||
return { ok: false, reason: "malformed" };
|
||||
}
|
||||
const value = readCookieValue(request, cookieName);
|
||||
if (!value) return { ok: false, reason: "missing" };
|
||||
const dot = value.lastIndexOf(".");
|
||||
if (dot <= 0) return { ok: false, reason: "malformed" };
|
||||
@@ -172,18 +178,48 @@ export function consumeAdminSsoChallenge(
|
||||
if (!verifySignature(body, sig, secret)) {
|
||||
return { ok: false, reason: "bad-signature" };
|
||||
}
|
||||
let decoded: { v: string; p: AdminSsoChallengePayload };
|
||||
let decoded: { v?: unknown; p?: unknown };
|
||||
try {
|
||||
decoded = JSON.parse(base64UrlDecode(body).toString("utf8"));
|
||||
decoded = JSON.parse(base64UrlDecode(body).toString("utf8")) as { v?: unknown; p?: unknown };
|
||||
} catch {
|
||||
return { ok: false, reason: "malformed" };
|
||||
}
|
||||
if (decoded.v !== PAYLOAD_VERSION || !decoded.p) {
|
||||
if (decoded.v !== PAYLOAD_VERSION || !isAdminSsoChallengePayload(decoded.p)) {
|
||||
return { ok: false, reason: "malformed" };
|
||||
}
|
||||
const now = options.now ? options.now() : Date.now();
|
||||
if (typeof decoded.p.createdAt !== "number" || now - decoded.p.createdAt > ADMIN_SSO_CHALLENGE_TTL_MS) {
|
||||
if (decoded.p.createdAt > now + ADMIN_SSO_CHALLENGE_CLOCK_SKEW_MS) {
|
||||
return { ok: false, reason: "malformed" };
|
||||
}
|
||||
if (now - decoded.p.createdAt > ADMIN_SSO_CHALLENGE_TTL_MS) {
|
||||
return { ok: false, reason: "expired" };
|
||||
}
|
||||
return { ok: true, payload: decoded.p, clearCookie: clearAdminSsoChallengeCookie() };
|
||||
}
|
||||
|
||||
function isAdminSsoChallengePayload(value: unknown): value is AdminSsoChallengePayload {
|
||||
if (!value || typeof value !== "object") {
|
||||
return false;
|
||||
}
|
||||
const payload = value as Partial<Record<keyof AdminSsoChallengePayload, unknown>>;
|
||||
if (
|
||||
typeof payload.state !== "string" ||
|
||||
!/^[0-9a-f]{64}$/.test(payload.state) ||
|
||||
typeof payload.nonce !== "string" ||
|
||||
!/^[0-9a-f]{64}$/.test(payload.nonce) ||
|
||||
typeof payload.codeVerifier !== "string" ||
|
||||
!/^[A-Za-z0-9._~-]{43,128}$/.test(payload.codeVerifier) ||
|
||||
typeof payload.codeChallenge !== "string" ||
|
||||
!/^[A-Za-z0-9_-]{43}$/.test(payload.codeChallenge) ||
|
||||
typeof payload.createdAt !== "number" ||
|
||||
!Number.isFinite(payload.createdAt) ||
|
||||
(payload.returnTo !== undefined && typeof payload.returnTo !== "string")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return generators.codeChallenge(payload.codeVerifier) === payload.codeChallenge;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user