Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
170 changes: 170 additions & 0 deletions docs/CODE_REVIEW_LENSES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
# Code review lenses

A set of focused, threshold-driven review lenses an AI coding agent (or a human
reviewer) can apply to a diff. They are deliberately narrow and verifiable: each
lens reports concrete findings with `file:line`, a severity, and a fix — not vibes.

These three lenses cover the **security and data-safety** surface that kit cares
about. They complement kit's other security docs:

- `docs/OWASP_2025.md` — the threat catalogue the security lens maps to.
- `docs/THREAT_MODEL.md` — kit's own threat model.
- `docs/VERIFY.md` — how to verify a change actually works before claiming it does.

Wire them into an agent with the templates in `examples/agent-hooks/` so the
agent self-reviews before it commits. Each lens is standalone — apply only the
ones a given change touches.

---

## Lens: verified-security

You review the change for security — **but every finding must be verified against
the actual source before you report it.** This lens has the worst false-positive
rate of any review lens. A speculative "this might be exploitable" without reading
the code is not a finding; it is noise that wastes the team's time.

### Hard rule (the calibration)

Before reporting any security finding, **read the actual handler, policy, query,
or config that backs it** and confirm the vulnerability is real. Cite `file:line`.
If you cannot point to the exact line that is exploitable, you do not have a
finding — note it as "to verify" at most.

### Ask of the change

1. **Authorization & data scoping.** Every read/write is scoped to the requesting
principal (tenant/org/owner), not global. Row-level / access policies are
tenant-scoped — no blanket-true policy (`USING (true)` / `WITH CHECK (true)`)
on user data.
2. **AuthN + AuthZ on every entry point.** Each route / endpoint / RPC checks
authentication AND that the caller may act on the specific object. No missing
check on a "secondary" handler.
3. **IDOR.** Object IDs from the client are re-checked against the caller's scope
server-side — you can't fetch/mutate another tenant's object by changing an ID.
4. **Privilege-escalation surfaces.** Elevated / `SECURITY DEFINER`-style
functions pin a safe search path / scope and don't leak elevated rights to the
caller.
5. **Input validation & injection.** Inputs validated server-side; parameterized
queries; no string-built SQL/commands; output encoded for its sink.
6. **Price/total integrity.** Amounts and totals are computed and trusted
server-side only — the client cannot manipulate what it pays. (Overlaps
revenue-recon; flag here if it's a security bypass, not just a reconciliation
gap.)
7. **Secrets.** No secrets/keys/tokens committed or sent to the client.
Signed/expiring URLs for file access, never public buckets.

### Output

For each VERIFIED finding: severity, `file:line` you read, the concrete exploit
(who can do what to whom), and the fix. Mark anything unverified explicitly as
"to verify" — do not inflate it to a finding.

---

## Lens: db-safety

You review the change for **database and migration discipline**. The schema is
shared, durable, and hard to roll back once data exists. The goal: every schema
change is forward-only-safe, reversible in principle, and can never destroy
production data.

This lens fires whenever the change touches a migration, schema definition, or
data-mutating statement (DDL, seed, backfill, ad-hoc SQL).

### Ask of the change

1. **Migration naming & ordering.** New migrations use a timestamped naming
scheme (`YYYYMMDDHHMMSS_<description>`, UTC) so they apply in a deterministic
order. No reused or out-of-order timestamps that collide with already-applied
migrations.
2. **Isolate fragile DDL.** Statements the engine refuses to run inside a
transaction or alongside other DDL (e.g. enum-value additions like
`ALTER TYPE ... ADD VALUE`, concurrent index builds) live in their **own**
migration file — not bundled with dependent changes.
3. **Additive & reversible.** Prefer additive changes (new nullable column, new
table) over destructive ones. A drop/rename/type-change is staged: add new →
backfill → switch reads → drop old in a later migration, so a deploy can be
rolled back without data loss. There is a down path or an explicit, documented
reason there isn't.
4. **Never auto-reset or destroy.** No command that wipes or recreates the
database (`db reset`, drop-and-recreate, truncate) in any dev/CI/automation
path that could reach a real environment. Migrations apply incrementally; data
is preserved.
5. **No unscoped destructive DML.** No `DELETE`/`UPDATE` without a `WHERE`, no
`DROP TABLE`/`TRUNCATE` against a populated table, in migrations or scripts.
Backfills are idempotent and bounded.
6. **Access control on by default.** New tables ship with row-level/access
policies enabled and tenant/owner-scoped from the first migration — never an
unprotected table left "to secure later", never a blanket-true policy on user
data. New privileged functions pin a safe search path / scope. (Overlaps
verified-security; flag here as a schema-level default gap.)
7. **Typecheck/build after schema change.** Generated DB types are regenerated
and the build / typecheck is run after a schema change, so renamed or dropped
columns surface as compile errors rather than runtime failures.

