Skip to content

Commit 9f24896

Browse files
giodl73-repoPatrick-ErichsenGio Della-Libera
authored
Verify signed marketplace feed refresh (#98338)
* feat: verify signed marketplace feed refresh * test: fix signed marketplace feed CI * Guard signed feed refresh trust state * test(feeds): sign decoded hosted feed payloads * fix(feeds): make signed snapshot writes monotonic --------- Co-authored-by: Patrick Erichsen <[email protected]> Co-authored-by: Gio Della-Libera <[email protected]>
1 parent 745b8c3 commit 9f24896

11 files changed

Lines changed: 950 additions & 54 deletions

‎scripts/plugin-sdk-surface-report.mjs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ const defaultPublicDeprecatedExportsByEntrypointBudget = Object.freeze({
105105
"approval-reply-runtime": 1,
106106
"config-runtime": 123,
107107
"config-contracts": 1,
108-
"config-types": 421,
108+
"config-types": 423,
109109
"config-schema": 3,
110110
"reply-dedupe": 1,
111111
"inbound-reply-dispatch": 33,
@@ -205,7 +205,7 @@ export function readPluginSdkSurfaceBudgets(env = process.env) {
205205
),
206206
publicDeprecatedExports: readPluginSdkSurfaceBudgetEnv(
207207
"OPENCLAW_PLUGIN_SDK_MAX_PUBLIC_DEPRECATED_EXPORTS",
208-
3263,
208+
3265,
209209
env,
210210
),
211211
publicWildcardReexports: readPluginSdkSurfaceBudgetEnv(

‎src/plugins/official-external-plugin-catalog-envelope.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,81 @@ describe("official external plugin catalog signed envelopes", () => {
138138
expect(result.ok).toBe(true);
139139
});
140140

141+
it("enforces the configured trusted signature threshold", () => {
142+
const first = signedEnvelope({ keyId: "clawhub-root-a" });
143+
const second = signedEnvelope({ keyId: "clawhub-root-b" });
144+
const firstSignature = first.envelope.signatures?.[0];
145+
const secondSignature = second.envelope.signatures?.[0];
146+
if (!firstSignature || !secondSignature) {
147+
throw new Error("expected signatures");
148+
}
149+
const envelope = {
150+
...first.envelope,
151+
signatures: [firstSignature, secondSignature],
152+
};
153+
154+
expect(
155+
verifyOfficialExternalPluginCatalogSignedEnvelope(envelope, {
156+
trustedKeys: [
157+
{ keyId: "clawhub-root-a", publicKey: first.publicKeyPem },
158+
{ keyId: "clawhub-root-b", publicKey: second.publicKeyPem },
159+
],
160+
threshold: 2,
161+
}),
162+
).toMatchObject({
163+
ok: true,
164+
signedBy: "clawhub-root-a",
165+
signedByKeyIds: ["clawhub-root-a", "clawhub-root-b"],
166+
signatureCount: 2,
167+
threshold: 2,
168+
});
169+
170+
expect(
171+
verifyOfficialExternalPluginCatalogSignedEnvelope(first.envelope, {
172+
trustedKeys: [
173+
{ keyId: "clawhub-root-a", publicKey: first.publicKeyPem },
174+
{ keyId: "clawhub-root-b", publicKey: second.publicKeyPem },
175+
],
176+
threshold: 2,
177+
}),
178+
).toMatchObject({
179+
ok: false,
180+
error: "invalid-signature",
181+
});
182+
});
183+
184+
it("does not count duplicate trust key material toward the signature threshold", () => {
185+
const { envelope, publicKeyPem } = signedEnvelope({ keyId: "clawhub-root-a" });
186+
const firstSignature = envelope.signatures?.[0];
187+
if (!firstSignature) {
188+
throw new Error("expected signature");
189+
}
190+
const result = verifyOfficialExternalPluginCatalogSignedEnvelope(
191+
{
192+
...envelope,
193+
signatures: [
194+
firstSignature,
195+
{
196+
...firstSignature,
197+
keyId: "clawhub-root-b",
198+
},
199+
],
200+
},
201+
{
202+
trustedKeys: [
203+
{ keyId: "clawhub-root-a", publicKey: publicKeyPem },
204+
{ keyId: "clawhub-root-b", publicKey: publicKeyPem },
205+
],
206+
threshold: 2,
207+
},
208+
);
209+
210+
expect(result).toMatchObject({
211+
ok: false,
212+
error: "invalid-signature",
213+
});
214+
});
215+
141216
it("rejects payload bytes changed after signing", () => {
142217
const { envelope, publicKeyPem } = signedEnvelope();
143218
const tamperedFeed = { ...fixtureFeed(), sequence: 43 };

‎src/plugins/official-external-plugin-catalog-envelope.ts‎

Lines changed: 34 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
import { verifyEd25519SignatureBytes } from "../infra/ed25519-signature.js";
1+
import {
2+
normalizeEd25519PublicKeyBase64Url,
3+
verifyEd25519SignatureBytes,
4+
} from "../infra/ed25519-signature.js";
25
import { isRecord } from "../utils.js";
36
import {
47
isOfficialExternalPluginCatalogFeed,
@@ -32,6 +35,9 @@ export type OfficialExternalPluginCatalogEnvelopeVerificationResult =
3235
ok: true;
3336
feed: OfficialExternalPluginCatalogFeed;
3437
signedBy: string;
38+
signedByKeyIds?: readonly string[];
39+
signatureCount?: number;
40+
threshold?: number;
3541
}
3642
| {
3743
ok: false;
@@ -61,6 +67,7 @@ export function verifyOfficialExternalPluginCatalogSignedEnvelope(
6167
raw: unknown,
6268
params: {
6369
trustedKeys: readonly OfficialExternalPluginCatalogTrustedSigningKey[];
70+
threshold?: number;
6471
},
6572
): OfficialExternalPluginCatalogEnvelopeVerificationResult {
6673
const envelope = parseOfficialExternalPluginCatalogSignedEnvelope(raw);
@@ -90,11 +97,17 @@ export function verifyOfficialExternalPluginCatalogSignedEnvelope(
9097
payloadType: envelope.payloadType,
9198
payloadBytes,
9299
});
93-
let trustedSignatureKeyId: string | undefined;
100+
const threshold = Math.max(1, Math.trunc(params.threshold ?? 1));
101+
const trustedSignatureKeyIds: string[] = [];
102+
const trustedSignaturePublicKeys = new Set<string>();
94103
for (const envelopeSignature of envelope.signatures) {
95104
const keyId = envelopeSignature.keyId;
96105
const trustedKey = params.trustedKeys.find((candidate) => candidate.keyId === keyId);
97-
if (!trustedKey) {
106+
if (!trustedKey || trustedSignatureKeyIds.includes(trustedKey.keyId)) {
107+
continue;
108+
}
109+
const normalizedPublicKey = normalizeEd25519PublicKeyBase64Url(trustedKey.publicKey);
110+
if (!normalizedPublicKey || trustedSignaturePublicKeys.has(normalizedPublicKey)) {
98111
continue;
99112
}
100113
if (
@@ -104,11 +117,14 @@ export function verifyOfficialExternalPluginCatalogSignedEnvelope(
104117
signatureBase64Url: envelopeSignature.signature,
105118
})
106119
) {
107-
trustedSignatureKeyId = trustedKey.keyId;
108-
break;
120+
trustedSignatureKeyIds.push(trustedKey.keyId);
121+
trustedSignaturePublicKeys.add(normalizedPublicKey);
122+
if (trustedSignaturePublicKeys.size >= threshold) {
123+
break;
124+
}
109125
}
110126
}
111-
if (trustedSignatureKeyId) {
127+
if (trustedSignaturePublicKeys.size >= threshold) {
112128
const feed = decodeOfficialExternalPluginCatalogEnvelopePayload(payloadBytes);
113129
if (!feed) {
114130
return {
@@ -120,7 +136,14 @@ export function verifyOfficialExternalPluginCatalogSignedEnvelope(
120136
return {
121137
ok: true,
122138
feed,
123-
signedBy: trustedSignatureKeyId,
139+
signedBy: trustedSignatureKeyIds[0] ?? "",
140+
...(threshold > 1
141+
? {
142+
signedByKeyIds: trustedSignatureKeyIds,
143+
signatureCount: trustedSignaturePublicKeys.size,
144+
threshold,
145+
}
146+
: {}),
124147
};
125148
}
126149
const hasKnownKey = envelope.signatures.some((signature) =>
@@ -130,7 +153,10 @@ export function verifyOfficialExternalPluginCatalogSignedEnvelope(
130153
? {
131154
ok: false,
132155
error: "invalid-signature",
133-
message: "hosted catalog signed envelope signature is invalid",
156+
message:
157+
trustedSignatureKeyIds.length > 0
158+
? "hosted catalog signed envelope did not meet the configured signature threshold"
159+
: "hosted catalog signed envelope signature is invalid",
134160
}
135161
: {
136162
ok: false,

‎src/plugins/official-external-plugin-catalog-snapshot-store.ts‎

Lines changed: 141 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@ import { resolveOpenClawStateSqlitePath } from "../state/openclaw-state-db.paths
1515
import type {
1616
HostedOfficialExternalPluginCatalogMetadata,
1717
HostedOfficialExternalPluginCatalogSnapshot,
18+
HostedOfficialExternalPluginCatalogSnapshotMonotonicState,
1819
HostedOfficialExternalPluginCatalogSnapshotStore,
20+
HostedOfficialExternalPluginCatalogTrustState,
1921
} from "./official-external-plugin-catalog.js";
2022

2123
export type HostedOfficialExternalPluginCatalogSnapshotStoreOptions = {
@@ -32,6 +34,11 @@ type HostedCatalogSnapshotRow = {
3234
last_modified: string | null;
3335
checksum: string;
3436
saved_at: string;
37+
trust_mode: string | null;
38+
trust_key_id: string | null;
39+
trust_signature_count: number | bigint | null;
40+
trust_threshold: number | bigint | null;
41+
trust_verified_at: string | null;
3542
};
3643

3744
type HostedCatalogSnapshotDatabase = Pick<
@@ -70,6 +77,90 @@ function resolveStateDatabasePath(
7077
return resolveOpenClawStateSqlitePath(resolveStoreEnv(options) ?? process.env);
7178
}
7279

80+
function rowToTrustState(
81+
row: HostedCatalogSnapshotRow,
82+
): HostedOfficialExternalPluginCatalogTrustState | undefined {
83+
if (
84+
row.trust_mode !== "signed" ||
85+
!row.trust_key_id ||
86+
row.trust_signature_count === null ||
87+
row.trust_threshold === null ||
88+
!row.trust_verified_at
89+
) {
90+
return undefined;
91+
}
92+
return {
93+
mode: "signed",
94+
signedBy: row.trust_key_id,
95+
signatureCount: Number(row.trust_signature_count),
96+
threshold: Number(row.trust_threshold),
97+
verifiedAt: row.trust_verified_at,
98+
};
99+
}
100+
101+
function decodeBase64Payload(payload: string): string {
102+
const normalized = payload.replace(/-/g, "+").replace(/_/g, "/");
103+
return Buffer.from(normalized, "base64").toString("utf8");
104+
}
105+
106+
function readMonotonicStateFromBody(
107+
body: string,
108+
): HostedOfficialExternalPluginCatalogSnapshotMonotonicState | undefined {
109+
try {
110+
const document = JSON.parse(body) as {
111+
payload?: unknown;
112+
sequence?: unknown;
113+
generatedAt?: unknown;
114+
};
115+
const feed =
116+
typeof document.payload === "string"
117+
? (JSON.parse(decodeBase64Payload(document.payload)) as {
118+
sequence?: unknown;
119+
generatedAt?: unknown;
120+
})
121+
: document;
122+
if (typeof feed.sequence !== "number" || typeof feed.generatedAt !== "string") {
123+
return undefined;
124+
}
125+
return {
126+
mode: "signed-feed",
127+
sequence: feed.sequence,
128+
generatedAt: feed.generatedAt,
129+
};
130+
} catch {
131+
return undefined;
132+
}
133+
}
134+
135+
function isMonotonicRollback(params: {
136+
candidate: HostedOfficialExternalPluginCatalogSnapshotMonotonicState;
137+
current: HostedOfficialExternalPluginCatalogSnapshotMonotonicState;
138+
}): boolean {
139+
if (params.candidate.sequence < params.current.sequence) {
140+
return true;
141+
}
142+
if (params.candidate.sequence > params.current.sequence) {
143+
return false;
144+
}
145+
return Date.parse(params.candidate.generatedAt) < Date.parse(params.current.generatedAt);
146+
}
147+
148+
function assertSignedSnapshotWriteIsMonotonic(params: {
149+
candidate: HostedOfficialExternalPluginCatalogSnapshotMonotonicState | undefined;
150+
current: HostedCatalogSnapshotRow | undefined;
151+
}): void {
152+
if (params.candidate?.mode !== "signed-feed" || params.current?.trust_mode !== "signed") {
153+
return;
154+
}
155+
const current = readMonotonicStateFromBody(params.current.body);
156+
if (!current) {
157+
return;
158+
}
159+
if (isMonotonicRollback({ candidate: params.candidate, current })) {
160+
throw new Error("hosted catalog signed feed sequence is older than current snapshot");
161+
}
162+
}
163+
73164
function rowToSnapshot(
74165
row: HostedCatalogSnapshotRow | undefined,
75166
): HostedOfficialExternalPluginCatalogSnapshot | null {
@@ -83,10 +174,12 @@ function rowToSnapshot(
83174
...(row.etag ? { etag: row.etag } : {}),
84175
...(row.last_modified ? { lastModified: row.last_modified } : {}),
85176
};
177+
const trust = rowToTrustState(row);
86178
return {
87179
body: row.body,
88180
metadata,
89181
savedAt: row.saved_at,
182+
...(trust ? { trust } : {}),
90183
};
91184
}
92185

@@ -106,7 +199,20 @@ export function createSqliteHostedOfficialExternalPluginCatalogSnapshotStore(
106199
database.db,
107200
stateDb
108201
.selectFrom("official_external_plugin_catalog_snapshots")
109-
.select(["feed_url", "body", "status", "etag", "last_modified", "checksum", "saved_at"])
202+
.select([
203+
"feed_url",
204+
"body",
205+
"status",
206+
"etag",
207+
"last_modified",
208+
"checksum",
209+
"saved_at",
210+
"trust_mode",
211+
"trust_key_id",
212+
"trust_signature_count",
213+
"trust_threshold",
214+
"trust_verified_at",
215+
])
110216
.where("feed_url", "=", url),
111217
) as HostedCatalogSnapshotRow | undefined;
112218
return rowToSnapshot(row);
@@ -115,6 +221,30 @@ export function createSqliteHostedOfficialExternalPluginCatalogSnapshotStore(
115221
const now = Date.now();
116222
runOpenClawStateWriteTransaction((database) => {
117223
const stateDb = getNodeSqliteKysely<HostedCatalogSnapshotDatabase>(database.db);
224+
const current = executeSqliteQueryTakeFirstSync(
225+
database.db,
226+
stateDb
227+
.selectFrom("official_external_plugin_catalog_snapshots")
228+
.select([
229+
"feed_url",
230+
"body",
231+
"status",
232+
"etag",
233+
"last_modified",
234+
"checksum",
235+
"saved_at",
236+
"trust_mode",
237+
"trust_key_id",
238+
"trust_signature_count",
239+
"trust_threshold",
240+
"trust_verified_at",
241+
])
242+
.where("feed_url", "=", snapshot.metadata.url),
243+
) as HostedCatalogSnapshotRow | undefined;
244+
assertSignedSnapshotWriteIsMonotonic({
245+
candidate: snapshot.monotonic,
246+
current,
247+
});
118248
executeSqliteQuerySync(
119249
database.db,
120250
stateDb
@@ -128,6 +258,11 @@ export function createSqliteHostedOfficialExternalPluginCatalogSnapshotStore(
128258
checksum: snapshot.metadata.checksum,
129259
saved_at: snapshot.savedAt,
130260
updated_at_ms: now,
261+
trust_mode: snapshot.trust?.mode ?? null,
262+
trust_key_id: snapshot.trust?.signedBy ?? null,
263+
trust_signature_count: snapshot.trust?.signatureCount ?? null,
264+
trust_threshold: snapshot.trust?.threshold ?? null,
265+
trust_verified_at: snapshot.trust?.verifiedAt ?? null,
131266
})
132267
.onConflict((conflict) =>
133268
conflict.column("feed_url").doUpdateSet({
@@ -138,6 +273,11 @@ export function createSqliteHostedOfficialExternalPluginCatalogSnapshotStore(
138273
checksum: snapshot.metadata.checksum,
139274
saved_at: snapshot.savedAt,
140275
updated_at_ms: now,
276+
trust_mode: snapshot.trust?.mode ?? null,
277+
trust_key_id: snapshot.trust?.signedBy ?? null,
278+
trust_signature_count: snapshot.trust?.signatureCount ?? null,
279+
trust_threshold: snapshot.trust?.threshold ?? null,
280+
trust_verified_at: snapshot.trust?.verifiedAt ?? null,
141281
}),
142282
),
143283
);

0 commit comments

Comments
 (0)