Skip to content

feat(auth): add durable authorization read rate control#175

Open
Abiorh001 wants to merge 16 commits into
mainfrom
codex/ws-auth-001-10b1-authorization-read-rate-control
Open

feat(auth): add durable authorization read rate control#175
Abiorh001 wants to merge 16 commits into
mainfrom
codex/ws-auth-001-10b1-authorization-read-rate-control

Conversation

@Abiorh001

@Abiorh001 Abiorh001 commented Jul 21, 2026

Copy link
Copy Markdown
Collaborator

Chunk

WS-AUTH-001-10B1 — Authorization Read Rate Control. Merge intent: .agent-loop/merge-intents/WS-AUTH-001-10B1.json.

Goal and intent

Provide durable cross-replica abuse control before privacy-sensitive project-role reads are exposed. This chunk prepares the shared control only; AUTH-10B2 owns route attachment, disclosure, concealment, cursors, and action activation.

What changed and why

  • migration 0033_authorization_read_rate after ART 0032_artifact_recovery adds one closed PostgreSQL authorization_read counter scope
  • bounded settings and an intentionally unattached FastAPI dependency extend the existing limiter
  • migration locking, constraint-drift refusal, downgrade refusal, scope isolation, concurrency, canonical 429, and private 503 are proven
  • operations/spec docs cover PostgreSQL 16 parity, rollout, rollback, and recovery
  • an additive 90% API-controls coverage report preserves the repository-wide 78% baseline

Design and alternatives

The existing framed HMAC, PostgreSQL time, repository, and independently committed session remain the only implementation. A second limiter/store, raw identity persistence, application-clock windows, route activation here, and version-check bypasses were rejected.

Scope control

No production route, action activation, cursor, authorization disclosure, or mutation is added. One merge intent declares AUTH-10B2 with explicit start.

Test delta and evidence

  • all nine internal tracks passed on integrated SHA 2d6d347e against main 92b8a7aa
  • focused isolated selector: 27 passed; migration/new-scope: 4; concurrency: 2; dependency/digest: 6
  • CI-repair migration sequence: 3/3 in fresh isolated PostgreSQL
  • hosted run 29876766313: preflight, API E2E, all four shards, aggregate 78% coverage, additive API-controls 90% coverage, and final gate passed
  • Agent Gates, Ruff, stale scans, Markdown links, evidence gate, and diff integrity passed

Reviewer results

Senior engineering, QA/test, security/auth, product/ops, architecture, CI integrity, docs, reuse/dedup, and test delta: PASS. CodeRabbit’s PostgreSQL-version comment is resolved by an executable PostgreSQL 16 preflight and stop/forward-repair guidance.

CI integrity

No skip, continue-on-error, threshold reduction, shard bypass, or weakened assertion was introduced. The hosted docstring gate passed.

Risks and recovery

Constraint drift fails closed before DDL. Downgrade locks before row checks. A non-16 PostgreSQL target must stop and use a reviewed forward migration. Stored keys contain no raw identity or authorization data.

Human review and merge ownership

Review the constraint transition, transactional downgrade, scope isolation, PostgreSQL 16 prerequisite, absence of route/action changes, and additive coverage gate. The user retains merge approval; AUTH-10B2 does not start automatically.

Summary by CodeRabbit

  • New Features

    • Added durable rate control for authorization-read requests, with configurable limits and time windows.
    • Added privacy-safe handling for rate-limit denials, including standard 429 responses and retry guidance.
    • Added migration safeguards that preserve existing counters and prevent unsafe rollback when active authorization-read data exists.
  • Documentation

    • Updated authorization specifications, operational guidance, migration sequencing, and review evidence.
    • Added automated coverage checks for the new API controls.

@coderabbitai

coderabbitai Bot commented Jul 21, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds the authorization_read rate-control scope, migration 0033_authorization_read_rate, bounded settings, an unattached FastAPI dependency, migration/runtime tests, CI coverage enforcement, and updated workstream, operational, specification, and review records.

Changes

Authorization Read Rate Control