### Failure modes to hunt

- Enum value or concurrent index added in the same migration as code that depends
on it → fails to apply or half-applies.
- A column dropped/renamed in one migration with reads still pointing at the old
name → a rollback (or a slow rollout) breaks production.
- A `db reset` / drop-recreate hiding in a setup, seed, or CI script reachable
from prod creds.
- A backfill `UPDATE` with no `WHERE` that rewrites every row.
- New table created without access policies, or with `USING (true)`.
- Schema changed but generated types stale → silent runtime breakage.

### Output

For each finding: severity, file:line (the migration/script), the risk (what data
is lost or what deploy breaks), and the fix — ideally the additive/staged
alternative.

---

## Lens: revenue-recon

**Mandatory for any change touching money, payments, inventory, or stock.** Never
skip it for those flows — this is the single most-missed class of bug and a
generic reviewer rarely thinks to ask it.

You are a reviewer whose only job is to confirm the change **reconciles**: every
unit of money and every unit of stock is accounted for, exactly once, and ends up
where downstream systems expect it.

### Ask of the change

1. **Does it create or move money?** A transaction/order/payment/refund record, a
balance change, a payout. If so: is the amount derived server-side (never
trusted from the client)? Is it recorded exactly once (idempotent against
retries/double-submit/webhook replay)?
2. **Does it move inventory/stock?** Is the decrement/increment atomic with the
sale, so a failure can't leave money taken but stock untouched (or vice versa)?
Can it go negative?
3. **Does it feed downstream reconciliation?** Totals, tax/VAT, daily
settlement/close-out, reporting, payouts, ledgers. If a number flows into any
aggregate, confirm it lands there with the right sign, currency, and rounding —
and isn't double-counted.
4. **Currency & rounding.** Single currency assumed? Integer minor units
(cents/öre) vs floats? Rounding applied once, consistently, at the documented
boundary?
5. **Reversibility.** Refund/void/cancel paths reverse both money AND stock
symmetrically. No path leaves the two out of sync.

### Failure modes to hunt

- Money charged but the record/stock update fails silently (no transaction
wrapping the two).
- Webhook or retry processed twice → double charge / double decrement (no
idempotency key).
- Total computed on the client and trusted by the server (price integrity).
- Float arithmetic on currency; rounding applied in two places.
- A sale that never reaches the settlement/reporting aggregate, or reaches it
twice.

### Output

For each finding: severity (blocker/high/med/low), file:line, the reconciliation
it breaks, and the fix. If the flow is fully reconciled, say so explicitly —
silence is not a pass.
65 changes: 65 additions & 0 deletions docs/HOST_OPS_CAPTURE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Host-ops Capture

Any machine that runs unattended — a VPS, a bot host, a build box, a self-hosted
service — accumulates operational state that lives only on disk and in one
person's head. When that box dies, gets reimaged, or the person leaves, the config
is gone. The fix is simple and non-negotiable: **the server's governance lives in
the repo, not on the server.** If you can't rebuild the box from version control,
you don't control it.

This pairs with kit's secret handling: capture the *config* in the repo, keep the
*values* in a vault. Names and structure are committed; secrets are referenced.

## The rule

Whenever you stand up or change an always-on host, commit the artifacts below to a
tracked `ops/<host>/` (or `infra/<host>/`) directory, and keep them in sync when
they change on the box. Secrets are referenced, never committed.

## Capture checklist

- [ ] **systemd units** (or equivalent supervisor config) — every `*.service`,
`*.timer`, and any drop-in overrides for daemons the box runs. Copy them from
`/etc/systemd/system/` (and `--user` units) into the repo verbatim.
- [ ] **Reverse-proxy / web-server config** — the nginx / Caddy / Traefik server
blocks, TLS settings, and upstream routing. Note where certs come from
(e.g. ACME issuer) — the renewal mechanism, not the private key.
- [ ] **Cron jobs / scheduled tasks** — crontab entries and any systemd timers,
with what they run and on what cadence. A scheduled job nobody remembers is a
future outage.
- [ ] **Backup scripts + schedule** — the backup command/script, what it backs up,
where it writes, retention, and how the schedule is wired (cron/timer).
- [ ] **Firewall / network rules** — open ports, allow-lists, and any VPN/overlay
network membership, enough to reproduce the network posture.
- [ ] **Env / config inventory** — the *names* and purpose of required env vars and
config files (e.g. an `.env.example`), and where each secret is sourced from
(which vault/secret store). Never the secret values.
- [ ] **Service inventory** — a short list of every long-running process on the box
and its purpose, so an outsider knows what is supposed to be running.

## Restore runbook (the other half — write it)

Committing config files is not enough; an operator under pressure needs the
*sequence*. Write `ops/<host>/RESTORE.md` covering, in order:

