fix(auth): harden unified diagnostic execution
This commit is contained in:
@@ -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