Skip to content

Commit 23a07c8

Browse files
fix(plugin-audit): a registered audit seam that fails to resolve stops the sealer instead of falling back (#34495)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi96xkbCcbB1nF3xM9vBtrWwE)_ Fixes #34280 Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么:** 审计封存器每轮取宿主的签名服务、导出服务和集群服务时,分清三种情况:没注册就用本机兜底(和以前一样);注册了能取到就用;注册了却取不到(比如 KMS 客户端起不来)就这一轮不封存,并报一条 error 点名哪个服务。 - **为什么改:** 以前「取不到」被当成「没注册」,于是悄悄改用本机密钥签名、悄悄不导出、悄悄不加集群锁,没有任何日志;客户以为是 KMS 签的,其实不是。另外用工厂方式注册的签名服务以前根本取不到,也被悄悄忽略。 - **风险与回滚:** 只影响注册了这三个服务的宿主;配置坏掉的宿主从「悄悄降级」变成「停止封存并报错」,配置正常的宿主无变化。回滚即还原本 PR。 - **先看:** `packages/plugins/plugin-audit/src/audit-seal/sealer.ts` 的 `resolveSeams`;`packages/plugins/plugin-audit/src/audit-plugin.ts` 末尾的 `hostSeamResolver`。 - **两分钟验证:** `cd packages/plugins/plugin-audit && npx vitest run src/audit-seal/audit-seal-host-seam-resolve-34280.integration.test.ts`,预期 5 条全绿。 - **需要你做的:** 无,席位落地。 ## What changes - `audit-seal/sealer.ts`: a pass resolves its three host seams (`audit.checkpointSigner`, `audit.checkpointSink`, `cluster`) once, at its start, in `resolveSeams()`. A getter that answers `undefined` means "not registered" and keeps its stand-in (local signer, no export, in-process lock). A getter that throws means "registered and not resolvable": the pass seals nothing and reports at `error`, naming the slot and the fallback it refused, once per `REPORT_REPEAT_MS` while it lasts (the sealer's existing `report()` discipline). The resolved sink and cluster are handed to the lock and the object passes; the lock no longer absorbs a throwing cluster getter, and delivery no longer re-resolves the sink per checkpoint. A sink whose `deliver()` fails is still only a warning, unchanged. The getters may now return a promise; `AuditSealer` is not exported from the package root. - `audit-plugin.ts`: `startSealer` resolves each seam with `hostSeamResolver`, which uses the kernel's async accessor and absorbs only the branded "never registered" rejection (`isServiceNotRegisteredError`, `@objectstack/core`), the pattern `service-automation` already uses for `tenancy`. Every other rejection propagates. The async accessor also builds a factory-registered seam, which the sync accessor refused with "is async" and the old helper read as absent. A host with no async accessor (`LiteKernel`, no factories) keeps the sync accessor, where "not registered" is the only fault. ## Tests New `src/audit-seal/audit-seal-host-seam-resolve-34280.integration.test.ts`, on a real `ObjectKernel` with ObjectQL over SQLite (wasm): 1. No host signer: one checkpoint, signed under the local key (its fingerprint is the only `sys_audit_signing_key` row); no error. 2. Host signer registered as a factory that throws: `runPass()` → 0, no checkpoint, no local key created, exactly one error naming `audit.checkpointSigner` and "does not sign with the local key"; a second pass adds no second line. 3. Host signer that resolves, as an instance and as a factory: the checkpoint carries the host key id and verifies under the host public key; no local key created. 4. Sink factory that throws: nothing sealed, one error naming `audit.checkpointSink`; a resolving sink factory is handed the checkpoint. 5. Cluster factory that throws: nothing sealed, one error naming `cluster`. Ablation (fix reverted, test kept): cases 2–5 red (`expected 1 to be +0` for 2/4/5; case 3's factory leg signs under the local key), case 1 green. No existing test changed. `plugin-audit`: 100 files / 1659 tests green; `pnpm typecheck` (incl. `check:test-typecheck`) green. ## Acceptance notes - **Narrowing declaration (the card asks the dev to measure it):** `Clause-②: no`. No key, config value or service shape a host writes is refused; what changes is the reaction to a registration that already fails. A host whose signer, sink or cluster registration threw used to seal silently with the local key or without its lock and now seals nothing until it is fixed, which is the card's rule. A working host sees no change. The changeset says this in its last paragraph. - **Same-family site, not changed here (out of the claimed file surface):** `packages/cli/src/utils/audit-redaction-seal.ts` resolves `audit.checkpointSigner` / `audit.checkpointSink` with the same catch-all helper, so a CLI redaction run with a failing host signer falls back to the local signer in `amendment-writer.ts`. Handed to the seat for a follow-up card. - "Logged once": the line repeats at most once per `REPORT_REPEAT_MS` while the fault lasts, as every other sealer fault does; the test pins that a second pass inside the window adds no line. ## Verification Gates per `node scripts/pm/dispatch-gates.mjs --commands` after the last commit: see the `os-dev-report` comment on #34280. Co-authored-by: Claude <noreply@anthropic.com>
1 parent 047f37b commit 23a07c8

4 files changed

Lines changed: 326 additions & 30 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/plugin-audit': patch
3+
---
4+
5+
fix(plugin-audit): a host checkpoint signer, sink or cluster service that is registered but fails to resolve stops the sealer instead of falling back
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The audit sealer (ADR-0154) resolves three host seams on each pass: `audit.checkpointSigner`, `audit.checkpointSink` and `cluster`. It turned every resolution error into "not registered". A host signer whose factory threw (a KMS client that cannot start, a missing credential) was therefore replaced by the local signing key, a failing sink dropped the off-host export, and a failing cluster service let the pass run on the in-process lock. Nothing was logged. A seam registered as a factory was never built at all, because the sealer used the synchronous accessor, so a factory-registered host signer was silently ignored.
11+
12+
Now only an absent seam falls back: no host signer signs with the local key, no sink exports nothing, no cluster service takes the in-process lock, all as before. A seam that is registered and resolves is used, including one registered as a factory. A seam that is registered and fails to resolve stops the pass: no checkpoint is signed, and the sealer reports it at `error`, naming the slot, once while it lasts. Each pass retries.
13+
14+
A host whose signer, sink or cluster registration was failing used to seal silently with the local key or without its lock; it now seals nothing until the registration is fixed. A working host sees no change.

‎packages/plugins/plugin-audit/src/audit-plugin.ts‎

Lines changed: 44 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
22

3-
import type { Plugin, PluginContext } from '@objectstack/core';
3+
import { isServiceNotRegisteredError, type Plugin, type PluginContext } from '@objectstack/core';
44
import {
55
effectiveTenancyPosture,
66
resolveLocalizationContext,
@@ -835,8 +835,9 @@ export class AuditPlugin implements Plugin {
835835
* Start the audit sealer (ADR-0154 D3) over the engine's storage. The
836836
* signer and the sink are resolved per pass from the `audit.checkpointSigner`
837837
* and `audit.checkpointSink` slots (D11), the signer falling back to the
838-
* default local key of D6; the `cluster` service, when registered, holds the
839-
* `audit.sealer` lock. An engine without the storage surface the sealer
838+
* default local key of D6 only when no host signer is registered; the
839+
* `cluster` service, when registered, holds the `audit.sealer` lock. A seam
840+
* that is registered but fails to resolve stops the pass (#34280). An engine without the storage surface the sealer
840841
* reads (a test double) starts no sealer, and neither does a one-shot
841842
* command's boot (`armSealer: false`).
842843
*/
@@ -848,19 +849,13 @@ export class AuditPlugin implements Plugin {
848849
const option = this.options.cryptoProvider ?? this.hostCryptoProvider;
849850
const crypto = typeof option === 'function' ? option() : option;
850851
const localSigner = crypto ? new LocalCheckpointSigner({ engine: sealEngine, crypto }) : undefined;
851-
const optional = <T>(name: string): T | undefined => {
852-
try {
853-
return ctx.getService<T>(name) ?? undefined;
854-
} catch {
855-
return undefined;
856-
}
857-
};
852+
const seam = hostSeamResolver(ctx);
858853
this.sealer = new AuditSealer({
859854
engine: sealEngine,
860855
...(crypto ? { crypto } : {}),
861-
signer: () => optional<IAuditCheckpointSigner>(AUDIT_CHECKPOINT_SIGNER_SERVICE) ?? localSigner,
862-
sink: () => optional<IAuditCheckpointSink>(AUDIT_CHECKPOINT_SINK_SERVICE),
863-
cluster: () => optional<IClusterService>('cluster'),
856+
signer: async () => (await seam<IAuditCheckpointSigner>(AUDIT_CHECKPOINT_SIGNER_SERVICE)) ?? localSigner,
857+
sink: () => seam<IAuditCheckpointSink>(AUDIT_CHECKPOINT_SINK_SERVICE),
858+
cluster: () => seam<IClusterService>('cluster'),
864859
logger: ctx.logger,
865860
});
866861
this.sealer.start();
@@ -1103,3 +1098,39 @@ function tenancyServiceResolver(ctx: PluginContext): TenancyServiceResolver | un
11031098
if (!kernel || typeof kernel.getServiceAsync !== 'function') return undefined;
11041099
return () => kernel.getServiceAsync!<TenancyPostureSource>('tenancy');
11051100
}
1101+
1102+
/**
1103+
* #34280: how the sealer reaches a host seam (`audit.checkpointSigner`,
1104+
* `audit.checkpointSink`, `cluster`), as three states, not two. Never
1105+
* registered ⇒ `undefined`, and the sealer uses its stand-in (the local
1106+
* signer, no export, the in-process lock). Registered and resolved ⇒ the
1107+
* service. Registered and NOT resolvable — a factory that throws, a KMS client
1108+
* that cannot start — ⇒ the rejection, which stops the pass instead of
1109+
* silently signing with the local key.
1110+
*
1111+
* The kernel's async accessor draws that line with the branded "never
1112+
* registered" rejection (`isServiceNotRegisteredError`), ⛔ not message text,
1113+
* and it also builds a factory-registered seam, which the sync accessor
1114+
* refuses ("is async"). A host with no async accessor (`LiteKernel`) has no
1115+
* factories, so "not registered" is the only fault its sync accessor reports.
1116+
*/
1117+
function hostSeamResolver(ctx: PluginContext): <T>(name: string) => Promise<T | undefined> {
1118+
return async <T>(name: string): Promise<T | undefined> => {
1119+
const kernel = ctx.getKernel?.() as
1120+
| { getServiceAsync?: <S>(name: string, scopeId?: string) => Promise<S> }
1121+
| undefined;
1122+
if (kernel && typeof kernel.getServiceAsync === 'function') {
1123+
try {
1124+
return (await kernel.getServiceAsync<T>(name)) ?? undefined;
1125+
} catch (err) {
1126+
if (isServiceNotRegisteredError(err)) return undefined;
1127+
throw err;
1128+
}
1129+
}
1130+
try {
1131+
return ctx.getService<T>(name) ?? undefined;
1132+
} catch {
1133+
return undefined;
1134+
}
1135+
};
1136+
}
Lines changed: 204 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { createHash, createPublicKey, generateKeyPairSync, sign as edSign, verify } from 'node:crypto';
4+
import { ObjectKernel } from '@objectstack/core';
5+
import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql';
6+
import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm';
7+
import { SysSecret } from '@objectstack/platform-objects/system';
8+
import {
9+
AUDIT_CHECKPOINT_SIGNER_SERVICE,
10+
AUDIT_CHECKPOINT_SINK_SERVICE,
11+
type AuditCheckpointSinkEntry,
12+
type IAuditCheckpointSigner,
13+
} from '@objectstack/spec/contracts';
14+
import { afterEach, describe, expect, it } from 'vitest';
15+
import { AuditPlugin } from '../audit-plugin.js';
16+
import { installDefaultOrganization } from '../default-organization.testkit.js';
17+
import { checkpointBodyFromRow, signedBodyBytes } from './index.js';
18+
import { bindingCrypto } from './seal-store.testkit.js';
19+
import type { AuditSealer } from './sealer.js';
20+
21+
/**
22+
* #34280 on a real kernel: the sealer reaches its three host seams
23+
* (`audit.checkpointSigner`, `audit.checkpointSink`, `cluster`, ADR-0154 D11)
24+
* in three states, not two. Only an ABSENT seam falls back — to the local
25+
* signer of D6, to no export, to the in-process lock. A seam that is
26+
* registered but cannot be resolved (here: a factory that throws, as a KMS
27+
* client that cannot start would) stops the pass — no checkpoint is signed —
28+
* and says so at `error`, naming the slot. A registered seam that resolves is
29+
* used, including one registered as a factory, which the sync accessor the
30+
* sealer used before could not build at all.
31+
*/
32+
33+
const PROBE = 'seal_probe';
34+
const H = 60 * 60 * 1000;
35+
const SYS = { isSystem: true } as const;
36+
37+
const probe = {
38+
name: PROBE,
39+
label: 'Seal Probe',
40+
systemFields: false,
41+
fields: {
42+
id: { name: 'id', label: 'ID', type: 'text' },
43+
created_at: { name: 'created_at', label: 'Created At', type: 'datetime' },
44+
action: { name: 'action', label: 'Action', type: 'text' },
45+
tenant_id: { name: 'tenant_id', label: 'Organization', type: 'text' },
46+
payload: { name: 'payload', label: 'Payload', type: 'textarea' },
47+
},
48+
lifecycle: { class: 'audit', retention: { maxAge: '90d' }, seal: { valueFields: ['payload'] } },
49+
};
50+
51+
/** A host-held Ed25519 key standing in for a KMS key: its own key id, its own public half. */
52+
function hostSigner(): IAuditCheckpointSigner & { publicKey: string; keyId: string } {
53+
const { publicKey, privateKey } = generateKeyPairSync('ed25519');
54+
const raw = Buffer.from(publicKey.export({ format: 'jwk' }).x!, 'base64url');
55+
const keyId = createHash('sha256').update(raw).digest('hex');
56+
return {
57+
keyId,
58+
publicKey: raw.toString('base64'),
59+
async sign(bytes) {
60+
return { keyId, signature: edSign(null, Buffer.from(bytes), privateKey).toString('base64') };
61+
},
62+
async trustedPublicKey(id) {
63+
return id === keyId ? raw.toString('base64') : null;
64+
},
65+
};
66+
}
67+
68+
/** The fault a host seam's factory raises when it cannot be built. */
69+
const unbuildable = (what: string) => () => {
70+
throw new Error(`${what} client cannot start: credential missing`);
71+
};
72+
73+
interface Booted {
74+
kernel: ObjectKernel;
75+
engine: ObjectQL;
76+
sealer: AuditSealer;
77+
errors: string[];
78+
checkpoints(): Promise<Array<Record<string, unknown>>>;
79+
}
80+
81+
const booted: ObjectKernel[] = [];
82+
83+
async function boot(register: (kernel: ObjectKernel) => void = () => {}): Promise<Booted> {
84+
const crypto = bindingCrypto();
85+
const plugin = new AuditPlugin({ cryptoProvider: crypto });
86+
const kernel = new ObjectKernel({ logger: { level: 'silent' } });
87+
booted.push(kernel);
88+
await kernel.use(new ObjectQLPlugin());
89+
await kernel.use(plugin);
90+
register(kernel);
91+
await kernel.bootstrap();
92+
const engine = kernel.getService<ObjectQL>('objectql');
93+
const sqlite = new SqliteWasmDriver({ filename: ':memory:' });
94+
await sqlite.connect();
95+
engine.registerDriver(sqlite, true);
96+
engine.registry.registerObject(probe as never, 'com.objectstack.audit.test.seal-probe');
97+
engine.registry.registerObject(SysSecret as never, 'com.objectstack.audit.test.seal-probe');
98+
await engine.syncSchemas();
99+
await installDefaultOrganization(engine);
100+
101+
// One row at rest in a settled window: one checkpoint's worth.
102+
const past = Math.floor(Date.now() / H) * H - 3 * H;
103+
const hot = engine.getDriverForObject(PROBE) as unknown as { create(o: string, r: Record<string, unknown>): Promise<unknown> };
104+
await hot.create(PROBE, { id: 'p1', created_at: new Date(past + 60_000).toISOString(), action: 'update', tenant_id: 'org_a', payload: 'x' });
105+
106+
const sealer = (plugin as unknown as { sealer: AuditSealer }).sealer;
107+
await sealer.stop(); // drive the pass here, not on the loop's clock
108+
const errors: string[] = [];
109+
const logger = (sealer as unknown as { options: { logger: { error(m: string): void } } }).options.logger;
110+
const error = logger.error.bind(logger);
111+
logger.error = (message: string) => {
112+
errors.push(message);
113+
error(message);
114+
};
115+
return {
116+
kernel,
117+
engine,
118+
sealer,
119+
errors,
120+
checkpoints: () => engine.find('sys_audit_checkpoint', { context: SYS }) as Promise<Array<Record<string, unknown>>>,
121+
};
122+
}
123+
124+
afterEach(async () => {
125+
for (const kernel of booted.splice(0)) {
126+
await Promise.race([kernel.shutdown(), new Promise<void>((r) => setTimeout(r, 10_000))]);
127+
}
128+
}, 60_000);
129+
130+
const signedBy = (row: Record<string, unknown>, publicKey: string): boolean =>
131+
verify(
132+
null,
133+
signedBodyBytes(checkpointBodyFromRow(row)),
134+
createPublicKey({ key: { kty: 'OKP', crv: 'Ed25519', x: Buffer.from(publicKey, 'base64').toString('base64url') }, format: 'jwk' }),
135+
Buffer.from(String(row.signature), 'base64'),
136+
);
137+
138+
describe('the sealer resolves its host seams in three states (#34280)', () => {
139+
it('no host signer registered: seals with the local key, as before', async () => {
140+
const s = await boot();
141+
expect(await s.sealer.runPass()).toBe(1);
142+
const [row] = await s.checkpoints();
143+
const keys = await s.engine.find('sys_audit_signing_key', { context: SYS });
144+
expect(keys.map((k: Record<string, unknown>) => k.fingerprint)).toEqual([row.signing_key_id]);
145+
expect(s.errors).toEqual([]);
146+
}, 120_000);
147+
148+
it('a registered host signer whose resolution throws: seals nothing, and says so at error naming the slot', async () => {
149+
const s = await boot((k) => k.registerServiceFactory(AUDIT_CHECKPOINT_SIGNER_SERVICE, unbuildable('KMS')));
150+
expect(await s.sealer.runPass()).toBe(0);
151+
expect(await s.checkpoints()).toEqual([]);
152+
// Nothing was signed with the local key either: no local key was ever made.
153+
expect(await s.engine.find('sys_audit_signing_key', { context: SYS })).toEqual([]);
154+
expect(s.errors).toHaveLength(1);
155+
expect(s.errors[0]).toContain(`the '${AUDIT_CHECKPOINT_SIGNER_SERVICE}' service is registered but could not be resolved`);
156+
expect(s.errors[0]).toContain('KMS client cannot start');
157+
expect(s.errors[0]).toContain('does not sign with the local key');
158+
// Reported once while it lasts, not once per pass.
159+
expect(await s.sealer.runPass()).toBe(0);
160+
expect(s.errors).toHaveLength(1);
161+
}, 120_000);
162+
163+
it('a registered host signer that resolves is used — as an instance, and as a factory', async () => {
164+
for (const how of ['instance', 'factory'] as const) {
165+
const host = hostSigner();
166+
const s = await boot((k) => {
167+
if (how === 'instance') k.registerService(AUDIT_CHECKPOINT_SIGNER_SERVICE, host);
168+
else k.registerServiceFactory(AUDIT_CHECKPOINT_SIGNER_SERVICE, () => host);
169+
});
170+
expect(await s.sealer.runPass(), how).toBe(1);
171+
const [row] = await s.checkpoints();
172+
expect(row.signing_key_id, how).toBe(host.keyId);
173+
expect(signedBy(row, host.publicKey), how).toBe(true);
174+
expect(await s.engine.find('sys_audit_signing_key', { context: SYS }), how).toEqual([]);
175+
expect(s.errors, how).toEqual([]);
176+
}
177+
}, 240_000);
178+
179+
it('a registered sink whose resolution throws: seals nothing, and says so; a resolved sink is handed the checkpoint', async () => {
180+
const broken = await boot((k) => k.registerServiceFactory(AUDIT_CHECKPOINT_SINK_SERVICE, unbuildable('SIEM')));
181+
expect(await broken.sealer.runPass()).toBe(0);
182+
expect(await broken.checkpoints()).toEqual([]);
183+
expect(broken.errors).toHaveLength(1);
184+
expect(broken.errors[0]).toContain(`the '${AUDIT_CHECKPOINT_SINK_SERVICE}' service is registered but could not be resolved`);
185+
expect(broken.errors[0]).toContain('does not seal without the off-host export');
186+
187+
const delivered: AuditCheckpointSinkEntry[] = [];
188+
const working = await boot((k) => k.registerServiceFactory(AUDIT_CHECKPOINT_SINK_SERVICE, () => ({
189+
deliver: async (entry: AuditCheckpointSinkEntry) => { delivered.push(entry); },
190+
})));
191+
expect(await working.sealer.runPass()).toBe(1);
192+
expect(delivered.map((e) => e.kind)).toEqual(['checkpoint']);
193+
expect(working.errors).toEqual([]);
194+
}, 240_000);
195+
196+
it('a registered cluster service whose resolution throws: seals nothing, and says so', async () => {
197+
const s = await boot((k) => k.registerServiceFactory('cluster', unbuildable('Redis')));
198+
expect(await s.sealer.runPass()).toBe(0);
199+
expect(await s.checkpoints()).toEqual([]);
200+
expect(s.errors).toHaveLength(1);
201+
expect(s.errors[0]).toContain("the 'cluster' service is registered but could not be resolved");
202+
expect(s.errors[0]).toContain('does not hold the audit.sealer lock in-process only');
203+
}, 120_000);
204+
});

0 commit comments

Comments
 (0)