Security

Secret scanning

How ulex prevents credentials from reaching logs, prompts, and git: the pre-write scrubber and its patterns, gitleaks in CI, the agent transcript problem, what to do when a key is found, and the redaction rules for audit metadata.

A credential that reaches a log is a credential that must be rotated. ulex treats "it will not happen" as a control with a test suite, not as a policy.

#The pre-write scrubber

Every log line, every error message, every audit metadata value, and every CloudWatch write passes through the scrubber before it is written. Not after, not in a log pipeline, not in a SIEM. In the same code path as the write.

ts
// packages/core/src/scrub.ts
import { createHash } from "node:crypto";

const REDACTIONS: Array<[RegExp, string]> = [
  [/\bulex_sk_(?:live|test)?_[A-Za-z0-9]{16,}/g, "[REDACTED_key]"],
  [/\bcs_[A-Za-z0-9]{16,}/g, "[REDACTED_client_secret]"],
  [/\bscim_[A-Za-z0-9]{16,}/g, "[REDACTED_scim_token]"],
  [/\bwhsec_[A-Za-z0-9]{16,}/g, "[REDACTED_webhook_secret]"],
  [/\b(?:rt|dc|ac|at|st|nc|grt)_[A-Za-z0-9_-]{16,}/g, "[REDACTED_token]"],
  [/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g, "[REDACTED_jwt]"],
  [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, "[REDACTED_private_key]"],
  [/\bAuthorization:\s*\S+.*/gi, "Authorization: [REDACTED]"],
  [/\bbearer\s+[A-Za-z0-9._-]{16,}/gi, "Bearer [REDACTED]"],
];

// Pseudonymise, do not redact, when the value is useful for correlation.
const PSEUDONYMISE: Array<[RegExp, (m: string) => string]> = [
  [/\b[\w.+-]+@[\w-]+\.[\w.-]+\.[a-z]{2,}\b/gi, (m) => `[EMAIL_${sha256Prefix(m)}]`],
  [/\b(?:\d{1,3}\.){3}\d{1,3}\b/g, (m) => `[IP_${sha256Prefix(m)}]`],
  [/\b(?:[0-9a-fA-F]{1,4}:){2,7}[0-9a-fA-F]{1,4}\b/g, (m) => `[IP_${sha256Prefix(m)}]`],
];

const sha256Prefix = (v: string) =>
  createHash("sha256").update(v).digest("hex").slice(0, 12);

export function scrub(input: string): string {
  let out = input;
  for (const [pattern, replacement] of PSEUDONYMISE) out = out.replace(pattern, replacement);
  for (const [pattern, replacement] of REDACTIONS) out = out.replace(pattern, replacement);
  return out;
}

export function scrubValue(value: unknown): unknown {
  if (typeof value === "string") return scrub(value);
  if (Array.isArray(value)) return value.map(scrubValue);
  if (value && typeof value === "object") {
    return Object.fromEntries(
      Object.entries(value as Record<string, unknown>).map(([k, v]) => [k, scrubValue(v)]),
    );
  }
  return value;
}
PatternActionWhy a pseudonym instead of a redaction
ulex_sk_live_…, ulex_sk_test_…redactthe value is useless anywhere
cs_…redactsame
scim_…redactsame
whsec_…redactsame
rt_ dc_ ac_ at_ st_ nc_ grt_redacttokens, state, and nonces are all bearer material
three-segment JWTredactthe payload is readable by anyone holding the log line
PEM private keyredact the whole blockincluding the trailing FOOTER so a partial match cannot leak
Authorization: / Bearerredact the rest of the linecatches every scheme, including ones we have not thought of
email addresspseudonymiseyou still need to correlate a login with a user
IPv4 / IPv6pseudonymiseyou still need to correlate a source
Warning

PII is pseudonymised, not redacted, because a log where every email is [EMAIL_3b1f0c9a7d2e] is still a log you can investigate, and one where every email is [REDACTED] is not. The pseudonym is a salted SHA-256 prefix: correlatable within a tenant, not across.

#The test suite

ts
import { describe, it, expect } from "vitest";
import { scrub } from "@ulex/core";

describe("scrubber", () => {
  const cases: Array<[string, string]> = [
    ["ulex_sk_live_7Qm2KpLx9Tb4Ns8RfWy3Zc1Hjf6Ee0Au", "[REDACTED_key]"],
    ["cs_9fKq2WmB7yLt4NxZ1pRc6HdE0sJg3AuV8", "[REDACTED_client_secret]"],
    ["scim_7Bq4Nxf2Vk9Lc3MdT6hR8wS1yP5aG0eJ", "[REDACTED_scim_token]"],
    ["whsec_3Kq9Xa2mB7yLt4NxZ1pRc6HdE0sJg3AuV8", "[REDACTED_webhook_secret]"],
    ["rt_51KpXq8WvN0kTzRb7YcLd2mXe9Pf6Sg3AuV8", "[REDACTED_token]"],
    [
      "eyJhbGciOiJSUzI1NiIsImtpZCI6ImtleV8wMU0zUFNWSkEwVVAyV0RQTTJSRFIxNU1HSCJ9.eyJzdWIiOiJ1c3JfIn0.sig",
      "[REDACTED_jwt]",
    ],
    ["Authorization: Bearer ulex_sk_live_7Qm2KpLx9Tb4Ns8Rf", "Authorization: [REDACTED]"],
    [
      "-----BEGIN RSA PRIVATE KEY-----\nMIIEow…\n-----END RSA PRIVATE KEY-----",
      "[REDACTED_private_key]",
    ],
  ];

  for (const [input, expected] of cases) {
    it(`redacts ${expected}`, () => {
      expect(scrub(input)).toContain(expected);
      expect(scrub(input)).not.toContain(input);
    });
  }

  it("pseudonymises an email but keeps it correlatable", () => {
    const out = scrub("login ok for dana@acme.example");
    expect(out).toMatch(/\[EMAIL_[0-9a-f]{12}\]/);
    expect(out).not.toContain("dana@acme.example");
    expect(scrub("dana@acme.example")).toBe(scrub("dana@acme.example")); // stable
    expect(scrub("dana@acme.example")).not.toBe(scrub("pat@acme.example"));
  });

  it("does not leave a partial key behind when the block is long", () => {
    const pem = `-----BEGIN PRIVATE KEY-----\n${"A".repeat(400)}\n-----END PRIVATE KEY-----`;
    const out = scrub(`before ${pem} after`);
    expect(out).toBe("before [REDACTED_private_key] after");
  });

  it("fails closed on a non-string", () => {
    expect(() => scrub(undefined as unknown as string)).toThrow();
  });
});

CI fails if any case regresses. The scrubber is a controlled artefact with a contract, not a best effort.

#Never pass a secret as a tool argument

An MCP tool argument is the transcript, the audit log, the vendor's request log, and whatever replays the transcript next month. It is the worst possible place for a secret.

json
// Wrong
{ "name": "ulex_create_connection", "arguments": {
  "config": { "strategy": "okta_oidc", "oidc": { "client_secret": "0oa3kq9x2mB7-Rc3f_T7dLp2XaN8eV5hK4" } }
} }
json
// Right
{ "name": "ulex_create_connection", "arguments": {
  "config": { "strategy": "okta_oidc", "oidc": { "client_secret": "env:ULEX_TEST_OKTA_SECRET" } }
} }

ulex reads ULEX_TEST_OKTA_SECRET from its own environment at request time and stores only the ciphertext. The literal never crosses the wire.

ConnectionField accepting env:
oidcclient_secret
scimtoken
jwtjwks
password.ldapbind_password
password.radiusshared_secret
directoryscim_token, oauth.client_secret

CI blocks it. scripts/check-no-secrets-in-args.ts fails the build if any MCP tool input in the docs, the tests, or the changelog contains a literal matching a secret pattern.

#gitleaks in CI

yaml
secret-scan:
  runs-on: ubuntu-latest
  steps:
    - uses: actions/checkout@v4
      with: { fetch-depth: 0 }
    - uses: gitleaks/gitleaks-action@v2
      env:
        GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }}
    - name: Scan the docs for literal secrets
      run: |
        gitleaks detect --no-git --source docs --config .gitleaks.toml --redact
    - name: Scan the deployed MCP schema
      run: |
        curl -fsS https://ulexid.com/api/v1/.well-known/oauth-protected-resource >/dev/null
        gitleaks detect --no-git --source /tmp/schemas --config .gitleaks.toml --redact

.gitleaks.toml:

toml
[extend]
useDefault = true

[[rules]]
id = "ulex-key"
description = "ulex tenant API key"
regex = '''\bulex_sk_(?:live|test)?_[A-Za-z0-9]{16,}\b'''
keywords = ["ulex_sk"]

[[rules]]
id = "ulex-scim-token"
description = "ulex SCIM bearer token"
regex = '''\bscim_[A-Za-z0-9]{16,}\b'''
keywords = ["scim_"]

