Skip to content

Add bootstrap and administrative role grants#131

Merged
abiorh-claw merged 12 commits into
mainfrom
codex/ws-auth-001-08-bootstrap-admin-grants
Jul 16, 2026
Merged

Add bootstrap and administrative role grants#131
abiorh-claw merged 12 commits into
mainfrom
codex/ws-auth-001-08-bootstrap-admin-grants

Conversation

@Abiorh001

@Abiorh001 Abiorh001 commented Jul 16, 2026

Copy link
Copy Markdown
Collaborator

Workstream PR Trust Bundle

Chunk

WS-AUTH-001-08 - Bootstrap And Administrative Role Grants

Merge intent: .agent-loop/merge-intents/WS-AUTH-001-08.json

Goal

Establish one-time local Access Administrator bootstrap and immutable administrative grants, then activate only the seven administrative actions owned by AUTH-08 through the central authorization kernel.

Human-Approved Intent

  • Intent: .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/INTENT.md
  • Chunk contract: .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/chunks/WS-AUTH-001-08-bootstrap-admin-grants.md

What Changed

  • Added migration 0022 with immutable AdminRoleGrant and AuthorityControl truth.
  • Added a one-time bootstrap CLI that accepts only an eligible canonical human ActorProfile UUID.
  • Added five closed administrative role definitions and seven active administrative actions.
  • Added authenticated definition, grant-list, grant-issue, and grant-revoke APIs through central authorization.
  • Added exact scope, decision/resource/reason binding, replay/mismatch handling, final-administrator safety, and immutable evidence linkage.
  • Added deferred commit-time coupling between the bootstrap grant and authority control.
  • Repaired transaction ownership, retryable evidence failures, verification timestamps, and migration-test isolation before adding new consumers.

Why It Changed

AUTH-07B installed deny-by-default authorization but deliberately granted no administrative authority. AUTH-08 provides the first local grant truth needed for later service-actor, project-grant, and product cutover chunks without treating token roles, email, or default Contributor state as authority.

Design Chosen

Identity remains global and external-issuer verified. Administrative authority comes only from active Workstream grants with exact system or project scope. Bootstrap is a serialized operational ceremony, while all later issue/revoke operations require an active system-scoped Access Administrator grant. Deferred database triggers require the bootstrap grant and control row to reach one valid final state in the same transaction.

Alternatives Rejected

  • Token roles or email as authority: external claims are identity evidence, not local authorization policy.
  • Default administrative access for every Contributor: violates least privilege.
  • Per-project permission duplication: permissions remain canonical; project scope is a grant constraint.
  • Independent bootstrap grant/control commits: permits unrecoverable partial authority state.

Scope Control

Allowed Files Changed

  • AUTH-08 authorization, actor integration, migration, API composition, and focused tests.
  • Authorization operations/spec documentation.
  • AUTH-08 loop memory, merge intent, review evidence, and trust artifacts.

Files Outside Contract

  • None

Product Behavior

  • No Workstream product behavior changed.
  • Product behavior changed and is explained here: eligible administrators can read definitions/history and issue or revoke exact-scope administrative grants; no later product action is pre-activated.

Evidence

Commands Run

python -m pytest -q tests/test_authorization.py tests/test_audit.py tests/test_auth.py tests/test_actors.py tests/test_api_controls.py tests/test_api_rate_controls.py --cov=app.modules.authorization --cov=app.api.deps.authorization --cov=app.modules.actors.repository --cov=app.modules.actors.service --cov=app.modules.actors.schemas --cov=app.modules.audit.schemas --cov=scripts.bootstrap_access_administrator --cov-branch --cov-fail-under=90
python -m pytest -q tests/test_alembic.py
ruff check app tests scripts alembic/versions/0022_bootstrap_admin_grants.py
docstr-coverage --config .docstr.yaml
python3 scripts/test_agent_gates.py
python3 scripts/check_internal_review_evidence.py
python3 scripts/check_stale_workstream_wording.py
python3 scripts/check_stale_authorization_docs.py
python3 scripts/check_markdown_links.py
python3 scripts/check_loop_memory_state.py
python3 scripts/update_post_merge_memory.py validate-merge-intent --base-ref origin/main

Result Summary

