mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-22 20:29:18 +01:00
feat(mcp) [split 2/8]: add governed access contracts (#9557)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Governed MCP access spans contracts, runtime enforcement, adapters, UI surfaces, and operator verification > - The parity reference PR #9534 is too large for effective automated or human review > - The feature therefore needs a linear stack whose individual diffs stay below the 100-file review limit > - This pull request is split 2/8 and focuses on database schema and shared governance contracts > - The benefit is a standalone, testable review boundary while preserving byte-for-byte parity at the top of the stack ## Linked Issues or Issue Description - Related parity reference: #9534 - Problem: The governed access model needs additive persistence and synchronized shared types before server enforcement can compile. - Proposed solution: Adds migrations 0148–0169, tool-access and Smoke Lab schema, shared types/validators/gallery helpers, and the minimal compile-required contract consumers identified by boundary testing. - Alternatives considered: keeping #9534 as one 403-file review, or rewriting the feature to manufacture seams; both were rejected in favor of path extraction plus compile-driven boundary moves. - Roadmap alignment: this advances the existing governed MCP/tool-access work already represented by #9534; it does not introduce a separate roadmap initiative. - Stack position: base branch is `pap10341-split/01-demo-servers`. - Merge policy: merge bottom-up, in order, only after the complete eight-PR stack has been reviewed and the top-of-stack parity gate remains empty. - Requested review: QA for migrations/validators; Greptile on every PR. ## What Changed - Adds migrations 0148–0169, tool-access and Smoke Lab schema, shared types/validators/gallery helpers, and the minimal compile-required contract consumers identified by boundary testing. - Keeps this PR below 100 changed files and independently typecheckable. - Preserves the final tree from #9534 when combined with the other seven stack levels. ## Verification - `pnpm typecheck` — passed, including migration numbering and safety checks - `pnpm --filter @paperclipai/db test` — passed - `pnpm --filter @paperclipai/shared test` — passed ## Risks - Migration or contract mistakes could affect every upper layer; all migrations are additive/idempotent and compile consumers are included in this boundary. - Stack risk: merging out of order can expose incomplete layers; mitigate by following the documented bottom-up merge policy. - Parity risk: later edits to an intermediate branch can drift from #9534; mitigate by re-running the empty top-of-stack diff before merge. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - OpenAI Codex, exact model ID `gpt-5.4`; runtime-managed context window; medium reasoning with repository, shell, Git, GitHub CLI, and code-execution tools enabled. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] Internal references are omitted except the execution-plan link explicitly required for this coordinated split stack - [x] My branch name describes the change and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge ## Stack Coordination - Internal execution plan: [PAP-13874](/PAP/issues/PAP-13874#document-plan) - Parity reference: #9534 - Stack: #9556 → #9557 → #9558 → #9559 → #9560 → #9561 → #9562 → #9563 - Merge bottom-up only after full-stack review and an empty parity diff at #9563. --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
7b35de65aa
commit
1de0a3bb1e
81 files changed
+7277
-307
No files matched your search
@@ -1,29 +1,213 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdirSync, rmSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { eq } from "drizzle-orm";
|
||||
import {
|
||||
companies,
|
||||
companySecretBindings,
|
||||
companySecretProviderConfigs,
|
||||
companySecrets,
|
||||
companySecretVersions,
|
||||
createDb,
|
||||
plugins,
|
||||
secretAccessEvents,
|
||||
} from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import {
|
||||
createPluginSecretsHandler,
|
||||
PLUGIN_SECRET_REFS_DISABLED_MESSAGE,
|
||||
extractSecretRefBindingsFromConfig,
|
||||
} from "../services/plugin-secrets-handler.js";
|
||||
import { secretService } from "../services/secrets.js";
|
||||
|
||||
describe("createPluginSecretsHandler", () => {
|
||||
it("fails closed for plugin secret resolution until company scoping lands", async () => {
|
||||
const handler = createPluginSecretsHandler({
|
||||
db: {} as never,
|
||||
pluginId: "11111111-1111-4111-8111-111111111111",
|
||||
});
|
||||
const pluginId = "11111111-1111-4111-8111-111111111111";
|
||||
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe.sequential : describe.skip;
|
||||
|
||||
await expect(
|
||||
handler.resolve({ secretRef: "77777777-7777-4777-8777-777777777777" }),
|
||||
).rejects.toThrow(PLUGIN_SECRET_REFS_DISABLED_MESSAGE);
|
||||
if (!embeddedPostgresSupport.supported) {
|
||||
console.warn(
|
||||
`Skipping plugin secret handler integration tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
|
||||
);
|
||||
}
|
||||
|
||||
describe("extractSecretRefBindingsFromConfig", () => {
|
||||
it("ignores UUID strings outside schema-declared secret fields", () => {
|
||||
const externalProjectId = "77777777-7777-4777-8777-777777777777";
|
||||
|
||||
expect(extractSecretRefBindingsFromConfig(
|
||||
{ externalProjectId },
|
||||
{ type: "object", properties: { externalProjectId: { type: "string" } } },
|
||||
)).toEqual([]);
|
||||
});
|
||||
|
||||
it("still rejects malformed secret refs before the feature-disable guard", async () => {
|
||||
const handler = createPluginSecretsHandler({
|
||||
db: {} as never,
|
||||
pluginId: "11111111-1111-4111-8111-111111111111",
|
||||
});
|
||||
it("rejects legacy UUID strings at schema-declared secret fields", () => {
|
||||
const secretId = "77777777-7777-4777-8777-777777777777";
|
||||
|
||||
expect(() => extractSecretRefBindingsFromConfig(
|
||||
{ token: secretId },
|
||||
{ type: "object", properties: { token: { format: "secret-ref" } } },
|
||||
)).toThrow(/must use.*secret_ref/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createPluginSecretsHandler fail-closed guards", () => {
|
||||
it("requires company context before touching the database", async () => {
|
||||
const db = { select: vi.fn(() => { throw new Error("db should not be touched"); }) };
|
||||
const handler = createPluginSecretsHandler({ db: db as never, pluginId });
|
||||
|
||||
await expect(
|
||||
handler.resolve({ secretRef: "not-a-uuid" }),
|
||||
).rejects.toThrow(/invalid secret reference/i);
|
||||
handler.resolve({ secretRef: { type: "secret_ref", secretId: randomUUID() } }),
|
||||
).rejects.toThrow(/companyId is required/i);
|
||||
expect(db.select).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects legacy string refs before provider resolution", async () => {
|
||||
const db = { select: vi.fn(() => { throw new Error("db should not be touched"); }) };
|
||||
const handler = createPluginSecretsHandler({ db: db as never, pluginId });
|
||||
|
||||
await expect(
|
||||
handler.resolve({ companyId: randomUUID(), secretRef: randomUUID() }),
|
||||
).rejects.toThrow(/use \{ type: "secret_ref"/i);
|
||||
expect(db.select).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describeEmbeddedPostgres("createPluginSecretsHandler shared vault integration", () => {
|
||||
let stopDb: (() => Promise<void>) | null = null;
|
||||
let db!: ReturnType<typeof createDb>;
|
||||
const previousKeyFile = process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE;
|
||||
const secretsTmpDir = path.join(os.tmpdir(), `paperclip-plugin-secrets-${randomUUID()}`);
|
||||
|
||||
beforeAll(async () => {
|
||||
mkdirSync(secretsTmpDir, { recursive: true });
|
||||
process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE = path.join(secretsTmpDir, "master.key");
|
||||
const started = await startEmbeddedPostgresTestDatabase("plugin-secrets-handler");
|
||||
stopDb = started.cleanup;
|
||||
db = createDb(started.connectionString);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await db.delete(secretAccessEvents);
|
||||
await db.delete(companySecretBindings);
|
||||
await db.delete(companySecretVersions);
|
||||
await db.delete(companySecrets);
|
||||
await db.delete(companySecretProviderConfigs);
|
||||
await db.delete(plugins);
|
||||
await db.delete(companies);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await stopDb?.();
|
||||
if (previousKeyFile === undefined) {
|
||||
delete process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE;
|
||||
} else {
|
||||
process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE = previousKeyFile;
|
||||
}
|
||||
rmSync(secretsTmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function seedCompany(name: string) {
|
||||
const companyId = randomUUID();
|
||||
await db.insert(companies).values({
|
||||
id: companyId,
|
||||
name,
|
||||
issuePrefix: `P${companyId.slice(0, 7)}`.toUpperCase(),
|
||||
status: "active",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
});
|
||||
return companyId;
|
||||
}
|
||||
|
||||
async function seedPlugin() {
|
||||
await db.insert(plugins).values({
|
||||
id: pluginId,
|
||||
pluginKey: "paperclip.plugin-secrets-test",
|
||||
packageName: "@paperclipai/plugin-secrets-test",
|
||||
version: "0.0.1",
|
||||
apiVersion: 1,
|
||||
categories: ["automation"],
|
||||
manifestJson: {
|
||||
id: "paperclip.plugin-secrets-test",
|
||||
apiVersion: 1,
|
||||
version: "0.0.1",
|
||||
displayName: "Plugin Secrets Test",
|
||||
description: "Test plugin",
|
||||
author: "Paperclip",
|
||||
categories: ["automation"],
|
||||
capabilities: [],
|
||||
entrypoints: { worker: "./dist/worker.js" },
|
||||
},
|
||||
status: "ready",
|
||||
installOrder: 1,
|
||||
});
|
||||
}
|
||||
|
||||
it("resolves bound plugin refs through secretService and emits plugin_worker access events", async () => {
|
||||
await seedPlugin();
|
||||
const companyId = await seedCompany("Plugin Co");
|
||||
const svc = secretService(db);
|
||||
const secret = await svc.create(companyId, {
|
||||
name: `plugin-api-key-${randomUUID()}`,
|
||||
provider: "local_encrypted",
|
||||
value: "resolved-plugin-secret",
|
||||
});
|
||||
await svc.syncSecretRefsForTarget(companyId, { targetType: "plugin", targetId: pluginId }, [
|
||||
{ secretId: secret.id, configPath: "apiKey" },
|
||||
], { replaceAll: true });
|
||||
|
||||
const handler = createPluginSecretsHandler({ db, pluginId });
|
||||
await expect(
|
||||
handler.resolve({
|
||||
companyId,
|
||||
secretRef: { type: "secret_ref", secretId: secret.id, version: "latest" },
|
||||
}),
|
||||
).resolves.toBe("resolved-plugin-secret");
|
||||
|
||||
const events = await db
|
||||
.select()
|
||||
.from(secretAccessEvents)
|
||||
.where(eq(secretAccessEvents.secretId, secret.id));
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]).toMatchObject({
|
||||
companyId,
|
||||
secretId: secret.id,
|
||||
consumerType: "plugin_worker",
|
||||
consumerId: pluginId,
|
||||
configPath: "apiKey",
|
||||
pluginId,
|
||||
outcome: "success",
|
||||
errorCode: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("fails closed for cross-company resolve before secret provider access", async () => {
|
||||
await seedPlugin();
|
||||
const companyA = await seedCompany("A");
|
||||
const companyB = await seedCompany("B");
|
||||
const svc = secretService(db);
|
||||
const foreignSecret = await svc.create(companyB, {
|
||||
name: `foreign-plugin-secret-${randomUUID()}`,
|
||||
provider: "local_encrypted",
|
||||
value: "foreign-value",
|
||||
});
|
||||
await svc.syncSecretRefsForTarget(companyB, { targetType: "plugin", targetId: pluginId }, [
|
||||
{ secretId: foreignSecret.id, configPath: "apiKey" },
|
||||
], { replaceAll: true });
|
||||
|
||||
const handler = createPluginSecretsHandler({ db, pluginId });
|
||||
await expect(
|
||||
handler.resolve({
|
||||
companyId: companyA,
|
||||
secretRef: { type: "secret_ref", secretId: foreignSecret.id, version: "latest" },
|
||||
}),
|
||||
).rejects.toThrow(/not bound/i);
|
||||
|
||||
const events = await db
|
||||
.select()
|
||||
.from(secretAccessEvents)
|
||||
.where(eq(secretAccessEvents.secretId, foreignSecret.id));
|
||||
expect(events).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -34,6 +34,8 @@ import crypto from "node:crypto";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { pluginRegistryService } from "../services/plugin-registry.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { assertCompanyAccess } from "./authz.js";
|
||||
import { badRequest } from "../errors.js";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
@@ -277,11 +279,23 @@ export function pluginUiStaticRoutes(db: Db, options: PluginUiStaticRouteOptions
|
||||
return;
|
||||
}
|
||||
|
||||
// Step 2b: Check for devUiUrl in plugin config — proxy to local dev server
|
||||
// when a plugin author has configured a dev server URL for hot-reload.
|
||||
const rawCompanyId = req.query.companyId;
|
||||
if (
|
||||
Array.isArray(rawCompanyId) ||
|
||||
(rawCompanyId !== undefined && typeof rawCompanyId !== "string")
|
||||
) {
|
||||
throw badRequest('"companyId" must be a string when provided');
|
||||
}
|
||||
const companyId = typeof rawCompanyId === "string" ? rawCompanyId.trim() : "";
|
||||
if (companyId) {
|
||||
assertCompanyAccess(req, companyId);
|
||||
}
|
||||
|
||||
// Step 2b: Check for devUiUrl in company-scoped plugin config — proxy to
|
||||
// local dev server when a plugin author has configured hot-reload.
|
||||
// See PLUGIN_SPEC.md §27.2 — Local Development Workflow
|
||||
try {
|
||||
const configRow = await registry.getConfig(plugin.id);
|
||||
const configRow = companyId ? await registry.getConfig(plugin.id, companyId) : null;
|
||||
const devUiUrl =
|
||||
configRow &&
|
||||
typeof configRow === "object" &&
|
||||
|
||||
@@ -81,8 +81,7 @@ import {
|
||||
setStoredLocalFolder,
|
||||
} from "../services/plugin-local-folders.js";
|
||||
import {
|
||||
extractSecretRefPathsFromConfig,
|
||||
PLUGIN_SECRET_REFS_DISABLED_MESSAGE,
|
||||
extractSecretRefBindingsFromConfig,
|
||||
} from "../services/plugin-secrets-handler.js";
|
||||
import { badRequest, forbidden, notFound, unauthorized, unprocessable } from "../errors.js";
|
||||
|
||||
@@ -2133,6 +2132,11 @@ export function pluginRoutes(
|
||||
router.get("/plugins/:pluginId/config", async (req, res) => {
|
||||
assertBoardOrgAccess(req);
|
||||
const { pluginId } = req.params;
|
||||
const companyId = typeof req.query.companyId === "string" ? req.query.companyId.trim() : "";
|
||||
if (!companyId) {
|
||||
throw badRequest('"companyId" is required and must be a non-empty string');
|
||||
}
|
||||
assertCompanyAccess(req, companyId);
|
||||
|
||||
const plugin = await resolvePlugin(registry, pluginId);
|
||||
if (!plugin) {
|
||||
@@ -2140,7 +2144,7 @@ export function pluginRoutes(
|
||||
return;
|
||||
}
|
||||
|
||||
const config = await registry.getConfig(plugin.id);
|
||||
const config = await registry.getConfig(plugin.id, companyId);
|
||||
res.json(config);
|
||||
});
|
||||
|
||||
@@ -2170,7 +2174,12 @@ export function pluginRoutes(
|
||||
return;
|
||||
}
|
||||
|
||||
const body = req.body as { configJson?: Record<string, unknown> } | undefined;
|
||||
const body = req.body as { companyId?: string; configJson?: Record<string, unknown> } | undefined;
|
||||
const companyId = typeof body?.companyId === "string" ? body.companyId.trim() : "";
|
||||
if (!companyId) {
|
||||
throw badRequest('"companyId" is required and must be a non-empty string');
|
||||
}
|
||||
assertCompanyAccess(req, companyId);
|
||||
if (!body?.configJson || typeof body.configJson !== "object") {
|
||||
res.status(400).json({ error: '"configJson" is required and must be an object' });
|
||||
return;
|
||||
@@ -2201,13 +2210,14 @@ export function pluginRoutes(
|
||||
}
|
||||
|
||||
try {
|
||||
const secretRefsByPath = extractSecretRefPathsFromConfig(body.configJson, schema);
|
||||
if (secretRefsByPath.size > 0) {
|
||||
res.status(422).json({ error: PLUGIN_SECRET_REFS_DISABLED_MESSAGE });
|
||||
const secretRefs = extractSecretRefBindingsFromConfig(body.configJson, schema);
|
||||
if (secretRefs.length > 0) {
|
||||
res.status(422).json({ error: "Plugin secret references require the governed tool-access server layer" });
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await registry.upsertConfig(plugin.id, {
|
||||
const result = await registry.upsertConfig(plugin.id, companyId, {
|
||||
companyId,
|
||||
configJson: body.configJson,
|
||||
});
|
||||
await logPluginMutationActivity(req, "plugin.config.updated", plugin.id, {
|
||||
@@ -2225,7 +2235,7 @@ export function pluginRoutes(
|
||||
await bridgeDeps.workerManager.call(
|
||||
plugin.id,
|
||||
"configChanged",
|
||||
{ config: body.configJson },
|
||||
{ config: body.configJson, companyId },
|
||||
);
|
||||
} catch (rpcErr) {
|
||||
if (
|
||||
|
||||
@@ -205,6 +205,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
|
||||
enableEnvironments: parsed.data.enableEnvironments ?? false,
|
||||
enableIsolatedWorkspaces: parsed.data.enableIsolatedWorkspaces ?? false,
|
||||
enableStreamlinedLeftNavigation: parsed.data.enableStreamlinedLeftNavigation ?? true,
|
||||
enableApps: parsed.data.enableApps ?? false,
|
||||
enablePipelines: parsed.data.enablePipelines ?? false,
|
||||
enableCases: parsed.data.enableCases ?? false,
|
||||
enableConferenceRoomChat: parsed.data.enableConferenceRoomChat ?? false,
|
||||
@@ -213,6 +214,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
|
||||
enableTaskWatchdogs: parsed.data.enableTaskWatchdogs ?? false,
|
||||
enableCloudSync: parsed.data.enableCloudSync ?? false,
|
||||
enableExternalObjects: parsed.data.enableExternalObjects ?? false,
|
||||
enableSmokeLab: parsed.data.enableSmokeLab ?? false,
|
||||
enableBuiltInAgents: parsed.data.enableBuiltInAgents ?? false,
|
||||
enableDecisions: parsed.data.enableDecisions ?? false,
|
||||
enableGoalsSidebarLink: parsed.data.enableGoalsSidebarLink ?? false,
|
||||
@@ -234,6 +236,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
|
||||
enableEnvironments: false,
|
||||
enableIsolatedWorkspaces: false,
|
||||
enableStreamlinedLeftNavigation: true,
|
||||
enableApps: false,
|
||||
enablePipelines: false,
|
||||
enableCases: false,
|
||||
enableConferenceRoomChat: false,
|
||||
@@ -242,6 +245,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
|
||||
enableExperimentalFileViewer: false,
|
||||
enableCloudSync: false,
|
||||
enableExternalObjects: false,
|
||||
enableSmokeLab: false,
|
||||
enableBuiltInAgents: false,
|
||||
enableDecisions: false,
|
||||
enableGoalsSidebarLink: false,
|
||||
|
||||
@@ -1062,8 +1062,10 @@ export function buildHostServices(
|
||||
|
||||
return {
|
||||
config: {
|
||||
async get() {
|
||||
const configRow = await registry.getConfig(pluginId);
|
||||
async get(params) {
|
||||
const companyId = ensureCompanyId(params.companyId);
|
||||
await ensurePluginAvailableForCompany(companyId);
|
||||
const configRow = await registry.getConfig(pluginId, companyId);
|
||||
return configRow?.configJson ?? {};
|
||||
},
|
||||
},
|
||||
@@ -1239,7 +1241,9 @@ export function buildHostServices(
|
||||
|
||||
secrets: {
|
||||
async resolve(params) {
|
||||
return secretsHandler.resolve(params);
|
||||
const companyId = ensureCompanyId(params.companyId);
|
||||
await ensurePluginAvailableForCompany(companyId);
|
||||
return secretsHandler.resolve({ ...params, companyId });
|
||||
},
|
||||
},
|
||||
|
||||
|
||||
@@ -2133,18 +2133,11 @@ export function pluginLoader(
|
||||
const hostHandlers = buildHostHandlers(pluginId, manifest);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 4. Retrieve plugin config (if any)
|
||||
// 4. Bootstrap worker config
|
||||
// ------------------------------------------------------------------
|
||||
let config: Record<string, unknown> = {};
|
||||
try {
|
||||
const configRow = await registry.getConfig(pluginId);
|
||||
if (configRow && typeof configRow === "object" && "configJson" in configRow) {
|
||||
config = (configRow as { configJson: Record<string, unknown> }).configJson ?? {};
|
||||
}
|
||||
} catch {
|
||||
// Config may not exist yet — use empty object
|
||||
log.debug({ pluginId }, "plugin-loader: no config found, using empty config");
|
||||
}
|
||||
// Plugin configuration is company-scoped. Workers receive an empty
|
||||
// bootstrap config and must use ctx.config.get(companyId) at runtime.
|
||||
const config: Record<string, unknown> = {};
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 5. Spawn worker process
|
||||
|
||||
@@ -280,27 +280,27 @@ export function pluginRegistryService(db: Db) {
|
||||
|
||||
// ----- Config ---------------------------------------------------------
|
||||
|
||||
/** Retrieve a plugin's instance configuration. */
|
||||
getConfig: (pluginId: string) =>
|
||||
/** Retrieve a plugin's company-scoped configuration. */
|
||||
getConfig: (pluginId: string, companyId: string) =>
|
||||
db
|
||||
.select()
|
||||
.from(pluginConfig)
|
||||
.where(eq(pluginConfig.pluginId, pluginId))
|
||||
.where(and(eq(pluginConfig.pluginId, pluginId), eq(pluginConfig.companyId, companyId)))
|
||||
.then((rows) => rows[0] ?? null),
|
||||
|
||||
/**
|
||||
* Create or fully replace a plugin's instance configuration.
|
||||
* If a config row already exists for the plugin it is replaced;
|
||||
* Create or fully replace a plugin's company-scoped configuration.
|
||||
* If a config row already exists for the plugin/company pair it is replaced;
|
||||
* otherwise a new row is inserted.
|
||||
*/
|
||||
upsertConfig: async (pluginId: string, input: UpsertPluginConfig) => {
|
||||
upsertConfig: async (pluginId: string, companyId: string, input: UpsertPluginConfig) => {
|
||||
const plugin = await getById(pluginId);
|
||||
if (!plugin) throw notFound("Plugin not found");
|
||||
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(pluginConfig)
|
||||
.where(eq(pluginConfig.pluginId, pluginId))
|
||||
.where(and(eq(pluginConfig.pluginId, pluginId), eq(pluginConfig.companyId, companyId)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
|
||||
if (existing) {
|
||||
@@ -311,7 +311,7 @@ export function pluginRegistryService(db: Db) {
|
||||
lastError: null,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(pluginConfig.pluginId, pluginId))
|
||||
.where(and(eq(pluginConfig.pluginId, pluginId), eq(pluginConfig.companyId, companyId)))
|
||||
.returning()
|
||||
.then((rows) => rows[0]);
|
||||
}
|
||||
@@ -320,6 +320,7 @@ export function pluginRegistryService(db: Db) {
|
||||
.insert(pluginConfig)
|
||||
.values({
|
||||
pluginId,
|
||||
companyId,
|
||||
configJson: input.configJson,
|
||||
})
|
||||
.returning()
|
||||
@@ -327,17 +328,17 @@ export function pluginRegistryService(db: Db) {
|
||||
},
|
||||
|
||||
/**
|
||||
* Partially update a plugin's instance configuration via shallow merge.
|
||||
* Partially update a plugin's company-scoped configuration via shallow merge.
|
||||
* If no config row exists yet one is created with the supplied values.
|
||||
*/
|
||||
patchConfig: async (pluginId: string, input: PatchPluginConfig) => {
|
||||
patchConfig: async (pluginId: string, companyId: string, input: PatchPluginConfig) => {
|
||||
const plugin = await getById(pluginId);
|
||||
if (!plugin) throw notFound("Plugin not found");
|
||||
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(pluginConfig)
|
||||
.where(eq(pluginConfig.pluginId, pluginId))
|
||||
.where(and(eq(pluginConfig.pluginId, pluginId), eq(pluginConfig.companyId, companyId)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
|
||||
if (existing) {
|
||||
@@ -349,7 +350,7 @@ export function pluginRegistryService(db: Db) {
|
||||
lastError: null,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(pluginConfig.pluginId, pluginId))
|
||||
.where(and(eq(pluginConfig.pluginId, pluginId), eq(pluginConfig.companyId, companyId)))
|
||||
.returning()
|
||||
.then((rows) => rows[0]);
|
||||
}
|
||||
@@ -358,6 +359,7 @@ export function pluginRegistryService(db: Db) {
|
||||
.insert(pluginConfig)
|
||||
.values({
|
||||
pluginId,
|
||||
companyId,
|
||||
configJson: input.configJson,
|
||||
})
|
||||
.returning()
|
||||
@@ -368,11 +370,11 @@ export function pluginRegistryService(db: Db) {
|
||||
* Record an error against a plugin's config (e.g. validation failure
|
||||
* against the plugin's instanceConfigSchema).
|
||||
*/
|
||||
setConfigError: async (pluginId: string, lastError: string | null) => {
|
||||
setConfigError: async (pluginId: string, companyId: string, lastError: string | null) => {
|
||||
const rows = await db
|
||||
.update(pluginConfig)
|
||||
.set({ lastError, updatedAt: new Date() })
|
||||
.where(eq(pluginConfig.pluginId, pluginId))
|
||||
.where(and(eq(pluginConfig.pluginId, pluginId), eq(pluginConfig.companyId, companyId)))
|
||||
.returning();
|
||||
|
||||
if (rows.length === 0) throw notFound("Plugin config not found");
|
||||
@@ -380,10 +382,10 @@ export function pluginRegistryService(db: Db) {
|
||||
},
|
||||
|
||||
/** Delete a plugin's config row. */
|
||||
deleteConfig: async (pluginId: string) => {
|
||||
deleteConfig: async (pluginId: string, companyId: string) => {
|
||||
const rows = await db
|
||||
.delete(pluginConfig)
|
||||
.where(eq(pluginConfig.pluginId, pluginId))
|
||||
.where(and(eq(pluginConfig.pluginId, pluginId), eq(pluginConfig.companyId, companyId)))
|
||||
.returning();
|
||||
|
||||
return rows[0] ?? null;
|
||||
|
||||
@@ -1,115 +1,148 @@
|
||||
/**
|
||||
* Plugin secrets host-side handler — resolves secret references through the
|
||||
* Paperclip secret provider system.
|
||||
*
|
||||
* When a plugin worker calls `ctx.secrets.resolve(secretRef)`, the JSON-RPC
|
||||
* request arrives at the host with `{ secretRef }`. This module provides the
|
||||
* concrete `HostServices.secrets` adapter that:
|
||||
*
|
||||
* 1. Parses the `secretRef` string to identify the secret.
|
||||
* 2. Looks up the secret record and its latest version in the database.
|
||||
* 3. Delegates to the configured `SecretProviderModule` to decrypt /
|
||||
* resolve the raw value.
|
||||
* 4. Returns the resolved plaintext value to the worker.
|
||||
*
|
||||
* ## Secret Reference Format
|
||||
*
|
||||
* A `secretRef` is a **secret UUID** — the primary key (`id`) of a row in
|
||||
* the `company_secrets` table. Operators place these UUIDs into plugin
|
||||
* config values; plugin workers resolve them at execution time via
|
||||
* `ctx.secrets.resolve(secretId)`.
|
||||
*
|
||||
* ## Security Invariants
|
||||
*
|
||||
* - Resolved values are **never** logged, persisted, or included in error
|
||||
* messages (per PLUGIN_SPEC.md §22).
|
||||
* - The handler is capability-gated: only plugins with `secrets.read-ref`
|
||||
* declared in their manifest may call it (enforced by `host-client-factory`).
|
||||
* - The host handler itself does not cache resolved values. Each call goes
|
||||
* through the secret provider to honour rotation.
|
||||
*
|
||||
* @see PLUGIN_SPEC.md §22 — Secrets
|
||||
* @see host-client-factory.ts — capability gating
|
||||
* @see services/secrets.ts — secretService used by agent env bindings
|
||||
* Plugin secrets host-side handler. Plugin workers may resolve shared
|
||||
* `secret_ref` config bindings only with an explicit company context.
|
||||
*/
|
||||
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { companySecretBindings } from "@paperclipai/db";
|
||||
import type { EnvSecretRefBinding, SecretProjectionClass, SecretVersionSelector } from "@paperclipai/shared";
|
||||
import { envBindingSecretRefSchema } from "@paperclipai/shared";
|
||||
import {
|
||||
collectSecretRefPaths,
|
||||
isUuidSecretRef,
|
||||
readConfigValueAtPath,
|
||||
} from "./json-schema-secret-refs.js";
|
||||
|
||||
export const PLUGIN_SECRET_REFS_DISABLED_MESSAGE =
|
||||
"Plugin secret references are disabled until company-scoped plugin config lands";
|
||||
import { secretService } from "./secrets.js";
|
||||
import { unprocessable } from "../errors.js";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Error helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function invalidSecretRef(secretRef: string): Error {
|
||||
const err = new Error(`Invalid secret reference: ${secretRef}`);
|
||||
function invalidSecretRef(secretRef: unknown): Error {
|
||||
const rendered = typeof secretRef === "string" ? secretRef : JSON.stringify(secretRef);
|
||||
const err = new Error(
|
||||
`Invalid secret reference for plugin: ${rendered ?? "<empty>"}. Use { type: "secret_ref", secretId, version? }`,
|
||||
);
|
||||
err.name = "InvalidSecretRefError";
|
||||
return err;
|
||||
}
|
||||
|
||||
function requireCompanyId(companyId: unknown): string {
|
||||
if (typeof companyId !== "string" || companyId.trim().length === 0) {
|
||||
throw unprocessable("companyId is required for plugin secret resolution");
|
||||
}
|
||||
return companyId.trim();
|
||||
}
|
||||
|
||||
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function parseSecretRefBinding(value: unknown): EnvSecretRefBinding | null {
|
||||
const parsed = envBindingSecretRefSchema.safeParse(value);
|
||||
return parsed.success ? parsed.data : null;
|
||||
}
|
||||
|
||||
function assertSecretRefBinding(
|
||||
value: unknown,
|
||||
path: string,
|
||||
rejectLegacyUuid = false,
|
||||
): EnvSecretRefBinding | null {
|
||||
if (rejectLegacyUuid && typeof value === "string" && isUuidSecretRef(value)) {
|
||||
throw unprocessable(
|
||||
`Plugin secret ref at ${path} must use { type: "secret_ref", secretId, version? }`,
|
||||
);
|
||||
}
|
||||
if (!isPlainRecord(value) || value.type !== "secret_ref") return null;
|
||||
const parsed = parseSecretRefBinding(value);
|
||||
if (!parsed) {
|
||||
throw unprocessable(`Invalid secret_ref binding at ${path}`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export interface PluginConfigSecretRefBinding {
|
||||
secretId: string;
|
||||
configPath: string;
|
||||
versionSelector?: SecretVersionSelector;
|
||||
required?: boolean;
|
||||
label?: string | null;
|
||||
projectionClass?: SecretProjectionClass;
|
||||
projectionAllowlistKey?: string | null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Validation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Extract secret reference UUIDs from a plugin's configJson, scoped to only
|
||||
* the fields annotated with `format: "secret-ref"` in the schema.
|
||||
*
|
||||
* When no schema is provided, falls back to collecting all UUID-shaped strings
|
||||
* (backwards-compatible for plugins without a declared instanceConfigSchema).
|
||||
*/
|
||||
/** Extract shared object-shaped secret refs from plugin config. */
|
||||
export function extractSecretRefBindingsFromConfig(
|
||||
configJson: unknown,
|
||||
schema?: Record<string, unknown> | null,
|
||||
): PluginConfigSecretRefBinding[] {
|
||||
if (configJson == null || typeof configJson !== "object") return [];
|
||||
|
||||
const refsByPath = new Map<string, PluginConfigSecretRefBinding>();
|
||||
const addRef = (binding: EnvSecretRefBinding, configPath: string) => {
|
||||
refsByPath.set(configPath, {
|
||||
secretId: binding.secretId,
|
||||
configPath,
|
||||
versionSelector: binding.version ?? "latest",
|
||||
required: true,
|
||||
label: configPath,
|
||||
projectionClass: binding.projectionClass,
|
||||
projectionAllowlistKey: binding.projectionAllowlistKey ?? null,
|
||||
});
|
||||
};
|
||||
|
||||
const secretPaths = collectSecretRefPaths(schema);
|
||||
for (const dotPath of secretPaths) {
|
||||
const current = readConfigValueAtPath(configJson as Record<string, unknown>, dotPath);
|
||||
const binding = assertSecretRefBinding(current, dotPath, true);
|
||||
if (binding) addRef(binding, dotPath);
|
||||
}
|
||||
|
||||
function walk(value: unknown, path: string): void {
|
||||
const binding = assertSecretRefBinding(value, path || "$");
|
||||
if (binding) {
|
||||
addRef(binding, path || "$");
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((item, index) => walk(item, path ? `${path}.${index}` : String(index)));
|
||||
return;
|
||||
}
|
||||
if (!isPlainRecord(value)) return;
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
walk(child, path ? `${path}.${key}` : key);
|
||||
}
|
||||
}
|
||||
|
||||
walk(configJson, "");
|
||||
return [...refsByPath.values()];
|
||||
}
|
||||
|
||||
/** Backward-compatible helper returning only secret IDs. */
|
||||
export function extractSecretRefsFromConfig(
|
||||
configJson: unknown,
|
||||
schema?: Record<string, unknown> | null,
|
||||
): Set<string> {
|
||||
return new Set(extractSecretRefPathsFromConfig(configJson, schema).keys());
|
||||
return new Set(extractSecretRefBindingsFromConfig(configJson, schema).map((ref) => ref.secretId));
|
||||
}
|
||||
|
||||
/** Backward-compatible helper returning secret IDs grouped by config path. */
|
||||
export function extractSecretRefPathsFromConfig(
|
||||
configJson: unknown,
|
||||
schema?: Record<string, unknown> | null,
|
||||
): Map<string, Set<string>> {
|
||||
const refs = new Map<string, Set<string>>();
|
||||
const addRef = (secretRef: string, path: string) => {
|
||||
const existing = refs.get(secretRef) ?? new Set<string>();
|
||||
existing.add(path);
|
||||
refs.set(secretRef, existing);
|
||||
};
|
||||
if (configJson == null || typeof configJson !== "object") return new Map();
|
||||
|
||||
const secretPaths = collectSecretRefPaths(schema);
|
||||
|
||||
// If schema declares secret-ref paths, extract only those values.
|
||||
if (secretPaths.size > 0) {
|
||||
for (const dotPath of secretPaths) {
|
||||
const current = readConfigValueAtPath(configJson as Record<string, unknown>, dotPath);
|
||||
if (typeof current === "string" && isUuidSecretRef(current)) {
|
||||
addRef(current, dotPath);
|
||||
}
|
||||
}
|
||||
return refs;
|
||||
for (const ref of extractSecretRefBindingsFromConfig(configJson, schema)) {
|
||||
const paths = refs.get(ref.secretId) ?? new Set<string>();
|
||||
paths.add(ref.configPath);
|
||||
refs.set(ref.secretId, paths);
|
||||
}
|
||||
|
||||
// Fallback: no schema or no secret-ref annotations — collect all UUIDs.
|
||||
// This preserves backwards compatibility for plugins that omit
|
||||
// instanceConfigSchema.
|
||||
function walkAll(value: unknown): void {
|
||||
if (typeof value === "string") {
|
||||
if (isUuidSecretRef(value)) addRef(value, "$");
|
||||
} else if (Array.isArray(value)) {
|
||||
for (const item of value) walkAll(item);
|
||||
} else if (value !== null && typeof value === "object") {
|
||||
for (const v of Object.values(value as Record<string, unknown>)) walkAll(v);
|
||||
}
|
||||
}
|
||||
|
||||
walkAll(configJson);
|
||||
return refs;
|
||||
}
|
||||
|
||||
@@ -117,69 +150,28 @@ export function extractSecretRefPathsFromConfig(
|
||||
// Handler factory
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Input shape for the `secrets.resolve` handler.
|
||||
*
|
||||
* Matches `WorkerToHostMethods["secrets.resolve"][0]` from `protocol.ts`.
|
||||
*/
|
||||
export interface PluginSecretsResolveParams {
|
||||
/** The secret reference string (a secret UUID). */
|
||||
secretRef: string;
|
||||
/** Shared secret reference object from company-scoped plugin config. */
|
||||
secretRef: string | EnvSecretRefBinding;
|
||||
/** Authorized company context for this worker invocation. */
|
||||
companyId?: string;
|
||||
/** Config path that produced this ref. Required when a secret appears in multiple paths. */
|
||||
configPath?: string;
|
||||
actorType?: "agent" | "user" | "system" | "plugin";
|
||||
actorId?: string | null;
|
||||
issueId?: string | null;
|
||||
heartbeatRunId?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for creating the plugin secrets handler.
|
||||
*/
|
||||
export interface PluginSecretsHandlerOptions {
|
||||
/** Database connection. */
|
||||
db: Db;
|
||||
/**
|
||||
* The plugin ID using this handler.
|
||||
* Used for logging context only; never included in error payloads
|
||||
* that reach the plugin worker.
|
||||
*/
|
||||
pluginId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The `HostServices.secrets` adapter for the plugin host-client factory.
|
||||
*/
|
||||
export interface PluginSecretsService {
|
||||
/**
|
||||
* Resolve a secret reference to its current plaintext value.
|
||||
*
|
||||
* @param params - Contains the `secretRef` (UUID of the secret)
|
||||
* @returns The resolved secret value
|
||||
* @throws {Error} If the secret is not found, has no versions, or
|
||||
* the provider fails to resolve
|
||||
*/
|
||||
resolve(params: PluginSecretsResolveParams): Promise<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a `HostServices.secrets` adapter for a specific plugin.
|
||||
*
|
||||
* The returned service looks up secrets by UUID, fetches the latest version
|
||||
* material, and delegates to the appropriate `SecretProviderModule` for
|
||||
* decryption.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const secretsHandler = createPluginSecretsHandler({ db, pluginId });
|
||||
* const handlers = createHostClientHandlers({
|
||||
* pluginId,
|
||||
* capabilities: manifest.capabilities,
|
||||
* services: {
|
||||
* secrets: secretsHandler,
|
||||
* // ...
|
||||
* },
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @param options - Database connection and plugin identity
|
||||
* @returns A `PluginSecretsService` suitable for `HostServices.secrets`
|
||||
*/
|
||||
/** Simple sliding-window rate limiter for secret resolution attempts. */
|
||||
function createRateLimiter(maxAttempts: number, windowMs: number) {
|
||||
const attempts = new Map<string, number[]>();
|
||||
|
||||
@@ -199,40 +191,95 @@ function createRateLimiter(maxAttempts: number, windowMs: number) {
|
||||
export function createPluginSecretsHandler(
|
||||
options: PluginSecretsHandlerOptions,
|
||||
): PluginSecretsService {
|
||||
const { pluginId } = options;
|
||||
|
||||
// Rate limit: max 30 resolution attempts per plugin per minute
|
||||
const { db, pluginId } = options;
|
||||
const rateLimiter = createRateLimiter(30, 60_000);
|
||||
|
||||
async function lookupBinding(input: {
|
||||
companyId: string;
|
||||
secretId: string;
|
||||
versionSelector: SecretVersionSelector;
|
||||
configPath?: string;
|
||||
}) {
|
||||
const conditions = [
|
||||
eq(companySecretBindings.companyId, input.companyId),
|
||||
eq(companySecretBindings.targetType, "plugin"),
|
||||
eq(companySecretBindings.targetId, pluginId),
|
||||
eq(companySecretBindings.secretId, input.secretId),
|
||||
];
|
||||
if (input.configPath) {
|
||||
conditions.push(eq(companySecretBindings.configPath, input.configPath));
|
||||
}
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(companySecretBindings)
|
||||
.where(and(...conditions));
|
||||
const matchingVersion = rows.filter(
|
||||
(row) => row.versionSelector === String(input.versionSelector),
|
||||
);
|
||||
return matchingVersion;
|
||||
}
|
||||
|
||||
return {
|
||||
async resolve(params: PluginSecretsResolveParams): Promise<string> {
|
||||
const { secretRef } = params;
|
||||
if (typeof params.secretRef === "string") {
|
||||
throw invalidSecretRef(params.secretRef.trim() || "<empty>");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------
|
||||
// 0. Rate limiting — prevent brute-force UUID enumeration
|
||||
// ---------------------------------------------------------------
|
||||
if (!rateLimiter.check(pluginId)) {
|
||||
const bindingRef = parseSecretRefBinding(params.secretRef);
|
||||
if (!bindingRef) throw invalidSecretRef(params.secretRef);
|
||||
|
||||
const companyId = requireCompanyId(params.companyId);
|
||||
|
||||
if (!rateLimiter.check(`${companyId}:${pluginId}`)) {
|
||||
const err = new Error("Rate limit exceeded for secret resolution");
|
||||
err.name = "RateLimitExceededError";
|
||||
throw err;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------
|
||||
// 1. Validate the ref format
|
||||
// ---------------------------------------------------------------
|
||||
if (!secretRef || typeof secretRef !== "string" || secretRef.trim().length === 0) {
|
||||
throw invalidSecretRef(secretRef ?? "<empty>");
|
||||
const versionSelector = bindingRef.version ?? "latest";
|
||||
const bindings = await lookupBinding({
|
||||
companyId,
|
||||
secretId: bindingRef.secretId,
|
||||
versionSelector,
|
||||
configPath: params.configPath,
|
||||
});
|
||||
|
||||
if (bindings.length === 0) {
|
||||
throw unprocessable(
|
||||
`Secret is not bound to plugin:${pluginId}${params.configPath ? ` at ${params.configPath}` : ""}`,
|
||||
{ code: "binding_missing" },
|
||||
);
|
||||
}
|
||||
if (bindings.length > 1) {
|
||||
throw unprocessable(
|
||||
"Plugin secret reference is ambiguous; pass configPath when resolving this secret",
|
||||
{ code: "binding_ambiguous" },
|
||||
);
|
||||
}
|
||||
|
||||
const trimmedRef = secretRef.trim();
|
||||
|
||||
if (!isUuidSecretRef(trimmedRef)) {
|
||||
throw invalidSecretRef(trimmedRef);
|
||||
}
|
||||
|
||||
// Fail closed until plugin config and worker runtime both carry an
|
||||
// explicit company scope for secret bindings and resolution.
|
||||
throw new Error(PLUGIN_SECRET_REFS_DISABLED_MESSAGE);
|
||||
const binding = bindings[0]!;
|
||||
return secretService(db).resolveSecretValue(companyId, bindingRef.secretId, versionSelector, {
|
||||
bindingContext: {
|
||||
consumerType: "plugin",
|
||||
consumerId: pluginId,
|
||||
configPath: binding.configPath,
|
||||
actorType: params.actorType ?? "plugin",
|
||||
actorId: params.actorId ?? pluginId,
|
||||
issueId: params.issueId ?? null,
|
||||
heartbeatRunId: params.heartbeatRunId ?? null,
|
||||
pluginId,
|
||||
},
|
||||
accessContext: {
|
||||
consumerType: "plugin_worker",
|
||||
consumerId: pluginId,
|
||||
configPath: binding.configPath,
|
||||
actorType: params.actorType ?? "plugin",
|
||||
actorId: params.actorId ?? pluginId,
|
||||
issueId: params.issueId ?? null,
|
||||
heartbeatRunId: params.heartbeatRunId ?? null,
|
||||
pluginId,
|
||||
},
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
+146
-15
@@ -26,6 +26,7 @@ import type {
|
||||
RemoteSecretImportRowResult,
|
||||
SecretProviderConfigDiscoveryPreviewResult,
|
||||
SecretBindingTargetType,
|
||||
SecretProjectionClass,
|
||||
SecretProvider,
|
||||
SecretProviderConfigHealthResponse,
|
||||
SecretProviderConfigHealthStatus,
|
||||
@@ -33,6 +34,7 @@ import type {
|
||||
SecretVersionSelector,
|
||||
} from "@paperclipai/shared";
|
||||
import {
|
||||
CLASS3_STATIC_LEASE_ALLOWLIST,
|
||||
createSecretProviderConfigSchema,
|
||||
deriveProjectUrlKey,
|
||||
envBindingSchema,
|
||||
@@ -377,7 +379,13 @@ async function cleanupPreparedProviderWrite(input: {
|
||||
|
||||
type CanonicalEnvBinding =
|
||||
| { type: "plain"; value: string }
|
||||
| { type: "secret_ref"; secretId: string; version: number | "latest" }
|
||||
| {
|
||||
type: "secret_ref";
|
||||
secretId: string;
|
||||
version: number | "latest";
|
||||
projectionClass: SecretProjectionClass;
|
||||
projectionAllowlistKey: string | null;
|
||||
}
|
||||
| {
|
||||
type: "user_secret_ref";
|
||||
key: string;
|
||||
@@ -386,8 +394,10 @@ type CanonicalEnvBinding =
|
||||
allowMissingOverride: boolean;
|
||||
};
|
||||
|
||||
type SecretAccessConsumerType = SecretBindingTargetType | "plugin_worker";
|
||||
|
||||
type SecretConsumerContext = {
|
||||
consumerType: SecretBindingTargetType;
|
||||
consumerType: SecretAccessConsumerType;
|
||||
consumerId: string;
|
||||
configPath?: string | null;
|
||||
responsibleUserId?: string | null;
|
||||
@@ -400,8 +410,12 @@ type SecretConsumerContext = {
|
||||
allowedBindingIds?: string[] | null;
|
||||
};
|
||||
|
||||
type SecretBindingContext = Omit<SecretConsumerContext, "consumerType"> & {
|
||||
consumerType: SecretBindingTargetType;
|
||||
};
|
||||
|
||||
type SecretResolutionOptions = {
|
||||
bindingContext?: SecretConsumerContext;
|
||||
bindingContext?: SecretBindingContext;
|
||||
accessContext?: SecretConsumerContext;
|
||||
allowUserSecretScope?: boolean;
|
||||
};
|
||||
@@ -439,6 +453,10 @@ export type MissingRuntimeBinding = {
|
||||
errorCode?: SecretResolutionErrorCode;
|
||||
};
|
||||
|
||||
function missingRuntimeConsumerType(consumerType: SecretAccessConsumerType): SecretBindingTargetType {
|
||||
return consumerType === "plugin_worker" ? "plugin" : consumerType;
|
||||
}
|
||||
|
||||
type RuntimeSecretResolution = {
|
||||
value: string;
|
||||
manifestEntry: RuntimeSecretManifestEntry;
|
||||
@@ -502,9 +520,41 @@ function canonicalizeBinding(binding: EnvBinding): CanonicalEnvBinding {
|
||||
type: "secret_ref",
|
||||
secretId: binding.secretId,
|
||||
version: binding.version ?? "latest",
|
||||
projectionClass: binding.projectionClass ?? "unclassified",
|
||||
projectionAllowlistKey: binding.projectionAllowlistKey ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function assertClass3StaticLeaseAllowed(input: {
|
||||
targetType: SecretBindingTargetType;
|
||||
configPath: string;
|
||||
projectionClass?: string | null;
|
||||
projectionAllowlistKey?: string | null;
|
||||
}) {
|
||||
const projectionClass = input.projectionClass ?? "unclassified";
|
||||
if (projectionClass !== "class_3_static_lease") return;
|
||||
if (!input.projectionAllowlistKey?.trim()) {
|
||||
throw unprocessable("Class-3 static lease bindings require an allowlist key", {
|
||||
code: "class_3_static_lease_allowlist_required",
|
||||
targetType: input.targetType,
|
||||
configPath: input.configPath,
|
||||
});
|
||||
}
|
||||
const allowed = CLASS3_STATIC_LEASE_ALLOWLIST.some((entry) =>
|
||||
entry.key === input.projectionAllowlistKey
|
||||
&& entry.targetType === input.targetType
|
||||
&& entry.configPath === input.configPath
|
||||
);
|
||||
if (!allowed) {
|
||||
throw unprocessable("Class-3 static lease binding is outside the approved allowlist", {
|
||||
code: "class_3_static_lease_not_allowed",
|
||||
allowlistKey: input.projectionAllowlistKey,
|
||||
targetType: input.targetType,
|
||||
configPath: input.configPath,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function defaultProviderConfigStatus(provider: SecretProvider): SecretProviderConfigStatus {
|
||||
return COMING_SOON_SECRET_PROVIDERS.has(provider) ? "coming_soon" : "ready";
|
||||
}
|
||||
@@ -556,7 +606,7 @@ function missingUserSecretDefinitionRuntimeBinding(
|
||||
errorCode: "user_secret_definition_missing" | "user_secret_definition_inactive",
|
||||
): MissingRuntimeBinding {
|
||||
return {
|
||||
consumerType: context.consumerType,
|
||||
consumerType: missingRuntimeConsumerType(context.consumerType),
|
||||
consumerId: context.consumerId,
|
||||
configPath: entry.configPath,
|
||||
envKey: entry.key,
|
||||
@@ -737,7 +787,7 @@ export function secretService(db: Db) {
|
||||
async function assertBindingContext(
|
||||
companyId: string,
|
||||
secretId: string,
|
||||
context: SecretConsumerContext | undefined,
|
||||
context: SecretBindingContext | undefined,
|
||||
) {
|
||||
if (!context) return null;
|
||||
if (!context.configPath) {
|
||||
@@ -765,6 +815,12 @@ export function secretService(db: Db) {
|
||||
{ code: "binding_not_allowed" },
|
||||
);
|
||||
}
|
||||
assertClass3StaticLeaseAllowed({
|
||||
targetType: binding.targetType as SecretBindingTargetType,
|
||||
configPath: binding.configPath,
|
||||
projectionClass: binding.projectionClass,
|
||||
projectionAllowlistKey: binding.projectionAllowlistKey,
|
||||
});
|
||||
return binding;
|
||||
}
|
||||
|
||||
@@ -1053,16 +1109,22 @@ export function secretService(db: Db) {
|
||||
}
|
||||
}
|
||||
|
||||
function isSecretResolutionOptions(
|
||||
value: SecretBindingContext | SecretResolutionOptions | undefined,
|
||||
): value is SecretResolutionOptions {
|
||||
return Boolean(value && ("bindingContext" in value || "accessContext" in value));
|
||||
}
|
||||
|
||||
async function resolveSecretValue(
|
||||
companyId: string,
|
||||
secretId: string,
|
||||
version: number | "latest",
|
||||
context?: SecretConsumerContext,
|
||||
contextOrOptions?: SecretBindingContext | SecretResolutionOptions,
|
||||
): Promise<string> {
|
||||
return (await resolveSecretValueInternal(companyId, secretId, version, {
|
||||
bindingContext: context,
|
||||
accessContext: context,
|
||||
})).value;
|
||||
const options = isSecretResolutionOptions(contextOrOptions)
|
||||
? contextOrOptions
|
||||
: { bindingContext: contextOrOptions, accessContext: contextOrOptions };
|
||||
return (await resolveSecretValueInternal(companyId, secretId, version, options)).value;
|
||||
}
|
||||
|
||||
async function resolveSecretValueForEphemeralAccess(
|
||||
@@ -1112,6 +1174,31 @@ export function secretService(db: Db) {
|
||||
})).value;
|
||||
}
|
||||
|
||||
async function resolveSecretVersion(
|
||||
companyId: string,
|
||||
secretId: string,
|
||||
version: number | "latest",
|
||||
context?: SecretBindingContext,
|
||||
): Promise<number> {
|
||||
const secret = await getById(secretId);
|
||||
if (!secret) throw notFound("Secret not found");
|
||||
if (secret.companyId !== companyId) throw unprocessable("Secret must belong to same company");
|
||||
const resolvedVersion = version === "latest" ? secret.latestVersion : version;
|
||||
if (secret.status === "deleted") {
|
||||
throw new HttpError(404, "Secret not found", { code: "secret_deleted" });
|
||||
}
|
||||
if (secret.status !== "active") {
|
||||
throw unprocessable("Secret is not active", { code: "secret_inactive" });
|
||||
}
|
||||
await assertBindingContext(companyId, secret.id, context);
|
||||
const versionRow = await getSecretVersion(secret.id, resolvedVersion);
|
||||
if (!versionRow) throw new HttpError(404, "Secret version not found", { code: "version_missing" });
|
||||
if (versionRow.status === "disabled" || versionRow.status === "destroyed" || versionRow.revokedAt) {
|
||||
throw unprocessable("Secret version is not active", { code: "version_inactive" });
|
||||
}
|
||||
return resolvedVersion;
|
||||
}
|
||||
|
||||
async function normalizeEnvConfig(
|
||||
companyId: string,
|
||||
envValue: unknown,
|
||||
@@ -1154,6 +1241,8 @@ export function secretService(db: Db) {
|
||||
type: "secret_ref",
|
||||
secretId: binding.secretId,
|
||||
version: binding.version,
|
||||
projectionClass: binding.projectionClass,
|
||||
projectionAllowlistKey: binding.projectionAllowlistKey,
|
||||
};
|
||||
}
|
||||
return normalized;
|
||||
@@ -1226,6 +1315,8 @@ export function secretService(db: Db) {
|
||||
type: "secret_ref",
|
||||
secretId: binding.secretId,
|
||||
version: binding.version,
|
||||
projectionClass: binding.projectionClass,
|
||||
projectionAllowlistKey: binding.projectionAllowlistKey,
|
||||
};
|
||||
}
|
||||
if (binding.type === "user_secret_ref") {
|
||||
@@ -2928,6 +3019,7 @@ export function secretService(db: Db) {
|
||||
getById,
|
||||
getByName,
|
||||
resolveSecretValue,
|
||||
resolveSecretVersion,
|
||||
resolveSecretValueForEphemeralAccess,
|
||||
|
||||
create: async (
|
||||
@@ -3402,8 +3494,16 @@ export function secretService(db: Db) {
|
||||
versionSelector?: SecretVersionSelector;
|
||||
required?: boolean;
|
||||
label?: string | null;
|
||||
projectionClass?: SecretProjectionClass;
|
||||
projectionAllowlistKey?: string | null;
|
||||
}) => {
|
||||
await assertSecretInCompany(input.companyId, input.secretId);
|
||||
assertClass3StaticLeaseAllowed({
|
||||
targetType: input.targetType,
|
||||
configPath: input.configPath,
|
||||
projectionClass: input.projectionClass,
|
||||
projectionAllowlistKey: input.projectionAllowlistKey,
|
||||
});
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(companySecretBindings)
|
||||
@@ -3428,6 +3528,8 @@ export function secretService(db: Db) {
|
||||
versionSelector: String(input.versionSelector ?? "latest"),
|
||||
required: input.required ?? true,
|
||||
label: input.label ?? null,
|
||||
projectionClass: input.projectionClass ?? "unclassified",
|
||||
projectionAllowlistKey: input.projectionAllowlistKey ?? null,
|
||||
})
|
||||
.returning()
|
||||
.then((rows) => rows[0]);
|
||||
@@ -3442,6 +3544,8 @@ export function secretService(db: Db) {
|
||||
versionSelector?: SecretVersionSelector;
|
||||
required?: boolean;
|
||||
label?: string | null;
|
||||
projectionClass?: SecretProjectionClass;
|
||||
projectionAllowlistKey?: string | null;
|
||||
}>,
|
||||
options?: { replaceAll?: boolean },
|
||||
) => {
|
||||
@@ -3451,15 +3555,27 @@ export function secretService(db: Db) {
|
||||
versionSelector: SecretVersionSelector;
|
||||
required: boolean;
|
||||
label: string | null;
|
||||
projectionClass: SecretProjectionClass;
|
||||
projectionAllowlistKey: string | null;
|
||||
}> = [];
|
||||
for (const ref of refs) {
|
||||
await assertSecretInCompany(companyId, ref.secretId);
|
||||
const projectionClass = ref.projectionClass ?? "unclassified";
|
||||
const projectionAllowlistKey = ref.projectionAllowlistKey ?? null;
|
||||
assertClass3StaticLeaseAllowed({
|
||||
targetType: target.targetType,
|
||||
configPath: ref.configPath,
|
||||
projectionClass,
|
||||
projectionAllowlistKey,
|
||||
});
|
||||
normalizedRefs.push({
|
||||
secretId: ref.secretId,
|
||||
configPath: ref.configPath,
|
||||
versionSelector: ref.versionSelector ?? "latest",
|
||||
required: ref.required ?? true,
|
||||
label: ref.label ?? null,
|
||||
projectionClass,
|
||||
projectionAllowlistKey,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3514,6 +3630,8 @@ export function secretService(db: Db) {
|
||||
versionSelector: String(ref.versionSelector),
|
||||
required: ref.required,
|
||||
label: ref.label,
|
||||
projectionClass: ref.projectionClass,
|
||||
projectionAllowlistKey: ref.projectionAllowlistKey,
|
||||
})),
|
||||
);
|
||||
});
|
||||
@@ -3545,6 +3663,8 @@ export function secretService(db: Db) {
|
||||
secretId: string;
|
||||
configPath: string;
|
||||
versionSelector: SecretVersionSelector;
|
||||
projectionClass: SecretProjectionClass;
|
||||
projectionAllowlistKey: string | null;
|
||||
}> = [];
|
||||
const userRefs: Array<{
|
||||
definitionKey: string;
|
||||
@@ -3574,10 +3694,19 @@ export function secretService(db: Db) {
|
||||
}
|
||||
if (binding.type !== "secret_ref") continue;
|
||||
await assertSecretInCompany(companyId, binding.secretId, bindingDb);
|
||||
const configPath = `${pathPrefix}.${key}`;
|
||||
assertClass3StaticLeaseAllowed({
|
||||
targetType: target.targetType,
|
||||
configPath,
|
||||
projectionClass: binding.projectionClass,
|
||||
projectionAllowlistKey: binding.projectionAllowlistKey,
|
||||
});
|
||||
refs.push({
|
||||
secretId: binding.secretId,
|
||||
configPath: `${pathPrefix}.${key}`,
|
||||
configPath,
|
||||
versionSelector: binding.version,
|
||||
projectionClass: binding.projectionClass,
|
||||
projectionAllowlistKey: binding.projectionAllowlistKey,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3602,6 +3731,8 @@ export function secretService(db: Db) {
|
||||
configPath: ref.configPath,
|
||||
versionSelector: String(ref.versionSelector),
|
||||
required: true,
|
||||
projectionClass: ref.projectionClass,
|
||||
projectionAllowlistKey: ref.projectionAllowlistKey,
|
||||
})),
|
||||
);
|
||||
};
|
||||
@@ -3684,7 +3815,7 @@ export function secretService(db: Db) {
|
||||
resolveEnvBindings: async (
|
||||
companyId: string,
|
||||
envValue: unknown,
|
||||
context?: Omit<SecretConsumerContext, "configPath">,
|
||||
context?: Omit<SecretBindingContext, "configPath">,
|
||||
): Promise<{ env: Record<string, string>; secretKeys: Set<string>; manifest: RuntimeSecretManifestEntry[] }> => {
|
||||
const record = asRecord(envValue);
|
||||
if (!record) return { env: {} as Record<string, string>, secretKeys: new Set<string>(), manifest: [] };
|
||||
@@ -3752,7 +3883,7 @@ export function secretService(db: Db) {
|
||||
collectMissingRuntimeBindings: async (
|
||||
companyId: string,
|
||||
envValue: unknown,
|
||||
context: Omit<SecretConsumerContext, "configPath">,
|
||||
context: Omit<SecretBindingContext, "configPath">,
|
||||
): Promise<MissingRuntimeBinding[]> => {
|
||||
const record = asRecord(envValue);
|
||||
if (!record) return [];
|
||||
@@ -3912,7 +4043,7 @@ export function secretService(db: Db) {
|
||||
companyId: string,
|
||||
adapterConfig: Record<string, unknown>,
|
||||
adapterType: string | null | undefined,
|
||||
context: Omit<SecretConsumerContext, "configPath">,
|
||||
context: Omit<SecretBindingContext, "configPath">,
|
||||
): Promise<MissingRuntimeBinding[]> => {
|
||||
const secretFieldKeys = await listAdapterSchemaSecretFieldKeys(adapterType);
|
||||
const secretRefs = secretFieldKeys.flatMap((key) => {
|
||||
@@ -4068,7 +4199,7 @@ export function secretService(db: Db) {
|
||||
resolveAdapterConfigForRuntime: async (
|
||||
companyId: string,
|
||||
adapterConfig: Record<string, unknown>,
|
||||
context?: Omit<SecretConsumerContext, "configPath">,
|
||||
context?: Omit<SecretBindingContext, "configPath">,
|
||||
opts?: ResolveAdapterConfigForRuntimeOptions,
|
||||
): Promise<{ config: Record<string, unknown>; secretKeys: Set<string>; manifest: RuntimeSecretManifestEntry[] }> => {
|
||||
const resolved = { ...adapterConfig };
|
||||
|
||||
Reference in new issue
Block a user