mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
fix(secrets): add env-name secret guardrails, collision recovery, and API-access clarity (#22982)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Operators configure agent and environment secrets across Environment
variables and Secret access settings
> - Three common mistakes currently fail poorly or leak credentials:
pasting a token into an environment variable name passes validation and
leaks into run settings and logs, converting a plain environment
variable onto an existing secret name dead-ends with a disabled submit
button, and adding an API-access secret does not clarify that processes
will not see `$NAME` unless it is also bound as an environment variable
> - Secret configuration should prevent credential leaks by default and
recover cleanly from common setup mistakes
> - This pull request rejects and redacts secret-shaped environment
variable names and access aliases across shared, server, and UI layers,
adds "Use existing secret" and "Save as new version" recovery actions on
secret name collisions, and explains API-only vs `$NAME` delivery with
an "Also bind as env var" quick action
> - The benefit is safer secret handling with zero raw token leaks in
errors, settings, or logs and a smoother operator workflow
## Linked Issues or Issue Description
**What happened?**
Three issues occur when operators configure agent and environment
secrets:
1. Pasting a credential token (for example `github_pat_...`, `ghp_...`,
or `sk-...`) into an environment variable Name field passes
`^[A-Za-z_][A-Za-z0-9_]*$` for underscore-based tokens (such as
`github_pat_...` and `ghp_...`) or echoes the raw token in the server
error message for dashed tokens (such as `sk-...`). Existing redactors
also scrub only values, not secret-shaped object keys, so legacy or
rejected payloads leak the token in run settings and logs.
2. Converting a plain environment variable to a secret via
`ConvertToSecretPopover` (or creating a secret via
`CreateSecretPopover`) disables submission with `"A secret with this
name already exists"` whenever the suggested name already exists,
forcing the operator to cancel and switch flows manually.
3. Binding a secret under `Secret access > API access (no env var)` does
not state clearly that agent processes and shell scripts will not see
`$NAME` unless the secret is also bound under Environment variables, and
provides no quick action to add the matching environment variable
binding.
**Expected behavior**
1. Both UI and server reject secret-shaped environment variable names
and access aliases with an actionable error that never echoes the token,
mask accidental token input immediately in the UI, and redact
secret-shaped keys in adapter configs, event payloads, command/text
redaction, and HTTP 4xx/5xx request logs.
2. When a secret name already exists in `CreateSecretPopover` /
`ConvertToSecretPopover`, the popover lets the operator bind the
existing secret directly or save the typed value as a new version
(rotate) without dead-ending.
3. `AgentSecretAccessEditor` clearly explains that API-access secrets
are not injected as `$NAME` in the process environment and offers an
`"Also bind as env var"` quick action for API-only bindings.
**Steps to reproduce**
1. Open an agent's Secrets & variables settings and paste a GitHub
fine-grained PAT (`github_pat_...`) into an environment variable Name
field and save; observe that it is accepted and returned verbatim in
redacted adapter config / logs.
2. Create a company secret named `gh_token`, then add a plain env var
`GH_TOKEN` with a value and click "Store as secret"; observe the
disabled `"Store & bind"` dead end.
3. Bind a secret under `Secret access > API access (no env var)` and
observe that no guidance mentions `$NAME` visibility for
processes/scripts and no quick action exists to also bind it as an
environment variable.
**Paperclip version or commit**
Reproduced on `origin/master` commit
`2d065677959b585065ff3fec8718156a4cf6f41d`.
## What Changed
- **Shared credential-token detection
(`packages/shared/src/validators/secret.ts`,
`packages/shared/src/validators/index.ts`,
`packages/shared/src/index.ts`)**: Exported `ENV_VAR_NAME_RE`,
`looksLikeCredentialToken`, `SECRET_SHAPED_ENV_NAME_ERROR`, and
`SECRET_SHAPED_ACCESS_ALIAS_ERROR` as a single source of truth shared by
`adapter-utils`, `server`, and `ui`. Updated pinned registry
`tests/runner-e2e/source-sdk-public-inputs.json`.
- **Server validation and defense-in-depth redaction
(`server/src/services/secrets.ts`, `server/src/redaction.ts`,
`server/src/middleware/redact-sensitive.ts`,
`packages/adapter-utils/src/command-redaction.ts`)**:
- Rejected credential-shaped env var names and `access.*` aliases in
`normalizeEnvConfig`, `normalizeAdapterConfigForPersistenceInternal`,
`assertSecretBindingConfigPath`, `resolveEnvBindings`, and
`resolveAdapterConfigForRuntime` without echoing the raw token.
- Redacted secret-shaped object keys in `redactAgentAdapterConfig`,
`sanitizeRecord`, and HTTP log `redactSensitive`, and expanded
`command-redaction.ts` / `redaction.ts` token patterns and hints to
cover `github_pat_`, `sk_live_`/`sk_test_`, `rk_live_`/`rk_test_`, Slack
(`xox*-`), AWS (`AKIA`/`ASIA`), Google (`AIza`), and GitLab (`glpat-`)
tokens.
- **UI env-name guardrails
(`ui/src/components/environment-variables-editor/sensitive.ts`,
`model.ts`, `Row.tsx`, `index.tsx`,
`ui/src/components/AgentSecretAccessEditor.tsx`)**:
- Flagged credential-shaped variable names and access aliases
immediately with an inline error, masked the input (`type="password"` +
`ANALYTICS_NO_CAPTURE_CLASS`), redacted credential-shaped names in the
unsaved-changes summary, disabled inline Save while present, and dropped
credential-shaped aliases from emitted access maps.
- **Plain-to-secret collision recovery
(`ui/src/components/environment-variables-editor/CreateSecretPopover.tsx`,
`Row.tsx`, `index.tsx`, `ui/src/components/AgentSecretAccessEditor.tsx`,
`ui/src/components/AgentConfigForm.tsx`,
`ui/src/pages/CompanyEnvironments.tsx`,
`ui/src/components/ProjectProperties.tsx`)**:
- Replaced the dead-end duplicate-name error in `SecretPopoverForm` with
an inline recovery panel offering `"Use existing secret"` and `"Save as
new version"` (when active and rotatable), wired to `secretsApi.rotate`
across agent, environment, and project editors.
- **API-access vs `$NAME` clarity
(`ui/src/components/AgentSecretAccessEditor.tsx`,
`ui/src/lib/secret-delivery.ts`,
`ui/src/components/AgentConfigForm.tsx`)**:
- Clarified under `API access (no env var)` that processes and shell
scripts will not see `$NAME` unless bound under Environment variables
above, and added an `"Also bind as env var"` quick action on API-only
secret summaries wired to `AgentConfigForm`.
- **Tests**: Extended existing owner suites
(`server/src/__tests__/redaction.test.ts`,
`server/src/__tests__/redact-sensitive.test.ts`,
`server/src/__tests__/agents-adapter-config-user-secret.test.ts`,
`ui/src/components/environment-variables-editor/model.test.ts`,
`ui/src/components/environment-variables-editor/EnvironmentVariablesEditor.test.tsx`,
`ui/src/components/AgentSecretAccessEditor.test.tsx`).
## Verification
- `pnpm vitest run
ui/src/components/environment-variables-editor/EnvironmentVariablesEditor.test.tsx
ui/src/components/AgentSecretAccessEditor.test.tsx
ui/src/components/environment-variables-editor/model.test.ts
ui/src/components/environment-variables-editor/sensitive.test.ts
server/src/__tests__/redaction.test.ts
server/src/__tests__/redact-sensitive.test.ts` — 6 files, 149/149
passed.
- `pnpm vitest run --hookTimeout=120000 --testTimeout=120000
server/src/__tests__/agents-adapter-config-user-secret.test.ts` — 1
file, 6/6 passed (embedded Postgres route test verifying HTTP 422
rejection without token echo for `github_pat_`, `ghp_`, and `sk-` env
var names).
- `pnpm vitest run packages/adapter-utils/src/command-redaction.test.ts`
— 1 file, 43/43 passed.
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/adapter-utils typecheck && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` — PASS (0 errors, Storybook catalog clean).
- `pnpm check:token-gates` — PASS (all 4 token gates clean).
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/redaction.test.ts
server/src/__tests__/redact-sensitive.test.ts
server/src/__tests__/agents-adapter-config-user-secret.test.ts
ui/src/components/environment-variables-editor/model.test.ts
ui/src/components/environment-variables-editor/EnvironmentVariablesEditor.test.tsx
ui/src/components/AgentSecretAccessEditor.test.tsx` — PASS.
- `pnpm verify --base 2d06567795
--explain` — `source-sdk-public-inputs.json` verified in sync; exited 2
due to broad input (`tests/runner-e2e/source-sdk-public-inputs.json`),
deferring repo-wide matrix to sharded PR CI.
## Risks
- Low risk. `looksLikeCredentialToken` matches only explicit provider
credential prefixes (`gh[pousr]_`, `github_pat_`, `sk-`,
`sk_live_`/`sk_test_`, `rk_live_`/`rk_test_`, `xox[baprs]-`,
`AKIA`/`ASIA`, `AIza`, `glpat-`, `npm_`, `hf_`, `lin_api_`, `sbp_`,
`SG.`, JWTs, PEM headers, `Bearer `) so ordinary uppercase or long env
var names are unaffected.
- Legacy agent or environment records that already stored a
secret-shaped env var key will now have that key masked as
`***REDACTED***` on reads and skipped with a redacted warning at runtime
(preserving existing heartbeats) and rejected on subsequent saves until
removed/renamed.
- No database migrations are required.
## Model Used
- Google Gemini (Antigravity agentic coding assistant with extended
reasoning, tool use, and local command execution)
## 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>
This commit is contained in:
1 parent
a74b4f8196
commit
079fb1fe63
26 files changed
+1668
-89
No files matched your search
@@ -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(?<![A-Za-z0-9_]-*)[A-Za-z0-9_-]{8,}(?:\.[A-Za-z0-9_-]{8,}){2}(?:\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,})?\b/g;
|
||||
@@ -79,11 +86,25 @@ const COMMAND_SECRET_HINTS = [
|
||||
"cookie",
|
||||
"connectionstring",
|
||||
"sk-",
|
||||
"sk_live_",
|
||||
"sk_test_",
|
||||
"rk_live_",
|
||||
"rk_test_",
|
||||
"ghp_",
|
||||
"gho_",
|
||||
"ghu_",
|
||||
"ghs_",
|
||||
"ghr_",
|
||||
"github_pat_",
|
||||
"xoxb-",
|
||||
"xoxp-",
|
||||
"xoxa-",
|
||||
"xoxr-",
|
||||
"xoxs-",
|
||||
"akia",
|
||||
"asia",
|
||||
"aiza",
|
||||
"glpat-",
|
||||
] as const;
|
||||
|
||||
function maybeContainsSecretText(command: string) {
|
||||
@@ -132,7 +153,12 @@ function redactSetAsideCommandText(command: string, redactedValue: string): stri
|
||||
},
|
||||
)
|
||||
.replace(COMMAND_OPENAI_KEY_RE, redactedValue)
|
||||
.replace(COMMAND_UNDERSCORE_SECRET_KEY_RE, redactedValue)
|
||||
.replace(COMMAND_GITHUB_TOKEN_RE, redactedValue)
|
||||
.replace(COMMAND_SLACK_TOKEN_RE, redactedValue)
|
||||
.replace(COMMAND_AWS_KEY_ID_RE, redactedValue)
|
||||
.replace(COMMAND_GOOGLE_API_KEY_RE, redactedValue)
|
||||
.replace(COMMAND_GITLAB_PAT_RE, redactedValue)
|
||||
.replace(COMMAND_JWT_RE, (match) => looksLikeCredentialJwt(match) ? redactedValue : match);
|
||||
}
|
||||
|
||||
@@ -275,6 +301,7 @@ export function collectDiagnosticEnvironmentSecrets(
|
||||
const secretName = new RegExp(`^(?:${SECRET_NAME_PATTERN})$`, "i");
|
||||
const values = new Set<string>();
|
||||
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) ||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<string, unknown> = { "[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<string, unknown> };
|
||||
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", () => {
|
||||
|
||||
@@ -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<string, unknown>).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<string, unknown>).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<string, unknown> = {};
|
||||
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<string, unknown>)).toHaveLength(4_000);
|
||||
expect(Object.keys(sanitized)).toHaveLength(4_000);
|
||||
expect(JSON.stringify(redactedAdapter)).not.toContain(prefix);
|
||||
expect(JSON.stringify(sanitized)).not.toContain(prefix);
|
||||
});
|
||||
});
|
||||
@@ -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>): () => 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<string, unknown>);
|
||||
let allocateRedactedKey: (() => string) | null = null;
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
|
||||
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<string, unknown>)) {
|
||||
const credentialKey = isCredentialShapedKey(key);
|
||||
if (credentialKey) values.add(key);
|
||||
collectSensitiveStringValuesInto(
|
||||
entry,
|
||||
values,
|
||||
collectAll || isSensitiveKey(key),
|
||||
collectAll || isSensitiveKey(key) || credentialKey,
|
||||
depth + 1,
|
||||
);
|
||||
}
|
||||
|
||||
+77
-4
@@ -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`(?<![A-Za-z0-9_-])`;
|
||||
@@ -397,11 +398,25 @@ const SECRET_TEXT_HINTS = [
|
||||
"cookie",
|
||||
"connectionstring",
|
||||
"sk-",
|
||||
"sk_live_",
|
||||
"sk_test_",
|
||||
"rk_live_",
|
||||
"rk_test_",
|
||||
"ghp_",
|
||||
"gho_",
|
||||
"ghu_",
|
||||
"ghs_",
|
||||
"ghr_",
|
||||
"github_pat_",
|
||||
"xoxb-",
|
||||
"xoxp-",
|
||||
"xoxa-",
|
||||
"xoxr-",
|
||||
"xoxs-",
|
||||
"akia",
|
||||
"asia",
|
||||
"aiza",
|
||||
"glpat-",
|
||||
] as const;
|
||||
export const REDACTED_EVENT_VALUE = "***REDACTED***";
|
||||
|
||||
@@ -903,11 +918,56 @@ function isPaperclipSchemaDiscriminator(
|
||||
);
|
||||
}
|
||||
|
||||
function isCredentialShapedObjectKey(key: string): boolean {
|
||||
if (looksLikeCredentialToken(key)) return true;
|
||||
if (key.startsWith("access.") && looksLikeCredentialToken(key.slice("access.".length))) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function createRedactedObjectKeyAllocator(
|
||||
base: string,
|
||||
existingKeys: ReadonlySet<string>,
|
||||
): () => 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<string, unknown>,
|
||||
): Record<string, unknown> {
|
||||
const entries = Object.entries(record);
|
||||
let allocateRedactedKey: (() => string) | null = null;
|
||||
const redacted: Record<string, unknown> = {};
|
||||
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<string, unknown> = {};
|
||||
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 };
|
||||
}
|
||||
|
||||
@@ -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<string, string> = {};
|
||||
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}`);
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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<string, EnvBinding> = {};
|
||||
|
||||
export function resolveEffectiveAgentEnv(
|
||||
overlayAdapterConfig: Record<string, unknown>,
|
||||
savedAdapterConfig: Record<string, unknown> | null | undefined,
|
||||
flushedEnv?: Record<string, EnvBinding> | null,
|
||||
): Record<string, EnvBinding> {
|
||||
if (flushedEnv !== undefined && flushedEnv !== null) return flushedEnv;
|
||||
if (Object.prototype.hasOwnProperty.call(overlayAdapterConfig, "env")) {
|
||||
return (overlayAdapterConfig.env as Record<string, EnvBinding> | undefined) ?? EMPTY_ENV;
|
||||
}
|
||||
return (savedAdapterConfig?.env as Record<string, EnvBinding> | 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<string, EnvBinding> | null,
|
||||
) => {
|
||||
if (isCreate) return;
|
||||
setOverlay((prev) => {
|
||||
const existingEnv = resolveEffectiveAgentEnv(
|
||||
prev.adapterConfig,
|
||||
props.agent.adapterConfig as Record<string, unknown> | 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<string, unknown> | 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<string, unknown>) : {};
|
||||
const effectiveSecretsAdapterConfig = useMemo(
|
||||
() => ({ ...config, ...overlay.adapterConfig }),
|
||||
[config, overlay.adapterConfig],
|
||||
);
|
||||
const runtimeConfig = !isCreate ? ((props.agent.runtimeConfig ?? {}) as Record<string, unknown>) : {};
|
||||
const runtimeOverlay = overlay.runtime.runtimeConfig as Record<string, unknown> | 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<string, EnvBinding>));
|
||||
@@ -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<string, EnvBinding>));
|
||||
@@ -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<string, EnvBinding>));
|
||||
@@ -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) {
|
||||
<div data-agent-tile={panels ? "" : undefined} className={cn(cards ? cardBody : "space-y-3 px-4 pb-3")}>
|
||||
<p className="text-xs text-muted-foreground">{help.secretAccess}</p>
|
||||
<AgentSecretAccessEditor
|
||||
config={{ ...config, ...overlay.adapterConfig }}
|
||||
config={effectiveSecretsAdapterConfig}
|
||||
secrets={availableSecrets}
|
||||
onChange={applyAccessGrants}
|
||||
onCreateSecret={(name, value) => createSecret.mutateAsync({ name, value })}
|
||||
onRotateSecret={(secretId, value) => rotateSecret.mutateAsync({ secretId, value })}
|
||||
onBindAsEnvVar={bindSecretAsEnvVar}
|
||||
proposals={agentBindingProposals}
|
||||
onApproveProposal={proposalReview.requestApprove}
|
||||
onRejectProposal={proposalReview.requestReject}
|
||||
/>
|
||||
{proposalReview.dialogs}
|
||||
<Dialog
|
||||
open={pendingEnvBindConflict !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setPendingEnvBindConflict(null);
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Environment variable already exists</DialogTitle>
|
||||
<DialogDescription>
|
||||
<code className="font-mono">{pendingEnvBindConflict?.binding.envKey}</code> is already set as{" "}
|
||||
{pendingEnvBindConflict?.existingKind === "secret_ref"
|
||||
? "another company secret"
|
||||
: pendingEnvBindConflict?.existingKind === "user_secret_ref"
|
||||
? "a user secret"
|
||||
: "a plain value"}
|
||||
. Choose <code className="font-mono">{pendingEnvBindConflict?.availableEnvKey}</code> to keep the
|
||||
existing variable, or confirm replacing it.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter className="sm:justify-between">
|
||||
<Button type="button" variant="ghost" onClick={() => setPendingEnvBindConflict(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
if (!pendingEnvBindConflict) return;
|
||||
commitSecretEnvBinding(
|
||||
pendingEnvBindConflict.availableEnvKey,
|
||||
pendingEnvBindConflict.binding.secretId,
|
||||
pendingEnvBindConflict.binding.version,
|
||||
);
|
||||
setPendingEnvBindConflict(null);
|
||||
}}
|
||||
>
|
||||
Bind as {pendingEnvBindConflict?.availableEnvKey}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
onClick={() => {
|
||||
if (!pendingEnvBindConflict) return;
|
||||
commitSecretEnvBinding(
|
||||
pendingEnvBindConflict.binding.envKey,
|
||||
pendingEnvBindConflict.binding.secretId,
|
||||
pendingEnvBindConflict.binding.version,
|
||||
);
|
||||
setPendingEnvBindConflict(null);
|
||||
}}
|
||||
>
|
||||
Replace {pendingEnvBindConflict?.binding.envKey}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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(
|
||||
<AgentSecretAccessEditor
|
||||
config={{
|
||||
"access.STRIPE_KEY": { type: "secret_ref", secretId: "s1", version: "latest" },
|
||||
}}
|
||||
secrets={secrets}
|
||||
onChange={() => {}}
|
||||
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<HTMLButtonElement>("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(
|
||||
<AgentSecretAccessEditor
|
||||
config={{
|
||||
env: {
|
||||
STRIPE_KEY: { type: "plain", value: "existing-plain" },
|
||||
},
|
||||
"access.STRIPE_KEY": { type: "secret_ref", secretId: "s1", version: "latest" },
|
||||
}}
|
||||
secrets={secrets}
|
||||
onChange={() => {}}
|
||||
onBindAsEnvVar={(binding) => boundEnv.push(binding)}
|
||||
/>,
|
||||
);
|
||||
|
||||
const bindEnvButton = [...container.querySelectorAll<HTMLButtonElement>("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<HTMLButtonElement>("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<HTMLButtonElement>("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(
|
||||
<AgentSecretAccessEditor
|
||||
config={{
|
||||
env: {
|
||||
OLD: { type: "plain", value: "occupied" },
|
||||
},
|
||||
"access.OLD": { type: "secret_ref", secretId: "s1", version: 1 },
|
||||
"access.NEW": { type: "secret_ref", secretId: "s1", version: 3 },
|
||||
}}
|
||||
secrets={secrets}
|
||||
onChange={() => {}}
|
||||
onBindAsEnvVar={(binding) => boundEnv.push(binding)}
|
||||
/>,
|
||||
);
|
||||
|
||||
const bindEnvButton = [...container.querySelectorAll<HTMLButtonElement>("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<string, unknown> = {};
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
largeConfig[`access.ALIAS_${index}`] = { type: "secret_ref", secretId: `s-${index}`, version: "latest" };
|
||||
}
|
||||
|
||||
render(
|
||||
<AgentSecretAccessEditor
|
||||
config={largeConfig}
|
||||
secrets={largeSecrets}
|
||||
onChange={() => {}}
|
||||
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<HTMLInputElement>('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);
|
||||
});
|
||||
});
|
||||
@@ -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<string, EnvS
|
||||
const map: Record<string, EnvSecretRefBinding> = {};
|
||||
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<string, EnvSecretRefBinding>):
|
||||
/* 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<string, unknown>;
|
||||
@@ -161,6 +170,10 @@ export interface AgentSecretAccessEditorProps {
|
||||
onChange: (next: Record<string, EnvSecretRefBinding>) => void;
|
||||
/** Create a company secret from the shared picker's pinned create action. */
|
||||
onCreateSecret?: (name: string, value: string) => Promise<CompanySecret>;
|
||||
/** Rotate an existing company secret when a name collision occurs during creation. */
|
||||
onRotateSecret?: (secretId: string, value: string) => Promise<CompanySecret>;
|
||||
/** 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<string, CompanySecret>();
|
||||
for (const secret of secrets) map.set(secret.id, secret);
|
||||
return map;
|
||||
}, [secrets]);
|
||||
const apiBindingByAlias = useMemo(() => {
|
||||
const map = new Map<string, AgentSecretRefEntry>();
|
||||
for (const entry of apiBindings) {
|
||||
map.set(entry.name, entry);
|
||||
}
|
||||
return map;
|
||||
}, [apiBindings]);
|
||||
const apiBindingBySecretId = useMemo(() => {
|
||||
const map = new Map<string, AgentSecretRefEntry>();
|
||||
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<AccessRow[]>(() => 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<string, HTMLDivElement>());
|
||||
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 ? (
|
||||
<div className="space-y-1.5">
|
||||
{summaries.map((summary) => (
|
||||
<div
|
||||
key={summary.secretId}
|
||||
className="flex flex-wrap items-center gap-x-2 gap-y-1 rounded-md border border-border bg-muted/30 px-2.5 py-1.5 text-xs"
|
||||
>
|
||||
<KeyRound className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
<span className="font-medium">{secretName(summary.secretId)}</span>
|
||||
{summary.envKeys.length > 0 ? <DeliveryBadge mode="env" /> : null}
|
||||
{summary.apiAliases.length > 0 ? <DeliveryBadge mode="api" /> : null}
|
||||
<span className="min-w-0 truncate font-mono text-(length:--text-micro) text-muted-foreground">
|
||||
{[
|
||||
...summary.envKeys.map((key) => `${ENV_CONFIG_PATH_PREFIX}${key}`),
|
||||
...summary.apiAliases.map((alias) => `${AGENT_ACCESS_CONFIG_PATH_PREFIX}${alias}`),
|
||||
].join(" · ")}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
{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 (
|
||||
<div
|
||||
key={summary.secretId}
|
||||
className="space-y-1.5 rounded-md border border-border bg-muted/30 px-2.5 py-1.5 text-xs"
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<KeyRound className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
<span className="font-medium">{secretName(summary.secretId)}</span>
|
||||
{summary.envKeys.length > 0 ? <DeliveryBadge mode="env" /> : null}
|
||||
{summary.apiAliases.length > 0 ? <DeliveryBadge mode="api" /> : null}
|
||||
<span className="min-w-0 truncate font-mono text-(length:--text-micro) text-muted-foreground">
|
||||
{[
|
||||
...summary.envKeys.map((key) => `${ENV_CONFIG_PATH_PREFIX}${key}`),
|
||||
...summary.apiAliases.map((alias) => `${AGENT_ACCESS_CONFIG_PATH_PREFIX}${alias}`),
|
||||
].join(" · ")}
|
||||
</span>
|
||||
{isApiOnly && onBindAsEnvVar && !disabled && suggestedEnvKey ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const version = matchingApiBinding?.version ?? "latest";
|
||||
if (envKeyOccupied) {
|
||||
setPendingEnvConflict({
|
||||
secretId: summary.secretId,
|
||||
envKey: suggestedEnvKey,
|
||||
availableEnvKey: nextAvailableEnvKey(suggestedEnvKey),
|
||||
version,
|
||||
});
|
||||
return;
|
||||
}
|
||||
onBindAsEnvVar({
|
||||
envKey: suggestedEnvKey,
|
||||
secretId: summary.secretId,
|
||||
version,
|
||||
});
|
||||
}}
|
||||
className="ml-auto inline-flex items-center gap-1 rounded-md border border-border bg-background px-2 py-0.5 text-(length:--text-micro) font-medium text-foreground transition-colors hover:bg-accent"
|
||||
title={
|
||||
envKeyOccupied
|
||||
? `$${suggestedEnvKey} already exists — click to choose a new name or confirm replacement`
|
||||
: `Bind as $${suggestedEnvKey} under Environment variables`
|
||||
}
|
||||
>
|
||||
<Variable className="size-3" />
|
||||
Also bind as env var
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
{conflictForRow && onBindAsEnvVar ? (
|
||||
<div className="flex flex-wrap items-center gap-1.5 rounded-md border border-border bg-background px-2 py-1.5 text-(length:--text-micro)">
|
||||
<span className="text-foreground">
|
||||
<code className="font-mono">${conflictForRow.envKey}</code> already exists under Environment
|
||||
variables.
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onBindAsEnvVar({
|
||||
envKey: conflictForRow.availableEnvKey,
|
||||
secretId: conflictForRow.secretId,
|
||||
version: conflictForRow.version,
|
||||
});
|
||||
setPendingEnvConflict(null);
|
||||
}}
|
||||
className="inline-flex items-center rounded-md border border-border bg-muted/40 px-2 py-0.5 font-medium text-foreground transition-colors hover:bg-accent"
|
||||
>
|
||||
Bind as {conflictForRow.availableEnvKey}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onBindAsEnvVar({
|
||||
envKey: conflictForRow.envKey,
|
||||
secretId: conflictForRow.secretId,
|
||||
version: conflictForRow.version,
|
||||
replaceExisting: true,
|
||||
});
|
||||
setPendingEnvConflict(null);
|
||||
}}
|
||||
className="inline-flex items-center rounded-md border border-destructive/40 bg-destructive/10 px-2 py-0.5 font-medium text-destructive transition-colors hover:bg-destructive/15"
|
||||
>
|
||||
Replace {conflictForRow.envKey}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPendingEnvConflict(null)}
|
||||
className="ml-auto inline-flex items-center rounded-md px-1.5 py-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">No company secret references are bound to this agent yet.</p>
|
||||
@@ -332,26 +478,34 @@ export function AgentSecretAccessEditor({
|
||||
|
||||
{/* Editable API-access grants (access.<ALIAS>). */}
|
||||
<div className="space-y-2">
|
||||
<div className="text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground">
|
||||
API access (no env var)
|
||||
<div className="space-y-1">
|
||||
<div className="text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground">
|
||||
API access (no env var)
|
||||
</div>
|
||||
<p className="text-(length:--text-micro) text-muted-foreground">
|
||||
Processes and shell scripts will not see <code className="font-mono">$NAME</code> for API-access secrets.
|
||||
To expose a secret as <code className="font-mono">$NAME</code>, bind it under Environment variables above.
|
||||
</p>
|
||||
</div>
|
||||
{rows.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{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 (
|
||||
<div key={row.id} className="space-y-1">
|
||||
<div className="grid grid-cols-(--gtc-65) items-start gap-1.5">
|
||||
<div>
|
||||
<Input
|
||||
type={aliasLooksLikeSecret ? "password" : "text"}
|
||||
value={row.alias}
|
||||
onChange={(event) => 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",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
@@ -425,7 +580,7 @@ export function AgentSecretAccessEditor({
|
||||
<CreateSecretPopover
|
||||
initialName={createRequest.name}
|
||||
initialValue=""
|
||||
existingSecretNames={secrets.map((secret) => 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}
|
||||
</PopoverContent>
|
||||
@@ -476,7 +650,11 @@ export function AgentSecretAccessEditor({
|
||||
<Trash2 className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
{aliasInvalid ? (
|
||||
{aliasLooksLikeSecret ? (
|
||||
<p className="pl-0.5 text-(length:--text-micro) text-destructive">
|
||||
Looks like a secret value — enter an alias name (e.g. GH_TOKEN), not the token itself
|
||||
</p>
|
||||
) : aliasInvalid ? (
|
||||
<p className="pl-0.5 text-(length:--text-micro) text-destructive">
|
||||
Invalid alias — use letters, digits and _
|
||||
</p>
|
||||
|
||||
@@ -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 })}
|
||||
/>
|
||||
|
||||
|
||||
@@ -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<void>;
|
||||
/** Bind the row to an existing secret when its name already exists. */
|
||||
onSelectExisting?: (secret: CompanySecret) => void | Promise<void>;
|
||||
/** Rotate an existing secret with the typed value and bind the row. */
|
||||
onRotateExisting?: (secret: CompanySecret, value: string) => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -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<string | null>(null);
|
||||
const [touched, setTouched] = useState(false);
|
||||
const [selectedAmbiguousId, setSelectedAmbiguousId] = useState<string | null>(null);
|
||||
|
||||
const { existingSecretByExactName, existingSecretsByLowerName } = useMemo(() => {
|
||||
const byExact = new Map<string, CompanySecret>();
|
||||
const byLower = new Map<string, CompanySecret[]>();
|
||||
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<string>()
|
||||
: 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 ? <span className="block text-(length:--text-micro) text-destructive">{nameError}</span> : null}
|
||||
</label>
|
||||
|
||||
{hasCollisionActions ? (
|
||||
<div className="space-y-2 rounded-md border border-border bg-muted/40 p-2.5">
|
||||
{ambiguousMatches.length > 1 ? (
|
||||
<>
|
||||
<p className="text-(length:--text-micro) text-foreground">
|
||||
Multiple secrets match <span className="font-mono font-medium">{trimmedName}</span> with different
|
||||
casing. Choose which secret to use, or enter a different name:
|
||||
</p>
|
||||
<div className="flex flex-col gap-1">
|
||||
{ambiguousMatches.map((candidate) => {
|
||||
const isSelected = matchingSecret?.id === candidate.id;
|
||||
return (
|
||||
<button
|
||||
key={candidate.id}
|
||||
type="button"
|
||||
onClick={() => setSelectedAmbiguousId(candidate.id)}
|
||||
aria-pressed={isSelected}
|
||||
className={cn(
|
||||
"flex items-center justify-between rounded border px-2 py-1 text-left text-(length:--text-micro) font-mono transition-colors",
|
||||
isSelected
|
||||
? "border-primary bg-primary/10 text-foreground"
|
||||
: "border-border bg-background/60 text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span className="truncate">{candidate.name}</span>
|
||||
<span className="ml-2 shrink-0 font-sans text-muted-foreground">
|
||||
{candidate.status === "active" ? `v${candidate.latestVersion}` : candidate.status}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
{matchingSecret ? (
|
||||
<>
|
||||
{existingIsActive ? (
|
||||
<p className="text-(length:--text-micro) text-foreground">
|
||||
<span className="font-mono font-medium">{matchingSecret.name}</span> 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."}
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-(length:--text-micro) text-foreground">
|
||||
<span className="font-mono font-medium">{matchingSecret.name}</span> already exists, but it is{" "}
|
||||
{matchingSecret.status}. Re-enable it in Secrets before reusing it, or choose a different name.
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{onSelectExisting ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => void handleUseExisting()}
|
||||
disabled={submitting || !existingIsActive}
|
||||
>
|
||||
Use existing secret
|
||||
</Button>
|
||||
) : null}
|
||||
{canRotateExisting ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={() => void handleRotateExisting()}
|
||||
disabled={submitting}
|
||||
>
|
||||
{submitting ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : null}
|
||||
Save as new version
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<label className="block space-y-1">
|
||||
<span className="text-(length:--text-micro) font-medium text-muted-foreground">Value</span>
|
||||
<div className="relative">
|
||||
|
||||
+365
-2
@@ -1,12 +1,14 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { useState } from "react";
|
||||
import { createRef, useState } from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { CompanySecret, EnvBinding } from "@paperclipai/shared";
|
||||
import { EnvironmentVariablesEditor } from "./index";
|
||||
import { EnvironmentVariablesEditor, type EnvironmentVariablesEditorHandle } from "./index";
|
||||
import { SecretPicker } from "./SecretPicker";
|
||||
import { SecretPopoverForm } from "./CreateSecretPopover";
|
||||
import { Popover, PopoverContent } from "@/components/ui/popover";
|
||||
|
||||
// Radix (DropdownMenu/Popover) relies on Pointer Capture APIs that jsdom omits.
|
||||
const OriginalPointerEvent = globalThis.PointerEvent;
|
||||
@@ -923,4 +925,365 @@ describe("EnvironmentVariablesEditor", () => {
|
||||
);
|
||||
expect(match?.querySelector<HTMLElement>("[title]")?.getAttribute("title")).toBe(cloudMigrationKey);
|
||||
});
|
||||
|
||||
it("lets plain-to-secret conversion reuse an existing secret on name collision", async () => {
|
||||
const existing = makeSecret("s-gh", { name: "gh_token", key: "gh_token", latestVersion: 2 });
|
||||
const onChange = vi.fn();
|
||||
const onRotateSecret = vi.fn(async (secretId: string, _value: string) => ({
|
||||
...existing,
|
||||
id: secretId,
|
||||
latestVersion: 3,
|
||||
}));
|
||||
|
||||
render(
|
||||
<EnvironmentVariablesEditor
|
||||
value={{ GH_TOKEN: { type: "plain", value: ["ghp", "0123456789abcdef0123456789abcdef"].join("_") } }}
|
||||
secrets={[existing]}
|
||||
onChange={onChange}
|
||||
onCreateSecret={async () => existing}
|
||||
onRotateSecret={onRotateSecret}
|
||||
/>,
|
||||
);
|
||||
const storeButton = container.querySelector<HTMLButtonElement>('button[title^="This value looks sensitive"]')!;
|
||||
storeButton.click();
|
||||
await flush();
|
||||
|
||||
const useExistingBtn = [...document.querySelectorAll<HTMLButtonElement>("button")].find((b) =>
|
||||
b.textContent?.includes("Use existing secret"),
|
||||
);
|
||||
const saveNewVersionBtn = [...document.querySelectorAll<HTMLButtonElement>("button")].find((b) =>
|
||||
b.textContent?.includes("Save as new version"),
|
||||
);
|
||||
expect(useExistingBtn, "Use existing secret action should render on collision").toBeTruthy();
|
||||
expect(saveNewVersionBtn, "Save as new version action should render on collision").toBeTruthy();
|
||||
|
||||
useExistingBtn!.click();
|
||||
await flush();
|
||||
saveButton().click();
|
||||
await flush();
|
||||
expect(onChange).toHaveBeenLastCalledWith({
|
||||
GH_TOKEN: { type: "secret_ref", secretId: "s-gh", version: "latest" },
|
||||
});
|
||||
expect(onRotateSecret).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("lets plain-to-secret conversion rotate an existing secret as a new version on name collision", async () => {
|
||||
const existing = makeSecret("s-gh", { name: "gh_token", key: "gh_token", latestVersion: 2 });
|
||||
const onChange = vi.fn();
|
||||
const onRotateSecret = vi.fn(async (secretId: string, _value: string) => ({
|
||||
...existing,
|
||||
id: secretId,
|
||||
latestVersion: 3,
|
||||
}));
|
||||
|
||||
const nextValue = ["ghp", "fedcba9876543210fedcba9876543210"].join("_");
|
||||
render(
|
||||
<EnvironmentVariablesEditor
|
||||
value={{ GH_TOKEN: { type: "plain", value: nextValue } }}
|
||||
secrets={[existing]}
|
||||
onChange={onChange}
|
||||
onCreateSecret={async () => existing}
|
||||
onRotateSecret={onRotateSecret}
|
||||
/>,
|
||||
);
|
||||
const storeButton = container.querySelector<HTMLButtonElement>('button[title^="This value looks sensitive"]')!;
|
||||
storeButton.click();
|
||||
await flush();
|
||||
|
||||
const rotateBtn = [...document.querySelectorAll<HTMLButtonElement>("button")].find((b) =>
|
||||
b.textContent?.includes("Save as new version"),
|
||||
)!;
|
||||
rotateBtn.click();
|
||||
await flush();
|
||||
expect(onRotateSecret).toHaveBeenCalledWith("s-gh", nextValue);
|
||||
saveButton().click();
|
||||
await flush();
|
||||
expect(onChange).toHaveBeenLastCalledWith({
|
||||
GH_TOKEN: { type: "secret_ref", secretId: "s-gh", version: "latest" },
|
||||
});
|
||||
});
|
||||
|
||||
it("disables reusing inactive (disabled or archived) secrets on name collision and explains why", async () => {
|
||||
for (const status of ["disabled", "archived"] as const) {
|
||||
const inactive = makeSecret(`s-gh-${status}`, { name: "gh_token", key: "gh_token", status, latestVersion: 2 });
|
||||
const onChange = vi.fn();
|
||||
const onRotateSecret = vi.fn(async () => inactive);
|
||||
|
||||
render(
|
||||
<EnvironmentVariablesEditor
|
||||
value={{ GH_TOKEN: { type: "plain", value: ["ghp", "0123456789abcdef0123456789abcdef"].join("_") } }}
|
||||
secrets={[inactive]}
|
||||
onChange={onChange}
|
||||
onCreateSecret={async () => inactive}
|
||||
onRotateSecret={onRotateSecret}
|
||||
/>,
|
||||
);
|
||||
const storeButton = container.querySelector<HTMLButtonElement>('button[title^="This value looks sensitive"]')!;
|
||||
storeButton.click();
|
||||
await flush();
|
||||
|
||||
const useExistingBtn = [...document.querySelectorAll<HTMLButtonElement>("button")].find((b) =>
|
||||
b.textContent?.includes("Use existing secret"),
|
||||
);
|
||||
const saveNewVersionBtn = [...document.querySelectorAll<HTMLButtonElement>("button")].find((b) =>
|
||||
b.textContent?.includes("Save as new version"),
|
||||
);
|
||||
expect(useExistingBtn?.disabled, `Use existing secret must be disabled for ${status}`).toBe(true);
|
||||
expect(saveNewVersionBtn, `Save as new version must not render for ${status}`).toBeUndefined();
|
||||
expect(document.body.textContent).toContain(`it is ${status}`);
|
||||
expect(document.body.textContent?.toLowerCase()).toContain("re-enable");
|
||||
|
||||
// Unmount before next iteration.
|
||||
root?.unmount();
|
||||
root = null;
|
||||
}
|
||||
});
|
||||
|
||||
it("warns immediately, masks input, and blocks save when a secret token is pasted into Variable name", async () => {
|
||||
const onChange = vi.fn();
|
||||
const token = ["ghp", "0123456789abcdef0123456789abcdef"].join("_");
|
||||
render(
|
||||
<EnvironmentVariablesEditor
|
||||
value={{}}
|
||||
secrets={secrets}
|
||||
onChange={onChange}
|
||||
onCreateSecret={async () => secrets[0]}
|
||||
/>,
|
||||
);
|
||||
const addButton = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Add variable"))!;
|
||||
addButton.click();
|
||||
await flush();
|
||||
|
||||
const nameInput = nameInputs()[0]!;
|
||||
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
|
||||
setter.call(nameInput, token);
|
||||
nameInput.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
await flush();
|
||||
|
||||
// Immediately surfaced without blur, masked, and raw token absent from unsaved banner.
|
||||
expect(container.textContent?.toLowerCase()).toMatch(/looks like a secret/);
|
||||
expect(nameInput.type).toBe("password");
|
||||
expect(container.textContent).not.toContain(token);
|
||||
expect(container.querySelector('button[aria-label="Remove variable"]')).toBeTruthy();
|
||||
expect(container.querySelector(`[aria-label*="${token}"], [title*="${token}"]`)).toBeNull();
|
||||
expect(saveButton().disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("returns a distinct blocked flush result and stops outer form submission when a secret-shaped token is pasted into Variable name", async () => {
|
||||
const onChange = vi.fn();
|
||||
const onFormSubmit = vi.fn((event: React.FormEvent) => event.preventDefault());
|
||||
const editorRef = createRef<EnvironmentVariablesEditorHandle>();
|
||||
const token = ["ghp", "0123456789abcdef0123456789abcdef"].join("_");
|
||||
render(
|
||||
<form onSubmit={onFormSubmit}>
|
||||
<EnvironmentVariablesEditor
|
||||
ref={editorRef}
|
||||
value={{ EXISTING_OK: { type: "plain", value: "keep" } }}
|
||||
secrets={secrets}
|
||||
onChange={onChange}
|
||||
onCreateSecret={async () => secrets[0]}
|
||||
/>
|
||||
</form>,
|
||||
);
|
||||
|
||||
// Clean editor returns { status: "clean" } rather than "blocked".
|
||||
expect(editorRef.current?.flushPendingDraft()).toEqual({ status: "clean" });
|
||||
|
||||
const addButton = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Add variable"))!;
|
||||
addButton.click();
|
||||
await flush();
|
||||
|
||||
const nameInput = nameInputs().at(-1)!;
|
||||
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
|
||||
setter.call(nameInput, token);
|
||||
nameInput.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
await flush();
|
||||
|
||||
const result = editorRef.current?.flushPendingDraft();
|
||||
expect(result?.status).toBe("blocked");
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
|
||||
// Native form submission must also be blocked so outer saves do not discard pending edits.
|
||||
const form = container.querySelector("form")!;
|
||||
form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
|
||||
await flush();
|
||||
expect(onFormSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("prefers an exact-case secret match over an earlier case-insensitive secret on collision", async () => {
|
||||
const upper = makeSecret("s-upper", { name: "GH_TOKEN", key: "gh_token_upper", latestVersion: 4 });
|
||||
const exact = makeSecret("s-exact", { name: "gh_token", key: "gh_token_exact", latestVersion: 1 });
|
||||
const onChange = vi.fn();
|
||||
const onRotateSecret = vi.fn(async (secretId: string, _value: string) => ({
|
||||
...exact,
|
||||
id: secretId,
|
||||
latestVersion: 2,
|
||||
}));
|
||||
const tokenValue = ["ghp", "0123456789abcdef0123456789abcdef"].join("_");
|
||||
|
||||
render(
|
||||
<EnvironmentVariablesEditor
|
||||
value={{ GH_TOKEN: { type: "plain", value: tokenValue } }}
|
||||
secrets={[upper, exact]}
|
||||
onChange={onChange}
|
||||
onCreateSecret={async () => exact}
|
||||
onRotateSecret={onRotateSecret}
|
||||
/>,
|
||||
);
|
||||
const storeButton = container.querySelector<HTMLButtonElement>('button[title^="This value looks sensitive"]')!;
|
||||
storeButton.click();
|
||||
await flush();
|
||||
|
||||
const rotateBtn = [...document.querySelectorAll<HTMLButtonElement>("button")].find((b) =>
|
||||
b.textContent?.includes("Save as new version"),
|
||||
)!;
|
||||
rotateBtn.click();
|
||||
await flush();
|
||||
expect(onRotateSecret).toHaveBeenCalledWith("s-exact", tokenValue);
|
||||
saveButton().click();
|
||||
await flush();
|
||||
expect(onChange).toHaveBeenLastCalledWith({
|
||||
GH_TOKEN: { type: "secret_ref", secretId: "s-exact", version: "latest" },
|
||||
});
|
||||
});
|
||||
|
||||
it("asks the user to choose when multiple case-insensitive secrets match with no exact match", async () => {
|
||||
const upper = makeSecret("s-upper", { name: "GH_TOKEN", key: "gh_token_upper", latestVersion: 4 });
|
||||
const mixed = makeSecret("s-mixed", { name: "Gh_Token", key: "gh_token_mixed", latestVersion: 2 });
|
||||
const onChange = vi.fn();
|
||||
const onRotateSecret = vi.fn(async (secretId: string, _value: string) => ({
|
||||
...mixed,
|
||||
id: secretId,
|
||||
latestVersion: 3,
|
||||
}));
|
||||
const tokenValue = ["ghp", "0123456789abcdef0123456789abcdef"].join("_");
|
||||
|
||||
render(
|
||||
<EnvironmentVariablesEditor
|
||||
value={{ GH_TOKEN: { type: "plain", value: tokenValue } }}
|
||||
secrets={[upper, mixed]}
|
||||
onChange={onChange}
|
||||
onCreateSecret={async () => mixed}
|
||||
onRotateSecret={onRotateSecret}
|
||||
/>,
|
||||
);
|
||||
const storeButton = container.querySelector<HTMLButtonElement>('button[title^="This value looks sensitive"]')!;
|
||||
storeButton.click();
|
||||
await flush();
|
||||
|
||||
// Before selecting one, neither action should target a secret blindly and Create/Store must be disabled.
|
||||
expect(document.body.textContent).toContain("Multiple secrets match");
|
||||
expect(
|
||||
[...document.querySelectorAll<HTMLButtonElement>("button")].find((b) =>
|
||||
b.textContent?.includes("Use existing secret"),
|
||||
),
|
||||
).toBeUndefined();
|
||||
const storeSubmitBtn = [...document.querySelectorAll<HTMLButtonElement>("button")].find((b) =>
|
||||
b.textContent?.includes("Store & bind"),
|
||||
)!;
|
||||
expect(storeSubmitBtn.disabled).toBe(true);
|
||||
|
||||
const mixedChoice = [...document.querySelectorAll<HTMLButtonElement>("button")].find((b) =>
|
||||
b.textContent?.includes("Gh_Token"),
|
||||
)!;
|
||||
mixedChoice.click();
|
||||
await flush();
|
||||
|
||||
const useExistingBtn = [...document.querySelectorAll<HTMLButtonElement>("button")].find((b) =>
|
||||
b.textContent?.includes("Use existing secret"),
|
||||
)!;
|
||||
useExistingBtn.click();
|
||||
await flush();
|
||||
saveButton().click();
|
||||
await flush();
|
||||
expect(onChange).toHaveBeenLastCalledWith({
|
||||
GH_TOKEN: { type: "secret_ref", secretId: "s-mixed", version: "latest" },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps SecretPopoverForm collision indexing linear across 300 secrets during typing and ambiguous choice selection", async () => {
|
||||
const SECRET_COUNT = 300;
|
||||
const MAX_NAME_READS = SECRET_COUNT * 2;
|
||||
let nameReads = 0;
|
||||
|
||||
function makeCountedSecret(id: string, secretName: string, latestVersion = 1): CompanySecret {
|
||||
const base = makeSecret(id, { name: secretName, key: id, latestVersion });
|
||||
Object.defineProperty(base, "name", {
|
||||
enumerable: true,
|
||||
get() {
|
||||
nameReads += 1;
|
||||
if (nameReads > MAX_NAME_READS) {
|
||||
throw new Error(`Runaway SecretPopoverForm secret scan: ${nameReads} > ${MAX_NAME_READS}`);
|
||||
}
|
||||
return secretName;
|
||||
},
|
||||
});
|
||||
return base;
|
||||
}
|
||||
|
||||
const largeSecrets: CompanySecret[] = [];
|
||||
for (let i = 0; i < SECRET_COUNT - 4; i += 1) {
|
||||
largeSecrets.push(makeCountedSecret(`s-bulk-${i}`, `service_secret_${i}`));
|
||||
}
|
||||
largeSecrets.push(
|
||||
makeCountedSecret("s-exact-upper", "EXACT_KEY", 3),
|
||||
makeCountedSecret("s-exact-lower", "exact_key", 1),
|
||||
makeCountedSecret("s-ambig-1", "AMBIG_KEY", 2),
|
||||
makeCountedSecret("s-ambig-2", "Ambig_Key", 4),
|
||||
);
|
||||
|
||||
const onSelectExisting = vi.fn();
|
||||
const onRotateExisting = vi.fn(async () => {});
|
||||
const tokenValue = ["ghp", "0123456789abcdef0123456789abcdef"].join("_");
|
||||
|
||||
render(
|
||||
<Popover open>
|
||||
<PopoverContent>
|
||||
<SecretPopoverForm
|
||||
mode="store"
|
||||
initialName="exact_key"
|
||||
initialValue={tokenValue}
|
||||
existingSecrets={largeSecrets}
|
||||
onCancel={() => {}}
|
||||
onSubmit={async () => {}}
|
||||
onSelectExisting={onSelectExisting}
|
||||
onRotateExisting={onRotateExisting}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>,
|
||||
);
|
||||
await flush();
|
||||
|
||||
// Exact match selected linearly without scanning multiple times.
|
||||
expect(document.body.textContent).toContain("exact_key already exists (v1)");
|
||||
const readsAfterInitialIndex = nameReads;
|
||||
expect(readsAfterInitialIndex).toBeLessThanOrEqual(SECRET_COUNT + 10);
|
||||
|
||||
// Typing keystrokes into the Name field must hit the memoized Maps in O(1) without re-indexing all 300 secrets.
|
||||
const nameInput = document.querySelector<HTMLInputElement>('input[aria-label="Secret name"]')!;
|
||||
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
|
||||
for (const nextName of ["a", "am", "amb", "ambig_key"]) {
|
||||
setter.call(nameInput, nextName);
|
||||
nameInput.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
await flush();
|
||||
}
|
||||
|
||||
expect(document.body.textContent).toContain("Multiple secrets match");
|
||||
const ambigChoice = [...document.querySelectorAll<HTMLButtonElement>("button")].find((b) =>
|
||||
b.textContent?.includes("Ambig_Key"),
|
||||
)!;
|
||||
ambigChoice.click();
|
||||
await flush();
|
||||
|
||||
const useExistingBtn = [...document.querySelectorAll<HTMLButtonElement>("button")].find((b) =>
|
||||
b.textContent?.includes("Use existing secret"),
|
||||
)!;
|
||||
useExistingBtn.click();
|
||||
await flush();
|
||||
|
||||
expect(onSelectExisting).toHaveBeenCalledTimes(1);
|
||||
expect(onSelectExisting.mock.calls[0]?.[0]?.id).toBe("s-ambig-2");
|
||||
// Extra reads across 4 keystrokes + choice selection must be O(1), not O(SECRET_COUNT).
|
||||
expect(nameReads - readsAfterInitialIndex).toBeLessThan(20);
|
||||
});
|
||||
});
|
||||
@@ -21,7 +21,7 @@ import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover"
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { SecretPicker } from "./SecretPicker";
|
||||
import { CreateSecretPopover, ConvertToSecretPopover } from "./CreateSecretPopover";
|
||||
import { isSensitiveEnv } from "./sensitive";
|
||||
import { isSensitiveEnv, looksLikeCredentialToken } from "./sensitive";
|
||||
import {
|
||||
computeRowHealth,
|
||||
computeUserSecretRowHealth,
|
||||
@@ -62,6 +62,7 @@ export interface EnvironmentVariableRowProps {
|
||||
/** Enter pressed in the value of the last row — append a fresh row and focus it. */
|
||||
onEnterInValueLast: () => void;
|
||||
onCreateSecret: (name: string, value: string) => Promise<CompanySecret>;
|
||||
onRotateSecret?: (secretId: string, value: string) => Promise<CompanySecret>;
|
||||
onToast: (message: string) => void;
|
||||
/** Parent-driven focus request for this row (append flow, source switch). */
|
||||
focusRequest: "name" | "value" | null;
|
||||
@@ -84,6 +85,7 @@ export function EnvironmentVariableRow({
|
||||
onNamePaste,
|
||||
onEnterInValueLast,
|
||||
onCreateSecret,
|
||||
onRotateSecret,
|
||||
onToast,
|
||||
focusRequest,
|
||||
onFocusConsumed,
|
||||
@@ -98,6 +100,7 @@ export function EnvironmentVariableRow({
|
||||
const health = computeRowHealth(row, secrets) ?? computeUserSecretRowHealth(row, userSecretDefinitions);
|
||||
const boundSecret = row.source === "secret" ? secrets.find((s) => s.id === row.secretId) ?? null : null;
|
||||
const userSecretsEnabled = (userSecretDefinitions?.length ?? 0) > 0;
|
||||
const nameLooksLikeSecret = looksLikeCredentialToken(row.name);
|
||||
const sensitive =
|
||||
row.source === "text" && !row.sensitiveDismissed && isSensitiveEnv(row.name, row.textValue);
|
||||
|
||||
@@ -177,6 +180,34 @@ export function EnvironmentVariableRow({
|
||||
setSecretPopover(null);
|
||||
}
|
||||
|
||||
function selectExistingSecret(existing: CompanySecret) {
|
||||
onPatch({
|
||||
source: "secret",
|
||||
secretId: existing.id,
|
||||
userSecretKey: "",
|
||||
required: true,
|
||||
version: "latest",
|
||||
textValue: "",
|
||||
});
|
||||
onToast(`Bound existing secret ${existing.name}`);
|
||||
setSecretPopover(null);
|
||||
}
|
||||
|
||||
async function rotateExistingSecret(existing: CompanySecret, value: string) {
|
||||
if (!onRotateSecret) return;
|
||||
const rotated = await onRotateSecret(existing.id, value);
|
||||
onPatch({
|
||||
source: "secret",
|
||||
secretId: rotated.id,
|
||||
userSecretKey: "",
|
||||
required: true,
|
||||
version: "latest",
|
||||
textValue: "",
|
||||
});
|
||||
onToast(`Saved new version of ${rotated.name} (v${rotated.latestVersion})`);
|
||||
setSecretPopover(null);
|
||||
}
|
||||
|
||||
function openStoreAsSecret() {
|
||||
const name = secretNameFromKey(row.name) || "secret";
|
||||
const { textValue } = row;
|
||||
@@ -209,8 +240,10 @@ export function EnvironmentVariableRow({
|
||||
<div className="col-start-1 row-start-1 min-w-0 @[40rem]/env:row-start-1 @[40rem]/env:self-start">
|
||||
<input
|
||||
ref={nameInputRef}
|
||||
type={nameLooksLikeSecret ? "password" : "text"}
|
||||
className={cn(
|
||||
nameInputClass,
|
||||
nameLooksLikeSecret && ANALYTICS_NO_CAPTURE_CLASS,
|
||||
dirtyFields.name && "border-amber-500/70 bg-amber-500/10 focus-visible:ring-amber-500/40",
|
||||
showNameIssue && nameIssue?.level === "error" && "border-destructive focus-visible:ring-destructive/40",
|
||||
showNameIssue && nameIssue?.level === "warn" && "border-amber-500 focus-visible:ring-amber-500/40",
|
||||
@@ -501,17 +534,21 @@ export function EnvironmentVariableRow({
|
||||
<ConvertToSecretPopover
|
||||
initialName={secretPopover.name}
|
||||
initialValue={secretPopover.value}
|
||||
existingSecretNames={secrets.map((s) => s.name)}
|
||||
existingSecrets={secrets}
|
||||
onCancel={() => setSecretPopover(null)}
|
||||
onSubmit={submitSecretPopover}
|
||||
onSelectExisting={selectExistingSecret}
|
||||
onRotateExisting={onRotateSecret ? rotateExistingSecret : undefined}
|
||||
/>
|
||||
) : secretPopover?.mode === "create" ? (
|
||||
<CreateSecretPopover
|
||||
initialName={secretPopover.name}
|
||||
initialValue={secretPopover.value}
|
||||
existingSecretNames={secrets.map((s) => s.name)}
|
||||
existingSecrets={secrets}
|
||||
onCancel={() => setSecretPopover(null)}
|
||||
onSubmit={submitSecretPopover}
|
||||
onSelectExisting={selectExistingSecret}
|
||||
onRotateExisting={onRotateSecret ? rotateExistingSecret : undefined}
|
||||
/>
|
||||
) : null}
|
||||
</PopoverContent>
|
||||
@@ -596,7 +633,7 @@ export function EnvironmentVariableRow({
|
||||
type="button"
|
||||
onClick={onRemove}
|
||||
disabled={disabled}
|
||||
aria-label={`Remove ${row.name.trim() || "variable"}`}
|
||||
aria-label={nameLooksLikeSecret ? "Remove variable" : `Remove ${row.name.trim() || "variable"}`}
|
||||
className="rounded p-1 text-muted-foreground opacity-100 hover:bg-destructive/10 hover:text-destructive @[40rem]/env:opacity-0 @[40rem]/env:group-hover/row:opacity-100 @[40rem]/env:group-focus-within/row:opacity-100"
|
||||
>
|
||||
<X className="size-4" />
|
||||
|
||||
@@ -10,12 +10,13 @@ import {
|
||||
} from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { AlertCircle, KeyRound, Plus, RotateCcw, Save, UserRound } from "lucide-react";
|
||||
import type { CompanySecret, EnvBinding, UserSecretDefinition } from "@paperclipai/shared";
|
||||
import { SECRET_SHAPED_ENV_NAME_ERROR, type CompanySecret, type EnvBinding, type UserSecretDefinition } from "@paperclipai/shared";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { useOptionalToastActions } from "@/context/ToastContext";
|
||||
import { EnvironmentVariableRow } from "./Row";
|
||||
import { parseDotenv } from "./parse-dotenv";
|
||||
import { looksLikeCredentialToken } from "./sensitive";
|
||||
import {
|
||||
computeDuplicateNames,
|
||||
computeRowHealth,
|
||||
@@ -81,9 +82,10 @@ function normalizedEnvKey(value: Record<string, EnvBinding> | null | undefined):
|
||||
const CHANGE_SUMMARY_MAX_NAMES = 3;
|
||||
|
||||
function formatChangedNames(names: readonly string[]): string {
|
||||
const shown = names.slice(0, CHANGE_SUMMARY_MAX_NAMES).join(", ");
|
||||
return names.length > CHANGE_SUMMARY_MAX_NAMES
|
||||
? `${shown} +${names.length - CHANGE_SUMMARY_MAX_NAMES} more`
|
||||
const safeNames = names.map((name) => (looksLikeCredentialToken(name) ? "[redacted]" : name));
|
||||
const shown = safeNames.slice(0, CHANGE_SUMMARY_MAX_NAMES).join(", ");
|
||||
return safeNames.length > CHANGE_SUMMARY_MAX_NAMES
|
||||
? `${shown} +${safeNames.length - CHANGE_SUMMARY_MAX_NAMES} more`
|
||||
: shown;
|
||||
}
|
||||
|
||||
@@ -125,6 +127,7 @@ export interface EnvironmentVariablesEditorProps {
|
||||
*/
|
||||
userSecretDefinitions?: readonly UserSecretDefinition[];
|
||||
onCreateSecret: (name: string, value: string) => Promise<CompanySecret>;
|
||||
onRotateSecret?: (secretId: string, value: string) => Promise<CompanySecret>;
|
||||
/** Optional "Recently used" picker group + quick-bind chips. */
|
||||
recentlyUsedSecrets?: readonly CompanySecret[];
|
||||
/** Read-only rendering. */
|
||||
@@ -143,12 +146,19 @@ export interface EnvironmentVariablesEditorProps {
|
||||
addLabel?: string;
|
||||
}
|
||||
|
||||
export type FlushPendingDraftResult =
|
||||
| { status: "clean" }
|
||||
| { status: "flushed"; value: Record<string, EnvBinding> }
|
||||
| { status: "blocked"; reason: string };
|
||||
|
||||
export interface EnvironmentVariablesEditorHandle {
|
||||
/**
|
||||
* Promote the editor-local draft into the controlled value before an outer
|
||||
* action reads parent state. Returns the promoted value when a draft existed.
|
||||
* action reads parent state. Returns `{ status: "blocked" }` when a draft row
|
||||
* has a secret-shaped variable name so callers stop outer saves instead of
|
||||
* silently saving stale state.
|
||||
*/
|
||||
flushPendingDraft: () => Record<string, EnvBinding> | null;
|
||||
flushPendingDraft: () => FlushPendingDraftResult;
|
||||
}
|
||||
|
||||
export const EnvironmentVariablesEditor = forwardRef<EnvironmentVariablesEditorHandle, EnvironmentVariablesEditorProps>(function EnvironmentVariablesEditor({
|
||||
@@ -157,6 +167,7 @@ export const EnvironmentVariablesEditor = forwardRef<EnvironmentVariablesEditorH
|
||||
secrets,
|
||||
userSecretDefinitions,
|
||||
onCreateSecret,
|
||||
onRotateSecret,
|
||||
recentlyUsedSecrets,
|
||||
disabled,
|
||||
reservedPrefixes = DEFAULT_RESERVED_PREFIXES,
|
||||
@@ -293,14 +304,23 @@ export const EnvironmentVariablesEditor = forwardRef<EnvironmentVariablesEditorH
|
||||
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
|
||||
}, [disabled, hasUnsavedChanges]);
|
||||
|
||||
const flushPendingDraft = useCallback(() => {
|
||||
if (disabled || !hasUnsavedChanges) return null;
|
||||
const hasSecretShapedName = useMemo(
|
||||
() => rows.some((row) => looksLikeCredentialToken(row.name)),
|
||||
[rows],
|
||||
);
|
||||
|
||||
const flushPendingDraft = useCallback((): FlushPendingDraftResult => {
|
||||
if (disabled) return { status: "clean" };
|
||||
if (hasSecretShapedName) {
|
||||
return { status: "blocked", reason: SECRET_SHAPED_ENV_NAME_ERROR };
|
||||
}
|
||||
if (!hasUnsavedChanges) return { status: "clean" };
|
||||
pendingSaveValueKeyRef.current = draftValueKey;
|
||||
flushSync(() => {
|
||||
onChange(draftValue);
|
||||
});
|
||||
return draftValue ?? {};
|
||||
}, [disabled, draftValue, draftValueKey, hasUnsavedChanges, onChange]);
|
||||
return { status: "flushed", value: draftValue ?? {} };
|
||||
}, [disabled, draftValue, draftValueKey, hasSecretShapedName, hasUnsavedChanges, onChange]);
|
||||
|
||||
useImperativeHandle(ref, () => ({ flushPendingDraft }), [flushPendingDraft]);
|
||||
|
||||
@@ -308,8 +328,11 @@ export const EnvironmentVariablesEditor = forwardRef<EnvironmentVariablesEditorH
|
||||
const form = editorRootRef.current?.closest("form");
|
||||
if (!form) return;
|
||||
|
||||
function handleSubmit() {
|
||||
flushPendingDraft();
|
||||
function handleSubmit(event: SubmitEvent) {
|
||||
if (flushPendingDraft().status === "blocked") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
}
|
||||
|
||||
form.addEventListener("submit", handleSubmit, true);
|
||||
@@ -407,7 +430,7 @@ export const EnvironmentVariablesEditor = forwardRef<EnvironmentVariablesEditorH
|
||||
}
|
||||
|
||||
function saveDraft() {
|
||||
if (!hasUnsavedChanges) return;
|
||||
if (!hasUnsavedChanges || hasSecretShapedName) return;
|
||||
pendingSaveValueKeyRef.current = draftValueKey;
|
||||
onChange(draftValue);
|
||||
}
|
||||
@@ -468,7 +491,8 @@ export const EnvironmentVariablesEditor = forwardRef<EnvironmentVariablesEditorH
|
||||
|
||||
{rows.map((row, index) => {
|
||||
const issue = validateName(row.name, duplicateNames, reservedPrefixes);
|
||||
const touched = touchedNames.has(row.name.trim());
|
||||
const trimmedName = row.name.trim();
|
||||
const showIssue = touchedNames.has(trimmedName) || looksLikeCredentialToken(trimmedName);
|
||||
return (
|
||||
<EnvironmentVariableRow
|
||||
key={row.id}
|
||||
@@ -479,7 +503,7 @@ export const EnvironmentVariablesEditor = forwardRef<EnvironmentVariablesEditorH
|
||||
recentlyUsedSecrets={recentlyUsedSecrets}
|
||||
disabled={disabled}
|
||||
nameIssue={issue}
|
||||
showNameIssue={touched}
|
||||
showNameIssue={showIssue}
|
||||
dirtyFields={rowDirtyFields(row, committedRowsById.get(row.id))}
|
||||
onPatch={(patch) => patchRow(row.id, patch)}
|
||||
onRemove={() => removeRow(row.id)}
|
||||
@@ -487,6 +511,7 @@ export const EnvironmentVariablesEditor = forwardRef<EnvironmentVariablesEditorH
|
||||
onNamePaste={(text) => bulkImport(text, row.id)}
|
||||
onEnterInValueLast={addRow}
|
||||
onCreateSecret={onCreateSecret}
|
||||
onRotateSecret={onRotateSecret}
|
||||
onToast={(message) => toast?.pushToast({ title: message, tone: "success" })}
|
||||
focusRequest={pendingFocus?.rowId === row.id ? pendingFocus.field : null}
|
||||
onFocusConsumed={() => setPendingFocus(null)}
|
||||
@@ -560,7 +585,8 @@ export const EnvironmentVariablesEditor = forwardRef<EnvironmentVariablesEditorH
|
||||
<button
|
||||
type="button"
|
||||
onClick={saveDraft}
|
||||
className="inline-flex h-9 items-center gap-1.5 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90"
|
||||
disabled={hasSecretShapedName}
|
||||
className="inline-flex h-9 items-center gap-1.5 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:pointer-events-none disabled:opacity-50"
|
||||
>
|
||||
<Save className="size-4" />
|
||||
Save
|
||||
|
||||
@@ -179,6 +179,23 @@ describe("validateName", () => {
|
||||
it("charset error takes precedence over reserved prefix", () => {
|
||||
expect(validateName("PAPERCLIP-X", new Set(), reserved)?.level).toBe("error");
|
||||
});
|
||||
|
||||
it("flags secret-shaped strings pasted as variable names", () => {
|
||||
for (const token of [
|
||||
["github", "pat", "11ABCDEF0123456789", "secretTokenValue99"].join("_"),
|
||||
["ghp", "0123456789abcdef0123456789abcdef"].join("_"),
|
||||
["sk", "proj", "secretApiKey1234567890abcdef"].join("-"),
|
||||
["sk", "live", "0123456789abcdef0123456789"].join("_"),
|
||||
["xoxb", "123456789012", "abcdefghijkl"].join("-"),
|
||||
["AKIA", "IOSFODNN7EXAMPLE"].join(""),
|
||||
]) {
|
||||
const issue = validateName(token, new Set(), reserved);
|
||||
expect(issue?.level, `expected error for ${token}`).toBe("error");
|
||||
expect(issue?.message.toLowerCase()).toMatch(/secret|token/);
|
||||
}
|
||||
// Ordinary long variable names must not false-positive.
|
||||
expect(validateName("MY_LONG_ENVIRONMENT_VARIABLE_NAME_2026", new Set(), reserved)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeDuplicateNames", () => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { CompanySecret, EnvBinding, SecretVersionSelector, UserSecretDefinition } from "@paperclipai/shared";
|
||||
import { ENV_VAR_NAME_RE, looksLikeCredentialToken } from "@paperclipai/shared";
|
||||
|
||||
export type RowSource = "text" | "secret" | "user_secret";
|
||||
|
||||
@@ -161,7 +162,7 @@ export function buildFixedClaudeOAuthBinding(): Record<string, EnvBinding> {
|
||||
}
|
||||
|
||||
|
||||
export const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
||||
export const ENV_NAME_RE = ENV_VAR_NAME_RE;
|
||||
|
||||
export type NameIssueLevel = "error" | "warn";
|
||||
export interface NameIssue {
|
||||
@@ -180,6 +181,12 @@ export function validateName(
|
||||
): NameIssue | null {
|
||||
const trimmed = name.trim();
|
||||
if (!trimmed) return null;
|
||||
if (looksLikeCredentialToken(trimmed)) {
|
||||
return {
|
||||
level: "error",
|
||||
message: "Looks like a secret value — put the variable name here (e.g. GH_TOKEN) and store the token in Value",
|
||||
};
|
||||
}
|
||||
if (!ENV_NAME_RE.test(trimmed)) {
|
||||
return { level: "error", message: "Invalid name — use letters, digits and _" };
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import { looksLikeCredentialToken } from "@paperclipai/shared";
|
||||
|
||||
export { looksLikeCredentialToken };
|
||||
|
||||
/**
|
||||
* Sensitive-value detection (plan §6.6). Kept in sync with the server-side
|
||||
* migration heuristic so the UI flags the same things the backend would.
|
||||
@@ -41,6 +45,7 @@ function looksHighEntropy(value: string): boolean {
|
||||
export function isSensitiveEnv(name: string, value: string): boolean {
|
||||
if (!value) return false;
|
||||
if (SENSITIVE_ENV_KEY_RE.test(name)) return true;
|
||||
if (looksLikeCredentialToken(value)) return true;
|
||||
if (CREDENTIAL_VALUE_RES.some((re) => re.test(value))) return true;
|
||||
return looksHighEntropy(value);
|
||||
}
|
||||
@@ -156,8 +156,13 @@ export function RoutineEditDialog({
|
||||
/** Saves the draft, including secrets rows still being typed. */
|
||||
const submit = () => {
|
||||
if (!canSave) return;
|
||||
const flushed = secretsRef.current?.flushPendingDraft() ?? null;
|
||||
onSave(flushed ? { ...draft, env: Object.keys(flushed).length > 0 ? flushed : null } : draft);
|
||||
const flushed = secretsRef.current?.flushPendingDraft();
|
||||
if (flushed?.status === "blocked") return;
|
||||
onSave(
|
||||
flushed?.status === "flushed"
|
||||
? { ...draft, env: Object.keys(flushed.value).length > 0 ? flushed.value : null }
|
||||
: draft,
|
||||
);
|
||||
};
|
||||
|
||||
/** Escape, the close button and Cancel all come here. Nothing closes while a save is running, so a failed save keeps the draft and its error. */
|
||||
|
||||
@@ -46,7 +46,7 @@ export function deliveryModeDescription(mode: SecretDeliveryMode): string {
|
||||
case "env":
|
||||
return "Injected as an environment variable at run start.";
|
||||
case "api":
|
||||
return "Fetched on demand via the run-bound agent API. Never written to the environment.";
|
||||
return "Fetched on demand via the run-bound agent API. Not injected as a $NAME environment variable.";
|
||||
default:
|
||||
return "Provided through adapter configuration.";
|
||||
}
|
||||
|
||||
@@ -1461,6 +1461,14 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
|
||||
await queryClient.invalidateQueries({ queryKey: queryKeys.secrets.list(selectedCompanyId) });
|
||||
},
|
||||
});
|
||||
const rotateSecret = useMutation({
|
||||
mutationFn: (input: { secretId: string; value: string }) =>
|
||||
secretsApi.rotate(input.secretId, { value: input.value }),
|
||||
onSuccess: async () => {
|
||||
if (!selectedCompanyId) return;
|
||||
await queryClient.invalidateQueries({ queryKey: queryKeys.secrets.list(selectedCompanyId) });
|
||||
},
|
||||
});
|
||||
|
||||
// Managed (platform-provisioned) environments accept exactly one tenant
|
||||
// edit: the env var map. The server's write floor rejects everything
|
||||
@@ -1825,9 +1833,12 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
|
||||
navigate(ENVIRONMENTS_PATH);
|
||||
}
|
||||
|
||||
function flushEnvironmentForm(): EnvironmentFormState {
|
||||
function flushEnvironmentForm(): EnvironmentFormState | null {
|
||||
const flushedEnvVars = environmentVariablesEditorRef.current?.flushPendingDraft();
|
||||
return flushedEnvVars ? { ...environmentForm, envVars: flushedEnvVars } : environmentForm;
|
||||
if (flushedEnvVars?.status === "blocked") return null;
|
||||
return flushedEnvVars?.status === "flushed"
|
||||
? { ...environmentForm, envVars: flushedEnvVars.value }
|
||||
: environmentForm;
|
||||
}
|
||||
|
||||
const discoveredPluginSandboxProviders = Object.entries(environmentCapabilities?.sandboxProviders ?? {})
|
||||
@@ -2218,6 +2229,7 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
|
||||
value={environmentForm.envVars}
|
||||
secrets={secrets ?? []}
|
||||
onCreateSecret={async (name, value) => await createSecret.mutateAsync({ name, value })}
|
||||
onRotateSecret={async (secretId, value) => await rotateSecret.mutateAsync({ secretId, value })}
|
||||
onChange={(env) =>
|
||||
setEnvironmentForm((current) => ({ ...current, envVars: env ?? {} }))}
|
||||
onDirtyChange={setEnvironmentVariablesDirty}
|
||||
@@ -2238,7 +2250,10 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => managedEnvironmentEnvVarsMutation.mutate(flushEnvironmentForm().envVars)}
|
||||
onClick={() => {
|
||||
const flushed = flushEnvironmentForm();
|
||||
if (flushed) managedEnvironmentEnvVarsMutation.mutate(flushed.envVars);
|
||||
}}
|
||||
disabled={managedEnvironmentEnvVarsMutation.isPending}
|
||||
>
|
||||
{managedEnvironmentEnvVarsMutation.isPending ? "Saving..." : "Save environment variables"}
|
||||
@@ -2544,6 +2559,7 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
|
||||
value={environmentForm.envVars}
|
||||
secrets={secrets ?? []}
|
||||
onCreateSecret={async (name, value) => await createSecret.mutateAsync({ name, value })}
|
||||
onRotateSecret={async (secretId, value) => await rotateSecret.mutateAsync({ secretId, value })}
|
||||
onChange={(env) =>
|
||||
setEnvironmentForm((current) => ({ ...current, envVars: env ?? {} }))}
|
||||
onDirtyChange={setEnvironmentVariablesDirty}
|
||||
@@ -2574,7 +2590,10 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
|
||||
{environmentForm.driver !== "local" ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => draftEnvironmentProbeMutation.mutate(flushEnvironmentForm())}
|
||||
onClick={() => {
|
||||
const flushed = flushEnvironmentForm();
|
||||
if (flushed) draftEnvironmentProbeMutation.mutate(flushed);
|
||||
}}
|
||||
disabled={draftEnvironmentProbeMutation.isPending || !environmentFormValid || (environmentForm.driver === "ssh" && environmentForm.sshNetwork === "tailscale")}
|
||||
title={environmentForm.driver === "ssh" && environmentForm.sshNetwork === "tailscale" ? "Save this environment, then test its connection from the list." : undefined}
|
||||
>
|
||||
@@ -2582,7 +2601,10 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
onClick={() => environmentMutation.mutate(flushEnvironmentForm())}
|
||||
onClick={() => {
|
||||
const flushed = flushEnvironmentForm();
|
||||
if (flushed) environmentMutation.mutate(flushed);
|
||||
}}
|
||||
disabled={environmentMutation.isPending || !environmentFormValid}
|
||||
>
|
||||
{environmentMutation.isPending
|
||||
|
||||
Reference in new issue
Block a user