Skip to content

feat(api): enforce RBAC with admin-only rule management - #69

Merged
vianbas merged 8 commits into
mainfrom
feat/68-rbac-rule-management
Nov 19, 2026
Merged

vianbas merged 8 commits into
mainfrom
feat/68-rbac-rule-management

Conversation

@vianbas

@vianbas vianbas commented Oct 7, 2026 •

Copy link
Copy Markdown
Owner

Summary

auth.RequireRole existed but was not mounted on any route, because there was no admin-only operation to protect. This PR adds the first admin surface, rule management, and enforces the role server-side:

  • GET /rules is open to any authenticated role.
  • PATCH /rules/{id} sets {"enabled": boolean} and is admin only. Operators get 403 FORBIDDEN.

Closes #68

Architecture summary

  • Contract first (contracts/openapi.yaml 0.1.0 → 0.2.0): adds the rules tag, GET /rules and PATCH /rules/{id}, the Rule, RuleList and RuleUpdate schemas (additionalProperties: false) and the RuleId parameter. It reuses the existing Unauthorized, Forbidden and NotFound responses.
  • internal/rules/httpapi (new): RegisterRoutes mounts r.With(auth.RequireRole(auth.RoleAdmin)).Patch("/rules/{id}", …).
    • The role check sits next to the route it protects, so it cannot be dropped by wiring elsewhere.
    • It fails closed: without claims on the context, RequireRole returns 403.
    • The module is mounted with the other protected modules, behind RequireAuth.
  • Body parsing is strict:
    • The body is capped at 1 KiB with MaxBytesReader.
    • DisallowUnknownFields is on, enabled is required (*bool, so null is rejected), and anything after the JSON object is rejected.
    • Every failure returns 400 INVALID_BODY.
  • Store: new sqlc queries ListRules and SetRuleEnabled … RETURNING. Unknown or malformed ids map to rules.ErrNotFound, which the handler returns as 404. rules.Rule gains CreatedAt.
  • Behaviour: alerts.Service already reloads the enabled rules on every ingest, so a toggle applies to the next transaction. Existing alerts are untouched.
  • CORS: the preflight now allows PATCH; before this change the browser would have blocked the call.
  • Docs: the threat model (Spoofing, Repudiation, Elevation of privilege), container-design.md, system-context.md, CLAUDE.md and .claude/rules/security.md no longer say that RequireRole is unmounted.

Security considerations

  • The role comes only from the verified HS256 token. A token that claims admin but is signed with another key gets 401, and there is a test for this.
  • Operators keep the full operational workflow: they can list and read alerts, acknowledge and resolve them, and read rules. Only changing a rule is privileged.
  • Each change logs rule_id, enabled and the acting user_id, an opaque synthetic UUID. Emails and tokens are never logged, and a test asserts it.
  • No new dependencies, no secrets, synthetic data only. The default rules are unchanged.

Testing evidence

$ make verify        # gofmt, go vet, go test, go build, eslint, tsc, vitest, vite build — EXIT 0
$ sqlc diff          # clean
$ git diff --check   # clean
$ npx @stoplight/spectral-cli lint contracts/openapi.yaml --ruleset contracts/.spectral.yaml
  0 errors (2 pre-existing warnings: info-contact, /alerts/{id} description)
$ FINWATCH_TEST_DATABASE_URL=… go test -p 1 ./...   # all ok, incl. new rules/store integration tests
  • Handler and RBAC tests run through the real httpserver.NewRouter with the real auth.RequireAuth and real JWTs:
    • Both roles can list.
    • Admin PATCH returns 200; operator gets 403, no token gets 401, and a forged admin signature gets 401. In all three rejected cases the store is never called.
    • Eight invalid bodies return 400.
    • Not found returns 404 and a store failure returns 500.
    • The log line contains user_id and no email or token.
  • Store integration tests (PostgreSQL 16):
    • List includes disabled rules, and a disabled rule drops out of ListEnabled.
    • Toggling is idempotent and reversible.
    • An unknown or malformed id gives ErrNotFound.
  • Manual end-to-end against the real API with the seeded demo accounts:
    • GET /rules as operator returned 200 with 3 rules.
    • PATCH returned 403 as operator, 401 without a token, and 200 as admin.
    • The preflight returned Access-Control-Allow-Methods: GET, POST, PATCH.
    • With gbp-currency disabled, seeding 60 transactions (13 in GBP) raised 0 new gbp-currency alerts (6 → 6). Re-enabling returned 200.

