Skip to main content

Security audit (security-audit)

Overview​

At a configured frequency (and on demand) Alakai clones an application's security branch, a coding agent analyzes the code for security issues at the configured depth, fixes what can be fixed safely in a single PR and posts a summary to #cybersecurity. It complements security-deps (dependencies). Findings that need a person are reported as "requires decision"; the pipeline never asks anyone to fix failing code.

Everything is off by default: SECURITY_AUDIT_ENABLED=false in core, and each application opts in with security.audit.enabled: true.

How it works​

1. Trigger: SecurityAuditScheduler (core)​

One entry point, trigger(app, { depth?, automatic, requestedBy?, slackThread? }), serves the cron and the Slack command.

  • Cron: monthly <m> <hour> <dayOfMonth> * * or weekly <m> <hour> * * <days>, in the configured time zone. <m> is per repository (sha256(repo) mod 60) so the monthly crons that share an hour do not all enqueue at the same minute and take every worker slot.
  • Scheduled run: claim the guard (SET NX, one run per repo per day, 48 h) -> read the security branch HEAD -> if it equals the last audited sha (security-audit.skipped.unchanged), stop -> monthly budget check -> enqueue. A pre-check error releases the guard.
  • Manual run: no period guard and no unchanged-skip; the budget check still applies.
  • One audit per repository at a time: an in-flight marker (<prefix>:security-audit:running:<repo>, 6 h TTL) is claimed before enqueueing and deleted by the orchestrator on /task-complete (success or failure). A manual run that finds it answers "An audit for <repo> is already running"; a scheduled one logs a warning and is skipped until its next schedule (its period guard is released, but a monthly audit does not retry before next month). The marker's value is the audit's task id: only the owner releases it (compare-and-delete), and its TTL restarts when the orchestrator really launches the task (time spent queued does not count). The orchestrator releases it when /task-complete arrives (also without a stored task), when reconciliation finds the worker lost, when a dispatch is dropped (duplicate, attempt budget, last allowed SQS receive) and when a deferred audit is dropped as an orphan duplicate.
  • Payload: repo, security branch, headSha, depth, previousSha, date, reviewers, limits, trigger. Identifiers only (SQS limit 256 KB): the findings memory stays in Redis.

2. Depth levels​

DepthScopePassesAgent timeoutMax runtimeCost cap
quickFiles changed since the last audited sha (whole repo when there is none)1 call per category group20 min60 minSECURITY_AUDIT_QUICK_MAX_COST_USD (10)
standardWhole repo1 call per category group30 min150 minSECURITY_AUDIT_STANDARD_MAX_COST_USD (50)
deepWhole repo+ an independent verification call per batch of 5 findings (fresh session)30 min200 minSECURITY_AUDIT_DEEP_MAX_COST_USD (200)

Categories: authn-authz, injection, framework-config, secrets, sensitive-data, ci-infra, mobile. Agent calls cover [authn-authz], [injection, sensitive-data], [framework-config, ci-infra] and [mobile] (only when the repo has Android/iOS files), so the cost cap can act between calls. secrets comes only from gitleaks, never from the model.

3. The worker​

  1. Clone the security branch (token only through the environment of one git command).
  2. Load .alakai/security-ignore.yml and the findings memory.
  3. Secrets scan: pinned gitleaks git --redact over the whole history. Only rule id, file, line and commit are read. A missing binary reports secrets as skipped and the run continues.
  4. Analysis: one agent call per group. The prompt forbids edits; anything the agent touches is discarded (git status check). Findings whose file does not exist or whose line range is outside the file are dropped; every field is validated by hand.
  5. Classify against the memory: new, persistent, resolved; apply the ignore file.
  6. Deep: independent verification; rejected findings are not reported.
  7. Fix pass: one agent call per fixable finding (at most 15 per run), one commit each (fix(security): <title>), on alakai/security/audit-<YYYY-MM-DD> (-2..-20 if taken). No fix is trusted without a change in the tree.
  8. Verification (best effort): install, build and test of a JavaScript project with a minimal environment (no worker secrets). Failure -> draft PR; nothing runnable (mobile, other stacks) -> normal PR that says "not verified".
  9. Push (never forced), open one PR (labels security, automated pr, ai-generated, reviewers = responsibleUsers) with a summary table, one section per fix, "Requires decision" and the hidden block <!-- alakai-security-audit: {...} --> with the fingerprints. Update the memory and the last audited sha; call back the orchestrator.

No PR is opened when there is no fixed finding. Each run opens a new PR even if an earlier audit PR is open: only what is new goes in it.

4. Findings memory and the ignore file​