[[rules]]
id = "ulex-webhook-secret"
description = "ulex webhook signing secret"
regex = '''\bwhsec_[A-Za-z0-9]{16,}\b'''
keywords = ["whsec"]

[[allowlists]]
description = "documentation placeholders"
paths = [
  '''docs/.*\.example\.(com|test|internal)''',
  '''docs/resources/limits\.mdx''',
]
regexes = ['''EXAMPLE_KEY''', '''YOUR_KEY_HERE''']

gitleaks runs on main, on every pull request, and on a nightly full-history scan. A finding on main is a SEV-2 and pages.

#Detection in production

SignalMeaning
ulex_key_used_from_new_ipa key used from an address that has never used it
api_key.last_used_ip_hash changinga key is now shared, or has moved
mcp.tool_invoked rate spike from one actora loop, or a scrape
impersonation.started on a key you did not use to testa key is being used to log in as users. SEV-1
api_key.created by anything other than CIsomebody is minting credentials
webhook.created pointing at an external domainpossible exfiltration channel
bash
curl -sS -G "$BASE/audit-events" -H "$ADMIN" \
  --data-urlencode 'action_prefix=api_key.' \
  --data-urlencode 'since='"$(date -u -d '30 days ago' +%Y-%m-%dT%H:%M:%S.000Z)" \
  --data-urlencode 'limit=200' | jq '.data[] | {timestamp, action, actor_type, target, ip_hash}'

#When a key is found in a log

Warning

Revoke first. The log is already written; the exposure window starts when the key was created and ends when you revoke it. Every minute of investigation is a minute of live exposure.

bash
# 1. Revoke
curl -sS -X DELETE "$BASE/tenants/current/api-keys/$KEY_ID" -H "$ADMIN"

# 2. Scope the exposure from the audit log
curl -sS -G "$BASE/audit-events" -H "$ADMIN" \
  --data-urlencode "actor_id=$KEY_ID" \
  --data-urlencode 'since='"$(date -u -d '90 days ago' +%Y-%m-%dT%H:%M:%S.000Z)" \
  --data-urlencode 'limit=200' \
  | jq -r '.data[] | "\(.timestamp) \(.action) \(.outcome)"' | sort | uniq -c | sort -rn

# 3. Escalate on the actions that matter
#    impersonation.started  -> someone logged in as a user
#    connection.updated     -> configuration was changed
#    application.updated    -> the client was redirected
#    audit_logs read        -> they were reading what you read

# 4. Rotate and redeploy
curl -sS -X POST "$BASE/tenants/current/api-keys" -H "$ADMIN" -H "$JSON" \
  -d '{"name":"agent-bootstrap-v3","scope":["mcp:tools","read:organizations","write:organizations","read:users","write:users"],"expires_in_days":90}'

# 5. Purge the log
aws logs delete-log-group --log-group-name /aws/lambda/ulex-api-prod --region us-east-1

Purging a CloudWatch group is a break-glass action with its own audit trail. Do it, because a rotated key in a 90-day-retention log is still a discoverable key.

#Audit metadata redaction

audit_event.metadata is free-form and must never contain a secret or raw PHI.

AllowedRejected
{"reason": "Offboarded 2026-09-29"}{"token": "rt_…"}
{"amr": ["pwd","otp","mfa"], "acr": "urn:ulex:acr:mfa"}{"client_secret": "…"}
{"silent": true, "new_application": true, "session_age_seconds": 184}{"email": "dana@acme.example"}
{"artifacts": ["acme-support:9f3c1a7"], "size": "412KiB"}{"password": "…"}
{"from": "dana@acme.example", "to": "dana.okafor@acme.example"} — pseudonymised to [EMAIL_…]{"ip": "203.0.113.42"} — pseudonymised to [IP_…]

Metadata is scrubbed on write, so a mistake is caught before it is stored. But scrubbed metadata is a symptom of a mistake in the calling code, and it shows up in review. The CI check greps the test suite for metadata: literals containing a @ or a secret pattern.

#The rules

  1. Secrets in the environment, not in code, not in arguments.
  2. env:VAR for every secret-shaped field on a connection or a directory.
  3. One key per workload, 90-day expiry, narrow scope.
  4. Rotate on any exposure. No cost, no ceremony.
  5. Assume a log is world-readable and write accordingly.
  6. If a secret reaches a transcript, treat it as compromised. A transcript is not a secret store; it is a document you do not control the retention of.
  7. Verify the chain after any incident. See Verify the audit chain.

#Reference