Skip to content

Add shared append-only authority audit evidence#115

Merged
abiorh-claw merged 22 commits into
mainfrom
codex/ws-auth-001-05-authority-evidence
Jul 14, 2026
Merged

Add shared append-only authority audit evidence#115
abiorh-claw merged 22 commits into
mainfrom
codex/ws-auth-001-05-authority-evidence

Conversation

@Abiorh001

@Abiorh001 Abiorh001 commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator

WS-AUTH-001-05A PR Trust Bundle

Chunk

WS-AUTH-001-05A - Shared Audit Ownership And Append-Only Authority Evidence

Goal

Add one typed, privacy-bounded, append-only authority evidence envelope to the
existing shared audit_events path without changing legacy task/checker
behavior or activating authorization decisions.

Human-Approved Intent

The human approved AUTH-05A as one semantic chunk bounded by its allowed files,
non-goals, acceptance criteria, behavior evidence, and required reviews rather
than an arbitrary production-line ceiling. AUTH-05B remains separate.

What Changed

  • Migration 0018 extends the shared audit table with versioned authority
    fields, closed registries, cross-field constraints, database-owned time,
    authority-cause integrity, and append-only normal-DML triggers.
  • A typed authority input and shared audit service enforce the same event,
    reason, fact, reference, permission, denial, role, and project matrices.
  • Task repository compatibility methods delegate to AuditRepository while
    preserving caller session and transaction ownership.
  • Behavior tests cover all 20 authority events through typed and direct-SQL
    positive and negative paths, legacy compatibility, rollback, mutation
    custody, non-retention, and migration downgrade guards.

Why It Changed

Later authorization chunks require trustworthy evidence custody before actor,
grant, permission evaluation, route cutover, idempotency, or invalidation
consumers can be implemented.

Design Chosen

The existing audit table remains the sole store. Application writes use one
typed service and shared repository. PostgreSQL independently enforces the
closed envelope so direct SQL cannot bypass privacy or integrity rules.
Rejected mappings and JSON are inspected from one stable snapshot, and service
re-admission never serializes untrusted mutated values before validation.

Alternatives Rejected

  • A parallel authority event table was rejected because it would split audit
    custody and duplicate writer behavior.
  • Application-only validation was rejected because direct SQL must enforce the
    same boundary.
  • Splitting typed and SQL matrices into mergeable partial states was rejected
    because either half alone is an incomplete security boundary.
  • AUTH-05B idempotency/replay work remains deferred to its own chunk.

Scope Control

No route, dependency, middleware, permission evaluator, actor/grant lifecycle,
authorization cutover, idempotency record/replay path, invalidation consumer,
token verifier, workflow, dependency, or CI threshold was added or changed.

Product Behavior

Legacy audit behavior and task/checker projections remain unchanged. New
authority evidence is internal foundation behavior only; it does not grant,
revoke, authorize, route, or invalidate product actions.

Acceptance Criteria Proof

  • All 20 registered events share typed and PostgreSQL positive/negative cases.
  • System and project grant scopes, project/resource equality, UUID references,
    registered tokens, denial codes, cause domain, self-cause, and append-only
    custody have direct behavior proof.
  • Malformed, scalar, duplicate-key, hostile mapping, mutable-buffer, secret
    representation, and post-validation mutation cases retain no rejected value
    and emit no serializer warning.
  • Legacy rows survive upgrade/downgrade proof and existing repository behavior.

Tests And Checks Run

  • Exact migration proof: 1 passed.
  • Audit suite: 10 passed.
  • Audit plus delegation coverage: 11 passed at 94.55 percent.
  • Two affected task lifecycle regressions passed.
  • Ruff, 95.1 percent docstring coverage, test-delta, migration line length,
    stale wording/auth/artifact, Markdown links, and diff integrity passed.
  • Full local repository tests were intentionally not repeated; GitHub Backend
    CI owns the full suite and repository-wide 78 percent coverage floor.

Test Delta

Tests were added or strengthened only. No assertion, raises guard, skip, xfail,
coverage threshold, or exclusion was removed or weakened.

CI Integrity

No workflow, package, dependency, coverage configuration, or test selection
file changed. GitHub checks must pass before merge.

Reviewer Results

Exact SHA 44901286b5c867a414cc39a9ccff5307bd23ad52 passed senior engineering,
architecture, reuse/dedup, docs, product/ops, QA/test, CI integrity, test delta,
and security/auth review with no remaining findings.

External Review

GitHub Actions and CodeRabbit are pending PR publication.

Remaining Risks

  • PostgreSQL append-only triggers protect normal DML, not database-owner or DDL
    credentials; production must use the documented non-owner runtime role.
  • The full repository suite and global coverage floor remain GitHub CI gates.
  • AUTH-05A records evidence but intentionally does not consume invalidations or
    perform authorization.