275 focused behavior tests passed
90.17% focused branch-aware coverage
17/17 isolated Alembic tests passed
92.5% repository docstring coverage
71/71 agent-gate tests passed
All static documentation, evidence, merge-intent, and diff-integrity gates passed
Final GitHub Backend, Agent Gates, and CodeRabbit checks passed

GitHub Backend remains authoritative for the repository-wide 78% floor. No workflow, threshold, exclusion, dependency, or skip changed.

Acceptance Criteria Proof

  • Bootstrap is one-time, serialized, human-targeted, and commit-atomically coupled to authority control.
  • Token roles, email, and Contributor defaults grant no administrative authority.
  • Five role definitions and seven actions have exact system/project scope rules.
  • Issue/revoke decisions bind the exact authorizing grant, resource context, scope, reason, and revalidation state.
  • Replay, mismatch, concealment, final-administrator safety, and immutable evidence linkage have behavior tests.
  • AUTH-09, AUTH-10, artifact behavior, and review/revision runtime remain inactive.

Test Delta

Tests Added

  • Signed-token bootstrap and grant lifecycle behavior.
  • Grant-backed allow/deny, replay/mismatch, concurrency, final-admin, evidence linkage, and zero-write substitution tests.
  • Migration adoption, downgrade custody, immutable grant/control, and deferred cross-table invariant tests.

Tests Modified

  • Existing actor, audit, API-control, and migration tests were extended for the new active actions and migration head.
  • The historical guarded-downgrade test now asserts the durable invariant that failed downgrade retains its captured pre-command head.
  • Generic admin mutation evidence now uses a distinct authorizing grant rather than the mutated grant.

Tests Removed Or Skipped

  • None

Internal Reviewer Results

Reviewed code SHA: a284a718e68f08e072cb965cc5834bcc7ab45ee9

Reviewed at: 2026-07-16T07:43:50Z

Reviewer run IDs: auth08_final_senior, auth08_final_qa, auth08_final_security

Reviewer Result Blocking Findings Notes
Senior engineering PASS AFTER FIXES None Final migration, evidence, test, and docs repair is maintainable.
QA/test PASS AFTER FIXES None Behavior and cleanup continuity are proved without weakened assertions.
Security/auth PASS AFTER FIXES None Atomic bootstrap, exact provenance, concurrency, and downgrade custody pass.
Product/ops PASS None Role and action behavior matches the staged product boundary.
Architecture PASS AFTER FIXES None Central authorization and transaction ownership remain intact.
CI integrity PASS AFTER FIXES None No workflow, dependency, threshold, skip, or exclusion changed.
Docs PASS AFTER FIXES None Catalogue counts and operational behavior are synchronized.
Reuse/dedup PASS None Existing kernel, audit, idempotency, and repository boundaries are reused.
Test delta PASS AFTER FIXES None New tests assert final-state invariants and genuine provenance.

External Review

External review response file:

  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-08-external-review-response.md
Source Status Notes
CodeRabbit PASS Four valid findings repaired at a284a71; all four threads are resolved. The enforced docstring gate passes at 92.5%.
GitHub checks PASS Final Backend run 29481047118 passed in 19m14s; Agent Gates passed.

CI And Gate Integrity

  • No workflow weakening.
  • No lint/test/docstring gate weakening.
  • No coverage threshold weakening.
  • No package script weakening.
  • No unpinned new GitHub Action.
  • Checkout credential persistence disabled where checkout is used.

Remaining Risks

  • Bootstrap remains a controlled operational trust ceremony against an already verified eligible human ActorProfile.
  • Production issuer and database availability remain operational dependencies.
  • Project contributor grants and product cutovers remain unavailable until their owning chunks.

Follow-Up Work

WS-AUTH-001-09 is named only as the inactive same-initiative successor. It requires AUTH-08 merge, automated merge memory, and a separate explicit user start.

Human Review Focus

Please inspect:

  • Bootstrap uniqueness, serialization, and deferred grant/control invariant.
  • Five-role matrix and exact scope matching.
  • Authorizing-grant provenance and revoke idempotency behavior.
  • Final-administrator safety and transaction ownership.
  • No-authority treatment of token roles, email, and Contributor defaults.

