diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d677b02f..2a4682e34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,9 @@ contain breaking changes; [UPGRADING.md](UPGRADING.md) lists them). ### Added +- Roles: five new roles for release teams and AI agents — `RELEASE_MANAGER`, `PROJECT_MANAGER`, `PRODUCT_MANAGER`, `DEVELOPER` and `AGENT` — and a permission catalogue behind them (`backend/app/core/permissions.py`, 46 permissions). The five existing roles keep exactly what they could do: their permission sets are computed from their rank. The new roles are not ranks; on every route that names no permission they count as VIEWER. A person may hold extra job roles (`users.additional_roles`, `project_members.additional_roles`, migration `0266`), and on a project write their instance and project permissions intersect, the rule "the lower of the two roles decides" applied to permissions. Routes admit a new role with `require_permission(Permission.X)` or `require_role(UserRole.X, permission=Permission.X)`; no route does yet. A members-route grant needs every permission of the role granted, and only an administrator gives `RELEASE_MANAGER`, `PROJECT_MANAGER` or `PRODUCT_MANAGER` (owner decision D-17, `permissions.ADMIN_ONLY_GRANTS`); nobody is given `AGENT` through the user or member routes. An MFA policy from QA_LEAD up covers release and product managers. Branch `feat/roles-e00-foundation`; `backend/tests/test_permission_catalogue.py`, `backend/tests/regression/test_permission_guards_hold_both_roles.py`, `backend/tests/regression/test_job_role_assignment_and_mfa.py`, the reworked `backend/tests/regression/test_role_hierarchy_is_five_tiers.py` (five ranks, ten roles), and `backend/tests/test_security_role_access_matrix.py` with the tracked `security_role_access_matrix.json`, which lists the roles each role-gated route admits. +- Roles, assigning them: Settings › Users (Edit, Add User, Invite User) and Members & access (**Extra roles** under a member) offer the ten roles with a one-line description each and an **Extra roles** picker; the users, members and invitation APIs carry `additional_roles` (an invitation's extra roles, globally and per project, apply on accept; migration `0266` adds `user_invitations.additional_roles`). A members-route refusal names the permissions the granter lacks (or says only an administrator gives a manager role), a project role caps what its holder may hand out in that project, and Members & access offers a QA lead only the roles they may give. An SSO group or a SCIM group mapped to a job role adds it as an extra role (the highest rank still sets the role; the SSO preview lists the extra roles and their groups). The MFA policy gains **Also require it from** (`required_roles`); its floor must be a rank. A feature flag's role list matches extra roles. `GET /api/v1/me/permissions?project_id=` answers what the caller may read and write in a project, and the SPA's `useMyPermissions().can(...)` reads it. Dev-login and the dev seed gain the four job roles (one developer is also a release manager); `seed_data.py` seeds a TESTER too (D-8). `backend/tests/regression/test_extra_roles_assignment.py`, `backend/tests/regression/test_job_roles_through_sso_scim_mfa_flags.py`, `backend/tests/test_me_permissions.py`, `backend/tests/test_role_access_runtime.py` (real requests as each role against the access matrix), `backend/tests/test_spa_permission_parity.py`, `backend/tests/regression/test_migration_0266_additional_roles.py`; `test_mfa.py` and `test_sso_role_preview.py` expect the two new response fields; `test_timeline_note_routes.py` expects the one rank helper (`rank_index`) where it pinned `_ROLE_ORDER.index`; the role crawl (`role-crawl-tester-viewer.spec.ts`) covers the job roles, `every-role-wording.spec.ts` checks the backend-unreachable banner as every role a person can hold and the viewer sentences as each job role, and `integration/test_scim_groups_postgres.py` and `integration/test_invitations_postgres.py` cover job-role groups and invited extra roles; frontend `UserManagementPage.extraRoles`, `ProjectMembersTab.extraRoles`, `lib/roles` tests. +- Quality gate: `backend.single-role-rank-helper` fails on `_ROLE_ORDER.index(...)`, a literal list of three or more roles, or a role compared with VIEWER outside `app/core/permissions.py` and `app/core/deps.py`; every rank lookup goes through `permissions.rank_index`. The write-route guard accepts `require_permission(`. - JSON and report uploads persist a PostgreSQL receipt before writing the queued payload or publishing a task. Clients can recover the same upload through `Idempotency-Key`, status polling, or an authorized retry of the retained receipt. - Delivery verification checks mounted rule inventories, targeted source security, rendered infrastructure and all Kubernetes application image identities. An optional disposable release gate verifies both worker roles, durable completion and correlated telemetry. - Optional API objectives report scoped availability, latency, error budgets and measurement coverage. Retained SQL cohorts expose downstream and AI completion, including missed deadlines, and a disposable benchmark measures telemetry capacity. diff --git a/README.md b/README.md index 1ee8bbbdb..4aed7b760 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ Nothing to install? Replay real screens in the browser with the [guided tours](h - **Test management**: authored test cases, plans and strategies with a reviewed lifecycle, linked to the executions they describe. - **Reports and sharing**: summary reports, PDF and Excel exports, evidence bundles, share links and compliance packs, with an optional human-review gate before AI-generated content is distributed. - **Integrations**: Jira, GitHub and GitLab (checks and merge-request notes), Slack, Microsoft Teams and email notifications, outbound webhooks, and knowledge sources for retrieval. -- **Access control**: five roles (`VIEWER`, `TESTER`, `QA_ENGINEER`, `QA_LEAD`, `ADMIN`) plus project membership, API keys, MFA, SAML and OpenID Connect single sign-on, and SCIM provisioning. +- **Access control**: five ranked roles (`VIEWER`, `TESTER`, `QA_ENGINEER`, `QA_LEAD`, `ADMIN`), job roles for release teams (`RELEASE_MANAGER`, `PROJECT_MANAGER`, `PRODUCT_MANAGER`, `DEVELOPER`) and an `AGENT` role for AI agents, each a set of permissions; plus project membership, API keys, MFA, SAML and OpenID Connect single sign-on, and SCIM provisioning. Some features are off by default and are turned on per installation or project with feature flags; the in-app guide (`/docs` on your instance) describes each one. diff --git a/THREAT_MODEL.md b/THREAT_MODEL.md index 7f6511de7..9e5f82e37 100644 --- a/THREAT_MODEL.md +++ b/THREAT_MODEL.md @@ -109,6 +109,7 @@ absent from the table above, which is how it went unnoticed. | **JWT** | Per-user session, short-lived (configurable expiry) | Signed with `JWT_SECRET_KEY`, refresh tokens in Postgres (hashes only); in the browser, `localStorage` (see below) | | **API keys** | Per-user or per-project, long-lived | SHA-256 hash stored in Postgres, raw key shown once at creation | | **Role hierarchy** | VIEWER < TESTER < QA_ENGINEER < QA_LEAD < ADMIN | Stored as `String(20)` on `users` and `project_members` | +| **Job roles** | RELEASE_MANAGER, PROJECT_MANAGER, PRODUCT_MANAGER, DEVELOPER, AGENT | Not ranks: each counts as VIEWER on a guard that names no permission (fail closed) and holds an explicit permission set (`backend/app/core/permissions.py`); extra job roles in `additional_roles`; on a project write the instance and project permissions intersect | | **Project scope** | Every data query is filtered by project membership | `require_project_access()` dependency, `get_accessible_project_ids()` returns None for ADMIN (no filter) | | **Dual auth** | Endpoints accept either JWT or API key | `get_current_user_or_api_key()` tries JWT first, then API key | | **MFA** | Optional per user, enforceable by policy | TOTP (RFC 6238) seed per user with one-time recovery codes; enrolling, disabling and reissuing codes are audited | diff --git a/architecture/DEVELOPER_GUIDE.md b/architecture/DEVELOPER_GUIDE.md index 6afd68b4f..d46e8ad19 100644 --- a/architecture/DEVELOPER_GUIDE.md +++ b/architecture/DEVELOPER_GUIDE.md @@ -40,10 +40,10 @@ API endpoint, a pipeline agent, a UI page and a migration. ## 1. Quality gates — the invariant ratchets -`make quality-gate` runs `scripts/quality_gate.py`, which enforces **68 guards**. +`make quality-gate` runs `scripts/quality_gate.py`, which enforces **70 guards**. 26 are *ratchets*: pre-existing violations are baselined in `scripts/quality-gate-baselines/` and the count can only shrink. New violations -fail CI. The other 42 ship at zero with **no baseline file at all** — those are +fail CI. The other 44 ship at zero with **no baseline file at all** — those are absolute rules, not ratchets, and are marked **†** in the tables below. Know these before you write code. @@ -68,6 +68,7 @@ and `scripts/test_quality_gate.py` fails if the two drift apart. | `backend.analytics-epoch-bump` † | a function that commits an analytics mutation — a registered base writer in `_ANALYTICS_MUTATION_BASES` (run/release/live/deletion/reset writers, plus the defect, active release-gate policy, quarantine-request, AI-analysis and failure-cluster writers the cached dashboard and hours-saved model read; the canonical case lifecycle the coverage map reads: suite move, bulk move, retirement, restore on re-sighting, suite rename; and the systemic cluster sweep `/analytics/systemic-clusters` reads), a source-discovered write (`update`/`delete`/`insert` of `TestRun`/`TestCase`, a new `TestRun`/`TestCase` row, an assignment to `status`/`primary_release_id`/`primary_suite_name`/`is_active` on such a row or `Project`, to `status`/`test_suite_id` on a `CanonicalTestCase`, or to `name` on a `TestSuite`), or a caller that reaches one without committing — and does not `await` `bump_analytics_epoch` / `bump_analytics_epochs` / `invalidate_analytics_cache` (resolved by import to `app.services.cache_service`) **after** the commit; or bumps before it, in `except`/`finally`, in a dead branch, or through `create_task`. A `get_db` route handler commits again when it returns, so it must commit explicitly before its bump. backend/scripts is not scanned | Analytics cache keys carry a per-project epoch (VIZ-212); a mutation that commits without bumping it leaves every cached report stale until TTL. After the commit: `await bump_analytics_epoch(project_id)`, or `bump_analytics_epochs(ids)` once per project for a sweep. A new primitive writer of what analytics read goes in the registry. A path that changes nothing analytics reads opts out with `# analytics-epoch: none — ` | | `backend.project-scope-guard-placement` † | an access check nested inside an `if not project_id` branch — the caller who *does* name a project skips it | Call `resolve_project_scope(db, user, project_id)` unconditionally; it 403s a non-admin naming a project they cannot reach | | `backend.write-routes-state-a-role` † | a POST/PUT/PATCH/DELETE route in `backend/app/routers` with no role: no `require_role` / `require_project_role` / `require_instance_admin` in its decorator, signature or router, and no `holds_role_for_project_write` check in its body, so a VIEWER can write through it | Add `Depends(require_role(UserRole.X))`; only when no role applies (the caller's own data, a read-shaped POST, a machine credential, a sign-in step) list it in `_ROLE_FREE_WRITE_ROUTES` with the reason | +| `backend.single-role-rank-helper` † | outside `app/core/permissions.py` and `app/core/deps.py`: `_ROLE_ORDER.index(...)`, a literal list of three or more `UserRole` members, or a role compared with VIEWER — another copy of the ladder, where a job role (RELEASE_MANAGER, PROJECT_MANAGER, PRODUCT_MANAGER, DEVELOPER, AGENT) would rank differently or slip past a deny check | Rank with `app.core.permissions.rank_index(role)` (job roles count as VIEWER), use `permissions.LADDER` for the order, compare `rank_index(role) == 0` instead of `role == VIEWER` | | `backend.model-imports-resolve` † | `from app.models.postgres import X` where `X` is not a real class | Fix the class name (`perf_baselines` is `PerfBaseline`, not `PerformanceBaseline`). A function-local import of a typo'd model is invisible until it runs, and a broad `except` turns it into a warning | | `backend.managed-test-case-status-single-writer` † | writing `ManagedTestCase.status` outside `services/test_case_lifecycle_service.py`, including status-capable generic `setattr` helpers | Call the lifecycle `transition(...)` owner so role/reason checks, immutable versions, audit rows and metrics remain one atomic unit. Constructors may set only the initial state | | `backend.status-enum-vocab` † | filtering an enum-backed string column — any column whose `Mapped[...]` or default names an enum (`status`, `role`, `channel`, `schedule`, ...) — with hand-written string literals | Build the filter from the enum (`FlakyQuarantineStatus.QUARANTINED.value`). A mismatched vocabulary matches nothing, silently and forever — FIX-002 had the Fixer selecting zero candidates on every run while reporting success | @@ -121,6 +122,7 @@ fails if a *second* deleter appears. | `frontend.ai-word-allowlisted` † | a hard-coded "AI" (the word, case-sensitive) in a string literal or JSX text of `frontend/src/**/*.tsx` (tests excluded) that is not on the reviewed allow-list. "AI" claims a language model answered; the default install has no model (D-13) | Say what produced the result: `producedByWord()` / `engineLabel()` from `components/ai/AISuggestion` for an engine-dependent label, or a neutral word ("Triage result", "Verdict"). A true use (shown only when a model answered, or a feature only a model can do) goes in `_AI_WORD_ALLOWED` as (relpath, the whole text) with a one-line reason; an entry that matches nothing fails. `.ts` copy models are not scanned | | `frontend.ingest-formats-match-backend` † | the upload dropdown (`reportUploadService.ts::SUPPORTED_FORMATS`) advertising a format `/ingest/file` rejects, the backend accepting a parser the UI never offers, or either registry becoming unparseable by the guard | Add or remove the format on **both** sides of the language boundary — the `SUPPORTED_FORMATS` array (value + label) and the `ReportFormat` union in `reportUploadService.ts`, and `_SUPPORTED_FORMATS` in `routers/ingest.py` (a new backend parser also needs `_detect_format` wired). If a refactor changes a registry's source shape, update the guard parser in the same change; otherwise CI fails instead of silently disabling parity enforcement | | `frontend.sdk-symbols-fresh` † | `frontend/src/components/live/sdkSymbols.json` differing from what `scripts/gen_sdk_symbols.py` reads out of `client/go` and `client/js` (the `/live` "Connect a test runner" snippet test checks every Go and JavaScript identifier against it) | Run `python scripts/gen_sdk_symbols.py` after an SDK change and commit the JSON, then `npx vitest run src/components/live/sdkSnippets.test.ts` in `frontend/` and fix any snippet that names a symbol the SDK no longer has | +| `frontend.single-role-order` † | outside `src/lib/roles.ts`, `src/types/permissions.ts` and `src/hooks/usePermissions.ts` (the shell's rank-only hook): `ROLE_ORDER.indexOf(...)` or a literal list of the five ranks — another copy of the ladder, where a job role ranks below VIEWER and the SPA offers or hides controls differently from the server | Rank with `roleRank` / `roleAtLeast` from `@/lib/roles` (job roles count as VIEWER); use `RANK_ROLES` from `@/types/permissions` for the order | **Details and forms open in the page** (`frontend.no-page-modals`, W27). An item's detail docks beside its list (`MasterDetail` + `DetailPane`); a form diff --git a/architecture/SECURITY.md b/architecture/SECURITY.md index 9bbdb11e2..d88cb6837 100644 --- a/architecture/SECURITY.md +++ b/architecture/SECURITY.md @@ -150,6 +150,47 @@ Deploy this change to **all read-serving replicas before relying on the new authorization path**; until then, an older replica can still accept its legacy Redis membership cache. +### Roles, ranks and permissions (enterprise roles E00) + +`backend/app/core/permissions.py` separates **rank** from **role**: + +- **Five ranks**, `VIEWER < TESTER < QA_ENGINEER < QA_LEAD < ADMIN`. Every + `require_role(X)` compares ranks, and `rank_index` is the only code that + indexes the ladder (the `backend.single-role-rank-helper` and + `frontend.single-role-order` quality-gate guards keep it that way). +- **Job roles** (`RELEASE_MANAGER`, `PROJECT_MANAGER`, `PRODUCT_MANAGER`, + `DEVELOPER`) and `AGENT` are not rungs. Each has a **base rank of VIEWER**: + on a guard that names no permission it gets exactly what a viewer gets, so a + new role never gains a write through an old guard by accident (fail closed). +- A **permission catalogue** (46 permissions, each with the rank that grants it + on the ladder and the most an agent may ever hold). Ladder roles' permission + sets are computed from rank, so moving a route from `require_role(X)` to + `require_permission(P)` (with `P`'s rank equal to `X`) answers every ladder + role exactly as before. Job roles' sets are explicit. A permission an agent + may never hold (`AGENT_FORBIDDEN`: sign, decide, override, administer, + delete, mint keys) is refused to an `AGENT` whatever it was granted. +- **Extra roles** (`users.additional_roles`, `project_members.additional_roles`) + add a job role's permissions; only the primary role gives the rank. +- **The lower of the two decides**: on a write into a project the caller's + instance permissions and project permissions **intersect**; a read uses the + project permissions. `enforce_project_role_floor` records every + `(rank, permission)` pair a route's guards name and holds a member to all of + them. +- **Grant ceiling**: a non-admin may give a project role or extra role only + when every permission of it is in their own effective permissions on that + project; `RELEASE_MANAGER`, `PROJECT_MANAGER` and `PRODUCT_MANAGER` + (`ADMIN_ONLY_GRANTS`) are given only by an administrator whatever the + granter holds; only an administrator changes instance roles; nobody changes + their own; `AGENT` is never given through the user or member routes. + +What each of the ten roles may do on every route is a reviewed file, +`backend/tests/security_role_access_matrix.json`, computed from each route's +guards; a pull request that changes any role's access shows as a diff there. +`tests/test_role_access_runtime.py` sends real requests as each role to a +sample of write routes and checks the answers match the file. +`GET /api/v1/me/permissions` tells the SPA what the caller may do in a project +(`useMyPermissions().can(...)`); the server stays the authority. + ### The ratchet's blind spot — ids that don't arrive in the path diff --git a/backend/app/bootstrap.py b/backend/app/bootstrap.py index ec353ac8a..dd3598ca9 100644 --- a/backend/app/bootstrap.py +++ b/backend/app/bootstrap.py @@ -107,6 +107,7 @@ test_management, timeline_notes, insights, + me_permissions, run_cadences, users, value_metric_assumptions, @@ -254,6 +255,7 @@ subject_erasure_requests.router, users.router, users.projects_router, + me_permissions.router, # Enterprise roles E00-S04: GET /api/v1/me/permissions api_keys.router, value_metrics.router, value_metric_assumptions.router, # PMF US-12.1: per-project hours-saved assumptions diff --git a/backend/app/core/deps.py b/backend/app/core/deps.py index 17b4485d9..0cd623142 100644 --- a/backend/app/core/deps.py +++ b/backend/app/core/deps.py @@ -16,7 +16,19 @@ from app.core.request_path import routed_path from app.core.security import ExpiredSignatureError, JWTError, decode_token from app.db.postgres import get_db -from app.models.postgres import ApiKey, User, UserRole +from app.core.permissions import ( + LADDER, + Permission, + assigned_roles, + effective_grants, + granted, + has_permission, + normalize_role, + permission_refusal_detail, + rank_index, + user_roles, +) +from app.models.postgres import ApiKey, ProjectMember, User, UserRole logger = logging.getLogger(__name__) @@ -59,14 +71,10 @@ class AuthorizedTestCaseContext: auto_error=False, ) -# Role hierarchy — higher index = more privileged -_ROLE_ORDER: list[UserRole] = [ - UserRole.VIEWER, - UserRole.TESTER, - UserRole.QA_ENGINEER, - UserRole.QA_LEAD, - UserRole.ADMIN, -] +# Role hierarchy — higher index = more privileged. The five ranks only; job +# roles and AGENT are placed on it by ``permissions.rank_index`` (base rank +# VIEWER). Index it through ``rank_index``, never ``_ROLE_ORDER.index``. +_ROLE_ORDER: list[UserRole] = list(LADDER) def _normalize_user_role(value: UserRole | str) -> UserRole: @@ -76,12 +84,7 @@ def _normalize_user_role(value: UserRole | str) -> UserRole: simple str → enum conversion. The ``UserRole.`` prefix guard is retained only as a safety net for any un-migrated rows. """ - if isinstance(value, UserRole): - return value - raw_value = str(value).strip() - if raw_value.startswith("UserRole."): - raw_value = raw_value.split(".", 1)[1] - return UserRole(raw_value) + return normalize_role(value) def _bind_api_key_project(user: User, project_id: uuid.UUID | None) -> User: @@ -314,8 +317,17 @@ def _route_takes_scoped_key_writes(request) -> bool: # which FastAPI resolves a route's dependencies. _MIN_ROLE_ATTR = "_testlookup_min_role" +#: The permission a ``require_role(..., permission=P)`` / ``require_permission(P)`` +#: guard also accepts, and whether its handler checks conditional grants. +_PERMISSION_ATTR = "_testlookup_permission" +_CONDITIONAL_OK_ATTR = "_testlookup_conditional_ok" _ROUTE_ROLE_FLOOR_ATTR = "_testlookup_route_role_floor" +_ROUTE_ROLE_REQUIREMENTS_ATTR = "_testlookup_route_role_requirements" _PROJECT_ROLE_FLOOR_ATTR = "_testlookup_project_role_floor" +_PROJECT_ROLE_REQUIREMENTS_ATTR = "_testlookup_project_role_requirements" + +#: One role guard on a route: (minimum rank, permission that also admits, conditional grants ok). +RoleRequirement = tuple[UserRole, Optional[Permission], bool] _NOT_COMPUTED = object() @@ -338,9 +350,9 @@ def _route_role_floor(request) -> UserRole | None: seen.add(id(dependant)) role = getattr(getattr(dependant, "call", None), _MIN_ROLE_ATTR, None) if isinstance(role, UserRole): - floor_idx = max(floor_idx, _ROLE_ORDER.index(role)) + floor_idx = max(floor_idx, rank_index(role)) pending.extend(getattr(dependant, "dependencies", None) or ()) - floor = _ROLE_ORDER[floor_idx] if floor_idx >= 0 else None + floor = LADDER[floor_idx] if floor_idx >= 0 else None try: setattr(route, _ROUTE_ROLE_FLOOR_ATTR, floor) except Exception: # a route object that takes no attributes: recompute next time @@ -348,12 +360,57 @@ def _route_role_floor(request) -> UserRole | None: return floor +def _route_role_requirements(request) -> tuple[RoleRequirement, ...]: + """Every role guard among the matched route's dependencies, as requirements. + + A route can carry more than one guard; with permissions each one is a + separate (floor, permission) pair and the project check must hold the + caller to all of them, not only to the highest floor. + """ + scope = getattr(request, "scope", None) + route = scope.get("route") if isinstance(scope, dict) else None + if route is None: + return () + cached = getattr(route, _ROUTE_ROLE_REQUIREMENTS_ATTR, _NOT_COMPUTED) + if cached is not _NOT_COMPUTED: + return cached if isinstance(cached, tuple) else () + found: list[RoleRequirement] = [] + seen: set[int] = set() + pending = [getattr(route, "dependant", None)] + while pending: + dependant = pending.pop() + if dependant is None or id(dependant) in seen: + continue + seen.add(id(dependant)) + call = getattr(dependant, "call", None) + role = getattr(call, _MIN_ROLE_ATTR, None) + if isinstance(role, UserRole): + permission = getattr(call, _PERMISSION_ATTR, None) + requirement = ( + role, + permission if isinstance(permission, Permission) else None, + getattr(call, _CONDITIONAL_OK_ATTR, False) is True, + ) + if requirement not in found: + found.append(requirement) + pending.extend(getattr(dependant, "dependencies", None) or ()) + requirements = tuple(found) + try: + setattr(route, _ROUTE_ROLE_REQUIREMENTS_ATTR, requirements) + except Exception: # a route object that takes no attributes: recompute next time + pass + return requirements + + def _bind_project_role_floor(user: User, request) -> User: """Record on the request's user the role its writes need in a project.""" - floor = _route_role_floor(request) if _is_write(request) else None + write = _is_write(request) + floor = _route_role_floor(request) if write else None + requirements = _route_role_requirements(request) if write else () # Not guarded: if the minimum could not be recorded the project guards # would not apply it, so a failure here must fail the request, not pass. setattr(user, _PROJECT_ROLE_FLOOR_ATTR, floor) + setattr(user, _PROJECT_ROLE_REQUIREMENTS_ATTR, requirements) return user @@ -368,6 +425,16 @@ def _project_role_floor(user: User) -> UserRole | None: return value if isinstance(value, UserRole) else None +def _project_role_requirements(user: User) -> tuple[RoleRequirement, ...]: + """The role guards this write must also pass in a project (``()`` for none).""" + value = getattr(user, _PROJECT_ROLE_REQUIREMENTS_ATTR, ()) + return value if isinstance(value, tuple) else () + + +def _names_a_permission(requirements: Sequence[RoleRequirement]) -> bool: + return any(permission is not None for _, permission, _ in requirements) + + def _is_instance_admin(user: User) -> bool: try: return _normalize_user_role(user.role) == UserRole.ADMIN @@ -378,7 +445,7 @@ def _is_instance_admin(user: User) -> bool: def _role_at_least(role: object, floor: UserRole) -> bool: try: normalized = _normalize_user_role(role if isinstance(role, UserRole) else str(role)) - return _ROLE_ORDER.index(normalized) >= _ROLE_ORDER.index(floor) + return rank_index(normalized) >= rank_index(floor) except ValueError: return False @@ -394,6 +461,54 @@ def _project_role_refusal(floor: UserRole) -> HTTPException: ) +def _permission_refusal(permission: Permission, *, in_project: bool) -> HTTPException: + _count_auth_failure("insufficient_role") + return HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail=permission_refusal_detail(permission, in_project=in_project), + ) + + +def _instance_holds(user: User, permission: Permission, *, allow_conditional: bool = False) -> bool: + """Whether the caller's instance roles (primary + extra) grant ``permission``.""" + try: + roles = user_roles(user) + except ValueError: + return False + return has_permission(roles, permission, allow_conditional=allow_conditional) + + +def _requirements_refusal( + user: User, + member_role: UserRole | str, + member_additional: object, + requirements: Sequence[RoleRequirement], +) -> HTTPException | None: + """Hold a member to every role guard of a write; ``None`` when they pass. + + A guard passes on the membership's rank (the rule before permissions) or + on its permission, held in BOTH the caller's instance roles and project + roles (the intersection: "the lower of the two decides"). + """ + grants = None + for min_role, permission, conditional_ok in requirements: + if _role_at_least(member_role, min_role): + continue + if permission is not None: + if grants is None: + try: + grants = effective_grants( + user_roles(user), assigned_roles(member_role, member_additional), is_write=True + ) + except ValueError: + grants = {} + if granted(grants, permission, allow_conditional=conditional_ok): + continue + return _permission_refusal(permission, in_project=True) + return _project_role_refusal(min_role) + return None + + async def enforce_project_role_floor(db: AsyncSession, user: User, project_id: uuid.UUID | None) -> None: """403 when this request is a write whose route minimum the caller does not hold in ``project_id``. A caller with no membership row is left to the @@ -403,6 +518,23 @@ async def enforce_project_role_floor(db: AsyncSession, user: User, project_id: u return from app.models.postgres import ProjectMember + requirements = _project_role_requirements(user) + if _names_a_permission(requirements): + row = ( + await db.execute( + select(ProjectMember.role, ProjectMember.additional_roles).where( + ProjectMember.user_id == user.id, + ProjectMember.project_id == project_id, + ) + ) + ).one_or_none() + if row is None: + return + refusal = _requirements_refusal(user, row[0], row[1], requirements) + if refusal is not None: + raise refusal + return + result = await db.execute( select(ProjectMember.role).where( ProjectMember.user_id == user.id, @@ -417,7 +549,11 @@ async def enforce_project_role_floor(db: AsyncSession, user: User, project_id: u async def holds_role_for_project_write( - db: AsyncSession, user: User, project_id: uuid.UUID | None, min_role: UserRole + db: AsyncSession, + user: User, + project_id: uuid.UUID | None, + min_role: UserRole, + permission: Permission | None = None, ) -> bool: """Whether ``user`` holds ``min_role`` on the instance AND in ``project_id``. @@ -426,10 +562,17 @@ async def holds_role_for_project_write( status needs QA_LEAD). Same rule as the guards apply: the lower of the two roles decides, and an instance ADMIN passes. A key with a scope list needs ``project:admin`` at QA_LEAD and above, as on a ``require_role`` route. + + ``permission`` also admits a caller below ``min_role`` who holds it, on the + instance and in the project (as ``require_role(..., permission=...)``). """ - if not _role_at_least(user.role, min_role): + if permission is not None and permission.legacy_min_rank != min_role: + raise ValueError(f"{permission.value} belongs to {permission.legacy_min_rank.value}, not {min_role.value}") + if not _role_at_least(user.role, min_role) and not ( + permission is not None and _instance_holds(user, permission) + ): return False - if _ROLE_ORDER.index(min_role) >= _ROLE_ORDER.index(UserRole.QA_LEAD): + if rank_index(min_role) >= rank_index(UserRole.QA_LEAD): grant = api_key_grant(user) if grant is not None and not grant.allows(PROJECT_ADMIN_SCOPE): return False @@ -439,6 +582,16 @@ async def holds_role_for_project_write( return False from app.models.postgres import ProjectMember + if permission is not None: + row = ( + await db.execute( + select(ProjectMember.role, ProjectMember.additional_roles).where( + ProjectMember.user_id == user.id, + ProjectMember.project_id == project_id, + ) + ) + ).one_or_none() + return row is not None and _requirements_refusal(user, row[0], row[1], ((min_role, permission, False),)) is None role = ( await db.execute( select(ProjectMember.role).where( @@ -454,7 +607,8 @@ async def _project_ids_with_role(db: AsyncSession, user: User, floor: UserRole) """The caller's projects in which their membership role is at least ``floor``.""" from app.models.postgres import ProjectMember - roles = [role.value for role in _ROLE_ORDER[_ROLE_ORDER.index(floor):]] + # Every role whose rank reaches the floor: job roles count as VIEWER. + roles = [role.value for role in UserRole if rank_index(role) >= rank_index(floor)] result = await db.execute( select(ProjectMember.project_id).where( ProjectMember.user_id == user.id, @@ -464,6 +618,32 @@ async def _project_ids_with_role(db: AsyncSession, user: User, floor: UserRole) return {row[0] for row in result.all()} +async def _project_ids_meeting( + db: AsyncSession, user: User, requirements: Sequence[RoleRequirement] +) -> set[uuid.UUID]: + """The caller's projects in which they pass every role guard of this write.""" + from app.models.postgres import ProjectMember + + result = await db.execute( + select(ProjectMember.project_id, ProjectMember.role, ProjectMember.additional_roles).where( + ProjectMember.user_id == user.id, + ) + ) + return { + row[0] + for row in result.all() + if _requirements_refusal(user, row[1], row[2], requirements) is None + } + + +async def _project_ids_for_write(db: AsyncSession, user: User, floor: UserRole) -> set[uuid.UUID]: + """Projects this write may reach: by rank, or by the permissions its guards name.""" + requirements = _project_role_requirements(user) + if _names_a_permission(requirements): + return await _project_ids_meeting(db, user, requirements) + return await _project_ids_with_role(db, user, floor) + + def _bind_api_key_grant(user: User, grant: ApiKeyGrant | None) -> User: setattr(user, _API_KEY_GRANT_ATTR, grant) return user @@ -952,7 +1132,13 @@ async def get_api_key_context( ) -def require_role(min_role: UserRole, *, allow_project_key: bool = False) -> Callable: +def require_role( + min_role: UserRole, + *, + allow_project_key: bool = False, + permission: Permission | None = None, + conditions_checked_in_handler: bool = False, +) -> Callable: """ Return a FastAPI dependency that enforces a minimum role level. @@ -1003,9 +1189,26 @@ def require_role(min_role: UserRole, *, allow_project_key: bool = False) -> Call A legacy key with an empty list stays full-access, and a JWT has no scopes at all. Below QA_LEAD the scopes are not read here; the project-scoped guards refuse such a key's writes (see ``_refuse_scoped_key_write``). + + **``permission`` admits the roles that are not rungs (enterprise roles + E00).** A caller below ``min_role`` passes when their roles grant + ``permission``; ``permission.legacy_min_rank`` must equal ``min_role``, so + for the five ladder roles nothing changes. Prefer ``require_permission(P)``, + which picks ``min_role`` for you. A conditional grant (for example a + DEVELOPER's "failures I own") counts only with + ``conditions_checked_in_handler=True``, and the handler then owes a + ``permissions.check_condition`` on the resource. Key and scope rules are + computed from ``min_role`` as before. """ - min_idx = _ROLE_ORDER.index(min_role) - at_least_qa_lead = min_idx >= _ROLE_ORDER.index(UserRole.QA_LEAD) + if min_role not in LADDER: + raise ValueError(f"require_role takes a rank ({', '.join(r.value for r in LADDER)}), not {min_role!r}") + if permission is not None and permission.legacy_min_rank != min_role: + raise ValueError( + f"{permission.value} belongs to {permission.legacy_min_rank.value}, not {min_role.value}: " + "use require_permission() so the floor cannot drift" + ) + min_idx = rank_index(min_role) + at_least_qa_lead = min_idx >= rank_index(UserRole.QA_LEAD) if allow_project_key and not at_least_qa_lead: raise ValueError( "allow_project_key applies only to require_role(UserRole.QA_LEAD) and " @@ -1018,7 +1221,7 @@ async def _check( current_user: User = Depends(get_current_active_user), ) -> User: try: - user_idx = _ROLE_ORDER.index(_normalize_user_role(current_user.role)) + user_idx = rank_index(_normalize_user_role(current_user.role)) except ValueError: _count_auth_failure("insufficient_role") raise HTTPException( @@ -1026,11 +1229,17 @@ async def _check( detail="Insufficient permissions", ) if user_idx < min_idx: - _count_auth_failure("insufficient_role") - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail=f"Requires at least {min_role.value} role", - ) + if permission is not None: + if not _instance_holds( + current_user, permission, allow_conditional=conditions_checked_in_handler + ): + raise _permission_refusal(permission, in_project=False) + else: + _count_auth_failure("insufficient_role") + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail=f"Requires at least {min_role.value} role", + ) if refuse_project_key and _api_key_bound_project(current_user) is not None: # Counted like any other role shortfall: a leaked CI key probing # the admin surface is exactly the burst an operator wants to see. @@ -1046,9 +1255,39 @@ async def _check( # Read by ``_route_role_floor``: on a write the project guards hold the # caller to this role in the project the request names as well. setattr(_check, _MIN_ROLE_ATTR, min_role) + setattr(_check, _PERMISSION_ATTR, permission) + setattr(_check, _CONDITIONAL_OK_ATTR, conditions_checked_in_handler) return _check +def require_permission( + permission: Permission, + *, + conditions_checked_in_handler: bool = False, +) -> Callable: + """A ``require_role`` guard whose floor comes from the permission catalogue. + + ``require_permission(Permission.RELEASE_WRITE)`` is + ``require_role(UserRole.QA_LEAD, permission=Permission.RELEASE_WRITE)``: + the five ladder roles are answered by rank exactly as before, and the job + roles that hold the permission are admitted too. The returned dependency + IS a ``require_role`` closure, so the role-floor snapshot + (``tests/test_security_role_floor.py``), the per-role access matrix and the + write-route checks read it unchanged. + + It takes no ``allow_project_key``: a route that lets a project-bound key in + keeps ``require_role(UserRole.X, allow_project_key=True, permission=P)``, + the form the opt-in review ratchet + (``tests/regression/test_admin_routes_refuse_project_keys.py``) reads, and + ``require_role`` refuses a ``P`` whose floor is not ``X``. + """ + return require_role( + permission.legacy_min_rank, + permission=permission, + conditions_checked_in_handler=conditions_checked_in_handler, + ) + + INGEST_MIN_ROLE = UserRole.QA_ENGINEER @@ -1064,10 +1303,10 @@ def ensure_ingest_role(user: User) -> None: CI key -- its owner's role -- passes unchanged. """ try: - idx = _ROLE_ORDER.index(_normalize_user_role(user.role)) + idx = rank_index(_normalize_user_role(user.role)) except ValueError: idx = -1 - if idx < _ROLE_ORDER.index(INGEST_MIN_ROLE): + if idx < rank_index(INGEST_MIN_ROLE): _count_auth_failure("insufficient_role") raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, @@ -1101,17 +1340,30 @@ def require_instance_admin() -> Callable: return require_role(UserRole.ADMIN) -def require_project_role(min_role: UserRole) -> Callable: +def require_project_role( + min_role: UserRole, + *, + permission: Permission | None = None, + conditions_checked_in_handler: bool = False, +) -> Callable: """ Dependency that checks project-level role from project_members table, falling back to the user's global role when no project membership exists. The project_id is read from path params. If no project_id in path, falls back to global role check. + + ``permission`` admits a caller below ``min_role`` whose roles grant it: on + a read the project roles, on a write the instance and project roles + together (the intersection), with no membership the instance roles. """ from app.models.postgres import ProjectMember # local import to avoid circular - min_idx = _ROLE_ORDER.index(min_role) + if min_role not in LADDER: + raise ValueError(f"require_project_role takes a rank, not {min_role!r}") + if permission is not None and permission.legacy_min_rank != min_role: + raise ValueError(f"{permission.value} belongs to {permission.legacy_min_rank.value}, not {min_role.value}") + min_idx = rank_index(min_role) async def _check( request: Request, @@ -1120,8 +1372,9 @@ async def _check( ) -> User: # At QA_LEAD and above a write administers the project: project:admin. _refuse_scoped_key_write( - request, current_user, admin=min_idx >= _ROLE_ORDER.index(UserRole.QA_LEAD) + request, current_user, admin=min_idx >= rank_index(UserRole.QA_LEAD) ) + membership = None project_id_str = request.path_params.get("project_id") if project_id_str: try: @@ -1143,7 +1396,7 @@ async def _check( if instance_role == UserRole.ADMIN: effective_role = instance_role elif _is_write(request) and ( - _ROLE_ORDER.index(instance_role) < _ROLE_ORDER.index(effective_role) + rank_index(instance_role) < rank_index(effective_role) ): effective_role = instance_role else: @@ -1154,11 +1407,18 @@ async def _check( effective_role = _normalize_user_role(current_user.role) try: - user_idx = _ROLE_ORDER.index(effective_role) + user_idx = rank_index(effective_role) except ValueError: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Insufficient permissions") if user_idx < min_idx: + if permission is not None: + if not _project_permission_held( + current_user, membership, permission, + is_write=_is_write(request), allow_conditional=conditions_checked_in_handler, + ): + raise _permission_refusal(permission, in_project=True) + return current_user raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=f"Requires at least {min_role.value} role for this project", @@ -1168,6 +1428,23 @@ async def _check( return _check +def _project_permission_held( + user: User, membership: ProjectMember | None, permission: Permission, *, is_write: bool, allow_conditional: bool +) -> bool: + """``require_project_role``'s permission branch (see its docstring).""" + try: + instance = user_roles(user) + project = ( + assigned_roles(membership.role, getattr(membership, "additional_roles", None)) + if membership is not None + else None + ) + except ValueError: + return False + grants = effective_grants(instance, project, is_write=is_write) + return granted(grants, permission, allow_conditional=allow_conditional) + + # ── Project / run-scoped access (BL-01: tenant isolation) ──────────────────── async def get_accessible_project_ids( @@ -1193,16 +1470,17 @@ async def get_accessible_project_ids( return {bound_project_id} # A write through a key whose owner is not an ADMIN: the owner must # hold the route's role in the key's project too. - return {bound_project_id} & await _project_ids_with_role(db, user, floor) + return {bound_project_id} & await _project_ids_for_write(db, user, floor) if _normalize_user_role(user.role) == UserRole.ADMIN: return None # ADMIN sees everything if floor is not None: # A write on a route with a role minimum reaches only the projects in - # which the caller holds that role. Asked of the database each time, - # like the membership-only read below. - return await _project_ids_with_role(db, user, floor) + # which the caller holds that role (by rank, or by a permission the + # route names). Asked of the database each time, like the + # membership-only read below. + return await _project_ids_for_write(db, user, floor) result = await db.execute( select(ProjectMember.project_id).where(ProjectMember.user_id == user.id) diff --git a/backend/app/core/metric_dimensions.py b/backend/app/core/metric_dimensions.py index 07e9a8397..9b387cf84 100644 --- a/backend/app/core/metric_dimensions.py +++ b/backend/app/core/metric_dimensions.py @@ -25,7 +25,11 @@ "draft", "review_requested", "under_review", "approved", "active", "rejected", "needs_update", "deprecated", "archived", "other", }) -ACTOR_ROLES = frozenset({"VIEWER", "TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN", "other"}) +# Every UserRole value (enterprise roles E00 added the four job roles and AGENT): still a closed set of eleven. +ACTOR_ROLES = frozenset({ + "VIEWER", "TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN", + "RELEASE_MANAGER", "PROJECT_MANAGER", "PRODUCT_MANAGER", "DEVELOPER", "AGENT", "other", +}) TASK_STATES = frozenset({ "pending", "received", "started", "success", "failure", "retry", "revoked", "rejected", "ignored", "unknown", "other", diff --git a/backend/app/core/permissions.py b/backend/app/core/permissions.py new file mode 100644 index 000000000..16784c6a4 --- /dev/null +++ b/backend/app/core/permissions.py @@ -0,0 +1,529 @@ +"""Roles, ranks and permissions (enterprise roles, epic E00). + +TestLookup has two ideas that used to be one: + +* **Rank** -- the authority ladder ``VIEWER < TESTER < QA_ENGINEER < QA_LEAD < + ADMIN``. Every ``require_role(X)`` compares ranks. The ladder has exactly + five rungs and never grows. +* **Role** -- what a person is assigned. The five ladder roles are their own + rank. The job roles added for release teams (RELEASE_MANAGER, + PROJECT_MANAGER, PRODUCT_MANAGER, DEVELOPER) and the AGENT principal are not + rungs: each has a *base rank* of VIEWER, used by every guard that names no + permission (fail closed), and an explicit *permission set*, used by guards + that do (``require_permission`` / ``require_role(..., permission=...)``). + +Every permission records ``legacy_min_rank``: the rank that grants it on the +ladder. The ladder roles' permission sets are COMPUTED from it, so for them +"has permission P" is exactly "rank >= P.legacy_min_rank" -- a route that moves +from ``require_role(X)`` to ``require_permission(P)`` (with +``P.legacy_min_rank == X``) answers every ladder role as before. + +A person may hold extra job roles (``users.additional_roles``, +``project_members.additional_roles``): the primary ``role`` gives the rank, the +extra roles only add permissions. On a write into a project the caller's +instance permissions and project permissions INTERSECT -- the generalisation +of "the lower of the two roles decides" (security audit 2026-11-18). + +Nothing here touches the database or FastAPI; ``app.core.deps`` builds the +guards on top of it. Keep this module import-light: ``deps`` imports it at +module load. +""" +from __future__ import annotations + +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass +from enum import Enum +from typing import Any, Optional + +from app.models.postgres import UserRole + +# ── Ranks ──────────────────────────────────────────────────────────────────── + +#: The authority ladder, lowest first. Exactly five rungs. +LADDER: tuple[UserRole, ...] = ( + UserRole.VIEWER, + UserRole.TESTER, + UserRole.QA_ENGINEER, + UserRole.QA_LEAD, + UserRole.ADMIN, +) + +#: Job roles a person may hold in addition to their primary role. +JOB_ROLES: frozenset[UserRole] = frozenset({ + UserRole.RELEASE_MANAGER, + UserRole.PROJECT_MANAGER, + UserRole.PRODUCT_MANAGER, + UserRole.DEVELOPER, +}) + +#: The extra roles the API accepts, in enum order (forms, messages, the OpenAPI enum). +EXTRA_ROLE_CHOICES: tuple[UserRole, ...] = tuple(role for role in UserRole if role in JOB_ROLES) + +#: Every role's rank on the ladder. Job roles and AGENT count as VIEWER on a +#: guard that names no permission, so a new role never gains a write through an +#: old guard by accident. +ROLE_BASE_RANK: Mapping[UserRole, UserRole] = { + **{role: role for role in LADDER}, + **{role: UserRole.VIEWER for role in (*JOB_ROLES, UserRole.AGENT)}, +} + + +def normalize_role(value: UserRole | str) -> UserRole: + """A stored role string as ``UserRole``; ``ValueError`` for an unknown string. + + The ``UserRole.`` prefix guard is a safety net for rows migration 0045 + did not clean. + """ + if isinstance(value, UserRole): + return value + raw = str(value).strip() + if raw.startswith("UserRole."): + raw = raw.split(".", 1)[1] + return UserRole(raw) + + +def is_ladder_role(role: UserRole | str) -> bool: + try: + return normalize_role(role) in LADDER + except ValueError: + return False + + +def role_rank(role: UserRole | str) -> UserRole: + """The ladder rung ``role`` counts as (itself for ladder roles, VIEWER for the rest).""" + return ROLE_BASE_RANK[normalize_role(role)] + + +def rank_index(role: UserRole | str) -> int: + """Position of ``role``'s rank on the ladder (0 = VIEWER). + + The ONLY place that indexes the ladder. Never raises for a ``UserRole`` + member; raises ``ValueError`` for a string that is not a role, which callers + already treat as "refuse". + """ + return LADDER.index(role_rank(role)) + + +# ── Permissions ────────────────────────────────────────────────────────────── + + +class AgentCeiling(str, Enum): + """How far an AGENT principal may ever hold a permission (epic E01).""" + + YES = "yes" # may hold it outright + PROPOSE = "propose" # its writes become proposals a human approves + DRAFT = "draft" # it may only create drafts / dry runs + NO = "no" # never granted to an agent + NEVER = "never" # never, by separation of duties (sign, decide, approve, administer) + + +@dataclass(frozen=True) +class PermissionSpec: + description: str + legacy_min_rank: UserRole + agent_ceiling: AgentCeiling + + +class Permission(str, Enum): + PROJECT_READ = "project.read" + REQUIREMENT_READ = "requirement.read" + RUN_INGEST = "run.ingest" + RUN_DELETE = "run.delete" + FAILURE_TRIAGE_ASSIGNED = "failure.triage.assigned" + FAILURE_TRIAGE_ANY = "failure.triage.any" + CLASSIFICATION_CORRECT = "classification.correct" + ANALYSIS_TRIGGER = "analysis.trigger" + DEFECT_CREATE = "defect.create" + QUARANTINE_PROPOSE = "quarantine.propose" + QUARANTINE_DECIDE = "quarantine.decide" + TESTCASE_WRITE = "testcase.write" + TESTCASE_REVIEW = "testcase.review" + TESTCASE_APPROVE = "testcase.approve" + TESTPLAN_WRITE = "testplan.write" + TESTPLAN_SCHEDULE = "testplan.schedule" + TESTPLAN_EXECUTE = "testplan.execute" + OWNERSHIP_MANAGE = "ownership.manage" + TAXONOMY_MANAGE = "taxonomy.manage" + REQUIREMENT_WRITE = "requirement.write" + REQUIREMENT_LINK = "requirement.link" + UAT_MANAGE = "uat.manage" + ACCEPTANCE_SIGNOFF = "acceptance.signoff" + RISK_WRITE = "risk.write" + RISK_ACCEPT = "risk.accept" + RELEASE_WRITE = "release.write" + RELEASE_SCHEDULE = "release.schedule" + RELEASE_GATE_EVALUATE = "release.gate.evaluate" + RELEASE_CHECKLIST_MANAGE = "release.checklist.manage" + RELEASE_SIGNOFF = "release.signoff" + RELEASE_DECIDE = "release.decide" + RELEASE_OVERRIDE_REQUEST = "release.override.request" + RELEASE_OVERRIDE_APPROVE = "release.override.approve" + RELEASE_CALENDAR_MANAGE = "release.calendar.manage" + RELEASE_DELETE = "release.delete" + GATE_POLICY_WRITE = "gate_policy.write" + GATE_POLICY_PUBLISH = "gate_policy.publish" + REPORT_PUBLISH = "report.publish" + AUDIT_READ_PROJECT = "audit.read.project" + AI_CHAT = "ai.chat" + AGENT_PROPOSAL_APPROVE = "agent.proposal.approve" + AGENT_MANAGE = "agent.manage" + APIKEY_CREATE_OWN = "apikey.create.own" + PROJECT_SETTINGS = "project.settings" + MEMBER_MANAGE = "member.manage" + INSTANCE_ADMIN = "instance.admin" + + @property + def spec(self) -> PermissionSpec: + return PERMISSION_SPECS[self] + + @property + def legacy_min_rank(self) -> UserRole: + return PERMISSION_SPECS[self].legacy_min_rank + + @property + def agent_ceiling(self) -> AgentCeiling: + return PERMISSION_SPECS[self].agent_ceiling + + +_V, _T, _E, _L, _A = ( + UserRole.VIEWER, UserRole.TESTER, UserRole.QA_ENGINEER, UserRole.QA_LEAD, UserRole.ADMIN, +) +_YES, _PROPOSE, _DRAFT, _NO, _NEVER = ( + AgentCeiling.YES, AgentCeiling.PROPOSE, AgentCeiling.DRAFT, AgentCeiling.NO, AgentCeiling.NEVER, +) + +#: The whole vocabulary, including permissions only later epics put on routes, +#: so parallel epics never edit this table at the same time. +PERMISSION_SPECS: Mapping[Permission, PermissionSpec] = { + Permission.PROJECT_READ: PermissionSpec("Read a project's runs, results, clusters, releases and reports", _V, _YES), + Permission.REQUIREMENT_READ: PermissionSpec("Read requirements and the coverage matrix", _V, _YES), + Permission.RUN_INGEST: PermissionSpec("Ingest, upload or stream test results", _E, _YES), + Permission.RUN_DELETE: PermissionSpec("Delete runs", _A, _NEVER), + Permission.FAILURE_TRIAGE_ASSIGNED: PermissionSpec("Triage failures assigned to me or in code I own", _E, _PROPOSE), + Permission.FAILURE_TRIAGE_ANY: PermissionSpec("Assign, reassign or resolve any failure in the project", _L, _NO), + Permission.CLASSIFICATION_CORRECT: PermissionSpec("Correct an AI root-cause classification", _E, _PROPOSE), + Permission.ANALYSIS_TRIGGER: PermissionSpec("Trigger AI analysis, investigations and pipelines", _E, _YES), + Permission.DEFECT_CREATE: PermissionSpec("Promote a cluster to a defect or file an issue", _E, _DRAFT), + Permission.QUARANTINE_PROPOSE: PermissionSpec("Propose quarantining a flaky test", _L, _YES), + Permission.QUARANTINE_DECIDE: PermissionSpec("Approve, reject or release a quarantine", _L, _NO), + Permission.TESTCASE_WRITE: PermissionSpec("Create and edit managed test cases and suites", _E, _DRAFT), + Permission.TESTCASE_REVIEW: PermissionSpec("Review managed test cases", _E, _NO), + Permission.TESTCASE_APPROVE: PermissionSpec("Approve managed test cases", _L, _NO), + Permission.TESTPLAN_WRITE: PermissionSpec("Create and edit test plans and their items", _T, _DRAFT), + Permission.TESTPLAN_SCHEDULE: PermissionSpec("Set dates, owners and assignees on plans, phases and UAT cycles", _L, _NO), + Permission.TESTPLAN_EXECUTE: PermissionSpec("Record manual results on assigned items", _T, _NO), + Permission.OWNERSHIP_MANAGE: PermissionSpec("Manage suite owners, ownership rules and the default QA lead", _L, _NO), + Permission.TAXONOMY_MANAGE: PermissionSpec("Manage test level and type classification rules", _L, _NO), + Permission.REQUIREMENT_WRITE: PermissionSpec("Create and edit requirements and acceptance criteria", _L, _DRAFT), + Permission.REQUIREMENT_LINK: PermissionSpec("Link tests to requirements", _E, _PROPOSE), + Permission.UAT_MANAGE: PermissionSpec("Create UAT cycles and assign testers", _L, _NO), + Permission.ACCEPTANCE_SIGNOFF: PermissionSpec("Accept or reject a requirement or UAT cycle", _L, _NEVER), + Permission.RISK_WRITE: PermissionSpec("Write the risks and blockers register", _E, _YES), + Permission.RISK_ACCEPT: PermissionSpec("Accept a known issue as a release exception", _L, _NEVER), + Permission.RELEASE_WRITE: PermissionSpec("Create, edit and activate releases, phases and run links", _L, _NO), + Permission.RELEASE_SCHEDULE: PermissionSpec("Change release and phase dates and milestones", _L, _NO), + Permission.RELEASE_GATE_EVALUATE: PermissionSpec("Evaluate a release or phase gate", _L, _YES), + Permission.RELEASE_CHECKLIST_MANAGE: PermissionSpec("Manage readiness checklist items and evidence", _L, _PROPOSE), + Permission.RELEASE_SIGNOFF: PermissionSpec("Sign a release as a required signer", _L, _NEVER), + Permission.RELEASE_DECIDE: PermissionSpec("Record the go / no-go decision", _L, _NEVER), + Permission.RELEASE_OVERRIDE_REQUEST: PermissionSpec("Request a gate override", _L, _NO), + Permission.RELEASE_OVERRIDE_APPROVE: PermissionSpec("Approve someone else's gate override", _L, _NEVER), + Permission.RELEASE_CALENDAR_MANAGE: PermissionSpec("Manage the release calendar and freeze windows", _L, _NO), + Permission.RELEASE_DELETE: PermissionSpec("Delete releases, phases and run links", _A, _NEVER), + Permission.GATE_POLICY_WRITE: PermissionSpec("Draft release gate policies", _A, _NO), + Permission.GATE_POLICY_PUBLISH: PermissionSpec("Publish or deactivate release gate policies", _A, _NEVER), + Permission.REPORT_PUBLISH: PermissionSpec("Publish status and completion reports and compliance packs", _L, _DRAFT), + Permission.AUDIT_READ_PROJECT: PermissionSpec("Read one project's audit trail", _L, _NO), + Permission.AI_CHAT: PermissionSpec("Ask AI (feature flags still apply)", _V, _YES), + Permission.AGENT_PROPOSAL_APPROVE: PermissionSpec("Approve or reject an agent's proposal", _L, _NEVER), + Permission.AGENT_MANAGE: PermissionSpec("Register agents, grant their permissions, revoke them", _A, _NEVER), + Permission.APIKEY_CREATE_OWN: PermissionSpec("Mint my own API keys", _E, _NEVER), + Permission.PROJECT_SETTINGS: PermissionSpec("Change one project's settings and integrations", _L, _NO), + Permission.MEMBER_MANAGE: PermissionSpec("Add and remove project members and set their roles", _L, _NEVER), + Permission.INSTANCE_ADMIN: PermissionSpec("Users, SSO/SCIM, flags, retention, storage, maintenance", _A, _NEVER), +} + +#: An AGENT can never hold these, whatever its grants say (SoD-1). +AGENT_FORBIDDEN: frozenset[Permission] = frozenset( + p for p, spec in PERMISSION_SPECS.items() if spec.agent_ceiling in (AgentCeiling.NO, AgentCeiling.NEVER) +) + +_P = Permission + +#: The job roles' and AGENT's explicit permission sets (03-role-model.md §6). +#: Conditional grants are listed here AND in ``ROLE_PERMISSION_CONDITIONS``. +_EXPLICIT_ROLE_PERMISSIONS: Mapping[UserRole, frozenset[Permission]] = { + UserRole.RELEASE_MANAGER: frozenset({ + _P.PROJECT_READ, _P.REQUIREMENT_READ, _P.ANALYSIS_TRIGGER, _P.DEFECT_CREATE, _P.TESTPLAN_SCHEDULE, + _P.RISK_WRITE, _P.RISK_ACCEPT, _P.RELEASE_WRITE, _P.RELEASE_SCHEDULE, _P.RELEASE_GATE_EVALUATE, + _P.RELEASE_CHECKLIST_MANAGE, _P.RELEASE_SIGNOFF, _P.RELEASE_DECIDE, _P.RELEASE_OVERRIDE_REQUEST, + _P.RELEASE_OVERRIDE_APPROVE, _P.RELEASE_CALENDAR_MANAGE, _P.GATE_POLICY_WRITE, _P.REPORT_PUBLISH, + _P.AUDIT_READ_PROJECT, _P.AGENT_PROPOSAL_APPROVE, _P.APIKEY_CREATE_OWN, _P.AI_CHAT, + }), + UserRole.PROJECT_MANAGER: frozenset({ + _P.PROJECT_READ, _P.REQUIREMENT_READ, _P.TESTPLAN_SCHEDULE, _P.RISK_WRITE, _P.RELEASE_SCHEDULE, + _P.RELEASE_SIGNOFF, _P.RELEASE_CALENDAR_MANAGE, _P.REPORT_PUBLISH, _P.AI_CHAT, + }), + UserRole.PRODUCT_MANAGER: frozenset({ + _P.PROJECT_READ, _P.REQUIREMENT_READ, _P.DEFECT_CREATE, _P.TESTPLAN_SCHEDULE, _P.TESTPLAN_EXECUTE, + _P.REQUIREMENT_WRITE, _P.REQUIREMENT_LINK, _P.UAT_MANAGE, _P.ACCEPTANCE_SIGNOFF, _P.RISK_WRITE, + _P.RISK_ACCEPT, _P.RELEASE_SIGNOFF, _P.AI_CHAT, + }), + UserRole.DEVELOPER: frozenset({ + _P.PROJECT_READ, _P.REQUIREMENT_READ, _P.RUN_INGEST, _P.FAILURE_TRIAGE_ASSIGNED, + _P.CLASSIFICATION_CORRECT, _P.ANALYSIS_TRIGGER, _P.DEFECT_CREATE, _P.QUARANTINE_PROPOSE, + _P.TESTCASE_WRITE, _P.TESTCASE_REVIEW, _P.REQUIREMENT_LINK, _P.RISK_WRITE, _P.AGENT_PROPOSAL_APPROVE, + _P.APIKEY_CREATE_OWN, _P.AI_CHAT, + }), + # An agent's base: it reads. Everything else comes from its registration + # grants (epic E01), never beyond its sponsor, never AGENT_FORBIDDEN. + UserRole.AGENT: frozenset({_P.PROJECT_READ, _P.REQUIREMENT_READ}), +} + + +def _ladder_permissions(role: UserRole) -> frozenset[Permission]: + idx = LADDER.index(role) + return frozenset(p for p, spec in PERMISSION_SPECS.items() if idx >= LADDER.index(spec.legacy_min_rank)) + + +#: Every role's permission set: computed for ladder roles, explicit for the rest. +ROLE_PERMISSIONS: Mapping[UserRole, frozenset[Permission]] = { + **{role: _ladder_permissions(role) for role in LADDER}, + **_EXPLICIT_ROLE_PERMISSIONS, +} + +#: Grants that hold only for some resources. The route guard admits the holder +#: only when the route declares that its handler checks the condition +#: (``conditions_checked_in_handler=True``); the handler then calls +#: ``check_condition``. Anywhere else a conditional grant counts as not held. +ROLE_PERMISSION_CONDITIONS: Mapping[tuple[UserRole, Permission], str] = { + (UserRole.DEVELOPER, _P.FAILURE_TRIAGE_ASSIGNED): "owns_failure", + (UserRole.DEVELOPER, _P.QUARANTINE_PROPOSE): "owns_failure", + (UserRole.DEVELOPER, _P.AGENT_PROPOSAL_APPROVE): "own_domain_proposal", + (UserRole.RELEASE_MANAGER, _P.AGENT_PROPOSAL_APPROVE): "own_domain_proposal", + (UserRole.PROJECT_MANAGER, _P.RELEASE_SIGNOFF): "listed_in_signoff_matrix", +} + +#: Condition name -> ``(user, resource) -> bool``. Epics register theirs +#: (E08: ``owns_failure``); an unregistered condition is never satisfied. +_CONDITIONS: dict[str, Callable[[Any, Any], bool]] = {} + +#: ``frozenset()`` = unconditional; otherwise every named condition must hold. +Conditions = frozenset[str] +Grants = Mapping[Permission, Conditions] + + +def register_condition(name: str, check: Callable[[Any, Any], bool]) -> None: + _CONDITIONS[name] = check + + +def check_condition(conditions: Iterable[str], user: Any, resource: Any) -> bool: + """True when every named condition holds for ``user`` on ``resource``.""" + for name in conditions: + check = _CONDITIONS.get(name) + if check is None or not check(user, resource): + return False + return True + + +# ── Whose roles, which grants ──────────────────────────────────────────────── + + +def _job_roles(values: Any) -> tuple[UserRole, ...]: + """The valid extra job roles in a stored ``additional_roles`` value.""" + if not values: + return () + if isinstance(values, str): + values = [values] + out: list[UserRole] = [] + for value in values: + try: + role = normalize_role(value) + except ValueError: + continue + if role in JOB_ROLES and role not in out: + out.append(role) + return tuple(out) + + +def job_roles_in(values: Any) -> tuple[UserRole, ...]: + """The valid extra job roles in a stored ``additional_roles`` value, in enum order.""" + found = set(_job_roles(values)) + return tuple(role for role in EXTRA_ROLE_CHOICES if role in found) + + +def clean_additional_roles(values: Any, *, primary: UserRole | str | None = None) -> list[str]: + """Extra roles as stored: job roles only, in enum order, no repeats, never the primary role. + + ``ValueError`` naming the first value that is not a job role (a ladder role, + AGENT or an unknown string) -- the API answers it with a 400. ``None`` or an + empty value is ``[]``. + """ + if not values: + return [] + if isinstance(values, str): + values = [values] + wanted: set[UserRole] = set() + for value in values: + try: + role: Optional[UserRole] = normalize_role(value) + except ValueError: + role = None + if role is None or role not in JOB_ROLES: + allowed = ", ".join(r.value for r in EXTRA_ROLE_CHOICES) + raise ValueError(f"'{getattr(value, 'value', value)}' cannot be an extra role (allowed: {allowed})") + wanted.add(role) + skip = normalize_role(primary) if primary is not None else None + return [role.value for role in EXTRA_ROLE_CHOICES if role in wanted and role != skip] + + +def assigned_roles(primary: UserRole | str, additional: Any = None) -> tuple[UserRole, ...]: + """Primary role first, then valid extra job roles. ``ValueError`` for an unknown primary. + + An AGENT carries no extra roles; neither does a stored value that is a + ladder role, an unknown string, or AGENT (defensive: the API refuses them). + """ + role = normalize_role(primary) + if role == UserRole.AGENT: + return (role,) + return (role, *(r for r in _job_roles(additional) if r != role)) + + +def user_roles(user: Any) -> tuple[UserRole, ...]: + """A user's instance roles (``users.role`` + ``users.additional_roles``).""" + return assigned_roles(user.role, getattr(user, "additional_roles", None)) + + +def grants_for(roles: Iterable[UserRole]) -> dict[Permission, Conditions]: + """Permission -> conditions for a set of roles held together. + + Any role granting a permission unconditionally makes it unconditional; + otherwise the first condition found applies. + """ + out: dict[Permission, Conditions] = {} + for role in roles: + for perm in ROLE_PERMISSIONS.get(role, frozenset()): + cond = ROLE_PERMISSION_CONDITIONS.get((role, perm)) + conditions: Conditions = frozenset({cond}) if cond else frozenset() + if perm not in out: + out[perm] = conditions + elif not conditions: + out[perm] = frozenset() # another role grants it outright + return out + + +def agent_grants(base: Iterable[UserRole], registered: Iterable[Permission] = ()) -> dict[Permission, Conditions]: + """An agent's grants: its role's base plus registration grants, minus AGENT_FORBIDDEN.""" + out = grants_for(base) + for perm in registered: + out.setdefault(perm, frozenset()) + return {p: c for p, c in out.items() if p not in AGENT_FORBIDDEN} + + +def intersect(a: Grants, b: Grants) -> dict[Permission, Conditions]: + """Permissions held on both sides; a permission conditional on either side keeps those conditions.""" + return {p: a[p] | b[p] for p in a.keys() & b.keys()} + + +def effective_grants( + instance_roles: Iterable[UserRole], + project_roles: Optional[Iterable[UserRole]], + *, + is_write: bool, +) -> dict[Permission, Conditions]: + """What a caller may do in one project. + + No membership row (``project_roles is None``): the instance roles (the + membership guard refuses a non-member separately). A read: the project + roles. A write: the intersection of both -- a project role can lower what + someone may do there, never raise it. + """ + instance = _for(instance_roles) + if project_roles is None: + return instance + project = _for(project_roles) + return intersect(instance, project) if is_write else project + + +def _for(roles: Iterable[UserRole]) -> dict[Permission, Conditions]: + roles = tuple(roles) + if UserRole.AGENT in roles: + return agent_grants(roles) + return grants_for(roles) + + +def has_permission( + roles: Iterable[UserRole], permission: Permission, *, allow_conditional: bool = False +) -> bool: + """Whether ``roles`` (held together) grant ``permission``. + + A conditional grant counts only with ``allow_conditional=True`` -- the caller + then owes a ``check_condition`` on the resource. + """ + grants = _for(roles) + if permission not in grants: + return False + return allow_conditional or not grants[permission] + + +def granted(grants: Grants, permission: Permission, *, allow_conditional: bool = False) -> bool: + if permission not in grants: + return False + return allow_conditional or not grants[permission] + + +def roles_holding(permission: Permission) -> list[UserRole]: + """Roles that hold ``permission`` (outright or conditionally), ladder first, for messages.""" + return [role for role in UserRole if permission in ROLE_PERMISSIONS.get(role, frozenset())] + + +def permission_refusal_detail(permission: Permission, *, in_project: bool = False) -> str: + holders = ", ".join(role.value for role in roles_holding(permission) if role != UserRole.AGENT) + where = " in this project" if in_project else "" + return f"Requires the '{permission.value}' permission{where} (held by: {holders})" + + +# ── Granting roles ─────────────────────────────────────────────────────────── + + +#: Roles only an administrator gives (owner decision D-17, 2026-11-26): the release, project and product +#: managers own sign-offs, schedules and acceptance, so who holds them is not a project lead's call even where +#: every permission of the role is one the lead holds. (AGENT is never given here at all.) +ADMIN_ONLY_GRANTS: frozenset[UserRole] = frozenset({ + UserRole.RELEASE_MANAGER, + UserRole.PROJECT_MANAGER, + UserRole.PRODUCT_MANAGER, +}) + + +def can_grant( + granter_roles: Iterable[UserRole], role: UserRole | str, *, grants: Optional[Grants] = None +) -> bool: + """Whether someone holding ``granter_roles`` may give ``role`` to another person. + + Every permission of ``role`` (conditional ones included) must be a + permission the granter holds. For two ladder roles this is "not above your + own rank", the rule the members router has always applied. A role in + ``ADMIN_ONLY_GRANTS`` also needs ``instance.admin`` (D-17). AGENT is + granted only through agent registration (epic E01), never here; ADMIN + callers are handled by the router before this is asked. + + ``grants`` (when given) replaces the granter's own grants: the members + routes pass what the granter may do in THAT project (``effective_grants``), + so a project role that caps them caps what they hand out there too. + """ + target = normalize_role(role) + if target == UserRole.AGENT: + return False + held = grants if grants is not None else grants_for(tuple(granter_roles)) + if target in ADMIN_ONLY_GRANTS and Permission.INSTANCE_ADMIN not in held: + return False + return ROLE_PERMISSIONS.get(target, frozenset()) <= held.keys() + + +def missing_for_grant( + granter_roles: Iterable[UserRole], role: UserRole | str, *, grants: Optional[Grants] = None +) -> list[str]: + """The permissions ``role`` has that the granter lacks, sorted, for refusal messages.""" + held = grants if grants is not None else grants_for(tuple(granter_roles)) + return sorted(p.value for p in ROLE_PERMISSIONS.get(normalize_role(role), frozenset()) - held.keys()) diff --git a/backend/app/models/postgres.py b/backend/app/models/postgres.py index b5a3407cb..5783cbd9e 100644 --- a/backend/app/models/postgres.py +++ b/backend/app/models/postgres.py @@ -92,11 +92,20 @@ class Severity(str, PyEnum): class UserRole(str, PyEnum): + # The authority ladder (ranks), lowest first. Exactly five rungs. VIEWER = "VIEWER" TESTER = "TESTER" QA_ENGINEER = "QA_ENGINEER" QA_LEAD = "QA_LEAD" ADMIN = "ADMIN" + # Job roles and the agent principal (enterprise roles E00). Not rungs: each + # counts as VIEWER on a guard that names no permission, and holds an + # explicit permission set (app/core/permissions.py). + RELEASE_MANAGER = "RELEASE_MANAGER" + PROJECT_MANAGER = "PROJECT_MANAGER" + PRODUCT_MANAGER = "PRODUCT_MANAGER" + DEVELOPER = "DEVELOPER" + AGENT = "AGENT" class TestCaseLifecycleState(str, PyEnum): @@ -233,6 +242,10 @@ class User(Base): # surface means this is NOT NULL; the row itself is never deleted (it is the pseudonymous key every # kept row points at). erased_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True) + # Enterprise roles E00 (migration 0266): extra job roles a person holds on the instance besides ``role`` + # (RELEASE_MANAGER, PROJECT_MANAGER, PRODUCT_MANAGER, DEVELOPER only). ``role`` alone gives the rank; + # these only add permissions (app/core/permissions.py). NULL = none. + additional_roles: Mapped[Optional[list]] = mapped_column(JSON().with_variant(JSONB(), "postgresql"), nullable=True) class MfaRecoveryCode(Base): @@ -4570,6 +4583,9 @@ class ProjectMember(Base): created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) # W20 ADM-09: NULL = granted by a person; "scim:" = created by SCIM group reconciliation. source: Mapped[Optional[str]] = mapped_column(String(80), nullable=True) + # Enterprise roles E00 (migration 0266): extra job roles in this project besides ``role``. On a write + # the instance roles and these project roles intersect (app/core/permissions.py). NULL = none. + additional_roles: Mapped[Optional[list]] = mapped_column(JSON().with_variant(JSONB(), "postgresql"), nullable=True) class ApiKey(Base): @@ -4906,6 +4922,8 @@ class UserInvitation(Base): ) #: ``[{"project_id": "", "role": ""}]`` granted on accept. project_memberships: Mapped[Optional[list]] = mapped_column(JSONB, nullable=True) + # Enterprise roles D-16 (migration 0266): extra job roles the invitee gets on accept; NULL = none. + additional_roles: Mapped[Optional[list]] = mapped_column(JSON().with_variant(JSONB(), "postgresql"), nullable=True) expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) diff --git a/backend/app/models/schemas.py b/backend/app/models/schemas.py index 1cd3223c7..dbd2b73f4 100644 --- a/backend/app/models/schemas.py +++ b/backend/app/models/schemas.py @@ -3,12 +3,13 @@ import re import uuid from datetime import date, datetime -from typing import Any, ClassVar, Dict, List, Literal, Optional, Union +from typing import Annotated, Any, ClassVar, Dict, List, Literal, Optional, Union from pydantic import ( AliasChoices, AwareDatetime, BaseModel, + BeforeValidator, ConfigDict, EmailStr, Field, @@ -193,6 +194,22 @@ def check_new_username(value: Optional[str]) -> Optional[str]: return value +#: Extra job roles a person may hold beside their primary role (enterprise roles D-16). A request listing +#: anything else is a 422. ``permissions.EXTRA_ROLE_CHOICES`` is the same list (a test keeps them equal). +ExtraRole = Literal["RELEASE_MANAGER", "PROJECT_MANAGER", "PRODUCT_MANAGER", "DEVELOPER"] + + +def _stored_extra_roles(value: Any) -> list[str]: + """``additional_roles`` read from a row: NULL is ``[]``; anything but a job role is dropped.""" + from app.core.permissions import job_roles_in + + return [role.value for role in job_roles_in(value)] + + +#: ``additional_roles`` in a response (enum order, never NULL). +StoredExtraRoles = Annotated[List[UserRole], BeforeValidator(_stored_extra_roles)] + + class UserCreate(BaseModel): email: EmailStr username: str = Field(..., min_length=3, max_length=50, json_schema_extra={"pattern": USERNAME_PATTERN}) @@ -659,6 +676,8 @@ class MfaStatusResponse(BaseModel): class MfaPolicyRead(BaseModel): require_mfa: bool required_for_role: Optional[UserRole] = None + #: Enterprise roles E00-S05: roles that need MFA whatever the floor (primary or extra role). + required_roles: List[UserRole] = Field(default_factory=list) lockout_enabled: bool lockout_threshold: int lockout_duration_minutes: int @@ -666,7 +685,10 @@ class MfaPolicyRead(BaseModel): class MfaPolicyUpdate(BaseModel): require_mfa: Optional[bool] = None + #: A rank (VIEWER .. ADMIN); a job role is refused (400) -- name it in ``required_roles`` instead. required_for_role: Optional[UserRole] = None + #: ``[]`` clears the list; omitted keeps it. AGENT is refused (agents never hold a second factor). + required_roles: Optional[List[UserRole]] = Field(None, max_length=10) lockout_enabled: Optional[bool] = None lockout_threshold: Optional[int] = Field(None, ge=3, le=100) lockout_duration_minutes: Optional[int] = Field(None, ge=1, le=1440) @@ -6821,6 +6843,8 @@ class UserListResponse(BaseModel): username: str full_name: Optional[str] = None role: UserRole + #: Enterprise roles D-16: extra job roles held beside ``role`` (which alone gives the rank). + additional_roles: StoredExtraRoles = Field(default_factory=list) is_active: bool created_at: datetime # W31 STRAT-12: an erased account (users.erased_at set) is still listed — as "Erased user" with the badge @@ -6857,6 +6881,8 @@ class UpdateUserProfileRequest(BaseModel): ) full_name: Optional[str] = None role: Optional[UserRole] = None + #: Extra job roles; ``[]`` clears them, omitted keeps them. + additional_roles: Optional[List[ExtraRole]] = Field(None, max_length=4) is_active: Optional[bool] = None @field_validator("username") @@ -6869,11 +6895,13 @@ class InviteProjectMembership(BaseModel): """W17b ADM-01: a project the invitee joins on accept, with its project role.""" project_id: uuid.UUID role: UserRole = UserRole.QA_ENGINEER + additional_roles: List[ExtraRole] = Field(default_factory=list, max_length=4) class InviteUserRequest(BaseModel): email: EmailStr role: UserRole = UserRole.QA_ENGINEER + additional_roles: List[ExtraRole] = Field(default_factory=list, max_length=4) project_memberships: List[InviteProjectMembership] = Field(default_factory=list, max_length=50) @@ -6881,6 +6909,7 @@ class InviteUserResponse(BaseModel): id: uuid.UUID email: str role: UserRole + additional_roles: StoredExtraRoles = Field(default_factory=list) expires_at: datetime #: ``{public_base_url}/accept-invite#token=…`` — shown once; only its hash is stored. invitation_link: str @@ -6893,6 +6922,7 @@ class InvitationMembershipView(BaseModel): project_id: uuid.UUID project_name: Optional[str] = None role: str + additional_roles: List[str] = Field(default_factory=list) class InvitationSummary(BaseModel): @@ -6900,6 +6930,7 @@ class InvitationSummary(BaseModel): id: uuid.UUID email: str role: UserRole + additional_roles: List[str] = Field(default_factory=list) #: ``pending`` | ``expired`` | ``used`` | ``revoked`` status: str expires_at: datetime @@ -6957,6 +6988,7 @@ class AdminCreateUserRequest(BaseModel): username: str = Field(..., min_length=3, max_length=50, json_schema_extra={"pattern": USERNAME_PATTERN}) full_name: Optional[str] = None role: UserRole = UserRole.QA_ENGINEER + additional_roles: List[ExtraRole] = Field(default_factory=list, max_length=4) @field_validator("username") @classmethod @@ -6970,6 +7002,7 @@ class AdminCreateUserResponse(BaseModel): username: str full_name: Optional[str] = None role: UserRole + additional_roles: StoredExtraRoles = Field(default_factory=list) is_active: bool created_at: datetime temp_password: str # shown once — admin must share with the user @@ -6982,6 +7015,9 @@ class ProjectMemberResponse(BaseModel): user_id: uuid.UUID project_id: uuid.UUID role: UserRole + #: Enterprise roles D-16: extra job roles in this project. On a write the caller's instance roles and these + #: project roles intersect ("the lower of the two decides"). + additional_roles: StoredExtraRoles = Field(default_factory=list) created_at: datetime # Joined user fields email: str @@ -7000,10 +7036,31 @@ class ProjectMemberResponse(BaseModel): class AddProjectMemberRequest(BaseModel): user_id: uuid.UUID role: UserRole = UserRole.QA_ENGINEER + additional_roles: List[ExtraRole] = Field(default_factory=list, max_length=4) class UpdateProjectMemberRoleRequest(BaseModel): role: UserRole + #: ``[]`` clears the extra roles; omitted keeps them. + additional_roles: Optional[List[ExtraRole]] = Field(None, max_length=4) + + +class MyPermissionsResponse(BaseModel): + """``GET /api/v1/me/permissions`` (enterprise roles E00-S04): what the caller may do, in one project or globally. + + ``read_permissions`` answers reads (the project roles decide); ``write_permissions`` answers writes (instance + roles and project roles intersect). A permission in ``conditional`` is granted only when the handler's check on + the resource passes (for example ``owns_failure``); the UI offers it and the server decides. + """ + role: UserRole + additional_roles: List[str] = Field(default_factory=list) + project_id: Optional[uuid.UUID] = None + #: ``None`` when ``project_id`` is absent, or the caller is an ADMIN who is not a member. + project_role: Optional[UserRole] = None + project_additional_roles: List[str] = Field(default_factory=list) + read_permissions: List[str] = Field(default_factory=list) + write_permissions: List[str] = Field(default_factory=list) + conditional: Dict[str, List[str]] = Field(default_factory=dict) # ── API Key Schemas ─────────────────────────────────────────── @@ -7497,6 +7554,9 @@ class SSORolePreviewResponse(BaseModel): source: Literal["mapping", "default"] ceiling: str clamped: bool + #: Enterprise roles E00-S05: extra job roles the groups add, and the groups that added each. + additional_roles: list[str] = Field(default_factory=list) + additional_matched_groups: dict[str, list[str]] = Field(default_factory=dict) class SAMLLoginInitResponse(BaseModel): diff --git a/backend/app/routers/app_settings.py b/backend/app/routers/app_settings.py index 71a319ba8..64e655d34 100644 --- a/backend/app/routers/app_settings.py +++ b/backend/app/routers/app_settings.py @@ -1609,13 +1609,32 @@ async def update_mfa_policy( db: AsyncSession = Depends(get_db), ) -> MfaPolicyRead: """Update the workspace MFA + lockout policy. ADMIN only, audit-logged.""" + from app.core.permissions import is_ladder_role from app.models.postgres import IdentityEventType - from app.services.mfa_service import MfaPolicy, load_policy, save_policy + from app.services.mfa_service import MfaPolicy, clean_required_roles, load_policy, save_policy from app.services.sso_service import log_identity_event current = await load_policy(db) updates = payload.model_dump(exclude_none=True) updates.pop("clear_required_for_role", None) + updates.pop("required_roles", None) + + # Enterprise roles E00-S05: the floor is a rank; a job role is named in ``required_roles`` instead (a job + # role's rank is VIEWER, so as a floor it would silently mean "everyone"). + if payload.required_for_role is not None and not is_ladder_role(payload.required_for_role): + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="The MFA floor must be a rank (VIEWER, TESTER, QA_ENGINEER, QA_LEAD or ADMIN); " + "list job roles under required roles", + ) + if payload.required_roles is not None and UserRole.AGENT in payload.required_roles: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, detail="AGENT cannot be required to use MFA (agents sign in with keys)", + ) + required_roles = ( + clean_required_roles(payload.required_roles) if payload.required_roles is not None + else current.required_roles + ) role_value = updates.pop("required_for_role", None) if payload.clear_required_for_role: @@ -1635,6 +1654,7 @@ async def update_mfa_policy( lockout_duration_minutes=updates.get( "lockout_duration_minutes", current.lockout_duration_minutes ), + required_roles=required_roles, ) await save_policy(db, merged, actor_id=current_user.id) diff --git a/backend/app/routers/auth.py b/backend/app/routers/auth.py index 8329b372c..f2fa0b1d5 100644 --- a/backend/app/routers/auth.py +++ b/backend/app/routers/auth.py @@ -168,6 +168,7 @@ async def accept_invitation( of tokens (an invite never skips the second factor). """ from app.core.deps import invalidate_membership_cache + from app.core.permissions import job_roles_in from app.models.postgres import Project, ProjectMember from app.services.access_audit_service import log_access_change @@ -196,6 +197,7 @@ async def accept_invitation( full_name=payload.full_name, hashed_password=get_password_hash(payload.password), role=invitation.role, + additional_roles=[r.value for r in job_roles_in(getattr(invitation, "additional_roles", None))] or None, must_change_password=False, ) db.add(user) @@ -211,10 +213,15 @@ async def accept_invitation( if project is None or not getattr(project, "is_active", True): continue # archived since the invite: skip, never fail the whole accept role_value = str(m.get("role") or UserRole.QA_ENGINEER.value) - db.add(ProjectMember(user_id=user.id, project_id=project_id, role=role_value)) + member_extras = [r.value for r in job_roles_in(m.get("additional_roles")) if r.value != role_value] + db.add(ProjectMember( + user_id=user.id, project_id=project_id, role=role_value, additional_roles=member_extras or None, + )) + added: dict = {"role": role_value, "via": "invitation"} + if member_extras: + added["additional_roles"] = member_extras await log_access_change( - db, "member_added", None, target_user_id=user.id, project_id=project_id, - after_value={"role": role_value, "via": "invitation"}, + db, "member_added", None, target_user_id=user.id, project_id=project_id, after_value=added, ) granted += 1 @@ -638,6 +645,12 @@ async def login( "qa_engineer": UserRole.QA_ENGINEER, "tester": UserRole.TESTER, "viewer": UserRole.VIEWER, + # Enterprise roles E00-S06: the four job roles. AGENT is not a slug -- agents + # are registered (E01), never signed in as a person. + "release_manager": UserRole.RELEASE_MANAGER, + "project_manager": UserRole.PROJECT_MANAGER, + "product_manager": UserRole.PRODUCT_MANAGER, + "developer": UserRole.DEVELOPER, } # Defaults used when creating a temporary user if the seed has not run yet @@ -647,6 +660,18 @@ async def login( UserRole.QA_ENGINEER: {"email": "engineer@testlookup.dev", "username": "qa_engineer", "full_name": "Dev QA Engineer"}, UserRole.TESTER: {"email": "tester@testlookup.dev", "username": "tester", "full_name": "Dev Tester"}, UserRole.VIEWER: {"email": "viewer@testlookup.dev", "username": "viewer", "full_name": "Dev Viewer"}, + UserRole.RELEASE_MANAGER: { + "email": "release.manager@testlookup.dev", "username": "release_manager", "full_name": "Dev Release Manager", + }, + UserRole.PROJECT_MANAGER: { + "email": "project.manager@testlookup.dev", "username": "project_manager", "full_name": "Dev Project Manager", + }, + UserRole.PRODUCT_MANAGER: { + "email": "product.manager@testlookup.dev", "username": "product_manager", "full_name": "Dev Product Manager", + }, + UserRole.DEVELOPER: { + "email": "developer@testlookup.dev", "username": "developer", "full_name": "Dev Developer", + }, } diff --git a/backend/app/routers/me_permissions.py b/backend/app/routers/me_permissions.py new file mode 100644 index 000000000..17e60c535 --- /dev/null +++ b/backend/app/routers/me_permissions.py @@ -0,0 +1,80 @@ +"""What the signed-in caller may do (enterprise roles, epic E00-S04). + +``GET /api/v1/me/permissions?project_id=`` answers the caller's roles and +permission sets in one project, or globally without ``project_id``. The SPA's +``can(permission, {write})`` reads it, so a control is offered only to someone +the server would let through. The server stays the authority: every route +checks its own guard. + +* Reads use the project roles; writes the intersection of the caller's instance + roles and project roles ("the lower of the two decides"). No membership (an + ADMIN looking at a project they are not a member of) means the instance roles. +* A project the caller cannot read is a 403 (``resolve_project_scope``), the + same answer every project-scoped read gives. +* A GET with no side effects, so no role gate: every signed-in role may ask. +""" +from __future__ import annotations + +import uuid +from typing import Optional + +from fastapi import APIRouter, Depends, Query +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.deps import get_current_active_user, resolve_project_scope +from app.core.permissions import Grants, assigned_roles, effective_grants, job_roles_in, user_roles +from app.db.postgres import get_db +from app.models.postgres import ProjectMember, User, UserRole +from app.models.schemas import MyPermissionsResponse + +router = APIRouter(prefix="/api/v1/me", tags=["My Permissions"]) + + +def _names(grants: Grants) -> list[str]: + return sorted(permission.value for permission in grants) + + +def _conditional(read: Grants, write: Grants) -> dict[str, list[str]]: + out: dict[str, set[str]] = {} + for grants in (read, write): + for permission, conditions in grants.items(): + if conditions: + out.setdefault(permission.value, set()).update(conditions) + return {name: sorted(conditions) for name, conditions in sorted(out.items())} + + +@router.get("/permissions", response_model=MyPermissionsResponse) +async def get_my_permissions( + project_id: Optional[str] = Query(None, description="Answer for this project; omitted, the global sets"), + db: AsyncSession = Depends(get_db), + current_user: User = Depends(get_current_active_user), +) -> MyPermissionsResponse: + """The caller's roles and the permissions they hold, for reads and for writes.""" + instance = user_roles(current_user) + pinned: Optional[uuid.UUID] = None + project_roles: Optional[tuple[UserRole, ...]] = None + if project_id: + pinned, _ = await resolve_project_scope(db, current_user, project_id) + row = (await db.execute( + select(ProjectMember.role, ProjectMember.additional_roles).where( + ProjectMember.user_id == current_user.id, ProjectMember.project_id == pinned, + ) + )).first() + if row is not None: + try: + project_roles = assigned_roles(row[0], row[1]) + except ValueError: + project_roles = (UserRole.VIEWER,) + read = effective_grants(instance, project_roles, is_write=False) + write = effective_grants(instance, project_roles, is_write=True) + return MyPermissionsResponse( + role=instance[0], + additional_roles=[role.value for role in instance[1:]], + project_id=pinned, + project_role=project_roles[0] if project_roles else None, + project_additional_roles=[role.value for role in job_roles_in(project_roles[1:])] if project_roles else [], + read_permissions=_names(read), + write_permissions=_names(write), + conditional=_conditional(read, write), + ) diff --git a/backend/app/routers/run_compare.py b/backend/app/routers/run_compare.py index 02a23031f..fa212bd33 100644 --- a/backend/app/routers/run_compare.py +++ b/backend/app/routers/run_compare.py @@ -16,8 +16,8 @@ from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession +from app.core.permissions import rank_index from app.core.deps import ( - _ROLE_ORDER, _normalize_user_role, get_current_active_user, get_db, @@ -207,10 +207,10 @@ async def compare_latest_suite_runs( def _may_generate_report(user: User) -> bool: """QA_ENGINEER and above, by global role, like every other LLM-triggering route.""" try: - idx = _ROLE_ORDER.index(_normalize_user_role(user.role)) + idx = rank_index(_normalize_user_role(user.role)) except ValueError: return False - return idx >= _ROLE_ORDER.index(UserRole.QA_ENGINEER) + return idx >= rank_index(UserRole.QA_ENGINEER) async def _resolve_ai_report( diff --git a/backend/app/routers/sso.py b/backend/app/routers/sso.py index feb393925..c46d8db0a 100644 --- a/backend/app/routers/sso.py +++ b/backend/app/routers/sso.py @@ -19,6 +19,7 @@ from app.services.refresh_token_service import issue_refresh_token from app.db.postgres import get_db from app.core.token_revocation import RevocationUnavailable, revoke_all_user_tokens +from app.core.permissions import EXTRA_ROLE_CHOICES, LADDER from app.models.postgres import ( FederatedIdentity, IdentityEventType, @@ -82,6 +83,10 @@ def _jit_refusal(user: User, is_new: bool) -> Optional[str]: return USERNAME_RESERVED_DETAIL return None +#: Enterprise roles E00-S05: a group maps to a rank (the user's role) or a job role (an extra role). +#: Never AGENT. ``default_role`` stays a rank. +_MAPPABLE_ROLES: tuple[str, ...] = tuple(r.value for r in (*LADDER, *EXTRA_ROLE_CHOICES)) + router = APIRouter(prefix="/api/v1/sso", tags=["SSO / SAML"]) # Upper bound on an inbound base64 SAMLResponse before we decode/parse it. @@ -789,7 +794,7 @@ async def create_sso_config( # Validate role mapping values if payload.role_mapping: - valid_roles = {r.value for r in UserRole} + valid_roles = _MAPPABLE_ROLES for group_name, role_value in payload.role_mapping.items(): if role_value not in valid_roles: raise HTTPException( @@ -889,7 +894,7 @@ async def update_sso_config( # Validate role mapping if being updated if "role_mapping" in update_data and update_data["role_mapping"]: - valid_roles = {r.value for r in UserRole} + valid_roles = _MAPPABLE_ROLES for group_name, role_value in update_data["role_mapping"].items(): if role_value not in valid_roles: raise HTTPException( @@ -1001,10 +1006,10 @@ async def preview_sso_role( config = (await db.execute(select(SSOConfiguration).where(SSOConfiguration.id == config_id))).scalar_one_or_none() if not config: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="SSO configuration not found") - valid_roles = {r.value for r in UserRole} + valid_roles = {r.value for r in LADDER} mapping = payload.role_mapping if payload.role_mapping is not None else (config.role_mapping or {}) for group_name, role_value in mapping.items(): - if role_value not in valid_roles: + if role_value not in _MAPPABLE_ROLES: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Invalid role '{role_value}' in role_mapping for group '{group_name}'", diff --git a/backend/app/routers/users.py b/backend/app/routers/users.py index f5c749d43..879cc88b2 100644 --- a/backend/app/routers/users.py +++ b/backend/app/routers/users.py @@ -14,6 +14,17 @@ from app.core.deps import get_current_active_user, require_project_access, require_role from app.core.security import get_password_hash from app.db.postgres import get_db +from app.core.permissions import ( + ADMIN_ONLY_GRANTS, + assigned_roles, + can_grant, + clean_additional_roles, + effective_grants, + job_roles_in, + missing_for_grant, + normalize_role, + user_roles, +) from app.models.postgres import Project, ProjectMember, SettingsAuditLog, User, UserInvitation, UserRole from app.models.schemas import ( AddProjectMemberRequest, @@ -56,54 +67,157 @@ def _normalize_user_role(value: UserRole | str) -> UserRole: - """Convert a stored role string to a UserRole enum. + """Convert a stored role string to a UserRole enum (``permissions.normalize_role``).""" + return normalize_role(value) - After migration 0045, the ``UserRole.`` prefix guard is a safety net only. - """ - if isinstance(value, UserRole): - return value - raw_value = str(value).strip() - if raw_value.startswith("UserRole."): - raw_value = raw_value.split(".", 1)[1] - return UserRole(raw_value) + +def _refuse_agent_role(role: UserRole | str | None) -> None: + """AGENT is assigned only through agent registration (enterprise roles E01), never to a person here.""" + if role is None: + return + try: + is_agent = normalize_role(role) == UserRole.AGENT + except ValueError: + return # the request schema refuses an unknown role first + if is_agent: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="The AGENT role is given to AI agents through agent registration, not to people", + ) -_ROLE_ORDER: list[UserRole] = [ - UserRole.VIEWER, - UserRole.TESTER, - UserRole.QA_ENGINEER, - UserRole.QA_LEAD, - UserRole.ADMIN, -] +def _clean_extras(values, primary: UserRole | str | None) -> list[str]: + """Extra job roles as stored (``permissions.clean_additional_roles``); 400 for anything else.""" + try: + return clean_additional_roles(values, primary=primary) + except ValueError as exc: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc -def _role_rank(role: UserRole | str) -> int: +def _refuse_extras_for_agent(primary: UserRole | str, extras: list[str]) -> None: + if extras and normalize_role(primary) == UserRole.AGENT: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="An agent holds no extra roles") + + +def _stored_extras(value) -> list[str]: + return [role.value for role in job_roles_in(value)] + + +async def _granter_project_roles( + db: AsyncSession, current_user: User, project_id: uuid.UUID +) -> Optional[tuple[UserRole, ...]]: + """The caller's roles in ``project_id`` (None when not a member): what caps what they may hand out there. + + Asked only after ``_enforce_grant_ceiling`` has said the caller is not an ADMIN (an ADMIN grants anything). + """ + row = (await db.execute( + select(ProjectMember.role, ProjectMember.additional_roles).where( + ProjectMember.user_id == current_user.id, ProjectMember.project_id == project_id, + ) + )).one_or_none() + if row is None: + return None try: - return _ROLE_ORDER.index(_normalize_user_role(role)) + return assigned_roles(row[0], row[1]) except ValueError: - return -1 + return (UserRole.VIEWER,) + + +_MAX_NAMED_PERMISSIONS = 5 -def _enforce_grant_ceiling(current_user: User, granted_role: UserRole, target_user_id: uuid.UUID) -> None: - """Reject project-role grants that exceed the caller's authority. +def _enforce_grant_ceiling( + current_user: User, + granted_role: UserRole, + target_user_id: uuid.UUID, + *, + additional_roles: tuple[str, ...] | list[str] = (), + granter_project_roles: Optional[tuple[UserRole, ...]] = None, +) -> bool: + """Reject project-role grants that exceed the caller's authority. ``True`` when the caller is an ADMIN. A global ADMIN may grant any project role. Anyone else (QA_LEAD managing - members) may not grant a project role above their own global role, and may - not change their own membership role at all — both close the project-scoped - privilege-escalation path where a QA_LEAD mints a project-ADMIN (incl. self). + members) may grant only a role -- primary or extra -- whose permissions they + hold themselves (``permissions.can_grant``: for two ladder roles, "not above + your own rank", as before), and may not change their own membership role at + all -- both close the project-scoped privilege-escalation path where a + QA_LEAD mints a project-ADMIN (incl. self). AGENT is granted only through + agent registration. + + ``granter_project_roles`` (the caller's membership in the project) caps the + check the way it caps their writes: what they may do there is their + instance permissions INTERSECTED with their project permissions (D-2). + The refusal names the permissions the caller lacks. Returns ``True`` for an + ADMIN (nothing more to check: callers then skip the project lookup) and + ``False`` for anyone it let through on their permissions. """ + _refuse_agent_role(granted_role) if _normalize_user_role(current_user.role) == UserRole.ADMIN: - return + return True if target_user_id == current_user.id: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="You cannot change your own project role", ) - if _role_rank(granted_role) > _role_rank(current_user.role): + missing: dict[str, list[str]] = {} + admin_only: list[str] = [] + try: + granter_roles = user_roles(current_user) + grants = ( + effective_grants(granter_roles, granter_project_roles, is_write=True) + if granter_project_roles is not None else None + ) + for role in (granted_role, *additional_roles): + if can_grant(granter_roles, role, grants=grants): + continue + if normalize_role(role) in ADMIN_ONLY_GRANTS: + admin_only.append(normalize_role(role).value) # D-17: whatever the granter holds + else: + missing[normalize_role(role).value] = missing_for_grant(granter_roles, role, grants=grants) + except ValueError: + missing = {"": []} + if admin_only and not missing: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail=f"Only an administrator can give the {', '.join(admin_only)} role", + ) + if missing: + named = [] + for role, perms in missing.items(): + if not role or not perms: + continue + shown = ", ".join(perms[:_MAX_NAMED_PERMISSIONS]) + more = len(perms) - _MAX_NAMED_PERMISSIONS + named.append(f"{role} needs {shown}" + (f" and {more} more" if more > 0 else "")) + named.extend(f"{role} is given only by an administrator" for role in admin_only) + detail = "You cannot grant a project role higher than your own" raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, - detail="You cannot grant a project role higher than your own", + detail=detail + (f" ({'; '.join(named)})" if named else ""), ) + return False + + +async def _enforce_member_grant( + db: AsyncSession, + current_user: User, + project_id: uuid.UUID, + granted_role: UserRole, + target_user_id: uuid.UUID, + *, + additional_roles: tuple[str, ...] | list[str] = (), +) -> Optional[tuple[UserRole, ...]]: + """The grant ceiling for a membership: first on the caller's instance roles, then capped by their roles in + ``project_id``. Returns those project roles (``None`` for an ADMIN or a non-member) for a later check.""" + if _enforce_grant_ceiling(current_user, granted_role, target_user_id, additional_roles=additional_roles): + return None + project_roles = await _granter_project_roles(db, current_user, project_id) + if project_roles is not None: + _enforce_grant_ceiling( + current_user, granted_role, target_user_id, + additional_roles=additional_roles, granter_project_roles=project_roles, + ) + return project_roles def _build_project_member_response(member: ProjectMember, user: User) -> ProjectMemberResponse: @@ -112,6 +226,7 @@ def _build_project_member_response(member: ProjectMember, user: User) -> Project user_id=member.user_id, project_id=member.project_id, role=_normalize_user_role(member.role), + additional_roles=list(job_roles_in(getattr(member, "additional_roles", None))), created_at=member.created_at, email=user.email, username=user.username, @@ -216,11 +331,15 @@ async def update_user_role( refuse_erased(user) # W31: an erased account is never changed or restored (409, string detail) if user.id == current_user.id: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot change your own role") + _refuse_agent_role(payload.role) # Last-admin guard: refuse to strip ADMIN from the only other active admin. if _normalize_user_role(payload.role) != UserRole.ADMIN: await _assert_not_last_admin(db, user) old_role = str(user.role) user.role = payload.role + kept = _stored_extras(getattr(user, "additional_roles", None)) + if kept: + user.additional_roles = clean_additional_roles(kept, primary=payload.role) or None await log_access_change(db, "role_changed", current_user, target_user_id=user_id, before_value={"role": old_role}, after_value={"role": str(payload.role)}) await db.commit() @@ -314,12 +433,32 @@ async def update_user_profile( if payload.role is not None: if user.id == current_user.id: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot change your own role") + _refuse_agent_role(payload.role) if _normalize_user_role(payload.role) != UserRole.ADMIN: await _assert_not_last_admin(db, user) if str(user.role) != str(payload.role): access_changes.append(("role_changed", {"role": str(user.role)}, {"role": str(payload.role)})) user.role = payload.role + # Enterprise roles D-16: extra job roles. Only the primary role gives the rank; an extra role only adds + # permissions. Re-cleaned when the primary role changes (a primary role is never also an extra one). + # getattr: an older caller's payload (or a test double) may not carry the field at all -- omitted keeps them. + requested_extras = getattr(payload, "additional_roles", None) + if requested_extras is not None or payload.role is not None: + if requested_extras is not None and user.id == current_user.id: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot change your own role") + before_extras = _stored_extras(getattr(user, "additional_roles", None)) + wanted = requested_extras if requested_extras is not None else before_extras + after_extras = _clean_extras(wanted, primary=user.role) + _refuse_extras_for_agent(user.role, after_extras) + if after_extras != before_extras: + access_changes.append(( + "additional_roles_changed", + {"additional_roles": before_extras}, + {"additional_roles": after_extras}, + )) + user.additional_roles = after_extras or None + if payload.is_active is not None: if user.id == current_user.id: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot deactivate your own account") @@ -365,6 +504,8 @@ async def admin_create_user( detail="Email or username already registered", ) + _refuse_agent_role(payload.role) + extras = _clean_extras(getattr(payload, "additional_roles", None), primary=payload.role) temp_password = secrets.token_urlsafe(12) logger.info("admin_creating_user", role=str(payload.role), by=str(current_user.id)) user = User( @@ -373,6 +514,7 @@ async def admin_create_user( full_name=payload.full_name, hashed_password=get_password_hash(temp_password), role=payload.role, + additional_roles=extras or None, must_change_password=True, ) db.add(user) @@ -385,6 +527,7 @@ async def admin_create_user( username=user.username, full_name=user.full_name, role=user.role, + additional_roles=list(job_roles_in(user.additional_roles)), is_active=user.is_active, created_at=user.created_at, temp_password=temp_password, @@ -423,12 +566,15 @@ async def invite_user( detail="An active invitation already exists for this email. Resend or revoke it from Pending invitations.", ) + _refuse_agent_role(payload.role) + extras = _clean_extras(getattr(payload, "additional_roles", None), primary=payload.role) memberships = await _validated_invite_memberships(db, payload) raw, token_hash = new_token() invitation = UserInvitation( email=email, role=payload.role, + additional_roles=extras or None, token=None, token_hash=token_hash, invited_by_id=current_user.id, @@ -457,6 +603,7 @@ async def invite_user( id=invitation.id, email=invitation.email, role=invitation.role, + additional_roles=list(job_roles_in(getattr(invitation, "additional_roles", None))), expires_at=invitation.expires_at, invitation_link=link, email_sent=email_sent, @@ -472,7 +619,12 @@ async def _validated_invite_memberships(db: AsyncSession, payload: InviteUserReq ).scalar_one_or_none() if project is None or not getattr(project, "is_active", True): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Project not found") - out[str(m.project_id)] = {"project_id": str(m.project_id), "role": _normalize_user_role(m.role).value} + _refuse_agent_role(m.role) + entry: dict[str, object] = {"project_id": str(m.project_id), "role": _normalize_user_role(m.role).value} + member_extras = _clean_extras(m.additional_roles, primary=m.role) + if member_extras: + entry["additional_roles"] = member_extras + out[str(m.project_id)] = entry return list(out.values()) @@ -511,6 +663,7 @@ async def _invitation_summaries(db: AsyncSession, invitations: list[UserInvitati id=inv.id, email=inv.email, role=_normalize_user_role(inv.role), + additional_roles=_stored_extras(getattr(inv, "additional_roles", None)), status=invitation_status(inv, now), expires_at=inv.expires_at, created_at=inv.created_at, @@ -522,6 +675,7 @@ async def _invitation_summaries(db: AsyncSession, invitations: list[UserInvitati project_id=m["project_id"], project_name=projects.get(str(m["project_id"])), role=str(m.get("role") or ""), + additional_roles=_stored_extras(m.get("additional_roles")), ) for m in (inv.project_memberships or []) if isinstance(m, dict) and m.get("project_id") @@ -588,6 +742,7 @@ async def resend_invitation( id=invitation.id, email=invitation.email, role=invitation.role, + additional_roles=list(job_roles_in(getattr(invitation, "additional_roles", None))), expires_at=invitation.expires_at, invitation_link=link, email_sent=email_sent, @@ -659,6 +814,7 @@ async def get_user_memberships( "project_id": str(pm.project_id), "project_name": p.name, "role": _normalize_user_role(pm.role).value, + "additional_roles": _stored_extras(getattr(pm, "additional_roles", None)), "created_at": pm.created_at.isoformat() if pm.created_at else None, } for pm, p in rows @@ -727,9 +883,11 @@ async def add_project_member( raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found") refuse_erased(user) # W31: an erased account never regains a membership - # Privilege-escalation guard: a non-admin cannot grant a project role above - # their own, nor add themselves above their current standing. - _enforce_grant_ceiling(current_user, payload.role, payload.user_id) + # Privilege-escalation guard: a non-admin cannot grant a project role (or an + # extra role) above their own, nor add themselves above their current standing. + _refuse_agent_role(payload.role) + extras = _clean_extras(getattr(payload, "additional_roles", None), primary=payload.role) + await _enforce_member_grant(db, current_user, project_id, payload.role, payload.user_id, additional_roles=extras) # Check not already a member existing = await db.execute( @@ -746,10 +904,16 @@ async def add_project_member( normalized_role = _normalize_user_role(payload.role) logger.info("adding_project_member", project_id=str(project_id), user_id=str(payload.user_id), role=normalized_role.value, by=str(current_user.id)) - member = ProjectMember(user_id=payload.user_id, project_id=project_id, role=normalized_role.value) + member = ProjectMember( + user_id=payload.user_id, project_id=project_id, role=normalized_role.value, + additional_roles=extras or None, + ) db.add(member) + added: dict = {"role": normalized_role.value} + if extras: + added["additional_roles"] = extras await log_access_change(db, "member_added", current_user, target_user_id=payload.user_id, - project_id=project_id, after_value={"role": normalized_role.value}) + project_id=project_id, after_value=added) await db.commit() await db.refresh(member) @@ -772,7 +936,8 @@ async def update_project_member_role( """Update a project member's role. Requires QA_LEAD or higher.""" # Privilege-escalation guard: a non-admin cannot grant a project role above # their own, nor change their own membership role. - _enforce_grant_ceiling(current_user, payload.role, user_id) + _refuse_agent_role(payload.role) + granter_project_roles = await _enforce_member_grant(db, current_user, project_id, payload.role, user_id) result = await db.execute( select(ProjectMember, User) @@ -785,6 +950,17 @@ async def update_project_member_role( member, user = row refuse_erased(user) # W31 (an erased account's memberships are deleted; defence in depth) + # Extra roles: omitted keeps them (re-cleaned against the new primary role). Only a NEWLY added extra + # role passes the ceiling -- removing one lowers access and keeping one an admin gave is not a grant. + previous_extras = _stored_extras(getattr(member, "additional_roles", None)) + requested_extras = getattr(payload, "additional_roles", None) + wanted_extras = requested_extras if requested_extras is not None else previous_extras + new_extras = _clean_extras(wanted_extras, primary=payload.role) + _enforce_grant_ceiling( + current_user, payload.role, user_id, + additional_roles=[r for r in new_extras if r not in previous_extras], + granter_project_roles=granter_project_roles, + ) # Captured BEFORE the mutation: `member` is a live ORM object, so reading # `member.role` after the assignment would record the new value as the old # one and the audit row would show a change from X to X. @@ -792,15 +968,21 @@ async def update_project_member_role( # The UserRole member (a str enum: its value is the stored text), as the # column is typed and as update_user_role assigns User.role above. member.role = _normalize_user_role(payload.role) + member.additional_roles = new_extras or None logger.info("updating_project_member_role", project_id=str(project_id), user_id=str(user_id), before=previous_role, after=member.role, by=str(current_user.id)) # A privilege change inside a project was not audited at all, while the # grant beside it was. An admin could escalate a member to a higher project # role and the access trail showed only the original, lower grant. + before_value: dict = {"role": previous_role} + after_value: dict = {"role": member.role} + if previous_extras or new_extras: + before_value["additional_roles"] = previous_extras + after_value["additional_roles"] = new_extras await log_access_change(db, "member_role_changed", current_user, target_user_id=user_id, project_id=project_id, - before_value={"role": previous_role}, - after_value={"role": member.role}) + before_value=before_value, + after_value=after_value) await db.commit() await db.refresh(member) diff --git a/backend/app/routers/webhooks_outbound.py b/backend/app/routers/webhooks_outbound.py index 89dd918a7..ef89b16f2 100644 --- a/backend/app/routers/webhooks_outbound.py +++ b/backend/app/routers/webhooks_outbound.py @@ -32,8 +32,8 @@ from fastapi import APIRouter, Depends, HTTPException, Query, status from sqlalchemy.ext.asyncio import AsyncSession +from app.core.permissions import rank_index from app.core.deps import ( - _ROLE_ORDER, _normalize_user_role, get_accessible_project_ids, get_current_active_user, @@ -63,10 +63,10 @@ def _sees_full_target_url(user: User) -> bool: """QA_LEAD and above by instance role: the roles that manage subscriptions.""" try: - idx = _ROLE_ORDER.index(_normalize_user_role(user.role)) + idx = rank_index(_normalize_user_role(user.role)) except ValueError: return False - return idx >= _ROLE_ORDER.index(UserRole.QA_LEAD) + return idx >= rank_index(UserRole.QA_LEAD) def _mask_target_url(target_url: str) -> str: diff --git a/backend/app/services/agent_action_adapters/adapter_base.py b/backend/app/services/agent_action_adapters/adapter_base.py index 689e5a997..a3f223dc4 100644 --- a/backend/app/services/agent_action_adapters/adapter_base.py +++ b/backend/app/services/agent_action_adapters/adapter_base.py @@ -26,7 +26,8 @@ from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession -from app.core.deps import _ROLE_ORDER, _normalize_user_role +from app.core.deps import _normalize_user_role +from app.core.permissions import rank_index from app.models.postgres import ProjectMember, User, UserRole from app.services.agent_action_types import ( ACTION_ERROR_SENTENCES, @@ -165,10 +166,10 @@ async def load_approver( raise _refuse_approver() try: role = _normalize_user_role(approver.role) - rank = _ROLE_ORDER.index(role) + rank = rank_index(role) except ValueError: raise _refuse_approver() from None - if rank < _ROLE_ORDER.index(required_role): + if rank < rank_index(required_role): raise _refuse_approver() instance_admin = role == UserRole.ADMIN if instance_admin: @@ -184,10 +185,10 @@ async def load_approver( if member_role is None: raise _refuse_approver() try: - member_rank = _ROLE_ORDER.index(_normalize_user_role(member_role)) + member_rank = rank_index(_normalize_user_role(member_role)) except ValueError: raise _refuse_approver() from None - if member_rank < _ROLE_ORDER.index(required_role): + if member_rank < rank_index(required_role): raise _refuse_approver() return approver diff --git a/backend/app/services/feature_flags.py b/backend/app/services/feature_flags.py index a881197d2..aa6a426ea 100644 --- a/backend/app/services/feature_flags.py +++ b/backend/app/services/feature_flags.py @@ -171,8 +171,11 @@ def _evaluate( if enabled_roles: if user is None: return False - user_role = _normalize_role(user.role) - if user_role not in {str(r) for r in enabled_roles}: + # Enterprise roles D-16: an extra job role (``users.additional_roles``) counts like the primary role. + from app.core.permissions import job_roles_in + + held = {_normalize_role(user.role), *(r.value for r in job_roles_in(getattr(user, "additional_roles", None)))} + if not held & {str(r) for r in enabled_roles}: return False # Rollout percentage — deterministic by user or project to avoid diff --git a/backend/app/services/feedback_service.py b/backend/app/services/feedback_service.py index 86918db34..da93bc7ad 100644 --- a/backend/app/services/feedback_service.py +++ b/backend/app/services/feedback_service.py @@ -38,14 +38,15 @@ def _require_correction_role(body, current_user) -> None: """ if not _is_correction(body): return - from app.core.deps import _ROLE_ORDER, _normalize_user_role # noqa: PLC0415 + from app.core.deps import _normalize_user_role # noqa: PLC0415 + from app.core.permissions import rank_index # noqa: PLC0415 from app.models.postgres import UserRole # noqa: PLC0415 try: - idx = _ROLE_ORDER.index(_normalize_user_role(current_user.role)) + idx = rank_index(_normalize_user_role(current_user.role)) except ValueError: idx = -1 - if idx < _ROLE_ORDER.index(UserRole.QA_ENGINEER): + if idx < rank_index(UserRole.QA_ENGINEER): raise HTTPException( 403, detail="Correcting an AI analysis requires at least QA_ENGINEER role" ) diff --git a/backend/app/services/mfa_service.py b/backend/app/services/mfa_service.py index 52c5cf59e..e478967df 100644 --- a/backend/app/services/mfa_service.py +++ b/backend/app/services/mfa_service.py @@ -59,7 +59,8 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.core.config import settings -from app.core.deps import _normalize_user_role, _ROLE_ORDER +from app.core.deps import _normalize_user_role +from app.core.permissions import rank_index, user_roles from app.core.security import AuthenticationAssurance, hash_token from app.models.postgres import ( AppSetting, @@ -406,11 +407,16 @@ class MfaPolicy: lockout_enabled: bool = True lockout_threshold: int = 10 lockout_duration_minutes: int = 15 + # Enterprise roles E00-S05: roles that need MFA whatever the floor -- held as + # the primary role or an extra one. Applies only under a floor (no floor is + # already everyone). Enum order, never AGENT. + required_roles: tuple[str, ...] = () def as_dict(self) -> dict: return { "require_mfa": self.require_mfa, "required_for_role": self.required_for_role, + "required_roles": list(self.required_roles), "lockout_enabled": self.lockout_enabled, "lockout_threshold": self.lockout_threshold, "lockout_duration_minutes": self.lockout_duration_minutes, @@ -447,6 +453,7 @@ def policy_from_dict(raw: Optional[dict]) -> MfaPolicy: return MfaPolicy( require_mfa=bool(raw.get("require_mfa", DEFAULT_POLICY.require_mfa)), required_for_role=role, + required_roles=clean_required_roles(raw.get("required_roles")), lockout_enabled=bool(raw.get("lockout_enabled", DEFAULT_POLICY.lockout_enabled)), lockout_threshold=_coerce_int( raw.get("lockout_threshold"), DEFAULT_POLICY.lockout_threshold, 3, 100 @@ -480,6 +487,30 @@ async def save_policy( return policy +def clean_required_roles(values) -> tuple[str, ...]: + """``required_roles`` as stored: known roles but AGENT, enum order, no repeats; anything else dropped.""" + if not values or isinstance(values, (str, bytes)) or not hasattr(values, "__iter__"): + return () + wanted: set[UserRole] = set() + for value in values: + try: + role = _normalize_user_role(value) + except (ValueError, AttributeError): + continue + if role != UserRole.AGENT: + wanted.add(role) + return tuple(role.value for role in UserRole if role in wanted) + + +#: Job roles that sign and decide releases count as QA_LEAD for the MFA floor +#: (enterprise roles D-9); every other role counts as its rank. +_MFA_RANK_AS_QA_LEAD = frozenset({UserRole.RELEASE_MANAGER, UserRole.PRODUCT_MANAGER}) + + +def _mfa_rank(role: UserRole) -> int: + return rank_index(UserRole.QA_LEAD) if role in _MFA_RANK_AS_QA_LEAD else rank_index(role) + + def policy_requires_mfa(user: User, policy: MfaPolicy) -> bool: """Does the workspace policy require this user to hold a second factor?""" if not policy.require_mfa: @@ -487,8 +518,11 @@ def policy_requires_mfa(user: User, policy: MfaPolicy) -> bool: if policy.required_for_role is None: return True try: - floor = _ROLE_ORDER.index(UserRole(policy.required_for_role)) - actual = _ROLE_ORDER.index(_normalize_user_role(user.role)) + held = user_roles(user) + if any(role.value in policy.required_roles for role in held): + return True + floor = rank_index(UserRole(policy.required_for_role)) + actual = max(_mfa_rank(role) for role in held) except (ValueError, KeyError): # An unrecognised role on either side is not a licence to skip the # requirement — a role we cannot place in the hierarchy is treated as diff --git a/backend/app/services/project_data_job_service.py b/backend/app/services/project_data_job_service.py index 6771e68de..6fe746a28 100644 --- a/backend/app/services/project_data_job_service.py +++ b/backend/app/services/project_data_job_service.py @@ -26,8 +26,8 @@ from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession +from app.core.permissions import rank_index from app.core.deps import ( - _ROLE_ORDER, PROJECT_ADMIN_SCOPE, _api_key_bound_project, _normalize_user_role, @@ -533,7 +533,7 @@ async def mark_failed(db: AsyncSession, job_id: uuid.UUID, *, code: str, now: da def _role_index(user: User) -> int: try: - return _ROLE_ORDER.index(_normalize_user_role(user.role)) + return rank_index(_normalize_user_role(user.role)) except ValueError: return -1 @@ -548,8 +548,8 @@ async def may_read_job(db: AsyncSession, job: ProjectDataJob, user: User) -> boo return False role = _role_index(user) if job.kind == KIND_IMPORT: - return role == _ROLE_ORDER.index(UserRole.ADMIN) and job.requested_by_id == user.id - if job.kind != KIND_EXPORT or role < _ROLE_ORDER.index(UserRole.QA_LEAD): + return role == rank_index(UserRole.ADMIN) and job.requested_by_id == user.id + if job.kind != KIND_EXPORT or role < rank_index(UserRole.QA_LEAD): return False accessible = await get_accessible_project_ids(db, user) if accessible is None: # ADMIN: every project diff --git a/backend/app/services/project_import_service.py b/backend/app/services/project_import_service.py index 609a5b15e..c618f52fd 100644 --- a/backend/app/services/project_import_service.py +++ b/backend/app/services/project_import_service.py @@ -891,10 +891,10 @@ async def _map_people(db: AsyncSession, pre: _Preflight) -> dict[uuid.UUID, _Per def _role_rank(role: Any) -> int: """The shared role ranking (``app.core.deps._ROLE_ORDER``, the members router's ceiling rule): -1 when the value is not a role this deployment knows.""" - from app.core.deps import _ROLE_ORDER, _normalize_user_role + from app.core.permissions import rank_index try: - return _ROLE_ORDER.index(_normalize_user_role(role)) + return rank_index(role) except ValueError: return -1 @@ -1410,9 +1410,9 @@ def _reviewers(copy: Mapping[uuid.UUID, tuple[str, str, bool]]) -> set[uuid.UUID def _role_name(rank: int) -> str: """The role at ``rank`` of the shared ranking ("" for -1).""" - from app.core.deps import _ROLE_ORDER + from app.core.permissions import LADDER - return _ROLE_ORDER[rank].value if rank >= 0 else "" + return LADDER[rank].value if rank >= 0 else "" def _decide_reviews(ctx: _Context, pre: _Preflight, reviewers: set[uuid.UUID]) -> None: diff --git a/backend/app/services/scim_group_service.py b/backend/app/services/scim_group_service.py index 379b79253..6550822ed 100644 --- a/backend/app/services/scim_group_service.py +++ b/backend/app/services/scim_group_service.py @@ -3,7 +3,10 @@ A group pushed over SCIM ``/Groups`` holds members; an administrator maps the group to (project, project role) pairs. ``reconcile_user`` makes a user's SCIM-created memberships equal to what their groups grant: -* the highest role any of the user's groups maps to a project wins; ``source`` names that group (``scim:``); +* the highest rank any of the user's groups maps to a project wins; ``source`` names that group (``scim:``); +* a group mapped to a job role (RELEASE_MANAGER, PROJECT_MANAGER, PRODUCT_MANAGER, DEVELOPER) ADDS it to the + membership's ``additional_roles`` -- no precedence fight with the rank; leaving the group removes it. A project + only job-role groups grant gets VIEWER as its primary role (enterprise roles E00-S05); * a membership a person granted (``source IS NULL``) is never changed or removed — at most it is left alone; * a SCIM-created membership no group grants any more is removed; one whose grant changed is updated. @@ -18,19 +21,30 @@ from sqlalchemy import delete, select from sqlalchemy.ext.asyncio import AsyncSession +from app.core.permissions import EXTRA_ROLE_CHOICES, LADDER, job_roles_in, rank_index from app.models.postgres import ProjectMember, SCIMGroup, SCIMGroupMapping, SCIMGroupMember, UserRole SOURCE_PREFIX = "scim:" -_ORDER = [UserRole.VIEWER.value, UserRole.TESTER.value, UserRole.QA_ENGINEER.value, UserRole.QA_LEAD.value, UserRole.ADMIN.value] -PROJECT_ROLES = tuple(r for r in _ORDER if r != UserRole.ADMIN.value) +_ORDER = [role.value for role in LADDER] +#: Job roles a group may map to: they add an extra role, never the rank. +JOB_ROLES = tuple(role.value for role in EXTRA_ROLE_CHOICES) +#: Roles a group may map to: every rank but ADMIN, then the job roles. Never AGENT. +PROJECT_ROLES = tuple(r for r in _ORDER if r != UserRole.ADMIN.value) + JOB_ROLES + +#: (primary role, source, extra job roles in enum order) +Grant = tuple[str, str, tuple[str, ...]] def _rank(role: str) -> int: - return _ORDER.index(role) if role in _ORDER else -1 + return rank_index(role) if role in _ORDER else -1 + +async def desired_grants(db: AsyncSession, user_id: uuid.UUID) -> dict[uuid.UUID, Grant]: + """project id → (role, source, extra roles) the user's groups grant. -async def desired_grants(db: AsyncSession, user_id: uuid.UUID) -> dict[uuid.UUID, tuple[str, str]]: - """project id → (role, source) the user's groups grant (highest role wins; ties keep the first group by name).""" + The highest rank wins the primary role (ties keep the first group by name); every job role a group maps to + is an extra role. A project only job-role groups grant: VIEWER, with the first such group as the source. + """ rows = (await db.execute( select(SCIMGroupMapping.project_id, SCIMGroupMapping.project_role, SCIMGroup.display_name) .join(SCIMGroupMember, SCIMGroupMember.group_id == SCIMGroupMapping.group_id) @@ -38,14 +52,34 @@ async def desired_grants(db: AsyncSession, user_id: uuid.UUID) -> dict[uuid.UUID .where(SCIMGroupMember.user_id == user_id) .order_by(SCIMGroup.display_name) )).all() - out: dict[uuid.UUID, tuple[str, str]] = {} + ranked: dict[uuid.UUID, tuple[str, str]] = {} + extras: dict[uuid.UUID, dict[str, str]] = {} + seen: dict[uuid.UUID, None] = {} # projects in the order the groups (by name) first grant them for project_id, role, group_name in rows: - current = out.get(project_id) + seen.setdefault(project_id, None) + source = f"{SOURCE_PREFIX}{group_name}"[:80] + if role in JOB_ROLES: + extras.setdefault(project_id, {}).setdefault(role, source) + continue + current = ranked.get(project_id) if current is None or _rank(role) > _rank(current[0]): - out[project_id] = (role, f"{SOURCE_PREFIX}{group_name}"[:80]) + ranked[project_id] = (role, source) + out: dict[uuid.UUID, Grant] = {} + for project_id in seen: + job = extras.get(project_id, {}) + held = tuple(r for r in JOB_ROLES if r in job) + if project_id in ranked: + role, source = ranked[project_id] + else: + role, source = UserRole.VIEWER.value, job[held[0]] + out[project_id] = (role, source, held) return out +def _held_extras(member: ProjectMember) -> tuple[str, ...]: + return tuple(role.value for role in job_roles_in(getattr(member, "additional_roles", None))) + + async def reconcile_user(db: AsyncSession, user_id: uuid.UUID, changes: Optional[list] = None) -> dict[str, int]: """Make the user's SCIM-created memberships match their groups. Returns counts (added/updated/removed/kept); ``changes`` (when given) collects ``(event, project_id, user_id, role)`` per change for the activity ledger.""" @@ -66,14 +100,18 @@ async def reconcile_user(db: AsyncSession, user_id: uuid.UUID, changes: Optional log.append(("member.removed", member.project_id, user_id, member.role)) await db.delete(member) counts["removed"] += 1 - elif (member.role, member.source) != grant: - if member.role != grant[0]: + elif (member.role, member.source, _held_extras(member)) != grant: + if member.role != grant[0] or _held_extras(member) != grant[2]: log.append(("member.role_changed", member.project_id, user_id, grant[0])) member.role, member.source = UserRole(grant[0]), grant[1] + member.additional_roles = list(grant[2]) or None counts["updated"] += 1 - for project_id, (role, source) in want.items(): + for project_id, (role, source, held) in want.items(): if project_id not in seen: - db.add(ProjectMember(user_id=user_id, project_id=project_id, role=role, source=source)) + db.add(ProjectMember( + user_id=user_id, project_id=project_id, role=role, source=source, + additional_roles=list(held) or None, + )) log.append(("member.added", project_id, user_id, role)) counts["added"] += 1 await db.flush() diff --git a/backend/app/services/sso_service.py b/backend/app/services/sso_service.py index a9fcec862..027f4e2a4 100644 --- a/backend/app/services/sso_service.py +++ b/backend/app/services/sso_service.py @@ -28,6 +28,7 @@ from app.core.config import settings from app.core.security import get_password_hash +from app.core.permissions import EXTRA_ROLE_CHOICES, LADDER, job_roles_in, rank_index from app.models.postgres import ( FederatedIdentity, IdentityEvent, @@ -783,7 +784,17 @@ def validate_saml_issuer(parsed: dict, config: SSOConfiguration) -> None: # Role hierarchy for picking the highest match / applying the ceiling. -_ROLE_ORDER = [UserRole.VIEWER, UserRole.TESTER, UserRole.QA_ENGINEER, UserRole.QA_LEAD, UserRole.ADMIN] +# The five ranks (``permissions.LADDER``). SSO and SCIM provision a rank; job +# roles are added as extra roles, never as the primary role. +_ROLE_ORDER = list(LADDER) + + +def _ladder_index(role) -> int: + """Rank position of a ladder role; ``ValueError`` for anything else (a job role is not a rank).""" + role = role if isinstance(role, UserRole) else UserRole(role) + if role not in _ROLE_ORDER: + raise ValueError(f"{role.value} is not a rank") + return rank_index(role) def _provisioning_ceiling() -> UserRole: @@ -823,16 +834,22 @@ def resolve_role_from_groups( if mapped: try: role = UserRole(mapped) - idx = _ROLE_ORDER.index(role) + idx = _ladder_index(role) if idx > best_idx: best_idx = idx except (ValueError, KeyError): continue resolved = _ROLE_ORDER[best_idx] if best_idx >= 0 else default_role + if resolved not in _ROLE_ORDER: + logger.warning( + "IdP/SCIM default role %s is not a rank — provisioning VIEWER", getattr(resolved, "value", resolved), + ) + resolved = UserRole.VIEWER + ceiling = _provisioning_ceiling() try: - if _ROLE_ORDER.index(resolved) > _ROLE_ORDER.index(ceiling): + if _ladder_index(resolved) > _ladder_index(ceiling): logger.warning( "IdP/SCIM provisioning resolved role %s exceeds ceiling %s — clamping", resolved.value, ceiling.value, @@ -842,7 +859,7 @@ def resolve_role_from_groups( pass try: - if _ROLE_ORDER.index(resolved) >= _ROLE_ORDER.index(UserRole.QA_LEAD): + if _ladder_index(resolved) >= _ladder_index(UserRole.QA_LEAD): logger.warning( "IdP/SCIM provisioning granting elevated role %s (groups=%s)", resolved.value, groups, @@ -853,6 +870,33 @@ def resolve_role_from_groups( return resolved +def mapping_names_job_roles(role_mapping: dict | None) -> bool: + """Does the mapping give any group a job role? Only then does the IdP manage a user's extra roles.""" + return bool(job_roles_in(list((role_mapping or {}).values()))) + + +def resolve_additional_roles_from_groups(groups: list[str], role_mapping: dict | None) -> list[str]: + """Extra job roles the user's groups map to (enterprise roles E00-S05), in enum order. + + A group mapped to RELEASE_MANAGER / PROJECT_MANAGER / PRODUCT_MANAGER / + DEVELOPER adds that role beside the rank ``resolve_role_from_groups`` picks; + it never competes for the rank. AGENT and anything unknown are ignored. + """ + if not role_mapping or not groups: + return [] + mapped = [role_mapping.get(group) for group in groups] + return [role.value for role in job_roles_in([m for m in mapped if m])] + + +def _extra_role_sources(groups: list[str], role_mapping: dict | None) -> dict[str, list[str]]: + out: dict[str, list[str]] = {} + for group in groups: + held = job_roles_in([(role_mapping or {}).get(group)]) + if held: + out.setdefault(held[0].value, []).append(group) + return {role.value: out[role.value] for role in EXTRA_ROLE_CHOICES if role.value in out} + + def preview_role_from_groups( groups: list[str], role_mapping: dict | None, @@ -869,21 +913,24 @@ def preview_role_from_groups( if not mapped: continue try: - idx = _ROLE_ORDER.index(UserRole(mapped)) + idx = _ladder_index(UserRole(mapped)) except (ValueError, KeyError): continue matched.append(group) best_idx = max(best_idx, idx) unclamped = _ROLE_ORDER[best_idx] if best_idx >= 0 else default_role ceiling = _provisioning_ceiling() - clamped = unclamped in _ROLE_ORDER and _ROLE_ORDER.index(unclamped) > _ROLE_ORDER.index(ceiling) + clamped = unclamped in _ROLE_ORDER and _ladder_index(unclamped) > _ladder_index(ceiling) role = ceiling if clamped else unclamped + extra_sources = _extra_role_sources(groups, role_mapping) return { "role": role.value, "matched_groups": matched, "source": "mapping" if best_idx >= 0 else "default", "ceiling": ceiling.value, "clamped": clamped, + "additional_roles": list(extra_sources), + "additional_matched_groups": extra_sources, } @@ -1000,6 +1047,21 @@ async def jit_provision_or_link( detail={"old_role": str(old_role), "new_role": str(new_role), "groups": groups}, ip_address=ip_address, ) + # Extra job roles follow the IdP only when the mapping names a job role; otherwise an + # administrator manages them and a sign-in leaves them alone. + if mapping_names_job_roles(config.role_mapping): + old_extras = [r.value for r in job_roles_in(getattr(user, "additional_roles", None))] + new_extras = resolve_additional_roles_from_groups(groups, config.role_mapping) + if old_extras != new_extras: + user.additional_roles = new_extras or None + await _log_identity_event( + db, + IdentityEventType.ROLE_MAPPED, + user_id=user.id, + sso_config_id=config.id, + detail={"old_additional_roles": old_extras, "new_additional_roles": new_extras, "groups": groups}, + ip_address=ip_address, + ) else: # No link yet. Which existing account, if any, does this sign-in name? # OIDC: the e-mail claim. SAML: the NameID only. @@ -1070,6 +1132,7 @@ async def jit_provision_or_link( # SSO users get a random password they'll never use hashed_password=get_password_hash(secrets.token_urlsafe(32)), role=role, + additional_roles=resolve_additional_roles_from_groups(groups, config.role_mapping) or None, is_active=True, must_change_password=False, # SSO users don't need password reset ) diff --git a/backend/app/services/timeline_note_service.py b/backend/app/services/timeline_note_service.py index 600a8b579..5808a4b48 100644 --- a/backend/app/services/timeline_note_service.py +++ b/backend/app/services/timeline_note_service.py @@ -103,10 +103,11 @@ def note_label(text: str) -> str: def _at_least_qa_lead(actor: Any) -> bool: - from app.core.deps import _ROLE_ORDER, _normalize_user_role # noqa: PLC0415 + from app.core.deps import _normalize_user_role # noqa: PLC0415 + from app.core.permissions import rank_index # noqa: PLC0415 try: - return _ROLE_ORDER.index(_normalize_user_role(actor.role)) >= _ROLE_ORDER.index(UserRole.QA_LEAD) + return rank_index(_normalize_user_role(actor.role)) >= rank_index(UserRole.QA_LEAD) except (ValueError, AttributeError): return False diff --git a/backend/migrations/versions/0266_role_additional_roles.py b/backend/migrations/versions/0266_role_additional_roles.py new file mode 100644 index 000000000..c45f32b75 --- /dev/null +++ b/backend/migrations/versions/0266_role_additional_roles.py @@ -0,0 +1,81 @@ +"""Extra job roles on users and project memberships (enterprise roles, epic E00). + +* ``users.additional_roles`` -- nullable JSONB list of role names. +* ``project_members.additional_roles`` -- nullable JSONB list of role names. +* ``user_invitations.additional_roles`` -- nullable JSONB list: the extra roles + the invitee gets on accept (their per-project extra roles ride in the + existing ``project_memberships`` JSON, one ``additional_roles`` key per entry). + +A person's primary ``role`` stays the only source of their rank; these lists add +the permissions of job roles they also hold (RELEASE_MANAGER, PROJECT_MANAGER, +PRODUCT_MANAGER, DEVELOPER), so a tech lead can be QA_ENGINEER with +RELEASE_MANAGER on top. On a write into a project the instance roles and the +project roles intersect (``app/core/permissions.py``). NULL means none. Adding a +nullable column with no default is metadata-only on PostgreSQL; no index (the +lists are read with the row they belong to). + +The five new ``UserRole`` values (RELEASE_MANAGER, PROJECT_MANAGER, +PRODUCT_MANAGER, DEVELOPER, AGENT) need no schema change: the role columns are +``String(20)`` with no CHECK constraint (migration 0079 says why). + +The downgrade drops the three columns and first maps every stored new role value +back to VIEWER, in every role column, because code before this revision +serialises roles through the strict five-value enum and would answer 500 on any +other value. Role columns: ``users.role``, ``project_members.role``, +``user_invitations.role``, ``sso_configurations.default_role``, +``scim_group_mappings.project_role``; and the ``role`` of each entry of +``user_invitations.project_memberships`` (accepting an invitation writes it to +``project_members.role``), whose ``additional_roles`` keys are dropped. Values +in JSON settings (an SSO ``role_mapping``, the MFA policy's ``required_roles``, +a feature flag's ``enabled_roles``) need nothing: older code skips a role it +does not know. + +Revision ID: 0266 +Revises: 0265 +""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects.postgresql import JSONB + +revision = "0266" +down_revision = "0265" +branch_labels = None +depends_on = None + +COLUMN = "additional_roles" +TABLES = ("users", "project_members", "user_invitations") + +NEW_ROLES = ("RELEASE_MANAGER", "PROJECT_MANAGER", "PRODUCT_MANAGER", "DEVELOPER", "AGENT") +ROLE_COLUMNS = ( + ("users", "role"), + ("project_members", "role"), + ("user_invitations", "role"), + ("sso_configurations", "default_role"), + ("scim_group_mappings", "project_role"), +) + + +def upgrade() -> None: + for table in TABLES: + op.add_column(table, sa.Column(COLUMN, JSONB(), nullable=True)) + + +def downgrade() -> None: + new_roles = sa.bindparam("new_roles", value=list(NEW_ROLES), expanding=True) + for table, column in ROLE_COLUMNS: + op.execute( + sa.text(f"UPDATE {table} SET {column} = 'VIEWER' WHERE {column} IN :new_roles").bindparams(new_roles) + ) + op.execute( + sa.text( + "UPDATE user_invitations SET project_memberships = (" + " SELECT jsonb_agg(CASE WHEN elem->>'role' IN :new_roles" + " THEN jsonb_set(elem - 'additional_roles', '{role}', '\"VIEWER\"')" + " ELSE elem - 'additional_roles' END)" + " FROM jsonb_array_elements(project_memberships) AS elem)" + " WHERE project_memberships IS NOT NULL AND jsonb_typeof(project_memberships) = 'array'" + " AND jsonb_array_length(project_memberships) > 0" + ).bindparams(new_roles) + ) + for table in TABLES: + op.drop_column(table, COLUMN) diff --git a/backend/scripts/seed_data.py b/backend/scripts/seed_data.py index 0da8d24c9..0ae32fbf5 100644 --- a/backend/scripts/seed_data.py +++ b/backend/scripts/seed_data.py @@ -68,6 +68,8 @@ def _seed_password(username: str) -> str: {"email": "admin@testlookup.example.com", "username": "admin", "full_name": "Admin User", "password": _seed_password("admin"), "role": "ADMIN"}, {"email": "lead@testlookup.example.com", "username": "qa_lead", "full_name": "QA Lead", "password": _seed_password("qa_lead"), "role": "QA_LEAD"}, {"email": "sara@testlookup.example.com", "username": "eng_sara", "full_name": "Sara Engineer", "password": _seed_password("eng_sara"), "role": "QA_ENGINEER"}, + # Enterprise roles D-8: the TESTER rank too, for demo parity with seed_dev_data.py. + {"email": "tester@testlookup.example.com", "username": "tester", "full_name": "Tom Tester", "password": _seed_password("tester"), "role": "TESTER"}, {"email": "viewer@testlookup.example.com", "username": "viewer", "full_name": "Viewer Read-only", "password": _seed_password("viewer"), "role": "VIEWER"}, ] diff --git a/backend/scripts/seed_dev_data.py b/backend/scripts/seed_dev_data.py index d31158d44..ef98f70ea 100644 --- a/backend/scripts/seed_dev_data.py +++ b/backend/scripts/seed_dev_data.py @@ -91,6 +91,13 @@ {"email": "engineer@testlookup.dev", "username": "qa_engineer", "full_name": "QA Engineer", "password": secrets.token_urlsafe(20), "role": UserRole.QA_ENGINEER}, {"email": "tester@testlookup.dev", "username": "tester", "full_name": "Tester", "password": secrets.token_urlsafe(20), "role": UserRole.TESTER}, {"email": "viewer@testlookup.dev", "username": "viewer", "full_name": "Read-Only Viewer", "password": secrets.token_urlsafe(20), "role": UserRole.VIEWER}, + # Enterprise roles E00-S06: the four job roles (AGENT is registered, never seeded as a person). The + # developer also holds RELEASE_MANAGER as an extra role, so multi-job access is exercised in dev. + {"email": "release.manager@testlookup.dev", "username": "release_manager", "full_name": "Release Manager", "password": secrets.token_urlsafe(20), "role": UserRole.RELEASE_MANAGER}, + {"email": "project.manager@testlookup.dev", "username": "project_manager", "full_name": "Project Manager", "password": secrets.token_urlsafe(20), "role": UserRole.PROJECT_MANAGER}, + {"email": "product.manager@testlookup.dev", "username": "product_manager", "full_name": "Product Manager", "password": secrets.token_urlsafe(20), "role": UserRole.PRODUCT_MANAGER}, + {"email": "developer@testlookup.dev", "username": "developer", "full_name": "Developer", "password": secrets.token_urlsafe(20), "role": UserRole.DEVELOPER, + "additional_roles": [UserRole.RELEASE_MANAGER.value]}, ] PROJECTS = [ @@ -433,6 +440,7 @@ async def _seed_users(db: AsyncSession) -> dict[UserRole, User]: full_name=u["full_name"], hashed_password=get_password_hash(u["password"]), role=u["role"], + additional_roles=u.get("additional_roles") or None, is_active=True, must_change_password=False, ) @@ -466,7 +474,10 @@ async def _seed_projects(db: AsyncSession, users: dict[UserRole, User]) -> list[ # .value, never str(): str() of the enum is 'UserRole.QA_LEAD' on Python 3.11+, # which no membership check matches -- a seeded QA lead got 403 triaging their # own Inbox (the UX redesign's browser E2E pass; migration 0198 repairs rows). - db.add(ProjectMember(id=uuid.uuid4(), project_id=project.id, user_id=user.id, role=role_key.value)) + db.add(ProjectMember( + id=uuid.uuid4(), project_id=project.id, user_id=user.id, role=role_key.value, + additional_roles=getattr(user, "additional_roles", None) or None, + )) print(f" {p['name']} ({p['slug']})") await db.flush() return projects @@ -1197,7 +1208,7 @@ async def main(reset: bool = False, wipe_only: bool = False) -> None: print(f" {'Role':<16} {'Email':<28}") print(f" {'-'*16} {'-'*28}") for u in USERS: - print(f" {str(u['role']):<16} {u['email']:<28}") + print(f" {u['role'].value:<16} {u['email']:<28}") print() print(" Log in via the Quick Login buttons at http://localhost:3000") print(" (DEV_AUTO_LOGIN_ENABLED=true in .env allows role-based login") diff --git a/backend/tests/integration/test_invitations_postgres.py b/backend/tests/integration/test_invitations_postgres.py index 05ded0768..a84bc32e8 100644 --- a/backend/tests/integration/test_invitations_postgres.py +++ b/backend/tests/integration/test_invitations_postgres.py @@ -134,6 +134,37 @@ async def test_invite_stores_only_the_hash_and_links_by_fragment(world, caplog): assert raw not in caplog.text +async def test_extra_job_roles_ride_the_invitation_into_the_account_and_the_project(world): + """Enterprise roles E00-S05 (D-16): global and per-project extra roles survive invite → accept.""" + from app.models.postgres import ProjectMember, User, UserInvitation, UserRole + from app.models.schemas import InviteProjectMembership, InviteUserRequest + from app.routers.users import invite_user + + payload = InviteUserRequest( + email=f"new-{world['marker']}@testlookup.dev", + role=UserRole.QA_ENGINEER, + additional_roles=["RELEASE_MANAGER"], + project_memberships=[InviteProjectMembership( + project_id=world["project"].id, role=UserRole.QA_ENGINEER, additional_roles=["DEVELOPER"], + )], + ) + answer = await invite_user(payload, db=world["db"], current_user=world["admin"]) + assert answer.additional_roles == [UserRole.RELEASE_MANAGER] + db = world["db"] + row = (await db.execute(select(UserInvitation).where(UserInvitation.id == answer.id))).scalar_one() + assert row.additional_roles == ["RELEASE_MANAGER"] + assert row.project_memberships == [ + {"project_id": str(world["project"].id), "role": "QA_ENGINEER", "additional_roles": ["DEVELOPER"]}, + ] + + await _accept(world, _token(answer.invitation_link)) + db.expire_all() + user = (await db.execute(select(User).where(User.email == payload.email))).scalar_one() + assert user.additional_roles == ["RELEASE_MANAGER"] + member = (await db.execute(select(ProjectMember).where(ProjectMember.user_id == user.id))).scalar_one() + assert (member.role, member.additional_roles) == ("QA_ENGINEER", ["DEVELOPER"]) + + async def test_accept_creates_the_account_with_role_and_project_and_signs_in(world): from app.models.postgres import ProjectMember, User, UserInvitation from app.models.schemas import InvitationTokenRequest, TokenResponse diff --git a/backend/tests/integration/test_scim_groups_postgres.py b/backend/tests/integration/test_scim_groups_postgres.py index 9d523225c..82989ac70 100644 --- a/backend/tests/integration/test_scim_groups_postgres.py +++ b/backend/tests/integration/test_scim_groups_postgres.py @@ -163,6 +163,43 @@ async def test_the_highest_role_wins_and_deleting_a_group_removes_its_grant(worl assert u[3].id not in await _members(world, pay.id) and u[3].id not in await _members(world, gw.id) +async def test_a_job_role_group_adds_an_extra_role_and_leaving_it_removes_it(world): + """Enterprise roles E00-S05: a group mapped to a job role ADDS it to the membership's extra roles (the highest + rank still sets the role); a project only job-role groups grant gets VIEWER; leaving the group removes it; + AGENT and ADMIN are not mappable.""" + from app.models.postgres import ProjectMember + from app.routers.scim import scim_patch_group + + u, pay, gw = world.users, world.projects[0], world.projects[1] + qa = await _create(world, world.names[0], [u[3].id]) + release = await _create(world, world.names[1], [u[3].id]) + await _map(world, qa["id"], [(pay.id, "QA_ENGINEER")]) + await _map(world, release["id"], [(pay.id, "RELEASE_MANAGER"), (gw.id, "DEVELOPER")]) + + async def _row(project_id): + """(role, source, additional_roles) of u[3]'s membership, read at once (an expired row cannot lazy-load).""" + world.db.expire_all() + row = (await world.db.execute( + select(ProjectMember.role, ProjectMember.source, ProjectMember.additional_roles).where( + ProjectMember.project_id == project_id, ProjectMember.user_id == u[3].id, + ) + )).one_or_none() + return tuple(row) if row is not None else None + + assert await _row(pay.id) == ("QA_ENGINEER", f"scim:{world.names[0]}", ["RELEASE_MANAGER"]) + assert await _row(gw.id) == ("VIEWER", f"scim:{world.names[1]}", ["DEVELOPER"]) + + patch = {"Operations": [{"op": "remove", "path": f'members[value eq "{u[3].id}"]'}]} + await scim_patch_group(uuid.UUID(release["id"]), _Req(patch), scim_token=_TOKEN, db=world.db) + assert await _row(pay.id) == ("QA_ENGINEER", f"scim:{world.names[0]}", None) + assert await _row(gw.id) is None, "a project only the job-role group granted is removed with it" + + for bad in ("AGENT", "ADMIN"): + with pytest.raises(HTTPException) as exc: + await _map(world, qa["id"], [(pay.id, bad)]) + assert exc.value.status_code == 400 + + async def test_filter_conflict_and_unknown_member(world): from app.routers.scim import scim_list_groups diff --git a/backend/tests/regression/test_extra_roles_assignment.py b/backend/tests/regression/test_extra_roles_assignment.py new file mode 100644 index 000000000..976e5b3e1 --- /dev/null +++ b/backend/tests/regression/test_extra_roles_assignment.py @@ -0,0 +1,342 @@ +"""Extra job roles: who may set them, how they are stored and audited (enterprise roles E00-S05, D-16). + +* Users: only an ADMIN sets a person's global extra roles (PATCH /users/{id}); never their own; never on an + AGENT; a primary role is never also an extra role (re-cleaned when the primary role changes); every change + writes an ``additional_roles_changed`` access-audit row. +* Members: a non-admin may add an extra role on a membership only if they hold every permission of it IN THAT + PROJECT (their instance grants intersected with their project grants); the refusal names what they lack. The + release, project and product managers are given only by an administrator (owner decision D-17). + Omitted extra roles are kept, ``[]`` clears them, and only a newly added extra role is checked. +* Requests: an extra role is one of the four job roles; anything else is a 422 from the schema. +""" +from __future__ import annotations + +import uuid +from datetime import datetime, timezone +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import pytest +from fastapi import HTTPException +from pydantic import ValidationError + +from app.models.postgres import ProjectMember, UserRole +from app.models.schemas import ( + AddProjectMemberRequest, + AdminCreateUserRequest, + InviteProjectMembership, + InviteUserRequest, + UpdateProjectMemberRoleRequest, + UpdateUserProfileRequest, +) +from app.routers import users as users_router + +pytestmark = pytest.mark.regression + + +def _person(role, additional=None): + return SimpleNamespace( + id=uuid.uuid4(), role=role, additional_roles=additional, email="p@example.com", username="person", + full_name="Person", is_active=True, erased_at=None, is_service_account=False, is_synthetic=False, + created_at=datetime.now(timezone.utc), + ) + + +def _result(*, scalar=None, one=None): + r = MagicMock() + r.scalar_one_or_none.return_value = scalar + r.one_or_none.return_value = one + r.first.return_value = scalar + return r + + +@pytest.fixture +def audit(monkeypatch): + rows: list[tuple] = [] + + async def _log(db, action, actor, **kw): + rows.append((action, kw.get("before_value"), kw.get("after_value"))) + + monkeypatch.setattr(users_router, "log_access_change", _log) + return rows + + +# -- request schemas ----------------------------------------------------------- + +@pytest.mark.parametrize("bad", ["AGENT", "QA_LEAD", "ADMIN", "VIEWER", "SUPERUSER"]) +def test_an_extra_role_is_a_job_role_or_a_422(bad): + for model, kw in ( + (UpdateUserProfileRequest, {}), + (AdminCreateUserRequest, {"email": "a@example.com", "username": "abc"}), + (InviteUserRequest, {"email": "a@example.com"}), + (InviteProjectMembership, {"project_id": uuid.uuid4()}), + (AddProjectMemberRequest, {"user_id": uuid.uuid4()}), + (UpdateProjectMemberRoleRequest, {"role": "VIEWER"}), + ): + with pytest.raises(ValidationError): + model(additional_roles=[bad], **kw) + + +def test_the_four_job_roles_are_accepted(): + jobs = ["RELEASE_MANAGER", "PROJECT_MANAGER", "PRODUCT_MANAGER", "DEVELOPER"] + assert AddProjectMemberRequest(user_id=uuid.uuid4(), additional_roles=jobs).additional_roles == jobs + + +def test_omitted_extra_roles_are_none_on_an_update_and_empty_on_a_create(): + assert UpdateUserProfileRequest().additional_roles is None + assert UpdateProjectMemberRoleRequest(role="VIEWER").additional_roles is None + assert AddProjectMemberRequest(user_id=uuid.uuid4()).additional_roles == [] + + +# -- global extra roles -------------------------------------------------------- + +async def _patch_user(target, payload, actor=None): + db = AsyncMock() + db.execute = AsyncMock(return_value=_result(scalar=target)) + db.refresh = AsyncMock() + return await users_router.update_user_profile( + target.id, payload, db=db, current_user=actor or _person(UserRole.ADMIN), + ) + + +async def test_an_admin_sets_a_persons_extra_roles_and_it_is_audited(audit): + target = _person(UserRole.QA_ENGINEER) + await _patch_user(target, UpdateUserProfileRequest(additional_roles=["DEVELOPER", "RELEASE_MANAGER"])) + assert target.additional_roles == ["RELEASE_MANAGER", "DEVELOPER"] # enum order, not request order + assert audit == [("additional_roles_changed", {"additional_roles": []}, + {"additional_roles": ["RELEASE_MANAGER", "DEVELOPER"]})] + + +async def test_an_empty_list_clears_them_and_omitting_keeps_them(audit): + target = _person(UserRole.QA_ENGINEER, ["RELEASE_MANAGER"]) + await _patch_user(target, UpdateUserProfileRequest(full_name="Renamed")) + assert target.additional_roles == ["RELEASE_MANAGER"] and audit == [] + await _patch_user(target, UpdateUserProfileRequest(additional_roles=[])) + assert target.additional_roles is None + assert audit[-1][0] == "additional_roles_changed" + + +async def test_nobody_changes_their_own_extra_roles(audit): + admin = _person(UserRole.ADMIN) + with pytest.raises(HTTPException) as exc: + await _patch_user(admin, UpdateUserProfileRequest(additional_roles=["DEVELOPER"]), actor=admin) + assert exc.value.status_code == 400 + + +async def test_an_agent_holds_no_extra_roles(audit): + with pytest.raises(HTTPException) as exc: + await _patch_user(_person(UserRole.AGENT), UpdateUserProfileRequest(additional_roles=["DEVELOPER"])) + assert exc.value.status_code == 400 and "agent" in exc.value.detail.lower() + + +async def test_a_new_primary_role_drops_the_same_extra_role(audit, monkeypatch): + monkeypatch.setattr(users_router, "_assert_not_last_admin", AsyncMock()) + target = _person(UserRole.QA_ENGINEER, ["RELEASE_MANAGER", "DEVELOPER"]) + await _patch_user(target, UpdateUserProfileRequest(role=UserRole.DEVELOPER)) + assert target.role == UserRole.DEVELOPER and target.additional_roles == ["RELEASE_MANAGER"] + assert [row[0] for row in audit] == ["role_changed", "additional_roles_changed"] + + +async def test_admin_create_stores_the_extra_roles(monkeypatch): + added = [] + db = AsyncMock() + db.execute = AsyncMock(return_value=_result(scalar=None)) + db.add = MagicMock(side_effect=added.append) + + async def _refresh(obj): + obj.id, obj.created_at, obj.is_active = uuid.uuid4(), datetime.now(timezone.utc), True + + db.refresh = AsyncMock(side_effect=_refresh) + payload = AdminCreateUserRequest( + email="new@example.com", username="newbie", role=UserRole.DEVELOPER, + additional_roles=["DEVELOPER", "PRODUCT_MANAGER"], + ) + out = await users_router.admin_create_user(payload, db=db, current_user=_person(UserRole.ADMIN)) + assert added[0].additional_roles == ["PRODUCT_MANAGER"] # the primary role is not repeated + assert out.additional_roles == [UserRole.PRODUCT_MANAGER] + + +async def test_invite_memberships_carry_their_extra_roles(): + db = AsyncMock() + project = SimpleNamespace(id=uuid.uuid4(), is_active=True) + db.execute = AsyncMock(return_value=_result(scalar=project)) + payload = InviteUserRequest( + email="i@example.com", + additional_roles=["RELEASE_MANAGER"], + project_memberships=[ + InviteProjectMembership(project_id=project.id, role=UserRole.DEVELOPER, additional_roles=["DEVELOPER"]), + ], + ) + entries = await users_router._validated_invite_memberships(db, payload) + assert entries == [{"project_id": str(project.id), "role": "DEVELOPER"}] # nothing extra once de-duplicated + payload.project_memberships[0].additional_roles = ["PROJECT_MANAGER"] + entries = await users_router._validated_invite_memberships(db, payload) + assert entries[0]["additional_roles"] == ["PROJECT_MANAGER"] + + +# -- project members ------------------------------------------------------------ + +def test_a_lead_may_add_a_developer_extra_role_but_not_a_manager_one(): + lead = _person(UserRole.QA_LEAD) + users_router._enforce_grant_ceiling(lead, UserRole.QA_ENGINEER, uuid.uuid4(), additional_roles=["DEVELOPER"]) + for manager in ("RELEASE_MANAGER", "PROJECT_MANAGER", "PRODUCT_MANAGER"): + with pytest.raises(HTTPException) as exc: + users_router._enforce_grant_ceiling(lead, UserRole.QA_ENGINEER, uuid.uuid4(), additional_roles=[manager]) + assert exc.value.status_code == 403 + assert exc.value.detail == f"Only an administrator can give the {manager} role" + + +def test_a_mixed_refusal_names_both_reasons(): + with pytest.raises(HTTPException) as exc: + users_router._enforce_grant_ceiling( + _person(UserRole.QA_LEAD), UserRole.ADMIN, uuid.uuid4(), additional_roles=["PROJECT_MANAGER"], + ) + assert "ADMIN needs" in exc.value.detail and "PROJECT_MANAGER is given only by an administrator" in exc.value.detail + + +def test_the_project_role_caps_what_a_lead_hands_out_there(): + lead = _person(UserRole.QA_LEAD) + target = uuid.uuid4() + # Instance roles alone: may grant DEVELOPER. + users_router._enforce_grant_ceiling(lead, UserRole.DEVELOPER, target) + # In a project where they are only a TESTER, the intersection lacks quarantine.propose. + with pytest.raises(HTTPException) as exc: + users_router._enforce_grant_ceiling(lead, UserRole.DEVELOPER, target, granter_project_roles=(UserRole.TESTER,)) + assert "DEVELOPER needs" in exc.value.detail + users_router._enforce_grant_ceiling(lead, UserRole.DEVELOPER, target, granter_project_roles=(UserRole.QA_LEAD,)) + + +def test_a_long_list_of_missing_permissions_is_shortened(): + with pytest.raises(HTTPException) as exc: + users_router._enforce_grant_ceiling(_person(UserRole.TESTER), UserRole.ADMIN, uuid.uuid4()) + assert "ADMIN needs" in exc.value.detail and "more)" in exc.value.detail + + +async def test_adding_a_member_stores_and_audits_the_extra_roles(audit, monkeypatch): + monkeypatch.setattr("app.core.deps.invalidate_membership_cache", AsyncMock()) + added = [] + member_user = _person(UserRole.QA_ENGINEER) + db = AsyncMock() + db.execute = AsyncMock(side_effect=[ + _result(scalar=SimpleNamespace(id=uuid.uuid4())), # project + _result(scalar=member_user), # user + _result(scalar=None), # not yet a member + ]) + db.add = MagicMock(side_effect=added.append) + + async def _refresh(obj): + obj.id, obj.created_at = uuid.uuid4(), datetime.now(timezone.utc) + + db.refresh = AsyncMock(side_effect=_refresh) + payload = AddProjectMemberRequest(user_id=member_user.id, role=UserRole.QA_ENGINEER, additional_roles=["DEVELOPER"]) + out = await users_router.add_project_member( + project_id=uuid.uuid4(), payload=payload, db=db, current_user=_person(UserRole.ADMIN), + ) + member = next(obj for obj in added if isinstance(obj, ProjectMember)) + assert member.additional_roles == ["DEVELOPER"] and out.additional_roles == [UserRole.DEVELOPER] + assert audit == [("member_added", None, {"role": "QA_ENGINEER", "additional_roles": ["DEVELOPER"]})] + + +async def _update_member(member, payload, actor, granter_row=None): + member_user = _person(UserRole.QA_ENGINEER) + db = AsyncMock() + results = [] + if _role_name(actor.role) != "ADMIN": + results.append(_result(one=granter_row)) + results.append(_result(one=(member, member_user))) + db.execute = AsyncMock(side_effect=results) + + async def _refresh(obj): + obj.created_at = datetime.now(timezone.utc) + + db.refresh = AsyncMock(side_effect=_refresh) + return await users_router.update_project_member_role( + project_id=member.project_id, user_id=member.user_id, payload=payload, db=db, current_user=actor, + ) + + +def _role_name(role): + return getattr(role, "value", role) + + +def _member(role="QA_ENGINEER", extras=None): + return SimpleNamespace( + id=uuid.uuid4(), user_id=uuid.uuid4(), project_id=uuid.uuid4(), role=role, additional_roles=extras, + created_at=datetime.now(timezone.utc), source=None, + ) + + +async def test_updating_a_member_keeps_extra_roles_unless_told(audit, monkeypatch): + monkeypatch.setattr("app.core.deps.invalidate_membership_cache", AsyncMock()) + member = _member(extras=["DEVELOPER"]) + await _update_member(member, UpdateProjectMemberRoleRequest(role=UserRole.TESTER), _person(UserRole.ADMIN)) + assert member.additional_roles == ["DEVELOPER"] + await _update_member(member, UpdateProjectMemberRoleRequest(role=UserRole.TESTER, additional_roles=[]), + _person(UserRole.ADMIN)) + assert member.additional_roles is None + assert audit[-1] == ("member_role_changed", + {"role": UserRole.TESTER, "additional_roles": ["DEVELOPER"]}, + {"role": UserRole.TESTER, "additional_roles": []}) + + +async def test_a_lead_keeps_an_extra_role_an_admin_gave_but_cannot_add_one(audit, monkeypatch): + monkeypatch.setattr("app.core.deps.invalidate_membership_cache", AsyncMock()) + lead = _person(UserRole.QA_LEAD) + lead_row = ("QA_LEAD", None) + member = _member(extras=["RELEASE_MANAGER"]) # an admin gave it + # Changing the primary role and keeping RELEASE_MANAGER is not a grant of it. + await _update_member(member, UpdateProjectMemberRoleRequest(role=UserRole.TESTER), lead, lead_row) + assert member.role == UserRole.TESTER and member.additional_roles == ["RELEASE_MANAGER"] + # Adding a manager role to someone without it is a grant only an administrator makes (D-17). + plain = _member() + with pytest.raises(HTTPException) as exc: + await _update_member( + plain, + UpdateProjectMemberRoleRequest(role=UserRole.TESTER, additional_roles=["RELEASE_MANAGER", "PRODUCT_MANAGER"]), + lead, lead_row, + ) + assert exc.value.status_code == 403 + assert exc.value.detail == "Only an administrator can give the RELEASE_MANAGER, PRODUCT_MANAGER role" + # DEVELOPER is inside the lead's own permissions. + await _update_member( + plain, UpdateProjectMemberRoleRequest(role=UserRole.TESTER, additional_roles=["DEVELOPER"]), lead, lead_row, + ) + assert plain.additional_roles == ["DEVELOPER"] + + +async def test_the_route_caps_a_lead_by_their_role_in_that_project(audit, monkeypatch): + """A QA lead globally who is only a TESTER in this project cannot hand out DEVELOPER here (D-2: the lower + of the two decides); as a QA lead in the project too, they can.""" + monkeypatch.setattr("app.core.deps.invalidate_membership_cache", AsyncMock()) + lead = _person(UserRole.QA_LEAD) + payload = UpdateProjectMemberRoleRequest(role=UserRole.TESTER, additional_roles=["DEVELOPER"]) + with pytest.raises(HTTPException) as exc: + await _update_member(_member(), payload, lead, granter_row=("TESTER", None)) + assert exc.value.status_code == 403 and "DEVELOPER needs" in exc.value.detail + member = _member() + await _update_member(member, payload, lead, granter_row=("QA_LEAD", None)) + assert member.additional_roles == ["DEVELOPER"] + + +async def test_adding_a_member_is_capped_by_the_granters_project_role(audit, monkeypatch): + """The add route applies the same cap: a QA lead who is only a TESTER in this project cannot add DEVELOPER.""" + monkeypatch.setattr("app.core.deps.invalidate_membership_cache", AsyncMock()) + lead = _person(UserRole.QA_LEAD) + target = _person(UserRole.QA_ENGINEER) + db = AsyncMock() + db.execute = AsyncMock(side_effect=[ + _result(scalar=SimpleNamespace(id=uuid.uuid4())), # project + _result(scalar=target), # user + _result(one=("TESTER", None)), # the granter's membership in this project + ]) + payload = AddProjectMemberRequest(user_id=target.id, role=UserRole.TESTER, additional_roles=["DEVELOPER"]) + with pytest.raises(HTTPException) as exc: + await users_router.add_project_member(project_id=uuid.uuid4(), payload=payload, db=db, current_user=lead) + assert exc.value.status_code == 403 and "DEVELOPER needs" in exc.value.detail + assert audit == [] + + +async def test_a_member_route_never_grants_agent(): + with pytest.raises(HTTPException) as exc: + await _update_member(_member(), UpdateProjectMemberRoleRequest(role=UserRole.AGENT), _person(UserRole.ADMIN)) + assert exc.value.status_code == 400 diff --git a/backend/tests/regression/test_job_role_assignment_and_mfa.py b/backend/tests/regression/test_job_role_assignment_and_mfa.py new file mode 100644 index 000000000..4e1afc8a1 --- /dev/null +++ b/backend/tests/regression/test_job_role_assignment_and_mfa.py @@ -0,0 +1,119 @@ +"""Assigning the new roles, and the MFA floor for them (enterprise roles E00-S05). + +* Grant ceiling: a non-admin may grant a project role only if they hold every + permission of it (``permissions.can_grant``). For two ladder roles that is the + old "not above your own rank"; a QA lead may hand out DEVELOPER. The release, + project and product managers are given only by an administrator (owner + decision D-17), and nobody grants AGENT through the members routes. +* MFA (owner decision D-9): RELEASE_MANAGER and PRODUCT_MANAGER sign and decide + releases, so a policy that requires MFA from QA_LEAD up covers them, as a + primary role or an extra one. Other job roles count as their rank, VIEWER. +""" +from __future__ import annotations + +import uuid +from types import SimpleNamespace + +import pytest +from fastapi import HTTPException + +from app.models.postgres import UserRole +from app.routers.users import _enforce_grant_ceiling +from app.services.mfa_service import MfaPolicy, policy_requires_mfa + +pytestmark = pytest.mark.regression + + +def _user(role, additional=None): + return SimpleNamespace(id=uuid.uuid4(), role=role, additional_roles=additional) + + +@pytest.mark.parametrize("target", [UserRole.DEVELOPER, UserRole.TESTER, UserRole.QA_ENGINEER, UserRole.VIEWER]) +def test_a_qa_lead_may_grant_roles_inside_their_own_permissions(target): + _enforce_grant_ceiling(_user(UserRole.QA_LEAD), target, uuid.uuid4()) # no raise + + +@pytest.mark.parametrize("target", [UserRole.RELEASE_MANAGER, UserRole.PROJECT_MANAGER, UserRole.PRODUCT_MANAGER, + UserRole.ADMIN]) +def test_a_qa_lead_may_not_grant_these(target): + with pytest.raises(HTTPException) as exc: + _enforce_grant_ceiling(_user(UserRole.QA_LEAD), target, uuid.uuid4()) + assert exc.value.status_code == 403 + + +@pytest.mark.parametrize("target", [UserRole.RELEASE_MANAGER, UserRole.PROJECT_MANAGER, UserRole.PRODUCT_MANAGER]) +def test_the_manager_roles_are_given_only_by_an_administrator(target): + """D-17: whatever the granter holds (a QA lead holds every PROJECT_MANAGER / PRODUCT_MANAGER permission).""" + with pytest.raises(HTTPException) as exc: + _enforce_grant_ceiling(_user(UserRole.QA_LEAD), target, uuid.uuid4()) + assert exc.value.detail == f"Only an administrator can give the {target.value} role" + _enforce_grant_ceiling(_user(UserRole.ADMIN), target, uuid.uuid4()) # no raise + + +def test_agent_is_never_granted_through_the_members_routes(): + for granter in (UserRole.QA_LEAD, UserRole.ADMIN): + with pytest.raises(HTTPException) as exc: + _enforce_grant_ceiling(_user(granter), UserRole.AGENT, uuid.uuid4()) + assert exc.value.status_code == 400 + + +def test_a_qa_engineer_may_not_grant_developer(): + with pytest.raises(HTTPException): + _enforce_grant_ceiling(_user(UserRole.QA_ENGINEER), UserRole.DEVELOPER, uuid.uuid4()) + + +def test_a_release_manager_may_not_grant_a_qa_lead(): + with pytest.raises(HTTPException): + _enforce_grant_ceiling(_user(UserRole.RELEASE_MANAGER), UserRole.QA_LEAD, uuid.uuid4()) + + +def test_holding_a_manager_role_does_not_let_a_lead_give_it(): + # D-17: a QA lead who is also a release manager holds every RM permission, and still may not hand it out. + lead_and_rm = _user(UserRole.QA_LEAD, additional=["RELEASE_MANAGER"]) + with pytest.raises(HTTPException) as exc: + _enforce_grant_ceiling(lead_and_rm, UserRole.RELEASE_MANAGER, uuid.uuid4()) + assert "Only an administrator" in exc.value.detail + + +def test_admin_grants_every_role_except_agent(): + for role in list(UserRole): + if role is not UserRole.AGENT: + _enforce_grant_ceiling(_user(UserRole.ADMIN), role, uuid.uuid4()) + with pytest.raises(HTTPException) as exc: + _enforce_grant_ceiling(_user(UserRole.ADMIN), UserRole.AGENT, uuid.uuid4()) + assert exc.value.status_code == 400 and "agent registration" in exc.value.detail + + +def test_nobody_changes_their_own_project_role(): + lead = _user(UserRole.QA_LEAD) + with pytest.raises(HTTPException): + _enforce_grant_ceiling(lead, UserRole.DEVELOPER, lead.id) + + +# -- MFA --------------------------------------------------------------------- + +LEAD_UP = MfaPolicy(require_mfa=True, required_for_role="QA_LEAD") + + +@pytest.mark.parametrize("role,required", [ + ("RELEASE_MANAGER", True), ("PRODUCT_MANAGER", True), + ("PROJECT_MANAGER", False), ("DEVELOPER", False), ("AGENT", False), + ("QA_LEAD", True), ("ADMIN", True), ("QA_ENGINEER", False), ("VIEWER", False), +]) +def test_mfa_from_qa_lead_up_covers_the_release_deciders(role, required): + assert policy_requires_mfa(_user(role), LEAD_UP) is required + + +def test_an_extra_release_role_brings_the_mfa_requirement(): + assert policy_requires_mfa(_user("QA_ENGINEER", additional=["PRODUCT_MANAGER"]), LEAD_UP) is True + assert policy_requires_mfa(_user("QA_ENGINEER", additional=["DEVELOPER"]), LEAD_UP) is False + + +def test_a_viewer_floor_still_means_everyone(): + everyone = MfaPolicy(require_mfa=True, required_for_role="VIEWER") + for role in list(UserRole): + assert policy_requires_mfa(_user(role.value), everyone) is True, role + + +def test_an_unknown_role_is_still_in_scope(): + assert policy_requires_mfa(_user("SUPERUSER"), LEAD_UP) is True diff --git a/backend/tests/regression/test_job_roles_through_sso_scim_mfa_flags.py b/backend/tests/regression/test_job_roles_through_sso_scim_mfa_flags.py new file mode 100644 index 000000000..dd79c4f2c --- /dev/null +++ b/backend/tests/regression/test_job_roles_through_sso_scim_mfa_flags.py @@ -0,0 +1,246 @@ +"""Job roles through SSO, SCIM, the MFA policy, feature flags and dev-login (enterprise roles E00-S05/S06). + +* SSO: a group mapped to a job role ADDS it as an extra role beside the rank the groups resolve to; the IdP + manages extra roles only when its mapping names a job role. ``default_role`` stays a rank; AGENT is never + mappable. +* SCIM groups: the highest rank wins the membership's role; job-role groups add extra roles, and leaving the + group removes them. A project only job-role groups grant gets VIEWER as its role. +* MFA: ``required_roles`` require MFA whatever the floor; the floor must be a rank. +* Feature flags: an extra role passes a role allow-list. +* Dev-login: every slug has defaults; AGENT is not a slug. +""" +from __future__ import annotations + +import uuid +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest +from fastapi import HTTPException + +from app.models.postgres import UserRole +from app.services import scim_group_service as sgs +from app.services import sso_service +from app.services.mfa_service import MfaPolicy, clean_required_roles, policy_from_dict, policy_requires_mfa + +pytestmark = pytest.mark.regression + +MAPPING = {"qa": "QA_ENGINEER", "leads": "QA_LEAD", "release": "RELEASE_MANAGER", "devs": "DEVELOPER", + "bots": "AGENT"} + + +# -- SSO ---------------------------------------------------------------------- + +def test_job_role_groups_add_extra_roles_and_never_the_rank(): + groups = ["qa", "release", "devs", "bots"] + assert sso_service.resolve_role_from_groups(groups, MAPPING, UserRole.VIEWER) == UserRole.QA_ENGINEER + assert sso_service.resolve_additional_roles_from_groups(groups, MAPPING) == ["RELEASE_MANAGER", "DEVELOPER"] + + +def test_only_job_role_groups_resolve_to_the_default_rank(): + assert sso_service.resolve_role_from_groups(["release"], MAPPING, UserRole.TESTER) == UserRole.TESTER + assert sso_service.resolve_additional_roles_from_groups(["release"], MAPPING) == ["RELEASE_MANAGER"] + + +def test_the_idp_manages_extra_roles_only_when_the_mapping_names_one(): + assert sso_service.mapping_names_job_roles(MAPPING) is True + assert sso_service.mapping_names_job_roles({"qa": "QA_ENGINEER", "bots": "AGENT"}) is False + assert sso_service.mapping_names_job_roles(None) is False + + +def test_the_preview_names_extra_roles_and_their_groups(): + out = sso_service.preview_role_from_groups(["qa", "release", "devs", "devs2"], {**MAPPING, "devs2": "DEVELOPER"}, + UserRole.VIEWER) + assert out["role"] == "QA_ENGINEER" + assert out["additional_roles"] == ["RELEASE_MANAGER", "DEVELOPER"] + assert out["additional_matched_groups"] == {"RELEASE_MANAGER": ["release"], "DEVELOPER": ["devs", "devs2"]} + + +async def test_the_preview_route_accepts_job_roles_but_not_agent_or_a_job_default(monkeypatch): + from app.models.schemas import SSORolePreviewRequest + from app.routers import sso + + config = SimpleNamespace(role_mapping={}, default_role="VIEWER") + db = MagicMock() + + async def _execute(*_a, **_k): + r = MagicMock() + r.scalar_one_or_none.return_value = config + return r + + db.execute = _execute + call = sso.preview_sso_role + ok = await call(uuid.uuid4(), SSORolePreviewRequest(groups=["release"], role_mapping={"release": "RELEASE_MANAGER"}), + db=db, current_user=None) + assert ok["additional_roles"] == ["RELEASE_MANAGER"] + for bad in ({"role_mapping": {"bots": "AGENT"}}, {"default_role": "DEVELOPER"}): + with pytest.raises(HTTPException) as exc: + await call(uuid.uuid4(), SSORolePreviewRequest(groups=["x"], **bad), db=db, current_user=None) + assert exc.value.status_code == 400 + + +def test_sso_mappable_roles_are_the_ranks_then_the_job_roles(): + from app.routers.sso import _MAPPABLE_ROLES + + assert _MAPPABLE_ROLES == ("VIEWER", "TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN", + "RELEASE_MANAGER", "PROJECT_MANAGER", "PRODUCT_MANAGER", "DEVELOPER") + + +# -- SCIM groups ----------------------------------------------------------------- + +class _Rows: + def __init__(self, rows): + self._rows = rows + + def all(self): + return self._rows + + +class _Db: + def __init__(self, rows): + self.rows = rows + + async def execute(self, *_a, **_k): + return _Rows(self.rows) + + +async def test_scim_job_role_groups_add_extra_roles_beside_the_highest_rank(): + p1, p2 = uuid.uuid4(), uuid.uuid4() + rows = [ # ordered by group name, as the query orders them + (p1, "DEVELOPER", "a-devs"), + (p1, "QA_ENGINEER", "b-qa"), + (p1, "RELEASE_MANAGER", "c-release"), + (p1, "TESTER", "d-testers"), + (p2, "PRODUCT_MANAGER", "e-product"), + ] + grants = await sgs.desired_grants(_Db(rows), uuid.uuid4()) + assert grants[p1] == ("QA_ENGINEER", "scim:b-qa", ("RELEASE_MANAGER", "DEVELOPER")) + assert grants[p2] == ("VIEWER", "scim:e-product", ("PRODUCT_MANAGER",)) + + +def test_scim_groups_map_to_ranks_below_admin_and_the_job_roles(): + assert sgs.PROJECT_ROLES == ("VIEWER", "TESTER", "QA_ENGINEER", "QA_LEAD", + "RELEASE_MANAGER", "PROJECT_MANAGER", "PRODUCT_MANAGER", "DEVELOPER") + assert "AGENT" not in sgs.PROJECT_ROLES and "ADMIN" not in sgs.PROJECT_ROLES + + +async def test_scim_reconcile_adds_and_removes_extra_roles(monkeypatch): + user_id, project = uuid.uuid4(), uuid.uuid4() + member = SimpleNamespace(project_id=project, role="QA_ENGINEER", source="scim:b-qa", additional_roles=None) + + class _Session: + def __init__(self): + self.added, self.deleted = [], [] + + async def execute(self, *_a, **_k): + r = MagicMock() + r.scalars.return_value.all.return_value = [member] + return r + + def add(self, obj): + self.added.append(obj) + + async def delete(self, obj): + self.deleted.append(obj) + + async def flush(self): + pass + + want = {project: ("QA_ENGINEER", "scim:b-qa", ("RELEASE_MANAGER",))} + + async def _desired(db, uid): + return want + + monkeypatch.setattr(sgs, "desired_grants", _desired) + changes: list = [] + counts = await sgs.reconcile_user(_Session(), user_id, changes) + assert member.additional_roles == ["RELEASE_MANAGER"] and counts["updated"] == 1 + assert changes == [("member.role_changed", project, user_id, "QA_ENGINEER")] + want[project] = ("QA_ENGINEER", "scim:b-qa", ()) # left the release group + await sgs.reconcile_user(_Session(), user_id) + assert member.additional_roles is None + + +# -- MFA ----------------------------------------------------------------------- + +def _person(role, additional=None): + return SimpleNamespace(id=uuid.uuid4(), role=role, additional_roles=additional) + + +def test_required_roles_need_mfa_whatever_the_floor(): + policy = MfaPolicy(require_mfa=True, required_for_role="ADMIN", required_roles=("DEVELOPER",)) + assert policy_requires_mfa(_person("DEVELOPER"), policy) is True + assert policy_requires_mfa(_person("QA_ENGINEER", ["DEVELOPER"]), policy) is True + assert policy_requires_mfa(_person("QA_LEAD"), policy) is False + assert policy_requires_mfa(_person("ADMIN"), policy) is True + + +def test_required_roles_are_cleaned_when_read(): + assert clean_required_roles(["DEVELOPER", "AGENT", "nope", "QA_LEAD", "DEVELOPER"]) == ("QA_LEAD", "DEVELOPER") + assert clean_required_roles("DEVELOPER") == () + stored = policy_from_dict({"require_mfa": True, "required_for_role": "QA_LEAD", "required_roles": ["DEVELOPER"]}) + assert stored.required_roles == ("DEVELOPER",) + assert policy_from_dict({"require_mfa": True}).required_roles == () + assert stored.as_dict()["required_roles"] == ["DEVELOPER"] + + +async def test_the_policy_route_refuses_a_job_role_floor_and_agent(monkeypatch): + from app.models.schemas import MfaPolicyUpdate + from app.routers import app_settings + from app.services import mfa_service + + async def _load(db): + return MfaPolicy() + + monkeypatch.setattr(mfa_service, "load_policy", _load) + for payload in (MfaPolicyUpdate(required_for_role=UserRole.RELEASE_MANAGER), + MfaPolicyUpdate(required_roles=[UserRole.AGENT])): + with pytest.raises(HTTPException) as exc: + await app_settings.update_mfa_policy(payload, current_user=_person(UserRole.ADMIN), db=MagicMock()) + assert exc.value.status_code == 400 + + +# -- feature flags ------------------------------------------------------------- + +def test_an_extra_role_passes_a_role_allow_list(): + from app.services.feature_flags import _evaluate + + flag = {"key": "x", "enabled_global": True, "enabled_roles": ["RELEASE_MANAGER"], "rollout_percent": 100} + assert _evaluate(flag, user=_person("QA_ENGINEER", ["RELEASE_MANAGER"]), project_id=None) is True + assert _evaluate(flag, user=_person("QA_ENGINEER"), project_id=None) is False + assert _evaluate(flag, user=_person("RELEASE_MANAGER"), project_id=None) is True + + +# -- dev-login ----------------------------------------------------------------- + +def test_every_dev_login_slug_has_defaults_and_agent_is_not_one(): + from app.routers.auth import _DEV_ROLE_DEFAULTS, _DEV_ROLE_MAP + + assert set(_DEV_ROLE_MAP.values()) == set(_DEV_ROLE_DEFAULTS) + assert set(_DEV_ROLE_MAP.values()) == {r for r in list(UserRole) if r is not UserRole.AGENT} + for defaults in _DEV_ROLE_DEFAULTS.values(): + assert defaults["email"].endswith("@testlookup.dev") + + +def test_the_dev_seed_has_every_role_but_agent_and_one_multi_job_person(): + import importlib.util + from pathlib import Path + + path = Path(__file__).resolve().parents[2] / "scripts" / "seed_dev_data.py" + source = path.read_text(encoding="utf-8") + for role in list(UserRole): + if role is UserRole.AGENT: + assert "UserRole.AGENT" not in source + else: + assert f'"role": UserRole.{role.name}' in source, role + assert '"additional_roles": [UserRole.RELEASE_MANAGER.value]' in source + assert importlib.util.find_spec("app") is not None + + +def test_the_demo_seed_has_all_five_ranks(): + """D-8: scripts/seed_data.py seeds a TESTER too (never run it on the homelab: it resets these passwords).""" + from pathlib import Path + + source = (Path(__file__).resolve().parents[2] / "scripts" / "seed_data.py").read_text(encoding="utf-8") + for rank in ("ADMIN", "QA_LEAD", "QA_ENGINEER", "TESTER", "VIEWER"): + assert f'"role": "{rank}"' in source, rank diff --git a/backend/tests/regression/test_migration_0266_additional_roles.py b/backend/tests/regression/test_migration_0266_additional_roles.py new file mode 100644 index 000000000..5e606e6de --- /dev/null +++ b/backend/tests/regression/test_migration_0266_additional_roles.py @@ -0,0 +1,58 @@ +"""Migration 0266 (enterprise roles E00): extra job roles, and a downgrade older code can read. + +Upgrade adds a nullable JSONB ``additional_roles`` to users, project_members and user_invitations. Downgrade +maps every new role value back to VIEWER in every place older code reads a role through its five-value enum -- +including SCIM group mappings and the per-project entries of a pending invitation -- then drops the columns. +""" +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import pytest + +pytestmark = pytest.mark.regression + +MIGRATION = Path(__file__).resolve().parents[2] / "migrations" / "versions" / "0266_role_additional_roles.py" +NEW_ROLES = ["RELEASE_MANAGER", "PROJECT_MANAGER", "PRODUCT_MANAGER", "DEVELOPER", "AGENT"] + + +def _load(): + spec = importlib.util.spec_from_file_location("migration_0266", MIGRATION) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_0266_follows_0265(): + module = _load() + assert (module.revision, module.down_revision) == ("0266", "0265") + + +def test_upgrade_adds_a_nullable_column_to_three_tables(monkeypatch): + from alembic import op + + added: list = [] + monkeypatch.setattr(op, "add_column", lambda table, column: added.append((table, column)), raising=False) + _load().upgrade() + assert [table for table, _ in added] == ["users", "project_members", "user_invitations"] + assert all(col.name == "additional_roles" and col.nullable for _, col in added) + + +def test_downgrade_maps_new_roles_to_viewer_everywhere_then_drops_the_columns(monkeypatch): + from alembic import op + + sent: list = [] + dropped: list = [] + monkeypatch.setattr(op, "execute", sent.append, raising=False) + monkeypatch.setattr(op, "drop_column", lambda table, column: dropped.append((table, column)), raising=False) + _load().downgrade() + sql = [str(stmt) for stmt in sent] + for table, column in (("users", "role"), ("project_members", "role"), ("user_invitations", "role"), + ("sso_configurations", "default_role"), ("scim_group_mappings", "project_role")): + assert any(f"UPDATE {table} SET {column} = 'VIEWER'" in s for s in sql), (table, column) + invites = next(s for s in sql if "project_memberships" in s) + assert "jsonb_set" in invites and "- 'additional_roles'" in invites + for stmt in sent: + assert stmt.compile().params.get("new_roles") == NEW_ROLES + assert dropped == [(t, "additional_roles") for t in ("users", "project_members", "user_invitations")] diff --git a/backend/tests/regression/test_permission_guards_hold_both_roles.py b/backend/tests/regression/test_permission_guards_hold_both_roles.py new file mode 100644 index 000000000..60dc84402 --- /dev/null +++ b/backend/tests/regression/test_permission_guards_hold_both_roles.py @@ -0,0 +1,330 @@ +"""A permission guard admits job roles, and a write still needs it in THAT project. + +Enterprise roles E00-S03. ``require_permission(P)`` is a ``require_role`` guard +whose floor comes from the catalogue: the five ladder roles are answered by rank +as before, and the job roles that hold ``P`` are admitted too. The 2026-11-18 +rule carries over (owner decision D-2): on a write, the caller's instance +permissions and their permissions in the project INTERSECT, so a person's +global role is their job and their project role caps it. Extra job roles +(``additional_roles``, D-16) add permissions without adding rank. + +Like ``test_project_writes_need_the_role_in_that_project.py``, this drives a +small app built from the real dependencies against a fake session. +""" +from __future__ import annotations + +import uuid +from types import SimpleNamespace + +import pytest +from fastapi import Depends, FastAPI +from fastapi.testclient import TestClient + +from app.core import deps +from app.core.deps import ( + get_accessible_project_ids, + get_current_user_or_api_key, + require_permission, + require_project_access, + require_project_role, + require_release_access, + require_role, +) +from app.core.permissions import Permission +from app.db.postgres import get_db +from app.models.postgres import UserRole + +pytestmark = pytest.mark.regression + +PROJECT = uuid.UUID("11111111-1111-4111-8111-111111111111") +OTHER = uuid.UUID("22222222-2222-4222-8222-222222222222") +RELEASE = uuid.UUID("44444444-4444-4444-8444-444444444444") + +Membership = tuple[str, list[str] | None] + + +class _Result: + def __init__(self, scalar=None, rows=None): + self._scalar, self._rows = scalar, rows or [] + + def scalar_one_or_none(self): + return self._scalar + + def all(self): + return self._rows + + def one_or_none(self): + return self._rows[0] if self._rows else None + + +class _Db: + """Answers the guards' membership lookups from ``project id -> (role, additional_roles)``.""" + + def __init__(self, memberships: dict[uuid.UUID, Membership]): + self.memberships = memberships + + async def execute(self, stmt): + compiled = stmt.compile() + sql, params = str(compiled), compiled.params + selected = sql.split("FROM", 1)[0] + + def bound(prefix): + return next((v for k, v in params.items() if k.startswith(prefix)), None) + + if "FROM releases" in sql: + return _Result(scalar=PROJECT) + if "FROM project_members" not in sql: + raise AssertionError(f"unexpected statement: {sql}") + wants_role = "project_members.role" in selected + wants_extra = "project_members.additional_roles" in selected + wants_id = "project_members.id" in selected + project = bound("project_id") + if project is None: # every project of the caller + if wants_extra: + return _Result(rows=[(pid, role, extra) for pid, (role, extra) in self.memberships.items()]) + wanted = bound("role") + return _Result(rows=[(pid,) for pid, (role, _) in self.memberships.items() + if wanted is None or role in wanted]) + member = self.memberships.get(project) + if member is None: + return _Result() + role, extra = member + if wants_role and wants_id: # the whole row + return _Result(scalar=SimpleNamespace(role=role, additional_roles=extra)) + if wants_role and wants_extra: + return _Result(rows=[(role, extra)]) + return _Result(scalar=role if wants_role else uuid.uuid4()) + + +def _app() -> FastAPI: + app = FastAPI() + + @app.post("/projects/{project_id}/releases") + async def write_release( + _access=Depends(require_project_access()), + _user=Depends(require_permission(Permission.RELEASE_WRITE)), + ): + return {"ok": True} + + @app.get("/projects/{project_id}/releases") + async def read_release( + _access=Depends(require_project_access()), + _user=Depends(require_permission(Permission.RELEASE_WRITE)), + ): + return {"ok": True} + + @app.post("/releases/{release_id}/gate") + async def evaluate_gate( + _access=Depends(require_release_access()), + _user=Depends(require_permission(Permission.RELEASE_GATE_EVALUATE)), + ): + return {"ok": True} + + @app.put("/projects/{project_id}/release-settings") + async def project_role_write( + _user=Depends(require_project_role(UserRole.QA_LEAD, permission=Permission.RELEASE_WRITE)), + ): + return {"ok": True} + + @app.post("/projects/{project_id}/triage") + async def triage( + _access=Depends(require_project_access()), + _user=Depends(require_permission(Permission.FAILURE_TRIAGE_ASSIGNED)), + ): + return {"ok": True} + + @app.post("/projects/{project_id}/triage-owned") + async def triage_owned( + _access=Depends(require_project_access()), + _user=Depends(require_permission(Permission.FAILURE_TRIAGE_ASSIGNED, conditions_checked_in_handler=True)), + ): + return {"ok": True} + + @app.post("/projects/{project_id}/two-guards") + async def two_guards( + _access=Depends(require_project_access()), + _engineer=Depends(require_role(UserRole.QA_ENGINEER)), + _release=Depends(require_permission(Permission.RELEASE_WRITE)), + ): + return {"ok": True} + + @app.post("/sweep") + async def sweep(db=Depends(get_db), user=Depends(require_permission(Permission.RELEASE_WRITE))): + ids = await get_accessible_project_ids(db, user) + return {"projects": sorted(str(p) for p in ids) if ids is not None else None} + + return app + + +def _client(role: str, memberships: dict[uuid.UUID, Membership], additional: list[str] | None = None) -> TestClient: + app = _app() + user = SimpleNamespace( + id=uuid.uuid4(), role=role, additional_roles=additional, is_active=True, + must_change_password=False, username="u", + ) + db = _Db(memberships) + + async def _user(): + return user + + async def _get_db(): + yield db + + app.dependency_overrides[get_current_user_or_api_key] = _user + app.dependency_overrides[get_db] = _get_db + return TestClient(app) + + +@pytest.fixture(autouse=True) +def _no_membership_cache(monkeypatch): + import app.db.redis_client as redis_client + + def _down(): + raise RuntimeError("no redis in this test") + + monkeypatch.setattr(redis_client, "get_redis", _down) + monkeypatch.setattr(deps, "_count_auth_failure", lambda reason: None) + + +def _post(client, path): + return client.post(path) + + +WRITE = f"/projects/{PROJECT}/releases" + + +# -- ladder roles: answered by rank, as before ---------------------------------- + +@pytest.mark.parametrize("role,status", [("ADMIN", 200), ("QA_LEAD", 200), ("QA_ENGINEER", 403), ("VIEWER", 403)]) +def test_ladder_roles_are_answered_by_rank(role, status): + response = _post(_client(role, {PROJECT: (role, None)}), WRITE) + assert response.status_code == status, response.text + + +def test_a_refusal_names_the_permission_and_who_holds_it(): + response = _post(_client("QA_ENGINEER", {PROJECT: ("QA_ENGINEER", None)}), WRITE) + detail = response.json()["detail"] + assert "'release.write' permission" in detail + assert "RELEASE_MANAGER" in detail and "QA_LEAD" in detail + + +def test_a_lead_capped_to_viewer_in_the_project_still_cannot_write(): + response = _post(_client("QA_LEAD", {PROJECT: ("VIEWER", None)}), WRITE) + assert response.status_code == 403, response.text + + +# -- job roles: admitted by permission, capped per project (D-2) ----------------- + +def test_a_release_manager_writes_releases_in_their_project(): + assert _post(_client("RELEASE_MANAGER", {PROJECT: ("RELEASE_MANAGER", None)}), WRITE).status_code == 200 + + +def test_the_project_role_caps_the_job_role(): + response = _post(_client("RELEASE_MANAGER", {PROJECT: ("VIEWER", None)}), WRITE) + assert response.status_code == 403 + assert "in this project" in response.json()["detail"] + + +def test_a_project_role_never_raises_the_instance_role(): + response = _post(_client("VIEWER", {PROJECT: ("RELEASE_MANAGER", None)}), WRITE) + assert response.status_code == 403 + + +def test_a_lead_whose_project_role_is_release_manager_writes_releases(): + # QA_LEAD ∩ RELEASE_MANAGER still holds release.write + assert _post(_client("QA_LEAD", {PROJECT: ("RELEASE_MANAGER", None)}), WRITE).status_code == 200 + + +def test_reads_check_the_instance_role_like_any_require_role_guard(): + assert _client("RELEASE_MANAGER", {PROJECT: ("RELEASE_MANAGER", None)}).get(WRITE).status_code == 200 + assert _client("VIEWER", {PROJECT: ("RELEASE_MANAGER", None)}).get(WRITE).status_code == 403 + + +def test_release_access_guard_holds_the_member_to_the_permission(): + path = f"/releases/{RELEASE}/gate" + assert _post(_client("RELEASE_MANAGER", {PROJECT: ("RELEASE_MANAGER", None)}), path).status_code == 200 + assert _post(_client("RELEASE_MANAGER", {PROJECT: ("DEVELOPER", None)}), path).status_code == 403 + + +def test_require_project_role_takes_a_permission_too(): + path = f"/projects/{PROJECT}/release-settings" + assert _client("RELEASE_MANAGER", {PROJECT: ("RELEASE_MANAGER", None)}).put(path).status_code == 200 + assert _client("RELEASE_MANAGER", {PROJECT: ("VIEWER", None)}).put(path).status_code == 403 + assert _client("ADMIN", {PROJECT: ("VIEWER", None)}).put(path).status_code == 200 + assert _client("QA_ENGINEER", {PROJECT: ("QA_ENGINEER", None)}).put(path).status_code == 403 + + +# -- extra job roles (D-16) ------------------------------------------------------ + +def test_an_extra_job_role_adds_the_permission(): + client = _client("QA_ENGINEER", {PROJECT: ("QA_ENGINEER", ["RELEASE_MANAGER"])}, additional=["RELEASE_MANAGER"]) + assert _post(client, WRITE).status_code == 200 + + +def test_an_extra_role_on_one_side_only_is_capped(): + instance_only = _client("QA_ENGINEER", {PROJECT: ("QA_ENGINEER", None)}, additional=["RELEASE_MANAGER"]) + assert _post(instance_only, WRITE).status_code == 403 + project_only = _client("QA_ENGINEER", {PROJECT: ("QA_ENGINEER", ["RELEASE_MANAGER"])}) + assert _post(project_only, WRITE).status_code == 403 + + +def test_a_stored_extra_role_that_is_a_rank_is_ignored(): + client = _client("VIEWER", {PROJECT: ("VIEWER", ["ADMIN"])}, additional=["ADMIN", "QA_LEAD"]) + assert _post(client, WRITE).status_code == 403 + + +# -- conditional grants ---------------------------------------------------------- + +def test_a_conditional_grant_counts_only_where_the_handler_checks_it(): + member = {PROJECT: ("DEVELOPER", None)} + assert _post(_client("DEVELOPER", member), f"/projects/{PROJECT}/triage").status_code == 403 + assert _post(_client("DEVELOPER", member), f"/projects/{PROJECT}/triage-owned").status_code == 200 + + +def test_qa_engineers_triage_unconditionally(): + member = {PROJECT: ("QA_ENGINEER", None)} + assert _post(_client("QA_ENGINEER", member), f"/projects/{PROJECT}/triage").status_code == 200 + + +# -- several guards, several projects, agents -------------------------------------- + +def test_every_guard_on_a_route_must_pass(): + path = f"/projects/{PROJECT}/two-guards" + rm = _post(_client("RELEASE_MANAGER", {PROJECT: ("RELEASE_MANAGER", None)}), path) + assert rm.status_code == 403 and "QA_ENGINEER" in rm.json()["detail"] + assert _post(_client("QA_LEAD", {PROJECT: ("QA_LEAD", None)}), path).status_code == 200 + + +def test_a_write_across_projects_reaches_only_projects_where_the_permission_holds(): + client = _client("RELEASE_MANAGER", {PROJECT: ("RELEASE_MANAGER", None), OTHER: ("VIEWER", None)}) + assert client.post("/sweep").json() == {"projects": [str(PROJECT)]} + + +def test_ladder_writes_across_projects_are_unchanged(): + client = _client("QA_LEAD", {PROJECT: ("QA_LEAD", None), OTHER: ("VIEWER", None)}) + assert client.post("/sweep").json() == {"projects": [str(PROJECT)]} + + +def test_an_agent_cannot_write_releases(): + assert _post(_client("AGENT", {PROJECT: ("AGENT", None)}), WRITE).status_code == 403 + + +# -- the guard factories refuse a drifting floor ----------------------------------- + +def test_require_role_refuses_a_permission_from_another_rank(): + with pytest.raises(ValueError, match="require_permission"): + require_role(UserRole.QA_ENGINEER, permission=Permission.RELEASE_WRITE) + + +def test_require_role_takes_ranks_only(): + with pytest.raises(ValueError): + require_role(UserRole.RELEASE_MANAGER) + with pytest.raises(ValueError): + require_project_role(UserRole.DEVELOPER) + + +def test_require_permission_is_a_require_role_guard_with_the_catalogue_floor(): + guard = require_permission(Permission.RELEASE_WRITE) + assert guard.__qualname__.startswith("require_role.") + assert getattr(guard, deps._MIN_ROLE_ATTR) is UserRole.QA_LEAD + assert getattr(guard, deps._PERMISSION_ATTR) is Permission.RELEASE_WRITE diff --git a/backend/tests/regression/test_role_hierarchy_is_five_tiers.py b/backend/tests/regression/test_role_hierarchy_is_five_tiers.py index f806d5ab2..ad751eea1 100644 --- a/backend/tests/regression/test_role_hierarchy_is_five_tiers.py +++ b/backend/tests/regression/test_role_hierarchy_is_five_tiers.py @@ -1,10 +1,17 @@ -"""Regression — the role hierarchy is FIVE tiers, and the docs must say so. +"""Regression — FIVE ranks, TEN roles, and the docs must say so. -US-13.3 compliance-audit finding 5 alleged stale "four roles" claims. A sweep -of the tracked tree found none — ``TESTER`` (added between ``VIEWER`` and -``QA_ENGINEER``) is present in every enumeration. This test pins that result so -the claim cannot silently go stale again: if a sixth tier is added, or a doc -drops one, the pinned files stop matching ``UserRole`` and CI says so. +US-13.3 compliance-audit finding 5 alleged stale "four roles" claims; this test +pinned the five-tier answer. Enterprise roles (epic E00, owner decision D-1, +2026-11-26) split two ideas that used to be one: + +* the **ranks** -- the authority ladder ``VIEWER < TESTER < QA_ENGINEER < + QA_LEAD < ADMIN`` that every ``require_role`` compares. Still exactly five. +* the **roles** -- what a person is assigned: the five ranks plus the job roles + RELEASE_MANAGER, PROJECT_MANAGER, PRODUCT_MANAGER, DEVELOPER and the AGENT + principal. A job role is not a rung: it counts as VIEWER on any guard that + names no permission. + +If a rank is added, a role is added, or a doc drops one, this file says so. Scope note: ``docs/`` is gitignored and deliberately not checked here. """ @@ -18,15 +25,18 @@ pytest.importorskip("sqlalchemy") from app.core.deps import _ROLE_ORDER # noqa: E402 +from app.core.permissions import JOB_ROLES, LADDER, ROLE_BASE_RANK # noqa: E402 from app.models.postgres import UserRole # noqa: E402 REPO_ROOT = Path(__file__).resolve().parents[3] -EXPECTED_ORDER = ["VIEWER", "TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"] +EXPECTED_RANKS = ["VIEWER", "TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"] +EXPECTED_ROLES = EXPECTED_RANKS + [ + "RELEASE_MANAGER", "PROJECT_MANAGER", "PRODUCT_MANAGER", "DEVELOPER", "AGENT", +] -# Tracked files that enumerate the hierarchy for a reader. Each must name -# every tier — a four-name list here is the exact staleness the audit looked -# for. ``user-guide/compliance.md`` is the SOC-2 control mapping. +# Tracked files that enumerate the roles for a reader. Each must name every +# rank and every role. ``user-guide/compliance.md`` is the SOC-2 control mapping. DOCS_THAT_ENUMERATE_THE_HIERARCHY = [ "README.md", "THREAT_MODEL.md", @@ -38,38 +48,58 @@ ) -def test_user_role_enum_has_exactly_five_tiers(): - assert [r.value for r in UserRole] == EXPECTED_ORDER +def test_user_role_enum_has_exactly_ten_roles(): + assert [r.value for r in UserRole] == EXPECTED_ROLES + + +def test_the_ladder_has_exactly_five_ranks(): + assert [r.value for r in LADDER] == EXPECTED_RANKS -def test_deps_role_order_matches_the_enum(): - """``_ROLE_ORDER`` is what ``require_role`` actually compares against.""" - assert [r.value for r in _ROLE_ORDER] == EXPECTED_ORDER +def test_deps_role_order_is_the_ladder(): + """``_ROLE_ORDER`` is what ``require_role`` compares against: ranks only.""" + assert [r.value for r in _ROLE_ORDER] == EXPECTED_RANKS -def test_sso_role_order_matches_the_enum(): +def test_sso_role_order_is_the_ladder(): from app.services.sso_service import _ROLE_ORDER as SSO_ROLE_ORDER - assert [r.value for r in SSO_ROLE_ORDER] == EXPECTED_ORDER + assert [r.value for r in SSO_ROLE_ORDER] == EXPECTED_RANKS + + +def test_every_role_has_a_rank_and_the_new_ones_count_as_viewer(): + assert set(ROLE_BASE_RANK) == set(UserRole) + for role in LADDER: + assert ROLE_BASE_RANK[role] is role + for role in set(UserRole) - set(LADDER): + assert ROLE_BASE_RANK[role] is UserRole.VIEWER, role + + +def test_job_roles_are_the_four_human_non_rank_roles(): + assert {r.value for r in JOB_ROLES} == {"RELEASE_MANAGER", "PROJECT_MANAGER", "PRODUCT_MANAGER", "DEVELOPER"} -def test_sso_provisioning_ceiling_accepts_every_tier(): - """The config validator's allow-list must not lag the enum — a typo'd or - missing role silently falls back to the ADMIN ceiling.""" +def test_sso_provisioning_ceiling_accepts_exactly_the_ranks(): + """The provisioning ceiling is a rank: the config validator accepts the five + ranks and refuses a job role (a typo'd or missing value would silently fall + back to the ADMIN ceiling).""" from app.core.config import Settings - for role in EXPECTED_ORDER: + for role in EXPECTED_RANKS: assert Settings._validate_sso_max_provisioned_role(role) == role + for role in set(EXPECTED_ROLES) - set(EXPECTED_RANKS): + with pytest.raises(ValueError): + Settings._validate_sso_max_provisioned_role(role) @pytest.mark.parametrize("rel", DOCS_THAT_ENUMERATE_THE_HIERARCHY) -def test_tracked_docs_name_every_role_tier(rel): +def test_tracked_docs_name_every_role(rel): path = REPO_ROOT / rel if not path.exists(): pytest.skip(f"{rel} not present in this checkout") text = path.read_text(encoding="utf-8", errors="ignore") - missing = [tier for tier in EXPECTED_ORDER if tier not in text] - assert not missing, f"{rel} omits role tier(s): {missing}" + missing = [role for role in EXPECTED_ROLES if role not in text] + assert not missing, f"{rel} omits role(s): {missing}" @pytest.mark.parametrize("rel", DOCS_THAT_ENUMERATE_THE_HIERARCHY) diff --git a/backend/tests/regression/test_sso_role_preview.py b/backend/tests/regression/test_sso_role_preview.py index 188122a73..b79266081 100644 --- a/backend/tests/regression/test_sso_role_preview.py +++ b/backend/tests/regression/test_sso_role_preview.py @@ -29,8 +29,9 @@ def _ceiling(monkeypatch): def test_the_highest_mapped_role_wins_and_names_the_matches(): out = sso_service.preview_role_from_groups(["qa", "qa-leads", "unknown"], MAPPING, UserRole.VIEWER) + # Enterprise roles E00-S05: the preview also names extra job roles the groups add (none in MAPPING). assert out == {"role": "QA_LEAD", "matched_groups": ["qa", "qa-leads"], "source": "mapping", - "ceiling": "ADMIN", "clamped": False} + "ceiling": "ADMIN", "clamped": False, "additional_roles": [], "additional_matched_groups": {}} def test_no_match_or_an_unknown_mapped_role_falls_back_to_the_default(): diff --git a/backend/tests/security_role_access_matrix.json b/backend/tests/security_role_access_matrix.json new file mode 100644 index 000000000..23fcbc773 --- /dev/null +++ b/backend/tests/security_role_access_matrix.json @@ -0,0 +1,358 @@ +{ + "DELETE /api/v1/ai-eval/datasets/{dataset_id}": ["ADMIN"], + "DELETE /api/v1/canonical-test-cases/{canonical_id}/managed-link": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "DELETE /api/v1/compliance-packs/{pack_id}": ["ADMIN"], + "DELETE /api/v1/dev/seed": ["ADMIN"], + "DELETE /api/v1/feature-flags/{key}": ["ADMIN"], + "DELETE /api/v1/keys/{key_id}": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "DELETE /api/v1/knowledge-sources/{source_id}": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "DELETE /api/v1/projects/{project_id}": ["QA_LEAD", "ADMIN"], + "DELETE /api/v1/projects/{project_id}/attribution-rules/{rule_id}": ["QA_LEAD", "ADMIN"], + "DELETE /api/v1/projects/{project_id}/classification-hints/{hint_id}": ["QA_LEAD", "ADMIN"], + "DELETE /api/v1/projects/{project_id}/github-integration": ["QA_LEAD", "ADMIN"], + "DELETE /api/v1/projects/{project_id}/members/{user_id}": ["ADMIN"], + "DELETE /api/v1/projects/{project_id}/ownership/rules/{rule_id}": ["QA_LEAD", "ADMIN"], + "DELETE /api/v1/projects/{project_id}/ownership/team-channels/{team_name}": ["QA_LEAD", "ADMIN"], + "DELETE /api/v1/projects/{project_id}/run-cadences/{cadence_id}": ["QA_LEAD", "ADMIN"], + "DELETE /api/v1/projects/{project_id}/timeline-notes/{note_id}": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "DELETE /api/v1/projects/{project_id}/workflows/defaults/{base}": ["QA_LEAD", "ADMIN"], + "DELETE /api/v1/projects/{project_id}/workflows/{workflow_id}": ["QA_LEAD", "ADMIN"], + "DELETE /api/v1/release-gate-policies/{policy_id}": ["ADMIN"], + "DELETE /api/v1/releases/{release_id}": ["ADMIN"], + "DELETE /api/v1/releases/{release_id}/phases/{phase_id}": ["ADMIN"], + "DELETE /api/v1/releases/{release_id}/test-runs/{run_id}": ["ADMIN"], + "DELETE /api/v1/runs/{run_id}": ["ADMIN"], + "DELETE /api/v1/scim-tokens/{token_id}": ["ADMIN"], + "DELETE /api/v1/settings/flags/{flag_key}": ["ADMIN"], + "DELETE /api/v1/sso/configs/{config_id}": ["ADMIN"], + "DELETE /api/v1/suites/{suite_id}": ["QA_LEAD", "ADMIN"], + "DELETE /api/v1/test-cases/{test_case_id}/review": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "DELETE /api/v1/test-management/cases/{case_id}": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "DELETE /api/v1/test-management/cases/{case_id}/requirements/{requirement_link_id}": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "DELETE /api/v1/test-management/plans/{plan_id}/items/{item_id}": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "DELETE /api/v1/webhooks/{subscription_id}": ["QA_LEAD", "ADMIN"], + "GET /api/v1/admin/dlq": ["ADMIN"], + "GET /api/v1/admin/maintenance/ai-cache": ["ADMIN"], + "GET /api/v1/admin/maintenance/dlq": ["ADMIN"], + "GET /api/v1/admin/maintenance/suite-membership-parity": ["ADMIN"], + "GET /api/v1/admin/maintenance/suite-membership-parity/{parity_run_id}": ["ADMIN"], + "GET /api/v1/admin/storage/deleted-projects": ["ADMIN"], + "GET /api/v1/agents/event-log/health": ["QA_LEAD", "ADMIN"], + "GET /api/v1/ai-eval/agent-stack-release-gate/runs": ["QA_LEAD", "ADMIN"], + "GET /api/v1/ai-eval/baselines": ["QA_LEAD", "ADMIN"], + "GET /api/v1/ai-eval/candidate-options": ["ADMIN"], + "GET /api/v1/ai-eval/dashboard": ["QA_LEAD", "ADMIN"], + "GET /api/v1/ai-eval/datasets": ["QA_LEAD", "ADMIN"], + "GET /api/v1/ai-eval/drift": ["QA_LEAD", "ADMIN"], + "GET /api/v1/ai-eval/gates/{checksum}": ["QA_LEAD", "ADMIN"], + "GET /api/v1/ai-eval/label-health": ["QA_LEAD", "ADMIN"], + "GET /api/v1/ai-eval/report-cycles": ["QA_LEAD", "ADMIN"], + "GET /api/v1/ai-eval/report-cycles/readiness": ["QA_LEAD", "ADMIN"], + "GET /api/v1/ai-eval/reviewer-quality/runs": ["QA_LEAD", "ADMIN"], + "GET /api/v1/ai-eval/runs": ["QA_LEAD", "ADMIN"], + "GET /api/v1/ai-eval/runs/{eval_run_id}": ["QA_LEAD", "ADMIN"], + "GET /api/v1/ai-eval/runs/{eval_run_id}/items": ["ADMIN"], + "GET /api/v1/ai-eval/shadow-pairs": ["QA_LEAD", "ADMIN"], + "GET /api/v1/ai-eval/tier-comparison/runs": ["QA_LEAD", "ADMIN"], + "GET /api/v1/analyze/{test_case_id}": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "GET /api/v1/audit-dashboard/categories": ["QA_LEAD", "ADMIN"], + "GET /api/v1/audit-dashboard/events": ["QA_LEAD", "ADMIN"], + "GET /api/v1/audit-dashboard/export": ["ADMIN"], + "GET /api/v1/audit-dashboard/observability/{project_id}": ["QA_LEAD", "ADMIN"], + "GET /api/v1/deep-investigate/defects/pending-review": ["QA_LEAD", "ADMIN"], + "GET /api/v1/feature-flags": ["ADMIN"], + "GET /api/v1/feature-flags/{key}": ["ADMIN"], + "GET /api/v1/feature-flags/{key}/history": ["ADMIN"], + "GET /api/v1/github/app/install-url": ["ADMIN"], + "GET /api/v1/identity/events": ["ADMIN"], + "GET /api/v1/identity/retention/policy": ["ADMIN"], + "GET /api/v1/identity/retention/preview": ["ADMIN"], + "GET /api/v1/identity/sync-status": ["ADMIN"], + "GET /api/v1/integration-health/history/{provider}": ["QA_LEAD", "ADMIN"], + "GET /api/v1/integration-health/status": ["QA_LEAD", "ADMIN"], + "GET /api/v1/integration-health/trends": ["QA_LEAD", "ADMIN"], + "GET /api/v1/keys": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "GET /api/v1/knowledge-sources/governance/confluence-spaces": ["ADMIN"], + "GET /api/v1/memory/projects/{project_id}": ["VIEWER", "TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN", "RELEASE_MANAGER", "PROJECT_MANAGER", "PRODUCT_MANAGER", "DEVELOPER", "AGENT"], + "GET /api/v1/memory/runs/{run_id}/timeline": ["VIEWER", "TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN", "RELEASE_MANAGER", "PROJECT_MANAGER", "PRODUCT_MANAGER", "DEVELOPER", "AGENT"], + "GET /api/v1/onboarding/events": ["ADMIN"], + "GET /api/v1/performance/budgets": ["QA_LEAD", "ADMIN"], + "GET /api/v1/performance/observed": ["QA_LEAD", "ADMIN"], + "GET /api/v1/performance/search-config": ["QA_LEAD", "ADMIN"], + "GET /api/v1/performance/slow-queries": ["ADMIN"], + "GET /api/v1/project-imports": ["ADMIN"], + "GET /api/v1/projects/{project_id}/agent-actions": ["QA_LEAD", "ADMIN"], + "GET /api/v1/projects/{project_id}/data-jobs": ["QA_LEAD", "ADMIN"], + "GET /api/v1/projects/{project_id}/defects/jira/metadata": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "GET /api/v1/projects/{project_id}/deletion/jobs": ["ADMIN"], + "GET /api/v1/projects/{project_id}/deletion/jobs/{job_id}": ["ADMIN"], + "GET /api/v1/projects/{project_id}/export-estimate": ["QA_LEAD", "ADMIN"], + "GET /api/v1/projects/{project_id}/reports/analysis": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "GET /api/v1/projects/{project_id}/storage": ["ADMIN"], + "GET /api/v1/reports/email-trends/availability": ["QA_LEAD", "ADMIN"], + "GET /api/v1/scim-tokens": ["ADMIN"], + "GET /api/v1/search/usage": ["QA_LEAD", "ADMIN"], + "GET /api/v1/settings/ai": ["QA_LEAD", "ADMIN"], + "GET /api/v1/settings/ai/embedding-index": ["QA_LEAD", "ADMIN"], + "GET /api/v1/settings/ai/ml/status": ["QA_LEAD", "ADMIN"], + "GET /api/v1/settings/ai/model-status": ["QA_LEAD", "ADMIN"], + "GET /api/v1/settings/audit-log": ["QA_LEAD", "ADMIN"], + "GET /api/v1/settings/flags": ["QA_LEAD", "ADMIN"], + "GET /api/v1/settings/github-app": ["ADMIN"], + "GET /api/v1/settings/integrations": ["QA_LEAD", "ADMIN"], + "GET /api/v1/settings/integrations/health": ["QA_LEAD", "ADMIN"], + "GET /api/v1/settings/mfa-policy": ["QA_LEAD", "ADMIN"], + "GET /api/v1/settings/retention-defaults": ["ADMIN"], + "GET /api/v1/settings/retention-defaults/enable-preview": ["ADMIN"], + "GET /api/v1/settings/review-gate": ["ADMIN"], + "GET /api/v1/settings/scim-delete-action": ["ADMIN"], + "GET /api/v1/settings/secret-providers": ["ADMIN"], + "GET /api/v1/settings/smtp": ["QA_LEAD", "ADMIN"], + "GET /api/v1/settings/storage": ["QA_LEAD", "ADMIN"], + "GET /api/v1/sso/configs": ["ADMIN"], + "GET /api/v1/sso/configs/{config_id}": ["ADMIN"], + "GET /api/v1/sso/scim-groups": ["ADMIN"], + "GET /api/v1/users": ["QA_LEAD", "ADMIN"], + "GET /api/v1/users/erasure-requests": ["ADMIN"], + "GET /api/v1/users/invitations": ["ADMIN"], + "GET /api/v1/users/{user_id}": ["QA_LEAD", "ADMIN"], + "GET /api/v1/users/{user_id}/access-audit": ["QA_LEAD", "ADMIN"], + "GET /api/v1/users/{user_id}/data-jobs": ["ADMIN"], + "GET /api/v1/users/{user_id}/erasure-preview": ["ADMIN"], + "GET /api/v1/users/{user_id}/memberships": ["QA_LEAD", "ADMIN"], + "GET /api/v1/webhooks/{subscription_id}/deliveries": ["QA_LEAD", "ADMIN"], + "PATCH /api/v1/feature-flags/{key}": ["ADMIN"], + "PATCH /api/v1/knowledge-sources/{source_id}": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "PATCH /api/v1/projects/{project_id}/agent-actions/{action_id}": ["QA_LEAD", "ADMIN"], + "PATCH /api/v1/projects/{project_id}/classification-hints/{hint_id}": ["QA_LEAD", "ADMIN"], + "PATCH /api/v1/projects/{project_id}/defects/{defect_id}": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "PATCH /api/v1/projects/{project_id}/members/{user_id}": ["QA_LEAD", "ADMIN"], + "PATCH /api/v1/projects/{project_id}/ownership/rules/{rule_id}": ["QA_LEAD", "ADMIN"], + "PATCH /api/v1/projects/{project_id}/run-cadences/{cadence_id}": ["QA_LEAD", "ADMIN"], + "PATCH /api/v1/projects/{project_id}/timeline-notes/{note_id}": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "PATCH /api/v1/release-gate-policies/{policy_id}": ["ADMIN"], + "PATCH /api/v1/sso/configs/{config_id}": ["ADMIN"], + "PATCH /api/v1/suites/{suite_id}": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "PATCH /api/v1/test-management/cases/{case_id}": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "PATCH /api/v1/test-management/plans/{plan_id}": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "PATCH /api/v1/test-management/plans/{plan_id}/items/{item_id}/execute": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "PATCH /api/v1/users/{user_id}": ["ADMIN"], + "PATCH /api/v1/users/{user_id}/role": ["ADMIN"], + "PATCH /api/v1/users/{user_id}/status": ["ADMIN"], + "PATCH /api/v1/webhooks/{subscription_id}": ["QA_LEAD", "ADMIN"], + "POST /api/v1/admin/dlq/{entry_id}/replay": ["ADMIN"], + "POST /api/v1/admin/maintenance/backfill-placeholder-test-cases": ["ADMIN"], + "POST /api/v1/admin/maintenance/backfill-unassigned-failures": ["ADMIN"], + "POST /api/v1/admin/maintenance/drain-active-live-sessions": ["ADMIN"], + "POST /api/v1/admin/maintenance/outbox/requeue": ["ADMIN"], + "POST /api/v1/admin/maintenance/suite-membership-cutover": ["ADMIN"], + "POST /api/v1/admin/maintenance/suite-membership-parity": ["ADMIN"], + "POST /api/v1/agents/defect-command": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/agents/event-log/{event_id}/replay": ["QA_LEAD", "ADMIN"], + "POST /api/v1/agents/invocations/{invocation_id}/cancel": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/agents/invocations/{invocation_id}/retry": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/agents/pipelines/bulk-jobs/{bulk_job_id}/cancel": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/agents/pipelines/bulk-trigger": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/agents/pipelines/trigger": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/agents/pipelines/{pipeline_id}/cancel": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/agents/pipelines/{pipeline_id}/retry": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/agents/regression-watch": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/agents/{agent_id}/invoke": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/ai-eval/agent-stack-release-gate": ["ADMIN"], + "POST /api/v1/ai-eval/baselines": ["ADMIN"], + "POST /api/v1/ai-eval/datasets": ["ADMIN"], + "POST /api/v1/ai-eval/datasets/from-feedback": ["ADMIN"], + "POST /api/v1/ai-eval/golden-datasets/seed": ["ADMIN"], + "POST /api/v1/ai-eval/pre-release-gate": ["ADMIN"], + "POST /api/v1/ai-eval/report-cycles": ["ADMIN"], + "POST /api/v1/ai-eval/reviewer-quality": ["QA_LEAD", "ADMIN"], + "POST /api/v1/ai-eval/runs/evaluate/{dataset_id}": ["ADMIN"], + "POST /api/v1/ai-eval/shadow-pairs/{shadow_pair_id}/label": ["QA_LEAD", "ADMIN"], + "POST /api/v1/ai-eval/tier-comparison": ["QA_LEAD", "ADMIN"], + "POST /api/v1/analytics/classify-uncategorized": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/analytics/defects": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/analytics/notify-owner": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/analyze": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/canonical-test-cases/bulk-link": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/canonical-test-cases/{canonical_id}/confirm-retirement": ["QA_LEAD", "ADMIN"], + "POST /api/v1/canonical-test-cases/{canonical_id}/link": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/canonical-test-cases/{canonical_id}/promote": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/compliance-packs/signing-keys/rotate": ["ADMIN"], + "POST /api/v1/compliance-packs/{pack_id}/retire": ["ADMIN"], + "POST /api/v1/debug/generate-test-run": ["ADMIN"], + "POST /api/v1/deep-investigate/defects/{defect_id}/review": ["QA_LEAD", "ADMIN"], + "POST /api/v1/deep-investigate/{run_id}": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/deep-investigate/{run_id}/clusters/{cluster_id}/promote": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/dev/seed": ["ADMIN"], + "POST /api/v1/dev/seed/reset": ["ADMIN"], + "POST /api/v1/feature-flags": ["ADMIN"], + "POST /api/v1/identity/retention/disable": ["ADMIN"], + "POST /api/v1/identity/retention/holds": ["ADMIN"], + "POST /api/v1/identity/retention/holds/{hold_id}/release": ["ADMIN"], + "POST /api/v1/identity/retention/policy": ["ADMIN"], + "POST /api/v1/identity/retention/purge": ["ADMIN"], + "POST /api/v1/integration-health/probe": ["QA_LEAD", "ADMIN"], + "POST /api/v1/integrations/jira": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/investigations/{investigation_id}/cancel": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/keys": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/knowledge-sources": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/knowledge-sources/connectors/test": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/knowledge-sources/{source_id}/sync": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/memory/projects/{project_id}/recall": ["VIEWER", "TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN", "RELEASE_MANAGER", "PROJECT_MANAGER", "PRODUCT_MANAGER", "DEVELOPER", "AGENT"], + "POST /api/v1/onboarding/{project_id}/restore": ["QA_LEAD", "ADMIN"], + "POST /api/v1/onboarding/{project_id}/skip": ["QA_LEAD", "ADMIN"], + "POST /api/v1/project-imports/uploads": ["ADMIN"], + "POST /api/v1/project-imports/uploads/{data_job_id}/complete": ["ADMIN"], + "POST /api/v1/projects": ["QA_LEAD", "ADMIN"], + "POST /api/v1/projects/import": ["ADMIN"], + "POST /api/v1/projects/{project_id}/attribution-rules": ["QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/classification-hints": ["QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/default-qa-lead/reset-password": ["QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/defects/jira": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/deletion/execute": ["ADMIN"], + "POST /api/v1/projects/{project_id}/deletion/jobs/{job_id}/acknowledge": ["ADMIN"], + "POST /api/v1/projects/{project_id}/deletion/jobs/{job_id}/collect": ["ADMIN"], + "POST /api/v1/projects/{project_id}/deletion/preview": ["ADMIN"], + "POST /api/v1/projects/{project_id}/duplicate-candidates/detect": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/duplicate-candidates/{candidate_id}/dismiss": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/duplicate-candidates/{candidate_id}/merge": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/export": ["QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/fix-outcomes": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/fixer/run": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/flaky-coach/refresh": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/github-integration/test": ["QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/insights/{insight_id}/dismiss": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/integrations/gitlab/test": ["QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/members": ["QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/ownership/codeowners/import": ["QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/ownership/rules": ["QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/ownership/rules/bulk-import": ["ADMIN"], + "POST /api/v1/projects/{project_id}/reset": ["ADMIN"], + "POST /api/v1/projects/{project_id}/restore": ["ADMIN"], + "POST /api/v1/projects/{project_id}/retention-holds": ["QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/retention-holds/{hold_id}/release": ["ADMIN"], + "POST /api/v1/projects/{project_id}/retention-policy/preview": ["ADMIN"], + "POST /api/v1/projects/{project_id}/retention-policy/purge": ["ADMIN"], + "POST /api/v1/projects/{project_id}/run-cadences": ["QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/run-cadences/{cadence_id}/pause": ["QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/run-cadences/{cadence_id}/resume": ["QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/systemic-clusters/{membership_key}/epic": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/timeline-notes": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/workflows": ["QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/workflows/{workflow_id}/evaluate": ["QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/workflows/{workflow_id}/fork": ["QA_LEAD", "ADMIN"], + "POST /api/v1/projects/{project_id}/workflows/{workflow_id}/publish": ["QA_LEAD", "ADMIN"], + "POST /api/v1/quarantine": ["QA_LEAD", "ADMIN"], + "POST /api/v1/quarantine/{request_id}/approve": ["QA_LEAD", "ADMIN"], + "POST /api/v1/quarantine/{request_id}/reject": ["QA_LEAD", "ADMIN"], + "POST /api/v1/quarantine/{request_id}/release": ["QA_LEAD", "ADMIN"], + "POST /api/v1/release-gate-policies": ["ADMIN"], + "POST /api/v1/release-gate-policies/simulate": ["ADMIN"], + "POST /api/v1/release-gate-policies/{policy_id}/deactivate": ["ADMIN"], + "POST /api/v1/release-gate-policies/{policy_id}/publish": ["ADMIN"], + "POST /api/v1/release-readiness/{run_id}/override": ["QA_LEAD", "ADMIN"], + "POST /api/v1/releases": ["QA_LEAD", "ADMIN"], + "POST /api/v1/releases/sync": ["QA_LEAD", "ADMIN"], + "POST /api/v1/releases/{release_id}/activate": ["QA_LEAD", "ADMIN"], + "POST /api/v1/releases/{release_id}/compliance-pack": ["QA_LEAD", "ADMIN"], + "POST /api/v1/releases/{release_id}/gate/evaluate": ["QA_LEAD", "ADMIN"], + "POST /api/v1/releases/{release_id}/outcomes": ["QA_LEAD", "ADMIN"], + "POST /api/v1/releases/{release_id}/phases": ["QA_LEAD", "ADMIN"], + "POST /api/v1/releases/{release_id}/phases/bulk": ["QA_LEAD", "ADMIN"], + "POST /api/v1/releases/{release_id}/phases/clone": ["QA_LEAD", "ADMIN"], + "POST /api/v1/releases/{release_id}/phases/generate": ["QA_LEAD", "ADMIN"], + "POST /api/v1/releases/{release_id}/phases/{phase_id}/gate/evaluate": ["QA_LEAD", "ADMIN"], + "POST /api/v1/releases/{release_id}/test-runs": ["QA_LEAD", "ADMIN"], + "POST /api/v1/reports/email-trends": ["QA_LEAD", "ADMIN"], + "POST /api/v1/reports/runs/{run_id}/share": ["QA_LEAD", "ADMIN"], + "POST /api/v1/reviews/{review_id}/accept": ["QA_LEAD", "ADMIN"], + "POST /api/v1/reviews/{review_id}/reject": ["QA_LEAD", "ADMIN"], + "POST /api/v1/runs/{run_id}/investigations": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/runs/{run_id}/recover-live": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/runs/{run_id}/release": ["QA_LEAD", "ADMIN"], + "POST /api/v1/scim-tokens": ["ADMIN"], + "POST /api/v1/settings/ai/embedding-index/rebuild": ["ADMIN"], + "POST /api/v1/settings/ai/ml/retrain": ["ADMIN"], + "POST /api/v1/settings/retention-defaults/enable": ["ADMIN"], + "POST /api/v1/settings/smtp/test": ["QA_LEAD", "ADMIN"], + "POST /api/v1/sso/configs": ["ADMIN"], + "POST /api/v1/sso/configs/{config_id}/preview-role": ["ADMIN"], + "POST /api/v1/sso/configs/{config_id}/test": ["ADMIN"], + "POST /api/v1/suites": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/suites/{suite_id}/set-default": ["QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/batches/{batch_id}/accept": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/batches/{batch_id}/cases/{case_id}/accept": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/batches/{batch_id}/cases/{case_id}/reject": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/cases": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/cases/ai-coverage": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/cases/ai-generate": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/cases/ai-generate/async": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/cases/bulk": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/cases/import": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/cases/rag-generate": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/cases/rag-retrieve": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/cases/{case_id}/ai-review": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/cases/{case_id}/comments": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/cases/{case_id}/dismiss-stale": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/cases/{case_id}/request-review": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/cases/{case_id}/requirements": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/cases/{case_id}/restore": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/cases/{case_id}/review-action": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/cases/{case_id}/transition": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/plans": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/plans/ai-create": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/plans/ai-create/async": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/plans/{plan_id}/items": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/strategies/ai-generate": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/test-management/strategies/ai-generate/async": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "POST /api/v1/training/export": ["ADMIN"], + "POST /api/v1/training/finetune": ["ADMIN"], + "POST /api/v1/training/promote": ["ADMIN"], + "POST /api/v1/users": ["ADMIN"], + "POST /api/v1/users/erasure-requests/{erasure_request_id}/decline": ["ADMIN"], + "POST /api/v1/users/invitations/{invitation_id}/resend": ["ADMIN"], + "POST /api/v1/users/invitations/{invitation_id}/revoke": ["ADMIN"], + "POST /api/v1/users/invite": ["ADMIN"], + "POST /api/v1/users/{user_id}/data-export": ["ADMIN"], + "POST /api/v1/users/{user_id}/erasure": ["ADMIN"], + "POST /api/v1/users/{user_id}/password-reset-link": ["ADMIN"], + "POST /api/v1/webhooks": ["QA_LEAD", "ADMIN"], + "POST /api/v1/webhooks/{subscription_id}/deliveries/{delivery_id}/replay": ["QA_LEAD", "ADMIN"], + "POST /api/v1/webhooks/{subscription_id}/test": ["QA_LEAD", "ADMIN"], + "PUT /api/v1/knowledge-sources/governance/confluence-spaces": ["ADMIN"], + "PUT /api/v1/knowledge-sources/governance/domain-allowlist": ["ADMIN"], + "PUT /api/v1/notifications/projects/{project_id}/transition-policy": ["QA_LEAD", "ADMIN"], + "PUT /api/v1/project-imports/uploads/{data_job_id}/parts/{part_number}": ["ADMIN"], + "PUT /api/v1/projects/{project_id}": ["QA_LEAD", "ADMIN"], + "PUT /api/v1/projects/{project_id}/agent-configs/{agent_id}": ["QA_LEAD", "ADMIN"], + "PUT /api/v1/projects/{project_id}/agent-policies/{agent_id}": ["QA_LEAD", "ADMIN"], + "PUT /api/v1/projects/{project_id}/attribution-rules/{rule_id}": ["QA_LEAD", "ADMIN"], + "PUT /api/v1/projects/{project_id}/fixer/config": ["QA_LEAD", "ADMIN"], + "PUT /api/v1/projects/{project_id}/github-integration": ["QA_LEAD", "ADMIN"], + "PUT /api/v1/projects/{project_id}/integrations/gitlab": ["QA_LEAD", "ADMIN"], + "PUT /api/v1/projects/{project_id}/llm-quota": ["ADMIN"], + "PUT /api/v1/projects/{project_id}/ownership/source-roots": ["QA_LEAD", "ADMIN"], + "PUT /api/v1/projects/{project_id}/ownership/team-channels/{team_name}": ["QA_LEAD", "ADMIN"], + "PUT /api/v1/projects/{project_id}/quarantine/policy": ["QA_LEAD", "ADMIN"], + "PUT /api/v1/projects/{project_id}/retention-policy": ["ADMIN"], + "PUT /api/v1/projects/{project_id}/value-metrics/assumptions": ["QA_LEAD", "ADMIN"], + "PUT /api/v1/projects/{project_id}/workflows/defaults/{base}": ["QA_LEAD", "ADMIN"], + "PUT /api/v1/projects/{project_id}/workflows/{workflow_id}": ["QA_LEAD", "ADMIN"], + "PUT /api/v1/releases/{release_id}": ["QA_LEAD", "ADMIN"], + "PUT /api/v1/releases/{release_id}/phases/{phase_id}": ["QA_LEAD", "ADMIN"], + "PUT /api/v1/settings/ai": ["ADMIN"], + "PUT /api/v1/settings/flags/{flag_key}": ["ADMIN"], + "PUT /api/v1/settings/github-app": ["ADMIN"], + "PUT /api/v1/settings/integrations": ["ADMIN"], + "PUT /api/v1/settings/mfa-policy": ["ADMIN"], + "PUT /api/v1/settings/retention-defaults": ["ADMIN"], + "PUT /api/v1/settings/review-gate": ["ADMIN"], + "PUT /api/v1/settings/scim-delete-action": ["ADMIN"], + "PUT /api/v1/settings/smtp": ["ADMIN"], + "PUT /api/v1/settings/storage": ["ADMIN"], + "PUT /api/v1/sso/scim-groups/{group_id}/mappings": ["ADMIN"], + "PUT /api/v1/test-cases/{test_case_id}/review": ["QA_ENGINEER", "QA_LEAD", "ADMIN"], + "PUT /api/v1/test-management/strategies/{strategy_id}": ["TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"], + "PUT /api/v1/test-management/suite-owners/{suite_name}": ["QA_LEAD", "ADMIN"], + "PUT /api/v1/test-management/suite-reviews/by-run/{test_run_id}/{suite_name}": ["QA_ENGINEER", "QA_LEAD", "ADMIN"] +} diff --git a/backend/tests/test_me_permissions.py b/backend/tests/test_me_permissions.py new file mode 100644 index 000000000..0f1cfde95 --- /dev/null +++ b/backend/tests/test_me_permissions.py @@ -0,0 +1,118 @@ +"""``GET /api/v1/me/permissions`` (enterprise roles E00-S04). + +Reads use the project roles; writes the intersection of instance and project roles; no membership means the +instance roles; a project the caller cannot read is refused by ``resolve_project_scope`` (403). The answer for +a ladder role is exactly "every permission at or below its rank", so the SPA's ``can()`` agrees with the +guards the routes already run. +""" +from __future__ import annotations + +import uuid +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import pytest +from fastapi import HTTPException + +from app.core.permissions import Permission, rank_index +from app.models.postgres import UserRole +from app.routers import me_permissions + + +def _user(role, additional=None): + return SimpleNamespace(id=uuid.uuid4(), role=role, additional_roles=additional) + + +def _db(row=None): + db = AsyncMock() + result = MagicMock() + result.first.return_value = row + db.execute = AsyncMock(return_value=result) + return db + + +@pytest.fixture +def scope(monkeypatch): + calls = [] + + async def _resolve(db, user, requested): + calls.append(requested) + if requested == "forbidden": + raise HTTPException(status_code=403, detail="Access denied to this project") + return uuid.UUID(requested), None + + monkeypatch.setattr(me_permissions, "resolve_project_scope", _resolve) + return calls + + +async def _ask(user, project_id=None, row=None): + return await me_permissions.get_my_permissions(project_id=project_id, db=_db(row), current_user=user) + + +def _ladder_set(role): + return sorted(p.value for p in Permission if rank_index(role) >= rank_index(p.legacy_min_rank)) + + +@pytest.mark.parametrize("role", [UserRole.VIEWER, UserRole.TESTER, UserRole.QA_ENGINEER, UserRole.QA_LEAD, + UserRole.ADMIN]) +async def test_a_ladder_role_holds_every_permission_at_or_below_its_rank(role): + out = await _ask(_user(role)) + assert out.role == role and out.additional_roles == [] + assert out.read_permissions == out.write_permissions == _ladder_set(role) + assert out.project_id is None and out.project_role is None + + +async def test_a_job_role_holds_its_explicit_set_and_conditions_are_named(): + out = await _ask(_user(UserRole.DEVELOPER)) + assert "run.ingest" in out.write_permissions and "release.write" not in out.write_permissions + assert out.conditional["failure.triage.assigned"] == ["owns_failure"] + + +async def test_an_extra_role_adds_its_permissions(): + plain = await _ask(_user(UserRole.QA_ENGINEER)) + with_rm = await _ask(_user(UserRole.QA_ENGINEER, ["RELEASE_MANAGER"])) + assert "gate_policy.write" not in plain.write_permissions + assert "gate_policy.write" in with_rm.write_permissions + assert with_rm.additional_roles == ["RELEASE_MANAGER"] + + +async def test_in_a_project_reads_follow_the_project_role_and_writes_the_lower_of_the_two(scope): + pid = str(uuid.uuid4()) + # Global QA_LEAD, capped to VIEWER in this project. + out = await _ask(_user(UserRole.QA_LEAD), pid, row=("VIEWER", None)) + assert out.project_role == UserRole.VIEWER and str(out.project_id) == pid + assert out.read_permissions == out.write_permissions == _ladder_set(UserRole.VIEWER) + # Global VIEWER who is RELEASE_MANAGER in the project: may read like one, never write like one (D-2). + out = await _ask(_user(UserRole.VIEWER), pid, row=("RELEASE_MANAGER", None)) + assert "release.write" in out.read_permissions + assert "release.write" not in out.write_permissions + + +async def test_project_extra_roles_count_on_both_sides(scope): + pid = str(uuid.uuid4()) + caller = _user(UserRole.QA_ENGINEER, ["RELEASE_MANAGER"]) + capped = await _ask(caller, pid, row=("QA_ENGINEER", None)) + held = await _ask(caller, pid, row=("QA_ENGINEER", ["RELEASE_MANAGER"])) + assert "gate_policy.write" not in capped.write_permissions + assert "gate_policy.write" in held.write_permissions + assert held.project_additional_roles == ["RELEASE_MANAGER"] + + +async def test_no_membership_answers_with_the_instance_roles(scope): + out = await _ask(_user(UserRole.ADMIN), str(uuid.uuid4()), row=None) + assert out.project_role is None and out.write_permissions == _ladder_set(UserRole.ADMIN) + + +async def test_a_foreign_project_is_refused(scope): + with pytest.raises(HTTPException) as exc: + await _ask(_user(UserRole.QA_LEAD), "forbidden") + assert exc.value.status_code == 403 + + +def test_the_route_is_a_plain_signed_in_read(): + from app.main import app + + route = next(r for r in app.routes if getattr(r, "path", "") == "/api/v1/me/permissions") + assert route.methods == {"GET"} + deps = [d.call for d in route.dependant.dependencies] + assert me_permissions.get_current_active_user in deps diff --git a/backend/tests/test_mfa.py b/backend/tests/test_mfa.py index 18b0f2501..cc75d8f0b 100644 --- a/backend/tests/test_mfa.py +++ b/backend/tests/test_mfa.py @@ -1299,6 +1299,8 @@ async def test_policy_endpoint_requires_admin_and_audits(self, db, client): "lockout_enabled": True, "lockout_threshold": 4, "lockout_duration_minutes": 15, + # Enterprise roles E00-S05: roles that need MFA whatever the floor (none set here). + "required_roles": [], } events = ( diff --git a/backend/tests/test_permission_catalogue.py b/backend/tests/test_permission_catalogue.py new file mode 100644 index 000000000..abc577083 --- /dev/null +++ b/backend/tests/test_permission_catalogue.py @@ -0,0 +1,284 @@ +"""The permission catalogue (enterprise roles E00-S01/S02): ranks, roles, grants. + +The properties every later epic leans on: + +* the five ladder roles' permission sets are exactly "rank >= the permission's + legacy rank", so moving a route to ``require_permission`` changes nothing for + them; +* a job role or AGENT counts as VIEWER wherever no permission is named; +* on a project write the instance and project grants intersect, which for two + ladder roles is "the lower of the two decides" (security audit 2026-11-18); +* an AGENT never holds a forbidden permission, whatever it is granted; +* a person can only grant a role whose permissions they hold. +""" +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + +from app.core import permissions as perms +from app.core.permissions import ( + AGENT_FORBIDDEN, + JOB_ROLES, + LADDER, + PERMISSION_SPECS, + ROLE_PERMISSIONS, + AgentCeiling, + Permission, + agent_grants, + assigned_roles, + can_grant, + effective_grants, + granted, + has_permission, + rank_index, + user_roles, +) +from app.models.postgres import UserRole + +NEW_ROLES = [r for r in UserRole if r not in LADDER] + + +# ── ranks ──────────────────────────────────────────────────────────────────── + +@pytest.mark.parametrize("role", list(UserRole)) +def test_rank_index_never_raises_for_a_role(role): + assert 0 <= rank_index(role) < len(LADDER) + + +@pytest.mark.parametrize("role", NEW_ROLES) +def test_new_roles_rank_as_viewer(role): + assert rank_index(role) == rank_index(UserRole.VIEWER) == 0 + assert rank_index(role.value) == 0 + + +def test_rank_index_refuses_a_string_that_is_not_a_role(): + with pytest.raises(ValueError): + rank_index("SUPERUSER") + + +def test_rank_index_accepts_the_legacy_prefix(): + assert rank_index("UserRole.QA_LEAD") == rank_index(UserRole.QA_LEAD) + + +# ── the catalogue ──────────────────────────────────────────────────────────── + +def test_every_permission_has_a_spec_with_a_ladder_rank(): + assert set(PERMISSION_SPECS) == set(Permission) + for permission, spec in PERMISSION_SPECS.items(): + assert spec.legacy_min_rank in LADDER, permission + assert spec.description, permission + assert permission.value == permission.value.lower(), permission + + +@pytest.mark.parametrize("role", LADDER) +@pytest.mark.parametrize("permission", list(Permission)) +def test_ladder_roles_hold_exactly_what_their_rank_reaches(role, permission): + expected = rank_index(role) >= rank_index(permission.legacy_min_rank) + assert has_permission([role], permission) is expected + + +def test_ladder_permission_sets_are_nested(): + for lower, higher in zip(LADDER, LADDER[1:]): + assert ROLE_PERMISSIONS[lower] <= ROLE_PERMISSIONS[higher] + + +def test_admin_holds_every_permission(): + assert ROLE_PERMISSIONS[UserRole.ADMIN] == frozenset(Permission) + + +@pytest.mark.parametrize("role", NEW_ROLES) +def test_every_role_has_a_permission_set_that_includes_reading(role): + assert Permission.PROJECT_READ in ROLE_PERMISSIONS[role] + assert Permission.REQUIREMENT_READ in ROLE_PERMISSIONS[role] + + +@pytest.mark.parametrize("role", list(JOB_ROLES)) +def test_job_roles_never_hold_instance_or_member_administration(role): + for permission in (Permission.INSTANCE_ADMIN, Permission.MEMBER_MANAGE, Permission.AGENT_MANAGE, + Permission.RUN_DELETE, Permission.RELEASE_DELETE, Permission.GATE_POLICY_PUBLISH): + assert permission not in ROLE_PERMISSIONS[role], (role, permission) + + +def test_release_manager_decides_releases_and_developer_does_not(): + assert has_permission([UserRole.RELEASE_MANAGER], Permission.RELEASE_DECIDE) + assert not has_permission([UserRole.DEVELOPER], Permission.RELEASE_DECIDE) + assert not has_permission([UserRole.PROJECT_MANAGER], Permission.RELEASE_DECIDE) + assert has_permission([UserRole.PRODUCT_MANAGER], Permission.ACCEPTANCE_SIGNOFF) + + +def test_conditional_grants_count_only_when_the_caller_checks_the_condition(): + roles = [UserRole.DEVELOPER] + assert not has_permission(roles, Permission.FAILURE_TRIAGE_ASSIGNED) + assert has_permission(roles, Permission.FAILURE_TRIAGE_ASSIGNED, allow_conditional=True) + + +def test_an_unconditional_grant_from_another_role_wins(): + roles = [UserRole.QA_ENGINEER, UserRole.DEVELOPER] # QA_ENGINEER triages assigned failures outright + assert has_permission(roles, Permission.FAILURE_TRIAGE_ASSIGNED) + + +def test_an_unregistered_condition_is_never_satisfied(): + assert perms.check_condition(["no_such_condition"], object(), object()) is False + assert perms.check_condition([], object(), object()) is True + + +# ── extra job roles ────────────────────────────────────────────────────────── + +def test_assigned_roles_keeps_only_valid_job_roles(): + roles = assigned_roles("QA_ENGINEER", ["RELEASE_MANAGER", "ADMIN", "AGENT", "nonsense", "RELEASE_MANAGER"]) + assert roles == (UserRole.QA_ENGINEER, UserRole.RELEASE_MANAGER) + + +def test_an_agent_carries_no_extra_roles(): + assert assigned_roles("AGENT", ["RELEASE_MANAGER"]) == (UserRole.AGENT,) + + +def test_extra_roles_add_permissions_but_not_rank(): + user = SimpleNamespace(role="QA_ENGINEER", additional_roles=["RELEASE_MANAGER"]) + roles = user_roles(user) + assert has_permission(roles, Permission.RELEASE_DECIDE) + assert rank_index(user.role) == rank_index(UserRole.QA_ENGINEER) + + +def test_a_user_without_the_column_has_only_the_primary_role(): + assert user_roles(SimpleNamespace(role="VIEWER")) == (UserRole.VIEWER,) + + +# ── project writes: the intersection ───────────────────────────────────────── + +@pytest.mark.parametrize("instance", LADDER) +@pytest.mark.parametrize("project", LADDER) +def test_for_ladder_roles_the_intersection_is_the_lower_role(instance, project): + lower = instance if rank_index(instance) <= rank_index(project) else project + grants = effective_grants([instance], [project], is_write=True) + assert set(grants) == set(ROLE_PERMISSIONS[lower]) + + +def test_a_project_role_caps_the_job_role_on_writes_d2(): + grants = effective_grants([UserRole.RELEASE_MANAGER], [UserRole.VIEWER], is_write=True) + assert not granted(grants, Permission.RELEASE_WRITE) + grants = effective_grants([UserRole.VIEWER], [UserRole.RELEASE_MANAGER], is_write=True) + assert not granted(grants, Permission.RELEASE_WRITE) + grants = effective_grants([UserRole.RELEASE_MANAGER], [UserRole.RELEASE_MANAGER], is_write=True) + assert granted(grants, Permission.RELEASE_WRITE) + + +def test_reads_use_the_project_roles_and_no_membership_uses_the_instance_roles(): + assert granted(effective_grants([UserRole.VIEWER], [UserRole.RELEASE_MANAGER], is_write=False), + Permission.AUDIT_READ_PROJECT) + assert granted(effective_grants([UserRole.RELEASE_MANAGER], None, is_write=True), Permission.RELEASE_WRITE) + + +def test_a_conditional_grant_on_either_side_stays_conditional(): + grants = effective_grants([UserRole.QA_ENGINEER, UserRole.DEVELOPER], [UserRole.DEVELOPER], is_write=True) + assert granted(grants, Permission.FAILURE_TRIAGE_ASSIGNED, allow_conditional=True) + assert not granted(grants, Permission.FAILURE_TRIAGE_ASSIGNED) + + +# ── agents ─────────────────────────────────────────────────────────────────── + +def test_agent_forbidden_is_exactly_the_no_and_never_ceilings(): + expected = {p for p, s in PERMISSION_SPECS.items() if s.agent_ceiling in (AgentCeiling.NO, AgentCeiling.NEVER)} + assert AGENT_FORBIDDEN == expected + for permission in (Permission.RELEASE_SIGNOFF, Permission.RELEASE_DECIDE, Permission.ACCEPTANCE_SIGNOFF, + Permission.RISK_ACCEPT, Permission.AGENT_PROPOSAL_APPROVE, Permission.APIKEY_CREATE_OWN, + Permission.MEMBER_MANAGE, Permission.INSTANCE_ADMIN, Permission.RELEASE_DELETE): + assert permission in AGENT_FORBIDDEN, permission + + +@pytest.mark.parametrize("permission", sorted(AGENT_FORBIDDEN, key=lambda p: p.value)) +def test_an_agent_never_holds_a_forbidden_permission_even_when_granted(permission): + grants = agent_grants([UserRole.AGENT], [permission]) + assert permission not in grants + assert not has_permission([UserRole.AGENT], permission) + + +def test_an_agent_reads_by_default_and_holds_what_it_is_granted(): + assert has_permission([UserRole.AGENT], Permission.PROJECT_READ) + assert not has_permission([UserRole.AGENT], Permission.ANALYSIS_TRIGGER) + assert Permission.ANALYSIS_TRIGGER in agent_grants([UserRole.AGENT], [Permission.ANALYSIS_TRIGGER]) + + +def test_the_agent_role_holds_nothing_forbidden(): + assert not (ROLE_PERMISSIONS[UserRole.AGENT] & AGENT_FORBIDDEN) + + +# ── granting roles ─────────────────────────────────────────────────────────── + +@pytest.mark.parametrize("granter", LADDER) +@pytest.mark.parametrize("target", LADDER) +def test_for_ladder_roles_can_grant_is_not_above_your_own_rank(granter, target): + assert can_grant([granter], target) is (rank_index(target) <= rank_index(granter)) + + +def test_a_qa_lead_may_grant_developer_and_tester_but_not_the_manager_roles(): + assert can_grant([UserRole.QA_LEAD], UserRole.DEVELOPER) + assert can_grant([UserRole.QA_LEAD], UserRole.TESTER) + # D-17: the manager roles are given only by someone holding instance.admin, even where every permission of + # the role is one the granter holds (PROJECT_MANAGER, PRODUCT_MANAGER are subsets of QA_LEAD). + for role in (UserRole.RELEASE_MANAGER, UserRole.PROJECT_MANAGER, UserRole.PRODUCT_MANAGER): + assert not can_grant([UserRole.QA_LEAD], role), role + assert not can_grant([UserRole.QA_LEAD, role], role), role + assert perms.ADMIN_ONLY_GRANTS == {UserRole.RELEASE_MANAGER, UserRole.PROJECT_MANAGER, UserRole.PRODUCT_MANAGER} + assert perms.missing_for_grant([UserRole.QA_LEAD], UserRole.RELEASE_MANAGER) == ["gate_policy.write"] + + +def test_a_qa_engineer_cannot_grant_developer(): + assert not can_grant([UserRole.QA_ENGINEER], UserRole.DEVELOPER) # quarantine.propose is a QA_LEAD permission + + +def test_nobody_grants_agent_here_and_admin_grants_everything_else(): + assert not can_grant([UserRole.ADMIN], UserRole.AGENT) + for role in UserRole: + if role is not UserRole.AGENT: + assert can_grant([UserRole.ADMIN], role), role + + +def test_refusal_detail_names_the_permission_and_its_holders(): + detail = perms.permission_refusal_detail(Permission.RELEASE_WRITE, in_project=True) + assert "'release.write' permission in this project" in detail + assert "QA_LEAD" in detail and "ADMIN" in detail and "RELEASE_MANAGER" in detail + assert "VIEWER" not in detail and "AGENT" not in detail + + +# -- extra job roles (E00-S05, D-16) ------------------------------------------------------------- + + +def test_the_api_extra_role_enum_is_the_catalogues_job_roles(): + from typing import get_args + + from app.models.schemas import ExtraRole + + assert list(get_args(ExtraRole)) == [role.value for role in perms.EXTRA_ROLE_CHOICES] + assert set(perms.EXTRA_ROLE_CHOICES) == perms.JOB_ROLES + + +def test_clean_additional_roles_orders_dedupes_and_drops_the_primary(): + clean = perms.clean_additional_roles + assert clean(None) == [] and clean([]) == [] + assert clean(["DEVELOPER", "RELEASE_MANAGER", "DEVELOPER"]) == ["RELEASE_MANAGER", "DEVELOPER"] + assert clean(["DEVELOPER", "RELEASE_MANAGER"], primary="DEVELOPER") == ["RELEASE_MANAGER"] + assert clean("PRODUCT_MANAGER") == ["PRODUCT_MANAGER"] + + +@pytest.mark.parametrize("bad", ["AGENT", "QA_LEAD", "ADMIN", "nope"]) +def test_clean_additional_roles_refuses_anything_but_a_job_role(bad): + with pytest.raises(ValueError, match="cannot be an extra role"): + perms.clean_additional_roles(["DEVELOPER", bad]) + + +def test_stored_extra_roles_are_read_leniently(): + assert perms.job_roles_in(["DEVELOPER", "AGENT", "junk", "RELEASE_MANAGER"]) == ( + UserRole.RELEASE_MANAGER, UserRole.DEVELOPER, + ) + assert perms.job_roles_in(None) == () + + +def test_a_project_grant_set_caps_what_can_be_granted(): + lead = [UserRole.QA_LEAD] + assert can_grant(lead, UserRole.DEVELOPER) + capped = perms.effective_grants(lead, [UserRole.TESTER], is_write=True) + assert not can_grant(lead, UserRole.DEVELOPER, grants=capped) + assert "quarantine.propose" in perms.missing_for_grant(lead, UserRole.DEVELOPER, grants=capped) diff --git a/backend/tests/test_project_scoped_key_auth.py b/backend/tests/test_project_scoped_key_auth.py index bb5e6b8a2..928204e62 100644 --- a/backend/tests/test_project_scoped_key_auth.py +++ b/backend/tests/test_project_scoped_key_auth.py @@ -160,3 +160,35 @@ async def test_require_instance_admin_still_refuses_a_bound_key(): unbound = _bind_api_key_project(_user(), None) assert await guard(current_user=unbound) is unbound + + +# ── Enterprise roles E00: a job role's key meets the same key rules ────────── + + +@pytest.mark.asyncio +@pytest.mark.parametrize("owner_role", [UserRole.RELEASE_MANAGER, UserRole.PRODUCT_MANAGER]) +async def test_a_job_roles_bound_key_is_refused_on_a_qa_lead_floor_unless_the_route_opts_in(owner_role): + """Key rules follow the route's floor, not the role that passed it: a release manager's + project-bound key gets past ``release.write`` only on a route that opts bound keys in.""" + from app.core.permissions import Permission + from app.core.deps import require_permission + + user = _bound_key_user(owner_role) + permission = Permission.RELEASE_WRITE if owner_role is UserRole.RELEASE_MANAGER else Permission.RISK_ACCEPT + with pytest.raises(HTTPException) as exc: + await require_permission(permission)(current_user=user) + assert exc.value.detail == PROJECT_KEY_NOT_INSTANCE_ADMIN_DETAIL + opted_in = require_role(UserRole.QA_LEAD, allow_project_key=True, permission=permission) + assert await opted_in(current_user=user) is user + + +@pytest.mark.asyncio +@pytest.mark.parametrize("min_role", _BELOW_QA_LEAD) +async def test_a_job_roles_bound_key_is_a_viewer_below_qa_lead(min_role): + user = _bound_key_user(UserRole.DEVELOPER) + if min_role is UserRole.VIEWER: + assert await require_role(min_role)(current_user=user) is user + else: + with pytest.raises(HTTPException) as exc: + await require_role(min_role)(current_user=user) + assert exc.value.detail == f"Requires at least {min_role.value} role" diff --git a/backend/tests/test_role_access_runtime.py b/backend/tests/test_role_access_runtime.py new file mode 100644 index 000000000..47627685a --- /dev/null +++ b/backend/tests/test_role_access_runtime.py @@ -0,0 +1,217 @@ +"""The reviewed access matrix, checked against the running app (enterprise roles E00-S02). + +``security_role_access_matrix.json`` is computed statically from each route's guards. This drives real HTTP +requests through the app -- authentication, ``require_role`` / ``require_permission``, the project role floor -- +for a sample of write routes, as each of the ten roles (held globally and in the project), and checks the +answer: a role the matrix leaves out gets 403; a role it admits gets past the guard (here: 422 for an empty +body, or 404 for a membership that does not exist). It also checks the lower-of-two rule end to end (D-2) and +that ``GET /api/v1/me/permissions`` answers every role. + +SQLite in memory, a closed set of tables (most of the schema is PostgreSQL-only), as in ``test_mfa.py``. +""" +from __future__ import annotations + +import itertools +import json +import uuid +from datetime import datetime, timezone +from pathlib import Path + +import pytest + +pytest.importorskip("aiosqlite") + +from httpx import ASGITransport, AsyncClient # noqa: E402 +from sqlalchemy import types as sqltypes # noqa: E402 +from sqlalchemy.dialects.sqlite import base as _sqlite_types # noqa: E402 +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine # noqa: E402 +from sqlalchemy.pool import StaticPool # noqa: E402 + +from app.core.security import create_access_token # noqa: E402 +from app.db.postgres import Base, get_db # noqa: E402 +from app.models.postgres import ( # noqa: E402 + AccessAuditLog, + ApiKey, + AppSetting, + IdentityEvent, + Project, + ProjectMember, + RefreshTokenRecord, + SettingsAuditLog, + User, + UserRole, +) + +MATRIX = json.loads((Path(__file__).parent / "security_role_access_matrix.json").read_text(encoding="utf-8")) + +_TABLES = [m.__table__ for m in (User, Project, ProjectMember, ApiKey, AppSetting, IdentityEvent, + RefreshTokenRecord, SettingsAuditLog, AccessAuditLog)] + +#: (method, path template, JSON body): one write route per rank, each refusing before it touches anything else. +SAMPLE = [ + ("POST", "/api/v1/test-management/cases", {}), # TESTER + ("POST", "/api/v1/projects/{project_id}/timeline-notes", {}), # QA_ENGINEER + ("POST", "/api/v1/projects/{project_id}/members", {}), # QA_LEAD + ("PATCH", "/api/v1/projects/{project_id}/members/{user_id}", {}), # QA_LEAD + ("DELETE", "/api/v1/projects/{project_id}/members/{user_id}", None), # ADMIN + ("POST", "/api/v1/users", {}), # ADMIN +] + + +class _AwareDateTime(_sqlite_types.DATETIME): + """Return aware datetimes, as PostgreSQL does (see ``test_mfa.py``).""" + + def result_processor(self, dialect, coltype): + inner = super().result_processor(dialect, coltype) + + def process(value): + parsed = inner(value) if inner is not None else value + if isinstance(parsed, datetime) and parsed.tzinfo is None: + return parsed.replace(tzinfo=timezone.utc) + return parsed + + return process + + +@pytest.fixture +async def db(): + engine = create_async_engine( + "sqlite+aiosqlite:///:memory:", poolclass=StaticPool, connect_args={"check_same_thread": False}, + ) + dialect = engine.sync_engine.dialect + dialect.colspecs = {**dialect.colspecs, sqltypes.DateTime: _AwareDateTime} + async with engine.begin() as conn: + await conn.run_sync(Base.metadata.create_all, tables=_TABLES) + async with async_sessionmaker(engine, expire_on_commit=False)() as session: + yield session + await engine.dispose() + + +@pytest.fixture(autouse=True) +def _redis(monkeypatch, fake_redis): + import app.db.redis_client as redis_client + + monkeypatch.setattr(redis_client, "get_redis", lambda: fake_redis) + return fake_redis + + +@pytest.fixture(autouse=True) +def _no_membership_cache(monkeypatch): + """Read memberships from the database on every request (no cached sets across role changes).""" + from app.core import deps + + async def _none(*_a, **_k): + return None + + monkeypatch.setattr(deps, "invalidate_membership_cache", _none) + + +_hosts = itertools.count(1) + + +@pytest.fixture +async def client(db): + from app.main import app, limiter + + try: + limiter.reset() + except Exception: # noqa: BLE001 -- best-effort test hygiene + pass + + async def _override(): + yield db + + app.dependency_overrides[get_db] = _override + n = next(_hosts) + transport = ASGITransport(app=app, client=(f"10.77.{n % 250}.{(n // 250) % 250}", 5000)) + async with AsyncClient(transport=transport, base_url="http://test") as ac: + yield ac + app.dependency_overrides.pop(get_db, None) + + +async def _person(db, project, role, project_role=None, additional=None, project_additional=None): + user = User( + email=f"{uuid.uuid4().hex[:10]}@example.com", username=f"u{uuid.uuid4().hex[:10]}", hashed_password="x", + role=role.value, additional_roles=additional, is_active=True, + ) + db.add(user) + await db.flush() + db.add(ProjectMember( + user_id=user.id, project_id=project.id, role=(project_role or role).value, additional_roles=project_additional, + )) + await db.commit() + return user + + +async def _project(db): + project = Project(id=uuid.uuid4(), name=f"P {uuid.uuid4().hex[:6]}", slug=f"p-{uuid.uuid4().hex[:8]}", + is_active=True) + db.add(project) + await db.commit() + return project + + +def _auth(user): + return {"Authorization": f"Bearer {create_access_token(str(user.id))}"} + + +async def _send(client, method, template, body, project, user): + # Only the placeholders this path names: a random user id for a membership that does not exist (404 once + # past the guard), the sample project's id. + values = {"project_id": project.id, "user_id": uuid.uuid4()} + path = template.format(**{name: value for name, value in values.items() if "{" + name + "}" in template}) + kwargs = {"headers": _auth(user)} + if body is not None: + kwargs["json"] = body + return await client.request(method, path, **kwargs) + + +@pytest.mark.parametrize("method,template,body", SAMPLE, ids=[f"{m} {t}" for m, t, _ in SAMPLE]) +async def test_every_role_gets_the_matrix_answer_from_the_running_app(client, db, method, template, body): + admitted = set(MATRIX[f"{method} {template}"]) + project = await _project(db) + wrong = [] + for role in list(UserRole): + user = await _person(db, project, role) + response = await _send(client, method, template, body, project, user) + expected = {404, 422} if role.value in admitted else {403} + if response.status_code not in expected: + wrong.append((role.value, response.status_code, response.text[:160])) + assert not wrong, wrong + + +async def test_the_lower_of_the_two_roles_decides_at_runtime(client, db): + project = await _project(db) + template = "/api/v1/projects/{project_id}/members" + capped = await _person(db, project, UserRole.QA_LEAD, project_role=UserRole.VIEWER) + raised = await _person(db, project, UserRole.VIEWER, project_role=UserRole.QA_LEAD) + lead = await _person(db, project, UserRole.QA_LEAD) + assert (await _send(client, "POST", template, {}, project, capped)).status_code == 403 + assert (await _send(client, "POST", template, {}, project, raised)).status_code == 403 + assert (await _send(client, "POST", template, {}, project, lead)).status_code == 422 + + +async def test_an_extra_job_role_gives_no_rank_at_runtime(client, db): + """Until a route names a permission, extra roles add nothing on it (fail closed).""" + project = await _project(db) + engineer_rm = await _person(db, project, UserRole.QA_ENGINEER, additional=["RELEASE_MANAGER"], + project_additional=["RELEASE_MANAGER"]) + response = await _send(client, "POST", "/api/v1/projects/{project_id}/members", {}, project, engineer_rm) + assert response.status_code == 403 + + +async def test_me_permissions_answers_every_role(client, db): + project = await _project(db) + for role in list(UserRole): + user = await _person(db, project, role) + response = await client.get(f"/api/v1/me/permissions?project_id={project.id}", headers=_auth(user)) + assert response.status_code == 200, (role, response.text[:200]) + body = response.json() + assert body["role"] == role.value and body["project_role"] == role.value + assert "project.read" in body["read_permissions"], role + capped = await _person(db, project, UserRole.QA_LEAD, project_role=UserRole.VIEWER) + body = (await client.get(f"/api/v1/me/permissions?project_id={project.id}", headers=_auth(capped))).json() + assert "member.manage" not in body["write_permissions"] + other = await _project(db) + response = await client.get(f"/api/v1/me/permissions?project_id={other.id}", headers=_auth(capped)) + assert response.status_code == 403 diff --git a/backend/tests/test_security_role_access_matrix.py b/backend/tests/test_security_role_access_matrix.py new file mode 100644 index 000000000..3534eab65 --- /dev/null +++ b/backend/tests/test_security_role_access_matrix.py @@ -0,0 +1,167 @@ +"""Enterprise roles E00-S02: what each of the ten roles may do on every role-gated route. + +``tests/security_role_floor_snapshot.json`` pins each route's FLOOR. With roles +that are not rungs on the ladder (RELEASE_MANAGER, PROJECT_MANAGER, +PRODUCT_MANAGER, DEVELOPER, AGENT) a floor no longer says who gets in: a route +guarded by ``require_permission(Permission.RELEASE_WRITE)`` has the floor +QA_LEAD and also admits a RELEASE_MANAGER. So this file pins the answer per +ROLE: ``tests/security_role_access_matrix.json`` lists, for every route a +``require_role`` / ``require_project_role`` guard covers, the roles it admits. + +The answer is for a caller who holds the role both on the instance and in the +route's project, read from the guards in the route's real dependency tree: + +* ``"QA_LEAD"`` -- admitted; +* ``"DEVELOPER (conditional)"`` -- admitted by a conditional grant on a route + whose handler declares it checks the condition; +* absent -- refused with 403 before the handler runs. + +Handler-level checks (``holds_role_for_project_write``, ``ensure_ingest_role``, +service-level role sets) are not visible here; the per-route tests own them. + +Owner decision 2026-11-26: tests may change when a role's expected behaviour +changes. Any difference fails until the matrix is regenerated -- +``python -m tests.test_security_role_access_matrix`` from ``backend/`` -- and the +diff, which is the reviewed list of behaviour changes per role, goes in the PR. +""" +from __future__ import annotations + +import inspect +import json +from pathlib import Path + +import pytest +from fastapi.routing import APIRoute + +from app.core.permissions import Permission, has_permission, rank_index +from app.models.postgres import UserRole + +MATRIX = Path(__file__).with_name("security_role_access_matrix.json") +ROLES = list(UserRole) +_GATES = ("require_role", "require_project_role") +_NEW_ROLES = [r for r in UserRole if r.value not in {"VIEWER", "TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN"}] + + +def _calls(dependant, seen=None): + seen = set() if seen is None else seen + for sub in dependant.dependencies: + if sub.call is not None and id(sub.call) not in seen: + seen.add(id(sub.call)) + yield sub.call + yield from _calls(sub, seen) + + +def _gate(call): + """``(min_role, permission, conditions_checked_in_handler)`` of a role guard, else ``None``.""" + if getattr(call, "__module__", "") != "app.core.deps": + return None + factory = getattr(call, "__qualname__", "").split("..", 1)[0] + if factory not in _GATES: + return None + nonlocals = inspect.getclosurevars(call).nonlocals + role = nonlocals.get("min_role") + assert isinstance(role, UserRole), f"{factory} closure without a min_role: {call}" + permission = nonlocals.get("permission") + assert permission is None or isinstance(permission, Permission), call + return role, permission, nonlocals.get("conditions_checked_in_handler", False) is True + + +def answer(role: UserRole, gates) -> str: + """``allow`` / ``conditional`` / ``deny`` for a caller holding ``role`` everywhere.""" + result = "allow" + for min_role, permission, conditional_ok in gates: + if rank_index(role) >= rank_index(min_role): + continue + if permission is not None and has_permission([role], permission): + continue + if permission is not None and conditional_ok and has_permission([role], permission, allow_conditional=True): + result = "conditional" + continue + return "deny" + return result + + +def current_matrix() -> dict[str, list[str]]: + from app.main import app + + matrix: dict[str, list[str]] = {} + for route in app.routes: + if not isinstance(route, APIRoute): + continue + gates = [gate for call in _calls(route.dependant) if (gate := _gate(call)) is not None] + if not gates: + continue + cells: list[str] = [] + for role in ROLES: + verdict = answer(role, gates) + if verdict == "allow": + cells.append(role.value) + elif verdict == "conditional": + cells.append(f"{role.value} (conditional)") + for method in sorted(route.methods - {"HEAD", "OPTIONS"}): + matrix[f"{method} {route.path}"] = cells + return dict(sorted(matrix.items())) + + +def _render(matrix: dict) -> str: + """One route per line, sorted: a change for one role is a one-line diff.""" + lines = [f" {json.dumps(k)}: {json.dumps(matrix[k])}" for k in sorted(matrix)] + return "{\n" + ",\n".join(lines) + "\n}\n" + + +@pytest.fixture(scope="module") +def snapshot() -> dict: + assert MATRIX.is_file(), f"missing {MATRIX.name}: run python -m tests.test_security_role_access_matrix" + return json.loads(MATRIX.read_text(encoding="utf-8")) + + +@pytest.fixture(scope="module") +def current() -> dict: + return current_matrix() + + +def test_the_walk_sees_the_role_gates(current): + assert len(current) >= 300, len(current) + assert current["POST /api/v1/scim-tokens"] == ["ADMIN"] + + +def test_every_role_answer_matches_the_reviewed_matrix(snapshot, current): + new = sorted(set(current) - set(snapshot)) + gone = sorted(set(snapshot) - set(current)) + changed = sorted(k for k in set(snapshot) & set(current) if snapshot[k] != current[k]) + details = [] + for key in changed: + was, now = set(snapshot[key]), set(current[key]) + details.append(f"{key}: gained {sorted(now - was)} lost {sorted(was - now)}") + assert not (new or gone or changed), ( + "per-role access differs from tests/security_role_access_matrix.json. If the change is intended and " + "listed in the epic, regenerate it (python -m tests.test_security_role_access_matrix) and put the diff " + f"in the PR.\n new routes: {new}\n removed or ungated: {gone}\n changed:\n " + "\n ".join(details) + ) + + +def test_the_matrix_file_is_canonical(snapshot): + assert MATRIX.read_bytes() == _render(snapshot).encode("utf-8") + + +def test_admin_is_admitted_everywhere(current): + assert all("ADMIN" in roles for roles in current.values()) + + +@pytest.mark.parametrize("role", _NEW_ROLES) +def test_a_new_role_gets_exactly_viewer_wherever_no_permission_is_named(role, current): + """Fail closed (E00): until a route names a permission, a job role or AGENT is a VIEWER there.""" + from app.main import app + + for route in app.routes: + if not isinstance(route, APIRoute): + continue + gates = [gate for call in _calls(route.dependant) if (gate := _gate(call)) is not None] + if not gates or any(permission is not None for _, permission, _ in gates): + continue + assert answer(role, gates) == answer(UserRole.VIEWER, gates), (route.path, role) + + +if __name__ == "__main__": # python -m tests.test_security_role_access_matrix + MATRIX.write_bytes(_render(current_matrix()).encode("utf-8")) + print(f"wrote {MATRIX}") diff --git a/backend/tests/test_spa_permission_parity.py b/backend/tests/test_spa_permission_parity.py new file mode 100644 index 000000000..dae4d57ed --- /dev/null +++ b/backend/tests/test_spa_permission_parity.py @@ -0,0 +1,54 @@ +"""The SPA's role and permission vocabulary equals the backend's (enterprise roles E00-S04). + +``frontend/src/types/permissions.ts`` spells out the ``Permission`` union and the role lists the SPA uses for +``can()`` and the role pickers. ``GET /api/v1/me/permissions`` answers with plain strings, so the OpenAPI +document cannot catch a drift: a permission added on one side only would make ``can()`` silently false. +""" +from __future__ import annotations + +import re +from pathlib import Path + +from app.core.permissions import EXTRA_ROLE_CHOICES, LADDER, Permission +from app.models.postgres import UserRole + +SPA_TYPES = Path(__file__).resolve().parents[2] / "frontend" / "src" / "types" / "permissions.ts" + + +def _source() -> str: + return SPA_TYPES.read_text(encoding="utf-8") + + +def _union(name: str) -> list[str]: + match = re.search(rf"export type {name} =(.*?)(?:\n\n|\nexport )", _source(), re.S) + assert match, f"{name} not found in {SPA_TYPES}" + return re.findall(r"'([^']+)'", match.group(1)) + + +def _array(name: str) -> list[str]: + match = re.search(rf"export const {name}: [^=]+= \[([^\]]*)\]", _source()) + assert match, f"{name} not found in {SPA_TYPES}" + return re.findall(r"'([^']+)'", match.group(1)) + + +def test_the_spa_permission_union_is_the_backend_catalogue_in_order(): + assert _union("Permission") == [p.value for p in Permission] + + +def test_the_spa_rank_and_job_role_lists_match(): + assert _union("RankRole") == [r.value for r in LADDER] + assert _array("RANK_ROLES") == [r.value for r in LADDER] + assert _union("JobRole") == [r.value for r in EXTRA_ROLE_CHOICES] + assert _array("JOB_ROLES") == [r.value for r in EXTRA_ROLE_CHOICES] + + +def test_the_spa_admin_only_grants_match_the_backend(): + """D-17: the SPA leaves out of a QA lead's pickers exactly the roles the server refuses them.""" + from app.core.permissions import ADMIN_ONLY_GRANTS + + assert set(_array("ADMIN_ONLY_GRANTS")) == {r.value for r in ADMIN_ONLY_GRANTS} + + +def test_every_backend_role_is_an_spa_role(): + spa = set(_union("RankRole")) | set(_union("JobRole")) | {"AGENT"} + assert spa == {r.value for r in UserRole} diff --git a/backend/tests/test_timeline_note_routes.py b/backend/tests/test_timeline_note_routes.py index a07b31b10..dc06d7fb8 100644 --- a/backend/tests/test_timeline_note_routes.py +++ b/backend/tests/test_timeline_note_routes.py @@ -197,5 +197,6 @@ def test_the_role_order_check_is_not_an_inline_admin_test(): source = inspect.getsource(timeline_note_service) assert "UserRole.ADMIN" not in source and "== \"ADMIN\"" not in source - assert "_ROLE_ORDER.index" in source + # Enterprise roles E00-S01: the rank comparison goes through the one rank helper (a job role ranks as VIEWER). + assert "rank_index(" in source and "_ROLE_ORDER.index" not in source assert UserRole.QA_LEAD.value == "QA_LEAD" diff --git a/docs/reference/api-index.md b/docs/reference/api-index.md index e807cb1d0..34c63d602 100644 --- a/docs/reference/api-index.md +++ b/docs/reference/api-index.md @@ -251,6 +251,7 @@ This indexes every OpenAPI HTTP operation. Exact parameters, body schemas and de | GET | `/api/v1/me/erasure-request` | Get My Erasure Request | [Subject rights](api/subject-rights.md) | | POST | `/api/v1/me/erasure-request` | File My Erasure Request | [Subject rights](api/subject-rights.md) | | POST | `/api/v1/me/erasure-request/withdraw` | Withdraw My Erasure Request | [Subject rights](api/subject-rights.md) | +| GET | `/api/v1/me/permissions` | Get My Permissions | [My Permissions](api/my-permissions.md) | | GET | `/api/v1/memory/projects/{project_id}` | List Project Memories | [Agent Memory](api/agent-memory.md) | | POST | `/api/v1/memory/projects/{project_id}/recall` | Recall Similar Memories | [Agent Memory](api/agent-memory.md) | | GET | `/api/v1/memory/runs/{run_id}/timeline` | Get Run Memory Timeline | [Agent Memory](api/agent-memory.md) | @@ -764,4 +765,4 @@ This indexes every OpenAPI HTTP operation. Exact parameters, body schemas and de | POST | `/webhooks/minio` | Minio Webhook | [Webhooks](api/webhooks.md) | | POST | `/ws/events/{run_id}` | Ingest Live Event | [Live Reporting](api/live-reporting.md) | -Total: **755 HTTP operations**, **639 paths**, **92 domain pages**. +Total: **756 HTTP operations**, **640 paths**, **93 domain pages**. diff --git a/docs/reference/api/authentication.md b/docs/reference/api/authentication.md index c002b3ee3..fc62456be 100644 --- a/docs/reference/api/authentication.md +++ b/docs/reference/api/authentication.md @@ -14,7 +14,7 @@ A wrong current password counts toward the same account lockout as a failed sign-in, and a locked account answers 429 whatever was typed. Without that, a stolen access token could be used to guess the password with no limit. -Source: [backend/app/routers/auth.py:1150](../../../backend/app/routers/auth.py#L1150). +Source: [backend/app/routers/auth.py:1175](../../../backend/app/routers/auth.py#L1175). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_interactive_session`. @@ -103,7 +103,7 @@ ordinary user, because everyone on the internet signs in as it. Answers Rate-limited per IP (``_AUTH_RATE_LIMITS``); the demo-mode middleware keeps the session read-only. -Source: [backend/app/routers/auth.py:792](../../../backend/app/routers/auth.py#L792). +Source: [backend/app/routers/auth.py:817](../../../backend/app/routers/auth.py#L817). Dependency chain: `get_db`. @@ -159,7 +159,7 @@ Query param: If the requested user does not exist yet (seed not run), a temporary account is created on the fly so developers can always access the UI after `make dev`. -Source: [backend/app/routers/auth.py:713](../../../backend/app/routers/auth.py#L713). +Source: [backend/app/routers/auth.py:738](../../../backend/app/routers/auth.py#L738). Dependency chain: `get_db`. @@ -248,7 +248,7 @@ Forced password reset for self-registered users on first login. - Does NOT require the current/registration password. - Clears the must_change_password flag after a successful change. -Source: [backend/app/routers/auth.py:842](../../../backend/app/routers/auth.py#L842). +Source: [backend/app/routers/auth.py:867](../../../backend/app/routers/auth.py#L867). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_interactive_session`. @@ -479,7 +479,7 @@ are **not** access tokens and are rejected by ``get_current_user``: see ``core/security.create_mfa_token`` for why a claim on a real access token would have been a complete bypass. -Source: [backend/app/routers/auth.py:466](../../../backend/app/routers/auth.py#L466). +Source: [backend/app/routers/auth.py:473](../../../backend/app/routers/auth.py#L473). Dependency chain: `OAuth2PasswordRequestForm`, `get_db`. @@ -565,7 +565,7 @@ so every access token already issued to the user stops working at once. Plain logout leaves the user's other access tokens to expire on their own (they cannot be refreshed). -Source: [backend/app/routers/auth.py:1056](../../../backend/app/routers/auth.py#L1056). +Source: [backend/app/routers/auth.py:1081](../../../backend/app/routers/auth.py#L1081). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_interactive_session`. @@ -648,7 +648,7 @@ Get Me Return the authenticated user's profile. -Source: [backend/app/routers/auth.py:1001](../../../backend/app/routers/auth.py#L1001). +Source: [backend/app/routers/auth.py:1026](../../../backend/app/routers/auth.py#L1026). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`. @@ -720,7 +720,7 @@ Update Me Self-service profile update — any authenticated user can update their own full_name and avatar_color. Email and username are read-only here. -Source: [backend/app/routers/auth.py:1038](../../../backend/app/routers/auth.py#L1038). +Source: [backend/app/routers/auth.py:1063](../../../backend/app/routers/auth.py#L1063). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`. @@ -802,7 +802,7 @@ List My Dismissals UI prompts this user has dismissed. Read-only; no project scope — a dismissal is a property of the person, not of a project. -Source: [backend/app/routers/auth.py:1007](../../../backend/app/routers/auth.py#L1007). +Source: [backend/app/routers/auth.py:1032](../../../backend/app/routers/auth.py#L1032). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`. @@ -874,7 +874,7 @@ Dismiss Prompt Dismiss a UI prompt for this user. Idempotent — dismissing twice is a no-op and still returns 201 with the full list. -Source: [backend/app/routers/auth.py:1018](../../../backend/app/routers/auth.py#L1018). +Source: [backend/app/routers/auth.py:1043](../../../backend/app/routers/auth.py#L1043). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`. @@ -1457,7 +1457,7 @@ Forgot Password Always 202 with the same body. The lookup and the mail run after the response. -Source: [backend/app/routers/auth.py:258](../../../backend/app/routers/auth.py#L258). +Source: [backend/app/routers/auth.py:265](../../../backend/app/routers/auth.py#L265). Dependency chain: . @@ -1519,7 +1519,7 @@ Redeem a reset link: set the password, clear lockout, sign out everywhere. MFA is untouched — the next sign-in still asks for the code. -Source: [backend/app/routers/auth.py:295](../../../backend/app/routers/auth.py#L295). +Source: [backend/app/routers/auth.py:302](../../../backend/app/routers/auth.py#L302). Dependency chain: `get_db`. @@ -1578,7 +1578,7 @@ Refresh Tokens Exchange a valid refresh token for a new access + refresh token pair (rotation). The old refresh token is not reusable after this call. -Source: [backend/app/routers/auth.py:884](../../../backend/app/routers/auth.py#L884). +Source: [backend/app/routers/auth.py:909](../../../backend/app/routers/auth.py#L909). Dependency chain: `get_db`. @@ -1650,7 +1650,7 @@ sign-up form promises -- with no project membership and must_change_password=True. It used to be QA_ENGINEER, which can create API keys. -Source: [backend/app/routers/auth.py:342](../../../backend/app/routers/auth.py#L342). +Source: [backend/app/routers/auth.py:349](../../../backend/app/routers/auth.py#L349). Dependency chain: `get_db`. @@ -1718,7 +1718,7 @@ Return active users for assignee dropdowns (bounded). Only the people the caller works with: users who share a project with them, and themselves. An admin sees everyone. -Source: [backend/app/routers/auth.py:1121](../../../backend/app/routers/auth.py#L1121). +Source: [backend/app/routers/auth.py:1146](../../../backend/app/routers/auth.py#L1146). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`. diff --git a/docs/reference/api/my-permissions.md b/docs/reference/api/my-permissions.md new file mode 100644 index 000000000..278f5f109 --- /dev/null +++ b/docs/reference/api/my-permissions.md @@ -0,0 +1,94 @@ +# My Permissions API + +[Documentation home](../../README.md) · [Regeneration](../../maintainers/maintenance.md) + +Generated from tracked source by `scripts/generate_reference.py`. Do not edit by hand. What the checks cover is recorded in [verification](../../maintainers/verification.md). + +## GET `/api/v1/me/permissions` + +Get My Permissions + +The caller's roles and the permissions they hold, for reads and for writes. + +Source: [backend/app/routers/me_permissions.py:47](../../../backend/app/routers/me_permissions.py#L47). + +Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`. + +Declared Python handler arguments (includes exact role/guard options): + +```python +project_id: Optional[str]=Query(None, description='Answer for this project; omitted, the global sets'), db: AsyncSession=Depends(get_db), current_user: User=Depends(get_current_active_user) +``` + +### Declared wire contract + +References such as `#/components/schemas/...` resolve in [schemas](../schemas.md) or [OpenAPI JSON](../openapi.json). + +```json +{ + "operationId": "get_my_permissions_api_v1_me_permissions_get", + "parameters": [ + { + "description": "Answer for this project; omitted, the global sets", + "in": "query", + "name": "project_id", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Answer for this project; omitted, the global sets", + "title": "Project Id" + } + }, + { + "in": "header", + "name": "X-API-Key", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "X-Api-Key" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MyPermissionsResponse" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "security": [ + { + "JWT": [] + } + ] +} +``` diff --git a/docs/reference/api/settings.md b/docs/reference/api/settings.md index e1614cf7c..82a2830aa 100644 --- a/docs/reference/api/settings.md +++ b/docs/reference/api/settings.md @@ -1014,7 +1014,7 @@ Return health status for all tracked integration providers. The deployment-wide view only (``scope_key = ''``): per-project GitHub / GitLab rows (W10 INT-04) are Integration Health's ``?scope=all`` read. -Source: [backend/app/routers/app_settings.py:1663](../../../backend/app/routers/app_settings.py#L1663). +Source: [backend/app/routers/app_settings.py:1683](../../../backend/app/routers/app_settings.py#L1683). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -1172,6 +1172,13 @@ Declared Python handler arguments (includes exact role/guard options): payload: MfaPolicyUpdate, current_user: User=Depends(require_role(UserRole.ADMIN)), db: AsyncSession=Depends(get_db) ``` +Direct handler error branches (dependency/service errors can add others): + +```python +HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='AGENT cannot be required to use MFA (agents sign in with keys)') +HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='The MFA floor must be a rank (VIEWER, TESTER, QA_ENGINEER, QA_LEAD or ADMIN); list job roles under required roles') +``` + ### Declared wire contract References such as `#/components/schemas/...` resolve in [schemas](../schemas.md) or [OpenAPI JSON](../openapi.json). @@ -1245,7 +1252,7 @@ The instance retention defaults: the stored values (NULL = the code default), the code defaults, the effective values, how many projects inherit each field, and who switched the default on. Reads only. -Source: [backend/app/routers/app_settings.py:1713](../../../backend/app/routers/app_settings.py#L1713). +Source: [backend/app/routers/app_settings.py:1733](../../../backend/app/routers/app_settings.py#L1733). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -1318,7 +1325,7 @@ Save the instance defaults (``clear`` resets a field to the code default). ``enabled: true`` is refused (422 ``enable_via_flow``); ``enabled: false`` switches the default off at once. Interactive login only. -Source: [backend/app/routers/app_settings.py:1739](../../../backend/app/routers/app_settings.py#L1739). +Source: [backend/app/routers/app_settings.py:1759](../../../backend/app/routers/app_settings.py#L1759). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -1408,7 +1415,7 @@ Switch the instance default ON for every project without its own ``preview_stale``) and the confirmation must be the exact phrase (422 ``confirmation_mismatch``). Interactive login only. -Source: [backend/app/routers/app_settings.py:1767](../../../backend/app/routers/app_settings.py#L1767). +Source: [backend/app/routers/app_settings.py:1787](../../../backend/app/routers/app_settings.py#L1787). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -1492,7 +1499,7 @@ no explicit ``enabled``), the hash ``POST …/enable`` must echo and the phrase it must type. An instance administrator's deployment-wide view. Writes NOTHING. -Source: [backend/app/routers/app_settings.py:1726](../../../backend/app/routers/app_settings.py#L1726). +Source: [backend/app/routers/app_settings.py:1746](../../../backend/app/routers/app_settings.py#L1746). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -1566,7 +1573,7 @@ none = audit only), whether the gate is enforced right now and why, and the distribution attempts that would have been withheld in the last 30 days. Reads only. -Source: [backend/app/routers/app_settings.py:1840](../../../backend/app/routers/app_settings.py#L1840). +Source: [backend/app/routers/app_settings.py:1860](../../../backend/app/routers/app_settings.py#L1860). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -1639,7 +1646,7 @@ Set the enforcement date (an ISO-8601 instant with an offset; past or future) or clear it with ``null`` (back to audit only). A past instant enforces at once. Interactive login only; audited once per actual change. -Source: [backend/app/routers/app_settings.py:1852](../../../backend/app/routers/app_settings.py#L1852). +Source: [backend/app/routers/app_settings.py:1872](../../../backend/app/routers/app_settings.py#L1872). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -1727,7 +1734,7 @@ Get Scim Delete Action What an identity provider's SCIM ``DELETE /Users/{id}`` does: ``deactivate`` (the default — the account is switched off and kept) or ``erase`` (the person's data is erased, as by an administrator). Reads only. -Source: [backend/app/routers/app_settings.py:1901](../../../backend/app/routers/app_settings.py#L1901). +Source: [backend/app/routers/app_settings.py:1921](../../../backend/app/routers/app_settings.py#L1921). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -1799,7 +1806,7 @@ Update Scim Delete Action Set what a SCIM ``DELETE`` does: ``deactivate`` or ``erase`` (anything else is the coded 422 ``scim_delete_action_invalid``). Interactive login only; audited once per actual change. -Source: [backend/app/routers/app_settings.py:1911](../../../backend/app/routers/app_settings.py#L1911). +Source: [backend/app/routers/app_settings.py:1931](../../../backend/app/routers/app_settings.py#L1931). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. diff --git a/docs/reference/api/sso-saml.md b/docs/reference/api/sso-saml.md index 82b39223b..5140b8dab 100644 --- a/docs/reference/api/sso-saml.md +++ b/docs/reference/api/sso-saml.md @@ -19,7 +19,7 @@ The POST comes from the browser. It answers with a 303 into the app app exchanges for the tokens (``POST /sso/exchange``); a refusal goes back to ``/login``. A client that asks for JSON gets the tokens as before. -Source: [backend/app/routers/sso.py:525](../../../backend/app/routers/sso.py#L525). +Source: [backend/app/routers/sso.py:530](../../../backend/app/routers/sso.py#L530). Dependency chain: `get_db`. @@ -64,7 +64,7 @@ List Sso Configs List all SSO configurations (ADMIN only). -Source: [backend/app/routers/sso.py:742](../../../backend/app/routers/sso.py#L742). +Source: [backend/app/routers/sso.py:747](../../../backend/app/routers/sso.py#L747). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -139,7 +139,7 @@ Create Sso Config Create a new SSO configuration (ADMIN only). -Source: [backend/app/routers/sso.py:771](../../../backend/app/routers/sso.py#L771). +Source: [backend/app/routers/sso.py:776](../../../backend/app/routers/sso.py#L776). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -227,7 +227,7 @@ Delete Sso Config Delete an SSO configuration (ADMIN only). -Source: [backend/app/routers/sso.py:956](../../../backend/app/routers/sso.py#L956). +Source: [backend/app/routers/sso.py:961](../../../backend/app/routers/sso.py#L961). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -307,7 +307,7 @@ Get Sso Config Get a specific SSO configuration (ADMIN only). -Source: [backend/app/routers/sso.py:755](../../../backend/app/routers/sso.py#L755). +Source: [backend/app/routers/sso.py:760](../../../backend/app/routers/sso.py#L760). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -394,7 +394,7 @@ Update Sso Config Update an SSO configuration (ADMIN only). -Source: [backend/app/routers/sso.py:846](../../../backend/app/routers/sso.py#L846). +Source: [backend/app/routers/sso.py:851](../../../backend/app/routers/sso.py#L851). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -497,7 +497,7 @@ W20 ADM-08a: the role a user in these IdP groups would get (ADMIN only; pure, wr The posted ``role_mapping`` / ``default_role`` preview an unsaved edit; otherwise the stored ones answer. -Source: [backend/app/routers/sso.py:990](../../../backend/app/routers/sso.py#L990). +Source: [backend/app/routers/sso.py:995](../../../backend/app/routers/sso.py#L995). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -596,7 +596,7 @@ Test Sso Connection Test an SSO configuration by validating the certificate and IdP metadata (ADMIN only). -Source: [backend/app/routers/sso.py:1019](../../../backend/app/routers/sso.py#L1019). +Source: [backend/app/routers/sso.py:1024](../../../backend/app/routers/sso.py#L1024). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -686,7 +686,7 @@ The tokens for an SSO sign-in the ACS completed, for its one-time code. Public, like the ACS: the code is the credential. It works once, within a minute of the IdP's response. -Source: [backend/app/routers/sso.py:703](../../../backend/app/routers/sso.py#L703). +Source: [backend/app/routers/sso.py:708](../../../backend/app/routers/sso.py#L708). Dependency chain: . @@ -757,7 +757,7 @@ The answer also sets the sign-in cookie that the ACS / OIDC callback require, so the caller must be the browser that will follow the URL (a page on another origin has to send the request with credentials). -Source: [backend/app/routers/sso.py:263](../../../backend/app/routers/sso.py#L263). +Source: [backend/app/routers/sso.py:268](../../../backend/app/routers/sso.py#L268). Dependency chain: `get_db`. @@ -839,7 +839,7 @@ configuration has an IdP SLO URL (``/sso/slo`` answers 404 otherwise, and advertising it then sent IdPs to that 404). IdP-initiated SLO only, so no SP signing key is published. -Source: [backend/app/routers/sso.py:155](../../../backend/app/routers/sso.py#L155). +Source: [backend/app/routers/sso.py:160](../../../backend/app/routers/sso.py#L160). Dependency chain: `get_db`. @@ -884,7 +884,7 @@ the ID token validated (signature / iss / aud / exp / nonce), then the user is J and handed into the app through the one-time-code fragment. Every refusal goes back to ``/login`` with a generic notice; the reason stays in the server log and the identity-event audit. -Source: [backend/app/routers/sso.py:369](../../../backend/app/routers/sso.py#L369). +Source: [backend/app/routers/sso.py:374](../../../backend/app/routers/sso.py#L374). Dependency chain: `get_db`. @@ -1007,7 +1007,7 @@ Oidc Login W20 ADM-08b: start an OIDC sign-in — 302 to the IdP's authorization endpoint (state, nonce, PKCE S256). -Source: [backend/app/routers/sso.py:348](../../../backend/app/routers/sso.py#L348). +Source: [backend/app/routers/sso.py:353](../../../backend/app/routers/sso.py#L353). Dependency chain: `get_db`. @@ -1261,7 +1261,7 @@ Saml Single Logout Redirect Binding W20 ADM-08c: IdP-initiated single logout, HTTP-Redirect binding (see ``saml_single_logout``). -Source: [backend/app/routers/sso.py:180](../../../backend/app/routers/sso.py#L180). +Source: [backend/app/routers/sso.py:185](../../../backend/app/routers/sso.py#L185). Dependency chain: `get_db`. @@ -1305,7 +1305,7 @@ Saml Single Logout Post Binding W20 ADM-08c: IdP-initiated single logout, HTTP-POST binding (see ``saml_single_logout``). -Source: [backend/app/routers/sso.py:188](../../../backend/app/routers/sso.py#L188). +Source: [backend/app/routers/sso.py:193](../../../backend/app/routers/sso.py#L193). Dependency chain: `get_db`. @@ -1349,7 +1349,7 @@ Get Sso Status Public endpoint to check if SSO is enabled and available. -Source: [backend/app/routers/sso.py:721](../../../backend/app/routers/sso.py#L721). +Source: [backend/app/routers/sso.py:726](../../../backend/app/routers/sso.py#L726). Dependency chain: `get_db`. diff --git a/docs/reference/api/user-management.md b/docs/reference/api/user-management.md index f74489ff6..2b9ac61ef 100644 --- a/docs/reference/api/user-management.md +++ b/docs/reference/api/user-management.md @@ -10,7 +10,7 @@ List Project Members List all members of a project. -Source: [backend/app/routers/users.py:682](../../../backend/app/routers/users.py#L682). +Source: [backend/app/routers/users.py:838](../../../backend/app/routers/users.py#L838). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_project_access.._check`. @@ -101,7 +101,7 @@ Add Project Member Add a user to a project with a role. Requires QA_LEAD or higher. -Source: [backend/app/routers/users.py:709](../../../backend/app/routers/users.py#L709). +Source: [backend/app/routers/users.py:865](../../../backend/app/routers/users.py#L865). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_project_access.._check`, `require_role.._check`. @@ -200,7 +200,7 @@ Remove Project Member Remove a user from a project. Requires ADMIN. -Source: [backend/app/routers/users.py:814](../../../backend/app/routers/users.py#L814). +Source: [backend/app/routers/users.py:996](../../../backend/app/routers/users.py#L996). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_project_access.._check`, `require_role.._check`. @@ -290,7 +290,7 @@ Update Project Member Role Update a project member's role. Requires QA_LEAD or higher. -Source: [backend/app/routers/users.py:763](../../../backend/app/routers/users.py#L763). +Source: [backend/app/routers/users.py:927](../../../backend/app/routers/users.py#L927). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_project_access.._check`, `require_role.._check`. @@ -400,7 +400,7 @@ List all users (paginated). Requires QA_LEAD or higher. The body stays a bare list (other callers read it); the number of users matching the filters, across every page, is the ``X-Total-Count`` header. -Source: [backend/app/routers/users.py:131](../../../backend/app/routers/users.py#L131). +Source: [backend/app/routers/users.py:246](../../../backend/app/routers/users.py#L246). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -553,7 +553,7 @@ Admin Create User Admin creates a user directly with a temporary password. Requires ADMIN. -Source: [backend/app/routers/users.py:347](../../../backend/app/routers/users.py#L347). +Source: [backend/app/routers/users.py:486](../../../backend/app/routers/users.py#L486). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -642,7 +642,7 @@ W17b ADM-01: pending (and expired) invitations, newest first. Never a token. ADM Declared before ``/{user_id}`` so ``invitations`` is not parsed as a user id. -Source: [backend/app/routers/users.py:173](../../../backend/app/routers/users.py#L173). +Source: [backend/app/routers/users.py:288](../../../backend/app/routers/users.py#L288). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -732,7 +732,7 @@ Issue a new link (new token, new expiry); the previous link stops working. ADMIN Also the only way to get a copyable link again: the raw token is never stored, so an old link cannot be shown twice. -Source: [backend/app/routers/users.py:561](../../../backend/app/routers/users.py#L561). +Source: [backend/app/routers/users.py:715](../../../backend/app/routers/users.py#L715). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -819,7 +819,7 @@ Revoke Invitation Kill an invitation link. A used invitation cannot be revoked (the account exists). ADMIN. -Source: [backend/app/routers/users.py:543](../../../backend/app/routers/users.py#L543). +Source: [backend/app/routers/users.py:697](../../../backend/app/routers/users.py#L697). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -910,7 +910,7 @@ W17b ADM-01: only ``sha256(token)`` is stored; the link carries the token in a URL fragment; the link is emailed when SMTP is configured and always returned so the admin can copy it (the offline path). -Source: [backend/app/routers/users.py:394](../../../backend/app/routers/users.py#L394). +Source: [backend/app/routers/users.py:537](../../../backend/app/routers/users.py#L537). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -998,7 +998,7 @@ Get User Get a specific user by ID. -Source: [backend/app/routers/users.py:190](../../../backend/app/routers/users.py#L190). +Source: [backend/app/routers/users.py:305](../../../backend/app/routers/users.py#L305). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -1085,7 +1085,7 @@ Update User Profile Update a user's profile attributes. Requires ADMIN. Only non-None fields are applied. -Source: [backend/app/routers/users.py:263](../../../backend/app/routers/users.py#L263). +Source: [backend/app/routers/users.py:382](../../../backend/app/routers/users.py#L382). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -1186,7 +1186,7 @@ Get User Access Audit Return access audit trail for a specific user. -Source: [backend/app/routers/users.py:668](../../../backend/app/routers/users.py#L668). +Source: [backend/app/routers/users.py:824](../../../backend/app/routers/users.py#L824). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -1461,7 +1461,7 @@ Get User Memberships Return all project memberships for a user in a single query. Replaces the N+1 pattern of fetching each project's members individually. -Source: [backend/app/routers/users.py:640](../../../backend/app/routers/users.py#L640). +Source: [backend/app/routers/users.py:795](../../../backend/app/routers/users.py#L795). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -1537,7 +1537,7 @@ References such as `#/components/schemas/...` resolve in [schemas](../schemas.md Handler return expressions (source excerpts, not an inferred wire schema): ```python -[{'project_id': str(pm.project_id), 'project_name': p.name, 'role': _normalize_user_role(pm.role).value, 'created_at': pm.created_at.isoformat() if pm.created_at else None} for pm, p in rows] +[{'project_id': str(pm.project_id), 'project_name': p.name, 'role': _normalize_user_role(pm.role).value, 'additional_roles': _stored_extras(getattr(pm, 'additional_roles', None)), 'created_at': pm.created_at.isoformat() if pm.created_at else None} for pm, p in rows] ``` Contract limit: at least one response has an unstructured schema. Read the linked handler/serializer for emitted fields; the empty schema is not a promise of an empty JSON object. @@ -1552,7 +1552,7 @@ The administrator never sees or sets the password. Older unused links for the user stop working. Refused for the caller's own account (change-password exists for that). Audited without the token. -Source: [backend/app/routers/users.py:597](../../../backend/app/routers/users.py#L597). +Source: [backend/app/routers/users.py:752](../../../backend/app/routers/users.py#L752). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -1641,7 +1641,7 @@ Update User Role Update a user's global role. Requires ADMIN. -Source: [backend/app/routers/users.py:204](../../../backend/app/routers/users.py#L204). +Source: [backend/app/routers/users.py:319](../../../backend/app/routers/users.py#L319). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -1739,7 +1739,7 @@ Update User Status Activate or deactivate a user account. Requires ADMIN. -Source: [backend/app/routers/users.py:231](../../../backend/app/routers/users.py#L231). +Source: [backend/app/routers/users.py:350](../../../backend/app/routers/users.py#L350). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. diff --git a/docs/reference/data-dictionary.md b/docs/reference/data-dictionary.md index 62b5903bd..2cb9c804f 100644 --- a/docs/reference/data-dictionary.md +++ b/docs/reference/data-dictionary.md @@ -93,7 +93,7 @@ Current SQLAlchemy metadata, without a database connection. All columns, server/ | [project_insights](#project_insights) | ProjectInsight | 16 | | [project_llm_quota](#project_llm_quota) | ProjectLlmQuota | 12 | | [project_llm_usage](#project_llm_usage) | ProjectLlmUsage | 10 | -| [project_members](#project_members) | ProjectMember | 6 | +| [project_members](#project_members) | ProjectMember | 7 | | [project_retention_policies](#project_retention_policies) | ProjectRetentionPolicy | 15 | | [project_workflow_defaults](#project_workflow_defaults) | ProjectWorkflowDefault | 6 | | [projects](#projects) | Project | 24 | @@ -164,9 +164,9 @@ Current SQLAlchemy metadata, without a database connection. All columns, server/ | [test_suites](#test_suites) | TestSuite | 8 | | [timeline_notes](#timeline_notes) | TimelineNote | 9 | | [upload_dispatch_receipts](#upload_dispatch_receipts) | UploadDispatchReceipt | 17 | -| [user_invitations](#user_invitations) | UserInvitation | 13 | +| [user_invitations](#user_invitations) | UserInvitation | 14 | | [user_ui_dismissals](#user_ui_dismissals) | UserUIDismissal | 4 | -| [users](#users) | User | 20 | +| [users](#users) | User | 21 | | [value_metric_assumptions](#value_metric_assumptions) | ValueMetricAssumptions | 8 | | [webhook_deliveries](#webhook_deliveries) | WebhookDelivery | 18 | | [webhook_subscriptions](#webhook_subscriptions) | WebhookSubscription | 20 | @@ -175,7 +175,7 @@ Current SQLAlchemy metadata, without a database connection. All columns, server/ ## access_audit_logs -[backend/app/models/postgres.py:4847](../../backend/app/models/postgres.py#L4847) +[backend/app/models/postgres.py:4863](../../backend/app/models/postgres.py#L4863) Append-only audit trail for user role and project membership changes. @@ -220,7 +220,7 @@ Constraints and indexes: ## agent_action_dispatch_outbox -[backend/app/models/postgres.py:6657](../../backend/app/models/postgres.py#L6657) +[backend/app/models/postgres.py:6675](../../backend/app/models/postgres.py#L6675) Durable delivery intent for approved actions; never contains prompts. @@ -252,7 +252,7 @@ Constraints and indexes: ## agent_action_ledger -[backend/app/models/postgres.py:6198](../../backend/app/models/postgres.py#L6198) +[backend/app/models/postgres.py:6216](../../backend/app/models/postgres.py#L6216) Append-only proposal/execution ledger for agent-originated actions. @@ -303,7 +303,7 @@ Constraints and indexes: ## agent_child_dispatch_outbox -[backend/app/models/postgres.py:2425](../../backend/app/models/postgres.py#L2425) +[backend/app/models/postgres.py:2438](../../backend/app/models/postgres.py#L2438) Durable dispatch record for a planner-spawned Investigator child. @@ -339,7 +339,7 @@ Constraints and indexes: ## agent_configs -[backend/app/models/postgres.py:6444](../../backend/app/models/postgres.py#L6444) +[backend/app/models/postgres.py:6462](../../backend/app/models/postgres.py#L6462) A project's configuration of one agent (architecture E4.1, section 4.2). @@ -371,7 +371,7 @@ Constraints and indexes: ## agent_investigations -[backend/app/models/postgres.py:2281](../../backend/app/models/postgres.py#L2281) +[backend/app/models/postgres.py:2294](../../backend/app/models/postgres.py#L2294) One Investigator run against a test run (shadow mode). @@ -440,7 +440,7 @@ Constraints and indexes: ## agent_invocations -[backend/app/models/postgres.py:6364](../../backend/app/models/postgres.py#L6364) +[backend/app/models/postgres.py:6382](../../backend/app/models/postgres.py#L6382) One call of a single agent through the public API (architecture E1.2). @@ -485,7 +485,7 @@ Constraints and indexes: ## agent_memory_entries -[backend/app/models/postgres.py:6143](../../backend/app/models/postgres.py#L6143) +[backend/app/models/postgres.py:6161](../../backend/app/models/postgres.py#L6161) Unified memory linking a run/snapshot to related entities (clusters, defects, release decisions, ownership) for project-scoped historical recall. @@ -533,7 +533,7 @@ Constraints and indexes: ## agent_pipeline_runs -[backend/app/models/postgres.py:2595](../../backend/app/models/postgres.py#L2595) +[backend/app/models/postgres.py:2608](../../backend/app/models/postgres.py#L2608) Tracks a single execution of the multi-agent pipeline for a test run. @@ -585,7 +585,7 @@ stages: Mapped[list['AgentStageResult']] = relationship('AgentStageResult', back ## agent_runs -[backend/app/models/postgres.py:2491](../../backend/app/models/postgres.py#L2491) +[backend/app/models/postgres.py:2504](../../backend/app/models/postgres.py#L2504) Agent activity ledger: one row per agent execution — what ran, why, what it proposed, what it actually did @@ -623,7 +623,7 @@ Constraints and indexes: ## agent_stage_results -[backend/app/models/postgres.py:2699](../../backend/app/models/postgres.py#L2699) +[backend/app/models/postgres.py:2712](../../backend/app/models/postgres.py#L2712) Per-stage result for an AgentPipelineRun. @@ -686,7 +686,7 @@ pipeline_run: Mapped['AgentPipelineRun'] = relationship('AgentPipelineRun', back ## ai_analysis -[backend/app/models/postgres.py:1534](../../backend/app/models/postgres.py#L1534) +[backend/app/models/postgres.py:1547](../../backend/app/models/postgres.py#L1547) Stored AI triage results per test case: the LATEST answer (fast read). @@ -729,7 +729,7 @@ test_case: Mapped['TestCase'] = relationship('TestCase', back_populates='ai_anal ## ai_analysis_versions -[backend/app/models/postgres.py:1576](../../backend/app/models/postgres.py#L1576) +[backend/app/models/postgres.py:1589](../../backend/app/models/postgres.py#L1589) One immutable version of a test result's AI analysis (AIH-01, migration 0205). @@ -792,7 +792,7 @@ Constraints and indexes: ## ai_eval_baselines -[backend/app/models/postgres.py:5860](../../backend/app/models/postgres.py#L5860) +[backend/app/models/postgres.py:5878](../../backend/app/models/postgres.py#L5878) Baseline metrics per agent/task_type for comparison gating. @@ -830,7 +830,7 @@ Constraints and indexes: ## ai_eval_datasets -[backend/app/models/postgres.py:5734](../../backend/app/models/postgres.py#L5734) +[backend/app/models/postgres.py:5752](../../backend/app/models/postgres.py#L5752) Labeled evaluation dataset for measuring AI quality over time. @@ -855,7 +855,7 @@ Constraints and indexes: ## ai_eval_gate_runs -[backend/app/models/postgres.py:5897](../../backend/app/models/postgres.py#L5897) +[backend/app/models/postgres.py:5915](../../backend/app/models/postgres.py#L5915) Historical record of an agent-stack release gate decision. @@ -891,7 +891,7 @@ Constraints and indexes: ## ai_eval_item_outputs -[backend/app/models/postgres.py:5821](../../backend/app/models/postgres.py#L5821) +[backend/app/models/postgres.py:5839](../../backend/app/models/postgres.py#L5839) One replayed item of a candidate evaluation run (W16 AGT-09, 0231). @@ -926,7 +926,7 @@ Constraints and indexes: ## ai_eval_reviewer_quality -[backend/app/models/postgres.py:5964](../../backend/app/models/postgres.py#L5964) +[backend/app/models/postgres.py:5982](../../backend/app/models/postgres.py#L5982) A G3 reviewer-quality observation batch or scheduled 30-day rollup. @@ -971,7 +971,7 @@ Constraints and indexes: ## ai_eval_runs -[backend/app/models/postgres.py:5754](../../backend/app/models/postgres.py#L5754) +[backend/app/models/postgres.py:5772](../../backend/app/models/postgres.py#L5772) Record of running an evaluation dataset against a model version. @@ -1022,7 +1022,7 @@ Constraints and indexes: ## ai_eval_shadow_pairs -[backend/app/models/postgres.py:5934](../../backend/app/models/postgres.py#L5934) +[backend/app/models/postgres.py:5952](../../backend/app/models/postgres.py#L5952) A bounded live tier pair awaiting a human or golden-input label. @@ -1057,7 +1057,7 @@ Constraints and indexes: ## ai_feedback -[backend/app/models/postgres.py:2830](../../backend/app/models/postgres.py#L2830) +[backend/app/models/postgres.py:2843](../../backend/app/models/postgres.py#L2843) Human feedback on AI triage results — the primary training signal. @@ -1098,7 +1098,7 @@ Constraints and indexes: ## api_keys -[backend/app/models/postgres.py:4575](../../backend/app/models/postgres.py#L4575) +[backend/app/models/postgres.py:4591](../../backend/app/models/postgres.py#L4591) Scoped personal access token (PAT) for CI/CD and API access. @@ -1134,7 +1134,7 @@ Constraints and indexes: ## app_settings -[backend/app/models/postgres.py:4502](../../backend/app/models/postgres.py#L4502) +[backend/app/models/postgres.py:4515](../../backend/app/models/postgres.py#L4515) Key-value store for application-level configuration (e.g. SMTP settings). @@ -1155,7 +1155,7 @@ Constraints and indexes: ## canonical_test_cases -[backend/app/models/postgres.py:1242](../../backend/app/models/postgres.py#L1242) +[backend/app/models/postgres.py:1255](../../backend/app/models/postgres.py#L1255) Project-scoped test case identity. @@ -1221,7 +1221,7 @@ attachments: Mapped[list['TestAttachment']] = relationship('TestAttachment', bac ## chat_messages -[backend/app/models/postgres.py:2806](../../backend/app/models/postgres.py#L2806) +[backend/app/models/postgres.py:2819](../../backend/app/models/postgres.py#L2819) A single message in a ChatSession. @@ -1248,7 +1248,7 @@ session: Mapped['ChatSession'] = relationship('ChatSession', back_populates='mes ## chat_sessions -[backend/app/models/postgres.py:2784](../../backend/app/models/postgres.py#L2784) +[backend/app/models/postgres.py:2797](../../backend/app/models/postgres.py#L2797) A conversation session between a user and the Conversation Agent. @@ -1281,7 +1281,7 @@ messages: Mapped[list['ChatMessage']] = relationship('ChatMessage', back_populat ## classification_hints -[backend/app/models/postgres.py:5395](../../backend/app/models/postgres.py#L5395) +[backend/app/models/postgres.py:5413](../../backend/app/models/postgres.py#L5413) A QA lead's rule: " contains -> " for one project. @@ -1315,7 +1315,7 @@ Constraints and indexes: ## compliance_packs -[backend/app/models/postgres.py:7504](../../backend/app/models/postgres.py#L7504) +[backend/app/models/postgres.py:7522](../../backend/app/models/postgres.py#L7522) Generated compliance export pack (ZIP) for a release decision. @@ -1349,7 +1349,7 @@ Constraints and indexes: ## compliance_signing_keys -[backend/app/models/postgres.py:7581](../../backend/app/models/postgres.py#L7581) +[backend/app/models/postgres.py:7599](../../backend/app/models/postgres.py#L7599) The deployment's Ed25519 compliance-pack signing keys (migration 0225, W11 REL-11, D14). @@ -1379,7 +1379,7 @@ Constraints and indexes: ## coverage_snapshots -[backend/app/models/postgres.py:1834](../../backend/app/models/postgres.py#L1834) +[backend/app/models/postgres.py:1847](../../backend/app/models/postgres.py#L1847) One coverage snapshot a project a UTC day (W08 TRND-07, migration 0217). @@ -1415,7 +1415,7 @@ Constraints and indexes: ## decision_report_eval_cycles -[backend/app/models/postgres.py:6026](../../backend/app/models/postgres.py#L6026) +[backend/app/models/postgres.py:6044](../../backend/app/models/postgres.py#L6044) Durable evidence for a report-level evaluation corpus cycle. @@ -1467,7 +1467,7 @@ Constraints and indexes: ## decision_report_feedback -[backend/app/models/postgres.py:2870](../../backend/app/models/postgres.py#L2870) +[backend/app/models/postgres.py:2883](../../backend/app/models/postgres.py#L2883) Structured human feedback bound to one immutable DecisionReport version. @@ -1507,7 +1507,7 @@ Constraints and indexes: ## decision_report_supersession_requests -[backend/app/models/postgres.py:6088](../../backend/app/models/postgres.py#L6088) +[backend/app/models/postgres.py:6106](../../backend/app/models/postgres.py#L6106) Durable, idempotent request to publish a child-enriched report version. @@ -1546,7 +1546,7 @@ Constraints and indexes: ## deep_findings -[backend/app/models/postgres.py:3012](../../backend/app/models/postgres.py#L3012) +[backend/app/models/postgres.py:3025](../../backend/app/models/postgres.py#L3025) Deep investigation result per failure cluster. @@ -1584,7 +1584,7 @@ Constraints and indexes: ## defect_candidates -[backend/app/models/postgres.py:1805](../../backend/app/models/postgres.py#L1805) +[backend/app/models/postgres.py:1818](../../backend/app/models/postgres.py#L1818) Staging area for defect candidates before promotion to full defects. @@ -1620,7 +1620,7 @@ Constraints and indexes: ## defects -[backend/app/models/postgres.py:1674](../../backend/app/models/postgres.py#L1674) +[backend/app/models/postgres.py:1687](../../backend/app/models/postgres.py#L1687) Defect records linked to test cases or failure clusters. @@ -1685,7 +1685,7 @@ approver: Mapped[Optional['User']] = relationship('User', foreign_keys=[approved ## deletion_jobs -[backend/app/models/postgres.py:7883](../../backend/app/models/postgres.py#L7883) +[backend/app/models/postgres.py:7901](../../backend/app/models/postgres.py#L7901) One record of a deletion actually happening (migration 0147, S2b). @@ -1764,7 +1764,7 @@ Constraints and indexes: ## digest_subscriptions -[backend/app/models/postgres.py:5681](../../backend/app/models/postgres.py#L5681) +[backend/app/models/postgres.py:5699](../../backend/app/models/postgres.py#L5699) User subscription to a scheduled or event-driven report delivery. @@ -1808,7 +1808,7 @@ Constraints and indexes: ## dismissed_duplicate_pairs -[backend/app/models/postgres.py:3468](../../backend/app/models/postgres.py#L3468) +[backend/app/models/postgres.py:3481](../../backend/app/models/postgres.py#L3481) Suppression record so a dismissed duplicate pair stays dismissed (Phase 4). @@ -1839,7 +1839,7 @@ Constraints and indexes: ## drop_folder_builds -[backend/app/models/postgres.py:8706](../../backend/app/models/postgres.py#L8706) +[backend/app/models/postgres.py:8724](../../backend/app/models/postgres.py#L8724) One build folder ``/runs//`` seen by the drop-folder watcher (W34 STRAT-13; migration 0254). @@ -1876,7 +1876,7 @@ Constraints and indexes: ## duplicate_test_case_candidates -[backend/app/models/postgres.py:3425](../../backend/app/models/postgres.py#L3425) +[backend/app/models/postgres.py:3438](../../backend/app/models/postgres.py#L3438) One detected near-duplicate PAIR of authored ManagedTestCases (Phase 4). @@ -1920,7 +1920,7 @@ Constraints and indexes: ## evidence_artifacts -[backend/app/models/postgres.py:4628](../../backend/app/models/postgres.py#L4628) +[backend/app/models/postgres.py:4644](../../backend/app/models/postgres.py#L4644) Tenant-bound immutable evidence captured from an executed tool. @@ -1968,7 +1968,7 @@ Constraints and indexes: ## failure_attribution -[backend/app/models/postgres.py:6911](../../backend/app/models/postgres.py#L6911) +[backend/app/models/postgres.py:6929](../../backend/app/models/postgres.py#L6929) @@ -1997,7 +1997,7 @@ Constraints and indexes: ## failure_clusters -[backend/app/models/postgres.py:2936](../../backend/app/models/postgres.py#L2936) +[backend/app/models/postgres.py:2949](../../backend/app/models/postgres.py#L2949) Semantic cluster of failures grouped by root-cause similarity. @@ -2025,7 +2025,7 @@ Constraints and indexes: ## feature_flags -[backend/app/models/postgres.py:6719](../../backend/app/models/postgres.py#L6719) +[backend/app/models/postgres.py:6737](../../backend/app/models/postgres.py#L6737) Named capability toggle gated by project, role, and rollout percent. @@ -2050,7 +2050,7 @@ Constraints and indexes: ## federated_identities -[backend/app/models/postgres.py:5124](../../backend/app/models/postgres.py#L5124) +[backend/app/models/postgres.py:5142](../../backend/app/models/postgres.py#L5142) Links an external IdP subject to a local User. @@ -2077,7 +2077,7 @@ Constraints and indexes: ## fix_attempts -[backend/app/models/postgres.py:2529](../../backend/app/models/postgres.py#L2529) +[backend/app/models/postgres.py:2542](../../backend/app/models/postgres.py#L2542) One (fixer run, candidate test, attempt) of the Fixer. @@ -2133,7 +2133,7 @@ Constraints and indexes: ## flaky_classifier_calibration -[backend/app/models/postgres.py:7085](../../backend/app/models/postgres.py#L7085) +[backend/app/models/postgres.py:7103](../../backend/app/models/postgres.py#L7103) @@ -2158,7 +2158,7 @@ Constraints and indexes: ## flaky_coach_results -[backend/app/models/postgres.py:4956](../../backend/app/models/postgres.py#L4956) +[backend/app/models/postgres.py:4974](../../backend/app/models/postgres.py#L4974) Project-level flaky test coaching results with quarantine recommendations. @@ -2194,7 +2194,7 @@ Constraints and indexes: ## flaky_detection_state -[backend/app/models/postgres.py:7121](../../backend/app/models/postgres.py#L7121) +[backend/app/models/postgres.py:7139](../../backend/app/models/postgres.py#L7139) @@ -2224,7 +2224,7 @@ Constraints and indexes: ## flaky_quarantine_requests -[backend/app/models/postgres.py:7624](../../backend/app/models/postgres.py#L7624) +[backend/app/models/postgres.py:7642](../../backend/app/models/postgres.py#L7642) Workflow record for proposing, approving, and enforcing quarantine of a flaky test. @@ -2288,7 +2288,7 @@ Constraints and indexes: ## flaky_score -[backend/app/models/postgres.py:7051](../../backend/app/models/postgres.py#L7051) +[backend/app/models/postgres.py:7069](../../backend/app/models/postgres.py#L7069) @@ -2315,7 +2315,7 @@ Constraints and indexes: ## generation_batches -[backend/app/models/postgres.py:3733](../../backend/app/models/postgres.py#L3733) +[backend/app/models/postgres.py:3746](../../backend/app/models/postgres.py#L3746) One row per AI test-case generation request (grounded or raw). @@ -2349,7 +2349,7 @@ Constraints and indexes: ## generation_case_sources -[backend/app/models/postgres.py:3764](../../backend/app/models/postgres.py#L3764) +[backend/app/models/postgres.py:3777](../../backend/app/models/postgres.py#L3777) Maps a generated ManagedTestCase to the KnowledgeChunks cited for it. @@ -2382,7 +2382,7 @@ Constraints and indexes: ## github_integrations -[backend/app/models/postgres.py:7356](../../backend/app/models/postgres.py#L7356) +[backend/app/models/postgres.py:7374](../../backend/app/models/postgres.py#L7374) Per-project GitHub Checks API integration config. @@ -2415,7 +2415,7 @@ Constraints and indexes: ## gitlab_integrations -[backend/app/models/postgres.py:7421](../../backend/app/models/postgres.py#L7421) +[backend/app/models/postgres.py:7439](../../backend/app/models/postgres.py#L7439) Per-project GitLab integration config (PMF Epic 3 US-3.1). @@ -2452,7 +2452,7 @@ Constraints and indexes: ## identity_events -[backend/app/models/postgres.py:5196](../../backend/app/models/postgres.py#L5196) +[backend/app/models/postgres.py:5214](../../backend/app/models/postgres.py#L5214) Append-only audit trail for SSO, SCIM, and identity lifecycle events. @@ -2502,7 +2502,7 @@ Constraints and indexes: ## insight_detector_states -[backend/app/models/postgres.py:1987](../../backend/app/models/postgres.py#L1987) +[backend/app/models/postgres.py:2000](../../backend/app/models/postgres.py#L2000) The last evaluation of each detector for each project (W23a FAIL-11, migration 0243). @@ -2528,7 +2528,7 @@ Constraints and indexes: ## instance_retention_policy -[backend/app/models/postgres.py:8466](../../backend/app/models/postgres.py#L8466) +[backend/app/models/postgres.py:8484](../../backend/app/models/postgres.py#L8484) The instance-wide retention defaults (W22b ACT-06, migration 0242). @@ -2569,7 +2569,7 @@ Constraints and indexes: ## integration_health_checks -[backend/app/models/postgres.py:4774](../../backend/app/models/postgres.py#L4774) +[backend/app/models/postgres.py:4790](../../backend/app/models/postgres.py#L4790) Integration health status: the latest snapshot per (provider, scope). @@ -2594,7 +2594,7 @@ Constraints and indexes: ## integration_probe_results -[backend/app/models/postgres.py:4793](../../backend/app/models/postgres.py#L4793) +[backend/app/models/postgres.py:4809](../../backend/app/models/postgres.py#L4809) Historical record of each integration health probe (OPS-01). @@ -2618,7 +2618,7 @@ Constraints and indexes: ## knowledge_chunks -[backend/app/models/postgres.py:3703](../../backend/app/models/postgres.py#L3703) +[backend/app/models/postgres.py:3716](../../backend/app/models/postgres.py#L3716) PostgreSQL metadata for each chunk stored in ChromaDB knowledge_chunks collection. @@ -2649,7 +2649,7 @@ Constraints and indexes: ## knowledge_sources -[backend/app/models/postgres.py:3642](../../backend/app/models/postgres.py#L3642) +[backend/app/models/postgres.py:3655](../../backend/app/models/postgres.py#L3655) Registry of external knowledge sources attached to a project for RAG-grounded test generation. @@ -2684,7 +2684,7 @@ Constraints and indexes: ## knowledge_sync_events -[backend/app/models/postgres.py:3677](../../backend/app/models/postgres.py#L3677) +[backend/app/models/postgres.py:3690](../../backend/app/models/postgres.py#L3690) Audit log for every sync attempt on a KnowledgeSource. @@ -2713,7 +2713,7 @@ Constraints and indexes: ## live_event_receipts -[backend/app/models/postgres.py:600](../../backend/app/models/postgres.py#L600) +[backend/app/models/postgres.py:613](../../backend/app/models/postgres.py#L613) Per-event idempotency receipt and bounded sanitized attempt evidence. @@ -2740,7 +2740,7 @@ Constraints and indexes: ## live_ingestion_attempts -[backend/app/models/postgres.py:567](../../backend/app/models/postgres.py#L567) +[backend/app/models/postgres.py:580](../../backend/app/models/postgres.py#L580) Durable record that an accepted live batch reached projection. @@ -2768,7 +2768,7 @@ Constraints and indexes: ## live_projection_checkpoints -[backend/app/models/postgres.py:629](../../backend/app/models/postgres.py#L629) +[backend/app/models/postgres.py:642](../../backend/app/models/postgres.py#L642) Committed per-run high watermark for Redis evidence projection. @@ -2788,7 +2788,7 @@ Constraints and indexes: ## live_sessions -[backend/app/models/postgres.py:3811](../../backend/app/models/postgres.py#L3811) +[backend/app/models/postgres.py:3824](../../backend/app/models/postgres.py#L3824) Tracks an active live test execution session from a client machine. @@ -2835,7 +2835,7 @@ Constraints and indexes: ## managed_test_cases -[backend/app/models/postgres.py:3143](../../backend/app/models/postgres.py#L3143) +[backend/app/models/postgres.py:3156](../../backend/app/models/postgres.py#L3156) Manually authored or AI-generated test case with full lifecycle management. @@ -2917,7 +2917,7 @@ Constraints and indexes: ## mfa_recovery_codes -[backend/app/models/postgres.py:238](../../backend/app/models/postgres.py#L238) +[backend/app/models/postgres.py:251](../../backend/app/models/postgres.py#L251) Single-use recovery code for a user with TOTP enabled. @@ -2950,7 +2950,7 @@ Constraints and indexes: ## model_versions -[backend/app/models/postgres.py:2899](../../backend/app/models/postgres.py#L2899) +[backend/app/models/postgres.py:2912](../../backend/app/models/postgres.py#L2912) Registry of fine-tuned model versions per training track. @@ -2983,7 +2983,7 @@ Constraints and indexes: ## nightly_job_observations -[backend/app/models/postgres.py:6705](../../backend/app/models/postgres.py#L6705) +[backend/app/models/postgres.py:6723](../../backend/app/models/postgres.py#L6723) Bounded operational state shared by the scheduled workers and API. @@ -3003,7 +3003,7 @@ Constraints and indexes: ## notification_logs -[backend/app/models/postgres.py:3079](../../backend/app/models/postgres.py#L3079) +[backend/app/models/postgres.py:3092](../../backend/app/models/postgres.py#L3092) Audit trail for every dispatched notification. @@ -3048,7 +3048,7 @@ Constraints and indexes: ## notification_preferences -[backend/app/models/postgres.py:2141](../../backend/app/models/postgres.py#L2141) +[backend/app/models/postgres.py:2154](../../backend/app/models/postgres.py#L2154) Per-user, per-channel notification configuration. @@ -3076,7 +3076,7 @@ Constraints and indexes: ## notification_test_states -[backend/app/models/postgres.py:2169](../../backend/app/models/postgres.py#L2169) +[backend/app/models/postgres.py:2182](../../backend/app/models/postgres.py#L2182) Per-(project, test_fingerprint) rolling state for transition-based notifications (PMF US-7.1). @@ -3112,7 +3112,7 @@ Constraints and indexes: ## notification_transition_policies -[backend/app/models/postgres.py:2215](../../backend/app/models/postgres.py#L2215) +[backend/app/models/postgres.py:2228](../../backend/app/models/postgres.py#L2228) Per-project policy for transition-based notifications (PMF US-7.1). @@ -3141,7 +3141,7 @@ Constraints and indexes: ## password_reset_tokens -[backend/app/models/postgres.py:4913](../../backend/app/models/postgres.py#L4913) +[backend/app/models/postgres.py:4931](../../backend/app/models/postgres.py#L4931) A single-use password-reset link (W17b ADM-02, migration 0233). Hash only. @@ -3169,7 +3169,7 @@ Constraints and indexes: ## perf_baselines -[backend/app/models/postgres.py:7171](../../backend/app/models/postgres.py#L7171) +[backend/app/models/postgres.py:7189](../../backend/app/models/postgres.py#L7189) Per-test running duration statistics. @@ -3199,7 +3199,7 @@ Constraints and indexes: ## pipeline_event_outbox -[backend/app/models/postgres.py:2665](../../backend/app/models/postgres.py#L2665) +[backend/app/models/postgres.py:2678](../../backend/app/models/postgres.py#L2678) Project-scoped event intent awaiting idempotent Mongo materialization. @@ -3241,7 +3241,7 @@ Constraints and indexes: ## product_usage_events -[backend/app/models/postgres.py:4830](../../backend/app/models/postgres.py#L4830) +[backend/app/models/postgres.py:4846](../../backend/app/models/postgres.py#L4846) Tracks product adoption events for analytics. @@ -3265,7 +3265,7 @@ Constraints and indexes: ## project_activity_events -[backend/app/models/postgres.py:8557](../../backend/app/models/postgres.py#L8557) +[backend/app/models/postgres.py:8575](../../backend/app/models/postgres.py#L8575) Append-only, project-scoped product feed of everything that happens. @@ -3343,7 +3343,7 @@ Constraints and indexes: ## project_data_jobs -[backend/app/models/postgres.py:8008](../../backend/app/models/postgres.py#L8008) +[backend/app/models/postgres.py:8026](../../backend/app/models/postgres.py#L8026) One project export or import (W24 ADM-05 phase 1: settings + catalog; migration 0247). @@ -3402,7 +3402,7 @@ Constraints and indexes: ## project_insights -[backend/app/models/postgres.py:1912](../../backend/app/models/postgres.py#L1912) +[backend/app/models/postgres.py:1925](../../backend/app/models/postgres.py#L1925) One EPISODE of one detector firing on one subject (W23a FAIL-11, migration 0243). @@ -3454,7 +3454,7 @@ Constraints and indexes: ## project_llm_quota -[backend/app/models/postgres.py:6788](../../backend/app/models/postgres.py#L6788) +[backend/app/models/postgres.py:6806](../../backend/app/models/postgres.py#L6806) Per-project LLM spend config used by the usage-based billing gate. @@ -3482,7 +3482,7 @@ Constraints and indexes: ## project_llm_usage -[backend/app/models/postgres.py:8517](../../backend/app/models/postgres.py#L8517) +[backend/app/models/postgres.py:8535](../../backend/app/models/postgres.py#L8535) Running per-period LLM cost meter for a project. @@ -3513,7 +3513,7 @@ Constraints and indexes: ## project_members -[backend/app/models/postgres.py:4559](../../backend/app/models/postgres.py#L4559) +[backend/app/models/postgres.py:4572](../../backend/app/models/postgres.py#L4572) Per-project role assignment for a user. @@ -3525,6 +3525,7 @@ Per-project role assignment for a user. | `role` | `VARCHAR(20)` | False | False | `application=QA_ENGINEER` | | | `created_at` | `DATETIME` | False | False | `server=now()` | | | `source` | `VARCHAR(80)` | True | False | `—` | | +| `additional_roles` | `JSON` | True | False | `—` | | Constraints and indexes: @@ -3535,7 +3536,7 @@ Constraints and indexes: ## project_retention_policies -[backend/app/models/postgres.py:8365](../../backend/app/models/postgres.py#L8365) +[backend/app/models/postgres.py:8383](../../backend/app/models/postgres.py#L8383) Per-project data retention policy (PMF US-11.4, migration 0113). @@ -3614,7 +3615,7 @@ Constraints and indexes: ## project_workflow_defaults -[backend/app/models/postgres.py:6571](../../backend/app/models/postgres.py#L6571) +[backend/app/models/postgres.py:6589](../../backend/app/models/postgres.py#L6589) A project's default workflow for one base (W14 AGT-08, migration 0230). @@ -3645,7 +3646,7 @@ Constraints and indexes: ## projects -[backend/app/models/postgres.py:265](../../backend/app/models/postgres.py#L265) +[backend/app/models/postgres.py:278](../../backend/app/models/postgres.py#L278) @@ -3697,7 +3698,7 @@ canonical_test_cases: Mapped[list['CanonicalTestCase']] = relationship('Canonica ## quarantine_lifecycle_policies -[backend/app/models/postgres.py:7760](../../backend/app/models/postgres.py#L7760) +[backend/app/models/postgres.py:7778](../../backend/app/models/postgres.py#L7778) Per-project quarantine lifecycle configuration (PMF US-5.4/5.5/5.6). @@ -3729,7 +3730,7 @@ Constraints and indexes: ## refresh_token_records -[backend/app/models/postgres.py:5321](../../backend/app/models/postgres.py#L5321) +[backend/app/models/postgres.py:5339](../../backend/app/models/postgres.py#L5339) Server-side record of issued refresh tokens for rotation and replay detection. @@ -3759,7 +3760,7 @@ Constraints and indexes: ## release_attribution_rules -[backend/app/models/postgres.py:4338](../../backend/app/models/postgres.py#L4338) +[backend/app/models/postgres.py:4351](../../backend/app/models/postgres.py#L4351) Per-project rule mapping run metadata to a release (migration 0154). @@ -3791,7 +3792,7 @@ Constraints and indexes: ## release_decisions -[backend/app/models/postgres.py:3045](../../backend/app/models/postgres.py#L3045) +[backend/app/models/postgres.py:3058](../../backend/app/models/postgres.py#L3058) Release gate decision produced by ReleaseRiskAgent. @@ -3831,7 +3832,7 @@ Constraints and indexes: ## release_gate_decisions -[backend/app/models/postgres.py:5503](../../backend/app/models/postgres.py#L5503) +[backend/app/models/postgres.py:5521](../../backend/app/models/postgres.py#L5521) A go/no-go verdict for a RELEASE, not for a run (migration 0156). @@ -3904,7 +3905,7 @@ Constraints and indexes: ## release_gate_policies -[backend/app/models/postgres.py:5242](../../backend/app/models/postgres.py#L5242) +[backend/app/models/postgres.py:5260](../../backend/app/models/postgres.py#L5260) Versioned release gate policy — per-project or system-wide default. @@ -3938,7 +3939,7 @@ Constraints and indexes: ## release_outcomes -[backend/app/models/postgres.py:4288](../../backend/app/models/postgres.py#L4288) +[backend/app/models/postgres.py:4301](../../backend/app/models/postgres.py#L4301) A human-marked production incident or rollback for a release (E9.9). @@ -3965,7 +3966,7 @@ Constraints and indexes: ## release_phases -[backend/app/models/postgres.py:4384](../../backend/app/models/postgres.py#L4384) +[backend/app/models/postgres.py:4397](../../backend/app/models/postgres.py#L4397) A phase / milestone within a Release lifecycle. @@ -4001,7 +4002,7 @@ release: Mapped['Release'] = relationship('Release', back_populates='phases') ## release_test_run_links -[backend/app/models/postgres.py:4419](../../backend/app/models/postgres.py#L4419) +[backend/app/models/postgres.py:4432](../../backend/app/models/postgres.py#L4432) Links a test run to a release for metrics aggregation. @@ -4037,7 +4038,7 @@ release: Mapped['Release'] = relationship('Release', back_populates='test_run_li ## releases -[backend/app/models/postgres.py:4089](../../backend/app/models/postgres.py#L4089) +[backend/app/models/postgres.py:4102](../../backend/app/models/postgres.py#L4102) A software release tracked through the QA lifecycle. @@ -4094,7 +4095,7 @@ test_run_links: Mapped[list['ReleaseTestRunLink']] = relationship('ReleaseTestRu ## report_exports -[backend/app/models/postgres.py:8314](../../backend/app/models/postgres.py#L8314) +[backend/app/models/postgres.py:8332](../../backend/app/models/postgres.py#L8332) VIZ-607: one background export of a report (migration 0194). @@ -4135,7 +4136,7 @@ Constraints and indexes: ## report_share_links -[backend/app/models/postgres.py:5293](../../backend/app/models/postgres.py#L5293) +[backend/app/models/postgres.py:5311](../../backend/app/models/postgres.py#L5311) Time-limited share token for run intelligence reports. @@ -4171,7 +4172,7 @@ Constraints and indexes: ## requirement_coverage -[backend/app/models/postgres.py:3792](../../backend/app/models/postgres.py#L3792) +[backend/app/models/postgres.py:3805](../../backend/app/models/postgres.py#L3805) Tracks which requirements are covered/uncovered by a generation batch. @@ -4197,7 +4198,7 @@ Constraints and indexes: ## retention_holds -[backend/app/models/postgres.py:8228](../../backend/app/models/postgres.py#L8228) +[backend/app/models/postgres.py:8246](../../backend/app/models/postgres.py#L8246) A retention hold on a project, a release, a run or a compliance pack (W22a ACT-05, migration 0239). @@ -4253,7 +4254,7 @@ Constraints and indexes: ## review_requests -[backend/app/models/postgres.py:6266](../../backend/app/models/postgres.py#L6266) +[backend/app/models/postgres.py:6284](../../backend/app/models/postgres.py#L6284) One human review for one AI report-producing run (architecture section 8.1). @@ -4313,7 +4314,7 @@ Constraints and indexes: ## run_baselines -[backend/app/models/postgres.py:4696](../../backend/app/models/postgres.py#L4696) +[backend/app/models/postgres.py:4712](../../backend/app/models/postgres.py#L4712) Records which baseline was selected for a run and why. @@ -4342,7 +4343,7 @@ Constraints and indexes: ## run_cadence_windows -[backend/app/models/postgres.py:2099](../../backend/app/models/postgres.py#L2099) +[backend/app/models/postgres.py:2112](../../backend/app/models/postgres.py#L2112) What the cadence beat DECIDED for one expected window (W23a TRND-03, migration 0244). @@ -4378,7 +4379,7 @@ Constraints and indexes: ## run_cadences -[backend/app/models/postgres.py:2017](../../backend/app/models/postgres.py#L2017) +[backend/app/models/postgres.py:2030](../../backend/app/models/postgres.py#L2030) One expected run cadence: "a run of arrives by