Known limitations

  • Only the enable/disable toggle is in scope. Creating, deleting or editing rule thresholds is not.
  • There is no rules UI yet. The web app does not hide admin actions by role; the server is the enforcement point.
  • The audit trail is a structured log line, not a persisted audit table.
  • This PR touches lines next to feat: transactional outbox relay and in-process WebSocket hub #65 in cmd/api/main.go, middleware.go and the docs. Whichever merges second needs a small conflict resolution, which I will handle.

Follow-up issues

  • A rules page in the web app, with the toggle shown to admins only.
  • A persistent audit log for state changes.

Checklist

  • Branch is not main; this PR targets main.
  • Conventional commit messages.
  • make verify passes locally.
  • git diff --check is clean.
  • No secrets, real/personal data, or proprietary references.
  • Contracts updated first where applicable (OpenAPI/AsyncAPI).
  • Docs updated to match the change.

claude added 7 commits October 3, 2026 14:24
Define subprotocol bearer auth, at-least-once delivery with stable
envelope ids, no-replay semantics, and server close codes.

Refs #5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xzt3HRqVzoHnEyEUbTT3h9
- realtime.Relay polls unpublished outbox rows oldest-first, publishes
  them to the hub, then marks published_at (at-least-once), backing off
  on consecutive failures.
- realtime.Hub fans out without blocking; clients that fall behind are
  dropped with 1013.
- GET /ws verifies the access token offered as the bearer.<token>
  subprotocol before upgrading, clears the server's connection
  deadlines, pings, and closes with 1008 when the token expires and
  1001 on shutdown.
- statusRecorder implements Unwrap so handlers behind AccessLog can
  hijack.
- OUTBOX_POLL_INTERVAL config (default 500ms).

Refs #5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xzt3HRqVzoHnEyEUbTT3h9
useRealtimeEvents keeps one socket open while signed in, dedupes on
envelope id, invalidates the transactions/alerts query keys, refetches
on every (re)connect, reconnects with capped jittered backoff, and logs
out on 1008. The shell shows an accessible connection status.

Refs #5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xzt3HRqVzoHnEyEUbTT3h9
GET /rules for any authenticated role; PATCH /rules/{id} with a strict
{"enabled": boolean} body, 403 for non-admins.

Refs #68

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xzt3HRqVzoHnEyEUbTT3h9
- rules/httpapi: GET /rules and PATCH /rules/{id}, the latter behind
  auth.RequireRole(auth.RoleAdmin) on the route itself.
- Strict body parsing: 1 KiB cap, unknown fields and trailing data
  rejected, enabled required.
- Each change logs rule_id, enabled and the acting user_id (no email).
- sqlc ListRules / SetRuleEnabled; store maps unknown or malformed ids
  to rules.ErrNotFound.
- CORS preflight allows PATCH.

Refs #68

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xzt3HRqVzoHnEyEUbTT3h9
…gement

Resolve conflicts with the outbox relay and WebSocket hub (#65):
- cmd/api/main.go: keep both the realtime and rule HTTP imports; drop the
  now-unused rules import since appServices holds *rulestore.Store.
- docs: keep the realtime DoS mitigations and the /ws section from #65 and
  the RBAC rows from this branch; neither streaming nor RBAC is listed as
  out of scope any more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013Yguxp4QdXefV36UWrij2T
@vianbas
vianbas merged commit 33f064a into main Nov 19, 2026
8 checks passed
@vianbas
vianbas deleted the feat/68-rbac-rule-management branch November 19, 2026 00:30
vianbas pushed a commit that referenced this pull request Nov 19, 2026
Resolve the threat-model conflict with RBAC (#69): keep the per-user
WebSocket cap in the denial-of-service row and the server-side role check
in the elevation-of-privilege row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013Yguxp4QdXefV36UWrij2T
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(api): enforce RBAC with admin-only rule management

2 participants