Human Merge Ownership

  • I can explain what changed.
  • I can explain why it changed.
  • I know what could break.
  • I accept the remaining risks.
  • The user explicitly approved this specific PR for merge.

@coderabbitai

coderabbitai Bot commented Jul 16, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR implements WS-AUTH-001-08: one-time local Access Administrator bootstrap and administrative role grant management. It adds migration 0022 (AdminRoleGrant/AuthorityControl tables with immutability triggers), extends the authorization kernel/runtime with admin action evaluation, adds admin grant schemas/service/repository/router, a bootstrap CLI script, actor-self profile wiring for admin roles, plus extensive tests, docs, and agent-loop tracking artifacts.

Changes

AUTH-08 Bootstrap And Administrative Role Grants

Layer / File(s) Summary
Agent-loop planning and review artifacts
.agent-loop/LOOP_STATE.md, .agent-loop/REVIEW_LOG.md, .agent-loop/WORK_QUEUE.md, .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/*, .agent-loop/merge-intents/WS-AUTH-001-08.json
Tracking files, decision records D18/D19, the full AUTH-08 chunk spec, review evidence/trust-bundle/plan-review docs, and merge-intent metadata are added/updated to reflect AUTH-08 progress.
Bootstrap/admin grant migration
backend/alembic/versions/0022_bootstrap_admin_grants.py
Adds admin_role_grants and authority_control tables, immutability triggers, and replaced PL/pgSQL evidence/linked-event validation functions, with guarded upgrade/downgrade.
Action catalogue, admin policy, and runtime contracts
backend/app/modules/authorization/catalogue.py, backend/app/modules/authorization/policy.py, backend/app/modules/authorization/runtime.py, backend/app/modules/authorization/schemas.py
Adds seven new ActionIds owned by AUTH_08, admin role permission/scope mappings, new resource-context models, resource digesting, and AuthorizationEvidenceUnavailable.
Kernel admin evaluation and mutation evidence
backend/app/modules/authorization/kernel.py, backend/app/modules/authorization/service.py, backend/app/modules/audit/schemas.py
Extends AuthorizationService with admin action routing/denial evaluation and AuthorityMutationService with admin grant issue/revoke evidence, mismatch, and invalidation handling.
Admin grant schemas, service, repository, router
backend/app/modules/authorization/admin_schemas.py, admin_service.py, repository.py, router.py, models.py, backend/app/api/router.py, backend/app/modules/projects/repository.py
Adds strict Pydantic schemas, AdminRoleGrantService orchestration, AdminAuthorizationRepository, and FastAPI endpoints for permission/role reads, grant listing, issue, and revoke, mounted at /api/v1.
Bootstrap CLI and actor self-profile wiring
backend/scripts/bootstrap_access_administrator.py, backend/app/api/routes/auth.py, backend/app/modules/actors/service.py, backend/app/modules/actors/repository.py, backend/app/api/deps/authorization.py, backend/app/db/models.py
Adds the one-time bootstrap CLI, monotonic timestamp touch logic, /actors/me admin_roles exposure, and evidence-unavailable/rollback handling in the authorization dependency.
Backend test suite
backend/tests/conftest.py, test_alembic.py, test_actors.py, test_api_controls.py, test_api_rate_controls.py, test_audit.py, test_auth.py, test_authorization.py
Extends fixtures, migration tests (including a new bootstrap/admin-grant schema test), and adds extensive end-to-end authorization/bootstrap/grant lifecycle test coverage.
Operations and spec docs
docs/operations_authorization_service.md, docs/operations_roles_permissions.md, docs/spec_authorization_service.md
Documents bootstrap custody, administrative authority operations, catalogue activation counts, and API family updates.

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

Sequence Diagram(s)

sequenceDiagram
  participant Router
  participant AdminRoleGrantService
  participant AuthorizationService
  participant AdminAuthorizationRepository
  participant AuditService

  Router->>AdminRoleGrantService: reserve(idempotency_key)
  Router->>AuthorizationService: require(issue resource context)
  AuthorizationService->>AdminAuthorizationRepository: lock control/grant/resource
  AdminAuthorizationRepository-->>AuthorizationService: guard results
  AuthorizationService->>AuditService: stage decision + evidence
  AuditService-->>Router: AuthorizationDecision
  Router->>AdminRoleGrantService: complete_issue(claim, decision)
  AdminRoleGrantService->>AdminAuthorizationRepository: add_grant
  AdminRoleGrantService-->>Router: AuthorityMutationResponse
Loading
sequenceDiagram
  participant Operator
  participant BootstrapScript
  participant AdminRoleGrantService
  participant Database

  Operator->>BootstrapScript: run --execute --actor-profile-id
  BootstrapScript->>AdminRoleGrantService: bootstrap(actor_profile_id)
  AdminRoleGrantService->>Database: lock AuthorityControl
  AdminRoleGrantService->>Database: verify eligibility, create grant
  AdminRoleGrantService->>Database: mark bootstrap completed + audit event
  AdminRoleGrantService-->>BootstrapScript: grant_id
  BootstrapScript-->>Operator: JSON result + exit code
Loading

Possibly related PRs

  • Flow-Research/workstream#113: AUTH-08 admin-role grant mutation endpoints use the enforce_admin_mutation_rate_limit dependency introduced by this rate-controls PR.
  • Flow-Research/workstream#115: Extends the same authority audit evidence-safety SQL functions and AUTHORITY_INVALIDATION_REQUESTED validation logic introduced here.
  • Flow-Research/workstream#119: Extends the AuthorityMutationService idempotency/evidence completion and mismatch logic from this PR to support admin role grant issue/revoke.

Suggested reviewers: abiorh-claw

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.25% 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
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 summarizes the main change: adding bootstrap and administrative role grants.
Description check ✅ Passed The description mostly follows the template and includes the required sections, with only a few non-critical gaps like the missing Files Outside Contract subsection.
✨ 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-08-bootstrap-admin-grants

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.

Actionable comments posted: 4

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)

413-425: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Pin this guard test below migration 0022.

The test upgrades to head but still expects a failed downgrade to restore revision 0021_auth_action_evidence. With head now at 0022, the transactional failure restores 0022 instead. Upgrade explicitly to 0021 so this remains a focused canonical-actor test.

Proposed fix
-            command.upgrade(config, "head")
+            command.upgrade(config, "0021_auth_action_evidence")
🤖 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 413 - 425, Update the migration
setup in the canonical-actor downgrade guard test to upgrade explicitly to
revision 0021_authority_idempotency instead of head, while preserving the
existing failed-downgrade assertions and expected revision
0021_auth_action_evidence.
🧹 Nitpick comments (1)
backend/app/modules/authorization/models.py (1)

193-203: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Keep ORM server defaults aligned with migration 0022.

The migration defines server defaults for status/version/bootstrap fields and uses clock_timestamp(), while these models use client defaults or func.now(). Mirror the migration defaults to prevent schema metadata drift and misleading future Alembic revisions.

As per coding guidelines, ORM and migrations must use SQLAlchemy 2.x and Alembic.

Also applies to: 225-233

🤖 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/authorization/models.py` around lines 193 - 203, Align
the mapped columns in the authorization model, including status, version,
bootstrap/grant fields, and granted_at, with migration 0022 by replacing
client-side default or func.now() usage with matching SQLAlchemy server_default
expressions. Use the migration’s exact default values and clock_timestamp()
expression so ORM metadata and Alembic schema definitions remain consistent.

Source: Coding guidelines

🤖 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/alembic/versions/0022_bootstrap_admin_grants.py`:
- Around line 473-479: Add a deferred constraint trigger in the bootstrap grant
migration that validates the cross-table invariant at transaction commit: allow
either no bootstrap grant with incomplete authority control, or exactly one
bootstrap grant referenced by completed control. Apply it to changes in both
admin_role_grants and authority_control, using the existing bootstrap grant and
control identifiers, while preserving the current row-level guards.

In `@backend/tests/test_alembic.py`:
- Around line 572-595: The migration 0022 upgrade adoption guard must recognize
the same AUTH-08 evidence as its downgrade guard. Update the upgrade predicate
in the 0022 migration to include AdminRoleGrantIssueDenied and
LastAccessAdministratorOperationDenied, then extend
test_bootstrap_admin_grant_schema_is_immutable_and_guarded to insert and assert
rejection of both denial events before cleanup.

In `@backend/tests/test_authorization.py`:
- Around line 1919-1920: Update the admin grant/revoke test cases around
admin_revoke_target and the referenced ranges so provenance records the distinct
grant ID that authorized the decision, not the newly issued grant or revoked
target. Pass the authorizer grant ID separately for both admin operations,
preserving matched_grant_id as the authorization source and avoiding
self-referential provenance.

In `@docs/operations_authorization_service.md`:
- Around line 542-544: Synchronize the action-catalogue counts throughout
docs/operations_authorization_service.md with the canonical contract in
docs/spec_authorization_service.md: update the earlier staging text from 50
total and two active to 57 total, 9 active, and 48 planned, while preserving the
existing description of the two self actions and seven AUTH-08 actions.

---

Outside diff comments:
In `@backend/tests/test_alembic.py`:
- Around line 413-425: Update the migration setup in the canonical-actor
downgrade guard test to upgrade explicitly to revision
0021_authority_idempotency instead of head, while preserving the existing
failed-downgrade assertions and expected revision 0021_auth_action_evidence.

---

Nitpick comments:
In `@backend/app/modules/authorization/models.py`:
- Around line 193-203: Align the mapped columns in the authorization model,
including status, version, bootstrap/grant fields, and granted_at, with
migration 0022 by replacing client-side default or func.now() usage with
matching SQLAlchemy server_default expressions. Use the migration’s exact
default values and clock_timestamp() expression so ORM metadata and Alembic
schema definitions remain consistent.
🪄 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: 51650bbb-780b-452d-bbc4-1f37ae78c1ef

📥 Commits

Reviewing files that changed from the base of the PR and between 90eca12 and 465303c.

📒 Files selected for processing (43)
  • .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/DECISIONS.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-08-bootstrap-admin-grants.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-08-internal-review-evidence.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-08-pr-trust-bundle.md
  • .agent-loop/initiatives/WS-AUTH-001-workstream-authorization-service/reviews/WS-AUTH-001-08-preimplementation-plan-review.md
  • .agent-loop/merge-intents/WS-AUTH-001-08.json
  • backend/alembic/versions/0022_bootstrap_admin_grants.py
  • backend/app/api/deps/authorization.py
  • backend/app/api/router.py
  • backend/app/api/routes/auth.py
  • backend/app/db/models.py
  • backend/app/modules/actors/repository.py
  • backend/app/modules/actors/service.py
  • backend/app/modules/audit/schemas.py
  • backend/app/modules/authorization/admin_schemas.py
  • backend/app/modules/authorization/admin_service.py
  • backend/app/modules/authorization/catalogue.py
  • backend/app/modules/authorization/kernel.py
  • backend/app/modules/authorization/models.py
  • backend/app/modules/authorization/policy.py
  • backend/app/modules/authorization/repository.py
  • backend/app/modules/authorization/router.py
  • backend/app/modules/authorization/runtime.py
  • backend/app/modules/authorization/schemas.py
  • backend/app/modules/authorization/service.py
  • backend/app/modules/projects/repository.py
  • backend/scripts/bootstrap_access_administrator.py
  • backend/tests/conftest.py
  • backend/tests/test_actors.py
  • backend/tests/test_alembic.py
  • backend/tests/test_api_controls.py
  • backend/tests/test_api_rate_controls.py
  • backend/tests/test_audit.py
  • backend/tests/test_auth.py
  • backend/tests/test_authorization.py
  • docs/operations_authorization_service.md
  • docs/operations_roles_permissions.md
  • docs/spec_authorization_service.md

Comment thread backend/alembic/versions/0022_bootstrap_admin_grants.py
Comment thread backend/tests/test_alembic.py
Comment thread backend/tests/test_authorization.py
Comment thread docs/operations_authorization_service.md
@abiorh-claw
abiorh-claw self-requested a review July 16, 2026 07:31
@abiorh-claw
abiorh-claw merged commit aa0fdcd into main Jul 16, 2026
5 checks passed
@abiorh-claw
abiorh-claw deleted the codex/ws-auth-001-08-bootstrap-admin-grants branch July 16, 2026 08:14
github-actions Bot pushed a commit that referenced this pull request Jul 16, 2026
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