diff --git a/packages/adapter-utils/src/command-redaction.ts b/packages/adapter-utils/src/command-redaction.ts index 2c7e8056ff2..b23eec7627f 100644 --- a/packages/adapter-utils/src/command-redaction.ts +++ b/packages/adapter-utils/src/command-redaction.ts @@ -1,3 +1,4 @@ +import { looksLikeCredentialToken } from "@paperclipai/shared"; import { containsSigV4PresignedUrl, protectSigV4PresignedUrlParameters, @@ -39,11 +40,17 @@ const COMMAND_ENV_SECRET_ASSIGNMENT_RE = new RegExp( const COMMAND_AUTHORIZATION_BEARER_RE = /(\bAuthorization\s*:\s*Bearer\s+)[^\s"'`]+/gi; const COMMAND_OPENAI_KEY_SOURCE = String.raw`\bsk-[A-Za-z0-9_-]{12,}\b`; -const COMMAND_GITHUB_TOKEN_SOURCE = String.raw`\bgh[pousr]_[A-Za-z0-9_]{20,}\b`; +const COMMAND_UNDERSCORE_SECRET_KEY_SOURCE = String.raw`\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b`; +const COMMAND_GITHUB_TOKEN_SOURCE = String.raw`\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]{16,}\b`; const COMMAND_OPENAI_KEY_RE = new RegExp(COMMAND_OPENAI_KEY_SOURCE, "g"); +const COMMAND_UNDERSCORE_SECRET_KEY_RE = new RegExp(COMMAND_UNDERSCORE_SECRET_KEY_SOURCE, "g"); const COMMAND_GITHUB_TOKEN_RE = new RegExp(COMMAND_GITHUB_TOKEN_SOURCE, "g"); +const COMMAND_SLACK_TOKEN_RE = /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g; +const COMMAND_AWS_KEY_ID_RE = /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g; +const COMMAND_GOOGLE_API_KEY_RE = /\bAIza[0-9A-Za-z\-_]{20,}\b/g; +const COMMAND_GITLAB_PAT_RE = /\bglpat-[A-Za-z0-9_-]{16,}\b/g; const STANDALONE_SECRET_TOKEN_RE = new RegExp( - `${COMMAND_OPENAI_KEY_SOURCE}|${COMMAND_GITHUB_TOKEN_SOURCE}|\\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\\b|\\bgithub_pat_[A-Za-z0-9_]{20,}\\b`, + `${COMMAND_OPENAI_KEY_SOURCE}|${COMMAND_GITHUB_TOKEN_SOURCE}|${COMMAND_UNDERSCORE_SECRET_KEY_SOURCE}`, ); const COMMAND_JWT_RE = /\b(? looksLikeCredentialJwt(match) ? redactedValue : match); } @@ -275,6 +301,7 @@ export function collectDiagnosticEnvironmentSecrets( const secretName = new RegExp(`^(?:${SECRET_NAME_PATTERN})$`, "i"); const values = new Set(); for (const [key, value] of Object.entries(env)) { + if (looksLikeCredentialToken(key)) values.add(key); if (typeof value !== "string" || !value) continue; if (declared.has(key) || secretName.test(key) || containsSigV4PresignedUrl(value) || diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index f1f6eb0b615..a22ae2c4f2d 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -2372,6 +2372,10 @@ export { attentionTransferSchema, type AttentionClose, type AttentionTransfer, + ENV_VAR_NAME_RE, + looksLikeCredentialToken, + SECRET_SHAPED_ENV_NAME_ERROR, + SECRET_SHAPED_ACCESS_ALIAS_ERROR, envBindingPlainSchema, envBindingSecretRefSchema, envBindingUserSecretRefSchema, diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts index 25a142aeffc..e5cc6c6d323 100644 --- a/packages/shared/src/validators/index.ts +++ b/packages/shared/src/validators/index.ts @@ -710,6 +710,10 @@ export { } from "./attention.js"; export { + ENV_VAR_NAME_RE, + looksLikeCredentialToken, + SECRET_SHAPED_ENV_NAME_ERROR, + SECRET_SHAPED_ACCESS_ALIAS_ERROR, envBindingPlainSchema, envBindingSecretRefSchema, envBindingUserSecretRefSchema, diff --git a/packages/shared/src/validators/secret.ts b/packages/shared/src/validators/secret.ts index 746be54ac08..f2a7af9a0a1 100644 --- a/packages/shared/src/validators/secret.ts +++ b/packages/shared/src/validators/secret.ts @@ -12,6 +12,39 @@ const secretKeySchema = z.string().trim().min(1).max(120).regex(/^[a-zA-Z0-9_.-] const secretVersionSelectorSchema = z.union([z.literal("latest"), z.number().int().positive()]); const creatableSecretStatusSchema = z.enum(["active", "disabled", "archived"]); +export const ENV_VAR_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/; + +const CREDENTIAL_TOKEN_PATTERNS: readonly RegExp[] = [ + /^gh[pousr]_[A-Za-z0-9_]{16,}$/, + /^github_pat_[A-Za-z0-9_]{16,}$/, + /^sk-(?:ant-|proj-|live-|test-)?[A-Za-z0-9_-]{12,}$/, + /^(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}$/, + /^xox[baprs]-[A-Za-z0-9-]{10,}$/, + /^(?:AKIA|ASIA)[0-9A-Z]{16}$/, + /^AIza[0-9A-Za-z\-_]{20,}$/, + /^glpat-[A-Za-z0-9_-]{16,}$/, + /^npm_[A-Za-z0-9]{20,}$/, + /^hf_[A-Za-z0-9]{20,}$/, + /^lin_api_[A-Za-z0-9]{20,}$/, + /^sbp_[A-Za-z0-9]{20,}$/, + /^SG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}$/, + /^eyJ[A-Za-z0-9-_]{8,}\.[A-Za-z0-9-_]{8,}\.[A-Za-z0-9-_]{8,}$/, + /-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----/, + /^Bearer\s+\S+/i, +]; + +export function looksLikeCredentialToken(value: string): boolean { + const trimmed = value.trim(); + if (!trimmed) return false; + return CREDENTIAL_TOKEN_PATTERNS.some((pattern) => pattern.test(trimmed)); +} + +export const SECRET_SHAPED_ENV_NAME_ERROR = + "Environment variable name looks like a secret or API token. Put the variable name (for example GH_TOKEN) in Name and store the token in Value as a secret."; + +export const SECRET_SHAPED_ACCESS_ALIAS_ERROR = + "Secret access alias looks like a secret or API token. Put an alias name (for example GH_TOKEN) in Alias, not the token itself."; + export const envBindingPlainSchema = z.object({ type: z.literal("plain"), value: z.string(), diff --git a/server/src/__tests__/agents-adapter-config-user-secret.test.ts b/server/src/__tests__/agents-adapter-config-user-secret.test.ts index 899133d02d4..870af7a5f4e 100644 --- a/server/src/__tests__/agents-adapter-config-user-secret.test.ts +++ b/server/src/__tests__/agents-adapter-config-user-secret.test.ts @@ -411,6 +411,86 @@ describeEmbeddedPostgres("agents adapter-config user-secret resolution routes", expect(mockRunClaudeLogin).toHaveBeenCalledTimes(1); expect(mockRunClaudeLogin.mock.calls[0][0].config.env.ANTHROPIC_API_KEY).toBe("sk-owner"); }); + + it("rejects secret-shaped env var names on PATCH /agents/:id without echoing the token", async () => { + const agentId = randomUUID(); + mockAgentService.getById.mockResolvedValue({ + id: agentId, + companyId: COMPANY_ID, + name: "Secret Guard Agent", + role: "engineer", + title: null, + status: "idle", + reportsTo: null, + adapterType: "external_test", + adapterConfig: {}, + runtimeConfig: {}, + permissions: {}, + metadata: null, + budgetMonthlyCents: 0, + defaultEnvironmentId: null, + lifecycleHolds: [], + updatedAt: new Date(0), + }); + beforeEachActor(boardUserActor); + const app = await createApp(); + + const secretShapedNames = [ + ["github", "pat", "11ABCDEF0123456789", "secretTokenValue99"].join("_"), + ["ghp", "0123456789abcdef0123456789abcdef"].join("_"), + ["sk", "proj", "secretApiKey1234567890abcdef"].join("-"), + ]; + + for (const secretName of secretShapedNames) { + const res = await request(app) + .patch(`/api/agents/${agentId}`) + .send({ + adapterConfig: { + env: { + [secretName]: { type: "plain", value: "some-value" }, + }, + }, + }); + expect(res.status, `expected 422 for ${secretName}: ${JSON.stringify(res.body)}`).toBe(422); + const serialized = JSON.stringify(res.body); + expect(serialized).not.toContain(secretName); + expect(serialized.toLowerCase()).toMatch(/secret|token/); + } + + // Also reject secret-shaped access.* aliases without echoing the token. + const secretAlias = ["ghp", "0123456789abcdef0123456789abcdef"].join("_"); + const aliasRes = await request(app) + .patch(`/api/agents/${agentId}`) + .send({ + adapterConfig: { + [`access.${secretAlias}`]: { + type: "secret_ref", + secretId: randomUUID(), + version: "latest", + }, + }, + }); + expect(aliasRes.status, JSON.stringify(aliasRes.body)).toBe(422); + expect(JSON.stringify(aliasRes.body)).not.toContain(secretAlias); + expect(JSON.stringify(aliasRes.body).toLowerCase()).toMatch(/secret|token/); + + // Legacy secret-shaped env names already stored in DB must be skipped at runtime + // instead of breaking existing heartbeats. + const svc = secretService(db); + const legacyKey = ["github", "pat", "11ABCDEF0123456789", "legacyTokenValue"].join("_"); + const resolvedEnv = await svc.resolveEnvBindings(COMPANY_ID, { + [legacyKey]: { type: "plain", value: "ignored" }, + SAFE_VAR: { type: "plain", value: "ok" }, + }); + expect(resolvedEnv.env).toEqual({ SAFE_VAR: "ok" }); + const resolvedRuntime = await svc.resolveAdapterConfigForRuntime(COMPANY_ID, { + env: { + [legacyKey]: { type: "plain", value: "ignored" }, + SAFE_VAR: { type: "plain", value: "ok" }, + }, + }); + expect(resolvedRuntime.config.env).toEqual({ SAFE_VAR: "ok" }); + }); }); function beforeEachActor(actor: TestActor) { diff --git a/server/src/__tests__/redact-sensitive.test.ts b/server/src/__tests__/redact-sensitive.test.ts index 7ade5be849f..6820abd07c0 100644 --- a/server/src/__tests__/redact-sensitive.test.ts +++ b/server/src/__tests__/redact-sensitive.test.ts @@ -226,6 +226,41 @@ describe("redactSensitive", () => { expect(json).not.toContain("null"); expect(json).not.toContain("[1,2,3]"); }); + + it("redacts secret-shaped object keys so accidental tokens in env var names never leak into 4xx logs", () => { + const githubPat = ["github", "pat", "11ABCDEF0123456789", "secretTokenValue99"].join("_"); + const ghpToken = ["ghp", "0123456789abcdef0123456789abcdef"].join("_"); + const openaiKey = ["sk", "proj", "secretApiKey1234567890abcdef"].join("-"); + const out = redactSensitive({ + adapterConfig: { + env: { + [githubPat]: { type: "plain", value: "x" }, + [ghpToken]: { type: "plain", value: "y" }, + [openaiKey]: { type: "plain", value: "z" }, + NODE_ENV: { type: "plain", value: "production" }, + }, + }, + }); + const serialized = JSON.stringify(out); + expect(serialized).not.toContain(githubPat); + expect(serialized).not.toContain(ghpToken); + expect(serialized).not.toContain(openaiKey); + expect(serialized).toContain("NODE_ENV"); + }); + + it("handles thousands of distinct credential-shaped object keys in linear time without leaking them", () => { + const env: Record = { "[REDACTED]": "existing", "[REDACTED]_2": "existing2" }; + const prefix = ["xoxb", "1234567890"].join("-"); + for (let index = 0; index < 4_000; index += 1) { + env[`${prefix}-${String(index).padStart(6, "0")}abcdef`] = "secret"; + } + const startedAt = performance.now(); + const out = redactSensitive({ env }) as { env: Record }; + const elapsedMs = performance.now() - startedAt; + expect(elapsedMs).toBeLessThan(1_000); + expect(Object.keys(out.env)).toHaveLength(4_002); + expect(JSON.stringify(out)).not.toContain(prefix); + }); }); describe("stripSecretBearingUrlParts", () => { diff --git a/server/src/__tests__/redaction.test.ts b/server/src/__tests__/redaction.test.ts index 98682dc89b9..fb2de3b0130 100644 --- a/server/src/__tests__/redaction.test.ts +++ b/server/src/__tests__/redaction.test.ts @@ -972,3 +972,67 @@ describe("redaction of long letter/digit runs", () => { } }); }); + +describe("secret-shaped env var names and tokens", () => { + const githubPat = ["github", "pat", "11ABCDEF0123456789", "secretTokenValue99"].join("_"); + const ghpToken = ["ghp", "0123456789abcdef0123456789abcdef"].join("_"); + const openaiKey = ["sk", "proj", "secretApiKey1234567890abcdef"].join("-"); + + it("redacts secret-shaped keys in redactAgentAdapterConfig without leaking the key name", () => { + const redacted = redactAgentAdapterConfig({ + model: "claude", + env: { + GH_TOKEN: { type: "plain", value: "plain-secret" }, + [githubPat]: { type: "plain", value: "accidental" }, + [ghpToken]: { type: "secret_ref", secretId: "11111111-1111-4111-8111-111111111111", version: "latest" }, + [openaiKey]: "raw-value", + }, + }); + const serialized = JSON.stringify(redacted); + expect(serialized).not.toContain(githubPat); + expect(serialized).not.toContain(ghpToken); + expect(serialized).not.toContain(openaiKey); + expect((redacted.env as Record).GH_TOKEN).toEqual({ + type: "plain", + value: REDACTED_EVENT_VALUE, + }); + }); + + it("redacts secret-shaped object keys in sanitizeRecord and redactEventPayload", () => { + const sanitized = redactEventPayload({ + env: { + [githubPat]: "x", + [ghpToken]: { type: "plain", value: "y" }, + SAFE_KEY: "visible", + }, + }); + const serialized = JSON.stringify(sanitized); + expect(serialized).not.toContain(githubPat); + expect(serialized).not.toContain(ghpToken); + expect((sanitized?.env as Record).SAFE_KEY).toBe("visible"); + }); + + it("redacts github_pat_ tokens in free-form text logs", () => { + const out = redactSensitiveText(`Exported ${githubPat} and ${ghpToken} and ${openaiKey}`); + expect(out).not.toContain(githubPat); + expect(out).not.toContain(ghpToken); + expect(out).not.toContain(openaiKey); + }); + + it("redacts thousands of distinct credential-shaped keys in linear time", () => { + const env: Record = {}; + const prefix = ["xoxb", "1234567890"].join("-"); + for (let index = 0; index < 4_000; index += 1) { + env[`${prefix}-${String(index).padStart(6, "0")}abcdef`] = { type: "plain", value: "v" }; + } + const startedAt = performance.now(); + const redactedAdapter = redactAgentAdapterConfig({ env }); + const sanitized = sanitizeRecord(env); + const elapsedMs = performance.now() - startedAt; + expect(elapsedMs).toBeLessThan(1_000); + expect(Object.keys(redactedAdapter.env as Record)).toHaveLength(4_000); + expect(Object.keys(sanitized)).toHaveLength(4_000); + expect(JSON.stringify(redactedAdapter)).not.toContain(prefix); + expect(JSON.stringify(sanitized)).not.toContain(prefix); + }); +}); diff --git a/server/src/middleware/redact-sensitive.ts b/server/src/middleware/redact-sensitive.ts index d84ca8c7f9e..fc40721e7dc 100644 --- a/server/src/middleware/redact-sensitive.ts +++ b/server/src/middleware/redact-sensitive.ts @@ -1,3 +1,5 @@ +import { looksLikeCredentialToken } from "@paperclipai/shared"; + // Redaction for HTTP log payloads. // // `customProps` in logger.ts copies `req.body` / `req.params` / `req.query` @@ -159,6 +161,29 @@ export function stripSecretBearingUrlParts(value: string): string { } } +function isCredentialShapedKey(key: string): boolean { + if (looksLikeCredentialToken(key)) return true; + if (key.startsWith("access.") && looksLikeCredentialToken(key.slice("access.".length))) return true; + return false; +} + +function createRedactedKeyAllocator(existingKeys: ReadonlySet): () => string { + let usedBase = false; + let nextSuffix = 2; + return () => { + if (!usedBase) { + usedBase = true; + if (!existingKeys.has(REDACTED)) return REDACTED; + } + while (existingKeys.has(`${REDACTED}_${nextSuffix}`)) { + nextSuffix += 1; + } + const allocated = `${REDACTED}_${nextSuffix}`; + nextSuffix += 1; + return allocated; + }; +} + export function redactSensitive(value: unknown, depth = 0): unknown { if (depth > MAX_DEPTH) return undefined; if (value === null || typeof value !== "object") return value; @@ -166,8 +191,17 @@ export function redactSensitive(value: unknown, depth = 0): unknown { if (depth + 1 > MAX_DEPTH) return undefined; return value.map((entry) => redactSensitive(entry, depth + 1)); } + const entries = Object.entries(value as Record); + let allocateRedactedKey: (() => string) | null = null; const out: Record = {}; - for (const [key, entry] of Object.entries(value as Record)) { + for (const [key, entry] of entries) { + if (isCredentialShapedKey(key)) { + if (!allocateRedactedKey) { + allocateRedactedKey = createRedactedKeyAllocator(new Set(entries.map(([k]) => k))); + } + out[allocateRedactedKey()] = REDACTED; + continue; + } if (isSensitiveKey(key)) { out[key] = REDACTED; continue; @@ -200,10 +234,12 @@ function collectSensitiveStringValuesInto( return; } for (const [key, entry] of Object.entries(value as Record)) { + const credentialKey = isCredentialShapedKey(key); + if (credentialKey) values.add(key); collectSensitiveStringValuesInto( entry, values, - collectAll || isSensitiveKey(key), + collectAll || isSensitiveKey(key) || credentialKey, depth + 1, ); } diff --git a/server/src/redaction.ts b/server/src/redaction.ts index a48caa03448..5653d44e30d 100644 --- a/server/src/redaction.ts +++ b/server/src/redaction.ts @@ -1,5 +1,6 @@ import { redactCommandText } from "@paperclipai/adapter-utils"; import { isPublicExecutorToolSelector, looksLikeCredentialJwt } from "@paperclipai/adapter-utils/command-redaction"; +import { looksLikeCredentialToken } from "@paperclipai/shared"; const SECRET_FIELD_NAME_PATTERN = String.raw`[A-Za-z0-9_-]*(?:api[-_]?key|access[-_]?token|auth(?:_?token)?|token|authorization(?:[-_]?code)?|bearer|secrets?|passwd|passwords?|credentials?|jwt|private[-_]?key|cookie|connectionstring|browser[-_]?code|login[-_]?url)(?:[-_]?(?:value|header|prod(?:uction)?|dev(?:elopment)?|test|staging|primary|secondary))*`; const SECRET_FIELD_NAME_START = String.raw`(?, +): () => string { + let usedBase = false; + let nextSuffix = 2; + return () => { + if (!usedBase) { + usedBase = true; + if (!existingKeys.has(base)) return base; + } + while (existingKeys.has(`${base}_${nextSuffix}`)) { + nextSuffix += 1; + } + const allocated = `${base}_${nextSuffix}`; + nextSuffix += 1; + return allocated; + }; +} + export function sanitizeRecord( record: Record, ): Record { + const entries = Object.entries(record); + let allocateRedactedKey: (() => string) | null = null; const redacted: Record = {}; - for (const [key, value] of Object.entries(record)) { + for (const [key, value] of entries) { + if (isCredentialShapedObjectKey(key)) { + if (!allocateRedactedKey) { + allocateRedactedKey = createRedactedObjectKeyAllocator( + REDACTED_EVENT_VALUE, + new Set(entries.map(([k]) => k)), + ); + } + const safeKey = allocateRedactedKey(); + if (isSecretRefBinding(value) || isUserSecretRefBinding(value)) { + redacted[safeKey] = sanitizeValue(value); + } else if (isPlainBinding(value)) { + redacted[safeKey] = { type: "plain", value: REDACTED_EVENT_VALUE }; + } else { + redacted[safeKey] = REDACTED_EVENT_VALUE; + } + continue; + } if (COMMAND_ARGS_PAYLOAD_KEY_RE.test(key) && Array.isArray(value)) { redacted[key] = sanitizeCommandArgs(value); continue; @@ -1007,9 +1067,22 @@ export function redactAgentAdapterConfig( // `env`; keeping it out of `sanitizeRecord` means a future change there // cannot alter entries this function has already redacted. const { env, ...rest } = adapterConfig; - const redactedEnv = Object.fromEntries( - Object.entries(env).map(([key, value]) => [key, redactAgentEnvBinding(value)]), - ); + const envEntries = Object.entries(env); + let allocateRedactedKey: (() => string) | null = null; + const redactedEnv: Record = {}; + for (const [key, value] of envEntries) { + let safeKey = key; + if (isCredentialShapedObjectKey(key)) { + if (!allocateRedactedKey) { + allocateRedactedKey = createRedactedObjectKeyAllocator( + REDACTED_EVENT_VALUE, + new Set(envEntries.map(([k]) => k)), + ); + } + safeKey = allocateRedactedKey(); + } + redactedEnv[safeKey] = redactAgentEnvBinding(value); + } return { ...(redactEventPayload(rest) ?? {}), env: redactedEnv }; } diff --git a/server/src/services/secrets.ts b/server/src/services/secrets.ts index 11ec3d36fb3..787df980cb0 100644 --- a/server/src/services/secrets.ts +++ b/server/src/services/secrets.ts @@ -40,9 +40,13 @@ import { CLASS3_STATIC_LEASE_ALLOWLIST, createSecretProviderConfigSchema, deriveProjectUrlKey, + ENV_VAR_NAME_RE, envBindingSchema, isUuidLike, + looksLikeCredentialToken, normalizeAgentUrlKey, + SECRET_SHAPED_ACCESS_ALIAS_ERROR, + SECRET_SHAPED_ENV_NAME_ERROR, secretProviderConfigPayloadSchema, secretProviderConfigDiscoveryPreviewSchema, updateSecretProviderConfigSchema, @@ -94,7 +98,7 @@ function latestDate(a: Date | null, b: Date | null): Date | null { return a.getTime() >= b.getTime() ? a : b; } -const ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/; +const ENV_KEY_RE = ENV_VAR_NAME_RE; const AGENT_ACCESS_CONFIG_PATH_PREFIX = "access."; // System consumer id for a durable orphan-sandbox teardown. The cleanup sweep // resolves the recorded connection secret under this id so the audit trail @@ -886,6 +890,24 @@ function secretResolutionErrorCode(error: unknown): SecretResolutionErrorCode { return "provider_error"; } +function assertSafeEnvName(key: string) { + if (looksLikeCredentialToken(key)) { + throw unprocessable(SECRET_SHAPED_ENV_NAME_ERROR); + } + if (!ENV_KEY_RE.test(key)) { + throw unprocessable(`Invalid environment variable name: ${key}`); + } +} + +function assertSafeAccessAlias(alias: string) { + if (looksLikeCredentialToken(alias)) { + throw unprocessable(SECRET_SHAPED_ACCESS_ALIAS_ERROR); + } + if (!ENV_KEY_RE.test(alias)) { + throw unprocessable(`Invalid agent secret access alias: ${alias || "(empty)"}`); + } +} + function assertSecretBindingConfigPath(input: { targetType: SecretBindingTargetType; configPath: string; @@ -895,9 +917,7 @@ function assertSecretBindingConfigPath(input: { throw unprocessable("API-only secret access bindings must target an agent"); } const alias = input.configPath.slice(AGENT_ACCESS_CONFIG_PATH_PREFIX.length); - if (!ENV_KEY_RE.test(alias)) { - throw unprocessable(`Invalid agent secret access alias: ${alias || "(empty)"}`); - } + assertSafeAccessAlias(alias); } function missingUserSecretDefinitionRuntimeBinding( @@ -1966,9 +1986,7 @@ export function secretService(db: Db | DbTransaction) { const normalized: AgentEnvConfig = {}; for (const [key, rawBinding] of Object.entries(record)) { - if (!ENV_KEY_RE.test(key)) { - throw unprocessable(`Invalid environment variable name: ${key}`); - } + assertSafeEnvName(key); const parsed = envBindingSchema.safeParse(rawBinding); if (!parsed.success) { @@ -2011,6 +2029,10 @@ export function secretService(db: Db | DbTransaction) { opts?: NormalizeAdapterConfigOptions, ) { const normalized = { ...adapterConfig }; + for (const [key, rawValue] of Object.entries(adapterConfig)) { + if (!key.startsWith(AGENT_ACCESS_CONFIG_PATH_PREFIX) || rawValue === undefined) continue; + assertSafeAccessAlias(key.slice(AGENT_ACCESS_CONFIG_PATH_PREFIX.length)); + } if (Object.prototype.hasOwnProperty.call(adapterConfig, "env")) { normalized.env = await normalizeEnvConfig(companyId, adapterConfig.env, opts); } @@ -5343,6 +5365,13 @@ export function secretService(db: Db | DbTransaction) { const manifest: RuntimeSecretManifestEntry[] = []; for (const [key, rawBinding] of Object.entries(record)) { + if (looksLikeCredentialToken(key)) { + logger.warn( + { companyId }, + "skipping legacy credential-shaped environment variable name during runtime env resolution", + ); + continue; + } if (!ENV_KEY_RE.test(key)) { throw unprocessable(`Invalid environment variable name: ${key}`); } @@ -5746,6 +5775,13 @@ export function secretService(db: Db | DbTransaction) { } else { const env: Record = {}; for (const [key, rawBinding] of Object.entries(record)) { + if (looksLikeCredentialToken(key)) { + logger.warn( + { companyId }, + "skipping legacy credential-shaped environment variable name during runtime adapter resolution", + ); + continue; + } if (!ENV_KEY_RE.test(key)) { throw unprocessable(`Invalid environment variable name: ${key}`); } diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 7748303d873..709f3a9739c 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -279,7 +279,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "f1f6eb0b6156bbdaa6d1da8973bf567245831744", + "packages/shared/src/index.ts": "a22ae2c4f2de39d75bdeac3ba0c81ce32ed67b1a", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -517,7 +517,7 @@ "packages/shared/src/validators/folder.ts": "b486444ab09ec3d5a9afec7dbd2e71c1bc2beb67", "packages/shared/src/validators/goal.ts": "602724134915e1e83c50115abba36b288c0abd3d", "packages/shared/src/validators/inbox-agent-policy.ts": "29cef157f4d9b564fd813868038aa8c813df4a7b", - "packages/shared/src/validators/index.ts": "25a142aeffc3b395993347c2d7bb0538738fefc3", + "packages/shared/src/validators/index.ts": "e5cc6c6d323e97ed17c16ed20ad3a9371fbb0727", "packages/shared/src/validators/instance.test.ts": "a8eac3e9a6eed97d6aa4f54e14e77c44720600af", "packages/shared/src/validators/instance.ts": "9cfe716ebf4dc1e24324e162ca096cdacbe97c4a", "packages/shared/src/validators/issue-chat-bootstrap.test.ts": "e1ebb9aa94da22c825bc3ddd32ce2cfc98bfe645", @@ -541,7 +541,7 @@ "packages/shared/src/validators/runtime-exposure.ts": "362cfc4721581beb4f495987bde60028e6f390f0", "packages/shared/src/validators/search.ts": "3b81dae383682c42f0582b644009b520da4031dc", "packages/shared/src/validators/secret.test.ts": "f25c85d91374c77885a775c8100555f2ebc92d36", - "packages/shared/src/validators/secret.ts": "746be54ac08ea676e608308d49dd75bcf2b83806", + "packages/shared/src/validators/secret.ts": "f2a7af9a0a1c571e6934b05535949b61a752bcbf", "packages/shared/src/validators/sidebar-preferences.ts": "7d950abbd95fcdbf9f7e25191a349e29000a7a2d", "packages/shared/src/validators/skill-policy.test.ts": "b9d74af4d8aecfc08db9be8993231e0e10a45179", "packages/shared/src/validators/skill-policy.ts": "7a6233776c17c4e83cbe7d6a9552638428c1c53c", diff --git a/ui/src/components/AgentConfigForm.test.ts b/ui/src/components/AgentConfigForm.test.ts index d0cc530bcad..0011b88e448 100644 --- a/ui/src/components/AgentConfigForm.test.ts +++ b/ui/src/components/AgentConfigForm.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import type { Environment } from "@paperclipai/shared"; import { + resolveEffectiveAgentEnv, resolvePaperclipRunnerTransitionModel, supportsAdapterModelRefresh, } from "./AgentConfigForm"; @@ -89,3 +90,28 @@ describe("resolveForcedKubernetesEnvironment", () => { expect(result.kubernetesEnvironment).toBeNull(); }); }); + +describe("resolveEffectiveAgentEnv", () => { + it("treats an explicit overlay env: undefined (all variables removed) as empty instead of restoring saved env", () => { + const savedAdapterConfig = { + env: { OLD_VAR: { type: "plain", value: "stale" } }, + }; + const clearedOverlay = { env: undefined }; + expect(resolveEffectiveAgentEnv(clearedOverlay, savedAdapterConfig, null)).toEqual({}); + }); + + it("falls back to saved env only when overlay does not own env", () => { + const savedAdapterConfig = { + env: { KEPT_VAR: { type: "plain", value: "kept" } }, + }; + expect(resolveEffectiveAgentEnv({}, savedAdapterConfig, null)).toEqual(savedAdapterConfig.env); + }); + + it("prefers freshly flushed env over both overlay and saved env", () => { + const savedAdapterConfig = { + env: { OLD_VAR: { type: "plain", value: "stale" } }, + }; + const flushed = { NEW_VAR: { type: "plain" as const, value: "fresh" } }; + expect(resolveEffectiveAgentEnv({ env: undefined }, savedAdapterConfig, flushed)).toEqual(flushed); + }); +}); diff --git a/ui/src/components/AgentConfigForm.tsx b/ui/src/components/AgentConfigForm.tsx index 37debe807ea..8ccc88bb8c4 100644 --- a/ui/src/components/AgentConfigForm.tsx +++ b/ui/src/components/AgentConfigForm.tsx @@ -28,6 +28,7 @@ import type { EnvBinding, EnvSecretRefBinding, Environment, + SecretVersionSelector, } from "@paperclipai/shared"; import { AGENT_DEFAULT_MAX_CONCURRENT_RUNS, supportedEnvironmentDriversForAdapter, isValidBrowserCode, ADAPTER_AUTH_MISSING_CHECK_CODE } from "@paperclipai/shared"; import type { AdapterModel } from "../api/agents"; @@ -92,7 +93,15 @@ import { type EnvironmentVariablesEditorHandle, } from "./environment-variables-editor"; import { buildFixedClaudeOAuthBinding, CLAUDE_OAUTH_TOKEN_ENV_KEY } from "./environment-variables-editor/model"; -import { AgentSecretAccessEditor } from "./AgentSecretAccessEditor"; +import { AgentSecretAccessEditor, type BindAsEnvVarRequest } from "./AgentSecretAccessEditor"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; import { useProposalReview } from "../pages/secrets/proposal-review"; import { AGENT_ACCESS_CONFIG_PATH_PREFIX } from "../lib/secret-delivery"; import { shouldShowLegacyWorkingDirectoryField } from "../lib/legacy-agent-config"; @@ -186,6 +195,18 @@ const emptyOverlay: AgentConfigOverlay = { /** Stable empty object used as fallback for missing env config to avoid new-object-per-render. */ const EMPTY_ENV: Record = {}; +export function resolveEffectiveAgentEnv( + overlayAdapterConfig: Record, + savedAdapterConfig: Record | null | undefined, + flushedEnv?: Record | null, +): Record { + if (flushedEnv !== undefined && flushedEnv !== null) return flushedEnv; + if (Object.prototype.hasOwnProperty.call(overlayAdapterConfig, "env")) { + return (overlayAdapterConfig.env as Record | undefined) ?? EMPTY_ENV; + } + return (savedAdapterConfig?.env as Record | undefined) ?? EMPTY_ENV; +} + export function supportsAdapterModelRefresh(adapterType: string): boolean { return adapterType === "claude_local" || adapterType === "codex_local" || adapterType === "paperclip_runner" || adapterType === "opencode_local"; } @@ -483,6 +504,14 @@ export function AgentConfigForm(props: AgentConfigFormProps) { queryClient.invalidateQueries({ queryKey: queryKeys.secrets.list(selectedCompanyId) }); }, }); + const rotateSecret = useMutation({ + mutationFn: (input: { secretId: string; value: string }) => + secretsApi.rotate(input.secretId, { value: input.value }), + onSuccess: () => { + if (!selectedCompanyId) return; + queryClient.invalidateQueries({ queryKey: queryKeys.secrets.list(selectedCompanyId) }); + }, + }); const uploadMarkdownImage = useMutation({ mutationFn: async ({ file, namespace }: { file: File; namespace: string }) => { @@ -572,7 +601,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) { } function flushEnvironmentDraft() { - return environmentVariablesEditorRef.current?.flushPendingDraft() ?? null; + return environmentVariablesEditorRef.current?.flushPendingDraft() ?? { status: "clean" as const }; } /** @@ -598,6 +627,81 @@ export function AgentConfigForm(props: AgentConfigFormProps) { }); }, [isCreate, !isCreate ? props.agent : undefined]); // eslint-disable-line react-hooks/exhaustive-deps + const [pendingEnvBindConflict, setPendingEnvBindConflict] = useState<{ + binding: BindAsEnvVarRequest; + availableEnvKey: string; + existingKind: "plain" | "secret_ref" | "user_secret_ref"; + } | null>(null); + + const commitSecretEnvBinding = useCallback(( + envKey: string, + secretId: string, + version: SecretVersionSelector, + baseEnvOverride?: Record | null, + ) => { + if (isCreate) return; + setOverlay((prev) => { + const existingEnv = resolveEffectiveAgentEnv( + prev.adapterConfig, + props.agent.adapterConfig as Record | null | undefined, + baseEnvOverride, + ); + return { + ...prev, + adapterConfig: { + ...prev.adapterConfig, + env: { + ...existingEnv, + [envKey]: { + type: "secret_ref", + secretId, + version, + }, + }, + }, + }; + }); + }, [isCreate, !isCreate ? props.agent : undefined]); // eslint-disable-line react-hooks/exhaustive-deps + + const bindSecretAsEnvVar = useCallback((binding: BindAsEnvVarRequest) => { + if (isCreate) return; + const flushResult = flushEnvironmentDraft(); + if (flushResult.status === "blocked") return; + const flushedEnv = flushResult.status === "flushed" ? flushResult.value : null; + const currentEnv = resolveEffectiveAgentEnv( + overlay.adapterConfig, + props.agent.adapterConfig as Record | null | undefined, + flushedEnv, + ); + const existing = Object.prototype.hasOwnProperty.call(currentEnv, binding.envKey) + ? currentEnv[binding.envKey] + : undefined; + const alreadySameSecret = + typeof existing === "object" && + existing !== null && + existing.type === "secret_ref" && + existing.secretId === binding.secretId; + if (existing !== undefined && !alreadySameSecret && !binding.replaceExisting) { + let suffix = 2; + while (Object.prototype.hasOwnProperty.call(currentEnv, `${binding.envKey}_${suffix}`)) { + suffix += 1; + } + const existingKind = + typeof existing === "object" && existing !== null && existing.type === "secret_ref" + ? "secret_ref" + : typeof existing === "object" && existing !== null && existing.type === "user_secret_ref" + ? "user_secret_ref" + : "plain"; + setPendingEnvBindConflict({ + binding, + availableEnvKey: `${binding.envKey}_${suffix}`, + existingKind, + }); + return; + } + commitSecretEnvBinding(binding.envKey, binding.secretId, binding.version, flushedEnv); + }, [isCreate, overlay.adapterConfig, !isCreate ? props.agent : undefined, commitSecretEnvBinding]); // eslint-disable-line react-hooks/exhaustive-deps + /** Build accumulated patch and send to parent */ const handleCancel = useCallback(() => { setOverlay({ ...emptyOverlay }); @@ -607,7 +711,9 @@ export function AgentConfigForm(props: AgentConfigFormProps) { const handleSave = useCallback(async () => { if (isCreate) return; - const flushedEnv = flushEnvironmentDraft(); + const flushResult = flushEnvironmentDraft(); + if (flushResult.status === "blocked") return; + const flushedEnv = flushResult.status === "flushed" ? flushResult.value : null; const nextOverlay = flushedEnv ? { ...overlay, @@ -640,6 +746,10 @@ export function AgentConfigForm(props: AgentConfigFormProps) { // ---- Resolve values ---- const config = !isCreate ? ((props.agent.adapterConfig ?? {}) as Record) : {}; + const effectiveSecretsAdapterConfig = useMemo( + () => ({ ...config, ...overlay.adapterConfig }), + [config, overlay.adapterConfig], + ); const runtimeConfig = !isCreate ? ((props.agent.runtimeConfig ?? {}) as Record) : {}; const runtimeOverlay = overlay.runtime.runtimeConfig as Record | undefined; const currentAiConnection = (runtimeOverlay ?? runtimeConfig).aiConnection; @@ -777,7 +887,9 @@ export function AgentConfigForm(props: AgentConfigFormProps) { // existing agent's own page fails to save the binding. const handleClaudeLoginStoredEdit = async () => { if (isCreate) return; - const flushedEnv = flushEnvironmentDraft(); + const flushResult = flushEnvironmentDraft(); + if (flushResult.status === "blocked") return; + const flushedEnv = flushResult.status === "flushed" ? flushResult.value : null; const baseEnv = flushedEnv ?? (eff("adapterConfig", "env", (config.env ?? EMPTY_ENV) as Record)); @@ -806,7 +918,9 @@ export function AgentConfigForm(props: AgentConfigFormProps) { // secret-reference binding through the normal agent-update patch. const handleCodexAccountBindingEdit = async (claim: CodexAccountBindingClaim) => { if (isCreate || !claim.companyIdentityDiffers) return; - const flushedEnv = flushEnvironmentDraft(); + const flushResult = flushEnvironmentDraft(); + if (flushResult.status === "blocked") return; + const flushedEnv = flushResult.status === "flushed" ? flushResult.value : null; const baseEnv = flushedEnv ?? (eff("adapterConfig", "env", (config.env ?? EMPTY_ENV) as Record)); @@ -859,7 +973,9 @@ export function AgentConfigForm(props: AgentConfigFormProps) { // pending editor draft first and keep every unrelated binding. const handleApplyStoredClaudeLoginEdit = async () => { if (isCreate) return; - const flushedEnv = flushEnvironmentDraft(); + const flushResult = flushEnvironmentDraft(); + if (flushResult.status === "blocked") return; + const flushedEnv = flushResult.status === "flushed" ? flushResult.value : null; const baseEnv = flushedEnv ?? (eff("adapterConfig", "env", (config.env ?? EMPTY_ENV) as Record)); @@ -963,10 +1079,12 @@ export function AgentConfigForm(props: AgentConfigFormProps) { && (runnerAvailability?.defaultRunner === "paperclip" || canQualifyRunnerUpgrade); const upgradeRunner = async () => { if (isCreate || runnerUpgradePending || upgradeEnvironmentChanged) return; + const flushResult = flushEnvironmentDraft(); + if (flushResult.status === "blocked") return; + const flushedEnv = flushResult.status === "flushed" ? flushResult.value : null; const agentId = props.agent.id; setRunnerUpgrade({ agentId, status: "pending" }); try { - const flushedEnv = flushEnvironmentDraft(); const nextOverlay = flushedEnv ? { ...overlay, adapterConfig: { ...overlay.adapterConfig, env: flushedEnv } } : overlay; @@ -1215,7 +1333,11 @@ export function AgentConfigForm(props: AgentConfigFormProps) { if (!selectedCompanyId) { throw new Error("Select an organization to test adapter environment"); } - const flushedEnv = flushEnvironmentDraft(); + const flushResult = flushEnvironmentDraft(); + if (flushResult.status === "blocked") { + throw new Error(flushResult.reason); + } + const flushedEnv = flushResult.status === "flushed" ? flushResult.value : null; const adapterConfigPatch = flushedEnv ? { env: flushedEnv } : undefined; // Probe where a real run would actually execute: the agent's own // environment, else the instance default. Testing the host for an @@ -1609,6 +1731,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) { const created = await createSecret.mutateAsync({ name, value }); return created; }} + onRotateSecret={(secretId, value) => rotateSecret.mutateAsync({ secretId, value })} onChange={(env) => isCreate ? set!({ envBindings: env ?? {}, envVars: "" }) @@ -1652,15 +1775,76 @@ export function AgentConfigForm(props: AgentConfigFormProps) {

{help.secretAccess}

createSecret.mutateAsync({ name, value })} + onRotateSecret={(secretId, value) => rotateSecret.mutateAsync({ secretId, value })} + onBindAsEnvVar={bindSecretAsEnvVar} proposals={agentBindingProposals} onApproveProposal={proposalReview.requestApprove} onRejectProposal={proposalReview.requestReject} /> {proposalReview.dialogs} + { + if (!open) setPendingEnvBindConflict(null); + }} + > + + + Environment variable already exists + + {pendingEnvBindConflict?.binding.envKey} is already set as{" "} + {pendingEnvBindConflict?.existingKind === "secret_ref" + ? "another company secret" + : pendingEnvBindConflict?.existingKind === "user_secret_ref" + ? "a user secret" + : "a plain value"} + . Choose {pendingEnvBindConflict?.availableEnvKey} to keep the + existing variable, or confirm replacing it. + + + + +
+ + +
+
+
+
diff --git a/ui/src/components/AgentSecretAccessEditor.test.tsx b/ui/src/components/AgentSecretAccessEditor.test.tsx index 9078713752b..0b31c03baec 100644 --- a/ui/src/components/AgentSecretAccessEditor.test.tsx +++ b/ui/src/components/AgentSecretAccessEditor.test.tsx @@ -264,4 +264,144 @@ describe("AgentSecretAccessEditor component", () => { flushSync(() => rejectButton.click()); expect(rejected).toEqual(["prop-1"]); }); + + it("explains that API-access secrets are not exposed as $NAME env vars and offers a quick bind-as-env-var action", () => { + const boundEnv: Array<{ envKey: string; secretId: string; version: number | "latest" }> = []; + render( + {}} + onBindAsEnvVar={(binding) => boundEnv.push(binding)} + />, + ); + + // Clarifies that processes/scripts will not see $NAME unless bound under Environment variables. + expect(container.textContent).toMatch(/\$NAME|\$STRIPE_KEY/); + expect(container.textContent?.toLowerCase()).toContain("environment variables"); + + const bindEnvButton = [...container.querySelectorAll("button")].find((button) => + button.textContent?.includes("Also bind as env var"), + ); + expect(bindEnvButton, "Also bind as env var action should render for API-only binding").toBeTruthy(); + flushSync(() => bindEnvButton!.click()); + expect(boundEnv).toEqual([{ envKey: "STRIPE_KEY", secretId: "s1", version: "latest" }]); + }); + + it("asks before replacing an occupied env var name on Also bind as env var", () => { + const boundEnv: Array<{ envKey: string; secretId: string; version: number | "latest"; replaceExisting?: boolean }> = []; + render( + {}} + onBindAsEnvVar={(binding) => boundEnv.push(binding)} + />, + ); + + const bindEnvButton = [...container.querySelectorAll("button")].find((button) => + button.textContent?.includes("Also bind as env var"), + )!; + flushSync(() => bindEnvButton.click()); + // Must not silently overwrite the occupied env var. + expect(boundEnv).toEqual([]); + expect(container.textContent).toContain("$STRIPE_KEY already exists"); + + // Option 1: pick the unused fallback name. + const fallbackButton = [...container.querySelectorAll("button")].find((button) => + button.textContent?.includes("Bind as STRIPE_KEY_2"), + )!; + flushSync(() => fallbackButton.click()); + expect(boundEnv).toEqual([{ envKey: "STRIPE_KEY_2", secretId: "s1", version: "latest" }]); + + // Option 2: explicitly confirm replacing the occupied name. + flushSync(() => bindEnvButton.click()); + const replaceButton = [...container.querySelectorAll("button")].find((button) => + button.textContent?.includes("Replace STRIPE_KEY"), + )!; + flushSync(() => replaceButton.click()); + expect(boundEnv.at(-1)).toEqual({ + envKey: "STRIPE_KEY", + secretId: "s1", + version: "latest", + replaceExisting: true, + }); + }); + + it("copies the chosen free alias's pinned version when multiple aliases reference the same secret", () => { + const boundEnv: Array<{ envKey: string; secretId: string; version: number | "latest" }> = []; + render( + {}} + onBindAsEnvVar={(binding) => boundEnv.push(binding)} + />, + ); + + const bindEnvButton = [...container.querySelectorAll("button")].find((button) => + button.textContent?.includes("Also bind as env var"), + )!; + flushSync(() => bindEnvButton.click()); + expect(boundEnv).toEqual([{ envKey: "NEW", secretId: "s1", version: 3 }]); + }); + + it("scales linearly when rendering and editing an alias across 200 secrets and bindings", () => { + const count = 200; + let secretIdReads = 0; + const maxReads = count * 20; + const largeSecrets = Array.from({ length: count }, (_, index) => { + const secret = makeSecret(`s-${index}`, `SECRET_${index}`); + let idValue = secret.id; + Object.defineProperty(secret, "id", { + enumerable: true, + get() { + secretIdReads += 1; + if (secretIdReads > maxReads) { + throw new Error(`Quadratic secret lookup detected (${secretIdReads} reads for ${count} secrets)`); + } + return idValue; + }, + set(next: string) { + idValue = next; + }, + }); + return secret; + }); + const largeConfig: Record = {}; + for (let index = 0; index < count; index += 1) { + largeConfig[`access.ALIAS_${index}`] = { type: "secret_ref", secretId: `s-${index}`, version: "latest" }; + } + + render( + {}} + onBindAsEnvVar={() => {}} + />, + ); + const readsAfterMount = secretIdReads; + expect(readsAfterMount).toBeLessThanOrEqual(count * 4); + + // Typing into one alias input must not rescan secrets per row/summary. + const aliasInput = container.querySelector('input[aria-label="Access alias"]')!; + const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")!.set!; + setter.call(aliasInput, "ALIAS_0_EDITED"); + flushSync(() => aliasInput.dispatchEvent(new Event("input", { bubbles: true }))); + expect(secretIdReads - readsAfterMount).toBeLessThanOrEqual(count * 2); + }); }); diff --git a/ui/src/components/AgentSecretAccessEditor.tsx b/ui/src/components/AgentSecretAccessEditor.tsx index d5223382e11..53ac6c0a44f 100644 --- a/ui/src/components/AgentSecretAccessEditor.tsx +++ b/ui/src/components/AgentSecretAccessEditor.tsx @@ -6,7 +6,9 @@ import type { SecretProposalView, SecretVersionSelector, } from "@paperclipai/shared"; +import { looksLikeCredentialToken } from "@paperclipai/shared"; import { cn } from "../lib/utils"; +import { ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy"; import { Input } from "@/components/ui/input"; import { Badge } from "@/components/ui/badge"; import { SecretPicker } from "./environment-variables-editor/SecretPicker"; @@ -128,7 +130,7 @@ export function rowsToAccessMap(rows: readonly AccessRow[]): Record = {}; for (const row of rows) { const alias = row.alias.trim(); - if (!alias || !SECRET_ALIAS_RE.test(alias) || !row.secretId) continue; + if (!alias || looksLikeCredentialToken(alias) || !SECRET_ALIAS_RE.test(alias) || !row.secretId) continue; map[alias] = { type: "secret_ref", secretId: row.secretId, version: row.version }; } return map; @@ -150,6 +152,13 @@ export function normalizeAccessMapKey(map: Record): /* Component */ /* -------------------------------------------------------------------------- */ +export interface BindAsEnvVarRequest { + envKey: string; + secretId: string; + version: SecretVersionSelector; + replaceExisting?: boolean; +} + export interface AgentSecretAccessEditorProps { /** Effective adapter config (env + top-level `access.*`), reflecting unsaved edits. */ config: Record; @@ -161,6 +170,10 @@ export interface AgentSecretAccessEditorProps { onChange: (next: Record) => void; /** Create a company secret from the shared picker's pinned create action. */ onCreateSecret?: (name: string, value: string) => Promise; + /** Rotate an existing company secret when a name collision occurs during creation. */ + onRotateSecret?: (secretId: string, value: string) => Promise; + /** Quick action to also expose an API-only secret binding as an environment variable. */ + onBindAsEnvVar?: (binding: BindAsEnvVarRequest) => void; disabled?: boolean; /** Pending binding proposals targeting this agent (PAP-14731). */ proposals?: readonly SecretProposalView[]; @@ -196,6 +209,8 @@ export function AgentSecretAccessEditor({ secrets, onChange, onCreateSecret, + onRotateSecret, + onBindAsEnvVar, disabled, proposals, onApproveProposal, @@ -208,12 +223,38 @@ export function AgentSecretAccessEditor({ const envBindings = useMemo(() => parseEnvSecretRefs(config), [config]); const apiBindings = useMemo(() => parseAccessGrants(config), [config]); const summaries = useMemo(() => summarizeAgentBindings(envBindings, apiBindings), [envBindings, apiBindings]); + const secretById = useMemo(() => { + const map = new Map(); + for (const secret of secrets) map.set(secret.id, secret); + return map; + }, [secrets]); + const apiBindingByAlias = useMemo(() => { + const map = new Map(); + for (const entry of apiBindings) { + map.set(entry.name, entry); + } + return map; + }, [apiBindings]); + const apiBindingBySecretId = useMemo(() => { + const map = new Map(); + for (const entry of apiBindings) { + if (!map.has(entry.secretId)) map.set(entry.secretId, entry); + } + return map; + }, [apiBindings]); + const occupiedEnvKeys = useMemo(() => new Set(Object.keys(asRecord(config?.env) ?? {})), [config]); const incomingMap = useMemo(() => rowsToAccessMap(entriesToRows(apiBindings)), [apiBindings]); const incomingKey = useMemo(() => normalizeAccessMapKey(incomingMap), [incomingMap]); const [rows, setRows] = useState(() => entriesToRows(apiBindings)); const [createRequest, setCreateRequest] = useState<{ rowId: string; name: string } | null>(null); + const [pendingEnvConflict, setPendingEnvConflict] = useState<{ + secretId: string; + envKey: string; + availableEnvKey: string; + version: SecretVersionSelector; + } | null>(null); const pickerAnchorRefs = useRef(new Map()); const lastEmittedKeyRef = useRef(incomingKey); const lastIncomingKeyRef = useRef(incomingKey); @@ -229,7 +270,15 @@ export function AgentSecretAccessEditor({ }, [incomingKey, apiBindings]); const secretName = (secretId: string): string => - secrets.find((secret) => secret.id === secretId)?.name ?? `${secretId.slice(0, 8)}…`; + secretById.get(secretId)?.name ?? `${secretId.slice(0, 8)}…`; + + function nextAvailableEnvKey(baseKey: string): string { + let suffix = 2; + while (occupiedEnvKeys.has(`${baseKey}_${suffix}`)) { + suffix += 1; + } + return `${baseKey}_${suffix}`; + } function emit(nextRows: AccessRow[]) { setRows(nextRows); @@ -266,23 +315,120 @@ export function AgentSecretAccessEditor({ {/* Overview: every secret bound to this agent + how it is delivered. */} {hasBindings ? (
- {summaries.map((summary) => ( -
- - {secretName(summary.secretId)} - {summary.envKeys.length > 0 ? : null} - {summary.apiAliases.length > 0 ? : null} - - {[ - ...summary.envKeys.map((key) => `${ENV_CONFIG_PATH_PREFIX}${key}`), - ...summary.apiAliases.map((alias) => `${AGENT_ACCESS_CONFIG_PATH_PREFIX}${alias}`), - ].join(" · ")} - -
- ))} + {summaries.map((summary) => { + const isApiOnly = summary.apiAliases.length > 0 && summary.envKeys.length === 0; + const validAliases = summary.apiAliases.filter( + (alias) => SECRET_ALIAS_RE.test(alias) && !looksLikeCredentialToken(alias), + ); + const chosenAlias = + validAliases.find((alias) => !occupiedEnvKeys.has(alias)) ?? validAliases[0] ?? null; + const derivedEnvKey = envKeyFromSecretName(secretName(summary.secretId)); + const fallbackEnvKey = + SECRET_ALIAS_RE.test(derivedEnvKey) && !looksLikeCredentialToken(derivedEnvKey) + ? derivedEnvKey + : ""; + const suggestedEnvKey = chosenAlias ?? fallbackEnvKey; + const matchingApiBinding = chosenAlias + ? apiBindingByAlias.get(chosenAlias) + : apiBindingBySecretId.get(summary.secretId); + const envKeyOccupied = Boolean(suggestedEnvKey && occupiedEnvKeys.has(suggestedEnvKey)); + const conflictForRow = + pendingEnvConflict?.secretId === summary.secretId ? pendingEnvConflict : null; + return ( +
+
+ + {secretName(summary.secretId)} + {summary.envKeys.length > 0 ? : null} + {summary.apiAliases.length > 0 ? : null} + + {[ + ...summary.envKeys.map((key) => `${ENV_CONFIG_PATH_PREFIX}${key}`), + ...summary.apiAliases.map((alias) => `${AGENT_ACCESS_CONFIG_PATH_PREFIX}${alias}`), + ].join(" · ")} + + {isApiOnly && onBindAsEnvVar && !disabled && suggestedEnvKey ? ( + + ) : null} +
+ {conflictForRow && onBindAsEnvVar ? ( +
+ + ${conflictForRow.envKey} already exists under Environment + variables. + + + + +
+ ) : null} +
+ ); + })}
) : (

No company secret references are bound to this agent yet.

@@ -332,26 +478,34 @@ export function AgentSecretAccessEditor({ {/* Editable API-access grants (access.). */}
-
- API access (no env var) +
+
+ API access (no env var) +
+

+ Processes and shell scripts will not see $NAME for API-access secrets. + To expose a secret as $NAME, bind it under Environment variables above. +

{rows.length > 0 ? (
{rows.map((row) => { const trimmedAlias = row.alias.trim(); - const aliasInvalid = Boolean(trimmedAlias) && !SECRET_ALIAS_RE.test(trimmedAlias); + const aliasLooksLikeSecret = looksLikeCredentialToken(trimmedAlias); + const aliasInvalid = Boolean(trimmedAlias) && !aliasLooksLikeSecret && !SECRET_ALIAS_RE.test(trimmedAlias); const aliasDuplicate = Boolean(trimmedAlias) && (aliasCounts.get(trimmedAlias) ?? 0) > 1; - const selectedSecret = secrets.find((secret) => secret.id === row.secretId) ?? null; + const selectedSecret = secretById.get(row.secretId) ?? null; return (
patchRow(row.id, { alias: event.target.value })} onBlur={(event) => { const next = event.target.value.trim(); - if (next && !SECRET_ALIAS_RE.test(next)) { + if (next && !looksLikeCredentialToken(next) && !SECRET_ALIAS_RE.test(next)) { const suggested = envKeyFromSecretName(next); if (suggested && suggested !== next) patchRow(row.id, { alias: suggested }); } @@ -361,7 +515,8 @@ export function AgentSecretAccessEditor({ disabled={disabled} className={cn( "h-9 font-mono text-sm", - (aliasInvalid || aliasDuplicate) && "border-destructive text-destructive", + aliasLooksLikeSecret && ANALYTICS_NO_CAPTURE_CLASS, + (aliasLooksLikeSecret || aliasInvalid || aliasDuplicate) && "border-destructive text-destructive", )} />
@@ -425,7 +580,7 @@ export function AgentSecretAccessEditor({ secret.name)} + existingSecrets={secrets} onCancel={() => setCreateRequest(null)} onSubmit={async (name, value) => { const created = await onCreateSecret(name, value); @@ -436,6 +591,25 @@ export function AgentSecretAccessEditor({ }); setCreateRequest(null); }} + onSelectExisting={(existing) => { + patchRow(row.id, { + secretId: existing.id, + version: "latest", + alias: row.alias.trim() || envKeyFromSecretName(existing.name), + }); + setCreateRequest(null); + }} + onRotateExisting={onRotateSecret + ? async (existing, value) => { + const rotated = await onRotateSecret(existing.id, value); + patchRow(row.id, { + secretId: rotated.id, + version: "latest", + alias: row.alias.trim() || envKeyFromSecretName(rotated.name), + }); + setCreateRequest(null); + } + : undefined} /> ) : null} @@ -476,7 +650,11 @@ export function AgentSecretAccessEditor({
- {aliasInvalid ? ( + {aliasLooksLikeSecret ? ( +

+ Looks like a secret value — enter an alias name (e.g. GH_TOKEN), not the token itself +

+ ) : aliasInvalid ? (

Invalid alias — use letters, digits and _

diff --git a/ui/src/components/ProjectProperties.tsx b/ui/src/components/ProjectProperties.tsx index 28a56780767..c95de020f62 100644 --- a/ui/src/components/ProjectProperties.tsx +++ b/ui/src/components/ProjectProperties.tsx @@ -261,6 +261,14 @@ export function ProjectProperties({ project, repositories, onUpdate, onFieldUpda queryClient.invalidateQueries({ queryKey: queryKeys.secrets.list(selectedCompanyId) }); }, }); + const rotateSecret = useMutation({ + mutationFn: (input: { secretId: string; value: string }) => + secretsApi.rotate(input.secretId, { value: input.value }), + onSuccess: () => { + if (!selectedCompanyId) return; + queryClient.invalidateQueries({ queryKey: queryKeys.secrets.list(selectedCompanyId) }); + }, + }); // PAP-749 task 1d: members populate the decision owner picker. const { data: companyMembers } = useQuery({ queryKey: queryKeys.access.companyMembers(selectedCompanyId ?? ""), @@ -551,6 +559,7 @@ export function ProjectProperties({ project, repositories, onUpdate, onFieldUpda const created = await createSecret.mutateAsync({ name, value }); return created; }} + onRotateSecret={(secretId, value) => rotateSecret.mutateAsync({ secretId, value })} onChange={(env) => commitField("env", { env: env ?? null })} /> diff --git a/ui/src/components/environment-variables-editor/CreateSecretPopover.tsx b/ui/src/components/environment-variables-editor/CreateSecretPopover.tsx index fa1b090eaa1..adc2bc314d6 100644 --- a/ui/src/components/environment-variables-editor/CreateSecretPopover.tsx +++ b/ui/src/components/environment-variables-editor/CreateSecretPopover.tsx @@ -1,5 +1,6 @@ -import { useState } from "react"; +import { useMemo, useState } from "react"; import { Eye, EyeOff, Loader2 } from "lucide-react"; +import type { CompanySecret } from "@paperclipai/shared"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy"; @@ -18,9 +19,15 @@ export interface SecretPopoverFormProps { initialValue: string; /** For a same-name uniqueness hint before the server round-trips. */ existingSecretNames?: readonly string[]; + /** Existing company secrets so name collisions can bind or rotate instead of dead-ending. */ + existingSecrets?: readonly CompanySecret[]; onCancel: () => void; /** Resolves once the secret is created + the row is bound; rejects with a message. */ onSubmit: (name: string, value: string) => Promise; + /** Bind the row to an existing secret when its name already exists. */ + onSelectExisting?: (secret: CompanySecret) => void | Promise; + /** Rotate an existing secret with the typed value and bind the row. */ + onRotateExisting?: (secret: CompanySecret, value: string) => Promise; } /** @@ -33,8 +40,11 @@ export function SecretPopoverForm({ initialName, initialValue, existingSecretNames, + existingSecrets, onCancel, onSubmit, + onSelectExisting, + onRotateExisting, }: SecretPopoverFormProps) { const [name, setName] = useState(initialName); const [value, setValue] = useState(initialValue); @@ -42,18 +52,70 @@ export function SecretPopoverForm({ const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(null); const [touched, setTouched] = useState(false); + const [selectedAmbiguousId, setSelectedAmbiguousId] = useState(null); + + const { existingSecretByExactName, existingSecretsByLowerName } = useMemo(() => { + const byExact = new Map(); + const byLower = new Map(); + for (const secret of existingSecrets ?? []) { + const secretName = secret.name; + if (!byExact.has(secretName)) byExact.set(secretName, secret); + const lowerKey = secretName.toLowerCase(); + const bucket = byLower.get(lowerKey); + if (bucket) { + bucket.push(secret); + } else { + byLower.set(lowerKey, [secret]); + } + } + return { existingSecretByExactName: byExact, existingSecretsByLowerName: byLower }; + }, [existingSecrets]); + + const existingSecretNameSet = useMemo( + () => + existingSecrets + ? new Set() + : new Set((existingSecretNames ?? []).map((existing) => existing.toLowerCase())), + [existingSecrets, existingSecretNames], + ); const trimmedName = name.trim(); + const normalizedName = trimmedName.toLowerCase(); + const exactMatch = trimmedName.length > 0 ? (existingSecretByExactName.get(trimmedName) ?? null) : null; + const lowerMatches = normalizedName.length > 0 ? (existingSecretsByLowerName.get(normalizedName) ?? []) : []; + const ambiguousMatches = !exactMatch && lowerMatches.length > 1 ? lowerMatches : []; + const selectedAmbiguousSecret = + ambiguousMatches.length > 1 && selectedAmbiguousId + ? (ambiguousMatches.find((candidate) => candidate.id === selectedAmbiguousId) ?? null) + : null; + const matchingSecret = + exactMatch ?? (lowerMatches.length === 1 ? lowerMatches[0]! : selectedAmbiguousSecret); + const hasNameCollision = Boolean(exactMatch || lowerMatches.length > 0); + const existingIsActive = matchingSecret?.status === "active"; + const canRecoverCollision = Boolean(onSelectExisting || onRotateExisting); + const hasCollisionActions = Boolean(hasNameCollision && canRecoverCollision); + const canUseExisting = Boolean(matchingSecret && onSelectExisting && existingIsActive); + const canRotateExisting = Boolean( + matchingSecret && + onRotateExisting && + value.length > 0 && + matchingSecret.managedMode !== "external_reference" && + existingIsActive, + ); + const nameError = (() => { if (!trimmedName) return touched ? "Name is required" : null; if (!SECRET_NAME_RE.test(trimmedName)) return "Use lowercase letters, digits and _"; - if (existingSecretNames?.some((existing) => existing.toLowerCase() === trimmedName)) { + if (hasNameCollision) { + return hasCollisionActions ? null : "A secret with this name already exists"; + } + if (existingSecretNameSet.has(normalizedName)) { return "A secret with this name already exists"; } return null; })(); const valueError = value.length === 0 ? (touched ? "Value is required" : null) : null; - const canSubmit = !submitting && trimmedName.length > 0 && value.length > 0 && !nameError; + const canSubmit = !submitting && !hasNameCollision && trimmedName.length > 0 && value.length > 0 && !nameError; async function handleSubmit() { setTouched(true); @@ -68,6 +130,30 @@ export function SecretPopoverForm({ } } + async function handleUseExisting() { + if (!matchingSecret || !canUseExisting || !onSelectExisting || submitting) return; + setSubmitting(true); + setError(null); + try { + await onSelectExisting(matchingSecret); + } catch (selectError) { + setError(selectError instanceof Error ? selectError.message : "Failed to bind existing secret"); + setSubmitting(false); + } + } + + async function handleRotateExisting() { + if (!matchingSecret || !onRotateExisting || !canRotateExisting || submitting) return; + setSubmitting(true); + setError(null); + try { + await onRotateExisting(matchingSecret, value); + } catch (rotateError) { + setError(rotateError instanceof Error ? rotateError.message : "Failed to save new secret version"); + setSubmitting(false); + } + } + const ctaLabel = mode === "create" ? "Create & bind" : "Store & bind"; const heading = mode === "create" ? "Create secret" : "Store value as secret"; @@ -93,7 +179,10 @@ export function SecretPopoverForm({ placeholder="secret_name" aria-label="Secret name" aria-invalid={nameError ? true : undefined} - onChange={(event) => setName(event.target.value)} + onChange={(event) => { + setName(event.target.value); + setSelectedAmbiguousId(null); + }} onBlur={() => setTouched(true)} onKeyDown={(event) => { if (event.key === "Enter") { @@ -105,6 +194,85 @@ export function SecretPopoverForm({ {nameError ? {nameError} : null} + {hasCollisionActions ? ( +
+ {ambiguousMatches.length > 1 ? ( + <> +

+ Multiple secrets match {trimmedName} with different + casing. Choose which secret to use, or enter a different name: +

+
+ {ambiguousMatches.map((candidate) => { + const isSelected = matchingSecret?.id === candidate.id; + return ( + + ); + })} +
+ + ) : null} + {matchingSecret ? ( + <> + {existingIsActive ? ( +

+ {matchingSecret.name} already exists (v + {matchingSecret.latestVersion}).{" "} + {canRotateExisting + ? "Reuse it, save this value as a new version, or choose a different name." + : "Reuse it or choose a different name."} +

+ ) : ( +

+ {matchingSecret.name} already exists, but it is{" "} + {matchingSecret.status}. Re-enable it in Secrets before reusing it, or choose a different name. +

+ )} +
+ {onSelectExisting ? ( + + ) : null} + {canRotateExisting ? ( + + ) : null} +
+ + ) : null} +
+ ) : null} +