mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 06:50:43 +01:00
## 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>
324 lines
14 KiB
TypeScript
324 lines
14 KiB
TypeScript
import { looksLikeCredentialToken } from "@paperclipai/shared";
|
|
import {
|
|
containsSigV4PresignedUrl,
|
|
protectSigV4PresignedUrlParameters,
|
|
} from "./sigv4-presigned-url.js";
|
|
|
|
export { containsSigV4PresignedUrl };
|
|
export const REDACTED_COMMAND_TEXT_VALUE = "***REDACTED***";
|
|
|
|
// Public Executor helper addresses retained for callers of this predicate.
|
|
// Dotted addresses alone do not meet the JWT credential heuristic.
|
|
const PUBLIC_EXECUTOR_TOOL_SELECTORS = new Set([
|
|
"executor.coreTools.integrations.list",
|
|
"executor.coreTools.connections.list",
|
|
"executor.coreTools.policies.list",
|
|
]);
|
|
export function isPublicExecutorToolSelector(value: string): boolean {
|
|
return PUBLIC_EXECUTOR_TOOL_SELECTORS.has(value);
|
|
}
|
|
|
|
const SECRET_NAME_WORDS = String.raw`(?:api[-_]?key|(?:access[-_]?|auth[-_]?)?token|token|authorization(?:[-_]?code)?|bearer|secrets?|passwd|passwords?|credentials?|jwt|private[-_]?key|cookie|connectionstring)(?:[-_]?(?:value|header|prod(?:uction)?|dev(?:elopment)?|test|staging|primary|secondary))*`;
|
|
const SECRET_NAME_PATTERN = String.raw`[A-Za-z0-9_-]*${SECRET_NAME_WORDS}`;
|
|
const SECRET_NAME_START = String.raw`(?<![A-Za-z0-9_-])`;
|
|
const SECRET_OPTION_NAME_PATTERN = String.raw`(?:[A-Za-z0-9_]|-(?!-))*${SECRET_NAME_WORDS}`;
|
|
|
|
const COMMAND_CLI_SECRET_OPTION_RE = new RegExp(
|
|
String.raw`(\B-{1,2}${SECRET_OPTION_NAME_PATTERN}(?:\s+|=)(["']?))[^\s"'` +
|
|
"`" +
|
|
String.raw`]+(\2)`,
|
|
"gi",
|
|
);
|
|
const COMMAND_ENV_SECRET_ASSIGNMENT_RE = new RegExp(
|
|
String.raw`(${SECRET_NAME_START}${SECRET_NAME_PATTERN}\s*=\s*)(?:(\\["'])([\s\S]*?)\2|(["'])([^"'` +
|
|
"`" +
|
|
String.raw`\r\n]*)\4|([^\s"'` +
|
|
"`" +
|
|
String.raw`]+))`,
|
|
"gi",
|
|
);
|
|
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_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}|${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;
|
|
/** Recognize encoded JSON headers, without treating dotted identifiers as tokens. */
|
|
export function looksLikeCredentialJwt(value: string): boolean {
|
|
const segments = value.split(".");
|
|
if (![3, 5].includes(segments.length)) return false;
|
|
if (segments.some((part, index) => {
|
|
// Compact JWE direct encryption has no encrypted-key value.
|
|
if (segments.length === 5 && index === 1 && part === "") return false;
|
|
return !/^[A-Za-z0-9_-]+$/.test(part);
|
|
})) return false;
|
|
if (segments[0].startsWith("eyJ")) return true;
|
|
try {
|
|
const header = JSON.parse(atob(segments[0].replace(/-/g, "+").replace(/_/g, "/")));
|
|
return typeof header === "object" && header !== null && typeof header.alg === "string";
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
const COMMAND_SECRET_HINTS = [
|
|
"api",
|
|
"key",
|
|
"token",
|
|
"auth",
|
|
"bearer",
|
|
"secret",
|
|
"pass",
|
|
"credential",
|
|
"jwt",
|
|
"private",
|
|
"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) {
|
|
const lower = command.toLowerCase();
|
|
return (
|
|
COMMAND_SECRET_HINTS.some((hint) => lower.includes(hint)) ||
|
|
command.includes(".")
|
|
);
|
|
}
|
|
|
|
function containsStandaloneSecretToken(value: string): boolean {
|
|
if (STANDALONE_SECRET_TOKEN_RE.test(value)) return true;
|
|
const jwtMatches = value.match(COMMAND_JWT_RE);
|
|
return jwtMatches !== null && jwtMatches.some(looksLikeCredentialJwt);
|
|
}
|
|
|
|
export function redactCommandText(
|
|
command: string,
|
|
redactedValue = REDACTED_COMMAND_TEXT_VALUE,
|
|
): string {
|
|
if (!maybeContainsSecretText(command)) return command;
|
|
const { text, restore } = protectSigV4PresignedUrlParameters(
|
|
command,
|
|
containsStandaloneSecretToken,
|
|
);
|
|
return restore(redactSetAsideCommandText(text, redactedValue));
|
|
}
|
|
|
|
function redactSetAsideCommandText(command: string, redactedValue: string): string {
|
|
return command
|
|
.replace(COMMAND_AUTHORIZATION_BEARER_RE, `$1${redactedValue}`)
|
|
.replace(COMMAND_CLI_SECRET_OPTION_RE, `$1${redactedValue}$3`)
|
|
.replace(
|
|
COMMAND_ENV_SECRET_ASSIGNMENT_RE,
|
|
(
|
|
_match,
|
|
prefix: string,
|
|
escapedQuote: string | undefined,
|
|
_escapedValue: string | undefined,
|
|
rawQuote: string | undefined,
|
|
) => {
|
|
const quote = escapedQuote ?? rawQuote;
|
|
return quote
|
|
? `${prefix}${quote}${redactedValue}${quote}`
|
|
: `${prefix}${redactedValue}`;
|
|
},
|
|
)
|
|
.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);
|
|
}
|
|
|
|
// A JSON secret field is a key/value pair such as `"token":"opaque-value"`. The
|
|
// command redaction handles shell `KEY=value` syntax only. A sandbox diagnostic
|
|
// can also carry a serialized JSON error, so the sanitizer must redact the JSON
|
|
// form too. The value body consumes JSON escape sequences. An escaped quote
|
|
// (`\"`) inside the value does not end the match early.
|
|
const JSON_SECRET_FIELD_RE = new RegExp(
|
|
String.raw`("(?:${SECRET_NAME_PATTERN})"\s*:\s*")(?:\\[\s\S]|[^"\\])*(")`,
|
|
"gi",
|
|
);
|
|
// An escaped JSON secret field is the same pair inside a JSON string. The double
|
|
// quote appears as `\"` and a backslash appears as `\\`. The value body
|
|
// consumes the doubled escape sequences. An escaped quote inside the value does
|
|
// not end the match early. The value ends at the next unescaped `\"`.
|
|
const JSON_ESCAPED_SECRET_FIELD_RE = new RegExp(
|
|
String.raw`(\\"(?:${SECRET_NAME_PATTERN})\\"\s*:\s*\\")(?:\\\\\\\\|\\\\\\"|\\\\[\s\S]|[^\\"])*(\\")`,
|
|
"gi",
|
|
);
|
|
|
|
/**
|
|
* Redact secrets from an untrusted diagnostic string.
|
|
*
|
|
* The function first runs the command redaction. The command redaction handles
|
|
* shell `KEY=value` assignments, CLI secret options, bearer headers, and common
|
|
* token shapes. The function then redacts JSON and escaped-JSON secret fields,
|
|
* because a sandbox diagnostic can carry a serialized JSON error such as
|
|
* `{"token":"opaque-value"}`. The caller must still bound the length after this
|
|
* step.
|
|
*/
|
|
export function redactDiagnosticText(
|
|
text: string,
|
|
redactedValue = REDACTED_COMMAND_TEXT_VALUE,
|
|
): string {
|
|
return redactCommandText(text, redactedValue)
|
|
.replace(JSON_ESCAPED_SECRET_FIELD_RE, `$1${redactedValue}$2`)
|
|
.replace(JSON_SECRET_FIELD_RE, `$1${redactedValue}$2`);
|
|
}
|
|
|
|
const PUBLIC_ENV_KEYS = new Set([
|
|
"PATH", "PATHEXT", "SYSTEMROOT", "WINDIR", "COMSPEC", "HOME", "USERPROFILE",
|
|
"HOMEDRIVE", "HOMEPATH", "USER", "USERNAME", "LOGNAME", "SHELL", "LANG",
|
|
"LANGUAGE", "LC_ALL", "LC_CTYPE", "TZ", "TMPDIR", "TEMP", "TMP", "NODE_ENV",
|
|
"XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME",
|
|
"PWD", "OLDPWD", "INIT_CWD", "SHLVL", "_", "TERM", "TERM_PROGRAM", "TERM_PROGRAM_VERSION", "COLORTERM",
|
|
"NPM_LIFECYCLE_EVENT", "NPM_COMMAND", "NPM_EXEC_PATH", "NPM_EXECPATH", "NPM_NODE_EXECPATH",
|
|
"NPM_PACKAGE_NAME", "NPM_PACKAGE_VERSION", "NPM_PACKAGE_JSON", "NPM_CONFIG_USER_AGENT",
|
|
"XPC_SERVICE_NAME", "VITEST_POOL_ID", "VITEST_WORKER_ID",
|
|
"REGION", "AWS_REGION", "AWS_DEFAULT_REGION", "KEYBOARD_LAYOUT", "PUBLIC_KEY_PATH", "PUBLIC_KEY",
|
|
"SORT_KEY", "CACHE_KEY", "ROUTING_KEY", "PARTITION_KEY", "IDEMPOTENCY_KEY",
|
|
"PAPERCLIP_AGENT_ID", "PAPERCLIP_COMPANY_ID", "PAPERCLIP_RUN_ID", "PAPERCLIP_TASK_ID",
|
|
]);
|
|
const PUBLIC_BOOLEAN_ENV_KEYS = new Set([
|
|
"OPENCODE_ALLOW_ALL_MODELS", "CLAUDE_CODE_USE_BEDROCK", "GOOGLE_GENAI_USE_GCA",
|
|
"CI", "NO_COLOR", "FORCE_COLOR",
|
|
"VITEST", "MALLOCNANOZONE", "CODEX_CI", "CODEX_SHELL", "CODEX_SAGE_BACKFILL_TRACKER_TAB_REUSE",
|
|
"DEV", "PROD", "SSR", "PAPERCLIP_REQUIRE_SENTRY_TEST_SDK",
|
|
"PAPERCLIP_DB_BACKUP_ENABLED", "PAPERCLIP_WORKSPACE_COMPACTION_ENABLED", "PAPERCLIP_AUTH_DISABLE_SIGN_UP", "PAPERCLIP_ENABLE_COMPANY_DELETION",
|
|
"PAPERCLIP_STORAGE_S3_FORCE_PATH_STYLE", "PAPERCLIP_SECRETS_STRICT_MODE",
|
|
"SERVE_UI", "PAPERCLIP_UI_DEV_MIDDLEWARE", "HEARTBEAT_SCHEDULER_ENABLED", "PAPERCLIP_ANNOUNCEMENTS_ENABLED",
|
|
"GITHUB_ACTIONS", "GITHUB_REF_PROTECTED", "RUNNER_DEBUG", "ACTIONS_RUNNER_DEBUG", "ACTIONS_STEP_DEBUG",
|
|
]);
|
|
const PUBLIC_NUMBER_ENV_KEYS = new Set([
|
|
"PORT", "PAPERCLIP_DB_BACKUP_INTERVAL_MINUTES", "PAPERCLIP_DB_BACKUP_RETENTION_DAYS",
|
|
"PAPERCLIP_WORKSPACE_REAPER_COOLDOWN_DAYS", "PAPERCLIP_WORKSPACE_COMPACTION_DELAY_HOURS",
|
|
"HEARTBEAT_SCHEDULER_INTERVAL_MS",
|
|
"GITHUB_RUN_ATTEMPT", "GITHUB_RUN_NUMBER", "GITHUB_RUN_ID", "GITHUB_RETENTION_DAYS",
|
|
]);
|
|
|
|
// A setting name and a bounded value must agree before it is public. Unknown
|
|
// opaque values remain private; declared bindings always override these rules.
|
|
function isOrdinaryDiagnosticEnvSetting(key: string, value: string): boolean {
|
|
const name = key.toUpperCase();
|
|
if (PUBLIC_ENV_KEYS.has(name)) return true;
|
|
if ((PUBLIC_BOOLEAN_ENV_KEYS.has(name) || /(?:^|_)(?:FLAG|ENABLED|DISABLED|DEBUG)$/.test(name)) &&
|
|
/^(?:0|1|true|false)$/i.test(value)) return true;
|
|
if ((PUBLIC_NUMBER_ENV_KEYS.has(name) || /(?:^|_)(?:COUNT|WORKERS|PORT|MAX_TOKENS)$/.test(name)) &&
|
|
/^\d+$/.test(value)) return true;
|
|
return (name === "BASE_URL" && value === "/") ||
|
|
(/(?:^|_)MODE$/.test(name) && /^(?:test|development|production|safe)$/.test(value)) ||
|
|
(name === "PAPERCLIP_SENTRY_RUN_FAILURES" && /^(?:off|unexpected|all)$/.test(value));
|
|
}
|
|
|
|
/** In the host process environment, an undeclared value under an
|
|
* unrecognized name is redacted as a substring only if it could be a
|
|
* credential: at least 8 characters, and not a bare number, hex number or
|
|
* boolean-like word. Shorter values ("vi", "RUN") are redacted only as whole
|
|
* tokens (`collectHostEnvironmentTokenSecrets`): as substrings they corrupted
|
|
* unrelated report text ("service" became "ser***REDACTED***ce"). Declared,
|
|
* secret-named and credential-shaped values are always substring-private. An
|
|
* agent's configured environment keeps the fail-closed substring rule. */
|
|
function plausibleUndeclaredCredential(key: string, value: string): boolean {
|
|
if (credentialNameSegments(key)) return true;
|
|
return value.length >= 8 && !/^(?:\d+|0x[0-9a-f]+|true|false|on|off|yes|no)$/i.test(value);
|
|
}
|
|
|
|
const CREDENTIAL_SEGMENTS = new Set(["TOKEN", "TOKENS", "SECRET", "SECRETS", "PASSWORD", "PASSWD", "PASSPHRASE",
|
|
"CREDENTIAL", "CREDENTIALS", "PRIVATE", "BEARER", "AUTHORIZATION", "APIKEY"]);
|
|
|
|
/** A name with a credential segment (AWS_SECRET_ACCESS_KEY, AWS_BEARER_TOKEN_BEDROCK),
|
|
* or a KEY segment that is last or followed only by ID (KEY, AWS_ACCESS_KEY_ID).
|
|
* Such a value stays private whatever its length. */
|
|
function credentialNameSegments(key: string): boolean {
|
|
const segments = key.toUpperCase().split(/[^A-Z0-9]+/).filter(Boolean);
|
|
return segments.some((segment, index) => CREDENTIAL_SEGMENTS.has(segment) ||
|
|
(segment === "KEY" && (index === segments.length - 1 || (index === segments.length - 2 && segments[index + 1] === "ID"))));
|
|
}
|
|
|
|
const BOOLEAN_WORD = /^(?:true|false|on|off|yes|no)$/i;
|
|
|
|
/**
|
|
* Host process values under unknown names that are too short or too plain to
|
|
* redact as substrings (see `plausibleUndeclaredCredential`). They are still
|
|
* private: callers redact them where they appear as a whole token, numbers
|
|
* included. Only flag values are exempt (boolean words, and `0` or `1`): they
|
|
* cannot hold a credential, and as tokens they would erase ordinary words
|
|
* ("on", "no") and exit codes from every report.
|
|
*/
|
|
export function collectHostEnvironmentTokenSecrets(env: unknown): string[] {
|
|
if (!env || typeof env !== "object") return [];
|
|
const substringValues = new Set(collectDiagnosticEnvironmentSecrets(env, [], { hostProcess: true }));
|
|
const values = new Set<string>();
|
|
for (const [key, value] of Object.entries(env)) {
|
|
if (typeof value !== "string" || !value.trim() || substringValues.has(value)) continue;
|
|
if (isOrdinaryDiagnosticEnvSetting(key, value) || BOOLEAN_WORD.test(value) || /^[01]$/.test(value)) continue;
|
|
values.add(value);
|
|
}
|
|
return [...values].sort((a, b) => b.length - a.length);
|
|
}
|
|
|
|
/** Select private values while preserving explicit ordinary process settings. */
|
|
export function collectDiagnosticEnvironmentSecrets(
|
|
env: unknown,
|
|
secretKeys: Iterable<string> = [],
|
|
options: { hostProcess?: boolean } = {},
|
|
): string[] {
|
|
if (!env || typeof env !== "object") return [];
|
|
const declared = new Set(secretKeys);
|
|
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) ||
|
|
redactDiagnosticText(value) !== value || looksLikeCredentialJwt(value) ||
|
|
/-----BEGIN (?:[A-Z]+ )*PRIVATE KEY-----/.test(value) ||
|
|
(!isOrdinaryDiagnosticEnvSetting(key, value) && (!options.hostProcess || plausibleUndeclaredCredential(key, value)))) {
|
|
values.add(value);
|
|
}
|
|
try {
|
|
const url = new URL(value);
|
|
if (url.password) {
|
|
values.add(value);
|
|
values.add(url.password);
|
|
values.add(decodeURIComponent(url.password));
|
|
}
|
|
} catch { /* ordinary settings and malformed URLs need no URL projection */ }
|
|
}
|
|
return [...values].sort((a, b) => b.length - a.length);
|
|
}
|