fix(auth): harden unified diagnostic execution

This commit is contained in:
2026-08-17 16:39:54 +02:00
parent 3ed00ff086
commit 30ee9433dc
20 changed files with 1034 additions and 57 deletions
+39 -13
View File
@@ -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;
}
+60
View File
@@ -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[]>;
+18 -4
View File
@@ -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 });