fix(auth): make diagnostics bounded and portable

This commit is contained in:
2026-08-17 12:19:19 +02:00
parent 7cfbee36fa
commit be1724890a
23 changed files with 1088 additions and 116 deletions
+85 -32
View File
@@ -2,10 +2,14 @@ import type { AuthenticationConfigProvider, AuthMode } from "./types.js";
import type { LocalUserRegistry } from "./local-registry.js";
import { OidcIssuerMismatchError, OidcJwksUnavailableError, type OidcProtocol } from "./oidc-client.js";
import { validateAuthSessionRoot } from "./session-store.js";
import { createWindowsAuthStorageBridge, type WindowsAuthStorageBridge } from "./windows-auth-storage.js";
import { isUsableAuthenticationSecret, type AuthenticationSecretReference } from "./secret-policy.js";
import type { AuthDiagnostic, AuthDiagnosticCode, AuthDiagnostics, GroupCatalog } from "./group-catalog.js";
export type { AuthDiagnostic, AuthDiagnosticCode, AuthDiagnostics } from "./group-catalog.js";
const LIVE_DIAGNOSTIC_TIMEOUT_MS = 30_000;
export interface AuthDiagnoser {
inspect(options: { live: boolean; interactive?: boolean; signal?: AbortSignal }): Promise<AuthDiagnostics>;
}
@@ -15,6 +19,7 @@ export interface AuthDiagnoserDependencies {
authStateRoot: string;
/** Platform integrations may inject an equivalent side-effect-free owner/ACL validator. */
sessionRootValidator?: (root: string) => void | Promise<void>;
windowsStorageBridge?: Pick<WindowsAuthStorageBridge, "validateRoot">;
authentication?: AuthenticationConfigProvider;
secrets?: ReadonlyMap<string, string>;
localUserRegistry?: LocalUserRegistry;
@@ -26,11 +31,6 @@ function check(code: AuthDiagnosticCode, message: string, field?: string): AuthD
return { level: "error", code, message, ...(field === undefined ? {} : { field }) };
}
function secretPresent(secrets: ReadonlyMap<string, string> | undefined, name: string): boolean {
const value = secrets?.get(name);
return typeof value === "string" && value.length > 0 && value.length <= 16 * 1024 && !/\p{Cc}/u.test(value);
}
function ordered(checks: readonly AuthDiagnostic[]): readonly AuthDiagnostic[] {
const unique = new Map<string, AuthDiagnostic>();
for (const item of checks) unique.set(`${item.code}\u0000${item.field ?? ""}`, item);
@@ -45,6 +45,45 @@ function stableCompare(left: string, right: string): number {
return left < right ? -1 : left > right ? 1 : 0;
}
function abortReason(signal: AbortSignal): unknown {
return signal.reason ?? new DOMException("The operation was aborted", "AbortError");
}
function awaitWithAbort<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {
return new Promise<T>((resolve, reject) => {
let settled = false;
const abort = () => {
if (settled) return;
settled = true;
signal.removeEventListener("abort", abort);
reject(abortReason(signal));
};
if (signal.aborted) abort();
else signal.addEventListener("abort", abort, { once: true });
operation.then(
(value) => {
if (settled) return;
settled = true;
signal.removeEventListener("abort", abort);
resolve(value);
},
(error: unknown) => {
if (settled) return;
settled = true;
signal.removeEventListener("abort", abort);
reject(error);
},
);
});
}
function startBeforeAbort<T>(signal: AbortSignal, operation: () => Promise<T>): Promise<T> {
return Promise.resolve().then(() => {
if (signal.aborted) throw abortReason(signal);
return operation();
});
}
async function localRegistryIsUsable(deps: AuthDiagnoserDependencies): Promise<AuthDiagnostic | undefined> {
try {
if (!deps.localUserRegistry) {
@@ -60,12 +99,15 @@ async function localRegistryIsUsable(deps: AuthDiagnoserDependencies): Promise<A
}
export function createAuthDiagnoser(deps: AuthDiagnoserDependencies): AuthDiagnoser {
const validateSessionRoot = deps.sessionRootValidator ?? (process.platform === "win32"
? (root: string) => (deps.windowsStorageBridge ?? createWindowsAuthStorageBridge()).validateRoot(root)
: validateAuthSessionRoot);
return {
async inspect(options): Promise<AuthDiagnostics> {
const checks: AuthDiagnostic[] = [];
const signal = options.signal ?? new AbortController().signal;
try {
await (deps.sessionRootValidator ?? validateAuthSessionRoot)(deps.authStateRoot);
await validateSessionRoot(deps.authStateRoot);
} catch {
checks.push(check("auth_session_store_invalid", "The authentication session store is invalid."));
}
@@ -103,8 +145,8 @@ export function createAuthDiagnoser(deps: AuthDiagnoserDependencies): AuthDiagno
: { ready: false, mode: "local", checks: result };
}
const requiredSecrets = ["THT_OIDC_CLIENT_SECRET", "THT_AUTHENTIK_API_TOKEN"];
if (requiredSecrets.some((name) => !secretPresent(deps.secrets, name))) {
const requiredSecrets: readonly AuthenticationSecretReference[] = ["THT_OIDC_CLIENT_SECRET", "THT_AUTHENTIK_API_TOKEN"];
if (requiredSecrets.some((name) => !isUsableAuthenticationSecret(name, deps.secrets?.get(name)))) {
checks.push(check("oidc_secret_missing", "A required OIDC or group catalog secret is unavailable."));
}
if (!options.live || checks.length > 0) {
@@ -113,33 +155,44 @@ export function createAuthDiagnoser(deps: AuthDiagnoserDependencies): AuthDiagno
? { ready: true, mode: "oidc", checks: [{ level: "info", code: "auth_ready", message: "Authentication is ready." }] }
: { ready: false, mode: "oidc", checks: result };
}
const mappedGroupNames = Object.keys(loaded.value.authorization.groupRoles).sort(stableCompare);
if (!deps.oidcProtocol) {
checks.push(check("oidc_discovery_unreachable", "The OIDC provider is unavailable."));
} else {
try {
await deps.oidcProtocol.diagnose(signal);
} catch (error) {
checks.push(check(
error instanceof OidcIssuerMismatchError
? "oidc_issuer_mismatch"
: error instanceof OidcJwksUnavailableError
? "oidc_jwks_unreachable"
: "oidc_discovery_unreachable",
"The OIDC provider could not be validated.",
));
const deadline = new AbortController();
const deadlineTimer = setTimeout(() => deadline.abort(), LIVE_DIAGNOSTIC_TIMEOUT_MS);
deadlineTimer.unref();
const liveSignal = AbortSignal.any([signal, deadline.signal]);
try {
if (!deps.oidcProtocol) {
checks.push(check("oidc_discovery_unreachable", "The OIDC provider is unavailable."));
} else {
try {
await awaitWithAbort(startBeforeAbort(liveSignal, () => deps.oidcProtocol!.diagnose(liveSignal)), liveSignal);
} catch (error) {
checks.push(check(
error instanceof OidcIssuerMismatchError
? "oidc_issuer_mismatch"
: error instanceof OidcJwksUnavailableError
? "oidc_jwks_unreachable"
: "oidc_discovery_unreachable",
"The OIDC provider could not be validated.",
));
}
}
}
if (!deps.groupCatalog) {
checks.push(check("oidc_group_catalog_unreachable", "The configured group catalog cannot be certified."));
} else {
try {
checks.push(...await deps.groupCatalog.verifyConfiguredGroups(
Object.keys(loaded.value.authorization.groupRoles).sort(stableCompare), signal,
));
} catch {
checks.push(check("oidc_group_catalog_unreachable", "The configured group catalog is unavailable."));
if (!liveSignal.aborted) {
if (!deps.groupCatalog) {
checks.push(check("oidc_group_catalog_unreachable", "The configured group catalog cannot be certified."));
} else {
try {
checks.push(...await awaitWithAbort(startBeforeAbort(liveSignal, () => deps.groupCatalog!.verifyConfiguredGroups(
mappedGroupNames, liveSignal,
)), liveSignal));
} catch {
checks.push(check("oidc_group_catalog_unreachable", "The configured group catalog is unavailable."));
}
}
}
} finally {
clearTimeout(deadlineTimer);
}
const result = ordered(checks);
return result.length === 0