From 7a9d9d935832d8b03dec39b4b34c528a268f76d2 Mon Sep 17 00:00:00 2001 From: Jasper Mayone Date: Thu, 12 Nov 2026 13:19:50 -0500 Subject: [PATCH 1/2] feat: read krater roles from the ganymede patch roles in weave's patches claim --- .env.example | 10 ++- CLAUDE.md | 13 ++-- README.md | 3 +- docs/SPEC.md | 5 +- docs/dev/production.md | 2 +- docs/dev/staging.md | 2 +- docs/weave-integration.md | 109 ++++++++++++++++++++++----- krater/config.py | 10 ++- krater/weave/live.py | 12 ++- krater/weave/roles.py | 72 +++++++++++++----- krater/weave/stub.py | 59 ++++++++++++--- krater/weave/stub_users.json | 15 +++- krater/weave/types.py | 3 +- tests/services/test_sign_in.py | 33 ++++++++ tests/services/test_slack_reviews.py | 30 ++++++++ tests/test_config.py | 18 +++++ tests/weave/test_live_client.py | 67 +++++++++++++++- tests/weave/test_roles.py | 86 +++++++++++++++++++++ tests/weave/test_stub_client.py | 43 +++++++++++ 19 files changed, 520 insertions(+), 72 deletions(-) diff --git a/.env.example b/.env.example index 1da2ab26..2003c7bd 100644 --- a/.env.example +++ b/.env.example @@ -24,9 +24,13 @@ KRATER_WEAVE_CLIENT_SECRET= KRATER_WEAVE_API_BASE_URL= KRATER_WEAVE_STUB_USERS_FILE= -# Krater's role keys on its Weave app, and the group slugs Krater falls back to when Weave sends no -# `roles` field at all. The defaults match the Weave setup in docs/weave-integration.md. There is no -# member role: everyone Weave lets use Krater is a Ganymede member. +# Krater's patch in Weave and its role keys there (the `patches` claim), Krater's legacy role keys on its +# Weave app, and the group slugs Krater falls back to when Weave sends no `roles` field at all. Krater +# holds the union of the patch roles and the app roles. The defaults match the Weave setup in +# docs/weave-integration.md. There is no member role: everyone Weave lets use Krater is a Ganymede member. +# KRATER_WEAVE_PATCH=ganymede +# KRATER_WEAVE_PATCH_ROLE_REVIEWER=krater:reviewer +# KRATER_WEAVE_PATCH_ROLE_ADMIN=krater:admin # KRATER_WEAVE_ROLE_REVIEWER=reviewer # KRATER_WEAVE_ROLE_ADMIN=admin # KRATER_WEAVE_GROUP_REVIEWER=krater-reviewers diff --git a/CLAUDE.md b/CLAUDE.md index 8d096ceb..3f806343 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -67,10 +67,13 @@ tests/ mirrors krater/ layout - **Primary keys are UUIDs** (`uuid.uuid4`), safe to show in URLs. - **Every Patchwork member is a Ganymede member.** Whoever Weave lets use the Krater app (it signs them in, or its directory returns them) holds `ganymede:member`; there is no member role in Weave. -- **Weave owns roles.** Krater's role keys in Weave are `reviewer` and `admin`, sent in the `roles` claim and in - directory records. Only when the `roles` field is absent does Krater fall back to the group slugs `krater-reviewers` - and `krater-admins`. `krater.weave.roles` is the one place that maps them to Krater's internal names - `ganymede:reviewer`, `ganymede:admin` (and adds `ganymede:member`); nothing else knows the keys or slugs. +- **Weave owns roles.** Krater's roles in Weave are the patch role keys `krater:reviewer` and `krater:admin` in the + patch `ganymede`, sent in the `patches` claim and in directory records. During the move from app roles, Krater also + reads its legacy app role keys `reviewer` and `admin` from the `roles` claim (and, only when `roles` is absent, the + group slugs `krater-reviewers` and `krater-admins`), and holds the union of both. A malformed `patches` value counts + as no patch role. `krater.weave.roles` is the one place that maps them to Krater's internal names + `ganymede:reviewer`, `ganymede:admin` (and adds `ganymede:member`); nothing else knows the keys, slugs or patch + slug. See `docs/weave-integration.md` "Patch roles" for the deploy order and the follow-up. Every state-changing action (`fresh_actor`, the Slack click path) re-checks Weave's directory by `sub` through `krater.services.users.authorize`, and fails closed if Weave is down. `users.roles_cached` is for display only. Krater has no role tables, no admin users page and no disable switch: those are done in Weave. @@ -78,7 +81,7 @@ tests/ mirrors krater/ layout other personal details: read those from Weave when needed (`krater.services.people`) and record who acted by Patchwork ID (`docs/weave-integration.md` "Member data"). - **All Weave access goes through `krater.weave`.** Nothing else imports httpx for Weave or knows Weave's URLs. - Krater asks for `openid profile email groups roles slack`, and calls the directory with a client_credentials token + Krater asks for `openid profile email groups roles slack patches`, and calls the directory with a client_credentials token of its own app (scope `directory`). Its token for Quilt (scope `quilt`) comes from `WeaveClient.quilt_token`, and its token for Stash (scope `stash`) from `WeaveClient.stash_token`. - **All Vast access goes through `krater.vast`**, and only from the worker: the organization's Vast key never diff --git a/README.md b/README.md index cef7348b..5feda954 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ The full stack (Postgres, a one-shot migration, the portal and the worker) also `docker compose up --build`. Every Patchwork member Weave lets use Krater is a member and can submit a proposal. Weave owns the other roles: a -Weave admin gives people or groups Krater's app roles `reviewer` and `admin`, and Krater reads them at sign-in and re-checks them with Weave's directory API before every action. In stub mode (the default for +Weave admin gives people or groups the Ganymede patch roles `krater:reviewer` and `krater:admin` (during the move, +Krater's old app roles `reviewer` and `admin` count too), and Krater reads them at sign-in and re-checks them with Weave's directory API before every action. In stub mode (the default for development) the fixture users in `krater/weave/stub_users.json` carry their roles. See `docs/weave-integration.md`. diff --git a/docs/SPEC.md b/docs/SPEC.md index afd83477..1aaeefa9 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -62,7 +62,7 @@ Three roles: A "logged in but can't submit" tier and a public/anonymous tier are still deferred. The gallery itself is public. **Authentication** is OIDC against Weave (Authorization Code + PKCE; Weave enforces PKCE). Krater asks for the scopes -`openid profile email groups roles slack`. All Weave access goes through one adapter module (`WeaveClient`) so Weave +`openid profile email groups roles slack patches`. All Weave access goes through one adapter module (`WeaveClient`) so Weave changes don't spread through the app. The contract is in [weave-integration.md](weave-integration.md). **Weave owns roles** (maintainer decision, Oct 7, 2026). Krater never stores a role as its own source of truth: @@ -76,6 +76,9 @@ changes don't spread through the app. The contract is in [weave-integration.md]( - The `roles` field is the source of truth. Only when Weave sends no `roles` field at all (absent, not empty) does Krater fall back to group slugs linked to the Krater app: `krater-reviewers` and `krater-admins`. The keys and slugs are settings (`KRATER_WEAVE_ROLE_*`, `KRATER_WEAVE_GROUP_*`). +- Weave is moving these roles to the Ganymede patch (weave#288): the patch role keys `krater:reviewer` and + `krater:admin` in the `patches` claim (settings `KRATER_WEAVE_PATCH`, `KRATER_WEAVE_PATCH_ROLE_*`). During the move + Krater holds the union of the patch roles and the app roles (`docs/weave-integration.md` "Patch roles"). - Inside Krater the roles keep the names `ganymede:member`, `ganymede:reviewer` and `ganymede:admin`, so review snapshots and approval policies read the same. `krater.weave` translates at the boundary. Later tiers (`ganymede:reviewer:`) will need a matching Weave role key. diff --git a/docs/dev/production.md b/docs/dev/production.md index cee4ebfb..102d2119 100644 --- a/docs/dev/production.md +++ b/docs/dev/production.md @@ -150,7 +150,7 @@ Production runs `hosts/weft/krater-production.nix` with compute off, and ships b - **Ports 80 and 443** open to the internet. Let's Encrypt needs port 80 to issue certificates. - **Weave** (production Weave, not staging), following [weave-integration.md](../weave-integration.md): - Krater's app has redirect URI `https:///auth/callback` and scopes - `openid profile email groups roles slack directory`. + `openid profile email groups roles slack patches directory`. - A Weave superadmin creates the roles `reviewer` and `admin` on it, and gives you `admin`. Members need no role. - **Slack:** the app's interactivity URL is `https:///slack/interactions` ([slack-setup.md](slack-setup.md)). - **Vast** (compute on only): the production API key, in a file only root can read, mounted into the worker alone diff --git a/docs/dev/staging.md b/docs/dev/staging.md index 8e81d592..dd02f2d2 100644 --- a/docs/dev/staging.md +++ b/docs/dev/staging.md @@ -33,7 +33,7 @@ At `http://localhost:3000/admin/oauth_applications`, create a **confidential** a `docs/weave-integration.md` "Setting up Weave for Krater"): - Redirect URI: `http://localhost:8000/auth/callback` -- Scopes: `openid profile email groups roles slack directory`. Krater uses `directory` for its own client_credentials +- Scopes: `openid profile email groups roles slack patches directory`. Krater uses `directory` for its own client_credentials token; without it the directory API answers 403. - Note the client id/secret for `KRATER_WEAVE_CLIENT_ID`/`KRATER_WEAVE_CLIENT_SECRET`. diff --git a/docs/weave-integration.md b/docs/weave-integration.md index fbe31b2e..db4559eb 100644 --- a/docs/weave-integration.md +++ b/docs/weave-integration.md @@ -15,6 +15,10 @@ Krater depends on this Weave work. All of it is merged on Weave `main`: - app-defined roles: [patchworklabsorg/weave#165](https://github.com/patchworklabsorg/weave/pull/165); - the directory API: [patchworklabsorg/weave#166](https://github.com/patchworklabsorg/weave/pull/166). +Patch roles (the `patches` scope and claim) need +[patchworklabsorg/weave#288](https://github.com/patchworklabsorg/weave/pull/288), which is not merged yet. See +"Patch roles" below for the deploy order. + Verification before funding reads the directory fields `verification_status`, `minor` and `guardian_verified` (see "Verification before funding" below). Weave `main` sends all three. A Weave without `verification_status` holds every project's budget and compute. The demographics gate reads the field @@ -30,7 +34,8 @@ everyone Weave lets use the Krater app is a Ganymede member. An admin must add ` | Discovery, JWKS, RS256 id_tokens | Verifying the id_token | | Claim `sub` | The user row. `sub` is the user's `p_id` (Patchwork ID), e.g. `PWL5A1B2C3D4` | | Claims `name`, `email` | The signed-in name in the session cookie; never stored (see "Member data" below) | -| Claim `roles` (scope `roles`) | Krater's app-defined role keys the user holds | +| Claim `patches` (scope `patches`) | The patch role keys the user holds, per patch. Krater reads its own patch, `ganymede` | +| Claim `roles` (scope `roles`) | Krater's app-defined role keys the user holds (legacy, see "Patch roles") | | Claim `groups` (scope `groups`) | Group slugs linked to the Krater app; the fallback when `roles` is absent | | Claims `slack_id`, `slack_member` (scope `slack`) | Mapping Slack clicks to users, and the Slack membership gate | | The client_credentials grant, scope `directory` | Krater's own token for the directory API | @@ -41,7 +46,7 @@ everyone Weave lets use the Krater app is a Ganymede member. An admin must add ` | `GET /api/v1/directory/users?role=` | "Everyone with role X", e.g. reviewers to invite to Slack channels | | A second, public app for the `krater` CLI; `GET /oauth/token/info` and `GET /oauth/userinfo` with a member's CLI token | Checking the CLI's tokens (docs/compute/cli.md) | -Krater asks for the sign-in scopes `openid profile email groups roles slack`. +Krater asks for the sign-in scopes `openid profile email groups roles slack patches`. ## Member data @@ -66,11 +71,14 @@ content they wrote (proposals, reviews), which belongs to their projects. 1. Register Krater as a **confidential** OAuth app at `/admin/oauth_applications`. 2. Set the redirect URI to `https:///auth/callback`. Add `http://localhost:/auth/callback` for development. -3. Give the app the scopes `openid profile email groups roles slack directory`. An admin must add `directory` to the - Krater app's scopes, or the directory API answers 403. Add `quilt` to send events to Quilt +3. Give the app the scopes `openid profile email groups roles slack patches directory`. An admin must add `directory` + to the Krater app's scopes, or the directory API answers 403. Without `patches` in the app's scopes, Weave refuses + Krater's sign-in request with `invalid_scope`, and the directory leaves out `patches`. Add `quilt` to send events to Quilt ([quilt-integration.md](quilt-integration.md)) and `stash` to archive submitted links in Stash ([stash-integration.md](stash-integration.md)); each is a client_credentials scope of the same app. -4. On the Krater app page, a Weave superadmin creates the roles `reviewer` and `admin`. +4. Link the Krater app to the patch `ganymede`. On that patch, a Weave superadmin creates the patch roles + `krater:reviewer` and `krater:admin`. Until the follow-up in "Patch roles" ships, the app roles `reviewer` and + `admin` on the Krater app page still count too. 5. Give those roles to the reviewer and admin groups (or people) in Weave. Members need no role: the app's access policy decides who can use Krater (on staging, everyone who can sign in to Weave). 6. Optional: link the groups `krater-reviewers` and `krater-admins` to the Krater app. Krater only @@ -80,24 +88,81 @@ content they wrote (proposals, reviews), which belongs to their projects. ## Roles -Weave sends the role keys a user holds for Krater in the `roles` claim and in each directory record. **`roles` is the -source of truth.** `krater.weave.roles.RoleMapping` translates them to Krater's internal names: +Weave sends a user's Krater roles two ways, in the id_token and in each directory record: + +- the `patches` claim: the patch role keys the user holds in each patch, for example + `{"ganymede": ["krater:admin", "krater:reviewer", "lead", "quilt:viewer"]}`; +- the `roles` claim (legacy): the app role keys the user holds on the Krater app, with the group slugs as a fallback. + +**Krater holds the union of both.** `krater.weave.roles.RoleMapping` is the one place that translates them to +Krater's internal names: -| Weave role key (setting) | Group slug fallback (setting) | Krater role | -| --- | --- | --- | -| `reviewer` (`KRATER_WEAVE_ROLE_REVIEWER`) | `krater-reviewers` (`KRATER_WEAVE_GROUP_REVIEWER`) | `ganymede:reviewer` | -| `admin` (`KRATER_WEAVE_ROLE_ADMIN`) | `krater-admins` (`KRATER_WEAVE_GROUP_ADMIN`) | `ganymede:admin` | +| Patch role key in `ganymede` (setting) | App role key (setting) | Group slug fallback (setting) | Krater role | +| --- | --- | --- | --- | +| `krater:reviewer` (`KRATER_WEAVE_PATCH_ROLE_REVIEWER`) | `reviewer` (`KRATER_WEAVE_ROLE_REVIEWER`) | `krater-reviewers` (`KRATER_WEAVE_GROUP_REVIEWER`) | `ganymede:reviewer` | +| `krater:admin` (`KRATER_WEAVE_PATCH_ROLE_ADMIN`) | `admin` (`KRATER_WEAVE_ROLE_ADMIN`) | `krater-admins` (`KRATER_WEAVE_GROUP_ADMIN`) | `ganymede:admin` | + +The patch slug is `KRATER_WEAVE_PATCH` (default `ganymede`). Rules: -- Everyone Weave signs in or returns holds `ganymede:member`, whatever `roles` says. +- Everyone Weave signs in or returns holds `ganymede:member`, whatever `roles` or `patches` says. +- Krater reads only its own patch in `patches`, and only the keys in the table. Other patches give nothing. Other keys + in `ganymede` give nothing: `lead` (the governance patch lead), `quilt:viewer`, or a bare `reviewer`. Every app of a + patch gets the same claim, so Krater's keys carry the `krater:` prefix. +- `patches` absent (no `patches` scope) or `{}` means no patch role. A malformed value counts as no patch role: not an + object, a value for `ganymede` that is not a list, or a list with a non-string entry. This fails closed for the + patch roles only. The app roles still count. - `roles: []` means "no reviewer or admin role". Krater does not fall back to groups for an empty list. - Krater uses the group slugs only when the `roles` field is absent. Weave leaves it out when the token has no `roles` scope. Weave's `groups` also include groups linked through a role assignment. - A `roles` value that isn't a list counts as no roles, so a malformed answer fails closed. Unknown keys (such as an old `member` role) are ignored. - The internal names (`ganymede:*`) stay inside Krater. The `Actor`, approval policies and review snapshots use them. - Nothing outside `krater.weave` sees Weave's keys or slugs. + Nothing outside `krater.weave` sees Weave's keys, slugs or patch slug. + +### Patch roles + +Weave moves app-specific roles from each app to the app's patch +([patchworklabsorg/weave#288](https://github.com/patchworklabsorg/weave/pull/288)). Krater's `reviewer` and `admin` +app roles become the patch roles `krater:reviewer` and `krater:admin` in `ganymede`. The maintainer approved the move. + +During the move, Krater holds the union of the patch roles and the app roles (with the group fallback when `roles` is +absent). Nothing changes for anyone until the Weave import runs, and nobody loses access during the switch. + +```mermaid +flowchart LR + P["patches claim: ganymede"] --> M[RoleMapping] + R["roles claim, or groups when roles is absent"] --> M + M --> U["union + ganymede:member"] +``` + +Deploy order: + +1. Weave #288 merges and deploys. +2. In Weave, add `patches` to the scopes of the Krater app. +3. Run the Weave import, first as a dry run, then with `APPLY=1`: + + ```sh + bin/rails patches:import_app_roles APP= PATCH=ganymede PREFIX=krater ACTOR= \ + GROUP_MAP=krater-reviewers:reviewer,krater-admins:admin + bin/rails patches:import_app_roles APP= PATCH=ganymede PREFIX=krater ACTOR= \ + GROUP_MAP=krater-reviewers:reviewer,krater-admins:admin APPLY=1 + ``` + +4. Deploy Krater. + +If Krater deploys before its Weave app lists `patches`, Weave refuses every Krater sign-in request with +`invalid_scope`. Actions keep working, because the directory only leaves `patches` out. + +**While the union holds, removing someone's reviewer or admin access takes both:** remove the app role (or the group) +and the patch role. + +Follow-up, in a later PR, once the import ran: remove the app roles and the fallback groups from `RoleMapping`, the +settings and this page, so the patch roles are the only source. Before that, `list_users_with_role` needs a new +source too. It calls `GET /api/v1/directory/users?role=`, and Weave's filter knows app roles only, so a person +who holds a role only as a patch role is not listed (no reviewer invite to Slack channels, no admin access to boxes +through `box_access`). Weave's directory needs a patch role filter first. ## The directory API @@ -114,16 +179,17 @@ Endpoints: - `GET /api/v1/directory/users/{sub}` answers `{sub, name, email, email_verified, slack_id, slack_member, slack_required, code_of_conduct_required, groups, roles, - active, minor, guardian_verified, verification_status, demographics_answered, us_resident, us_residency_checked_on}`. A 404 means the user is unknown or may not use Krater: + patches, active, minor, guardian_verified, verification_status, demographics_answered, us_resident, us_residency_checked_on}`. A 404 means the user is unknown or may not use Krater: Krater treats them as not a member. Only `active: true` counts as active. `minor`, `guardian_verified`, `demographics_answered`, `us_resident`, `slack_required` and `code_of_conduct_required` are booleans that older Weave versions leave out (the last two came in weave#274). Krater reads a value that isn't a boolean as missing. `us_resident` is also null when the member has no standing residency result. `verification_status` is a string (`needs_submission`, `pending`, `verified` or `ineligible`); Krater reads anything - else as missing. Krater doesn't read `us_residency_checked_on`. + else as missing. Krater doesn't read `us_residency_checked_on`. Weave sends `patches` only when the Krater app's + scopes list `patches`; Krater reads it as in "Roles". - `GET /api/v1/directory/users?role=` (or `?group=`, which Krater doesn't use) answers `{"users": [...]}`, sorted by `sub`. Send exactly one parameter. A role or group that isn't linked to Krater answers - 404: Krater treats it as an empty list and logs a warning. + 404: Krater treats it as an empty list and logs a warning. The filter knows app roles only (see "Patch roles"). `get_user` answers are cached for 60 seconds for page views only: every state-changing action (`fresh_actor` on anything but a GET/HEAD, and Slack clicks) asks with `fresh=True`, which skips the cache. Any other failure (no answer, a 5xx, malformed JSON) raises @@ -275,7 +341,8 @@ Only the submission is gated. Saving a draft is not. A completion asks for no bu ### Disabling someone -Do it in Weave: remove their Krater roles or their access to the Krater app, and revoke their tokens. The next action +Do it in Weave: remove their Krater roles (both the app role and the patch role, see "Patch roles") or their access +to the Krater app, and revoke their tokens. The next action they take in Krater is refused straight away: actions never use the directory cache. Pages they already have open can keep showing what they could see for up to 60 seconds. Their boxes keep their SSH keys until the box stops; an admin can cancel them from the project's Compute page. @@ -284,14 +351,16 @@ admin can cancel them from the project's Compute page. `KRATER_WEAVE_MODE=stub` (refused in production) replaces Weave with `krater/weave/stub_users.json`. Each fixture user has the fields a real Weave sends: `sub`, `name`, `email`, `email_verified`, `slack_id`, optional -`slack_member`, `groups` (slugs), `roles` (keys) and optional `minor`, `guardian_verified`, +`slack_member`, `groups` (slugs), `roles` (keys), optional `patches` (patch slug to keys) and optional `minor`, `guardian_verified`, `verification_status`, `demographics_answered` and `us_resident`. Every fixture user has `verification_status: "verified"`, and `put_user` defaults to it too. No fixture user has `demographics_answered`, so the gate lets them all submit and logs a warning. One user (`PWLREVIEWERTWO`) has no `roles` field, to exercise the group fallback. `PWLMINORONE` is a minor without a verified guardian, `PWLMINORVERIFIED` is a minor with one, and `PWLMEMBERTWO` has no `minor` field. The stub client answers the -directory lookups from the same fixture with the same `RoleMapping`. +directory lookups from the same fixture with the same `RoleMapping`. `PWLPATCHREVIEWER` is a reviewer through the +patch role `krater:reviewer` only, and `PWLMEMBERONE` has `patches: {}`. Like Weave, the stub's +`list_users_with_role` lists by app role, so it leaves `PWLPATCHREVIEWER` out. -Tests change what Weave says mid-test with `StubWeaveClient.set_roles`, `set_active`, `set_minor`, +Tests change what Weave says mid-test with `StubWeaveClient.set_roles` (with `patches=` for patch roles), `set_active`, `set_minor`, `set_guardian_verified`, `set_verification_status`, `set_demographics_answered`, `remove_user` and `put_user`. The `weave_stub` fixture in `tests/conftest.py` is the stub the test app uses. diff --git a/krater/config.py b/krater/config.py index e3f8e3fa..1a698aad 100644 --- a/krater/config.py +++ b/krater/config.py @@ -58,9 +58,13 @@ class Settings(BaseSettings): weave_cli_loopback: bool = False # How Weave's answers map onto Krater's roles `ganymede:reviewer` and `ganymede:admin`. Everyone Weave lets use - # Krater is `ganymede:member`, with no role in Weave. The `roles` claim (Krater's app-defined role keys in Weave) - # is the source of truth. Only when Weave sends no `roles` at all does Krater fall back to these group slugs. - # See `krater.weave.roles`. + # Krater is `ganymede:member`, with no role in Weave. Krater holds the union of two sources (see + # `krater.weave.roles`): the patch role keys it holds in the patch `weave_patch` (the `patches` claim), and the + # legacy app role keys (the `roles` claim). Only when Weave sends no `roles` at all does Krater fall back to the + # group slugs. + weave_patch: str = "ganymede" + weave_patch_role_reviewer: str = "krater:reviewer" + weave_patch_role_admin: str = "krater:admin" weave_role_reviewer: str = "reviewer" weave_role_admin: str = "admin" weave_group_reviewer: str = "krater-reviewers" diff --git a/krater/weave/live.py b/krater/weave/live.py index 5525e983..406a6457 100644 --- a/krater/weave/live.py +++ b/krater/weave/live.py @@ -34,7 +34,7 @@ logger = logging.getLogger(__name__) -SCOPES = "openid profile email groups roles slack" +SCOPES = "openid profile email groups roles slack patches" #: The scope Krater asks for on its client_credentials token for the directory API. DIRECTORY_SCOPE = "directory" @@ -170,7 +170,9 @@ def _verify_id_token(self, id_token: str, *, nonce: str) -> WeaveIdentity: email_verified=claims.get("email_verified") is True, slack_id=_string(claims.get("slack_id")) or None, slack_member=_optional_bool(claims.get("slack_member")), - roles=self._roles.krater_roles(roles=claims.get("roles"), groups=claims.get("groups")), + roles=self._roles.krater_roles( + roles=claims.get("roles"), groups=claims.get("groups"), patches=claims.get("patches") + ), ) # -- Directory ------------------------------------------------------------------------------- @@ -191,6 +193,8 @@ def get_user(self, sub: str, *, fresh: bool = False) -> WeaveUser | None: return user def list_users_with_role(self, role: str) -> list[WeaveUser]: + # Weave's directory filters by app role key only: someone who holds the role only as a patch role is not + # listed. Fine while the app roles and patch roles are the same people (docs/weave-integration.md). key = self._roles.weave_role_key(role) response = self._directory_get("/api/v1/directory/users", params={"role": key}) if response.status_code == 404: @@ -346,7 +350,9 @@ def _parse_user(self, data: object) -> WeaveUser: email_verified=data.get("email_verified") is True, slack_id=_string(data.get("slack_id")) or None, slack_member=_optional_bool(data.get("slack_member")), - roles=self._roles.krater_roles(roles=data.get("roles"), groups=data.get("groups")), + roles=self._roles.krater_roles( + roles=data.get("roles"), groups=data.get("groups"), patches=data.get("patches") + ), # Fail closed: only an explicit `true` counts as active. active=data.get("active") is True, # Only a real boolean counts; a missing or malformed value is "Weave didn't say". diff --git a/krater/weave/roles.py b/krater/weave/roles.py index e4b3d079..7a125db9 100644 --- a/krater/weave/roles.py +++ b/krater/weave/roles.py @@ -4,22 +4,32 @@ app's access policy, so a user who signs in, or whom the directory returns, holds `ganymede:member`. There is no member role in Weave. -Weave owns the other roles. Krater is an OAuth app in Weave with two app-defined role keys (by default -`reviewer` and `admin`), usually given to a group on the app page. Weave sends the keys a user holds -for Krater in the `roles` claim and in each directory record. That list is the source of truth. - -If Weave sends no `roles` field at all (absent, not empty), Krater falls back to the group slugs -linked to the Krater app (by default `krater-reviewers`, `krater-admins`). +Weave owns the other roles, and sends them two ways. Krater holds the union of both: + +- Patch roles. Ganymede is a patch in Weave with its own role keys. Weave sends the keys a user holds + per patch in the `patches` claim and in each directory record, e.g. + `{"ganymede": ["krater:admin", "krater:reviewer", "lead"]}`. Every app of the patch gets the same + claim, so Krater's keys carry the `krater:` prefix (by default `krater:reviewer` and `krater:admin`). + Krater reads only its own patch (by default `ganymede`) and ignores every other key there (`lead`, + `quilt:viewer`). +- App roles (legacy). Krater is an OAuth app in Weave with two app-defined role keys (by default + `reviewer` and `admin`), sent in the `roles` claim and in each directory record. If Weave sends no + `roles` field at all (absent, not empty), Krater falls back to the group slugs linked to the Krater + app (by default `krater-reviewers`, `krater-admins`). + +The union is for the move from app roles to patch roles: nobody loses access while Weave copies the app +roles into patch roles. A later change removes the app roles and groups from this mapping +(`docs/weave-integration.md`, "Patch roles"). Inside Krater, roles keep their `ganymede:*` names (`krater.services.actor`), so the `Actor`, approval policies and review snapshots don't change. The translation happens here, at the `krater.weave` -boundary, and nothing outside this package sees Weave's keys or slugs. +boundary, and nothing outside this package sees Weave's keys, slugs or patch slug. """ from __future__ import annotations from collections.abc import Iterable, Mapping -from dataclasses import dataclass +from dataclasses import dataclass, field from krater.config import Settings from krater.services.actor import GROUP_ADMIN, GROUP_MEMBER, GROUP_REVIEWER @@ -27,11 +37,14 @@ @dataclass(frozen=True) class RoleMapping: - """Krater role name -> Weave role key, and Krater role name -> Weave group slug, for the roles Weave - gives (`ganymede:reviewer`, `ganymede:admin`).""" + """Krater role name -> Weave app role key, Krater role name -> Weave group slug, and Krater role name -> + Weave patch role key in the patch `patch_slug`, for the roles Weave gives (`ganymede:reviewer`, + `ganymede:admin`).""" role_keys: Mapping[str, str] group_slugs: Mapping[str, str] + patch_slug: str = "ganymede" + patch_role_keys: Mapping[str, str] = field(default_factory=dict) @classmethod def from_settings(cls, settings: Settings) -> RoleMapping: @@ -44,6 +57,11 @@ def from_settings(cls, settings: Settings) -> RoleMapping: GROUP_REVIEWER: settings.weave_group_reviewer, GROUP_ADMIN: settings.weave_group_admin, }, + patch_slug=settings.weave_patch, + patch_role_keys={ + GROUP_REVIEWER: settings.weave_patch_role_reviewer, + GROUP_ADMIN: settings.weave_patch_role_admin, + }, ) @classmethod @@ -51,24 +69,40 @@ def default(cls) -> RoleMapping: """The mapping with every setting at its default.""" return cls.from_settings(Settings(_env_file=None)) - def krater_roles(self, *, roles: object, groups: object) -> frozenset[str]: - """Krater's role names for a user Weave let use Krater, from Weave's `roles` and `groups` values. + def krater_roles(self, *, roles: object, groups: object, patches: object = None) -> frozenset[str]: + """Krater's role names for a user Weave let use Krater, from Weave's `roles`, `groups` and `patches` values. + + Always holds `ganymede:member`. The result is the union of the patch roles and the app roles. - Always holds `ganymede:member`. `roles` is `None` when Weave didn't send the field at all; only - then are `groups` used. A value that isn't a list counts as holding no Weave role, so a - malformed answer fails closed. Unknown keys and slugs, and non-string entries, are ignored. + `roles` is `None` when Weave didn't send the field at all; only then are `groups` used. A `roles` value + that isn't a list counts as holding no app role, so a malformed answer fails closed. Unknown keys and + slugs, and non-string entries, are ignored. + + `patches` is `None` when Weave didn't send the field (the token or app lacks the `patches` scope). It + counts as no patch role, as does any malformed value: not an object, a value for Krater's patch that + isn't a list, or a list with a non-string entry. That fails closed for patch roles only. Other patches + and unknown keys in Krater's patch are ignored. """ - given = self._match(self.role_keys, roles) if roles is not None else self._match(self.group_slugs, groups) - return given | {GROUP_MEMBER} + app = self._match(self.role_keys, roles) if roles is not None else self._match(self.group_slugs, groups) + return app | self._match(self.patch_role_keys, self._patch_keys(patches)) | {GROUP_MEMBER} def weave_role_key(self, krater_role: str) -> str: - """The Weave role key for a Krater role name, e.g. `ganymede:reviewer` -> `reviewer`. `ganymede:member` has - none: every user Weave lets use Krater holds it.""" + """The Weave app role key for a Krater role name, e.g. `ganymede:reviewer` -> `reviewer`. `ganymede:member` + has none: every user Weave lets use Krater holds it.""" try: return self.role_keys[krater_role] except KeyError: raise ValueError(f"no Weave role key for Krater role {krater_role!r}") from None + def _patch_keys(self, patches: object) -> frozenset[str]: + """The keys the user holds in Krater's patch, or none if `patches` is missing or malformed.""" + if not isinstance(patches, Mapping): + return frozenset() + keys = patches.get(self.patch_slug) + if not isinstance(keys, list | tuple) or not all(isinstance(key, str) for key in keys): + return frozenset() + return frozenset(keys) + @staticmethod def _match(table: Mapping[str, str], values: object) -> frozenset[str]: held = _string_set(values) diff --git a/krater/weave/stub.py b/krater/weave/stub.py index 49b0ca59..a76f6a51 100644 --- a/krater/weave/stub.py +++ b/krater/weave/stub.py @@ -5,11 +5,12 @@ picker page; `exchange_code` treats the authorization code as the chosen user's `sub` directly. Each fixture user has the same fields a real Weave sends: `sub`, `name`, `email`, `email_verified`, -`slack_id`, optional `slack_member`, `groups` (group slugs), `roles` (Weave role keys; leave it out -to exercise the group-slug fallback), and optional `minor`, `guardian_verified`, `demographics_answered`, +`slack_id`, optional `slack_member`, `groups` (group slugs), `roles` (Weave app role keys; leave it out +to exercise the group-slug fallback), optional `patches` (patch slug -> patch role keys; leave it out for a +token without the `patches` scope), and optional `minor`, `guardian_verified`, `demographics_answered`, `us_resident` and `verification_status` (leave them out for "Weave didn't say"). Sign-in and the directory lookups translate them with the same `RoleMapping` the live client uses. -Tests change a user mid-test with `set_roles`, `set_active`, `set_minor`, `set_guardian_verified`, +Tests change a user mid-test with `set_roles` (also for `patches`), `set_active`, `set_minor`, `set_guardian_verified`, `set_demographics_answered`, `set_verification_status` or `remove_user`. The app refuses stub mode in production. """ @@ -18,7 +19,7 @@ import dataclasses import json -from collections.abc import Iterable +from collections.abc import Iterable, Mapping from dataclasses import dataclass from pathlib import Path from urllib.parse import urlencode @@ -34,6 +35,9 @@ #: The stub accepts `:` as a Krater CLI token for that fixture user. STUB_CLI_TOKEN_PREFIX = "stub-cli-token" +#: `set_roles` leaves `patches` as it is unless the test passes it. +_KEEP = object() + #: The bundled fixture, used whenever `settings.weave_stub_users_file` is blank. DEFAULT_STUB_USERS_FILE = Path(__file__).parent / "stub_users.json" @@ -51,6 +55,9 @@ class StubUser: groups: tuple[str, ...] roles: tuple[str, ...] | None # None: Weave sends no `roles` field active: bool + # Patch slug -> patch role keys, kept as Weave would send it (a malformed value stays malformed). + # None: Weave sends no `patches` field. + patches: object = None minor: bool | None = None # None: Weave sends no `minor` field guardian_verified: bool | None = None # None: Weave sends no `guardian_verified` field demographics_answered: bool | None = None # None: Weave sends no `demographics_answered` field @@ -87,6 +94,7 @@ def __init__(self, stub_users_file: str | Path | None = None, *, role_mapping: R groups=tuple(entry.get("groups", [])), roles=None if raw_roles is None else tuple(raw_roles), active=entry.get("active", True), + patches=entry.get("patches"), minor=entry.get("minor"), guardian_verified=entry.get("guardian_verified"), demographics_answered=entry.get("demographics_answered"), @@ -125,8 +133,13 @@ def get_user(self, sub: str, *, fresh: bool = False) -> WeaveUser | None: return None if user is None else self._record(user) def list_users_with_role(self, role: str) -> list[WeaveUser]: - records = (self._record(user) for user in self._users_by_sub.values()) - return [record for record in records if role in record.roles] + # Like Weave's `?role=`, this lists by app role (and, as before, the group fallback), not by patch role: + # a user who holds the role only in `patches` is left out, as Weave leaves them out. + return [ + self._record(user) + for user in self._users_by_sub.values() + if role in self._mapping.krater_roles(roles=user.roles, groups=user.groups) + ] def quilt_token(self) -> str: self.quilt_token_requests += 1 @@ -173,6 +186,7 @@ def put_user( roles: Iterable[str] | None = (), groups: Iterable[str] = (), active: bool = True, + patches: object = None, minor: bool | None = None, guardian_verified: bool | None = None, demographics_answered: bool | None = None, @@ -181,8 +195,9 @@ def put_user( slack_required: bool | None = None, code_of_conduct_required: bool | None = None, ) -> None: - """Add or replace a user. `roles` are Weave role keys (`None` for no `roles` field at all), - `groups` are group slugs, and `minor`, `guardian_verified`, `demographics_answered` or + """Add or replace a user. `roles` are Weave app role keys (`None` for no `roles` field at all), + `groups` are group slugs, `patches` maps a patch slug to patch role keys (`None` for no `patches` field), + and `minor`, `guardian_verified`, `demographics_answered` or `verification_status` is `None` when Weave sends no such field. A put user has passed ID verification unless the test says otherwise.""" self._users_by_sub[sub] = StubUser( @@ -195,6 +210,7 @@ def put_user( groups=tuple(groups), roles=None if roles is None else tuple(roles), active=active, + patches=_copy_patches(patches), minor=minor, guardian_verified=guardian_verified, demographics_answered=demographics_answered, @@ -204,13 +220,24 @@ def put_user( code_of_conduct_required=code_of_conduct_required, ) - def set_roles(self, sub: str, roles: Iterable[str] | None, *, groups: Iterable[str] | None = None) -> None: - """Change what Weave says `sub` holds: Weave role keys (`None` for no `roles` field at all) and, - optionally, group slugs. For tests that revoke or grant a role mid-test.""" + def set_roles( + self, + sub: str, + roles: Iterable[str] | None, + *, + groups: Iterable[str] | None = None, + patches: object = _KEEP, + ) -> None: + """Change what Weave says `sub` holds: Weave app role keys (`None` for no `roles` field at all) and, + optionally, group slugs and the `patches` value (`None` for no `patches` field). For tests that revoke + or grant a role mid-test. Krater holds the union of app and patch roles, so revoking a role a user holds + both ways takes both.""" user = self._users_by_sub[sub] changes: dict = {"roles": None if roles is None else tuple(roles)} if groups is not None: changes["groups"] = tuple(groups) + if patches is not _KEEP: + changes["patches"] = _copy_patches(patches) self._users_by_sub[sub] = dataclasses.replace(user, **changes) def set_active(self, sub: str, active: bool) -> None: @@ -255,7 +282,7 @@ def _record(self, user: StubUser) -> WeaveUser: email_verified=user.email_verified, slack_id=user.slack_id, slack_member=user.slack_member, - roles=self._mapping.krater_roles(roles=user.roles, groups=user.groups), + roles=self._mapping.krater_roles(roles=user.roles, groups=user.groups, patches=user.patches), active=user.active, minor=user.minor, guardian_verified=user.guardian_verified, @@ -267,4 +294,12 @@ def _record(self, user: StubUser) -> WeaveUser: ) +def _copy_patches(patches: object) -> object: + """A copy of a `patches` value, so a test changing its own dict later doesn't change the stub. A malformed + value is kept as it is, for tests of the fail-closed rule.""" + if isinstance(patches, Mapping): + return {slug: list(keys) if isinstance(keys, list | tuple) else keys for slug, keys in patches.items()} + return patches + + __all__ = ["DEFAULT_STUB_USERS_FILE", "STUB_QUILT_TOKEN", "StubUser", "StubWeaveClient"] diff --git a/krater/weave/stub_users.json b/krater/weave/stub_users.json index c2ee27fa..6acf55e2 100644 --- a/krater/weave/stub_users.json +++ b/krater/weave/stub_users.json @@ -8,7 +8,8 @@ "slack_id": "U0001MEMBER", "minor": false, "groups": [], - "roles": [] + "roles": [], + "patches": {} }, { "sub": "PWLMEMBERTWO", @@ -51,6 +52,18 @@ "groups": ["krater-reviewers", "krater-admins"], "roles": ["reviewer", "admin"] }, + { + "sub": "PWLPATCHREVIEWER", + "name": "Pat Patchrole", + "email": "pat@example.com", + "email_verified": true, + "verification_status": "verified", + "slack_id": "U0008PATCH", + "minor": false, + "groups": [], + "roles": [], + "patches": {"ganymede": ["krater:reviewer", "lead", "quilt:viewer"], "europa": ["krater:admin"]} + }, { "sub": "PWLNOROLE", "name": "Nico Norole", diff --git a/krater/weave/types.py b/krater/weave/types.py index 4aea2d8f..b964eeae 100644 --- a/krater/weave/types.py +++ b/krater/weave/types.py @@ -2,7 +2,8 @@ `WeaveIdentity` comes from a freshly verified id_token, at sign-in time. `WeaveUser` comes from the directory API, and is what Weave says about a user *right now*. Both carry Krater's role names -(`ganymede:*`), already translated from Weave's role keys or group slugs by `krater.weave.roles`. +(`ganymede:*`), already translated from Weave's patch role keys, app role keys or group slugs by +`krater.weave.roles`. See `docs/weave-integration.md`. """ diff --git a/tests/services/test_sign_in.py b/tests/services/test_sign_in.py index 5e9ab7ea..ea23b8d2 100644 --- a/tests/services/test_sign_in.py +++ b/tests/services/test_sign_in.py @@ -115,6 +115,39 @@ def test_authorize_drops_a_role_weave_removed(db_session: Session, weave: StubWe assert signed_in.roles_cached == [GROUP_MEMBER] +def test_authorize_reads_patch_roles_from_the_directory(db_session: Session, weave: StubWeaveClient, signed_in) -> None: + weave.set_roles("PWLSIGNIN01", [], patches={"ganymede": ["krater:admin", "lead"], "europa": ["krater:reviewer"]}) + + assert authorize(db_session, weave, signed_in).groups == frozenset({GROUP_MEMBER, GROUP_ADMIN}) + assert signed_in.roles_cached == [GROUP_ADMIN, GROUP_MEMBER] + + +def test_authorize_holds_the_union_of_app_and_patch_roles( + db_session: Session, weave: StubWeaveClient, signed_in +) -> None: + weave.set_roles("PWLSIGNIN01", ["reviewer"], patches={"ganymede": ["krater:admin"]}) + + assert authorize(db_session, weave, signed_in).groups == frozenset({GROUP_MEMBER, GROUP_REVIEWER, GROUP_ADMIN}) + + +def test_authorize_keeps_a_role_until_both_sources_drop_it( + db_session: Session, weave: StubWeaveClient, signed_in +) -> None: + weave.set_roles("PWLSIGNIN01", ["reviewer"], patches={"ganymede": ["krater:reviewer"]}) + + weave.set_roles("PWLSIGNIN01", []) + assert authorize(db_session, weave, signed_in).groups == frozenset({GROUP_MEMBER, GROUP_REVIEWER}) + + weave.set_roles("PWLSIGNIN01", [], patches={"ganymede": []}) + assert authorize(db_session, weave, signed_in).groups == frozenset({GROUP_MEMBER}) + + +def test_authorize_ignores_a_malformed_patches_value(db_session: Session, weave: StubWeaveClient, signed_in) -> None: + weave.set_roles("PWLSIGNIN01", ["reviewer"], patches={"ganymede": ["krater:admin", 7]}) + + assert authorize(db_session, weave, signed_in).groups == frozenset({GROUP_MEMBER, GROUP_REVIEWER}) + + def test_authorize_refuses_an_inactive_user(db_session: Session, weave: StubWeaveClient, signed_in) -> None: weave.set_active("PWLSIGNIN01", False) diff --git a/tests/services/test_slack_reviews.py b/tests/services/test_slack_reviews.py index e63c63e7..7c908c19 100644 --- a/tests/services/test_slack_reviews.py +++ b/tests/services/test_slack_reviews.py @@ -207,6 +207,36 @@ def test_a_reviewer_whose_reviewer_role_weave_revoked_is_refused( assert reviewer.user.roles_cached == [GROUP_MEMBER] +def test_a_reviewer_who_holds_only_the_patch_role_can_approve( + db_session: Session, member: Actor, reviewer: Actor, weave: StubWeaveClient +) -> None: + reviewer.user.slack_user_id = "U_REVIEWER" + _project, revision = _submitted_revision(db_session, member) + weave.set_roles(reviewer.user.weave_sub, [], patches={"ganymede": ["krater:reviewer"]}) + slack_client = FakeSlackClient() + + _approve(db_session, slack_client, weave, revision, "U_REVIEWER") + + db_session.refresh(revision) + assert revision.outcome is RevisionOutcome.APPROVED + assert GROUP_REVIEWER in reviewer.user.roles_cached + + +def test_a_reviewer_whose_patch_role_weave_revoked_is_refused( + db_session: Session, member: Actor, reviewer: Actor, weave: StubWeaveClient +) -> None: + reviewer.user.slack_user_id = "U_REVIEWER" + _project, revision = _submitted_revision(db_session, member) + weave.set_roles(reviewer.user.weave_sub, [], patches={"ganymede": ["lead", "quilt:viewer"]}) + slack_client = FakeSlackClient() + + _approve(db_session, slack_client, weave, revision, "U_REVIEWER") + + db_session.refresh(revision) + assert revision.outcome is RevisionOutcome.PENDING + assert reviewer.user.roles_cached == [GROUP_MEMBER] + + def test_a_reviewer_weave_no_longer_returns_is_refused( db_session: Session, member: Actor, reviewer: Actor, weave: StubWeaveClient ) -> None: diff --git a/tests/test_config.py b/tests/test_config.py index 67fc9d91..52175f51 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -148,6 +148,24 @@ def test_weave_role_keys_and_group_slugs_have_the_contract_defaults() -> None: assert not hasattr(settings, "weave_group_member") +def test_weave_patch_and_its_role_keys_have_the_contract_defaults() -> None: + settings = Settings() + + assert settings.weave_patch == "ganymede" + assert (settings.weave_patch_role_reviewer, settings.weave_patch_role_admin) == ("krater:reviewer", "krater:admin") + + +def test_weave_patch_settings_read_from_the_environment(monkeypatch) -> None: + monkeypatch.setenv("KRATER_WEAVE_PATCH", "europa") + monkeypatch.setenv("KRATER_WEAVE_PATCH_ROLE_REVIEWER", "krater:judge") + monkeypatch.setenv("KRATER_WEAVE_PATCH_ROLE_ADMIN", "krater:boss") + + settings = Settings() + + assert settings.weave_patch == "europa" + assert (settings.weave_patch_role_reviewer, settings.weave_patch_role_admin) == ("krater:judge", "krater:boss") + + def test_weave_role_keys_read_from_the_environment(monkeypatch) -> None: monkeypatch.setenv("KRATER_WEAVE_ROLE_REVIEWER", "krater-reviewer") monkeypatch.setenv("KRATER_WEAVE_API_BASE_URL", "https://api.weave.test") diff --git a/tests/weave/test_live_client.py b/tests/weave/test_live_client.py index 750f933d..6e5e63fd 100644 --- a/tests/weave/test_live_client.py +++ b/tests/weave/test_live_client.py @@ -146,7 +146,7 @@ def test_authorization_url_uses_s256_pkce_and_the_roles_scopes(live_client: Live assert params["response_type"] == ["code"] assert params["client_id"] == [CLIENT_ID] assert params["redirect_uri"] == [REDIRECT_URI] - assert params["scope"] == ["openid profile email groups roles slack"] + assert params["scope"] == ["openid profile email groups roles slack patches"] assert params["state"] == ["s1"] assert params["nonce"] == ["n1"] assert params["code_challenge_method"] == ["S256"] @@ -210,6 +210,46 @@ def test_exchange_code_falls_back_to_groups_without_a_roles_claim( assert identity.slack_member is None +def test_the_authorization_url_asks_for_the_patches_scope(live_client: LiveWeaveClient) -> None: + url = live_client.authorization_url(state="s1", nonce="n1", code_verifier="a" * 64, redirect_uri=REDIRECT_URI) + + assert "patches" in parse_qs(urlparse(url).query)["scope"][0].split() + + +def test_exchange_code_maps_the_patches_claim( + fake_weave: FakeWeave, live_client: LiveWeaveClient, rsa_key: RSAKey +) -> None: + fake_weave.id_token = _id_token( + rsa_key, + roles=[], + patches={"ganymede": ["krater:admin", "lead", "quilt:viewer"], "europa": ["krater:reviewer"]}, + ) + + identity = live_client.exchange_code(code="c1", code_verifier="v", redirect_uri=REDIRECT_URI, nonce=GOOD_NONCE) + + assert identity.roles == frozenset({GROUP_MEMBER, GROUP_ADMIN}) + + +def test_exchange_code_unions_the_roles_and_patches_claims( + fake_weave: FakeWeave, live_client: LiveWeaveClient, rsa_key: RSAKey +) -> None: + fake_weave.id_token = _id_token(rsa_key, roles=["reviewer"], patches={"ganymede": ["krater:admin"]}) + + identity = live_client.exchange_code(code="c1", code_verifier="v", redirect_uri=REDIRECT_URI, nonce=GOOD_NONCE) + + assert identity.roles == frozenset({GROUP_MEMBER, GROUP_REVIEWER, GROUP_ADMIN}) + + +def test_exchange_code_ignores_a_malformed_patches_claim( + fake_weave: FakeWeave, live_client: LiveWeaveClient, rsa_key: RSAKey +) -> None: + fake_weave.id_token = _id_token(rsa_key, roles=["reviewer"], patches={"ganymede": "krater:admin"}) + + identity = live_client.exchange_code(code="c1", code_verifier="v", redirect_uri=REDIRECT_URI, nonce=GOOD_NONCE) + + assert identity.roles == frozenset({GROUP_MEMBER, GROUP_REVIEWER}) + + @pytest.mark.parametrize("email_verified", [False, "true", None], ids=["false", "string", "absent"]) def test_exchange_code_only_trusts_a_boolean_true_email_verified( fake_weave: FakeWeave, live_client: LiveWeaveClient, rsa_key: RSAKey, email_verified: object @@ -531,6 +571,31 @@ def test_a_fresh_lookup_skips_the_cache_and_refreshes_it(fake_weave: FakeWeave, assert len(lookups) == 2 +def test_get_user_reads_patch_roles_from_the_directory_record( + fake_weave: FakeWeave, live_client: LiveWeaveClient +) -> None: + fake_weave.directory_users["PWLDIR0001"] = { + **DIRECTORY_USER, + "roles": [], + "patches": {"ganymede": ["krater:admin", "krater:reviewer"]}, + } + + user = live_client.get_user("PWLDIR0001", fresh=True) + + assert user is not None and user.roles == frozenset({GROUP_MEMBER, GROUP_REVIEWER, GROUP_ADMIN}) + + +def test_a_fresh_lookup_sees_a_patch_role_removed(fake_weave: FakeWeave, live_client: LiveWeaveClient) -> None: + admin = {**DIRECTORY_USER, "roles": [], "patches": {"ganymede": ["krater:admin"]}} + fake_weave.directory_users["PWLDIR0001"] = admin + live_client.get_user("PWLDIR0001") + + fake_weave.directory_users["PWLDIR0001"] = {**DIRECTORY_USER, "roles": [], "patches": {"ganymede": []}} + fresh = live_client.get_user("PWLDIR0001", fresh=True) + + assert fresh is not None and fresh.roles == frozenset({GROUP_MEMBER}) + + def test_list_users_with_role_sends_the_weave_role_key(fake_weave: FakeWeave, live_client: LiveWeaveClient) -> None: fake_weave.directory_users["PWLDIR0001"] = DIRECTORY_USER fake_weave.directory_users["PWLDIR0002"] = {**DIRECTORY_USER, "sub": "PWLDIR0002", "roles": ["member"]} diff --git a/tests/weave/test_roles.py b/tests/weave/test_roles.py index 5a0c0eef..f31c4e48 100644 --- a/tests/weave/test_roles.py +++ b/tests/weave/test_roles.py @@ -65,3 +65,89 @@ def test_settings_change_the_keys_and_slugs() -> None: def test_weave_role_key_rejects_a_role_weave_doesnt_give(mapping: RoleMapping, krater_role: str) -> None: with pytest.raises(ValueError): mapping.weave_role_key(krater_role) + + +# -- Patch roles (the `patches` claim), and the union with app roles during the move -------------------------- + + +def test_patch_role_keys_map_to_krater_role_names(mapping: RoleMapping) -> None: + roles = mapping.krater_roles(roles=[], groups=[], patches={"ganymede": ["krater:admin", "krater:reviewer"]}) + + assert roles == frozenset({GROUP_MEMBER, GROUP_REVIEWER, GROUP_ADMIN}) + + +def test_patch_roles_alone_count_without_a_roles_claim(mapping: RoleMapping) -> None: + roles = mapping.krater_roles(roles=None, groups=[], patches={"ganymede": ["krater:reviewer"]}) + + assert roles == frozenset({GROUP_MEMBER, GROUP_REVIEWER}) + + +def test_app_roles_alone_still_count_with_an_empty_patches_claim(mapping: RoleMapping) -> None: + assert mapping.krater_roles(roles=["admin"], groups=[], patches={}) == frozenset({GROUP_MEMBER, GROUP_ADMIN}) + + +def test_app_roles_and_patch_roles_are_a_union(mapping: RoleMapping) -> None: + roles = mapping.krater_roles(roles=["reviewer"], groups=[], patches={"ganymede": ["krater:admin"]}) + + assert roles == frozenset({GROUP_MEMBER, GROUP_REVIEWER, GROUP_ADMIN}) + + +def test_the_group_fallback_and_patch_roles_are_a_union(mapping: RoleMapping) -> None: + roles = mapping.krater_roles(roles=None, groups=["krater-admins"], patches={"ganymede": ["krater:reviewer"]}) + + assert roles == frozenset({GROUP_MEMBER, GROUP_REVIEWER, GROUP_ADMIN}) + + +def test_another_patchs_keys_give_nothing(mapping: RoleMapping) -> None: + assert mapping.krater_roles(roles=[], groups=[], patches={"europa": ["krater:admin"]}) == frozenset({GROUP_MEMBER}) + + +def test_unknown_keys_in_the_patch_are_ignored(mapping: RoleMapping) -> None: + # `lead` is the governance patch lead, `quilt:viewer` is Quilt's key, and a bare `reviewer` is the app key, + # which counts only in `roles`. + patches = {"ganymede": ["lead", "quilt:viewer", "reviewer", "admin", "krater:member"]} + + assert mapping.krater_roles(roles=[], groups=[], patches=patches) == frozenset({GROUP_MEMBER}) + + +@pytest.mark.parametrize( + "bad", + [ + ["ganymede", "krater:admin"], + "krater:admin", + 7, + {"ganymede": "krater:admin"}, + {"ganymede": {"krater:admin": True}}, + {"ganymede": None}, + {"ganymede": ["krater:admin", 7]}, + {"ganymede": ["krater:admin", None]}, + ], +) +def test_a_malformed_patches_value_gives_no_patch_role(mapping: RoleMapping, bad: object) -> None: + assert mapping.krater_roles(roles=[], groups=[], patches=bad) == frozenset({GROUP_MEMBER}) + + +def test_a_malformed_patches_value_keeps_the_app_roles(mapping: RoleMapping) -> None: + # Fail closed for the patch source only: the `roles` claim still counts. + roles = mapping.krater_roles(roles=["reviewer"], groups=[], patches={"ganymede": ["krater:admin", 7]}) + + assert roles == frozenset({GROUP_MEMBER, GROUP_REVIEWER}) + + +def test_a_malformed_value_for_another_patch_does_not_matter(mapping: RoleMapping) -> None: + patches = {"ganymede": ["krater:admin"], "europa": "oops"} + + assert mapping.krater_roles(roles=[], groups=[], patches=patches) == frozenset({GROUP_MEMBER, GROUP_ADMIN}) + + +def test_settings_change_the_patch_and_its_keys() -> None: + mapping = RoleMapping.from_settings( + Settings(_env_file=None, weave_patch="europa", weave_patch_role_admin="krater:boss") + ) + + assert mapping.krater_roles(roles=[], groups=[], patches={"europa": ["krater:boss", "krater:reviewer"]}) == ( + frozenset({GROUP_MEMBER, GROUP_REVIEWER, GROUP_ADMIN}) + ) + assert mapping.krater_roles(roles=[], groups=[], patches={"ganymede": ["krater:admin"]}) == frozenset( + {GROUP_MEMBER} + ) diff --git a/tests/weave/test_stub_client.py b/tests/weave/test_stub_client.py index fa93151d..9c874fd1 100644 --- a/tests/weave/test_stub_client.py +++ b/tests/weave/test_stub_client.py @@ -155,3 +155,46 @@ def test_set_us_resident_changes_the_record(stub_client: StubWeaveClient) -> Non record = stub_client.get_user("PWLMEMBERONE") assert record is not None assert record.us_resident is True + + +def test_the_fixture_has_a_reviewer_by_patch_role_only(stub_client: StubWeaveClient) -> None: + # PWLPATCHREVIEWER holds no app role: only `krater:reviewer` in the `ganymede` patch. Its `europa` keys and + # `lead`, `quilt:viewer` give nothing. + record = stub_client.get_user("PWLPATCHREVIEWER") + + assert record is not None + assert record.roles == frozenset({GROUP_MEMBER, GROUP_REVIEWER}) + + +def test_sign_in_reads_the_patches_field(stub_client: StubWeaveClient) -> None: + identity = stub_client.exchange_code( + code="PWLPATCHREVIEWER", code_verifier="v", redirect_uri="http://testserver/auth/callback", nonce="n" + ) + + assert identity.roles == frozenset({GROUP_MEMBER, GROUP_REVIEWER}) + + +def test_list_users_with_role_lists_by_app_role_only_like_weave(stub_client: StubWeaveClient) -> None: + # Weave's `?role=` filter knows app roles only, so a patch-only reviewer is not listed. + reviewers = {u.sub for u in stub_client.list_users_with_role(GROUP_REVIEWER)} + + assert "PWLPATCHREVIEWER" not in reviewers + + +def test_set_roles_changes_patches_only_when_asked(stub_client: StubWeaveClient) -> None: + stub_client.set_roles("PWLPATCHREVIEWER", ["admin"]) + kept = stub_client.get_user("PWLPATCHREVIEWER") + stub_client.set_roles("PWLPATCHREVIEWER", [], patches=None) + cleared = stub_client.get_user("PWLPATCHREVIEWER") + + assert kept is not None and kept.roles == frozenset({GROUP_MEMBER, GROUP_REVIEWER, GROUP_ADMIN}) + assert cleared is not None and cleared.roles == frozenset({GROUP_MEMBER}) + + +def test_put_user_copies_the_patches_value(stub_client: StubWeaveClient) -> None: + patches = {"ganymede": ["krater:admin"]} + stub_client.put_user("PWLPUT", patches=patches) + patches["ganymede"].clear() + + record = stub_client.get_user("PWLPUT") + assert record is not None and record.roles == frozenset({GROUP_MEMBER, GROUP_ADMIN}) From 361e881a2e7003d1a85d919213c675874e8bd625 Mon Sep 17 00:00:00 2001 From: Jasper Mayone Date: Thu, 12 Nov 2026 13:40:28 -0500 Subject: [PATCH 2/2] feat: list role holders by patch role too, and fall back to app roles until weave is set up --- docs/weave-integration.md | 40 ++++++++++------ krater/weave/client.py | 3 +- krater/weave/live.py | 40 ++++++++++++++-- krater/weave/roles.py | 7 +++ krater/weave/stub.py | 10 ++-- tests/compute/test_box_access.py | 11 +++++ tests/services/test_slack_notify.py | 14 ++++++ tests/weave/test_live_client.py | 74 ++++++++++++++++++++++++++++- tests/weave/test_roles.py | 7 +++ tests/weave/test_stub_client.py | 8 ++-- 10 files changed, 183 insertions(+), 31 deletions(-) diff --git a/docs/weave-integration.md b/docs/weave-integration.md index db4559eb..bdfe49c6 100644 --- a/docs/weave-integration.md +++ b/docs/weave-integration.md @@ -43,7 +43,7 @@ everyone Weave lets use the Krater app is a Ganymede member. An admin must add ` | `GET /api/v1/directory/users/{sub}` | The fresh role check before every action, the verification check before a project's compute starts, the demographics gate before every grant application, and names and emails when a page needs them | | The page `/profile/demographics?return_to=` | Where a member answers the demographics form. Weave sends them back to `return_to` after they save | | The page `/verification` | Where a member does ID verification. The project and new-job pages link to it | -| `GET /api/v1/directory/users?role=` | "Everyone with role X", e.g. reviewers to invite to Slack channels | +| `GET /api/v1/directory/users?role=` and `?patch=&patch_role=` | "Everyone with role X", e.g. reviewers to invite to Slack channels: the union of both lists | | A second, public app for the `krater` CLI; `GET /oauth/token/info` and `GET /oauth/userinfo` with a member's CLI token | Checking the CLI's tokens (docs/compute/cli.md) | Krater asks for the sign-in scopes `openid profile email groups roles slack patches`. @@ -76,7 +76,7 @@ content they wrote (proposals, reviews), which belongs to their projects. Krater's sign-in request with `invalid_scope`, and the directory leaves out `patches`. Add `quilt` to send events to Quilt ([quilt-integration.md](quilt-integration.md)) and `stash` to archive submitted links in Stash ([stash-integration.md](stash-integration.md)); each is a client_credentials scope of the same app. -4. Link the Krater app to the patch `ganymede`. On that patch, a Weave superadmin creates the patch roles +4. A superadmin links the Krater app to the patch `ganymede` (the Patch field on the app). On that patch, a Weave superadmin creates the patch roles `krater:reviewer` and `krater:admin`. Until the follow-up in "Patch roles" ships, the app roles `reviewer` and `admin` on the Krater app page still count too. 5. Give those roles to the reviewer and admin groups (or people) in Weave. Members need no role: the app's access @@ -140,17 +140,19 @@ flowchart LR Deploy order: 1. Weave #288 merges and deploys. -2. In Weave, add `patches` to the scopes of the Krater app. -3. Run the Weave import, first as a dry run, then with `APPLY=1`: +2. In Weave, a superadmin links the Krater app to the patch `ganymede` (the Patch field on the app). The import + refuses to run without that link. +3. In Weave, add `patches` to the scopes of the Krater app. +4. Run the Weave import, first as a dry run, then with `APPLY=1`: ```sh - bin/rails patches:import_app_roles APP= PATCH=ganymede PREFIX=krater ACTOR= \ - GROUP_MAP=krater-reviewers:reviewer,krater-admins:admin - bin/rails patches:import_app_roles APP= PATCH=ganymede PREFIX=krater ACTOR= \ - GROUP_MAP=krater-reviewers:reviewer,krater-admins:admin APPLY=1 + bin/rails patches:import_app_roles APP= PATCH=ganymede PREFIX=krater ACTOR= + bin/rails patches:import_app_roles APP= PATCH=ganymede PREFIX=krater ACTOR= APPLY=1 ``` -4. Deploy Krater. + Krater needs no `GROUP_MAP`. It reads the group fallback only when `roles` is absent, and it always asks for + `roles`. +5. Deploy Krater. If Krater deploys before its Weave app lists `patches`, Weave refuses every Krater sign-in request with `invalid_scope`. Actions keep working, because the directory only leaves `patches` out. @@ -158,11 +160,15 @@ If Krater deploys before its Weave app lists `patches`, Weave refuses every Krat **While the union holds, removing someone's reviewer or admin access takes both:** remove the app role (or the group) and the patch role. +"Everyone with role X" (`list_users_with_role`: reviewer invites to Slack channels, admin keys on boxes through +`box_access`) is the union too, deduplicated by `sub`. Krater asks Weave's directory by app role +(`?role=`) and by patch role (`?patch=ganymede&patch_role=krater:`). Until Weave is set up, the patch +filter answers 403 (the app's scopes don't list `patches`) or 404 (the app isn't linked to the patch, or the patch +has no such role). Krater then logs one warning and uses the app-role list alone. Any other failure fails closed, as +the app-role list does. + Follow-up, in a later PR, once the import ran: remove the app roles and the fallback groups from `RoleMapping`, the -settings and this page, so the patch roles are the only source. Before that, `list_users_with_role` needs a new -source too. It calls `GET /api/v1/directory/users?role=`, and Weave's filter knows app roles only, so a person -who holds a role only as a patch role is not listed (no reviewer invite to Slack channels, no admin access to boxes -through `box_access`). Weave's directory needs a patch role filter first. +settings, the `?role=` list and this page, so the patch roles are the only source. ## The directory API @@ -189,7 +195,11 @@ Endpoints: scopes list `patches`; Krater reads it as in "Roles". - `GET /api/v1/directory/users?role=` (or `?group=`, which Krater doesn't use) answers `{"users": [...]}`, sorted by `sub`. Send exactly one parameter. A role or group that isn't linked to Krater answers - 404: Krater treats it as an empty list and logs a warning. The filter knows app roles only (see "Patch roles"). + 404: Krater treats it as an empty list and logs a warning. +- `GET /api/v1/directory/users?patch=&patch_role=` answers the same `{"users": [...]}` for a patch role: + direct holders and active members of a group that holds it. Send `patch` and `patch_role` together, and no `role` + or `group`. A 403 means the app's scopes don't list `patches`. A 404 means the app isn't linked to that patch, or + the patch has no such role. Krater treats both as an empty list, with one warning (see "Patch roles"). `get_user` answers are cached for 60 seconds for page views only: every state-changing action (`fresh_actor` on anything but a GET/HEAD, and Slack clicks) asks with `fresh=True`, which skips the cache. Any other failure (no answer, a 5xx, malformed JSON) raises @@ -359,7 +369,7 @@ warning. One user guardian, `PWLMINORVERIFIED` is a minor with one, and `PWLMEMBERTWO` has no `minor` field. The stub client answers the directory lookups from the same fixture with the same `RoleMapping`. `PWLPATCHREVIEWER` is a reviewer through the patch role `krater:reviewer` only, and `PWLMEMBERONE` has `patches: {}`. Like Weave, the stub's -`list_users_with_role` lists by app role, so it leaves `PWLPATCHREVIEWER` out. +`list_users_with_role` lists by app role and by patch role, so it lists `PWLPATCHREVIEWER` too. Tests change what Weave says mid-test with `StubWeaveClient.set_roles` (with `patches=` for patch roles), `set_active`, `set_minor`, `set_guardian_verified`, `set_verification_status`, `set_demographics_answered`, `remove_user` and `put_user`. The diff --git a/krater/weave/client.py b/krater/weave/client.py index 59bccb03..d6a31fbf 100644 --- a/krater/weave/client.py +++ b/krater/weave/client.py @@ -34,7 +34,8 @@ def get_user(self, sub: str, *, fresh: bool = False) -> WeaveUser | None: ... def list_users_with_role(self, role: str) -> list[WeaveUser]: - """Every user who holds a Krater role (a `ganymede:*` name, e.g. `ganymede:reviewer`).""" + """Every user who holds a Krater role (a `ganymede:*` name, e.g. `ganymede:reviewer`), as an app role or as + a patch role.""" ... def quilt_token(self) -> str: diff --git a/krater/weave/live.py b/krater/weave/live.py index 406a6457..74537e87 100644 --- a/krater/weave/live.py +++ b/krater/weave/live.py @@ -78,6 +78,8 @@ def __init__(self, settings: Settings, *, http_client: httpx.Client | None = Non self._directory_cache: TTLCache[str, WeaveUser | None] = TTLCache(DIRECTORY_CACHE_TTL_SECONDS) # CLI tokens already checked, by their sha256: (sub, monotonic time to check again at). self._cli_tokens: dict[str, tuple[str, float]] = {} + # Whether the patch-role list's 403/404 was logged (once per process: it stays so until Weave is set up). + self._patch_list_warned = False # -- OIDC ------------------------------------------------------------------------------------ @@ -193,21 +195,51 @@ def get_user(self, sub: str, *, fresh: bool = False) -> WeaveUser | None: return user def list_users_with_role(self, role: str) -> list[WeaveUser]: - # Weave's directory filters by app role key only: someone who holds the role only as a patch role is not - # listed. Fine while the app roles and patch roles are the same people (docs/weave-integration.md). + """The union of the users who hold `role` as an app role and those who hold it as a patch role in Krater's + patch, by `sub`, sorted by `sub` (docs/weave-integration.md, "Patch roles").""" key = self._roles.weave_role_key(role) response = self._directory_get("/api/v1/directory/users", params={"role": key}) if response.status_code == 404: # Weave answers 404 for a role that isn't defined on (or linked to) the Krater app. logger.warning("Weave's directory doesn't know Krater role key %r; treating it as nobody", key) + users: dict[str, WeaveUser] = {} + else: + users = {user.sub: user for user in self._user_list(response)} + for user in self._list_users_with_patch_role(role): + users.setdefault(user.sub, user) + return [users[sub] for sub in sorted(users)] + + def _list_users_with_patch_role(self, role: str) -> list[WeaveUser]: + patch, key = self._roles.patch_slug, self._roles.patch_role_key(role) + response = self._directory_get( + "/api/v1/directory/users", params={"patch": patch, "patch_role": key}, passthrough=(403,) + ) + if response.status_code in (403, 404): + # 403: the Krater app's scopes don't list `patches` yet. 404: the app isn't linked to the patch, or the + # patch has no such role. Both are the state before Weave's setup is done, so the app-role list stands. + if not self._patch_list_warned: + self._patch_list_warned = True + logger.warning( + "Weave's directory refused to list patch %r role %r (%s): link the Krater app to the patch, " + "add `patches` to its scopes, and create the role. Listing by app role only.", + patch, + key, + response.status_code, + ) return [] + return self._user_list(response) + + def _user_list(self, response: httpx.Response) -> list[WeaveUser]: data = self._directory_json(response) entries = data.get("users") if isinstance(data, dict) else None if not isinstance(entries, list): raise WeaveUnavailableError("Weave's directory returned a malformed user list") return [self._parse_user(entry) for entry in entries] - def _directory_get(self, path: str, *, params: dict[str, str] | None = None) -> httpx.Response: + def _directory_get( + self, path: str, *, params: dict[str, str] | None = None, passthrough: tuple[int, ...] = () + ) -> httpx.Response: + """A directory GET. 200 and 404 come back, and so does any status in `passthrough`; anything else raises.""" base = (self._settings.weave_api_base_url or self._settings.weave_issuer).rstrip("/") url = f"{base}{path}" response = self._authorized_get(url, params) @@ -215,6 +247,8 @@ def _directory_get(self, path: str, *, params: dict[str, str] | None = None) -> # The token may have been revoked or rotated early: fetch a new one and try once more. self._service_tokens.pop(DIRECTORY_SCOPE, None) response = self._authorized_get(url, params) + if response.status_code in passthrough: + return response if response.status_code == 403: # Not a token problem, so no refetch: the token lacks the `directory` scope, or Weave doesn't # let this app use the directory. Only an admin fixing Weave's config helps. diff --git a/krater/weave/roles.py b/krater/weave/roles.py index 7a125db9..916bc414 100644 --- a/krater/weave/roles.py +++ b/krater/weave/roles.py @@ -94,6 +94,13 @@ def weave_role_key(self, krater_role: str) -> str: except KeyError: raise ValueError(f"no Weave role key for Krater role {krater_role!r}") from None + def patch_role_key(self, krater_role: str) -> str: + """The Weave patch role key for a Krater role name, e.g. `ganymede:reviewer` -> `krater:reviewer`.""" + try: + return self.patch_role_keys[krater_role] + except KeyError: + raise ValueError(f"no Weave patch role key for Krater role {krater_role!r}") from None + def _patch_keys(self, patches: object) -> frozenset[str]: """The keys the user holds in Krater's patch, or none if `patches` is missing or malformed.""" if not isinstance(patches, Mapping): diff --git a/krater/weave/stub.py b/krater/weave/stub.py index a76f6a51..b44887f0 100644 --- a/krater/weave/stub.py +++ b/krater/weave/stub.py @@ -133,13 +133,9 @@ def get_user(self, sub: str, *, fresh: bool = False) -> WeaveUser | None: return None if user is None else self._record(user) def list_users_with_role(self, role: str) -> list[WeaveUser]: - # Like Weave's `?role=`, this lists by app role (and, as before, the group fallback), not by patch role: - # a user who holds the role only in `patches` is left out, as Weave leaves them out. - return [ - self._record(user) - for user in self._users_by_sub.values() - if role in self._mapping.krater_roles(roles=user.roles, groups=user.groups) - ] + # The union of the app-role list and the patch-role list, as the live client asks Weave for both. + records = (self._record(user) for user in self._users_by_sub.values()) + return [record for record in records if role in record.roles] def quilt_token(self) -> str: self.quilt_token_requests += 1 diff --git a/tests/compute/test_box_access.py b/tests/compute/test_box_access.py index 6c298a97..4e7a2282 100644 --- a/tests/compute/test_box_access.py +++ b/tests/compute/test_box_access.py @@ -69,6 +69,17 @@ def test_an_admin_removed_in_weave_leaves_the_boxes(db_session, admin, weave, bo assert {"added": [], "removed": [admin.user.weave_sub]} in _changes(db_session) +def test_an_admin_by_patch_role_only_goes_on_every_box(db_session, admin, weave, box) -> None: + _, row, owner_key = box + admin_key = _key(db_session, admin) + weave.set_roles(admin.user.weave_sub, [], patches={"ganymede": ["krater:admin"]}) + + added, _removed = box_access.sync_admins(db_session, weave, now=AT) + + assert added == [admin.user.weave_sub] + assert _beat(db_session, row, 5).ssh_keys == (owner_key, admin_key) + + def test_a_locked_admin_account_isnt_listed(db_session, admin, weave, box) -> None: _key(db_session, admin) weave.set_active(admin.user.weave_sub, False) diff --git a/tests/services/test_slack_notify.py b/tests/services/test_slack_notify.py index 2b3cbb3f..b29c645a 100644 --- a/tests/services/test_slack_notify.py +++ b/tests/services/test_slack_notify.py @@ -406,6 +406,20 @@ def test_sync_reviewer_invites_sees_a_reviewer_role_weave_granted_after_the_chan assert "U_NEWCOMER" in slack_client.channels[project.slack_channel_id]["members"] +def test_sync_reviewer_invites_invites_a_reviewer_by_patch_role_only( + db_session: Session, member: Actor, make_actor, weave: StubWeaveClient +) -> None: + project = new_project(db_session, member, title="Rover", write_up="w", budget_requested_cents=5000) + slack_client = FakeSlackClient() + project.slack_channel_id = slack_client.create_channel("ganymede-rover-test") + newcomer = make_actor(groups=frozenset({GROUP_MEMBER}), slack_user_id="U_PATCHREVIEWER") + weave.set_roles(newcomer.user.weave_sub, [], patches={"ganymede": ["krater:reviewer"]}) + + slack_notify.sync_reviewer_invites(db_session, slack_client, weave) + + assert "U_PATCHREVIEWER" in slack_client.channels[project.slack_channel_id]["members"] + + class _OneBrokenChannelSlackClient(FakeSlackClient): def __init__(self) -> None: super().__init__() diff --git a/tests/weave/test_live_client.py b/tests/weave/test_live_client.py index 6e5e63fd..44ca8f55 100644 --- a/tests/weave/test_live_client.py +++ b/tests/weave/test_live_client.py @@ -71,6 +71,8 @@ def __init__(self, signing_key: RSAKey) -> None: self.valid_tokens: set[str] = set() self.expires_in: object = 3600 self.directory_status: int | None = None + # The status the `?patch=&patch_role=` filter answers instead of a list (403 or 404 before Weave's setup). + self.patch_filter_status: int | None = None def handler(self, request: httpx.Request) -> httpx.Response: self.requests.append(request) @@ -107,6 +109,17 @@ def handler(self, request: httpx.Request) -> httpx.Response: return httpx.Response(401, json={"error": "invalid_token"}) if self.directory_status is not None: return httpx.Response(self.directory_status, json={"error": "boom"}) + if path == "/api/v1/directory/users" and "patch" in request.url.params: + patch, key = request.url.params["patch"], request.url.params.get("patch_role") + if self.patch_filter_status is not None: + return httpx.Response(self.patch_filter_status, json={"error": "refused"}) + if patch != "ganymede" or not key: + return httpx.Response(404, json={"error": "not_found"}) + users = sorted( + (u for u in self.directory_users.values() if key in (u.get("patches") or {}).get(patch, [])), + key=lambda u: u["sub"], + ) + return httpx.Response(200, json={"users": users}) if path == "/api/v1/directory/users": role = request.url.params.get("role") if role == "unlinked": @@ -588,7 +601,8 @@ def test_get_user_reads_patch_roles_from_the_directory_record( def test_a_fresh_lookup_sees_a_patch_role_removed(fake_weave: FakeWeave, live_client: LiveWeaveClient) -> None: admin = {**DIRECTORY_USER, "roles": [], "patches": {"ganymede": ["krater:admin"]}} fake_weave.directory_users["PWLDIR0001"] = admin - live_client.get_user("PWLDIR0001") + first = live_client.get_user("PWLDIR0001") + assert first is not None and GROUP_ADMIN in first.roles fake_weave.directory_users["PWLDIR0001"] = {**DIRECTORY_USER, "roles": [], "patches": {"ganymede": []}} fresh = live_client.get_user("PWLDIR0001", fresh=True) @@ -607,6 +621,64 @@ def test_list_users_with_role_sends_the_weave_role_key(fake_weave: FakeWeave, li assert list_request.url.params["role"] == "reviewer" +def _list_requests(fake_weave: FakeWeave) -> list[httpx.Request]: + return [r for r in fake_weave.requests if r.url.path == "/api/v1/directory/users"] + + +def test_list_users_with_role_lists_a_patch_only_holder(fake_weave: FakeWeave, live_client: LiveWeaveClient) -> None: + fake_weave.directory_users["PWLDIR0003"] = { + **DIRECTORY_USER, + "sub": "PWLDIR0003", + "roles": [], + "patches": {"ganymede": ["krater:reviewer"]}, + } + + reviewers = live_client.list_users_with_role(GROUP_REVIEWER) + + assert [u.sub for u in reviewers] == ["PWLDIR0003"] + patch_request = _list_requests(fake_weave)[1] + assert dict(patch_request.url.params) == {"patch": "ganymede", "patch_role": "krater:reviewer"} + + +def test_list_users_with_role_is_the_union_deduped_by_sub(fake_weave: FakeWeave, live_client: LiveWeaveClient) -> None: + both = {**DIRECTORY_USER, "sub": "PWLDIR0002", "roles": ["admin"], "patches": {"ganymede": ["krater:admin"]}} + app_only = {**DIRECTORY_USER, "sub": "PWLDIR0004", "roles": ["admin"]} + patch_only = {**DIRECTORY_USER, "sub": "PWLDIR0001", "roles": [], "patches": {"ganymede": ["krater:admin"]}} + other_patch = {**DIRECTORY_USER, "sub": "PWLDIR0005", "roles": [], "patches": {"europa": ["krater:admin"]}} + for user in (both, app_only, patch_only, other_patch): + fake_weave.directory_users[user["sub"]] = user + + admins = live_client.list_users_with_role(GROUP_ADMIN) + + assert [u.sub for u in admins] == ["PWLDIR0001", "PWLDIR0002", "PWLDIR0004"] + + +@pytest.mark.parametrize("status", [403, 404]) +def test_a_refused_patch_filter_falls_back_to_the_app_role_list_and_warns_once( + fake_weave: FakeWeave, live_client: LiveWeaveClient, monkeypatch: pytest.MonkeyPatch, status: int +) -> None: + warnings: list[str] = [] + monkeypatch.setattr(live_module.logger, "warning", lambda msg, *args: warnings.append(msg % args)) + fake_weave.directory_users["PWLDIR0001"] = DIRECTORY_USER + fake_weave.patch_filter_status = status + + first = live_client.list_users_with_role(GROUP_REVIEWER) + second = live_client.list_users_with_role(GROUP_REVIEWER) + + assert [u.sub for u in first] == [u.sub for u in second] == ["PWLDIR0001"] + assert len(warnings) == 1 and str(status) in warnings[0] + # A 403 here is no token problem: no new token is fetched. + assert len(_token_requests(fake_weave)) == 1 + + +def test_any_other_patch_filter_error_fails_closed(fake_weave: FakeWeave, live_client: LiveWeaveClient) -> None: + fake_weave.directory_users["PWLDIR0001"] = DIRECTORY_USER + fake_weave.patch_filter_status = 500 + + with pytest.raises(WeaveUnavailableError): + live_client.list_users_with_role(GROUP_REVIEWER) + + def test_a_403_fails_closed_without_refetching_the_token(fake_weave: FakeWeave, live_client: LiveWeaveClient) -> None: fake_weave.directory_status = 403 diff --git a/tests/weave/test_roles.py b/tests/weave/test_roles.py index f31c4e48..d600731e 100644 --- a/tests/weave/test_roles.py +++ b/tests/weave/test_roles.py @@ -151,3 +151,10 @@ def test_settings_change_the_patch_and_its_keys() -> None: assert mapping.krater_roles(roles=[], groups=[], patches={"ganymede": ["krater:admin"]}) == frozenset( {GROUP_MEMBER} ) + + +def test_patch_role_key_names_the_patch_key(mapping: RoleMapping) -> None: + assert mapping.patch_role_key(GROUP_REVIEWER) == "krater:reviewer" + assert mapping.patch_role_key(GROUP_ADMIN) == "krater:admin" + with pytest.raises(ValueError): + mapping.patch_role_key(GROUP_MEMBER) diff --git a/tests/weave/test_stub_client.py b/tests/weave/test_stub_client.py index 9c874fd1..b287a5c1 100644 --- a/tests/weave/test_stub_client.py +++ b/tests/weave/test_stub_client.py @@ -58,7 +58,7 @@ def test_exchange_code_rejects_an_unknown_code(stub_client: StubWeaveClient) -> def test_directory_lookups(stub_client: StubWeaveClient) -> None: assert stub_client.get_user("does-not-exist") is None reviewers = {u.sub for u in stub_client.list_users_with_role(GROUP_REVIEWER)} - assert reviewers == {"PWLREVIEWERONE", "PWLREVIEWERTWO", "PWLADMINONE"} + assert reviewers == {"PWLREVIEWERONE", "PWLREVIEWERTWO", "PWLADMINONE", "PWLPATCHREVIEWER"} def test_set_roles_and_remove_user_change_later_lookups(stub_client: StubWeaveClient) -> None: @@ -174,11 +174,11 @@ def test_sign_in_reads_the_patches_field(stub_client: StubWeaveClient) -> None: assert identity.roles == frozenset({GROUP_MEMBER, GROUP_REVIEWER}) -def test_list_users_with_role_lists_by_app_role_only_like_weave(stub_client: StubWeaveClient) -> None: - # Weave's `?role=` filter knows app roles only, so a patch-only reviewer is not listed. +def test_list_users_with_role_lists_a_patch_only_holder(stub_client: StubWeaveClient) -> None: + # Like the live client, which asks Weave by app role and by patch role. reviewers = {u.sub for u in stub_client.list_users_with_role(GROUP_REVIEWER)} - assert "PWLPATCHREVIEWER" not in reviewers + assert "PWLPATCHREVIEWER" in reviewers def test_set_roles_changes_patches_only_when_asked(stub_client: StubWeaveClient) -> None: