11 Commits

Author SHA1 Message Date
1214dc8030 fix(ledger-core,card-issuance): bridge-funding's HOLD could land on a deposit webhook-ingestion had already settled
RationBridgeFunding reads a deposit as late, then several RPC round
trips later applies a HOLD referencing that deposit_id — with nothing
serializing that gap against webhook-ingestion's own, separate-process
handleTransactionCreated marking the SAME deposit received in between.
mark_deposit_received_with_entry only releases bridge holds that exist
at the moment it runs, so a hold created afterward is permanently
unreleasable. Round 25/26's per-tenant locks live in different OS
processes and cannot fix this.

Fixes it the same way apply_entry already re-validates the reserve
floor atomically: ApplyEntryRequest gains an optional
require_deposit_outstanding_id, checked under ledger-core's own single
mutex before any mutation (apply_entry_checked), returning
DepositAlreadyReceived instead of applying the hold. bridge.Service
now always sets this on its bridge-hold ApplyEntry call and declines
cleanly instead of stranding funds.

Reproduced the exact interleaving via a deterministic raceLedger test
(confirmed it fails without the fix, passes with it, under go test
-race). Live-reproduced the race window against the real 8-service
stack; happy path and full build/test matrix unaffected.
2026-10-29 18:51:07 +03:00
5bb6bc92f2 fix(card-issuance): persist card metadata — a restart silently lost every issued card forever
cardsvc.Service's own `cards map[string]*cardissuancepb.Card` was the
only place this repo stores Card metadata (ledger-core's proto has no
Card message), and it was pure in-memory state with zero durability.
A card-issuance restart lost every issued card's id/cardholder/limit/
status while the ledger HOLD backing its limit lived on in ledger-core
forever, unreachable by GetCard/AdjustCardLimit/CloseCard ever again
(all three look the card up by id first). card_issuance.proto's own
service comment also claimed this service was "stateless... safe to
run as N replicas" — false given this in-memory map; corrected.

Adds a file-backed store (services/card-issuance/internal/cardsvc/
store.go): atomic write-then-fsync-then-rename JSON file, loaded on
startup via a new EnablePersistence(path) method (opt-in, so existing
unit tests that never call it are unaffected) and written after every
IssueCard/AdjustCardLimit/CloseCard. New RATION_CARD_ISSUANCE_DATA_DIR
env var (default ./data, same convention as RATION_AUDIT_LOG_DATA_DIR),
wired in main.go.

Verified live against the real bare-metal stack: issued a card,
confirmed data/cards.json held it, killed and restarted card-issuance,
and confirmed `ration card get`/`ration status` still found the card
(pre-fix this would have been NotFound). go build/vet/test clean for
card-issuance (0 regressions), full `make build` clean.

Does not make this service safe to run as N replicas (each replica
would still load/save its own independent copy of the file) — that
needs a real shared store, the same class of gap already named and
left open for services/auth's apikey.Store; documented, not attempted,
in this round.
2026-10-29 13:53:46 +03:00
c3236f0bca feat(card-issuance,gateway,cli): add CloseCard — issued cards could never be shut off
CARD_STATUS_SUSPENDED/CLOSED have existed in common.proto since the
original build, and the Airwallex client package even defined
CardStatusSuspended/CardStatusClosed constants, but nothing in this
repo ever transitioned a stored card into either state: card-issuance's
airwallex.Client interface only exposed IssueCard/GetCard/
SetCardControls (limit/controls only, never status), so a leaked
credential, an offboarded cardholder's card, or any card that should
stop spending forever had no real operator path to close — only
"adjust-limit" to a smaller (but still nonzero-possible, still active)
limit.

Adds card_issuance.proto/gateway.proto's CloseCard RPC, a real
airwallex.Client.CloseCard on both Mock and Live (POST
/api/v1/issuing/cards/{id}/close), cardsvc.Service.CloseCard (releases
the card's full remaining ledger HOLD back to the tenant's available
balance, idempotent on an already-closed card), the gateway fan-out,
and `ration card close --card <id>`. AdjustCardLimit now rejects a
closed card instead of silently reopening a zombie hold.

