mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-08 01:57:31 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agent runs often need provider credentials, API tokens, and other environment-bound secrets. > - Company-level secrets work for shared credentials, but they do not model values that should differ by human operator. > - Without a user-scoped model, a run can dispatch without knowing whether the responsible human has supplied the needed value. > - Paperclip also needs run attribution to make those user-scoped runtime checks deterministic and auditable. > - This pull request adds user-specific secret definitions, per-user values, environment bindings, responsible-user attribution, and runtime resolution gates. > - The benefit is that teams can define the secret once, let each user provide their own value, and block runs before dispatch when required user secrets or active definitions are unavailable. ## Linked Issues or Issue Description Refs #224 Refs #6057 This PR implements user-specific secret support as a core secret-management capability rather than a one-off adapter setting. It is related to existing public work on company secrets UI and runtime secret refs, but is distinct because the value is owned by the responsible user and resolved at run dispatch time. Related PR search before opening found existing secrets work such as #1550, #8256, #8614, #8634, and #8647; none of those add the full user-secret definition/value/runtime gate covered here. ## What Changed - Added user-secret definitions and per-user "My secrets" values, keeping stored values out of access metadata. - Added `user_secret_ref` environment bindings and UI affordances to pick them alongside existing secret refs. - Added responsible-user runtime resolution so user-secret refs resolve against the human responsible for the run. - Added pre-dispatch missing-secret gates so runs fail before adapter dispatch when required user values are absent or definitions are inactive. - Added low-trust allowlist hardening for user-secret runtime access. - Added issue, routine, run, and agent API key responsible-user attribution and fail-closed dispatch behavior when attribution cannot be resolved. - Added denial-copy mapping so responsible-user authorization failures surface as actionable run outcomes instead of opaque setup failures. - Added OpenAPI documentation for the user-secret routes. - Rebases cleanly on current `master`; migrations were renumbered incrementally as `0128_user_specific_secrets`, `0129_agent_api_key_responsible_user`, and `0130_run_responsible_user_invariant` after upstream `0126`/`0127` migrations. - Removed previously committed local design screenshots so the PR contains code/docs/tests only. ## Verification - PASS: PR head `2527febd106bcf3ca264ca0da7fca491084192d6` is based on `paperclipai/paperclip:master`. - PASS: `git diff --check` - PASS: `git diff --name-only public/master...HEAD | rg '^(pnpm-lock\\.yaml|\\.github/workflows/|screenshots/)' || true` produced no files. - PASS: migration journal audit confirmed unique indexes through `130` with tail entries `0126_issue_comment_derived_attribution`, `0127_environment_custom_images_instance_scoped`, `0128_user_specific_secrets`, `0129_agent_api_key_responsible_user`, and `0130_run_responsible_user_invariant`. - PASS: `pnpm --filter @paperclipai/ui typecheck` - PASS: `pnpm --filter @paperclipai/server typecheck` - PASS: `pnpm --filter @paperclipai/server exec vitest run src/__tests__/heartbeat-responsible-user-invariant.test.ts` - PASS: `pnpm --filter @paperclipai/server exec vitest run src/__tests__/heartbeat-active-run-output-watchdog.test.ts src/__tests__/heartbeat-stale-queue-invalidation.test.ts src/__tests__/heartbeat-workspace-finalize-branch.test.ts src/__tests__/issue-monitor-scheduler.test.ts` - PASS: `pnpm --filter @paperclipai/server exec vitest run src/__tests__/heartbeat-comment-wake-batching.test.ts src/__tests__/heartbeat-retry-scheduling.test.ts src/__tests__/heartbeat-accepted-plan-workspace-refresh.test.ts src/__tests__/heartbeat-plugin-environment.test.ts` - PASS: `pnpm --filter @paperclipai/server exec vitest run src/__tests__/low-trust-red-team-routes.test.ts` - PASS: `pnpm --filter @paperclipai/server exec vitest run src/__tests__/secrets-service.test.ts` (55 tests) - PASS: `pnpm vitest run server/src/__tests__/secrets-routes.test.ts server/src/__tests__/secrets-service.test.ts` (89 tests after final Greptile cleanup fixes) - PASS: `pnpm --filter @paperclipai/server exec vitest run src/__tests__/heartbeat-issue-liveness-escalation.test.ts` (17 tests after the final rebase CI fix) - PASS: focused server Vitest batches covering heartbeat recovery, project env, plugin env, routines, low-trust, pipelines, monitors, watchdog, and stale queue paths. - PASS: GitHub checks are green on `2527febd106bcf3ca264ca0da7fca491084192d6`, including Typecheck + Release Registry, Build, General tests, serialized server suites, e2e, Canary Dry Run, verify, security checks, and Greptile Review. - PASS: Greptile Review completed successfully on `2527febd106bcf3ca264ca0da7fca491084192d6` with Confidence Score 5/5, and GraphQL review-thread audit returned zero unresolved non-outdated threads. ## Risks - Runtime behavior now depends on a run having a correct responsible user; missing or incorrect responsibility assignment can block runs before adapter dispatch. - `user_secret_ref` bindings intentionally expose metadata without values, but UI/API callers may need to handle the new binding kind explicitly. - External secret providers and IAM policies are not automatically provisioned by this PR; operators still need to configure provider-side access for non-local vaults. - The PR is broad across db/shared/server/UI/runtime paths, so release validation should include both API and UI secret workflows before merge. - The migration renumbering is intentionally incremental after upstream migrations; the branch migrations use guarded column/table/index/constraint creation so users who tested the older draft numbering should not hit duplicate DDL for the existing objects. > 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, GPT-5-based coding agent (`gpt-5`), Codex local adapter with shell/tool use and code execution. Context window and internal reasoning mode are not exposed by the runtime. ## 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] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
826 lines
28 KiB
TypeScript
826 lines
28 KiB
TypeScript
import express from "express";
|
|
import request from "supertest";
|
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { secretRoutes } from "../routes/secrets.js";
|
|
import { errorHandler } from "../middleware/error-handler.js";
|
|
import { HttpError, unprocessable } from "../errors.js";
|
|
|
|
const mockSecretService = vi.hoisted(() => ({
|
|
listProviders: vi.fn(),
|
|
checkProviders: vi.fn(),
|
|
listProviderConfigs: vi.fn(),
|
|
previewProviderConfigDiscovery: vi.fn(),
|
|
getProviderConfigById: vi.fn(),
|
|
createProviderConfig: vi.fn(),
|
|
updateProviderConfig: vi.fn(),
|
|
disableProviderConfig: vi.fn(),
|
|
removeProviderConfig: vi.fn(),
|
|
setDefaultProviderConfig: vi.fn(),
|
|
checkProviderConfigHealth: vi.fn(),
|
|
getById: vi.fn(),
|
|
create: vi.fn(),
|
|
rotate: vi.fn(),
|
|
update: vi.fn(),
|
|
remove: vi.fn(),
|
|
listUserSecretDefinitions: vi.fn(),
|
|
createUserSecretDefinition: vi.fn(),
|
|
updateUserSecretDefinition: vi.fn(),
|
|
removeUserSecretDefinition: vi.fn(),
|
|
getUserSecretDefinitionCoverage: vi.fn(),
|
|
listCurrentUserSecretValues: vi.fn(),
|
|
createCurrentUserSecretValue: vi.fn(),
|
|
updateCurrentUserSecretValue: vi.fn(),
|
|
rotateCurrentUserSecretValue: vi.fn(),
|
|
removeCurrentUserSecretValue: vi.fn(),
|
|
previewRemoteImport: vi.fn(),
|
|
importRemoteSecrets: vi.fn(),
|
|
}));
|
|
const mockLogActivity = vi.hoisted(() => vi.fn());
|
|
|
|
vi.mock("../services/index.js", () => ({
|
|
secretService: () => mockSecretService,
|
|
logActivity: mockLogActivity,
|
|
}));
|
|
|
|
function createApp(actor: Record<string, unknown> = {
|
|
type: "board",
|
|
userId: "user-1",
|
|
source: "session",
|
|
companyIds: ["company-1"],
|
|
memberships: [{ companyId: "company-1", status: "active", membershipRole: "admin" }],
|
|
}) {
|
|
const app = express();
|
|
app.use(express.json());
|
|
app.use((req, _res, next) => {
|
|
(req as any).actor = actor;
|
|
next();
|
|
});
|
|
app.use("/api", secretRoutes({} as any));
|
|
app.use(errorHandler);
|
|
return app;
|
|
}
|
|
|
|
describe("secret routes", () => {
|
|
beforeEach(() => {
|
|
for (const mock of Object.values(mockSecretService)) {
|
|
mock.mockReset();
|
|
}
|
|
mockLogActivity.mockReset();
|
|
});
|
|
|
|
it("returns provider health checks for board callers with company access", async () => {
|
|
mockSecretService.checkProviders.mockResolvedValue([
|
|
{
|
|
provider: "local_encrypted",
|
|
status: "ok",
|
|
message: "Local encrypted provider configured",
|
|
backupGuidance: ["Back up the key file together with database backups."],
|
|
},
|
|
]);
|
|
|
|
const res = await request(createApp()).get("/api/companies/company-1/secret-providers/health");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body).toEqual({
|
|
providers: [
|
|
{
|
|
provider: "local_encrypted",
|
|
status: "ok",
|
|
message: "Local encrypted provider configured",
|
|
backupGuidance: ["Back up the key file together with database backups."],
|
|
},
|
|
],
|
|
});
|
|
});
|
|
|
|
it("rejects managed secret creation when externalRef is supplied", async () => {
|
|
const res = await request(createApp()).post("/api/companies/company-1/secrets").send({
|
|
name: "OpenAI API Key",
|
|
managedMode: "paperclip_managed",
|
|
value: "secret-value",
|
|
externalRef: "arn:aws:secretsmanager:us-east-1:123456789012:secret:shared/other",
|
|
});
|
|
|
|
expect(res.status).toBe(400);
|
|
expect(JSON.stringify(res.body)).toMatch(/Managed secrets cannot set externalRef/);
|
|
expect(mockSecretService.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("restricts user secret definition management to company admins", async () => {
|
|
const res = await request(createApp({
|
|
type: "board",
|
|
userId: "user-1",
|
|
source: "session",
|
|
companyIds: ["company-1"],
|
|
memberships: [{ companyId: "company-1", status: "active", membershipRole: "member" }],
|
|
})).post("/api/companies/company-1/user-secret-definitions").send({
|
|
key: "github_token",
|
|
name: "GitHub token",
|
|
provider: "local_encrypted",
|
|
});
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(mockSecretService.createUserSecretDefinition).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("records implicit user-secret definition admins as system actors instead of board pseudo-users", async () => {
|
|
mockSecretService.createUserSecretDefinition.mockResolvedValue({
|
|
id: "definition-1",
|
|
companyId: "company-1",
|
|
key: "github_token",
|
|
name: "GitHub token",
|
|
provider: "local_encrypted",
|
|
status: "active",
|
|
});
|
|
|
|
const res = await request(createApp({
|
|
type: "board",
|
|
source: "local_implicit",
|
|
isInstanceAdmin: true,
|
|
companyIds: ["company-1"],
|
|
memberships: [],
|
|
})).post("/api/companies/company-1/user-secret-definitions").send({
|
|
key: "github_token",
|
|
name: "GitHub token",
|
|
provider: "local_encrypted",
|
|
});
|
|
|
|
expect(res.status).toBe(201);
|
|
expect(mockSecretService.createUserSecretDefinition).toHaveBeenCalledWith(
|
|
"company-1",
|
|
expect.objectContaining({ key: "github_token" }),
|
|
{ userId: null, agentId: null },
|
|
);
|
|
expect(mockLogActivity).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
expect.objectContaining({
|
|
actorType: "system",
|
|
actorId: "local_implicit",
|
|
action: "user_secret_definition.created",
|
|
}),
|
|
);
|
|
expect(JSON.stringify(mockLogActivity.mock.calls)).not.toContain("\"board\"");
|
|
});
|
|
|
|
it("logs patched user-secret definition deletion as deletion activity", async () => {
|
|
mockSecretService.updateUserSecretDefinition.mockResolvedValue({
|
|
id: "definition-1",
|
|
companyId: "company-1",
|
|
key: "github_token__deleted__definition-1",
|
|
name: "GitHub token",
|
|
provider: "local_encrypted",
|
|
status: "deleted",
|
|
});
|
|
|
|
const res = await request(createApp())
|
|
.patch("/api/companies/company-1/user-secret-definitions/definition-1")
|
|
.send({ status: "deleted" });
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockSecretService.updateUserSecretDefinition).toHaveBeenCalledWith(
|
|
"company-1",
|
|
"definition-1",
|
|
expect.objectContaining({ status: "deleted" }),
|
|
{ userId: "user-1", agentId: null },
|
|
);
|
|
expect(mockLogActivity).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
expect.objectContaining({
|
|
action: "user_secret_definition.deleted",
|
|
entityType: "user_secret_definition",
|
|
entityId: "definition-1",
|
|
}),
|
|
);
|
|
});
|
|
|
|
it("creates current-user secret values for the authenticated user only", async () => {
|
|
mockSecretService.createCurrentUserSecretValue.mockResolvedValue({
|
|
id: "secret-1",
|
|
companyId: "company-1",
|
|
scope: "user",
|
|
ownerUserId: "user-1",
|
|
userSecretDefinitionId: "definition-1",
|
|
provider: "local_encrypted",
|
|
latestVersion: 1,
|
|
});
|
|
|
|
const res = await request(createApp()).post("/api/companies/company-1/me/user-secrets").send({
|
|
definitionKey: "github_token",
|
|
value: "secret-value",
|
|
});
|
|
|
|
expect(res.status).toBe(201);
|
|
expect(mockSecretService.createCurrentUserSecretValue).toHaveBeenCalledWith(
|
|
"company-1",
|
|
"user-1",
|
|
{
|
|
definitionKey: "github_token",
|
|
definitionId: undefined,
|
|
value: "secret-value",
|
|
externalRef: undefined,
|
|
providerVersionRef: undefined,
|
|
providerConfigId: undefined,
|
|
},
|
|
{ userId: "user-1", agentId: null },
|
|
);
|
|
expect(JSON.stringify(mockLogActivity.mock.calls)).not.toContain("secret-value");
|
|
});
|
|
|
|
it("rejects current-user secret values without a concrete user identity", async () => {
|
|
const res = await request(createApp({
|
|
type: "board",
|
|
source: "local_implicit",
|
|
companyIds: ["company-1"],
|
|
memberships: [{ companyId: "company-1", status: "active", membershipRole: "admin" }],
|
|
})).post("/api/companies/company-1/me/user-secrets").send({
|
|
definitionKey: "github_token",
|
|
value: "secret-value",
|
|
});
|
|
|
|
expect(res.status).toBe(401);
|
|
expect(res.body).toMatchObject({ error: "User identity required for user-specific secrets" });
|
|
expect(mockSecretService.createCurrentUserSecretValue).not.toHaveBeenCalled();
|
|
expect(mockLogActivity).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects empty current-user secret rotation payloads", async () => {
|
|
const res = await request(createApp())
|
|
.post("/api/companies/company-1/me/user-secrets/secret-1/rotate")
|
|
.send({});
|
|
|
|
expect(res.status).toBe(400);
|
|
expect(JSON.stringify(res.body)).toMatch(/requires value, externalRef/);
|
|
expect(mockSecretService.rotateCurrentUserSecretValue).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("hides user-scoped secrets from legacy company secret mutation routes", async () => {
|
|
mockSecretService.getById.mockResolvedValue({
|
|
id: "secret-1",
|
|
companyId: "company-1",
|
|
scope: "user",
|
|
ownerUserId: "user-2",
|
|
status: "active",
|
|
});
|
|
|
|
const res = await request(createApp()).post("/api/secrets/secret-1/rotate").send({
|
|
value: "new-secret-value",
|
|
});
|
|
|
|
expect(res.status).toBe(404);
|
|
expect(mockSecretService.rotate).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects provider vault routes for non-board actors", async () => {
|
|
const res = await request(createApp({
|
|
type: "agent",
|
|
agentId: "agent-1",
|
|
companyId: "company-1",
|
|
})).get("/api/companies/company-1/secret-provider-configs");
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(mockSecretService.listProviderConfigs).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects provider vault cross-company access before calling the service", async () => {
|
|
const res = await request(createApp({
|
|
type: "board",
|
|
userId: "user-1",
|
|
source: "session",
|
|
companyIds: ["company-2"],
|
|
memberships: [{ companyId: "company-2", status: "active", membershipRole: "admin" }],
|
|
})).get("/api/companies/company-1/secret-provider-configs");
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(mockSecretService.listProviderConfigs).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects provider vault discovery preview for non-board actors", async () => {
|
|
const res = await request(createApp({
|
|
type: "agent",
|
|
agentId: "agent-1",
|
|
companyId: "company-1",
|
|
}))
|
|
.post("/api/companies/company-1/secret-provider-configs/discovery/preview")
|
|
.send({
|
|
provider: "aws_secrets_manager",
|
|
config: { region: "us-east-1" },
|
|
});
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(mockSecretService.previewProviderConfigDiscovery).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects sensitive provider vault config fields", async () => {
|
|
const res = await request(createApp()).post("/api/companies/company-1/secret-provider-configs").send({
|
|
provider: "aws_secrets_manager",
|
|
displayName: "AWS prod",
|
|
config: {
|
|
region: "us-east-1",
|
|
accessKeyId: "AKIA...",
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(400);
|
|
expect(JSON.stringify(res.body)).toMatch(/sensitive field/i);
|
|
expect(mockSecretService.createProviderConfig).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects sensitive provider vault discovery draft config fields", async () => {
|
|
const res = await request(createApp())
|
|
.post("/api/companies/company-1/secret-provider-configs/discovery/preview")
|
|
.send({
|
|
provider: "aws_secrets_manager",
|
|
config: {
|
|
region: "us-east-1",
|
|
secretAccessKey: "secret",
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(400);
|
|
expect(JSON.stringify(res.body)).toMatch(/sensitive field/i);
|
|
expect(mockSecretService.previewProviderConfigDiscovery).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("previews provider vault discovery and logs only aggregate metadata", async () => {
|
|
mockSecretService.previewProviderConfigDiscovery.mockResolvedValue({
|
|
provider: "aws_secrets_manager",
|
|
nextToken: null,
|
|
sampledSecretCount: 2,
|
|
skippedForeignPaperclipSampleCount: 0,
|
|
candidates: [
|
|
{
|
|
provider: "aws_secrets_manager",
|
|
displayName: "AWS production",
|
|
config: {
|
|
region: "us-east-1",
|
|
namespace: "prod-use1",
|
|
secretNamePrefix: "paperclip",
|
|
environmentTag: "production",
|
|
ownerTag: "platform",
|
|
kmsKeyId: null,
|
|
},
|
|
sampleCount: 2,
|
|
samples: [
|
|
{ name: "paperclip/prod-use1/company-1/openai", hasKmsKey: false, tagKeys: ["environment"] },
|
|
],
|
|
signals: {
|
|
namespace: "prod-use1",
|
|
secretNamePrefix: "paperclip",
|
|
environmentTag: "production",
|
|
ownerTag: "platform",
|
|
kmsKeyId: null,
|
|
hasKmsKey: false,
|
|
sampleCount: 2,
|
|
paperclipManagedSampleCount: 0,
|
|
skippedForeignPaperclipSampleCount: 0,
|
|
},
|
|
warnings: [],
|
|
},
|
|
],
|
|
warnings: [],
|
|
});
|
|
|
|
const res = await request(createApp())
|
|
.post("/api/companies/company-1/secret-provider-configs/discovery/preview")
|
|
.send({
|
|
provider: "aws_secrets_manager",
|
|
config: { region: "us-east-1" },
|
|
query: "paperclip",
|
|
pageSize: 25,
|
|
});
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockSecretService.previewProviderConfigDiscovery).toHaveBeenCalledWith("company-1", {
|
|
provider: "aws_secrets_manager",
|
|
config: { region: "us-east-1" },
|
|
query: "paperclip",
|
|
nextToken: undefined,
|
|
pageSize: 25,
|
|
});
|
|
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
|
action: "secret_provider_config.discovery_previewed",
|
|
entityType: "secret_provider_config_discovery",
|
|
entityId: "company-1",
|
|
details: {
|
|
provider: "aws_secrets_manager",
|
|
candidateCount: 1,
|
|
sampledSecretCount: 2,
|
|
warningCount: 0,
|
|
},
|
|
}));
|
|
expect(JSON.stringify(mockLogActivity.mock.calls)).not.toContain("paperclip/prod-use1/company-1/openai");
|
|
});
|
|
|
|
it("returns actionable sanitized provider vault discovery errors", async () => {
|
|
mockSecretService.previewProviderConfigDiscovery.mockRejectedValue(
|
|
new HttpError(
|
|
403,
|
|
"AWS Secrets Manager denied the request. Check IAM permissions for this provider vault.",
|
|
{
|
|
code: "access_denied",
|
|
provider: "aws_secrets_manager",
|
|
operation: "secret_provider_config.discovery.preview",
|
|
providerConfigId: "discovery-preview",
|
|
providerVaultContext: "draft_config",
|
|
region: "us-east-1",
|
|
credentialPath: "Paperclip server runtime/provider credential path",
|
|
requiredCapability: "secretsmanager:ListSecrets",
|
|
actionableMessage:
|
|
"AWS discovery preview needs secretsmanager:ListSecrets in the selected region for the Paperclip server runtime/provider credential path.",
|
|
safeAlternative:
|
|
"If the operator already knows the exact AWS Secrets Manager ARN, paste/link that ARN instead of using discovery. Exact-resource DescribeSecret and runtime read permissions are still required.",
|
|
},
|
|
),
|
|
);
|
|
|
|
const res = await request(createApp())
|
|
.post("/api/companies/company-1/secret-provider-configs/discovery/preview")
|
|
.send({
|
|
provider: "aws_secrets_manager",
|
|
config: { region: "us-east-1" },
|
|
pageSize: 25,
|
|
});
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body).toMatchObject({
|
|
error: "AWS Secrets Manager denied the request. Check IAM permissions for this provider vault.",
|
|
details: {
|
|
code: "access_denied",
|
|
provider: "aws_secrets_manager",
|
|
operation: "secret_provider_config.discovery.preview",
|
|
providerVaultContext: "draft_config",
|
|
region: "us-east-1",
|
|
requiredCapability: "secretsmanager:ListSecrets",
|
|
},
|
|
});
|
|
expect(res.body.details.actionableMessage).toContain("Paperclip server runtime/provider credential path");
|
|
expect(res.body.details.safeAlternative).toContain("paste/link that ARN");
|
|
expect(JSON.stringify(res.body)).not.toContain("arn:aws");
|
|
expect(JSON.stringify(res.body)).not.toContain("123456789012");
|
|
expect(mockLogActivity).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects ready status for coming-soon provider vaults", async () => {
|
|
const res = await request(createApp()).post("/api/companies/company-1/secret-provider-configs").send({
|
|
provider: "vault",
|
|
displayName: "Vault draft",
|
|
status: "ready",
|
|
config: {
|
|
address: "https://vault.example.com",
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(400);
|
|
expect(JSON.stringify(res.body)).toMatch(/locked while coming soon/i);
|
|
expect(mockSecretService.createProviderConfig).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects credential-bearing Vault provider vault addresses before persistence", async () => {
|
|
const res = await request(createApp()).post("/api/companies/company-1/secret-provider-configs").send({
|
|
provider: "vault",
|
|
displayName: "Vault draft",
|
|
config: {
|
|
address: "https://user:pass@vault.example.com",
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(400);
|
|
expect(JSON.stringify(res.body)).toMatch(/origin-only HTTP\(S\) URL/i);
|
|
expect(mockSecretService.createProviderConfig).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each([
|
|
"https://vault.example.com?token=hvs.x",
|
|
"https://vault.example.com#token=hvs.x",
|
|
])("rejects token-bearing Vault provider vault address %s before persistence", async (address) => {
|
|
const res = await request(createApp()).post("/api/companies/company-1/secret-provider-configs").send({
|
|
provider: "vault",
|
|
displayName: "Vault draft",
|
|
config: { address },
|
|
});
|
|
|
|
expect(res.status).toBe(400);
|
|
expect(JSON.stringify(res.body)).toMatch(/origin-only HTTP\(S\) URL/i);
|
|
expect(mockSecretService.createProviderConfig).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects unsafe Vault provider vault address patches before persistence", async () => {
|
|
const res = await request(createApp()).patch("/api/secret-provider-configs/vault-1").send({
|
|
config: {
|
|
address: "https://vault.example.com#token=hvs.x",
|
|
},
|
|
});
|
|
|
|
expect(res.status).toBe(400);
|
|
expect(JSON.stringify(res.body)).toMatch(/origin-only HTTP\(S\) URL/i);
|
|
expect(mockSecretService.getProviderConfigById).not.toHaveBeenCalled();
|
|
expect(mockSecretService.updateProviderConfig).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("creates provider vaults and logs safe activity details", async () => {
|
|
const createdAt = new Date("2026-05-06T00:00:00.000Z");
|
|
mockSecretService.createProviderConfig.mockResolvedValue({
|
|
id: "11111111-1111-4111-8111-111111111111",
|
|
companyId: "company-1",
|
|
provider: "aws_secrets_manager",
|
|
displayName: "AWS prod",
|
|
status: "ready",
|
|
isDefault: true,
|
|
config: { region: "us-east-1" },
|
|
healthStatus: null,
|
|
healthCheckedAt: null,
|
|
healthMessage: null,
|
|
healthDetails: null,
|
|
disabledAt: null,
|
|
createdByAgentId: null,
|
|
createdByUserId: "user-1",
|
|
createdAt,
|
|
updatedAt: createdAt,
|
|
});
|
|
|
|
const res = await request(createApp()).post("/api/companies/company-1/secret-provider-configs").send({
|
|
provider: "aws_secrets_manager",
|
|
displayName: "AWS prod",
|
|
isDefault: true,
|
|
config: { region: "us-east-1" },
|
|
});
|
|
|
|
expect(res.status).toBe(201);
|
|
expect(mockSecretService.createProviderConfig).toHaveBeenCalledWith(
|
|
"company-1",
|
|
{
|
|
provider: "aws_secrets_manager",
|
|
displayName: "AWS prod",
|
|
status: undefined,
|
|
isDefault: true,
|
|
config: { region: "us-east-1" },
|
|
},
|
|
{ userId: "user-1", agentId: null },
|
|
);
|
|
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
|
action: "secret_provider_config.created",
|
|
details: {
|
|
provider: "aws_secrets_manager",
|
|
displayName: "AWS prod",
|
|
status: "ready",
|
|
isDefault: true,
|
|
},
|
|
}));
|
|
expect(JSON.stringify(mockLogActivity.mock.calls)).not.toContain("accessKey");
|
|
});
|
|
|
|
it("removes provider vault config locally without deleting remote provider data", async () => {
|
|
const createdAt = new Date("2026-05-06T00:00:00.000Z");
|
|
const providerConfig = {
|
|
id: "11111111-1111-4111-8111-111111111111",
|
|
companyId: "company-1",
|
|
provider: "aws_secrets_manager",
|
|
displayName: "AWS prod",
|
|
status: "ready",
|
|
isDefault: false,
|
|
config: { region: "us-east-1" },
|
|
healthStatus: null,
|
|
healthCheckedAt: null,
|
|
healthMessage: null,
|
|
healthDetails: null,
|
|
disabledAt: null,
|
|
createdByAgentId: null,
|
|
createdByUserId: "user-1",
|
|
createdAt,
|
|
updatedAt: createdAt,
|
|
};
|
|
mockSecretService.getProviderConfigById.mockResolvedValue(providerConfig);
|
|
mockSecretService.removeProviderConfig.mockResolvedValue(providerConfig);
|
|
|
|
const res = await request(createApp()).delete(
|
|
"/api/secret-provider-configs/11111111-1111-4111-8111-111111111111",
|
|
);
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockSecretService.removeProviderConfig).toHaveBeenCalledWith(
|
|
"11111111-1111-4111-8111-111111111111",
|
|
);
|
|
expect(mockSecretService.disableProviderConfig).not.toHaveBeenCalled();
|
|
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
|
action: "secret_provider_config.removed",
|
|
details: {
|
|
provider: "aws_secrets_manager",
|
|
displayName: "AWS prod",
|
|
remoteDeleted: false,
|
|
},
|
|
}));
|
|
});
|
|
|
|
it("rejects remote import preview for non-board actors", async () => {
|
|
const res = await request(createApp({
|
|
type: "agent",
|
|
agentId: "agent-1",
|
|
companyId: "company-1",
|
|
})).post("/api/companies/company-1/secrets/remote-import/preview").send({
|
|
providerConfigId: "11111111-1111-4111-8111-111111111111",
|
|
});
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(mockSecretService.previewRemoteImport).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("previews remote imports and logs only aggregate metadata", async () => {
|
|
mockSecretService.previewRemoteImport.mockResolvedValue({
|
|
providerConfigId: "11111111-1111-4111-8111-111111111111",
|
|
provider: "aws_secrets_manager",
|
|
nextToken: null,
|
|
candidates: [
|
|
{
|
|
externalRef: "arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/openai",
|
|
remoteName: "prod/openai",
|
|
name: "openai",
|
|
key: "openai",
|
|
providerVersionRef: null,
|
|
providerMetadata: { description: "OpenAI API key" },
|
|
status: "ready",
|
|
importable: true,
|
|
conflicts: [],
|
|
},
|
|
],
|
|
});
|
|
|
|
const res = await request(createApp())
|
|
.post("/api/companies/company-1/secrets/remote-import/preview")
|
|
.send({
|
|
providerConfigId: "11111111-1111-4111-8111-111111111111",
|
|
query: "openai",
|
|
pageSize: 25,
|
|
});
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockSecretService.previewRemoteImport).toHaveBeenCalledWith("company-1", {
|
|
providerConfigId: "11111111-1111-4111-8111-111111111111",
|
|
query: "openai",
|
|
nextToken: undefined,
|
|
pageSize: 25,
|
|
});
|
|
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
|
action: "secret.remote_import.previewed",
|
|
details: {
|
|
provider: "aws_secrets_manager",
|
|
candidateCount: 1,
|
|
readyCount: 1,
|
|
duplicateCount: 0,
|
|
conflictCount: 0,
|
|
},
|
|
}));
|
|
expect(JSON.stringify(mockLogActivity.mock.calls)).not.toContain("prod/openai");
|
|
});
|
|
|
|
it("returns sanitized remote import preview provider errors", async () => {
|
|
mockSecretService.previewRemoteImport.mockRejectedValue(
|
|
new HttpError(
|
|
403,
|
|
"AWS Secrets Manager denied the request. Check IAM permissions for this provider vault.",
|
|
{ code: "access_denied" },
|
|
),
|
|
);
|
|
|
|
const res = await request(createApp())
|
|
.post("/api/companies/company-1/secrets/remote-import/preview")
|
|
.send({
|
|
providerConfigId: "11111111-1111-4111-8111-111111111111",
|
|
});
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body).toEqual({
|
|
code: "access_denied",
|
|
error: "AWS Secrets Manager denied the request. Check IAM permissions for this provider vault.",
|
|
details: { code: "access_denied" },
|
|
});
|
|
expect(JSON.stringify(res.body)).not.toContain("arn:aws");
|
|
expect(JSON.stringify(res.body)).not.toContain("123456789012");
|
|
expect(mockLogActivity).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("imports remote references and logs aggregate row counts", async () => {
|
|
mockSecretService.importRemoteSecrets.mockResolvedValue({
|
|
providerConfigId: "11111111-1111-4111-8111-111111111111",
|
|
provider: "aws_secrets_manager",
|
|
importedCount: 1,
|
|
skippedCount: 0,
|
|
errorCount: 0,
|
|
results: [
|
|
{
|
|
externalRef: "arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/openai",
|
|
name: "OpenAI API key",
|
|
key: "openai-api-key",
|
|
status: "imported",
|
|
reason: null,
|
|
secretId: "22222222-2222-4222-8222-222222222222",
|
|
conflicts: [],
|
|
},
|
|
],
|
|
});
|
|
|
|
const res = await request(createApp())
|
|
.post("/api/companies/company-1/secrets/remote-import")
|
|
.send({
|
|
providerConfigId: "11111111-1111-4111-8111-111111111111",
|
|
secrets: [
|
|
{
|
|
externalRef: "arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/openai",
|
|
name: "OpenAI API key",
|
|
key: "openai-api-key",
|
|
description: "Operator-entered Paperclip description",
|
|
},
|
|
],
|
|
});
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(mockSecretService.importRemoteSecrets).toHaveBeenCalledWith(
|
|
"company-1",
|
|
{
|
|
providerConfigId: "11111111-1111-4111-8111-111111111111",
|
|
secrets: [
|
|
{
|
|
externalRef: "arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/openai",
|
|
name: "OpenAI API key",
|
|
key: "openai-api-key",
|
|
description: "Operator-entered Paperclip description",
|
|
},
|
|
],
|
|
},
|
|
{ userId: "user-1", agentId: null },
|
|
);
|
|
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
|
action: "secret.remote_import.completed",
|
|
details: {
|
|
provider: "aws_secrets_manager",
|
|
importedCount: 1,
|
|
skippedCount: 0,
|
|
errorCount: 0,
|
|
},
|
|
}));
|
|
expect(JSON.stringify(mockLogActivity.mock.calls)).not.toContain("prod/openai");
|
|
});
|
|
|
|
it("surfaces update-route externalRef retarget rejection without logging raw refs", async () => {
|
|
mockSecretService.getById.mockResolvedValue({
|
|
id: "22222222-2222-4222-8222-222222222222",
|
|
companyId: "company-1",
|
|
name: "OpenAI API key",
|
|
key: "openai-api-key",
|
|
provider: "aws_secrets_manager",
|
|
managedMode: "external_reference",
|
|
externalRef: "arn:aws:secretsmanager:us-east-1:123456789012:secret:shared/original",
|
|
});
|
|
mockSecretService.update.mockRejectedValue(
|
|
unprocessable("External reference secrets cannot be retargeted through generic update"),
|
|
);
|
|
|
|
const res = await request(createApp())
|
|
.patch("/api/secrets/22222222-2222-4222-8222-222222222222")
|
|
.send({
|
|
externalRef: "arn:aws:secretsmanager:us-east-1:123456789012:secret:shared/repointed",
|
|
});
|
|
|
|
expect(res.status).toBe(422);
|
|
expect(mockSecretService.update).toHaveBeenCalledWith(
|
|
"22222222-2222-4222-8222-222222222222",
|
|
expect.objectContaining({
|
|
externalRef: "arn:aws:secretsmanager:us-east-1:123456789012:secret:shared/repointed",
|
|
}),
|
|
);
|
|
expect(mockLogActivity).not.toHaveBeenCalled();
|
|
expect(JSON.stringify(mockLogActivity.mock.calls)).not.toContain("shared/repointed");
|
|
});
|
|
|
|
it("allows DELETE to retry cleanup for already soft-deleted secrets", async () => {
|
|
const secret = {
|
|
id: "33333333-3333-4333-8333-333333333333",
|
|
companyId: "company-1",
|
|
name: "OpenAI API Key__deleted__33333333-3333-4333-8333-333333333333",
|
|
key: "openai-api-key__deleted__33333333-3333-4333-8333-333333333333",
|
|
provider: "aws_secrets_manager",
|
|
managedMode: "paperclip_managed",
|
|
status: "deleted",
|
|
};
|
|
mockSecretService.getById.mockResolvedValue(secret);
|
|
mockSecretService.remove.mockResolvedValue(secret);
|
|
|
|
const res = await request(createApp()).delete(
|
|
"/api/secrets/33333333-3333-4333-8333-333333333333",
|
|
);
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body).toEqual({ ok: true });
|
|
expect(mockSecretService.remove).toHaveBeenCalledWith(
|
|
"33333333-3333-4333-8333-333333333333",
|
|
);
|
|
expect(mockLogActivity).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
expect.objectContaining({
|
|
action: "secret.deleted",
|
|
companyId: "company-1",
|
|
entityId: secret.id,
|
|
}),
|
|
);
|
|
});
|
|
});
|