1. **Provision** — OS/image, sizing, and where to get it (provider, region).
2. **Bootstrap** — install the runtimes/packages the services need.
3. **Place config** — copy the committed units/proxy/cron into their system paths,
reload the supervisor (`systemctl daemon-reload`, enable + start units).
4. **Inject secrets** — where each secret comes from and how it lands on the box
(secret manager/vault, manual placement) — referencing the env inventory above.
5. **Restore data** — how to recover from the latest backup, and how to verify it.
6. **Verify** — concrete checks that prove the box is healthy: services active,
proxy answering, a smoke request succeeding, backups running again.

Keep it executable in spirit: each step should be a command or a precise pointer,
not a vague gesture. Prefer scripts the runbook invokes over prose the operator
must translate.

## Sync discipline

Drift kills this practice. When you change a unit, proxy block, cron entry, or
backup script *on the box*, mirror the change into the repo in the same work — the
committed copy is the source of truth, the box is a deployment of it. A periodic
diff between the live config and the committed copy catches silent drift before an
outage does.
77 changes: 77 additions & 0 deletions docs/SECRETS_LIFECYCLE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Secrets Lifecycle

A secret's *name* belongs in the repo; its *value* never does. Config references a
key (`DATABASE_URL`, `STRIPE_SECRET_KEY`); the value is resolved at runtime from a
secret store. If a value reaches git history, a script, a CI log, or a screenshot,
it is compromised — go to [Leak response](#leak-response). This guide is the decision
layer that pairs with kit's vault backends and its secret prescan (`kit prescan`,
backed by gitleaks): the scan and the vault enforce *where values live*; this doc
owns the part tooling can't — how you provision, rotate, and respond when a value
leaks.

## Provision

- Commit an `.env.example` of key **names + purpose only** — never a real value.
kit's `.env.template` follows this convention.
- Mint a fresh, scoped credential per service per environment (dev/staging/prod);
one leaked dev key must not unlock prod.
- **Never inline a secret in a script.** The classic anti-pattern is a backup
script with the DB password in the connection string so cron "just runs it" —
that value is now in git, in shell history, in every CI log, and in `ps`. Read
it from the environment instead:

```bash
# BAD — secret committed forever:
pg_dump "postgresql://admin:S3cr3tP@ss@db/app" > backup.sql
# GOOD — injected at runtime, file is safe to commit:
: "${DATABASE_URL:?DATABASE_URL not set}"; pg_dump "$DATABASE_URL" > backup.sql
```

- Keep secrets off the command line (visible in `ps`/history); use env or a file.

## Store

- One source of truth: a managed **secret store / vault** — not a doc, chat, or
hand-passed `.env`. A vault gives you access control, audit logs, versioning,
and rotation in one place. kit supports a range of vault backends so the same
config resolves against whichever store a team already uses.
- Inject at runtime (a `run`/`exec` wrapper that loads the vault, a sidecar, or a
platform env binding); don't copy values around. Local dev uses a gitignored
`.env.local` sourced from the store. Scope least-privilege per environment.
- Defense at the boundary: a pre-commit secret scan (`kit prescan`) plus the host's
push protection; `.env*` gitignored except `.env.example`.

## Rotate

Rotate on a **cadence** (≈90 days for API/DB keys; 180 for signing/webhook
secrets) **and** on any trigger (leak, offboarding, vendor advisory). Zero-downtime
procedure: **issue** new → **store** it → **roll out** → **verify** → **revoke**
old → **record** the date so the next rotation is scheduled. Use a dual-key window
where the provider allows two live keys.

## Leak response

A secret is leaked the moment its value lands anywhere uncontrolled. Assume
compromise — don't debate it. **Revoke within minutes; fully rotated within the
hour.** Scrubbing git history does *not* un-leak it; revoking does.

1. **Detect & contain** — which secret, where, exposure window. Start the clock.
2. **Revoke/rotate first** — invalidate the exposed value at the provider, then
issue + store + roll out a replacement. This is the action that closes the door.
3. **Rotate dependents** — anything derived from, sharing a key with, or reachable
*using* the leaked secret (session keys, downstream tokens). Map blast radius
from vault access scopes.
4. **Audit for abuse** — provider + store logs for the window: odd IPs, unusual
calls, data egress, new keys/grants. Escalate if abuse found.
5. **Document** — short post-incident note: what leaked, root cause, window,
actions + timestamps, and the prevention fix; feed it back into your runbook.

| Step | Target |
|---|---|
| Detect → revoke | minutes |
| Replacement rolled out | < 1 hour |
| Dependents rotated | same incident |
| Abuse audit | < 24 hours |

> Deleting the secret from a file or rewriting history is **not** remediation.
> Once exposed, the only fix is to make the value worthless by revoking it.
Loading