fix(auth): harden unified diagnostic execution
This commit is contained in:
@@ -1,31 +1,41 @@
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { resolve } from "node:path";
|
||||
import { loadConfig, type AppConfig } from "../config.js";
|
||||
import { secretValue } from "../config/secret-bundle.js";
|
||||
import { loadSecretBundle, SECRET_BUNDLE_KEYS, secretValue } from "../config/secret-bundle.js";
|
||||
import { createAuthentikGroupCatalog } from "./authentik-group-catalog.js";
|
||||
import { createCurrentLocalUserRegistryResolver, type LocalUserRegistry } from "./local-registry.js";
|
||||
import { createOidcProtocol, OidcDeviceFlowUnavailableError, type OidcProtocol } from "./oidc-client.js";
|
||||
import { createAuthDiagnoser, type AuthDiagnoser, type AuthDiagnostic, type AuthDiagnostics } from "./diagnostics.js";
|
||||
import { decodeAuthDiagnostics, type GroupCatalog } from "./group-catalog.js";
|
||||
import type { LoadedAuthConfig } from "./types.js";
|
||||
|
||||
const AUTH_SECRET_REFERENCES = ["THT_OIDC_CLIENT_SECRET", "THT_AUTHENTIK_API_TOKEN"] as const;
|
||||
|
||||
function configuredSecretValues(config: AppConfig): readonly string[] {
|
||||
const values: string[] = [];
|
||||
for (const reference of AUTH_SECRET_REFERENCES) {
|
||||
export function configuredSecretValues(config: AppConfig): readonly string[] {
|
||||
const values = new Set<string>();
|
||||
if (config.secretsFile) {
|
||||
try {
|
||||
const value = secretValue(config, reference);
|
||||
if (value !== undefined) values.push(value);
|
||||
for (const value of loadSecretBundle(config.secretsFile).values()) values.add(value);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
for (const reference of SECRET_BUNDLE_KEYS) {
|
||||
try {
|
||||
const value = secretValue({ secretFiles: config.secretFiles }, reference);
|
||||
if (value !== undefined) values.add(value);
|
||||
} catch {
|
||||
// The fixed report below is the only externally-visible failure surface.
|
||||
}
|
||||
}
|
||||
return values;
|
||||
return [...values];
|
||||
}
|
||||
|
||||
export interface ConfiguredAuthDiagnoserOptions {
|
||||
localUserRegistry?: (loaded: LoadedAuthConfig) => LocalUserRegistry | undefined;
|
||||
oidcProtocol?: (loaded: LoadedAuthConfig) => OidcProtocol | undefined;
|
||||
groupCatalog?: (loaded: LoadedAuthConfig) => GroupCatalog | undefined;
|
||||
sessionRootValidator?: (root: string) => void | Promise<void>;
|
||||
}
|
||||
|
||||
/** Builds the one shared auth diagnostic implementation used by app routes and the one-shot CLI. */
|
||||
@@ -70,7 +80,7 @@ export function createConfiguredAuthDiagnoser(
|
||||
} catch { return undefined; }
|
||||
})()
|
||||
: undefined;
|
||||
const groupCatalog = current?.value.mode === "oidc" ? (() => {
|
||||
const groupCatalog = current?.value.mode === "oidc" ? options.groupCatalog?.(current) ?? (() => {
|
||||
try {
|
||||
const token = secretValues().get("THT_AUTHENTIK_API_TOKEN");
|
||||
return token === undefined ? undefined : createAuthentikGroupCatalog({
|
||||
@@ -82,6 +92,7 @@ export function createConfiguredAuthDiagnoser(
|
||||
const report = await createAuthDiagnoser({
|
||||
authMode: config.authMode,
|
||||
authStateRoot: config.authStateRoot,
|
||||
...(options.sessionRootValidator === undefined ? {} : { sessionRootValidator: options.sessionRootValidator }),
|
||||
authentication: config.authentication,
|
||||
secrets: secretValues(),
|
||||
localUserRegistry: current?.value.mode === "local"
|
||||
@@ -108,10 +119,21 @@ export function createConfiguredAuthDiagnoser(
|
||||
);
|
||||
// Exact names only: unrelated provider groups are neither emitted nor retained.
|
||||
const mappedRoles = new Set<string>();
|
||||
for (const group of identity.groups) {
|
||||
for (const role of current.value.authorization.groupRoles[group] ?? []) mappedRoles.add(role);
|
||||
for (const [configuredGroup, roles] of Object.entries(current.value.authorization.groupRoles)) {
|
||||
if (!identity.groups.includes(configuredGroup)) continue;
|
||||
for (const role of roles) mappedRoles.add(role);
|
||||
}
|
||||
if (mappedRoles.size === 0) {
|
||||
return {
|
||||
ready: false,
|
||||
mode: "oidc",
|
||||
checks: [{
|
||||
level: "error",
|
||||
code: "oidc_groups_claim_invalid",
|
||||
message: "The OIDC device-flow identity could not be validated.",
|
||||
}],
|
||||
};
|
||||
}
|
||||
void mappedRoles;
|
||||
return report;
|
||||
} catch (error) {
|
||||
return {
|
||||
@@ -188,18 +210,22 @@ export async function runDiagnosticCommand(
|
||||
return 2;
|
||||
}
|
||||
let report: AuthDiagnostics;
|
||||
const secrets = dependencies.secretValues ?? [];
|
||||
try {
|
||||
report = await dependencies.diagnoser.inspect({
|
||||
live: true,
|
||||
...(options.interactive ? {
|
||||
interactive: true,
|
||||
presentDeviceCode: (uri: string, code: string) => dependencies.stderr(`Open ${uri} and enter code ${code}`),
|
||||
presentDeviceCode: (uri: string, code: string) => dependencies.stderr(
|
||||
redact(`Open ${uri} and enter code ${code}`, secrets),
|
||||
),
|
||||
} : {}),
|
||||
});
|
||||
} catch {
|
||||
report = genericFailure();
|
||||
}
|
||||
const safe = redactedReport(report, dependencies.secretValues ?? []);
|
||||
const decoded = decodeAuthDiagnostics(report) ?? genericFailure();
|
||||
const safe = decodeAuthDiagnostics(redactedReport(decoded, secrets)) ?? genericFailure();
|
||||
dependencies.stdout(`${JSON.stringify(safe)}\n`);
|
||||
return safe.ready ? 0 : 1;
|
||||
}
|
||||
|
||||
@@ -30,6 +30,66 @@ export interface AuthDiagnostics {
|
||||
checks: readonly AuthDiagnostic[];
|
||||
}
|
||||
|
||||
const diagnosticCodes = new Set<AuthDiagnosticCode>([
|
||||
"auth_ready", "auth_config_incomplete", "auth_config_invalid", "auth_session_store_invalid",
|
||||
"local_user_registry_invalid", "local_admin_missing", "oidc_secret_missing",
|
||||
"oidc_discovery_unreachable", "oidc_issuer_mismatch", "oidc_jwks_unreachable",
|
||||
"oidc_group_catalog_unreachable", "oidc_group_catalog_unauthorized", "oidc_mapped_group_missing",
|
||||
"oidc_mapped_group_ambiguous", "oidc_groups_claim_invalid", "oidc_device_flow_unavailable",
|
||||
]);
|
||||
const diagnosticModes = new Set<AuthDiagnostics["mode"]>(["local", "oidc", "upstream", "none", "mock"]);
|
||||
const fieldCodes = new Set<AuthDiagnosticCode>(["oidc_mapped_group_missing", "oidc_mapped_group_ambiguous"]);
|
||||
|
||||
function exactObject(value: unknown, keys: readonly string[]): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
||||
const source = value as Record<string, unknown>;
|
||||
const actual = Object.keys(source);
|
||||
return actual.length === keys.length && actual.every((key) => keys.includes(key)) ? source : undefined;
|
||||
}
|
||||
|
||||
function safeText(value: unknown): value is string {
|
||||
return typeof value === "string" && value.length > 0 && value.length <= 512
|
||||
&& value.trim() === value && !/\p{Cc}/u.test(value);
|
||||
}
|
||||
|
||||
/** Strict decoder for the machine contract shared with tht and the frontend. */
|
||||
export function decodeAuthDiagnostics(value: unknown): AuthDiagnostics | undefined {
|
||||
const source = exactObject(value, ["ready", "mode", "checks"]);
|
||||
if (!source || typeof source.ready !== "boolean" || typeof source.mode !== "string"
|
||||
|| !diagnosticModes.has(source.mode as AuthDiagnostics["mode"])
|
||||
|| !Array.isArray(source.checks) || source.checks.length === 0 || source.checks.length > 129) return undefined;
|
||||
const seen = new Set<string>();
|
||||
const checks: AuthDiagnostic[] = [];
|
||||
for (const value of source.checks) {
|
||||
const raw = value && typeof value === "object" && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
: undefined;
|
||||
const check = raw && exactObject(raw, raw.field === undefined
|
||||
? ["level", "code", "message"]
|
||||
: ["level", "code", "message", "field"]);
|
||||
if (!check || (check.level !== "error" && check.level !== "info")
|
||||
|| typeof check.code !== "string" || !diagnosticCodes.has(check.code as AuthDiagnosticCode)
|
||||
|| !safeText(check.message) || (check.field !== undefined && !safeText(check.field))) return undefined;
|
||||
const code = check.code as AuthDiagnosticCode;
|
||||
if (check.field !== undefined && !fieldCodes.has(code)) return undefined;
|
||||
const key = `${code}\u0000${check.field ?? ""}`;
|
||||
if (seen.has(key)) return undefined;
|
||||
seen.add(key);
|
||||
checks.push({
|
||||
level: check.level,
|
||||
code,
|
||||
message: check.message,
|
||||
...(check.field === undefined ? {} : { field: check.field }),
|
||||
});
|
||||
}
|
||||
if (source.ready) {
|
||||
if (checks.length !== 1 || checks[0].level !== "info" || checks[0].code !== "auth_ready"
|
||||
|| checks[0].field !== undefined) return undefined;
|
||||
} else if (!checks.some(({ level }) => level === "error")
|
||||
|| checks.some(({ code }) => code === "auth_ready")) return undefined;
|
||||
return { ready: source.ready, mode: source.mode as AuthDiagnostics["mode"], checks };
|
||||
}
|
||||
|
||||
/** A provider-specific proof that only the configured authorization groups exist. */
|
||||
export interface GroupCatalog {
|
||||
verifyConfiguredGroups(names: readonly string[], signal: AbortSignal): Promise<readonly AuthDiagnostic[]>;
|
||||
|
||||
@@ -611,23 +611,37 @@ export function createOidcProtocol(options: OidcProtocolOptions): OidcProtocol {
|
||||
signal.throwIfAborted();
|
||||
},
|
||||
async verifyDeviceFlow(signal, present) {
|
||||
const maximumDeadline = AbortSignal.timeout(MAX_DEVICE_FLOW_TIMEOUT_MS);
|
||||
const operationSignal = AbortSignal.any([signal, maximumDeadline]);
|
||||
let config: Configuration;
|
||||
try {
|
||||
operationSignal.throwIfAborted();
|
||||
config = await configuration();
|
||||
operationSignal.throwIfAborted();
|
||||
const endpoint = config.serverMetadata().device_authorization_endpoint;
|
||||
httpsEndpoint(endpoint);
|
||||
} catch (error) {
|
||||
if (error instanceof OidcIssuerMismatchError || error instanceof OidcProviderUnavailableError) throw error;
|
||||
throw new OidcDeviceFlowUnavailableError();
|
||||
}
|
||||
const deadline = AbortSignal.timeout(MAX_DEVICE_FLOW_TIMEOUT_MS);
|
||||
const deviceSignal = AbortSignal.any([signal, deadline]);
|
||||
try {
|
||||
deviceSignal.throwIfAborted();
|
||||
const device = await initiateDeviceAuthorization(config, { scope: options.scopes.join(" ") });
|
||||
operationSignal.throwIfAborted();
|
||||
const device = await awaitWithAbort(
|
||||
initiateDeviceAuthorization(config, { scope: options.scopes.join(" ") }),
|
||||
operationSignal,
|
||||
);
|
||||
if (!text(device.verification_uri, 2048) || !text(device.user_code, 256)) {
|
||||
throw new OidcDeviceFlowUnavailableError();
|
||||
}
|
||||
const providerLifetimeMs = device.expires_in * 1000;
|
||||
if (!Number.isSafeInteger(providerLifetimeMs) || providerLifetimeMs <= 0) {
|
||||
throw new OidcDeviceFlowUnavailableError();
|
||||
}
|
||||
const deviceSignal = AbortSignal.any([
|
||||
signal,
|
||||
maximumDeadline,
|
||||
AbortSignal.timeout(Math.min(providerLifetimeMs, MAX_DEVICE_FLOW_TIMEOUT_MS)),
|
||||
]);
|
||||
const verificationUri = httpsEndpoint(device.verification_uri);
|
||||
present(verificationUri.href, device.user_code);
|
||||
const tokens = await pollDeviceAuthorizationGrant(config, device, undefined, { signal: deviceSignal });
|
||||
|
||||
@@ -19,6 +19,7 @@ import type { RuntimeBindings } from "../workspaces/runtime-renderer.js";
|
||||
import type { ConnectorDiagnostics } from "../workspaces/diagnostics.js";
|
||||
import { isPrincipalContext, requirePermission } from "../auth/authorization.js";
|
||||
import type { AuthDiagnoser } from "../auth/diagnostics.js";
|
||||
import { decodeAuthDiagnostics, type AuthDiagnostics } from "../auth/group-catalog.js";
|
||||
|
||||
export type WorkspaceDiagnoser = (
|
||||
workspace: WorkspaceDescriptor,
|
||||
@@ -55,6 +56,12 @@ const SAFE_MESSAGES = {
|
||||
semantic_index_incompatible: "Semantic index is incompatible with this workspace.",
|
||||
} as const;
|
||||
|
||||
function authenticationReport(value: unknown): AuthDiagnostics {
|
||||
const report = decodeAuthDiagnostics(value);
|
||||
if (!report) throw new Error("invalid authentication diagnostic report");
|
||||
return report;
|
||||
}
|
||||
|
||||
function workspaceErrorCode(error: unknown): keyof typeof SAFE_MESSAGES {
|
||||
return error instanceof WorkspaceRegistryError ? error.code : "workspace_invalid";
|
||||
}
|
||||
@@ -149,7 +156,7 @@ export function workspaceRoutes(app: FastifyInstance, deps: WorkspaceRoutesDeps)
|
||||
try {
|
||||
const { workspace } = workspacePayload.parse(request.body);
|
||||
const canonical = validateWorkspaceDescriptor(workspace);
|
||||
const authentication = await deps.authDiagnoser.inspect({ live: false });
|
||||
const authentication = authenticationReport(await deps.authDiagnoser.inspect({ live: false }));
|
||||
return {
|
||||
workspace: canonical,
|
||||
contract: buildInstallationContract(canonical),
|
||||
@@ -231,10 +238,11 @@ export function workspaceRoutes(app: FastifyInstance, deps: WorkspaceRoutesDeps)
|
||||
deps.secretStore,
|
||||
);
|
||||
try {
|
||||
const [workspaceDiagnostics, authentication] = await Promise.all([
|
||||
const [workspaceDiagnostics, inspectedAuthentication] = await Promise.all([
|
||||
deps.diagnose(operational, lease.bindings, { writeProbe: false }),
|
||||
deps.authDiagnoser.inspect({ live: true }),
|
||||
]);
|
||||
const authentication = authenticationReport(inspectedAuthentication);
|
||||
return {
|
||||
...workspaceDiagnostics,
|
||||
activatable: workspaceDiagnostics.activatable && authentication.ready,
|
||||
|
||||
@@ -1,6 +1,69 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
import type { AuthDiagnoser, AuthDiagnostics } from "../src/auth/diagnostics.js";
|
||||
import { runDiagnosticCommand } from "../src/auth/diagnostic-command.js";
|
||||
import {
|
||||
configuredSecretValues,
|
||||
createConfiguredAuthDiagnoser,
|
||||
runDiagnosticCommand,
|
||||
} from "../src/auth/diagnostic-command.js";
|
||||
import type { AppConfig } from "../src/config.js";
|
||||
import type { LoadedAuthConfig } from "../src/auth/types.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
|
||||
|
||||
function secretBundle(contents: string): string {
|
||||
const root = mkdtempSync(join(tmpdir(), "thothii-diagnostic-command-"));
|
||||
roots.push(root);
|
||||
const file = join(root, "secrets");
|
||||
writeFileSync(file, contents, { mode: 0o600 });
|
||||
chmodSync(file, 0o600);
|
||||
return file;
|
||||
}
|
||||
|
||||
function configuredOidc(groups: readonly string[]): AuthDiagnoser {
|
||||
const loaded: LoadedAuthConfig = {
|
||||
revision: "a".repeat(64),
|
||||
sourcePath: "/safe/auth.yaml",
|
||||
value: {
|
||||
version: 1,
|
||||
mode: "oidc",
|
||||
publicUrl: "https://thothii.example.test",
|
||||
session: { regularTtlSeconds: 1, regularIdleSeconds: 1, rememberTtlSeconds: 1, rememberIdleSeconds: 1, oidcTtlSeconds: 1 },
|
||||
oidc: {
|
||||
issuer: "https://issuer.example.test", clientId: "thothii",
|
||||
clientSecretRef: "THT_OIDC_CLIENT_SECRET", scopes: ["openid"], groupsClaim: "groups",
|
||||
},
|
||||
groupCatalog: {
|
||||
driver: "authentik", baseUrl: "https://authentik.example.test",
|
||||
apiTokenRef: "THT_AUTHENTIK_API_TOKEN",
|
||||
},
|
||||
authorization: { groupRoles: { "Thoth Users": ["user"], "Thoth Administrators": ["admin"] } },
|
||||
},
|
||||
};
|
||||
const config = {
|
||||
authMode: "oidc",
|
||||
authStateRoot: "/safe/auth-state",
|
||||
authentication: { current: () => loaded },
|
||||
secretsFile: secretBundle("THT_OIDC_CLIENT_SECRET=oidc-secret\nTHT_AUTHENTIK_API_TOKEN=catalog-secret\n"),
|
||||
secretFiles: {},
|
||||
} as AppConfig;
|
||||
return createConfiguredAuthDiagnoser(config, {
|
||||
sessionRootValidator: async () => undefined,
|
||||
groupCatalog: () => ({ verifyConfiguredGroups: async () => [] }),
|
||||
oidcProtocol: () => ({
|
||||
diagnose: async () => undefined,
|
||||
authorizationUrl: async () => new URL("https://issuer.example.test/authorize"),
|
||||
callback: async () => { throw new Error("not used"); },
|
||||
verifyDeviceFlow: async () => ({
|
||||
issuer: "https://issuer.example.test", subject: "subject", groups,
|
||||
tokenExpiresAt: new Date(Date.now() + 60_000),
|
||||
}),
|
||||
}),
|
||||
} as any);
|
||||
}
|
||||
|
||||
const failure: AuthDiagnostics = {
|
||||
ready: false,
|
||||
@@ -65,3 +128,110 @@ test("delegates an interactive diagnostic to OIDC and keeps its device prompt on
|
||||
expect(stderr).toEqual(["Open https://issuer.example.test/device and enter code ABCD-EFGH"]);
|
||||
expect(JSON.parse(stdout.join(""))).toEqual(ready);
|
||||
});
|
||||
|
||||
test("fails a direct-group identity that maps to zero Thoth roles without exposing provider groups", async () => {
|
||||
const unmapped = "Unmapped Provider Group SECRET-SENTINEL";
|
||||
const report = await configuredOidc([unmapped]).inspect({
|
||||
live: true,
|
||||
interactive: true,
|
||||
presentDeviceCode: () => undefined,
|
||||
});
|
||||
|
||||
expect(report).toEqual({
|
||||
ready: false,
|
||||
mode: "oidc",
|
||||
checks: [{
|
||||
level: "error",
|
||||
code: "oidc_groups_claim_invalid",
|
||||
message: "The OIDC device-flow identity could not be validated.",
|
||||
}],
|
||||
});
|
||||
expect(JSON.stringify(report)).not.toContain(unmapped);
|
||||
});
|
||||
|
||||
test("accepts a direct-group identity with at least one exact configured role mapping", async () => {
|
||||
const report = await configuredOidc(["Thoth Users", "Unmapped Provider Group"]).inspect({
|
||||
live: true,
|
||||
interactive: true,
|
||||
presentDeviceCode: () => undefined,
|
||||
});
|
||||
|
||||
expect(report).toMatchObject({ ready: true, checks: [{ code: "auth_ready" }] });
|
||||
expect(JSON.stringify(report)).not.toContain("Unmapped Provider Group");
|
||||
});
|
||||
|
||||
test("redacts every parsed mounted secret before writing an interactive prompt", async () => {
|
||||
const modelSecret = "model-secret-SENTINEL";
|
||||
const deviceCode = "DEVICE-CODE-SENTINEL";
|
||||
const legacyVectorSecret = "legacy-vector-secret-SENTINEL";
|
||||
const config = {
|
||||
secretsFile: secretBundle([
|
||||
`THT_MODEL_API_KEY=${modelSecret}`,
|
||||
`THT_DWH_API_KEY=${deviceCode}`,
|
||||
"THT_OIDC_CLIENT_SECRET=oidc-secret",
|
||||
"THT_AUTHENTIK_API_TOKEN=catalog-secret",
|
||||
"",
|
||||
].join("\n")),
|
||||
secretFiles: { THT_VEC_API_KEY_SECRET_FILE: secretBundle(legacyVectorSecret) },
|
||||
} as AppConfig;
|
||||
const secrets = configuredSecretValues(config);
|
||||
const stdout: string[] = [];
|
||||
const stderr: string[] = [];
|
||||
|
||||
await runDiagnosticCommand(["--json", "--interactive"], {
|
||||
diagnoser: {
|
||||
inspect: async (request) => {
|
||||
request.presentDeviceCode?.(
|
||||
`https://issuer.example.test/device/${modelSecret}?legacy=${legacyVectorSecret}`,
|
||||
deviceCode,
|
||||
);
|
||||
return { ready: true, mode: "oidc", checks: [{ level: "info", code: "auth_ready", message: "Authentication is ready." }] };
|
||||
},
|
||||
},
|
||||
secretValues: secrets,
|
||||
stdout: (line) => stdout.push(line),
|
||||
stderr: (line) => stderr.push(line),
|
||||
});
|
||||
|
||||
expect(secrets).toEqual(expect.arrayContaining([
|
||||
modelSecret, deviceCode, legacyVectorSecret, "oidc-secret", "catalog-secret",
|
||||
]));
|
||||
expect(stdout.join("") + stderr.join("")).not.toContain(modelSecret);
|
||||
expect(stdout.join("") + stderr.join("")).not.toContain(deviceCode);
|
||||
expect(stdout.join("") + stderr.join("")).not.toContain(legacyVectorSecret);
|
||||
});
|
||||
|
||||
test.each([
|
||||
{
|
||||
ready: true, mode: "oidc", checks: [{ level: "error", code: "oidc_secret_missing", message: "attacker-message" }],
|
||||
},
|
||||
{
|
||||
ready: false, mode: "oidc", checks: [{ level: "info", code: "auth_ready", message: "attacker-message" }],
|
||||
},
|
||||
{
|
||||
ready: false, mode: "oidc", checks: [
|
||||
{ level: "error", code: "oidc_secret_missing", message: "one" },
|
||||
{ level: "error", code: "oidc_secret_missing", message: "duplicate-attacker" },
|
||||
],
|
||||
},
|
||||
{
|
||||
ready: false, mode: "oidc", checks: [{
|
||||
level: "error", code: "oidc_secret_missing", message: "failure", field: "attacker-field-SENTINEL",
|
||||
}],
|
||||
},
|
||||
])("fails closed on a hostile semantic report %#", async (hostile) => {
|
||||
const stdout: string[] = [];
|
||||
const exitCode = await runDiagnosticCommand(["--json"], {
|
||||
diagnoser: { inspect: async () => hostile as AuthDiagnostics },
|
||||
stdout: (line) => stdout.push(line),
|
||||
stderr: () => undefined,
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(1);
|
||||
expect(JSON.parse(stdout.join(""))).toEqual({
|
||||
ready: false,
|
||||
mode: "none",
|
||||
checks: [{ level: "error", code: "auth_config_invalid", message: "Authentication configuration is unavailable." }],
|
||||
});
|
||||
expect(stdout.join("")).not.toMatch(/attacker|duplicate/i);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createSign, generateKeyPairSync } from "node:crypto";
|
||||
import { expect, test } from "vitest";
|
||||
import { expect, test, vi } from "vitest";
|
||||
import {
|
||||
createOidcProtocol,
|
||||
OidcIssuerMismatchError,
|
||||
@@ -170,6 +170,51 @@ test("refuses device flow when discovery has no safe device authorization endpoi
|
||||
.rejects.toBeInstanceOf(OidcDeviceFlowUnavailableError);
|
||||
});
|
||||
|
||||
test("stops authorization-pending polling at the provider device expiry", async () => {
|
||||
const caller = new AbortController();
|
||||
const timeout = vi.spyOn(AbortSignal, "timeout");
|
||||
try {
|
||||
const tokenResponse = vi.fn(async () => Response.json(
|
||||
{ error: "authorization_pending", error_description: "pending" },
|
||||
{ status: 400 },
|
||||
));
|
||||
const subject = protocol({
|
||||
discoveryMetadata: { device_authorization_endpoint: `${issuer}/device` },
|
||||
deviceResponse: async () => Response.json({
|
||||
device_code: "ephemeral-device-code",
|
||||
user_code: "ABCD-EFGH",
|
||||
verification_uri: `${issuer}/device`,
|
||||
expires_in: 0.05,
|
||||
interval: 0.01,
|
||||
}),
|
||||
tokenResponse,
|
||||
});
|
||||
const completion = subject.verifyDeviceFlow!(caller.signal, () => undefined);
|
||||
|
||||
expect(await settlesWithin(completion, 250)).toBe("rejected");
|
||||
expect(tokenResponse.mock.calls.length).toBeLessThanOrEqual(5);
|
||||
expect(timeout).toHaveBeenCalledWith(10 * 60_000);
|
||||
expect(timeout).toHaveBeenCalledWith(50);
|
||||
await expect(completion).rejects.toThrow(OidcProtocolError);
|
||||
} finally {
|
||||
caller.abort();
|
||||
timeout.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
test("combines the caller cancellation with device-flow deadlines before provider requests", async () => {
|
||||
const seen: URL[] = [];
|
||||
const caller = new AbortController();
|
||||
caller.abort(new DOMException("caller deadline", "AbortError"));
|
||||
const subject = protocol({
|
||||
seen,
|
||||
discoveryMetadata: { device_authorization_endpoint: `${issuer}/device` },
|
||||
});
|
||||
|
||||
await expect(subject.verifyDeviceFlow!(caller.signal, () => undefined)).rejects.toThrow(OidcProtocolError);
|
||||
expect(seen).toEqual([]);
|
||||
});
|
||||
|
||||
test("rejects a hanging discovery request at the provider transport deadline", async () => {
|
||||
let aborted = false;
|
||||
const subject = protocol({
|
||||
|
||||
@@ -250,6 +250,26 @@ test("aggregates one static and one live authentication report without reorderin
|
||||
expect(authDiagnoser.inspect).toHaveBeenNthCalledWith(2, { live: true });
|
||||
});
|
||||
|
||||
test("fails closed without reflecting a hostile authentication report", async () => {
|
||||
const attacker = "attacker-field-SENTINEL";
|
||||
const authDiagnoser: AuthDiagnoser = { inspect: vi.fn(async () => ({
|
||||
ready: false,
|
||||
mode: "oidc",
|
||||
checks: [{
|
||||
level: "error", code: "oidc_secret_missing", message: "failure", field: attacker,
|
||||
}],
|
||||
} as AuthDiagnostics)) };
|
||||
const app = appFor(registryFake(), undefined, testSecretStore(), {}, authDiagnoser);
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST", url: "/workspaces/validate", payload: { workspace },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.json()).toEqual({ code: "workspace_invalid", message: "Workspace request is invalid." });
|
||||
expect(response.body).not.toContain(attacker);
|
||||
});
|
||||
|
||||
test.each([1, 2])("rejects schema v%s at the validation boundary with a sanitized error", async (version) => {
|
||||
const legacy = {
|
||||
...workspace,
|
||||
|
||||
Reference in New Issue
Block a user