diff --git a/src/console/console-config-catalog.ts b/src/console/console-config-catalog.ts index 0da31cbe..980621dc 100644 --- a/src/console/console-config-catalog.ts +++ b/src/console/console-config-catalog.ts @@ -26,10 +26,52 @@ export interface ConsoleConfigCatalogDiscoveryOptions { readonly ownerUid?: number; /** Test seam for Windows DACL verification. */ readonly windowsAclVerifier?: WindowsConfigAclVerifier; + /** Test-only opaque diagnostic observer for one catalog invocation. */ + readonly candidateStageObserver?: ConsoleConfigCatalogCandidateStageObserver; } export type WindowsConfigAclVerifier = (path: string, kind: "file" | "directory") => Promise; +/** Opaque test-only stages for diagnosing a rejected catalog candidate. */ +export type ConsoleConfigCatalogCandidateStage = + | "acl" + | "open" + | "opened-validation" + | "read" + | "after-read-validation" + | "decode" + | "parse" + | "migration-source" + | "close" + | "dedupe" + | "metadata" + | "accepted" + | "candidate"; + +/** A stage outcome never carries a path, filesystem identity, config value, or error detail. */ +export type ConsoleConfigCatalogCandidateOutcome = "success" | "rejected" | "duplicate" | "error"; + +export interface ConsoleConfigCatalogCandidateStageEvent { + /** Stable only within one discovery invocation; never derived from a pathname. */ + readonly candidateIndex: number; + readonly stage: ConsoleConfigCatalogCandidateStage; + readonly outcome: ConsoleConfigCatalogCandidateOutcome; +} + +/** Test-only observer for opaque candidate diagnostics. */ +export type ConsoleConfigCatalogCandidateStageObserver = (event: ConsoleConfigCatalogCandidateStageEvent) => void; + +type TrustedConfigurationFileHandle = Awaited>; + +function observeCandidateStage( + observer: ConsoleConfigCatalogCandidateStageObserver | undefined, + candidateIndex: number, + stage: ConsoleConfigCatalogCandidateStage, + outcome: ConsoleConfigCatalogCandidateOutcome +): void { + observer?.({ candidateIndex, stage, outcome }); +} + export interface DiscoveredConsoleConfiguration { /** Canonical local path retained only in the in-process registry. */ readonly path: string; @@ -137,12 +179,29 @@ async function trustedDirectory( return canonical; } +async function closeTrustedConfigurationHandle( + handle: TrustedConfigurationFileHandle, + candidateIndex: number, + candidateStageObserver: ConsoleConfigCatalogCandidateStageObserver | undefined +): Promise { + try { + await handle.close(); + } catch (error) { + observeCandidateStage(candidateStageObserver, candidateIndex, "close", "error"); + // Candidate discovery deliberately fails closed if any guarded-read cleanup fails. + throw error; + } + observeCandidateStage(candidateStageObserver, candidateIndex, "close", "success"); +} + async function readTrustedConfiguration( path: string, directory: string, ownerUid: number | undefined, platform: NodeJS.Platform, - windowsAclVerifier: WindowsConfigAclVerifier + windowsAclVerifier: WindowsConfigAclVerifier, + candidateIndex: number, + candidateStageObserver: ConsoleConfigCatalogCandidateStageObserver | undefined ): Promise<{ readonly path: string; readonly identity: string; @@ -154,40 +213,97 @@ async function readTrustedConfiguration( if (!isWithin(directory, canonical)) return undefined; const resolved = await stat(canonical); if (!isTrustedFile(resolved, ownerUid, platform) || !sameEntry(observed, resolved)) return undefined; - if (!(await hasTrustedWindowsAcl(canonical, "file", platform, windowsAclVerifier))) return undefined; + if (!(await hasTrustedWindowsAcl(canonical, "file", platform, windowsAclVerifier))) { + observeCandidateStage(candidateStageObserver, candidateIndex, "acl", "rejected"); + return undefined; + } + observeCandidateStage(candidateStageObserver, candidateIndex, "acl", "success"); - const handle = await open(canonical, readOnlyFlags); + let handle: TrustedConfigurationFileHandle; + try { + handle = await open(canonical, readOnlyFlags); + } catch (error) { + observeCandidateStage(candidateStageObserver, candidateIndex, "open", "error"); + throw error; + } + observeCandidateStage(candidateStageObserver, candidateIndex, "open", "success"); try { - const opened = await handle.stat(); + let opened: Stats; + try { + opened = await handle.stat(); + } catch (error) { + observeCandidateStage(candidateStageObserver, candidateIndex, "opened-validation", "error"); + throw error; + } if ( !isTrustedFile(opened, ownerUid, platform) || !sameEntry(observed, opened) || opened.size > maximumConfigurationBytes ) { + observeCandidateStage(candidateStageObserver, candidateIndex, "opened-validation", "rejected"); return undefined; } - const content = await handle.readFile(); - const afterRead = await handle.stat(); + observeCandidateStage(candidateStageObserver, candidateIndex, "opened-validation", "success"); + let content: Buffer; + try { + content = await handle.readFile(); + } catch (error) { + observeCandidateStage(candidateStageObserver, candidateIndex, "read", "error"); + throw error; + } + observeCandidateStage(candidateStageObserver, candidateIndex, "read", "success"); + let afterRead: Stats; + try { + afterRead = await handle.stat(); + } catch (error) { + observeCandidateStage(candidateStageObserver, candidateIndex, "after-read-validation", "error"); + throw error; + } if ( !isTrustedFile(afterRead, ownerUid, platform) || !sameEntry(observed, afterRead) || afterRead.size !== opened.size || content.byteLength > maximumConfigurationBytes ) { + observeCandidateStage(candidateStageObserver, candidateIndex, "after-read-validation", "rejected"); return undefined; } - const text = new TextDecoder("utf-8", { fatal: true }).decode(content); + observeCandidateStage(candidateStageObserver, candidateIndex, "after-read-validation", "success"); + let text: string; + try { + text = new TextDecoder("utf-8", { fatal: true }).decode(content); + } catch (error) { + observeCandidateStage(candidateStageObserver, candidateIndex, "decode", "error"); + throw error; + } + observeCandidateStage(candidateStageObserver, candidateIndex, "decode", "success"); + let config: ReturnType; + try { + config = loadConfigFromText(text, canonical); + } catch (error) { + observeCandidateStage(candidateStageObserver, candidateIndex, "parse", "error"); + throw error; + } + observeCandidateStage(candidateStageObserver, candidateIndex, "parse", "success"); + let migrationSource: ReturnType; + try { + migrationSource = createConfigMigrationSource(content, afterRead); + } catch (error) { + observeCandidateStage(candidateStageObserver, candidateIndex, "migration-source", "error"); + throw error; + } + observeCandidateStage(candidateStageObserver, candidateIndex, "migration-source", "success"); return { path: canonical, identity: `${opened.dev}:${opened.ino}`, trustedConfiguration: { - config: loadConfigFromText(text, canonical), + config, contentDigest: createHash("sha256").update(content).digest("base64url"), - migrationSource: createConfigMigrationSource(content, afterRead) + migrationSource } }; } finally { - await handle.close(); + await closeTrustedConfigurationHandle(handle, candidateIndex, candidateStageObserver); } } @@ -201,6 +317,7 @@ export async function discoverConsoleConfigCatalog( const platform = options.platform ?? process.platform; const ownerUid = options.ownerUid ?? defaultOwnerUid(platform); const windowsAclVerifier = options.windowsAclVerifier ?? verifyWindowsConfigPathSecurity; + const candidateStageObserver = options.candidateStageObserver; let directory: string | undefined; try { directory = await trustedDirectory(resolve(options.configDirectory), ownerUid, platform, windowsAclVerifier); @@ -229,19 +346,32 @@ export async function discoverConsoleConfigCatalog( const identities = new Set(); const configurations: DiscoveredConsoleConfiguration[] = []; - for (const name of names) { + for (const [candidateIndex, name] of names.entries()) { try { const discovered = await readTrustedConfiguration( join(directory, name), directory, ownerUid, platform, - windowsAclVerifier + windowsAclVerifier, + candidateIndex, + candidateStageObserver ); if (discovered === undefined) continue; - if (identities.has(discovered.identity)) continue; + if (identities.has(discovered.identity)) { + observeCandidateStage(candidateStageObserver, candidateIndex, "dedupe", "duplicate"); + continue; + } identities.add(discovered.identity); - const summary = consoleInitializedConfigMetadata(discovered.trustedConfiguration.config); + observeCandidateStage(candidateStageObserver, candidateIndex, "dedupe", "success"); + let summary: ReturnType; + try { + summary = consoleInitializedConfigMetadata(discovered.trustedConfiguration.config); + } catch (error) { + observeCandidateStage(candidateStageObserver, candidateIndex, "metadata", "error"); + throw error; + } + observeCandidateStage(candidateStageObserver, candidateIndex, "metadata", "success"); const configuration: DiscoveredConsoleConfiguration = { path: discovered.path, initializedMetadata: summary, @@ -262,7 +392,9 @@ export async function discoverConsoleConfigCatalog( }; trustedConfigurations.set(configuration, discovered.trustedConfiguration); configurations.push(configuration); + observeCandidateStage(candidateStageObserver, candidateIndex, "accepted", "success"); } catch { + observeCandidateStage(candidateStageObserver, candidateIndex, "candidate", "error"); // A malformed, raced, or untrusted candidate is never a Console entry. } } diff --git a/tests/console-dashboard-application-service.test.ts b/tests/console-dashboard-application-service.test.ts index f3928cf4..c6966222 100644 --- a/tests/console-dashboard-application-service.test.ts +++ b/tests/console-dashboard-application-service.test.ts @@ -1,8 +1,11 @@ -import { chmod, link, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises"; +import { chmod, link, lstat, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { afterEach, describe, expect, it } from "vitest"; -import { discoverConsoleConfigCatalog } from "../src/console/console-config-catalog.js"; +import { basename, join } from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + discoverConsoleConfigCatalog, + type ConsoleConfigCatalogCandidateStageEvent +} from "../src/console/console-config-catalog.js"; import { ConsoleDashboardApplicationService } from "../src/console/console-dashboard-application-service.js"; import { buildPresetConfig } from "../src/config/presets.js"; import { verifyWindowsConfigPathSecurity } from "../src/cli/windows-config-acl.js"; @@ -13,6 +16,29 @@ import { import { startOAuthCompatibilityProbe } from "./helpers/fake-remote-upstream.js"; const temporaryDirectories: string[] = []; +const catalogAclDiagnostic = vi.hoisted(() => ({ + verifier: undefined as undefined | ((path: string, kind: "file" | "directory") => Promise) +})); +const catalogStageDiagnostic = vi.hoisted(() => ({ + observer: undefined as undefined | ((event: ConsoleConfigCatalogCandidateStageEvent) => void) +})); + +vi.mock("../src/console/console-config-catalog.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + discoverConsoleConfigCatalog: (options: Parameters[0]) => { + const verifier = catalogAclDiagnostic.verifier; + const observer = catalogStageDiagnostic.observer; + const instrumentedOptions = { + ...options, + ...(verifier === undefined ? {} : { windowsAclVerifier: verifier }), + ...(observer === undefined ? {} : { candidateStageObserver: observer }) + }; + return actual.discoverConsoleConfigCatalog(instrumentedOptions); + } + }; +}); function supportedKnownConnectorOptions(): { readonly preset: string; @@ -37,6 +63,8 @@ function importableClientEntry(): { readonly command: string; readonly args: rea } afterEach(async () => { + catalogAclDiagnostic.verifier = undefined; + catalogStageDiagnostic.observer = undefined; await Promise.all(temporaryDirectories.splice(0).map((directory) => rm(directory, { recursive: true, force: true }))); }); @@ -48,6 +76,53 @@ async function writeCatalogFixture(path: string, value: unknown): Promise await writeFile(path, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 }); } +function catalogFixtureLabel(path: string, kind: "file" | "directory"): "directory" | "gsc" | "sentry" | "other" { + if (kind === "directory") return "directory"; + switch (basename(path).toLocaleLowerCase("en-US")) { + case "gsc.json": + return "gsc"; + case "sentry.json": + return "sentry"; + default: + return "other"; + } +} + +async function compareFileIdentities(first: string, second: string): Promise<{ + readonly bigintIdentity: "same" | "different"; + readonly numberIdentity: "same" | "different"; +}> { + const [firstNumber, secondNumber, firstBigInt, secondBigInt] = await Promise.all([ + lstat(first), + lstat(second), + lstat(first, { bigint: true }), + lstat(second, { bigint: true }) + ]); + return { + numberIdentity: firstNumber.dev === secondNumber.dev && firstNumber.ino === secondNumber.ino ? "same" : "different", + bigintIdentity: firstBigInt.dev === secondBigInt.dev && firstBigInt.ino === secondBigInt.ino ? "same" : "different" + }; +} + +function catalogStageSummary( + events: readonly ConsoleConfigCatalogCandidateStageEvent[], + configurationNames: readonly string[] | undefined +): readonly { + readonly candidate: "gsc" | "sentry"; + readonly stages: readonly Omit[]; + readonly accepted: boolean; +}[] { + // The catalog sorts the only two JSON fixtures alphabetically: gsc is index 0, sentry is index 1. + const candidates = ["gsc", "sentry"] as const; + return candidates.map((candidate, candidateIndex) => ({ + candidate, + stages: events + .filter((event) => event.candidateIndex === candidateIndex) + .map(({ stage, outcome }) => ({ stage, outcome })), + accepted: configurationNames?.includes(candidate) ?? false + })); +} + describe("Console dashboard application service", () => { it.runIf(process.platform === "win32")("creates fixture files that pass the production Windows ACL verifier", async () => { const root = await mkdtemp(join(tmpdir(), "miftah-console-dashboard-acl-")); @@ -91,11 +166,34 @@ describe("Console dashboard application service", () => { profiles: { work: {} } }); - // Keep the production-only ACL boundary explicit on Windows: catalog - // discovery deliberately suppresses individual untrusted candidates. + const fixtureIdentity = process.platform === "win32" + ? await compareFileIdentities(gscPath, sentryPath) + : undefined; + const candidateStages: ConsoleConfigCatalogCandidateStageEvent[] = []; + catalogStageDiagnostic.observer = (event) => { + candidateStages.push(event); + }; + + // Instrument the exact dashboard catalog invocation on Windows. The mock + // delegates to the real catalog and real verifier; it only records safe + // fixture labels so a fail-closed omission identifies its boundary. + const aclProbes: Array<{ + candidate: "directory" | "gsc" | "sentry" | "other"; + kind: "file" | "directory"; + outcome: "trusted" | "untrusted" | "error"; + }> = []; if (process.platform === "win32") { - await expect(verifyWindowsConfigPathSecurity(gscPath, "file")).resolves.toBe(true); - await expect(verifyWindowsConfigPathSecurity(sentryPath, "file")).resolves.toBe(true); + catalogAclDiagnostic.verifier = async (path, kind) => { + const candidate = catalogFixtureLabel(path, kind); + try { + const trusted = await verifyWindowsConfigPathSecurity(path, kind); + aclProbes.push({ candidate, kind, outcome: trusted ? "trusted" : "untrusted" }); + return trusted; + } catch (error) { + aclProbes.push({ candidate, kind, outcome: "error" }); + throw error; + } + }; } const service = new ConsoleDashboardApplicationService({ @@ -104,7 +202,63 @@ describe("Console dashboard application service", () => { launcher: { command: process.execPath, args: ["serve"] } }); - const initial = await service.configMetadata(); + const initial = await service.configMetadata().finally(() => { + catalogAclDiagnostic.verifier = undefined; + catalogStageDiagnostic.observer = undefined; + }); + expect(catalogStageSummary(candidateStages, initial.catalog?.configurations.map((configuration) => configuration.name))).toEqual([ + { + candidate: "gsc", + stages: [ + { stage: "acl", outcome: "success" }, + { stage: "open", outcome: "success" }, + { stage: "opened-validation", outcome: "success" }, + { stage: "read", outcome: "success" }, + { stage: "after-read-validation", outcome: "success" }, + { stage: "decode", outcome: "success" }, + { stage: "parse", outcome: "success" }, + { stage: "migration-source", outcome: "success" }, + { stage: "close", outcome: "success" }, + { stage: "dedupe", outcome: "success" }, + { stage: "metadata", outcome: "success" }, + { stage: "accepted", outcome: "success" } + ], + accepted: true + }, + { + candidate: "sentry", + stages: [ + { stage: "acl", outcome: "success" }, + { stage: "open", outcome: "success" }, + { stage: "opened-validation", outcome: "success" }, + { stage: "read", outcome: "success" }, + { stage: "after-read-validation", outcome: "success" }, + { stage: "decode", outcome: "success" }, + { stage: "parse", outcome: "success" }, + { stage: "migration-source", outcome: "success" }, + { stage: "close", outcome: "success" }, + { stage: "dedupe", outcome: "success" }, + { stage: "metadata", outcome: "success" }, + { stage: "accepted", outcome: "success" } + ], + accepted: true + } + ]); + if (process.platform === "win32") { + expect({ + aclProbeSummary: [...aclProbes].sort((left, right) => left.candidate.localeCompare(right.candidate)), + fixtureIdentity, + serviceConfigurationNames: initial.catalog?.configurations.map((configuration) => configuration.name) + }).toEqual({ + aclProbeSummary: [ + { candidate: "directory", kind: "directory", outcome: "trusted" }, + { candidate: "gsc", kind: "file", outcome: "trusted" }, + { candidate: "sentry", kind: "file", outcome: "trusted" } + ], + fixtureIdentity: { bigintIdentity: "different", numberIdentity: "different" }, + serviceConfigurationNames: ["gsc", "sentry"] + }); + } expect(initial).toMatchObject({ initialized: false, restartRequiredForExistingClients: true,