tenantauth/ratelimit needed zero changes: both resolve card_id via
reflection, so CloseCardRequest's card_id field is automatically
tenant-scoped and rate-limited the same way GetCard/AdjustCardLimit
already are.

Verified live against the real bare-metal 7-service stack
(scripts/run-demo.sh): issued a real card (Held 1,000.00 USD), closed
it (status CLOSED, Held back to 0.00, Available back to 7,500.00),
re-closed it (idempotent — Available unchanged, no double-release),
confirmed adjust-limit on the closed card is rejected, and confirmed
closing an unknown card_id surfaces the same NotFound-wrapped error
GetCard/AdjustCardLimit already do. verify-chain: intact (5 records).
`go build`/`go vet` clean across every Go module (gateway,
card-issuance, cli, tui, auth, tenant-registry, webhook-ingestion,
agent, audit-log, sdk/go/ration), full `make build` (Rust+Go+SDK)
clean, 0 regressions.
2026-10-29 11:35:23 +03:00
9972a6b846 feat(auth,cli): add ration apikey list; fix(docs): THREAT-MODEL.md was stale about its own closed gaps
`apikey issue`/`revoke` had no read side: an operator could mint or
revoke a key by key_id, but had no way to discover what key_ids exist
in the first place — only a key_id personally kept from its own
one-time `issue` output could ever be acted on. Adds auth.proto's
ListAPIKeys RPC, apikey.Store.List (sorted, tenant-filterable), the
server implementation, a CLI authclient wrapper, and `ration apikey
list [--tenant <id>]` — never returning the plaintext secret, which is
never stored anywhere after issuance.

Verified live against the real bare-metal 8-service stack
(scripts/run-demo.sh): issue -> list -> simulate-deposit --late ->
agent poll -> status (real recorded bridge-funding decision) ->
revoke -> list again (revoked: true) -> verify-chain (intact).
docker-compose rebuild was blocked by genuine host-disk exhaustion
from concurrent sibling workflows on this shared machine, not by
anything in this diff (pure proto/Go, zero compose/env changes).

Also corrects docs/THREAT-MODEL.md's "Known gaps" items 1, 6, and 7,
which still described tenant-auth, encryption-at-rest, and terminal-
injection as open/off-by-default despite rounds 2-4 actually closing
all three (RATION_GATEWAY_REQUIRE_TENANT_AUTH and
RATION_LEDGER_REQUIRE_TENANT_AUTH both default true, AES-256-GCM is
live on ledger-core's WAL/SQLite, pkg/textsanitize is wired into
cli/tui) — a judge reading the old text would see a security posture
strictly worse than what the code ships. Appends a short, honest
"Updates since initial submission" section to docs/SUBMISSION.md for
the same reason, without touching its original round-1 content.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-29 02:58:21 +03:00
cda90fcef4 feat(gateway): add a judge-facing live web dashboard
STRATEGY-2026-10-23.md names the exact risk this closes: "Ration's
actual differentiators... are invisible in a UI-less terminal demo
unless explicitly called out on screen." A judge can now open a
shareable gateway URL instead of running the TUI locally.

Add gateway.proto's GetDashboardSnapshot RPC (aggregates ListTenants +
per-tenant GetBalance/CheckReserveFloor + ListAgentDecisions into one
round trip — the same ledger-core data services/tui already fetches
per-tenant, just server-side aggregated for a browser) and three new
httpapi routes: GET /v1/dashboard (a single self-contained HTML/CSS/JS
page, zero external dependencies so it renders on a network-isolated
judging box), GET /v1/dashboard/snapshot (polled every 3s for
per-tenant reserve-floor headroom gauges and recent agent-decision
rationale), and GET /v1/dashboard/activity/stream (a true
text/event-stream SSE framing of StreamActivity for the page's
EventSource, separate from the existing NDJSON /v1/activity).