Redis keys (prefix <REDIS_KEY_PREFIX>:security-audit:, equal to core's TASK_TRACKING_REDIS_KEY_PREFIX, alakai-<env>):

KeyContent
findings:<repo>hash fingerprint -> { finding, firstSeen, lastSeen, lastRunId, state: open/resolved/ignored, prNumber? }, no TTL
lastsha:<repo>sha of the last completed audit (read by core to skip unchanged repos)
run:<repo>:<date>scheduled guard (core), 48 h
running:<repo>in-flight marker (core claims, orchestrator releases), 6 h

Fingerprint (first 16 hex of sha256): LLM findings category|file|evidence (whitespace removed, lower-cased; line numbers and title excluded on purpose); gitleaks gitleaks|ruleId|file|commit. If the model quotes other lines for the same issue it gets a new fingerprint; every prompt lists the open findings to reduce that.

Dedupe. A finding open in memory is persistent (counted, not repeated, not fixed again) when its PR is open, was closed without merging, does not exist (a decision-only finding) or cannot be read. If its PR was merged and it shows up again it is new ("reappeared after PR #n was merged") and is fixed again; only findings that were fixed in a PR are tied to it (a decision-only finding stays persistent after the merge). To dismiss one for good, add it to the ignore file. Open LLM findings the model does not repeat (its prompt says not to) stay persistent when the stored evidence snippet (normalized and masked, kept for LLM findings only, never for secrets) is still in the same file, or when the model lists their id in stillPresentIds. Resolved = open in memory, neither reported nor still present as above, its category analyzed and (for quick) its file in scope. Findings whose fix failed or was skipped (including when the PR could not be opened) are not remembered, so the next run retries them.

.alakai/security-ignore.yml on the security branch:

version: 1
ignore:
- fingerprint: "a1b2c3d4e5f60708" # preferred
reason: "Endpoint is internal-only behind VPN"
- path: "test/fixtures/**" # glob, any category
reason: "Test fixtures"

Strict: an entry needs a reason and exactly one of fingerprint/path. An invalid file does not stop the run: nothing is ignored and the error is shown in the PR and in Slack.

Secrets never appear in the PR, Slack, logs, memory or analytics: gitleaks runs with --redact, only rule/location/commit are read, and credential shapes in model-written text are masked (redact.ts). Secrets are always requires_decision, listed first under "Immediate action".

5. Slack​

The orchestrator posts (workers have no Slack token) only to SECURITY_SLACK_CHANNEL_ID, because the summary lists unpatched findings. A manual run requested from that channel is answered in the requester's thread; one requested from any other channel is posted as a new message in the security channel, and the requester is told where to find it:

:rotating_light: *Immediate action* (any secret or critical)
• Secret committed (aws-access-token) - `config/aws.ts:1` - rotate it, then remove it
*Security audit* · `acme/api` · standard · 3 new / 2 persistent / 1 resolved
PR: <url|#99>
*Critical:* ... *High:* ... *Medium/Low:* <count> *Requires decision:* ...
Cost: $12.35 · Duration: 14m (limit reached: cost)

Empty sections are omitted, at most 15 items, then +N more in the PR. Each finding is listed once, in its highest section, with its status. Nothing new -> silence (manual runs answer "No new findings"). A failed scheduled run follows Alakai's usual path (dashboard retry, DLQ) with no Slack; a failed manual run answers Audit failed: <reason>. Outside production every message starts with [<env>] .

6. On demand: @Alakai security-audit​

@Alakai security-audit app=<app> [project=<project>] [depth=quick|standard|deep] (the keyword is the first word). Only users in SECURITY_ALLOWED_SLACK_USER_IDS (empty = nobody); the application must have security.audit.enabled: true; 3 per user per hour. project= is needed only when the app name exists in several projects. Without depth= the application's depth is used. Replies are threaded. Without SECURITY_SLACK_CHANNEL_ID on-demand audits are refused, since the summary has nowhere safe to go.

7. Cost caps​

  • Per run: the worker stops starting agent calls once the estimated cost reaches the depth's cap (a call in progress is never cut). The rest is skipped with the reason and limitReached is set; an incomplete audit does not advance lastsha. The sha is also not recorded when the secrets scan did not run, an analysis group was skipped, or a finding ended fix_failed/skipped, so the scheduler does not skip the repo.
  • Monthly: SECURITY_MONTHLY_BUDGET_USD counts audit and deps runs (counter <prefix>:security:cost:<YYYY-MM>, month in America/Montevideo, incremented by the orchestrator). Core refuses an audit when spent + cap(depth) > budget and posts "Monthly security budget reached" once per month; at 80 % it posts one warning per month. Only audits are blocked.

8. Weekly reminder​

With SECURITY_AUDIT_REMINDER_ENABLED=true, Mondays 09:00 America/Montevideo: one message in the security channel listing Alakai and Dependabot security PRs (against the security branch) open more than 7 days; silence when none; once per ISO week.

9. Security PRs and the other workers​

Audit PRs (branch alakai/security/audit-*) are skipped by bug-hunter and the PR classifier when security-deps or security-audit is on for the repo (global switch plus the application's own enabled).

Configuration​

config.json​

// projects.<p>.security
"audit": {
"schedule": { "frequency": "monthly", "dayOfMonth": 1, "hour": 3, "timezone": "America/Montevideo" },
"depth": "standard"
}
// applications.<a>.security
"audit": { "enabled": true, "depth": "quick",
"schedule": { "frequency": "weekly", "days": ["Mon"], "hour": 4, "timezone": "America/Montevideo" } }

schedule is a union on frequency (monthly: dayOfMonth 1-28; weekly: days); defaults: monthly, day 1, 03:00, America/Montevideo; depth standard. Application overrides project overrides default; a schedule is overridden as a whole; enabled exists only on the application. The branch is security.branch -> baseBranch -> the repo default. One schedule and one depth per application.

Environment variables​

VariableServiceDefaultNotes
SECURITY_AUDIT_ENABLEDcorefalsemaster switch (cron, Slack command, bug-hunter/classifier gate)
SECURITY_ALLOWED_SLACK_USER_IDScoreempty = nobodyCSV of Slack user ids
SECURITY_SLACK_CHANNEL_IDcoreunset = no Slackchannel of summaries, notices and the reminder
SECURITY_AUDIT_{QUICK,STANDARD,DEEP}_MAX_COST_USDworker, core10 / 50 / 200core uses them for the budget check: keep them equal
SECURITY_MONTHLY_BUDGET_USDcoreunset = no capcounts audit + deps; only blocks audits
SECURITY_AUDIT_REMINDER_ENABLEDcorefalseweekly reminder
SECURITY_SCAN_LLM_PROVIDER/_MODEL/_EFFORT/_API_KEYworkeranthropic / claude-opus-5-5own key SECURITY_SCAN_LLM_API_KEY (required, no fallback to IMPLEMENTATION); it must exist in Secrets Manager before the worker task definition is deployed
MAX_CONCURRENT_SECURITY_AUDITSorchestrator2per-type cap, see worker pipeline

Invalid values stop the service from starting (core: schema; worker: explicit error).

Prerequisites outside the code​

  • The Alakai bot is a member of #cybersecurity.
  • GitHub App on the installation: Contents: write, Pull requests: write (no new permission).
  • Analytics migration 010 (SECURITY_AUDIT interaction type): deploy core before the worker.
  • Redis maxmemory-policy must not be allkeys-* (the findings memory has no TTL and would be evictable). If it is, the memory moves to S3 in a follow-up.
  • gitleaks is pinned in workers/Dockerfile (version and SHA-256 per architecture).

Analytics​

One SECURITY_AUDIT event per agent run; metadata { repo, depth, phase, categoryGroup, provider }.

Known limitations​

  • Fingerprints change if the model quotes other lines for the same issue.
  • The shared worker task definition (1 vCPU / 4 GB) is kept; deep runs on big repos may need more (measured in the trial).
  • A failed agent run reports no usage, so the monthly counter under-counts.
  • The monthly budget blocks only audits; blocking security-deps runs is a follow-up.
  • The repository's own gitleaks config and ignore file are honored by gitleaks.
  • Verification covers JavaScript projects only; everything else is "not verified".
  • Semgrep or other fixed-rule analyzers are decided after the trial (source is a union).
  • A quick audit also scans the whole git history for secrets.
  • The in-flight marker's 6 h TTL can expire while an audit waits in the deferred list during a large monthly burst, allowing a concurrent manual run. Follow-up: refresh it while deferred.
  • The per-run cost cap and the monthly counter fail open when the model has no seeded price or usage is missing.
  • A monthly budget lower than a depth's cost cap blocks every run of that depth (the refusal says so).
  • lastsha is shared across depths: a manual quick at HEAD makes the next scheduled standard run skip as unchanged.
  • After a publishError the pushed branch stays dangling: the retry uses -2 and nothing cleans the old one.
  • A dashboard retry of a failed audit runs without the in-flight marker (it can overlap a new audit of the same repo).
  • Mobile findings stay open if all the mobile code is deleted in a quick run (the mobile group is not analyzed without mobile files).
  • A deferred audit that a second orchestrator instance is launching at that very moment can be recovered and launched twice during a rolling deploy; the second dispatch is rejected as a duplicate. Dropping a duplicate whose dispatch never launched cannot tell it from a worker run by another instance (the execution record has no ECS task ARN).
  • The monthly budget only counts completed runs: a burst of runs that start together (for example every monthly cron of the same hour) can exceed it. Follow-up: reserve the cap at enqueue.
  • /task-complete is not idempotent: a callback retry after a lost response can double-count the cost and double-post to Slack.
  • security-deps runs now add their cost to the monthly counter even when the audit is disabled (intended, harmless).
  • redactSecrets tests cover only the AWS key and bearer-token shapes (a local hook blocked writing other token-shaped literals); the other patterns are untested.
  • gitleaks may allowlist AKIAIOSFODNN7EXAMPLE: the sandbox fixture should use a different fake AWS-format key.

Local testing and tests​

See workers/security-audit/README.md. Tests: yarn workspace @alakai/worker test (worker, shared), @alakai/core, @alakai/orchestrator, @alakai/github.