Follow-Up Work

After merge, post-merge memory, and a separate human start, AUTH-05B may add the
idempotency and invalidation foundation. Later chunks own actor profiles,
grants, permission evaluation, and route cutover.

Human Review Focus

Review the migration constraints and downgrade ordering, typed/SQL matrix
parity, single-snapshot privacy boundary, shared writer transaction ownership,
and proof that no authorization behavior was activated.

Human Merge Ownership

Only the human may approve and merge this PR. Completion of internal or
external review does not authorize merge.

Summary by CodeRabbit

  • New Features

    • Added privacy-safe authority audit evidence with structured event details, references, and lifecycle facts.
    • Added shared audit storage and retrieval while preserving existing task-audit behavior.
    • Added database protections to prevent unauthorized modification or deletion of audit history.
  • Bug Fixes

    • Improved validation to reject malformed, inconsistent, mixed, or privacy-sensitive audit data.
    • Preserved legacy audit records during schema upgrades and guarded unsafe downgrades.
  • Documentation

    • Updated architecture and operations guidance for authority audit storage, custody, and maintenance.

@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@Abiorh001, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 25 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 8a2d2451-d2f6-41df-922d-1d0ccd12819c

📥 Commits

Reviewing files that changed from the base of the PR and between 3536e39 and d023952.

📒 Files selected for processing (7)
  • .agent-loop/REVIEW_LOG.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/chunks/WS-AUTH-001-05B-idempotency-invalidation.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-05A-external-review-response.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-05A-internal-review-evidence.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-05A-pr-trust-bundle.md
  • backend/app/modules/audit/schemas.py
  • backend/tests/test_tasks.py
📝 Walkthrough

Walkthrough

AUTH-05 is split into active 05A and inactive 05B. The change implements a typed, privacy-bounded, append-only authority evidence envelope in the existing audit ledger, adds migration and repository/service support, and expands migration, audit, compatibility, and custody tests.

Changes

Authorization evidence foundation

