feat(auth): validate mapped groups through Authentik

This commit is contained in:
2026-08-17 10:44:56 +02:00
parent 33ae7cfdc2
commit f0ae680671
9 changed files with 669 additions and 2 deletions
+147
View File
@@ -0,0 +1,147 @@
import type { AuthenticationConfigProvider, AuthMode } from "./types.js";
import type { LocalUserRegistry } from "./local-registry.js";
import { OidcJwksUnavailableError, type OidcProtocol } from "./oidc-client.js";
import type { AuthDiagnostic, AuthDiagnosticCode, AuthDiagnostics, GroupCatalog } from "./group-catalog.js";
export type { AuthDiagnostic, AuthDiagnosticCode, AuthDiagnostics } from "./group-catalog.js";
export interface AuthDiagnoser {
inspect(options: { live: boolean; interactive?: boolean; signal?: AbortSignal }): Promise<AuthDiagnostics>;
}
export interface AuthDiagnoserDependencies {
authMode: AuthMode;
authStateRoot: string;
authentication?: AuthenticationConfigProvider;
secrets?: ReadonlyMap<string, string>;
localUserRegistry?: LocalUserRegistry;
/** Enables a host integration to inspect a local registry without exposing user records. */
hasEnabledLocalAdmin?: () => Promise<boolean>;
oidcProtocol?: OidcProtocol;
groupCatalog?: GroupCatalog;
}
function check(code: AuthDiagnosticCode, message: string, field?: string): AuthDiagnostic {
return { level: "error", code, message, ...(field === undefined ? {} : { field }) };
}
function sessionRootIsSafe(value: string): boolean {
return typeof value === "string" && value.startsWith("/") && value.trim() === value
&& value.length > 1 && !value.includes("\0") && !/\p{Cc}/u.test(value);
}
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);
return [...unique.values()].sort((left, right) => {
const leftKey = `${left.code}\u0000${left.field ?? ""}`;
const rightKey = `${right.code}\u0000${right.field ?? ""}`;
return leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0;
});
}
function stableCompare(left: string, right: string): number {
return left < right ? -1 : left > right ? 1 : 0;
}
async function localRegistryIsUsable(deps: AuthDiagnoserDependencies): Promise<AuthDiagnostic | undefined> {
try {
if (deps.hasEnabledLocalAdmin) {
if (!await deps.hasEnabledLocalAdmin()) return check("local_admin_missing", "No enabled local administrator is configured.");
return undefined;
}
if (!deps.localUserRegistry) return check("local_user_registry_invalid", "The local user registry is unavailable.");
// The registry's safe parser refuses to load without an enabled admin; this probe never exposes users.
await deps.localUserRegistry.findByUsername("diagnostic-probe");
return undefined;
} catch {
return check("local_user_registry_invalid", "The local user registry is invalid.");
}
}
export function createAuthDiagnoser(deps: AuthDiagnoserDependencies): AuthDiagnoser {
return {
async inspect(options): Promise<AuthDiagnostics> {
const checks: AuthDiagnostic[] = [];
const signal = options.signal ?? new AbortController().signal;
if (!sessionRootIsSafe(deps.authStateRoot)) checks.push(check("auth_session_store_invalid", "The authentication session store is invalid."));
if (deps.authMode === "none" || deps.authMode === "mock") {
const result = ordered(checks);
return result.length === 0
? { ready: true, mode: deps.authMode, checks: [{ level: "info", code: "auth_ready", message: "Authentication is ready." }] }
: { ready: false, mode: deps.authMode, checks: result };
}
if (deps.authMode === "upstream") {
checks.push(check("auth_config_incomplete", "The deprecated upstream authentication mode is not certifiable."));
return { ready: false, mode: deps.authMode, checks: ordered(checks) };
}
let loaded;
try {
if (!deps.authentication) throw new Error("missing authentication configuration");
loaded = deps.authentication.current();
} catch {
checks.push(check(deps.authentication ? "auth_config_invalid" : "auth_config_incomplete", "Authentication configuration is unavailable."));
return { ready: false, mode: deps.authMode, checks: ordered(checks) };
}
if (loaded.value.mode !== deps.authMode) {
checks.push(check("auth_config_invalid", "Authentication mode does not match its configuration."));
return { ready: false, mode: deps.authMode, checks: ordered(checks) };
}
if (loaded.value.mode === "local") {
const local = await localRegistryIsUsable(deps);
if (local) checks.push(local);
const result = ordered(checks);
return result.length === 0
? { ready: true, mode: "local", checks: [{ level: "info", code: "auth_ready", message: "Authentication is ready." }] }
: { ready: false, mode: "local", checks: result };
}
const requiredSecrets = ["THT_OIDC_CLIENT_SECRET", "THT_AUTHENTIK_API_TOKEN"];
if (requiredSecrets.some((name) => !secretPresent(deps.secrets, name))) {
checks.push(check("oidc_secret_missing", "A required OIDC or group catalog secret is unavailable."));
}
if (!options.live || checks.length > 0) {
const result = ordered(checks);
return result.length === 0
? { ready: true, mode: "oidc", checks: [{ level: "info", code: "auth_ready", message: "Authentication is ready." }] }
: { ready: false, mode: "oidc", checks: result };
}
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 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."));
}
}
const result = ordered(checks);
return result.length === 0
? { ready: true, mode: "oidc", checks: [{ level: "info", code: "auth_ready", message: "Authentication is ready." }] }
: { ready: false, mode: "oidc", checks: result };
},
};
}