diff --git a/product-source/guanghu-knowledge-base/server/trusted-signer-snapshot.test.ts b/product-source/guanghu-knowledge-base/server/trusted-signer-snapshot.test.ts new file mode 100644 index 0000000..2a9565e --- /dev/null +++ b/product-source/guanghu-knowledge-base/server/trusted-signer-snapshot.test.ts @@ -0,0 +1,184 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + TrustedSignerSnapshotLoader, + type TrustedSignerSnapshotTransport, +} from './trusted-signer-snapshot.js'; +import { resolveTrustedManifestSigner } from './trusted-signer-registry.js'; + +const COMMIT = 'a'.repeat(40); +const ANCHOR_URL = 'https://guanghulab.com/api/ai/v1/anchor'; +const REGISTRY_PATH = 'routing/trusted-domain-manifest-signers.json'; +const registryUrl = (commit: string) => + `https://guanghulab.com/code/bingshuo/guanghu-ice-heart/raw/commit/${commit}/${REGISTRY_PATH}`; + +function anchor(commit = COMMIT, overrides: Record = {}) { + return { + schema: 'guanghu.public-navigation-anchor/v1', + anchor_id: 'GLW-PUBLIC-NAV-ANCHOR-001', + state: 'CURRENT_CANONICAL', + repository_id: 'REPO-012', + branch: 'main', + public_entry: ANCHOR_URL, + code_entry: 'https://guanghulab.com/code/bingshuo/guanghu-ice-heart', + maps: { + trusted_domain_manifest_signers: { + path: REGISTRY_PATH, + id: 'GH-AIOS-TRUSTED-DOMAIN-MANIFEST-SIGNERS-001', + version: '1.0.0', + }, + }, + navigation_source: { + anchor_id: 'GLW-PUBLIC-NAV-ANCHOR-001', + source_commit: commit, + source_mode: 'REPO-012_MAIN_GIT_SNAPSHOT', + source_degraded: false, + }, + ...overrides, + }; +} + +function registry() { + return { + schema: 'gh-aios.trusted-domain-manifest-signers/v1', + registryId: 'GH-AIOS-TRUSTED-DOMAIN-MANIFEST-SIGNERS-001', + version: '1.0.0', + state: 'CURRENT', + signers: [], + }; +} + +function transport(responses: Map): TrustedSignerSnapshotTransport & { calls: string[] } { + const calls: string[] = []; + return { + calls, + async fetchJson(url) { + calls.push(url); + if (!responses.has(url)) throw new Error('unexpected_url'); + const response = responses.get(url); + if (response instanceof Error) throw response; + return response; + }, + }; +} + +test('loads the anchor and signer registry from one exact REPO-012 commit', async () => { + const source = transport(new Map([ + [ANCHOR_URL, anchor()], + [registryUrl(COMMIT), registry()], + ])); + const loader = new TrustedSignerSnapshotLoader(source); + + const result = await loader.refresh(); + + assert.deepEqual(source.calls, [ANCHOR_URL, registryUrl(COMMIT)]); + assert.equal(result.receipt.status, 'CURRENT'); + assert.equal(result.receipt.sourceCommit, COMMIT); + assert.equal(result.receipt.registryVersion, '1.0.0'); + assert.equal(result.receipt.signerCount, 0); + assert.ok(result.registry); + assert.equal(result.registry.source.sourceCommit, COMMIT); + assert.equal(resolveTrustedManifestSigner(result.registry, { + domainId: 'DOM-FIFTH-0001', + repositoryId: 'REPO-014', + signerId: 'GH-LIGHTHOUSE-001', + }), null); +}); + +test('a degraded anchor fails closed before any registry URL is fetched', async () => { + const source = transport(new Map([ + [ANCHOR_URL, anchor(COMMIT, { + navigation_source: { + anchor_id: 'GLW-PUBLIC-NAV-ANCHOR-001', + source_commit: COMMIT, + source_mode: 'REPO-012_MAIN_GIT_SNAPSHOT', + source_degraded: true, + }, + })], + ])); + const loader = new TrustedSignerSnapshotLoader(source); + + const result = await loader.refresh(); + + assert.deepEqual(source.calls, [ANCHOR_URL]); + assert.equal(result.registry, null); + assert.deepEqual(result.receipt, { + status: 'UNAVAILABLE', + reason: 'ANCHOR_INVALID', + sourceCommit: null, + registryVersion: null, + signerCount: 0, + }); +}); + +test('an invalid later update retains only the in-memory last-known-good snapshot', async () => { + let currentAnchor: unknown = anchor(); + let currentRegistry: unknown = registry(); + const source: TrustedSignerSnapshotTransport = { + async fetchJson(url) { + if (url === ANCHOR_URL) return currentAnchor; + if (url === registryUrl(COMMIT)) return currentRegistry; + throw new Error('unexpected_url'); + }, + }; + const loader = new TrustedSignerSnapshotLoader(source); + const first = await loader.refresh(); + assert.equal(first.receipt.status, 'CURRENT'); + + currentRegistry = { ...registry(), version: 'not-semver' }; + const degraded = await loader.refresh(); + + assert.equal(degraded.registry, first.registry); + assert.deepEqual(degraded.receipt, { + status: 'DEGRADED_LAST_KNOWN_GOOD', + reason: 'REGISTRY_INVALID', + sourceCommit: COMMIT, + registryVersion: '1.0.0', + signerCount: 0, + }); + + currentAnchor = anchor('b'.repeat(40)); + const transportFailure = await loader.refresh(); + assert.equal(transportFailure.registry, first.registry); + assert.equal(transportFailure.receipt.status, 'DEGRADED_LAST_KNOWN_GOOD'); + assert.equal(transportFailure.receipt.reason, 'SOURCE_UNAVAILABLE'); + assert.equal(transportFailure.receipt.sourceCommit, COMMIT); +}); + +test('concurrent callers share one refresh and receive no raw error details', async () => { + let releaseAnchor!: () => void; + const anchorGate = new Promise(resolve => { releaseAnchor = resolve; }); + const source = transport(new Map([ + [ANCHOR_URL, anchor()], + [registryUrl(COMMIT), registry()], + ])); + const originalFetch = source.fetchJson.bind(source); + source.fetchJson = async url => { + if (url === ANCHOR_URL) await anchorGate; + return originalFetch(url); + }; + const loader = new TrustedSignerSnapshotLoader(source); + + const first = loader.refresh(); + const second = loader.refresh(); + releaseAnchor(); + assert.equal(await first, await second); + assert.deepEqual(source.calls, [ANCHOR_URL, registryUrl(COMMIT)]); + + const failing = new TrustedSignerSnapshotLoader({ + async fetchJson() { + throw new Error('secret transport detail'); + }, + }); + const result = await failing.refresh(); + assert.equal(JSON.stringify(result), JSON.stringify({ + registry: null, + receipt: { + status: 'UNAVAILABLE', + reason: 'SOURCE_UNAVAILABLE', + sourceCommit: null, + registryVersion: null, + signerCount: 0, + }, + })); +}); diff --git a/product-source/guanghu-knowledge-base/server/trusted-signer-snapshot.ts b/product-source/guanghu-knowledge-base/server/trusted-signer-snapshot.ts new file mode 100644 index 0000000..6572ac7 --- /dev/null +++ b/product-source/guanghu-knowledge-base/server/trusted-signer-snapshot.ts @@ -0,0 +1,155 @@ +import { + parseTrustedManifestSignerRegistry, + type TrustedManifestSignerRegistry, +} from './trusted-signer-registry.js'; + +const ANCHOR_URL = 'https://guanghulab.com/api/ai/v1/anchor'; +const CODE_URL = 'https://guanghulab.com/code/bingshuo/guanghu-ice-heart'; +const REGISTRY_ID = 'GH-AIOS-TRUSTED-DOMAIN-MANIFEST-SIGNERS-001'; +const REGISTRY_PATH = 'routing/trusted-domain-manifest-signers.json'; +const COMMIT_PATTERN = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/; +const VERSION_PATTERN = /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/; + +export interface TrustedSignerSnapshotTransport { + fetchJson(url: string): Promise; +} + +export type TrustedSignerSnapshotReason = + | 'ANCHOR_INVALID' + | 'REGISTRY_INVALID' + | 'SOURCE_UNAVAILABLE'; + +export interface TrustedSignerSnapshotReceipt { + status: 'CURRENT' | 'DEGRADED_LAST_KNOWN_GOOD' | 'UNAVAILABLE'; + reason?: TrustedSignerSnapshotReason; + sourceCommit: string | null; + registryVersion: string | null; + signerCount: number; +} + +export interface TrustedSignerSnapshotResult { + registry: TrustedManifestSignerRegistry | null; + receipt: Readonly; +} + +interface ParsedAnchor { + registryVersion: string; + sourceCommit: string; +} + +class SnapshotLoadError extends Error { + constructor(readonly reason: TrustedSignerSnapshotReason) { + super(reason); + } +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function parseAnchor(input: unknown): ParsedAnchor { + if (!isRecord(input) + || input.schema !== 'guanghu.public-navigation-anchor/v1' + || input.anchor_id !== 'GLW-PUBLIC-NAV-ANCHOR-001' + || input.state !== 'CURRENT_CANONICAL' + || input.repository_id !== 'REPO-012' + || input.branch !== 'main' + || input.public_entry !== ANCHOR_URL + || input.code_entry !== CODE_URL + || !isRecord(input.maps) + || !isRecord(input.maps.trusted_domain_manifest_signers) + || input.maps.trusted_domain_manifest_signers.path !== REGISTRY_PATH + || input.maps.trusted_domain_manifest_signers.id !== REGISTRY_ID + || typeof input.maps.trusted_domain_manifest_signers.version !== 'string' + || !VERSION_PATTERN.test(input.maps.trusted_domain_manifest_signers.version) + || !isRecord(input.navigation_source) + || input.navigation_source.anchor_id !== 'GLW-PUBLIC-NAV-ANCHOR-001' + || input.navigation_source.source_mode !== 'REPO-012_MAIN_GIT_SNAPSHOT' + || input.navigation_source.source_degraded !== false + || typeof input.navigation_source.source_commit !== 'string' + || !COMMIT_PATTERN.test(input.navigation_source.source_commit)) { + throw new SnapshotLoadError('ANCHOR_INVALID'); + } + return Object.freeze({ + registryVersion: input.maps.trusted_domain_manifest_signers.version, + sourceCommit: input.navigation_source.source_commit, + }); +} + +function registryUrl(sourceCommit: string): string { + return `${CODE_URL}/raw/commit/${sourceCommit}/${REGISTRY_PATH}`; +} + +function receipt( + status: TrustedSignerSnapshotReceipt['status'], + registry: TrustedManifestSignerRegistry | null, + reason?: TrustedSignerSnapshotReason, +): Readonly { + return Object.freeze({ + status, + ...(reason ? { reason } : {}), + sourceCommit: registry?.source.sourceCommit ?? null, + registryVersion: registry?.version ?? null, + signerCount: registry?.signers.length ?? 0, + }); +} + +function result( + registry: TrustedManifestSignerRegistry | null, + snapshotReceipt: Readonly, +): TrustedSignerSnapshotResult { + return Object.freeze({ registry, receipt: snapshotReceipt }); +} + +export class TrustedSignerSnapshotLoader { + #inFlight: Promise | null = null; + #lastKnownGood: TrustedManifestSignerRegistry | null = null; + + constructor(private readonly transport: TrustedSignerSnapshotTransport) {} + + refresh(): Promise { + if (this.#inFlight) return this.#inFlight; + this.#inFlight = this.#load().finally(() => { + this.#inFlight = null; + }); + return this.#inFlight; + } + + async #load(): Promise { + try { + let rawAnchor: unknown; + try { + rawAnchor = await this.transport.fetchJson(ANCHOR_URL); + } catch { + throw new SnapshotLoadError('SOURCE_UNAVAILABLE'); + } + const anchor = parseAnchor(rawAnchor); + let rawRegistry: unknown; + try { + rawRegistry = await this.transport.fetchJson(registryUrl(anchor.sourceCommit)); + } catch { + throw new SnapshotLoadError('SOURCE_UNAVAILABLE'); + } + let registry: TrustedManifestSignerRegistry; + try { + registry = parseTrustedManifestSignerRegistry(rawRegistry, { + repositoryId: 'REPO-012', + sourceCommit: anchor.sourceCommit, + sourceUrl: registryUrl(anchor.sourceCommit), + }); + } catch { + throw new SnapshotLoadError('REGISTRY_INVALID'); + } + if (registry.version !== anchor.registryVersion) { + throw new SnapshotLoadError('REGISTRY_INVALID'); + } + this.#lastKnownGood = registry; + return result(registry, receipt('CURRENT', registry)); + } catch (error) { + const reason = error instanceof SnapshotLoadError ? error.reason : 'SOURCE_UNAVAILABLE'; + return this.#lastKnownGood + ? result(this.#lastKnownGood, receipt('DEGRADED_LAST_KNOWN_GOOD', this.#lastKnownGood, reason)) + : result(null, receipt('UNAVAILABLE', null, reason)); + } + } +}