Layer / File(s) Summary
AUTH-05A workflow and contract split
.agent-loop/*, .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/{CHUNK_MAP.md,DISCOVERY.md,PLAN.md,STATUS.md}, .../chunks/WS-AUTH-001-05-authority-evidence-foundation.md
AUTH-05 is split into active 05A shared audit evidence and inactive 05B idempotency/invalidation work, with updated sequencing, boundaries, review gates, and status records.
Authority evidence contracts and review evidence
.../chunks/WS-AUTH-001-05A-shared-audit-authority-evidence.md, .../reviews/WS-AUTH-001-05A-*
Defines typed authority-event fields, privacy and fact constraints, shared writer custody, append-only enforcement, migration behavior, acceptance criteria, and review evidence.
AUTH-05B deferred idempotency contract
.../chunks/WS-AUTH-001-05B-idempotency-invalidation.md
Defines the inactive idempotency reservation/replay state machine and typed invalidation orchestration without implementing them.
Shared audit schema and persistence implementation
backend/alembic/versions/0018_authority_audit_evidence.py, backend/app/modules/audit/*, backend/app/modules/tasks/{models.py,repository.py}
Adds the authority audit schema, database constraints and triggers, strict input validation, service persistence, repository queries, and task-repository delegation.
Migration, behavior, and custody validation
backend/tests/*, docs/architecture_data_model.md, docs/operations_authorization_service.md
Adds migration lifecycle, typed/direct-SQL parity, privacy, rollback, compatibility, delegation, append-only, and operational custody coverage and documentation.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant AuthorityAuditEventInput
  participant AuditService
  participant AuditRepository
  participant PostgreSQL
  Caller->>AuthorityAuditEventInput: submit authority evidence
  AuthorityAuditEventInput->>AuditService: validated normalized input
  AuditService->>AuditRepository: create authority AuditEvent
  AuditRepository->>PostgreSQL: insert and flush audit row
  PostgreSQL-->>AuditRepository: enforce constraints and append-only triggers
  AuditRepository-->>Caller: persisted AuditEvent
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 48.89% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding shared append-only authority audit evidence.
Description check ✅ Passed The description largely matches the required trust-bundle template and includes the main sections, with only a few sub-fields left implicit.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/ws-auth-001-05-authority-evidence

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.

@abiorh-claw abiorh-claw self-requested a review July 14, 2026 13:05

@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: 2

🧹 Nitpick comments (2)
backend/app/modules/audit/schemas.py (1)

102-121: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Fragile positional enum slicing for shared reasons.

tuple(AuthorityEventType)[2:5] picks ACTOR_IDENTITY_LINKED/REVOKED/REACTIVATED by declaration position rather than by name. It currently matches the migration's explicit REASONS dict, but silently breaks (assigns the wrong reason set with no error) if a future PR inserts/reorders an enum member before index 5.

♻️ Proposed fix: use explicit keys instead of positional slicing
-    **dict.fromkeys(tuple(AuthorityEventType)[2:5], {"identity_lifecycle_change"}),
+    **dict.fromkeys(
+        (
+            AuthorityEventType.ACTOR_IDENTITY_LINKED,
+            AuthorityEventType.ACTOR_IDENTITY_LINK_REVOKED,
+            AuthorityEventType.ACTOR_IDENTITY_LINK_REACTIVATED,
+        ),
+        {"identity_lifecycle_change"},
+    ),
🤖 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/app/modules/audit/schemas.py` around lines 102 - 121, Replace the
positional tuple slice in _REASONS with explicit AuthorityEventType keys for
ACTOR_IDENTITY_LINKED, ACTOR_IDENTITY_REVOKED, and ACTOR_IDENTITY_REACTIVATED,
assigning each the existing identity_lifecycle_change reason set. Preserve all
other reason mappings unchanged.
backend/tests/test_tasks.py (1)

80-101: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Suggest typing session for developer ergonomics.

Consider adding an AsyncSession type hint to the session parameter to improve IDE support and code clarity.

♻️ Proposed refactor
-async def delete_audit_fixture_as_owner(session, event_id: str) -> None:
+async def delete_audit_fixture_as_owner(session: AsyncSession, event_id: str) -> None:

(Assuming AsyncSession is or will be imported in the module context)

🤖 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_tasks.py` around lines 80 - 101, Update the
delete_audit_fixture_as_owner helper to annotate its session parameter with the
project’s AsyncSession type, adding or reusing the appropriate import if needed
while preserving the existing behavior.
🤖 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
@.agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/chunks/WS-AUTH-001-05B-idempotency-invalidation.md:
- Around line 149-165: The verification block contains prose and placeholders
instead of runnable commands. Replace the migration, AUTH-05B coverage, and
full-suite entries with concrete shell commands, running the exact migration
node first against the same isolated PostgreSQL database, then
audit/authorization tests, focused AUTH-05B coverage with its 90% threshold, and
the full suite with its 78% threshold; preserve all other CI integrity commands
unchanged.

In
@.agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-05A-internal-review-evidence.md:
- Around line 3-5: Update the “Reviewer run IDs” entry in the AUTH-05A evidence
record to replace the stale /root/auth04b_final_* references with the actual
AUTH-05A reviewer run IDs for reviewed SHA
44901286b5c867a414cc39a9ccff5307bd23ad52, preserving the existing audit-record
format.

---

Nitpick comments:
In `@backend/app/modules/audit/schemas.py`:
- Around line 102-121: Replace the positional tuple slice in _REASONS with
explicit AuthorityEventType keys for ACTOR_IDENTITY_LINKED,
ACTOR_IDENTITY_REVOKED, and ACTOR_IDENTITY_REACTIVATED, assigning each the
existing identity_lifecycle_change reason set. Preserve all other reason
mappings unchanged.

In `@backend/tests/test_tasks.py`:
- Around line 80-101: Update the delete_audit_fixture_as_owner helper to
annotate its session parameter with the project’s AsyncSession type, adding or
reusing the appropriate import if needed while preserving the existing behavior.
🪄 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: 30676bdc-7525-4deb-8f9e-a87d42c64f92

📥 Commits

Reviewing files that changed from the base of the PR and between 97cd0f5 and 3536e39.

📒 Files selected for processing (23)
  • .agent-loop/LOOP_STATE.md
  • .agent-loop/REVIEW_LOG.md
  • .agent-loop/WORK_QUEUE.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/CHUNK_MAP.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/DISCOVERY.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/PLAN.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/STATUS.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/chunks/WS-AUTH-001-05-authority-evidence-foundation.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/chunks/WS-AUTH-001-05A-shared-audit-authority-evidence.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/chunks/WS-AUTH-001-05B-idempotency-invalidation.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-05A-internal-review-evidence.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-05A-pr-trust-bundle.md
  • backend/alembic/versions/0018_authority_audit_evidence.py
  • backend/app/modules/audit/repository.py
  • backend/app/modules/audit/schemas.py
  • backend/app/modules/audit/service.py
  • backend/app/modules/tasks/models.py
  • backend/app/modules/tasks/repository.py
  • backend/tests/test_alembic.py
  • backend/tests/test_audit.py
  • backend/tests/test_tasks.py
  • docs/architecture_data_model.md
  • docs/operations_authorization_service.md

@abiorh-claw abiorh-claw merged commit 8e1cde6 into main Jul 14, 2026
3 checks passed
@abiorh-claw abiorh-claw deleted the codex/ws-auth-001-05-authority-evidence branch July 14, 2026 13:37
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.

2 participants