Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions .github/scripts/verify-trusted-tooling-identity.cjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const { lstatSync, readFileSync } = require("node:fs");

const MAX_JSON_BYTES = 8 * 1024;
const MAX_PARENT_RECEIPT_BYTES = 64 * 1024;
const POSITIVE_INTEGER_PATTERN = /^[1-9][0-9]*$/;
const REPOSITORY_PATTERN = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
const SHA_PATTERN = /^[a-f0-9]{40}$/;
Expand Down Expand Up @@ -94,12 +95,12 @@ function requireMatchingRef(ref, fullRef, name) {
}
}

function parseExactJson(raw, { name, keys, version }) {
function parseExactJson(raw, { name, keys, version, maxBytes = MAX_JSON_BYTES }) {
if (typeof raw !== "string" || !raw.trim()) {
fail(`${name} JSON is required`);
}
if (Buffer.byteLength(raw, "utf8") > MAX_JSON_BYTES) {
fail(`${name} JSON exceeds the 8 KiB limit`);
if (Buffer.byteLength(raw, "utf8") > maxBytes) {
fail(`${name} JSON exceeds the ${maxBytes / 1024} KiB limit`);
}

let value;
Expand Down Expand Up @@ -192,6 +193,7 @@ function parseParentAuthorizationReceipt(raw) {
name: "release parent authorization receipt",
keys: PARENT_RECEIPT_KEYS,
version: 2,
maxBytes: MAX_PARENT_RECEIPT_BYTES,
});
const receipt = {
version: 2,
Expand Down Expand Up @@ -561,10 +563,10 @@ function validateMainLineage(identity, comparison) {
}
}

function readBoundedReceipt(path, name) {
function readBoundedReceipt(path, name, maxBytes = MAX_JSON_BYTES) {
const receiptPath = requireString(path, `${name} path`);
const stat = lstatSync(receiptPath);
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_JSON_BYTES) {
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > maxBytes) {
fail(`${name} file is not a bounded regular file`);
}
return readFileSync(receiptPath, "utf8");
Expand Down Expand Up @@ -666,6 +668,7 @@ async function main() {
rawParentReceipt: readBoundedReceipt(
process.env.PARENT_AUTHORIZATION_RECEIPT_PATH,
"release parent authorization receipt",
MAX_PARENT_RECEIPT_BYTES,
),
rawRecoveryReceipt,
env: process.env,
Expand Down
52 changes: 52 additions & 0 deletions .github/scripts/verify-trusted-tooling-identity.node-test.cjs
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
const assert = require("node:assert/strict");
const test = require("node:test");
const { spawnSync } = require("node:child_process");
const { mkdtempSync, rmSync, writeFileSync } = require("node:fs");
const { tmpdir } = require("node:os");
const { join } = require("node:path");
const {
deriveAuthorizationRoute,
parentArtifactName,
parseParentAuthorizationReceipt,
parseRecoveryApprovalReceipt,
parseTrustedToolingIdentity,
recoveryArtifactName,
validateArtifactResponse,
Expand All @@ -26,6 +31,53 @@ const humanActor = "release-maintainer";
const digest = `sha256:${"d".repeat(64)}`;
const inventoryDigest = "e".repeat(64);

test("accepts a complete 89-package parent authorization inventory", () => {
const packages = Array.from({ length: 89 }, (_, index) => ({
name: `@openclaw/release-plugin-${index}`,
version: "2026.8.2",
inventoryDigest,
}));
const raw = JSON.stringify(parentReceipt(protectedIdentity(), { packages }));
assert.ok(Buffer.byteLength(raw) > 8 * 1024);
assert.deepEqual(parseParentAuthorizationReceipt(raw).packages, packages);
});

test("bounds parent receipts at 64 KiB while identity and recovery stay at 8 KiB", () => {
for (const [parse, value, limit] of [
[parseParentAuthorizationReceipt, parentReceipt(protectedIdentity()), 64 * 1024],
[parseTrustedToolingIdentity, protectedIdentity(), 8 * 1024],
[parseRecoveryApprovalReceipt, recoveryReceipt(protectedIdentity()), 8 * 1024],
]) {
const raw = JSON.stringify(value);
const exact = raw + " ".repeat(limit - Buffer.byteLength(raw));
assert.doesNotThrow(() => parse(exact));
assert.throws(() => parse(`${exact} `), new RegExp(`${limit / 1024} KiB limit`));
}
});

test("applies the parent-only 64 KiB limit before reading receipt files", () => {
const directory = mkdtempSync(join(tmpdir(), "clawhub-receipt-limit-"));
try {
const receiptPath = join(directory, "receipt.json");
for (const [variable, limit] of [
["PARENT_AUTHORIZATION_RECEIPT_PATH", 64 * 1024],
["RECOVERY_APPROVAL_RECEIPT_PATH", 8 * 1024],
]) {
const run = () =>
spawnSync(process.execPath, [require.resolve("./verify-trusted-tooling-identity.cjs")], {
env: { GH_TOKEN: "fixture", [variable]: receiptPath },
encoding: "utf8",
});
writeFileSync(receiptPath, " ".repeat(limit));
assert.doesNotMatch(run().stderr, /not a bounded regular file/);
writeFileSync(receiptPath, " ".repeat(limit + 1));
assert.match(run().stderr, /not a bounded regular file/);
}
} finally {
rmSync(directory, { recursive: true, force: true });
}
});

function protectedIdentity(overrides = {}) {
return {
version: 2,
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@

### Fixes

- GitHub Actions: accept complete release inventories in parent authorization receipts up to the backend's 64 KiB limit while retaining 8 KiB identity and recovery limits.
- API: preserve inspector findings when workspace cleanup fails, report the failing stage, and keep cleanup failures publication-blocking.
- API: bound runtime-identity checks to the owning publisher, reject collisions during personal-principal recovery, and prevent malicious-release quarantine from restoring a historical runtime identity that was administratively replaced.
- Browser tests: use a supported manifest warning fixture and prepare local Convex fully with short scratch paths on the backend's volume before starting authenticated flows.
- API: scope code-plugin runtime identity claims to the owning publisher so community and official packages can retain their manifest ids under distinct scoped names, while rejecting same-owner collisions during publication, transfer, restore, and administrative repair.
- UI proof: supervise isolated loopback backend and browser proof together without writing project dotenv, preserving diagnostics and private-state cleanup on failure.
- CI: authenticate weekly design-audit pull request mutations with the Barnacle GitHub App while retaining the workflow token for branch publication and clean-audit closure.
Expand Down
6 changes: 4 additions & 2 deletions convex/_generated/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,15 +99,16 @@ import type * as lib_httpRouteRateLimit from "../lib/httpRouteRateLimit.js";
import type * as lib_httpUtils from "../lib/httpUtils.js";
import type * as lib_installResolver from "../lib/installResolver.js";
import type * as lib_leaderboards from "../lib/leaderboards.js";
import type * as lib_manualOverrides from "../lib/manualOverrides.js";
import type * as lib_moderation from "../lib/moderation.js";
import type * as lib_moderationEngine from "../lib/moderationEngine.js";
import type * as lib_moderationReasonCodes from "../lib/moderationReasonCodes.js";
import type * as lib_observabilityEvents from "../lib/observabilityEvents.js";
import type * as lib_officialPublishers from "../lib/officialPublishers.js";
import type * as lib_openClawPublishAuthorization from "../lib/openClawPublishAuthorization.js";
import type * as lib_openaiResponse from "../lib/openaiResponse.js";
import type * as lib_packageArtifacts from "../lib/packageArtifacts.js";
import type * as lib_packageRegistry from "../lib/packageRegistry.js";
import type * as lib_packageRuntimeIdentity from "../lib/packageRuntimeIdentity.js";
import type * as lib_packageSearchDigest from "../lib/packageSearchDigest.js";
import type * as lib_packageSecurity from "../lib/packageSecurity.js";
import type * as lib_packageStatEvents from "../lib/packageStatEvents.js";
Expand Down Expand Up @@ -315,15 +316,16 @@ declare const fullApi: ApiFromModules<{
"lib/httpUtils": typeof lib_httpUtils;
"lib/installResolver": typeof lib_installResolver;
"lib/leaderboards": typeof lib_leaderboards;
"lib/manualOverrides": typeof lib_manualOverrides;
"lib/moderation": typeof lib_moderation;
"lib/moderationEngine": typeof lib_moderationEngine;
"lib/moderationReasonCodes": typeof lib_moderationReasonCodes;
"lib/observabilityEvents": typeof lib_observabilityEvents;
"lib/officialPublishers": typeof lib_officialPublishers;
"lib/openClawPublishAuthorization": typeof lib_openClawPublishAuthorization;
"lib/openaiResponse": typeof lib_openaiResponse;
"lib/packageArtifacts": typeof lib_packageArtifacts;
"lib/packageRegistry": typeof lib_packageRegistry;
"lib/packageRuntimeIdentity": typeof lib_packageRuntimeIdentity;
"lib/packageSearchDigest": typeof lib_packageSearchDigest;
"lib/packageSecurity": typeof lib_packageSecurity;
"lib/packageStatEvents": typeof lib_packageStatEvents;
Expand Down
62 changes: 62 additions & 0 deletions convex/lib/packageRuntimeIdentity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { ConvexError } from "convex/values";
import type { Doc, Id } from "../_generated/dataModel";
import type { QueryCtx } from "../_generated/server";
import { getPersonalPublisherForUser } from "./publishers";

export async function assertPackageRuntimeIdAvailable(
ctx: Pick<QueryCtx, "db">,
identity: Pick<Doc<"packages">, "ownerUserId" | "ownerPublisherId" | "runtimeId"> & {
_id?: Id<"packages">;
},
) {
if (!identity.runtimeId) return;
const runtimeId = identity.runtimeId;
const publisher = identity.ownerPublisherId ? await ctx.db.get(identity.ownerPublisherId) : null;
const userId = !identity.ownerPublisherId
? identity.ownerUserId
: publisher?.kind === "user"
? publisher.linkedUserId
: undefined;
const personalPublisher = userId ? await getPersonalPublisherForUser(ctx, userId) : null;
const publisherId = userId
? personalPublisher?.kind === "user"
? personalPublisher._id
: undefined
: identity.ownerPublisherId;
// Personal publishers and legacy user-owned packages share one namespace.
// Query both exact claims; unrelated publishers must not consume this transaction's read budget.
const claims = [];
if (userId) {
claims.push(
ctx.db
.query("packages")
.withIndex("by_ownerUserId_ownerPublisherId_runtimeId_softDeletedAt", (q) =>
q
.eq("ownerUserId", userId)
.eq("ownerPublisherId", undefined)
.eq("runtimeId", runtimeId)
.eq("softDeletedAt", undefined),
),
);
}
if (publisherId) {
claims.push(
ctx.db
.query("packages")
.withIndex("by_ownerPublisherId_runtimeId_softDeletedAt", (q) =>
q
.eq("ownerPublisherId", publisherId)
.eq("runtimeId", runtimeId)
.eq("softDeletedAt", undefined),
),
);
}
for (const claim of claims) {
for await (const candidate of claim) {
if (candidate._id === identity._id) continue;
throw new ConvexError(
`Plugin id "${identity.runtimeId}" is already claimed by another package in this publisher namespace`,
);
}
}
}
106 changes: 106 additions & 0 deletions convex/packageInspectorNode.lifecycle.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/* @vitest-environment node */

import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ActionCtx } from "./_generated/server";
import { runPackageInspectorForPublishInternal } from "./packageInspectorNode";

const mocks = vi.hoisted(() => ({
rm: vi.fn(),
runCheck: vi.fn(),
prepare: vi.fn(),
}));

vi.mock("node:fs/promises", () => ({
mkdir: vi.fn(),
mkdtemp: vi.fn(async () => "/tmp/clawhub-plugin-inspector-test"),
readFile: vi.fn(async () => "{}"),
writeFile: vi.fn(),
rm: mocks.rm,
}));
vi.mock("@openclaw/plugin-inspector", () => ({
openClawTargets: {
resolveVersion: vi.fn(async () => ({ version: "2026.8.1" })),
prepare: mocks.prepare,
},
pluginRoot: { runCheck: mocks.runCheck },
}));

const inspect = () =>
(
runPackageInspectorForPublishInternal as unknown as {
_handler: (
ctx: ActionCtx,
args: { packageName: string; version: string; files: [] },
) => Promise<{
status: string;
summary: { breakageCount: number; issueCount: number; warningCount: number };
breakages: Array<{ code: string; message: string }>;
warnings: Array<{ code: string }>;
}>;
}
)._handler({} as ActionCtx, { packageName: "@example/voice", version: "1.0.0", files: [] });

describe("publish inspector workspace lifecycle", () => {
beforeEach(() => {
vi.resetAllMocks();
mocks.prepare.mockResolvedValue({ status: "ok", version: "2026.8.1" });
mocks.runCheck.mockResolvedValue({ report: { status: "pass" } });
mocks.rm.mockResolvedValue(undefined);
});

it("retains the target preparation failure when workspace cleanup also fails", async () => {
mocks.prepare.mockRejectedValue(
Object.assign(new Error("target disk full"), { code: "ENOSPC" }),
);
mocks.rm.mockRejectedValue(
Object.assign(new Error("workspace still busy"), { code: "ENOTEMPTY" }),
);

const result = await inspect();
expect(result.status).toBe("fail");
expect(result.summary).toMatchObject({ breakageCount: 2, issueCount: 2 });
expect(result.breakages).toEqual([
expect.objectContaining({
code: "plugin-inspector-error",
message: expect.stringContaining("target disk full"),
}),
expect.objectContaining({
code: "plugin-inspector-cleanup-error",
message: expect.stringContaining("workspace still busy"),
}),
]);
expect(mocks.runCheck).not.toHaveBeenCalled();
expect(mocks.rm).toHaveBeenCalledWith("/tmp/clawhub-plugin-inspector-test", {
recursive: true,
force: true,
});
});

it("fails closed when cleanup fails after a passing inspection", async () => {
mocks.rm.mockRejectedValue(new Error("cleanup denied"));

const result = await inspect();
expect(result.status).toBe("fail");
expect(result.summary).toMatchObject({ breakageCount: 1, issueCount: 1 });
expect(result.breakages[0]).toMatchObject({ code: "plugin-inspector-cleanup-error" });
});

it("preserves policy findings and warnings alongside a cleanup error", async () => {
mocks.runCheck.mockResolvedValue({
report: {
breakages: [{ code: "package-entrypoint-missing", message: "entrypoint missing" }],
warnings: [{ code: "manifest-name-missing", message: "name missing" }],
},
});
mocks.rm.mockRejectedValue(new Error("cleanup denied"));

const result = await inspect();
expect(result.status).toBe("fail");
expect(result.summary).toMatchObject({ breakageCount: 2, issueCount: 3, warningCount: 1 });
expect(result.breakages.map((finding) => finding.code)).toEqual([
"package-entrypoint-missing",
"plugin-inspector-cleanup-error",
]);
expect(result.warnings.map((finding) => finding.code)).toEqual(["manifest-name-missing"]);
});
});
Loading
Loading