The dashboard is deliberately credential-free (GetDashboardSnapshot
carries no tenant_id/card_id, which internal/tenantauth's own
documented behavior already passes through unscoped); its activity SSE
stream presents gateway's own operator-scoped credential
(Handler.SetDashboardOperatorToken) specifically because
internal/tenantauth's StreamServerInterceptor requires some credential
on every streaming call — scoped narrowly to this one new route so the
existing, still-credentialed /v1/activity route's security posture is
unchanged.

Verified live: snapshot JSON returns correct per-tenant
available/held/headroom; the SSE stream delivers a real simulated-
deposit event end-to-end with zero auth errors; the page itself serves
at 200 text/html.
2026-10-23 19:38:22 +03:00
7bb72dbaa8 feat(tui): add an Agent Decisions tab
docs/THREAT-MODEL.md states plainly: "The TUI does not currently
display rationale/agent decisions at all — only tenants, deposits,
cards, and the live activity stream." Add a 5th tab (new
view/decisions.go, wired into model.go/state.go's tab state) that
fetches every tenant's ListAgentDecisions each refresh, sorted newest
first across tenants, and renders WHEN/TENANT/TRIGGER/ACTION/
RATIONALE/POLICY SNAPSHOT.

Extract the CLI's existing sanitizeControlChars into pkg/textsanitize
and apply it (via the new format.SanitizedCell, sanitize-then-truncate)
to every LLM-authored field this new tab renders, closing the same
terminal-escape-sequence injection gap for this surface at the same
time it's built, not after.
2026-10-23 18:53:58 +03:00
eef5f6b420 feat(auth): add operator-scoped API keys and JWTs
Add an is_operator flag to IssueAPIKey/MintJWT and thread it through
VerifyAPIKey/VerifyJWT's response, so a credential can authenticate as
a trusted cross-tenant caller (CLI/TUI operator dashboards, the
agent's polling loop) instead of being bound to one tenant_id. This is
the credential type gateway's tenantauth interceptor now exempts from
its per-tenant match.
2026-10-23 18:08:54 +03:00
ecac03914b fix(audit-log): bind source_service to verified mTLS peer identity, not the claimed field
Closes the mTLS-enabled half of docs/THREAT-MODEL.md's "Known gaps" item 2:
with mTLS disabled (the default) nothing bound a gRPC caller's transport
identity to the source_service string its AppendRequest claimed, so a
compromised agent calling audit-log.Append directly with
source_service: "ledger-core" could forge an entry that looked
authoritative. Added pkg/mtls.PeerCommonName (extracts the verified leaf
cert's CommonName from a gRPC context, ok=false for any non-mTLS peer)
and wired it into audit-log's Append: when a verified identity is
present it overrides the claimed source_service outright, rather than
merely checking it. The mTLS-disabled case is unavoidable and stays
exactly as documented. Full go test suite green across every module;
THREAT-MODEL.md's gap #2 and the earlier-stale gap #4 entry updated to
match what the code actually does today.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-21 16:23:43 +03:00
13abc31645 feat(ration): observability, infra-as-code, security hardening, and test depth
Phase 2 sections 2-6 and 8 of docs/SCALE-EXPANSION.md:

- pkg/telemetry + pkg/metrics: OpenTelemetry trace propagation and
  Prometheus metrics across every service hop (CLI -> agent -> gateway ->
  card-issuance/tenant-registry/auth -> ledger-core), tracing added to
  ledger-core itself via services/ledger-core/src/telemetry.rs.
- infra/: otel-collector + Prometheus + Grafana docker-compose stack, a
  Terraform ECS Fargate module + dev/staging/prod envs (plan-only, no
  apply — real AWS spend is an owner action), and a dev-only mTLS CA
  (infra/dev-ca) wired through pkg/mtls + services/ledger-core/src/mtls.rs.
- services/audit-log (from the prior commit) gets its async mirror writer
  in services/ledger-core/src/audit_mirror.rs, and services/gateway gets
  a per-tenant token-bucket rate limiter (internal/ratelimit).
- Test depth: a Rust proptest suite proving concurrent ApplyEntry never
  breaches the reserve floor (tests/apply_entry_proptest.rs, passing), a Go
  fuzz seed corpus for the policy envelope (rules_fuzz_test.go), a libFuzzer
  harness for the C WAL frame parser (services/wal/fuzz, deliberately not
  wired into `make test` per its own Makefile comment - needs a
  libFuzzer-bundled clang), and a real chaos test
  (scripts/chaos/kill-ledger-mid-write.sh) that SIGKILLs ledger-core
  mid-write under concurrent load and verifies via ListEntries that
  nothing was lost or double-applied.
- docs/formal/ledger.tla: a TLA+ spec of the ledger state machine (balance
  >= reserve_floor safety, HOLD-eventually-resolves liveness) plus a TLC
  model config - not run through TLC in this pass, that's a precise
  documented TODO, not faked.
- docs/adr/0001-0004, docs/RUNBOOK.md, docs/SLO.md, docs/THREAT-MODEL.md.

Verified: `make build && make test` clean (C WAL, Rust incl. the new
proptest suite, all 10 Go modules) from a cold target.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-19 12:25:58 +03:00
77324a7b50 feat(ration): split gateway into auth/tenant-registry/card-issuance/webhook-ingestion
Phase 2 service decomposition per docs/SCALE-EXPANSION.md section 1: extracts
internal/{airwallex,bridge,card,tenant,httpserver} out of the monolithic
gateway into four independently deployable gRPC services (each own go.mod,
Dockerfile, and tests), with gateway now a thin BFF that fans out through new
cardissuanceclient/webhookeventsclient gRPC clients. gateway.proto's external
surface is unchanged — agent/tui/cli still talk to gateway exactly as before.

Verified: all 10 go.work modules build and `go test ./...` passes across
every one, including the new gateway client packages against the live split
services (via `make build && make test`).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-19 12:25:41 +03:00
2b686594a3 feat: Ration phase 1 — full polyglot build for Airwallex Starter Kit 5
Six services, independently built then integrated:
- services/wal (C): crash-safe write-ahead log, CRC32-checksummed
  frames, torn-write recovery via truncate-to-last-valid-frame.
- services/ledger-core (Rust): double-entry ledger over the C WAL via
  FFI, reserve-floor enforcement BEFORE any WAL write, idempotent
  ApplyEntry, full LedgerCore gRPC service.
- services/gateway (Go): Airwallex Issuing/Global-Accounts client
  (mock mode default, live mode ready), the actual rationing math
  (reserve floor, 60% bridge cap, 24h velocity cap, partial-over-decline).
- services/agent (Go): deterministic hard-rule policy envelope computed
  BEFORE any LLM call; Claude only decides within that pre-approved
  envelope; every decision audit-logged even when the LLM call fails.
- services/tui (Go, Bubble Tea) + services/cli (Go, cobra): the only
  UI — no web frontend, per explicit direction.

Integration found and fixed three real bugs, not just compile errors:
- proto regen collision shadowing checked-in pkg/pb packages
- ledger-core/gateway address-variable mismatch (stack would never
  actually connect on default config)
- the big one: MarkDepositReceived never credited the ledger, so every
  tenant's balance was permanently stuck at 0 and bridge-funding could
  only ever decline — the core agentic-rationing feature could never
  produce a real grant. Fixed at the ledger level with idempotent
  mark-and-credit in one WAL frame, covered by 3 new tests.

End-to-end verified live, reproducibly: seed -> simulate a late deposit
-> agent grants a partial bridge with a computed rationale -> second
grant correctly declines once the 24h velocity cap engages. Verified
independently by the orchestrator too: 'make build' and 'make test'
both clean (Rust: 29 tests; Go: all packages; C: WAL test suite).

Airwallex sandbox credentials still pending organizer approval —
tracked as an owner blocker in docs/AIRWALLEX-SETUP.md, not a code gap.
2026-10-19 03:04:13 +03:00