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:
DottaandPaperclip authored and GitHub committed 2026-11-25 22:08:28 +00:00
1 parent a74b4f8196
commit 079fb1fe63
26 files changed
+1668 -89

No files matched your search

@@ -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", () => {
+64
View File
@@ -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);
});
});
+38 -2
View File
@@ -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
View File
@@ -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 };
}
+43 -7
View File
@@ -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}`);
}