Layer / File(s) Summary
Durable scope migration
backend/alembic/versions/..., backend/app/modules/api_controls/*, backend/tests/test_alembic.py
Adds the authorization_read scope, guarded migration upgrade/downgrade behavior, constraint-drift checks, locking tests, and updated Alembic head assertions.
Runtime configuration and dependency
backend/app/core/config.py, backend/app/api/deps/api_controls.py
Adds bounded authorization-read rate/window settings and an unattached dependency that consumes the new scope.
Behavior and gate validation
backend/tests/test_api_rate_controls.py, backend/tests/test_config.py, scripts/test_agent_gates.py, .github/workflows/backend.yml
Covers scope isolation, resets, concurrency, 429/503 behavior, configuration bounds, and dedicated API-controls coverage enforcement.
Specification and delivery records
.agent-loop/..., docs/*
Updates migration ordering, chunk acceptance and verification details, operational/specification guidance, and review evidence for AUTH-10B1.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Alembic
  participant PostgreSQL
  participant FastAPI
  participant RateControlService
  Alembic->>PostgreSQL: Add authorization_read scope
  FastAPI->>RateControlService: Consume authorization_read allowance
  RateControlService->>PostgreSQL: Persist counter state
  PostgreSQL-->>RateControlService: Return decision
  RateControlService-->>FastAPI: Allow or rate-limit request
Loading

Possibly related PRs

  • Flow-Research/workstream#113: Extends the existing PostgreSQL API rate-control system with the authorization_read scope and related migration coverage.

Suggested reviewers: abiorh-claw

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.59% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description covers the core change, but it omits many required template sections such as Human-Approved Intent, Evidence, Acceptance Criteria Proof, and Internal Reviewer Results. Rewrite the PR description to match the template headings and add the missing required sections, especially Human-Approved Intent, Evidence, Acceptance Criteria Proof, and reviewer tables.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely summarizes the main change: durable authorization read rate control.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/ws-auth-001-10b1-authorization-read-rate-control

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
backend/alembic/versions/0032_authorization_read_rate_control.py (1)

24-31: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Confirm pg_get_expr canonical form is stable across the PostgreSQL versions you deploy.

_require_scope_constraint compares the live constraint against these hardcoded ANY (ARRAY[...]) strings via exact equality. pg_get_expr output formatting is PostgreSQL-version dependent, so if a deployed server's major version differs from the CI-pinned postgres:16, upgrade()/downgrade() could refuse a structurally-correct constraint with "unexpected API rate-control scope constraint" and block the migration. Worth confirming all target environments run the same PG major version as CI, or documenting that constraint as a deployment prerequisite.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/alembic/versions/0032_authorization_read_rate_control.py` around
lines 24 - 31, Verify and document that all deployment PostgreSQL major versions
match the CI-pinned PostgreSQL 16 version before relying on the exact
pg_get_expr strings used by _require_scope_constraint. If version parity cannot
be guaranteed, replace the exact comparison with a version-independent
structural validation while preserving the existing upgrade and downgrade
constraint checks.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@backend/alembic/versions/0032_authorization_read_rate_control.py`:
- Around line 24-31: Verify and document that all deployment PostgreSQL major
versions match the CI-pinned PostgreSQL 16 version before relying on the exact
pg_get_expr strings used by _require_scope_constraint. If version parity cannot
be guaranteed, replace the exact comparison with a version-independent
structural validation while preserving the existing upgrade and downgrade
constraint checks.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 00579e92-982a-49e0-a3ac-370cad897991

📥 Commits

Reviewing files that changed from the base of the PR and between 1473f7a and bf48253.

📒 Files selected for processing (18)
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/DECISIONS.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/chunks/WS-AUTH-001-10B1-authorization-read-rate-control.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-10B1-external-review-response.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-10B1-internal-review-evidence.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-10B1-pr-trust-bundle.md
  • .agent-loop/merge-intents/WS-AUTH-001-10B1.json
  • .github/workflows/backend.yml
  • backend/alembic/versions/0032_authorization_read_rate_control.py
  • backend/app/api/deps/api_controls.py
  • backend/app/core/config.py
  • backend/app/modules/api_controls/models.py
  • backend/app/modules/api_controls/service.py
  • backend/tests/test_alembic.py
  • backend/tests/test_api_rate_controls.py
  • backend/tests/test_config.py
  • docs/operations_authorization_service.md
  • docs/spec_authorization_service.md
  • scripts/test_agent_gates.py

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/tests/test_alembic.py (1)

5328-5344: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Make lock-wait polling deadline-based.

The helper can exhaust 100 immediate polls before the downgrade worker has connected and requested AccessExclusiveLock, causing a flaky failure unrelated to migration correctness. Use a bounded monotonic deadline with event-loop yielding, or an explicit session handshake, instead of a fixed iteration count.

Suggested adjustment
-        for _ in range(100):
+        deadline = asyncio.get_running_loop().time() + 5
+        while asyncio.get_running_loop().time() < deadline:
             async with engine.connect() as connection:
                 waiting = await connection.scalar(...)
             if waiting:
                 return
             await asyncio.sleep(0)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/tests/test_alembic.py` around lines 5328 - 5344, Update
_wait_for_rate_control_table_lock to poll until a bounded monotonic deadline
rather than stopping after 100 iterations. Continue yielding to the event loop
between checks so the downgrade worker can acquire its connection, and raise the
existing assertion only when the deadline expires.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@backend/tests/test_alembic.py`:
- Around line 2799-2808: Update the migration round-trip test around
command.upgrade and command.downgrade to seed both legacy scopes, first_access
and admin_mutation, before upgrading to 0033_authorization_read_rate. Assert
both scopes are preserved after upgrade, insert authorization_read, verify
downgrade raises the existing RuntimeError, and assert both legacy scopes remain
afterward.

---

Outside diff comments:
In `@backend/tests/test_alembic.py`:
- Around line 5328-5344: Update _wait_for_rate_control_table_lock to poll until
a bounded monotonic deadline rather than stopping after 100 iterations. Continue
yielding to the event loop between checks so the downgrade worker can acquire
its connection, and raise the existing assertion only when the deadline expires.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 8c2314f6-4676-41e7-b7a1-29bfcd4943d3

📥 Commits

Reviewing files that changed from the base of the PR and between bf48253 and 452d2d5.

📒 Files selected for processing (13)
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/DECISIONS.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/INTENT.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/PLAN.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/chunks/WS-AUTH-001-10B1-authorization-read-rate-control.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-10B-internal-review-evidence.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-10B-pr-trust-bundle.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-10B1-external-review-response.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-10B1-internal-review-evidence.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-10B1-pr-trust-bundle.md
  • backend/alembic/versions/0033_authorization_read_rate_control.py
  • backend/tests/test_alembic.py
  • docs/operations_authorization_service.md
  • docs/spec_authorization_service.md
🚧 Files skipped from review as they are similar to previous changes (4)
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/DECISIONS.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-10B1-internal-review-evidence.md
  • docs/operations_authorization_service.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-10B1-external-review-response.md

Comment thread backend/tests/test_alembic.py Outdated
Comment on lines +2799 to +2808
asyncio.run(insert("first_access", 41))
command.upgrade(config, "0033_authorization_read_rate")
assert asyncio.run(scopes()) == ["first_access"]
asyncio.run(insert("authorization_read", 42))
with pytest.raises(
RuntimeError,
match="cannot downgrade live authorization-read rate controls",
):
command.downgrade(config, "0032_artifact_recovery")
assert asyncio.run(scopes()) == ["authorization_read", "first_access"]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Cover preservation of both legacy scopes.

Only first_access is seeded, so this test does not prove that an existing admin_mutation counter survives the 0032_artifact_recovery0033_authorization_read_rate round trip and remains after downgrade.

Suggested test adjustment
 asyncio.run(insert("first_access", 41))
+asyncio.run(insert("admin_mutation", 42))
 command.upgrade(config, "0033_authorization_read_rate")
-assert asyncio.run(scopes()) == ["first_access"]
+assert asyncio.run(scopes()) == ["admin_mutation", "first_access"]

 ...
-assert asyncio.run(scopes()) == ["first_access"]
+assert asyncio.run(scopes()) == ["admin_mutation", "first_access"]

Also applies to: 2842-2845

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/tests/test_alembic.py` around lines 2799 - 2808, Update the migration
round-trip test around command.upgrade and command.downgrade to seed both legacy
scopes, first_access and admin_mutation, before upgrading to
0033_authorization_read_rate. Assert both scopes are preserved after upgrade,
insert authorization_read, verify downgrade raises the existing RuntimeError,
and assert both legacy scopes remain afterward.

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.

1 participant