From 6d13e98ca4878fbdb4f77bf91876f5f8edd5dff6 Mon Sep 17 00:00:00 2001 From: Jasper Mayone Date: Mon, 16 Nov 2026 23:08:55 -0500 Subject: [PATCH 1/2] docs: add saml idp (#104) and nested groups (#294) designs --- docs/designs/nested-groups.md | 680 +++++++++++++++++++++++ docs/designs/saml-idp.md | 986 ++++++++++++++++++++++++++++++++++ 2 files changed, 1666 insertions(+) create mode 100644 docs/designs/nested-groups.md create mode 100644 docs/designs/saml-idp.md diff --git a/docs/designs/nested-groups.md b/docs/designs/nested-groups.md new file mode 100644 index 0000000..c741427 --- /dev/null +++ b/docs/designs/nested-groups.md @@ -0,0 +1,680 @@ +# Nested groups and access sets + +* **Author:** Jasper Mayone +* **Status:** Proposed +* **Date:** 2026-11-16 +* **Issue:** #294 + +-------------------------------------------------------------------------------- + +## Overview + +A Weave group is a flat list of users today. Groups are the unit of access: +an app is opened to groups (`ApplicationAccessGrant`), app roles and patch +roles are given to groups, and an app sees the slugs of the groups linked to +it in the `groups` claim. + +This design answers five questions from #294: + +1. Can a group contain other groups? +2. Do teams (the org chart) and access sets (who may use an app) stay one + kind of group, or become two kinds? +3. Does each app pick the name it sees for a group, or does it see the + global slug? +4. Do group permissions (see members, manage members, connect to an app) + become grants that can be delegated, or stay the `manager` membership + role? +5. How do the `groups`, `roles` and `patches` claims, access grants, app + roles and patch roles move to the new model without a break for the + apps that read them? + +## The Problem + +1. **The same people are added in many places.** A person who joins the + design team must be added to each group that opens an app to designers. + When they leave, someone must remember each of those groups. A missed + group keeps access open. +2. **A reorg can lock people out.** Apps see group slugs. If an admin + renames, splits or deletes a team group, every app linked to it changes + at once. An app that keys roles on the slug `design` breaks when `design` + becomes `product-design`. +3. **Every app learns the same names.** All apps get the same global slug, + so the slug must make sense to every app and can never change (the + `Group` model forbids slug changes for this reason). +4. **Only admins and group managers can change membership.** A manager can + add and remove members of one group. Nobody below admin can connect a + group to an app, and a manager of a parent team has no say over its + sub-teams. +5. **Groups carry more than membership.** A group can waive the Code of + Conduct and Slack steps for a sponsored project, hold patch roles, and + have managers. Nesting must say which of these pass to the members of a + child group. A wrong answer gives a waiver or a patch role to people + nobody chose. +6. **No concrete case asks for nesting yet.** Weave has 8 system groups and + few manual groups. Nesting adds a rebuild and a lock to each membership + write. The design must show that the cost buys something now, or keep + the cost low until it does. + +## Goals + +* A group can contain other groups, and a member of a child group counts + as a member of each ancestor group for access, with a fixed depth limit + and no cycles. +* Each place that reads membership (`AppAccess`, the claims, app roles, + patch roles, the directory API, waivers) reads one source of effective + membership. Each one states whether it uses direct or effective + membership. +* Waivers and patch roles never pass to people through nesting unless the + design says so on purpose and the UI shows it. +* A change to the org chart can not change what an app sees unless an + admin links the changed group to that app. +* An app can get stable names for the groups it is linked to, which do not + depend on the global slug. +* Group managers can do more without an admin, within limits that an admin + sets, and every such change goes into the audit log. +* Apps that read `groups`, `roles` or `patches` today see the same values + on the day of the migration. Any later change is opt-in for each app. +* Membership expiry (`Group::Membership#expires_at`) keeps working through + nesting: an expired membership grants nothing at any level. +* `AppAccess.explain` and `.permitted?` keep their signatures, so session + revokers (#292) and the SAML design (`docs/designs/saml-idp.md`) need no + change. + +## Non-Goals + +* **Removal preview (#293).** It will read the effective membership this + design adds, but it is a separate issue. +* **Session revokers (#292).** +* **Syncing groups from outside systems** (Google Workspace groups, Slack + user groups, an HR tool). +* **Self-service group creation.** Admins still create groups. +* **Changing system group rules.** System groups stay rule-driven. This + design only decides if they can be parents or children. +* **Changing the `patches` claim shape.** It is a contract with Quilt. + Only how patch roles reach people through groups is in scope. + +## Open Questions + +None. The author decided the six questions from #294 and one more during +drafting (see Decisions). + +## Decisions + +The author's choices during drafting (2026-11-16): + +1. **Teams vs. access sets**: two purposes. A group is a `team` or an + `access` group. Apps link only to access groups. +2. **Waivers and patch roles**: direct members only. Nesting never passes a + Code of Conduct waiver, a Slack waiver or a patch role. +3. **Storage**: a stored closure table and stored effective memberships, + rebuilt under an advisory lock in the write transaction, with a nightly + check that repairs drift. +4. **Claim names**: opt-in per app, all-or-nothing. An app with no names + keeps getting slugs. +5. **Delegation**: full grants (`view`, `manage_members`, `link_apps`), + optionally recursive. The `manager` membership role goes away. +6. **System groups**: access groups that are leaves. They can be children of + a manual access group, and they never hold children. +7. **App owners**: new. A `link_apps` holder can link an access group only to + apps they own. Admins name app owners. + +## Critical User Journeys (CUJs) + +### CUJ 1: A person joins a sub-team + +* **Given**: The team `design` is inside the team `product`, and `product` + is inside the access group `figma-users`, which is linked to the Figma + app. +* **When**: A manager with `manage_members` on `design` adds a person to + `design`. +* **Then**: In the same transaction, Weave adds effective rows for the + person in `design`, `product` and `figma-users`. Their next Figma sign-in + passes `AppAccess`. The groups claim for Figma lists `figma-users` (or + the Figma name for it). It does not list `design` or `product`, because + Figma is not linked to them. + +### CUJ 2: A reorg does not touch apps + +* **Given**: The same tree. +* **When**: An admin moves `design` from `product` into a new team + `brand`, and puts `brand` inside `figma-users`. +* **Then**: The diff of effective rows shows no change for `figma-users`, + so no token is revoked and Figma sees the same claim. + +### CUJ 3: A person leaves through expiry + +* **Given**: A contractor in `design` with `expires_at` next Friday. +* **When**: The expiry passes. +* **Then**: The effective rows for `design`, `product` and `figma-users` + expire at the same time, because each one carries the latest expiry of + the paths that reach it. The expiry sweep removes the rows and starts + `RevokeLostAppAccessJob` for the person. + +### CUJ 4: An app switches to its own names + +* **Given**: An app linked to `staff` and `figma-users`, getting slugs. +* **When**: An app owner sets names for both links (`employees`, + `designers`) and turns on claim names. +* **Then**: Weave refuses to turn it on while any linked access group has + no name. After it is on, the claim is `["designers", "employees"]`. + +### CUJ 5: A waiver does not leak + +* **Given**: A sponsored project group `hackboston` that waives the Code of + Conduct, with the team `hackboston-mentors` inside it. +* **When**: A person is added to `hackboston-mentors` only. +* **Then**: The person still must accept the Code of Conduct, because the + waiver applies to direct members of `hackboston` only. The group page of + `hackboston-mentors` says so. + +## Technical Plan (Architecture) + +### Graph rules + +```mermaid +flowchart BT + design[team: design] --> product[team: product] + product --> figma[access: figma-users] + staff[access, system: staff] --> eng[access: eng-tools] + figma -. linked .-> FigmaApp[(Figma app)] + eng -. linked .-> Tools[(Internal tools)] +``` + +* Allowed parent and child pairs: a team inside a team, a team inside an + access group, an access group inside an access group. An access group + can not go inside a team, because then a team's members would depend on + an access set. +* A system group is an access group. It can be a child of a manual access + group. It can not be a parent. +* A group with a waiver or patch role assignments can be nested, but its + waivers and patch roles apply to its direct members only (Decision 2). +* Depth limit: 6 levels. No cycles. Both are checked in Ruby before the + write and again by the rebuild, which raises inside the transaction. +* Only access groups can be the grantee of an `ApplicationAccessGrant` or + an `ApplicationRoleAssignment`. Patch role assignments can go to any + group (they are not app links). + +### Data model + +* **`groups.purpose`** (new column, `team` or `access`, not null). It is + separate from `groups.kind` (`manual` or `system`), which says who + manages the members. +* **`group_nestings`** (new). `child_group_id`, `parent_group_id`, + `created_by_id`, timestamps, `has_paper_trail`. Unique on the pair. +* **`group_closures`** (new, derived). `ancestor_id`, `descendant_id`, + `depth`. Includes a row for each group to itself (depth 0). +* **`effective_group_memberships`** (new, derived). `user_id`, `group_id`, + `expires_at`, `direct` (boolean). `expires_at` is the latest expiry of + the direct memberships that reach the group (null if any path never + expires). Unique on `user_id, group_id`. Readers filter + `expires_at IS NULL OR expires_at > now()`. +* **`group_grants`** (new). `grantee_type` (`User` or `Group`), + `grantee_id`, `group_id` (the target), `permission` (`view`, + `manage_members`, `link_apps`), `recursive` (boolean), `created_by_id`, + `has_paper_trail`. A group grantee means the group's effective members. + A recursive grant covers every descendant of the target. +* **`app_owners`** (new). `application_id` (a foreign key to + `oauth_applications`, which also holds SAML SPs), `user_id`, + `created_by_id`. +* **`app_group_names`** (new). `application_id`, `group_id`, `claim_name` (format `[a-z][a-z0-9_-]*`, unique for each + app). Plus a boolean `uses_group_claim_names` on the app. +* **`group_memberships.role`** goes away after the grant migration + (Phase 4). + +### The write path + +```mermaid +sequenceDiagram + participant C as Caller + participant G as GroupGraph.mutate! + participant DB as Postgres + participant J as Jobs + C->>G: mutate!(cause:) { change } + G->>DB: BEGIN; pg_advisory_xact_lock + G->>DB: snapshot effective rows of affected users + G->>DB: the change (membership, nesting, purpose) + G->>DB: rebuild closures + effective rows for the affected subtree + G->>DB: diff old and new rows + G->>DB: COMMIT + G->>J: after commit: RevokeLostAppAccessJob(user_id) for each user who lost a group +``` + +* Every write that changes membership or nesting goes through + `GroupGraph.mutate!`: `Group::Membership` create, update (expiry) and + destroy, `GroupNesting` create and destroy, group delete, the + `purpose` change, and `SystemGroups` sync. +* The rebuild is limited to the subtree above the changed group, and to the + users in it. A full rebuild (`GroupGraph.rebuild_all!`) runs nightly + inside the same lock and reports any row it had to change to Sentry. + Those reports are bugs. +* The diff gives the users who lost an effective group. Only they get a + `RevokeLostAppAccessJob`, which checks `AppAccess.permitted?` again as + today. +* `ExpireGroupMembershipsJob` already handles direct expiry. It now calls + `mutate!`, so effective rows follow. + +### Readers: direct or effective + +| Reader | Uses | Change | +| --- | --- | --- | +| `AppAccess.grant_decision` (group grants) | effective | `user.groups` becomes `user.effective_groups` | +| `AppAccess.linked_groups`, `.group_slugs` (`groups` claim) | effective | access groups only; names when the app opts in | +| `ApplicationRole.held_by` (`roles` claim) | effective | through `effective_group_memberships` | +| Directory API `?group=` | effective | same set as the claim | +| `PatchRole.held_by` (`patches` claim) | direct | no change (Decision 2) | +| `User#code_of_conduct_required?`, `#slack_required?` | direct | no change (Decision 2) | +| Access request approval | grant | `manage_members` on the request's group | +| Group pages | both | show direct members, then "through" rows with the path | +| Webhooks `group.member_added` / `removed` | direct | no change; effective changes are future work | + +### Grants and app owners + +* `GroupPermissions.can?(user, permission, group)` answers every + permission check. It looks for a grant on the group or, if recursive, on + an ancestor, held by the user or by a group the user is effectively in. + Admins pass every check. Superadmin-only rules stay (adding members to a + group with patch roles). +* `manage_members` lets a person add and remove members, set expiry and + approve access requests. `view` lets a person see members and the + "through" rows. `link_apps` lets a person link the group to an app they + own, and set the app's claim name for it. +* Nesting a group needs `manage_members` on both groups (and everything + under the moved group). Nesting anything inside an access group, or + changing `purpose`, is admins only. +* Admins name app owners on the app page (OAuth and, later, SAML). App + owners see their app's links and claim names on a new `/apps/:id/access` + page. They can not change the app's access policy, flags or session + revoker (#292 keeps revokers superadmin-only). + +### Claims + +* `AppAccess.group_slugs(user, app)` keeps its name and signature. It + returns the slugs of linked access groups the user is effectively in, or, + when `uses_group_claim_names` is on, their claim names. +* Turning `uses_group_claim_names` on fails while any linked access group + has no name. Linking a new access group to such an app needs a name in + the same form. + +### Migration (no change for apps on day one) + +1. Every group that is the grantee of an `ApplicationAccessGrant` or an + `ApplicationRoleAssignment` gets `purpose: access`. All system groups get + `access`. Every other group gets `team`. +2. `group_closures` and `effective_group_memberships` are built from the + direct memberships. With no nesting yet, effective equals direct, so + every claim keeps its value. A spec checks this on a copy of the + fixtures: claims before equal claims after for each app and user. +3. Each `manager` membership becomes a `manage_members` grant and a `view` + grant for that user on that group (not recursive), and the membership + becomes a plain `member`. Then the `role` column goes. +4. No app gets claim names. `uses_group_claim_names` is false everywhere. + +### Effect on other work + +* `AppAccess.explain` and `.permitted?` keep their signatures. They read + effective membership, so a user can now get access through a nested + team. #292 session revokers start from the same `RevokeLostAppAccessJob` + calls, now driven by the diff. +* #293 removal preview can read the closure table to list what a person + loses. +* The SAML design (`docs/designs/saml-idp.md`) gets the same `groups` + values through `AppAccess.group_slugs`. A SAML SP is an + `oauth_applications` row, so `app_owners` and `app_group_names` cover + SAML SPs with a plain foreign key. The two designs do not depend on each + other's order. + +## Alternatives Considered + +### Alternative A: one kind of group with a "linkable to apps" flag + +* **Pros**: No second concept for admins. Existing links need only the + flag set. +* **Cons**: Nothing stops an admin from linking a team, so a reorg can + still change what an app sees. +* **Reason for Rejection**: Rejected by author: problem 2 needs a rule, + not a convention. + +### Alternative B: nesting only, no split + +* **Pros**: The smallest change. +* **Cons**: Apps keep seeing team slugs, so problems 2 and 3 stay. +* **Reason for Rejection**: Rejected by author: it solves problem 1 only. + +### Alternative C: waivers and patch roles pass down, with guards + +* **Pros**: A sponsored project can have sub-teams without flags on each. +* **Cons**: A manager of a child team can give a waiver or a patch role + with no superadmin check. +* **Reason for Rejection**: Rejected by author: direct members only keeps + those grants deliberate. + +### Alternative D: forbid nesting for groups with waivers or patch roles + +* **Pros**: The simplest rule. +* **Cons**: The first real case needs a rule change. +* **Reason for Rejection**: Rejected by author: direct-only gives the same + safety and still allows nesting. + +### Alternative E: recursive query at read time + +* **Pros**: No derived tables, no stale data. +* **Cons**: Each `AppAccess` check, token refresh and userinfo call runs a + recursive query. Finding who lost access after a change needs a check of + every affected user. +* **Reason for Rejection**: Rejected by author: stored rows make reads one + join and make the loss diff exact. + +### Alternative F: recursive query with a per-user cache + +* **Pros**: Fast reads without derived tables. +* **Cons**: A write path that forgets to clear the cache gives stale access + with no way to see it. +* **Reason for Rejection**: Rejected by author: the closure table's drift + is visible to the nightly check. + +### Alternative G: per-app names required for every app + +* **Pros**: The slug stops being a contract, so it can change. +* **Cons**: Each link needs a name. Two apps can see one group under two + names. +* **Reason for Rejection**: Rejected by author: opt-in keeps day one + unchanged and costs nothing for apps that are happy with slugs. + +### Alternative H: keep global slugs + +* **Pros**: No new table. +* **Cons**: Slugs stay frozen. +* **Reason for Rejection**: Rejected by author: it leaves problem 3. + +### Alternative I: keep managers, recursive + +* **Pros**: Small change. Admins already know managers. +* **Cons**: A manager must be a member. An app owner can not run an access + group without being in it. +* **Reason for Rejection**: Rejected by author: grants separate "can act + on" from "is in". + +### Alternative J: managers plus a single "app owner" grant + +* **Pros**: Less than full grants. +* **Cons**: A second migration to full grants when needs grow. +* **Reason for Rejection**: Rejected by author: one migration now. + +### Alternative K: system groups as parents, or as teams + +* **Pros**: As parents, an admin can put a team inside `staff`. As teams, + every app link goes through a manual access group. +* **Cons**: As parents, `staff` then has people who are not staff by + role. As teams, every existing link needs a wrapper group. +* **Reason for Rejection**: Rejected by author: as leaves, system groups + keep their exact meaning and need no wrappers. + +### Alternative L: `link_apps` without app owners + +* **Pros**: No new concept. (Admin-only holders, or any app.) +* **Cons**: Admin-only gives no delegation. Any app lets one grant open any + restricted app. +* **Reason for Rejection**: Rejected by author: app owners limit links to + apps the person is responsible for. + +-------------------------------------------------------------------------------- + +## Non-Functional Requirements + +* **Correctness over speed**: the derived tables are the access source, so + every write that changes them runs inside `GroupGraph.mutate!`. A spec + scans `app/` and `lib/` for direct writes to `group_memberships`, + `group_nestings`, `group_closures` and `effective_group_memberships` + outside `GroupGraph` and fails on one. +* **Locking**: one transaction-scoped advisory lock serializes graph + writes. Weave's write rate on groups is low, so one lock is enough. Never + take `User#lock!` or `with_lock` on a user inside `mutate!` (it locks the + account, not the row). +* **Known gap, not changed here**: `AppAccess.permitted?` does not check + `User#can_authenticate?`, so a re-check for a locked user passes on an + `everyone` app. `AppAccess.token_usable?` does check it. #292 tracks this. +* **Rollout**: Phases 1 and 2 change no claim value. Nesting UI (Phase 3) + ships behind the Flipper flag `group_nesting`, on for admins first. +* **Rollback**: Phase 2 readers can switch back to direct membership by + one method (`User#effective_groups` returns `groups`) while the flag is + off, because no nesting exists yet. + +-------------------------------------------------------------------------------- + +## Detailed Implementation Plan + +Code is named by class or module, because a running refactor +(untangle-codebase) can move files. Check each path against `main` before +work starts. Each phase is one pull request from `main`, started after the +one before it merges. + +### Phase 1: group purpose + +#### 1. `db/migrate/_add_purpose_to_groups.rb` (Create) + +* **Type / Scope**: Migration. +* **Proposed Changes**: Add `purpose` (string, null). Backfill in a + separate data migration: `access` for system groups and for every + grantee group of `ApplicationAccessGrant` or `ApplicationRoleAssignment`, + `team` for the rest. Then set `NOT NULL` with a check constraint + (`purpose IN ('team','access')`), in the strong_migrations safe order. + +#### 2. `Group` (Modify) + +* **Type / Scope**: Model. +* **Proposed Changes**: `enum :purpose, { team:, access: }`. Validations: + a system group is `access`; `purpose` changes only by an admin, and a + change to `team` fails while the group has app links. + +#### 3. `ApplicationAccessGrant`, `ApplicationRoleAssignment` (Modify) + +* **Type / Scope**: Models. +* **Proposed Changes**: A group grantee must be `access`. + `PatchRoleAssignment` keeps any group. + +#### 4. Admin group form and pages (Modify) + +* **Type / Scope**: `Admin::GroupsController`, `admin/groups` views, + `admin/oauth_applications/show`. +* **Proposed Changes**: A purpose field (with help text) on create and + edit. The app page's group picker lists only access groups. + +#### 5. Specs (Modify / Create) + +* **Type / Scope**: RSpec. +* **Proposed Changes**: The backfill, the validations, and the picker. + +### Phase 2: derived tables and readers (no claim change) + +#### 6. `db/migrate/_create_group_graph_tables.rb` (Create) + +* **Type / Scope**: Migration. +* **Proposed Changes**: `group_nestings`, `group_closures`, + `effective_group_memberships` with the indexes in "Data model" + (`effective_group_memberships (user_id, group_id)` unique, + `(group_id, user_id)`, `(expires_at)`). A data step runs + `GroupGraph.rebuild_all!`. + +#### 7. `GroupNesting`, `GroupClosure`, `EffectiveGroupMembership` (Create) + +* **Type / Scope**: Models. +* **Proposed Changes**: `GroupNesting` holds the graph rules (allowed + pairs, no system parent, depth 6, no cycle). The two derived models are + read-only (`readonly?` true outside `GroupGraph`). + +#### 8. `GroupGraph` (Create, `app/services/group_graph.rb`) + +* **Type / Scope**: Service. +* **Proposed Changes**: `mutate!(cause:) { }`, `rebuild_for!(group_ids)`, + `rebuild_all!`, `lock!` (`pg_advisory_xact_lock` with a fixed key), + `diff(before, after)`. After commit, enqueue + `RevokeLostAppAccessJob.perform_later(user_id:)` for each user in the + loss set. + +#### 9. Every membership writer (Modify) + +* **Type / Scope**: Models, services, jobs, controllers. +* **Proposed Changes**: Wrap each write in `GroupGraph.mutate!`: + `Group::Membership` (create, update of `expires_at`, destroy), + `Group` destroy, `SystemGroups.sync!`, `ExpireGroupMembershipsJob`, + `DeletionPipeline`, `PatchRoleImport`, `Admin::GroupMembershipsController`, + `GroupMembersController`, `AccessRequests` (approve adds a member), and + the `one_time_fixes` rake task if it writes memberships. The membership + callbacks that start `RevokeLostAppAccessJob` today go: the diff does it. + +#### 10. `User` (Modify) + +* **Type / Scope**: Model. +* **Proposed Changes**: `has_many :effective_group_memberships` (active + scope) and `has_many :effective_groups, through:`. `groups` stays + direct. `code_of_conduct_required?` and `slack_required?` keep `groups` + (direct) with a comment that cites Decision 2. + +#### 11. Readers that switch to effective (Modify) + +* **Type / Scope**: Services, models, controllers. +* **Proposed Changes**: `AppAccess.grant_decision` and `.group_slugs`, + `ApplicationRole.held_by`, `Api::V1::Directory::UsersController` + (`users_in_group` and role holders via groups). `PatchRole.held_by` + stays direct with a comment. + +#### 12. `GroupGraphCheckJob` (Create) and `config/recurring.yml` (Modify) + +* **Type / Scope**: Job. +* **Proposed Changes**: Nightly `rebuild_all!` in the lock. Reports each + changed row to Sentry with the group and user IDs. + +#### 13. Specs (Create) + +* **Type / Scope**: RSpec. +* **Proposed Changes**: `GroupGraph` (rebuild, diff, expiry as the latest + path expiry, lock), the claims-equal migration spec (every app and user: + `groups`, `roles`, `patches` before equal after), and the + direct-write scan spec from Non-Functional Requirements. + +### Phase 3: nesting + +#### 14. `lib/feature_flags.rb` (Modify) + +* **Type / Scope**: Feature flags. +* **Proposed Changes**: Add `group_nesting` to `FeatureFlags::FLAGS`. + +#### 15. `Admin::GroupNestingsController`, `GroupNestingsController` (Create) and routes + +* **Type / Scope**: Controllers. +* **Proposed Changes**: Add and remove a child group. Admins anywhere. + Others need `manage_members` on both groups and on every descendant of + the moved group, and can not touch an access group parent. Both go + through `GroupGraph.mutate!`. + +#### 16. Group pages (Modify) + +* **Type / Scope**: `groups/show`, `admin/groups/show`, `groups/index`. +* **Proposed Changes**: "Child groups" and "Parent groups" lists. A + "Through other groups" table of effective members with the path. On a + group with a waiver or patch roles, a note that they apply to direct + members only. Follow `docs/UI.md` (`.table-wrap`, `time_label`, + `confirm-submit` on remove). + +### Phase 4: grants replace managers + +#### 17. `db/migrate/_create_group_grants.rb` (Create) + +* **Type / Scope**: Migration. +* **Proposed Changes**: The `group_grants` table. A data step makes + `manage_members` and `view` grants for every `manager` membership and + sets those memberships to `member`. A later migration in the same phase + removes `group_memberships.role` after the code no longer reads it + (`ignored_columns` first). + +#### 18. `GroupGrant` (Create) and `GroupPermissions` (Create) + +* **Type / Scope**: Model, service. +* **Proposed Changes**: `GroupPermissions.can?(user, permission, group)` + and `.holders(permission, group)` (for mail). Recursive grants check + `group_closures` ancestors. Group grantees use effective membership. + +#### 19. Manager readers (Modify) + +* **Type / Scope**: Policies, services, mailers, views. +* **Proposed Changes**: Replace `managed_by?`, `managers` and + `role_manager` with `GroupPermissions`: `GroupPolicy`, + `Group::MembershipPolicy`, `AccessRequestPolicy`, `AccessRequests`, + `AccessRequestMailer` (mail `holders(:manage_members, group)`), + `MemberTasks`, `Oauth::AuthorizationsController` and the + `doorkeeper/authorizations/access_denied` view, `access_requests/_form`, + `groups/index` and `groups/show`, `admin/groups/show`, + `admin/oauth_applications/show`, `admin/users/new` and `edit`, + `shared/_topbar` (the Groups link shows for any grant holder), + `Admin::GroupMembershipsController`, `Group::Membership` + (`manager_is_manual` validation goes). + +#### 20. Grant admin UI (Create) + +* **Type / Scope**: `Admin::GroupGrantsController` and a section on the + admin group page. +* **Proposed Changes**: Add and remove grants (user or group grantee, + permission, recursive). Admins only. Each change is in PaperTrail. + +### Phase 5: app owners and claim names + +#### 21. `db/migrate/_create_app_owners_and_group_names.rb` (Create) + +* **Type / Scope**: Migration. +* **Proposed Changes**: `app_owners`, `app_group_names` (each with a + foreign key to `oauth_applications`, `on_delete: :cascade`), and + `uses_group_claim_names` (boolean, default false) on + `oauth_applications`. + +#### 22. `AppOwner`, `AppGroupName` (Create) + +* **Type / Scope**: Models. +* **Proposed Changes**: Validations: owner is an active user; claim name + format and per-app uniqueness; the group is `access` and linked to the + app. The app model validates that `uses_group_claim_names` is on only + when every linked access group has a name. + +#### 23. `AppAccess.group_slugs` (Modify) + +* **Type / Scope**: Service. +* **Proposed Changes**: Return claim names when the app opts in. + +#### 24. `AppsAccessController` (Create, `/apps/:id/access`) and views + +* **Type / Scope**: Controller, views. +* **Proposed Changes**: For app owners: the app's linked access groups, + link and unlink (needs `link_apps` on the group), claim names and the + opt-in switch. No access policy, flags or revoker. Admin app pages get an + "Owners" section. + +#### 25. Docs (Create / Modify) + +* **Type / Scope**: `docs/GROUPS.md` (Create), `docs/OAUTH.md`, + `docs/WEBHOOKS.md`, `CLAUDE.md` (Modify). +* **Proposed Changes**: Teams vs. access groups, nesting rules, the + direct-or-effective table, grants, app owners, claim names, with Mermaid + diagrams. `docs/OAUTH.md` describes the `groups` claim with names. + `docs/WEBHOOKS.md` says member events are for direct changes. + +#### 26. Specs (Create) + +* **Type / Scope**: RSpec request, model, policy and UI specs for Phases 3 + to 5. +* **Proposed Changes**: Each CUJ as a request spec. Policy specs for every + grant path, including recursive and group grantees. A spec that a waiver + and a patch role do not reach a member of a child group. + +### Verification Plan + +* **Tests**: `bundle exec rspec` and `bin/rails test`. +* **Static analysis**: `bin/rubocop`, `bin/brakeman --no-pager`, + `bin/rails zeitwerk:check`, `spec/ui/view_conventions_spec.rb`. +* **Migration proof**: the claims-equal spec on fixtures, and the same + comparison run on staging data before and after Phase 2 (a rake task + that prints differences; it must print none). +* **Load**: on staging, time `GroupGraph.rebuild_all!` and one + `mutate!` on the largest group. Record both in the PR. +* **UI**: every changed page at 1280 and 390 wide, light and dark, with + keyboard, screenshots in each PR. + +*Drafted with EGM* diff --git a/docs/designs/saml-idp.md b/docs/designs/saml-idp.md new file mode 100644 index 0000000..ee917ef --- /dev/null +++ b/docs/designs/saml-idp.md @@ -0,0 +1,986 @@ +# SAML identity provider + +* **Author:** Jasper Mayone +* **Status:** Proposed (revised after review and re-audit) +* **Date:** 2026-11-16 +* **Issue:** [#104](https://github.com/patchworklabsorg/weave/issues/104) +* **Review:** `design_drafts/saml-idp/consolidated_review_report.md` + +-------------------------------------------------------------------------------- + +## Overview + +Weave signs members in to other apps through OAuth 2.0 and OpenID Connect +(OIDC). Some apps accept only SAML 2.0 for single sign-on. This design makes +Weave a SAML 2.0 identity provider (IdP) for those apps. SAML calls such an +app a service provider (SP). + +An SP is an OAuth app row in Weave with a SAML extension. So an SP gets the +same access rules, access grants, app roles, launcher tile and access +requests as an OAuth app, with no copy of that code. + +Admins add and change SPs in Weave. A new SP needs no code change and no +deploy. Weave signs each SAML response with a key from encrypted +credentials, in the same way as the OIDC signing key. + +### Terms + +* **Weave ID:** the public identifier of a member (`user.p_id`). OIDC apps + get it as `sub`. +* **Access decision:** the result of `AppAccess.explain(user, app)`. It + checks the app's access policy (`everyone` or `restricted`), access + grants, app roles, email domains, the Code of Conduct, guardian consent + for members under 18, and identity verification. +* **Patch:** a grant program in Patchwork Labs. The `patches` claim lists a + member's roles in each patch. +* **Admin, superadmin, owner:** the admin tiers on `users.role`. A + superadmin is an admin with more rights. An owner is above a superadmin. + +## The Problem + +1. **Apps that need SAML have no path to Weave.** Some paid tools (chat + workspaces on enterprise plans, HR and payroll tools, some dashboards) + give single sign-on only through SAML. Patchwork Labs must keep a + separate account for each person in each of those tools. Weave does not + disable those accounts when a person leaves a group or leaves Patchwork + Labs. +2. **A second sign-in path can bypass access rules.** If SAML has its own + access logic, the two paths will become different over time. A person + whom OAuth refuses can then sign in through SAML. +3. **A signing key needs a rotation path.** Each SP stores the IdP + certificate. If Weave replaces its signing key and the SPs do not have + the new certificate first, every SP refuses Weave's responses at the same + time. + +This design solves problem 1 at sign-in time only. A person who loses access +can not sign in to the SP again. Their SP account and any open SP session +stay until the SP ends them. Session revokers +([#292](https://github.com/patchworklabsorg/weave/issues/292), +`docs/designs/session-revokers.md`) cover open sessions later. + +## Goals + +* A member signs in to a SAML SP with Weave through SP-initiated sign-in: + the SP sends an `AuthnRequest` and Weave answers. +* Each SP is an `oauth_applications` row with a 1:1 + `saml_service_providers` row. `AppAccess` needs no SAML code. +* Every SAML sign-in uses the same access decision as an OAuth sign-in, + including the birthday step that the OAuth authorize page runs first. +* The NameID is the member's Weave ID. It does not change when the member + changes their email address. +* Weave sends only the attributes that an admin selects for the SP. Weave + sends `email` only when the address is verified or the SP has email + domains. +* Admins create SPs by pasting or uploading the SP's metadata XML, or by + typing the entity ID and the ACS URL. +* Weave publishes its IdP metadata at `/saml/metadata`. The metadata lists + the current signing certificate and, during a rotation, the next one. +* Outside development, Weave accepts only HTTPS ACS URLs. +* The `saml_idp` Flipper flag controls sign-in. Admins can test before + launch. +* Weave builds and signs SAML through the `saml_idp` gem. It has no + XML signature code of its own. + +## Non-Goals + +* **IdP-initiated sign-in** (the member starts from Weave). It has a weaker + security model. Add it when a real SP needs it. +* **Checking the SPs' request signatures.** Weave posts responses only to + the ACS URL it stores for the SP, so a request signature adds little. + Add it when a real SP requires it. +* **Fetching SP metadata from a URL.** Admins paste or upload it. +* **An `emailAddress` NameID format.** +* **Weave as a SAML service provider.** Weave does not accept sign-in from + another SAML IdP. +* **SAML Single Logout (SLO), encrypted assertions and SCIM + provisioning.** SPs create accounts at first sign-in (just-in-time). +* **Self-service SPs.** Only admins add SPs. +* **Nested groups.** The `groups` attribute uses today's groups. The nested + groups design (`docs/designs/nested-groups.md`) changes + `AppAccess.group_slugs`, which SAML then follows. +* **Changes to OAuth or OIDC behaviour** for OAuth apps. + +## Decisions + +The author's choices (2026-11-16, revised after review the same day): + +1. **SP model:** an `oauth_applications` row plus a 1:1 + `saml_service_providers` row with a cascading foreign key. Doorkeeper + refuses every OAuth flow for a SAML row. +2. **Signing key:** in encrypted credentials, like the OIDC key. Rotation + uses a "next" slot and two deploys. No database table and no new role. +3. **No replay cache.** Weave posts only to the stored ACS URL. Each stored + request is used once. +4. **SP request signatures:** not checked in version one. +5. **Version one scope:** SP-initiated sign-in, metadata by paste or upload, + the persistent NameID. +6. **Library:** the `saml_idp` gem, version 1.0. +7. **Refused sign-in:** a signed SAML `Response` with the status + `urn:oasis:names:tc:SAML:2.0:status:RequestDenied`, posted to the ACS + URL. Weave writes the reason to the SAML sign-in log. +8. **NameID:** the Weave ID. The author accepted that SPs can use it to + match the same person across their records. + +## Library findings + +The author read the `saml_idp` 1.0.0 gem source (released 2025-10-09): + +* **Signing key:** `SamlIdp.config.x509_certificate` and `secret_key` + accept a Proc, which the gem calls for each signature + (`lib/saml_idp/signed_info_builder.rb` L67-68, + `lib/saml_idp/signature_builder.rb` L23-24). Weave sets both from one + memoized credentials read. +* **Metadata:** `SamlIdp::MetadataBuilder#build_key_descriptor` writes one + certificate (`lib/saml_idp/metadata_builder.rb` L56-64). Weave subclasses + the builder to write one `KeyDescriptor` for each published certificate. +* **Refused sign-in:** `SamlIdp::ResponseBuilder` always writes the status + `Success` (`lib/saml_idp/response_builder.rb` L59). Weave builds the + refused `Response` XML itself and signs it through the gem's + `SamlIdp::Signable` module. + +## Critical User Journeys (CUJs) + +### CUJ 1: SP-initiated sign-in + +* **Given:** a member with a Weave account, and an enabled SP that is + restricted to the group `design`. The member is in `design`. +* **When:** the member opens the SP and selects "Sign in with SSO". The SP + sends an `AuthnRequest` to `/saml/sso`. +* **Then:** + 1. Weave stores the request and redirects the browser to a same-site + page. + 2. If the member has no Weave session, Weave asks them to sign in, then + continues the same request. + 3. `AppAccess` permits the member. + 4. Weave posts a signed `Response` to the stored ACS URL. The NameID is + the member's Weave ID. The attributes are only those set for the SP. + +### CUJ 2: Refused sign-in + +* **Given:** the same SP, and a member who is not in `design`. +* **When:** the member starts SP-initiated sign-in. +* **Then:** Weave posts a signed `Response` with the status + `RequestDenied` and no assertion. Weave writes the refusal and its + `AppAccess` reason to the SAML sign-in log. The SP shows its own error. + The member can still request access from the Weave launcher tile, if the + app has an access request group. + +### CUJ 3: Admin adds an SP from metadata + +* **Given:** an admin and the SP's metadata XML file. +* **When:** the admin selects "SAML" on the new app page and uploads the + file. +* **Then:** Weave reads the entity ID and the HTTP-POST ACS URL from the + file and shows the form to review. Weave saves nothing until the admin + submits the form. Weave makes no network request. + +### CUJ 4: Signing certificate rotation + +* **Given:** the current signing key and certificate in credentials. +* **When:** an owner adds `next_signing_key` and `next_certificate` to + credentials and deploys. +* **Then:** the IdP metadata lists both certificates. The owner tells each + SP owner to add the new certificate (the list is on + `/admin/oauth_applications?protocol=saml`). When all SPs have it, the + owner moves the next pair to the current slot, removes the old pair and + deploys again. `docs/SAML.md` has the runbook. + +## Technical Plan (Architecture) + +### Components + +```mermaid +flowchart LR + SP[Service provider] -- AuthnRequest --> Entry["/saml/sso
Saml::SsoController#create"] + Entry --> Req[(saml_requests)] + Entry -- 303 --> Resume["/saml/sso/resume
Saml::SsoController#show"] + Resume -- no session --> SignIn[Sign-in, ReturnAfterSignIn] + SignIn --> Resume + Resume --> Access[AppAccess.explain] + Access --> App[(oauth_applications
+ saml_service_providers)] + Resume --> Builder[Saml::ResponseBuilder] + Builder --> Attr[Saml::Attributes] + Builder --> Key[SamlSigningKey
credentials] + Resume --> Log[(saml_sign_ins)] + Resume -- signed Response, HTTP-POST --> SP + Meta["/saml/metadata"] --> Key +``` + +### Data model + +* **`oauth_applications.redirect_uri`** becomes nullable. A SAML row has no + redirect URI. Doorkeeper's `allow_blank_redirect_uri` allows a blank one + only for SAML rows. +* **`saml_service_providers`** (new), one row for each SP: + * `oauth_application_id`: unique, foreign key with + `ON DELETE CASCADE`. + * `entity_id`: unique. + * `acs_url`: the only URL Weave posts to for this SP. + * `attribute_keys`: the attribute keys Weave sends (from + `Saml::Attributes::ALL`). + * `enabled`. + + All access fields (`access_policy`, `requires_code_of_conduct`, + `requires_guardian_consent`, `requires_verification`, `email_domains`) + and launcher fields stay on `oauth_applications`. +* **`saml_requests`** (new). It holds one `AuthnRequest` between the SP's + post and the response. Columns: a random `handle`, the SP, the SAML + request ID, `relay_state`, `force_authn`, `is_passive` and `expires_at` + (10 minutes). Weave deletes the row when it answers the request, so each + request is used once: Weave answers only if its `DELETE` removed exactly + one row. A job deletes expired rows. +* **`saml_sign_ins`** (new), the SAML sign-in log. One row for each + response to a signed-in member: the user, the SP, the request ID, the result (`success`, + `refused`, `unsupported`), the `AppAccess` reason and the time. It holds + no IP address. `DataRetention` deletes rows after the period in + `config/kyc/data_retention.yml`. Takeout exports a member's rows, and the + deletion pipeline deletes them. + +### OAuth rows that are SAML SPs + +* `Doorkeeper::Application` gets `has_one :saml_service_provider` and a + `saml?` method. +* Doorkeeper's `allow_grant_flow_for_client` refuses a SAML row at the + authorize endpoint and for `client_credentials` at the token endpoint + (`unauthorized_client`). Doorkeeper does not call it for + `authorization_code` or `refresh_token`. A SAML row never has a code or a + token, so those grants fail with `invalid_grant`. +* `Oauth::TokensController` refuses introspection and revocation for a + SAML client with `unauthorized_client` (403). +* A SAML row gets a random client secret that Weave never shows. The admin + page hides the client ID and the secret for SAML rows. +* Doorkeeper's own `/oauth/applications` pages refuse SAML rows. +* A SAML row has no OAuth scopes. + +### Request flow + +1. **Entry.** `Saml::SsoController#create` (POST, HTTP-POST binding) and + `#new` (GET, HTTP-Redirect binding) receive the `AuthnRequest`. This + action never reads or writes the session or the flash. A cross-site + POST carries no `SameSite=Lax` session cookie, and a new cookie would + replace the member's real session. +2. **Request checks.** `Saml::RequestValidator` decodes the request with + `saml_idp`. It checks these items: + * the issuer is an enabled SP; + * `Destination` equals Weave's SSO URL; + * `IssueInstant` is not older than 5 minutes and not more than 1 + minute in the future; + * `AssertionConsumerServiceURL`, if present, equals the SP's `acs_url`; + * `ProtocolBinding`, if present, is HTTP-POST. + + If a check fails, Weave shows an error page. Weave never posts to a URL + that the request supplies. +3. **Store and redirect.** Weave writes a `saml_requests` row and redirects + (303) to `GET /saml/sso/resume?handle=`. The browser sends the + session cookie on this same-site GET. +4. **Resume.** `Saml::SsoController#show` runs these checks in this order: + 1. Load the live row by handle. An unknown, expired or used handle, or + an SP that is now disabled, gets the error page (404). + 2. No session: if `is_passive`, answer with the status `NoPassive` (no + log row, because there is no member). Else store the resume path + with `ReturnAfterSignIn` (short, so it fits the 1024-character + limit) and send the member to sign in. + 3. The member must pass the same gate as OAuth sign-in: + `email_verified? && can_authenticate?`. Else the same page as + OAuth. + 4. The `saml_idp` flag must be on for the member. Else 404. + 5. An admin who impersonates the member gets the error page. Weave sends + nothing, the same rule as deletion requests. + 6. `force_authn`: answer with the status `RequestUnsupported`. This + matches the OIDC side, which refuses `prompt=login` (#87). + 7. No birthday and the app requires guardian consent: ask for the + birthday first, as the OAuth authorize page does, then continue. +5. **Access decision.** `AppAccess.explain(user, app)` decides. The SP row + is an OAuth app row, so `AppAccess` needs no change. Every refusal, + including a missing Code of Conduct or guardian consent, gets + `RequestDenied`. OAuth sends those two cases to the step that fixes them. + SAML does not, because it must answer the SP. +6. **Response.** `Saml::ResponseBuilder` builds the response with + `saml_idp`: + * Permitted: a `Response` with an assertion, both signed (RSA-SHA256), + with the Weave ID as a persistent + NameID, the selected attributes, `AuthnContextClassRef` + `urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified`, `NotOnOrAfter` + of 5 minutes, `InResponseTo` the request ID and an + `AudienceRestriction` to the SP's entity ID. + * Refused or unsupported: `Saml::DeniedResponse`, a signed `Response` + with the status code and no assertion. +7. **Post.** Weave deletes the `saml_requests` row and writes a + `saml_sign_ins` row. Then it renders an auto-submit form that posts + `SAMLResponse` and `RelayState` to the stored `acs_url`. The page sets + the CSP `form-action` to `'self'` and the origin of the stored `acs_url`, + with the pattern of `OauthClientRedirectOrigins`. The submit script uses + the CSP nonce. + +### Attributes + +`Saml::Attributes` is a registry. Each entry has a SAML `Name`, a +`FriendlyName` (the key), `NameFormat` +`urn:oasis:names:tc:SAML:2.0:attrname-format:uri` and a value. Each value +comes from the same method that the OIDC claim uses, so the two protocols +send the same values. SPs store these names, so they never change after +launch. A blank value is left out. + +| Key | `Name` | Value | Rule | +| --- | --- | --- | --- | +| `email` | `urn:oid:0.9.2342.19200300.100.1.3` | `AppAccess.email_for` | Sent only if the SP has email domains or `user.email_verified?`, the rule of the OIDC `email_verified` claim. | +| `given_name` | `urn:oid:2.5.4.42` | `user.first_name` | | +| `family_name` | `urn:oid:2.5.4.4` | `user.last_name` | | +| `name` | `urn:oid:2.16.840.1.113730.3.1.241` | `user.full_name` | | +| `weave_id` | `urn:patchworklabs:weave:attribute:weave_id` | `user.p_id` | The same as the NameID. | +| `groups` | `urn:patchworklabs:weave:attribute:groups` | `AppAccess.group_slugs` | One `AttributeValue` for each slug. | +| `roles` | `urn:patchworklabs:weave:attribute:roles` | `AppAccess.role_keys` | One `AttributeValue` for each key. | +| `patches` | `urn:patchworklabs:weave:attribute:patches` | `PatchRoles.for` | One `AttributeValue` for each pair, as `=`. Role keys can contain `:`, so the separator is `=`. | + +Weave's IdP entity ID is `/saml/metadata`. The metadata lists the +SSO endpoint `/saml/sso` for both the HTTP-POST and the +HTTP-Redirect binding, and the NameID format +`urn:oasis:names:tc:SAML:2.0:nameid-format:persistent`. + +An admin selects the keys for each SP. This selection is the SAML gate that +matches the OIDC scope gate on `patches`. + +### Signing key + +`SamlSigningKey` reads encrypted credentials, in the same way as +`OidcSigningKey`: + +```yaml +saml: + signing_key: + certificate: + next_signing_key: + next_certificate: +``` + +* Weave signs with `signing_key` and `certificate`. A missing or + mismatched pair raises on first use, like the OIDC key. +* `/saml/metadata` lists `certificate` and, if set, `next_certificate`. +* Test uses a key that it generates in memory, like the OIDC test key. +* A daily job warns owners 60 and 14 days before the certificate expires. + +### Feature flag + +`saml_idp` in `FeatureFlags::FLAGS`. The flag is on for the Flipper group +`admins` before launch, and on for everyone at launch. + +* `/saml/sso/resume` (the page that answers) returns 404 when the flag is + off for the viewer. +* `/saml/sso` (the entry) does not check the flag, because it has no signed-in + viewer. It only stores the request for an enabled SP. +* `/saml/metadata` is always public. It holds only certificates. +* The SAML section on the admin app pages shows when the flag is on for + the viewer. + +### Admin pages + +* The new app page gets a protocol choice: OAuth or SAML. It can not change + after create. +* For a SAML row, the app page shows a SAML section: entity ID, ACS URL, + attributes, enabled, and the metadata paste or upload field. It hides the + client ID, the secret, the redirect URIs and the scopes. +* The SAML sign-in log shows on the app page. +* Grants, roles, access requests, the launcher fields, the patch link and + the superadmin-only access actions are the existing OAuth app features. + They need no change. +* The app list gets a protocol column and a `protocol` filter. + +### Effect on other work + +* `AppAccess.explain` and `.permitted?` do not change. + `RevokeLostAppAccessJob` does not change. SAML has no tokens, so it has + nothing to revoke. +* Session revokers (#292) can use the plain `oauth_applications` foreign + key for SAML SPs too. A successful SAML response can write an + `app_sign_ins` row when #292 ships. +* Nested groups (`docs/designs/nested-groups.md`) can keep plain foreign + keys to `oauth_applications` for `app_owners` and `app_group_names`. + +## Risks and Mitigations + +| Risk | Effect | Mitigation | +| --- | --- | --- | +| An unverified email reaches an SP that links accounts by email | Account takeover in the SP | Send `email` only when verified or when the SP has email domains. No email NameID. | +| A SAML row is used as an OAuth client | OAuth tokens for an app that should only get SAML | `allow_grant_flow_for_client` refuses all flows. The secret is random and never shown. A spec calls each OAuth endpoint with a SAML row. | +| A bug or a vulnerability in `saml_idp` signing | Forged or broken responses | Weave signs only. It parses no signed XML from SPs. Dependabot watches the gem. A spec checks the signed response with `ruby-saml` and with signature-wrapping cases. | +| The gem is abandoned | No security fixes | The gem surface is small: response, metadata and `Signable`. Replace it with `saml2` or `ruby-saml` behind the same `Saml::` classes. | +| The access decision runs at sign-in only | A person who lost access keeps an open SP session | Stated in The Problem. Session revokers (#292). Ask SP owners to set short sessions. | +| An SP does not load the next certificate before the swap | That SP refuses Weave's responses | Two-deploy rotation, an SP list on the admin page, the runbook, and expiry warnings at 60 and 14 days. | +| A request is replayed | A second response to the same SP | Weave posts only to the stored ACS URL, to the member's own browser. Each stored request is used once. | +| An admin impersonates a member | The admin signs in to the member's HR or payroll SP | SAML sign-in is refused while impersonating. | +| A minor with no birthday | `AppAccess` can not see the age | The birthday step runs before the access decision. | +| `saml_sign_ins` growth | Storage and personal data | No IP column. Retention key in `config/kyc/data_retention.yml`. Takeout and deletion cover it. | +| No signing key in credentials | Every SAML sign-in fails | Raises on first use with a clear message, like the OIDC key. Boot is not blocked. | + +## Alternatives Considered + +### Alternative A: SPs in `config/saml.yml` + +* **Pros:** no admin page. Each change gets code review. +* **Cons:** each new SP needs a deploy. +* **Reason for Rejection:** the author requires SPs that admins add with + no deploy (#104). + +### Alternative B: a separate `SamlServiceProvider` model with polymorphic grant tables + +* **Pros:** a model with SAML fields only. +* **Cons:** grants, roles and access requests lose their foreign keys and + `ON DELETE CASCADE`. Each lookup must match a type column, or a SAML SP + and an OAuth app with the same ID share access. The SP table copies 12 + access columns. +* **Reason for Rejection:** the author first chose this. The review showed + the ID collision and the copied columns. The author changed to the 1:1 + extension, which keeps one access source and real foreign keys. + +### Alternative C: a supertype `apps` table + +* **Pros:** real foreign keys and no Doorkeeper rows for SAML. +* **Cons:** moves columns off a model that Doorkeeper owns. Each app is two + rows. +* **Reason for Rejection:** the author chose the 1:1 extension, which gives + the same integrity with less change. + +### Alternative D: signing certificates in a database table with a SAML officer role + +* **Pros:** rotation with no deploy, and per-step audit records. +* **Cons:** a table, a four-state machine, an admin page, a new role in the + locked `config/roles.yml`, for a certificate that lasts 3 years. It also + departs from the OIDC key pattern. +* **Reason for Rejection:** the author first chose this. After review the + author chose credentials and two deploys. + +### Alternative E: a replay cache in Redis or the database + +* **Pros:** stops the reuse of a request ID. +* **Cons:** Redis is a cache that can evict keys. Its error behaviour is + unclear. The test cache is `:null_store`. A reused request can only send + the member's own assertion to the stored ACS URL. +* **Reason for Rejection:** the author removed it. Single-use stored + requests and the fixed ACS URL cover the risk. + +### Alternative F: check SP request signatures in version one + +* **Pros:** proves the request came from the SP. +* **Cons:** pure-Ruby XML signature checks, the HTTP-Redirect signature + format, and failures when the SP rotates its key. +* **Reason for Rejection:** the fixed ACS URL removes most of the risk. Add + it when a real SP requires it. + +### Alternative G: the `saml2` gem + +* **Pros:** typed builders, signing through libxmlsec1. +* **Cons:** a native dependency on the Alpine and musl image. +* **Reason for Rejection:** `saml_idp` signs in pure Ruby and adds no + native build step. + +### Alternative H: `ruby-saml` with Weave-built responses + +* **Pros:** the Ruby SAML library with the longest history. +* **Cons:** it is built for SPs. Weave would write its own signing code. +* **Reason for Rejection:** #104 rejects signing code in Weave. + +### Alternative I: a Weave page for a refused sign-in + +* **Pros:** the member sees the reason and an access-request button. +* **Cons:** a second page to keep the same as the OAuth one. Some SPs wait + for a response. +* **Reason for Rejection:** the author keeps `RequestDenied` for version + one. The launcher tile offers the access request. + +### Alternative J: a per-SP NameID + +* **Pros:** two SPs can not use the NameID to match the same person. +* **Cons:** support must look the value up. A key change makes every SP + see new users. +* **Reason for Rejection:** the author chose the Weave ID, the same value + as the OIDC `sub`, so support staff can read it directly. + +-------------------------------------------------------------------------------- + +## Non-Functional Requirements + +* **Security:** see Risks and Mitigations. A failed request check never + posts. Metadata upload parses with Nokogiri strict mode, with no DTD, no + external entities, no network and a 1 MB limit. +* **Rate limit:** `saml/ip`, 20 requests a minute for paths that start + with `/saml/`, the same as `oauth/ip`. +* **Rollout:** Phase 1 and Phase 2 change nothing for members. Phase 3 + ships with the flag on for `admins` only. The flag goes on for everyone + after one real SP passes the manual test. +* **Rollback:** turn the flag off. SAML rows stay as disabled apps. + +-------------------------------------------------------------------------------- + +## Detailed Implementation Plan + +Each phase is one pull request from `main`. Start a phase only after the pull +request before it merges. Paths are as of 2026-11-16. A refactor +(untangle-codebase) can move files, so compare each path with `main` before +work starts. + +### Phase 1: SAML rows and admin pages + +#### 1. `db/migrate/_allow_blank_redirect_uri.rb` (Create) + +* `change_column_null :oauth_applications, :redirect_uri, true`. + +#### 2. `db/migrate/_create_saml_service_providers.rb` (Create) + +* `oauth_application_id` bigint, not null, unique index, foreign key to + `oauth_applications` with `on_delete: :cascade`. +* `entity_id` string, not null, unique index. +* `acs_url` string, not null. +* `attribute_keys` string array, not null, default `[]`. +* `enabled` boolean, not null, default `true`. +* Timestamps. +* Run `bundle exec annotaterb models` after the migration. + +#### 3. `app/models/saml_service_provider.rb` (Create) + +* `belongs_to :application, class_name: "Doorkeeper::Application", + foreign_key: :oauth_application_id, inverse_of: :saml_service_provider`. +* `has_many :saml_requests, dependent: :delete_all` and + `has_many :saml_sign_ins, dependent: :delete_all` (Phase 3 adds the + models; add these lines in Phase 3). +* `has_paper_trail`. +* Validations: `entity_id` present and unique; `acs_url` an HTTPS URL + outside development; each `attribute_keys` entry in + `Saml::Attributes::ALL`. + +#### 4. `app/models/concerns/oauth_application_saml.rb` (Create) + +* `has_one :saml_service_provider, foreign_key: :oauth_application_id, + inverse_of: :application, dependent: :destroy`. +* `accepts_nested_attributes_for :saml_service_provider`. +* `saml?` returns `saml_service_provider.present?`. It works on an unsaved + record, because the controller builds the child before `save`. +* Validation: a SAML row has blank `scopes`. Doorkeeper's own + `RedirectUriValidator` keeps the redirect URI rule for other rows. + +#### 5. `config/initializers/oauth_application_public_id.rb` (Modify) + +* Add `Doorkeeper::Application.include OauthApplicationSaml` next to the + other includes. + +#### 6. `config/initializers/doorkeeper.rb` (Modify) + +* `allow_grant_flow_for_client { |_flow, application| !application&.saml? }`. + Doorkeeper 5.9.9 passes the `Doorkeeper::Application` + (`oauth/pre_authorization.rb` L121, + `oauth/client_credentials/validator.rb` L31). It can be nil on the + password path. +* `allow_blank_redirect_uri { |_server_flows, application| application.saml? }`. + Doorkeeper passes the server's grant flows and the record under + validation (`orm/active_record/redirect_uri_validator.rb` L11). + +#### 7. `app/controllers/oauth/tokens_controller.rb` (Modify) + +* Before `introspect` and `revoke`: if the authenticated client's + application is `saml?`, render the `unauthorized_client` error with 403. + +#### 8. `config/routes.rb` (Modify, Phase 1 part) + +* Keep the Doorkeeper `applications` routes, but make + `Doorkeeper::ApplicationsController` refuse SAML rows: add + `app/controllers/doorkeeper_applications_saml_guard.rb` (Create), a + `before_action` that redirects to the admin app page for a `saml?` + record, included from `config/initializers/doorkeeper.rb` in a + `to_prepare` block. + +#### 9. `app/services/saml/attributes.rb` (Create) + +* `Saml::Attributes::ALL`: a frozen hash from key to `name`, + `friendly_name` and a value lambda `(user, application)`, as in the + Attributes table. +* `Saml::Attributes.for(user, application)` returns + `[[name, friendly_name, [values]], ...]` for the selected keys, without + blank values. + +#### 10. `app/services/saml/metadata_import.rb` (Create) + +* Input: pasted XML, or an uploaded file. Refuse more than 1 MB before + parsing. +* Parse with `Nokogiri::XML(xml) { |config| config.strict.nonet }`. Do not + set `noent` or `dtdload`. Refuse the document if + `doc.internal_subset` is present. +* Read one `EntityDescriptor` with one `SPSSODescriptor`. If the file has + more, refuse it. +* Return unsaved values: `entityID` and the first + `AssertionConsumerService` with the HTTP-POST binding. Ignore signing + certificates and `AuthnRequestsSigned`. +* Errors: a `Saml::MetadataImport::Error` with a message key in + `config/locales/saml.en.yml` (Create). + +#### 11. `app/controllers/admin/oauth_applications_controller.rb` (Modify) + +* `new`: a `protocol` parameter (`oauth` or `saml`). Show the SAML choice + only when the `saml_idp` flag is on for the admin. +* `create`: + * With `import=1` and a metadata field: run `Saml::MetadataImport`, + fill `saml_service_provider_attributes`, and render `new` again + with the values. Save nothing. + * For `protocol=saml`: build the row with `confidential: true`, blank + `redirect_uri`, blank `scopes`, and the nested + `saml_service_provider_attributes` (`entity_id`, `acs_url`, + `enabled`, `attribute_keys: []`). On success redirect to the app + page with a notice. Do not call `show_secret_once`. + * For `protocol=oauth`: as today. +* `update`: for a SAML row, permit only `name`, the launcher fields, the + patch field rule as today, and `saml_service_provider_attributes` with + `:id`. Never `redirect_uri`, `scopes` or `confidential`. A row's protocol + can not change. +* `regenerate_secret`: refuse for SAML rows with an alert. +* `index`: a `protocol` filter (`oauth`, `saml`). + +#### 12. `app/views/admin/oauth_applications/` (Modify and Create) + +* `new.html.erb`: the protocol choice; for SAML, the + `_saml_fields.html.erb` partial (Create) with entity ID, ACS URL, + attribute checkboxes, enabled, and a metadata text area and file field + with an "Import" button (`import=1`). +* `edit.html.erb`: the same partial for SAML rows, without the protocol + choice. +* `show.html.erb`: for SAML rows, hide the client ID, secret, redirect + URIs and scopes (L440 reads `redirect_uri.split`), and show the SAML + section. Show the SAML section only when the flag is on for the viewer. +* `index.html.erb`: a "Protocol" column. For SAML rows, the Client ID and + Type columns show "SAML". +* Follow `docs/UI.md`. Run `spec/ui/view_conventions_spec.rb`. + +#### 13. `lib/feature_flags.rb` (Modify) + +* Add `saml_idp` to `FeatureFlags::FLAGS` with a description. + +#### 14. `Gemfile` (Modify) + +* Add `gem "saml_idp", "~> 1.0"`. +* Add `gem "ruby-saml", "~> 1.18"` to `group :test`. It checks Weave's + responses as a test SP. +* Build the Alpine image to check it. + +#### 15. Specs and factories (Create) + +* `spec/factories/saml_service_providers.rb`, and a `:saml` trait on the + `oauth_application` factory. +* `spec/models/saml_service_provider_spec.rb`: validations. +* `spec/requests/oauth_saml_row_refused_spec.rb`: + * `/oauth/authorize`: `unauthorized_client`; + * `/oauth/token` with `client_credentials`: `unauthorized_client`; + with `authorization_code` and `refresh_token`: `invalid_grant`; + * `/oauth/introspect`, `/oauth/revoke`: 403 `unauthorized_client`; + * `/oauth/applications/:id` for a SAML row: redirect. +* `spec/services/saml/metadata_import_spec.rb`: a good file, two + `SPSSODescriptor`s, an internal DTD, an external entity, a file over + 1 MB, no HTTP-POST ACS. +* `spec/services/saml/attributes_spec.rb`: `email` with and without + verification and email domains; blank names left out; multi-value + `groups`, `roles`, `patches`; the `patches` separator. +* `spec/requests/admin_oauth_application_saml_spec.rb`: import, create, + no secret shown, update parameters, refused `regenerate_secret`, the + SAML choice hidden with the flag off. + +#### 16. `docs/SAML.md` (Create) + +* What an SP is in Weave, how to add one, and the attributes table. + +### Phase 2: signing key and metadata + +#### 17. `config/initializers/saml_idp.rb` (Create) + +* `SamlSigningKey` module, beside `OidcSigningKey`: + * `current` returns `{ key: OpenSSL::PKey::RSA, certificate: + OpenSSL::X509::Certificate }` from `saml.signing_key` and + `saml.certificate`. It raises `SamlSigningKey::MissingKey` with + the setup steps when one is missing, and + `SamlSigningKey::Mismatch` when the certificate's public key is not + the key's. + * `next_pair` returns the same shape from `saml.next_signing_key` and + `saml.next_certificate`, or nil. A mismatched next pair raises. + * `published_certificates` returns `[current certificate, next + certificate]` without nil. + * Values are memoized for the process. Test generates a 2048-bit key + and a self-signed certificate in memory. +* `SamlIdp.configure`: + * `x509_certificate` and `secret_key`: Procs that return the PEM of + `SamlSigningKey.current`. + * `algorithm`: `:sha256`. + * `base_saml_location`: `SamlIdp::Urls.base + "/saml"`. + * `single_service_post_location` and + `single_service_redirect_location`: `SamlIdp::Urls.base + + "/saml/sso"`. + * `entity_id`: `SamlIdp::Urls.base + "/saml/metadata"`. + * `name_id.formats`: persistent only, value `user.p_id`. +* `Weave.oauth_base_url` in `lib/weave.rb` (Modify): returns + `ENV["OIDC_ISSUER"].presence || (production ? Weave.url : test ? + "http://www.example.com" : "http://localhost:3000")`. The OIDC `issuer` + block in `config/initializers/doorkeeper_openid_connect.rb` (Modify) + calls it, and SAML calls it, so the rule exists once. + (`SamlIdp::Urls.base` is `Weave.oauth_base_url`.) + +#### 18. `app/services/saml/metadata_builder.rb` (Create) + +* Subclass of `SamlIdp::MetadataBuilder`. Override `build_key_descriptor` + to write one `KeyDescriptor use="signing"` for each + `SamlSigningKey.published_certificates` entry. + +#### 19. `app/controllers/saml/metadata_controller.rb` (Create), `config/routes.rb` (Modify) + +* `class Saml::MetadataController < ActionController::Base`. No session, + no sign-in, no flag check. +* `GET /saml/metadata`: XML from `Saml::MetadataBuilder`, with + `Cache-Control: public, max-age=3600`. + +#### 20. `app/jobs/saml_certificate_expiry_job.rb` (Create), `config/recurring.yml` (Modify) + +* Schedule: `every day at 7am`. +* For the current and the next certificate, send a warning when today is + exactly `not_after.to_date - 60` or `not_after.to_date - 14`. The job + keeps no state. A missed run means one missed warning, which is + acceptable because there are two warnings. +* Recipients: `User.owner`. +* Mail: `AdminMailer#saml_certificate_expiring(user, certificate, days)` + (Modify `app/mailers/admin_mailer.rb`), with + `app/views/admin_mailer/saml_certificate_expiring.text.erb` and + `.html.erb` (Create). + +#### 21. Specs (Create) + +* `spec/initializers/saml_signing_key_spec.rb`: missing key, mismatched + pair, mismatched next pair, published certificates. +* `spec/requests/saml_metadata_spec.rb`: the entity ID, both bindings, one + certificate, two certificates, public with the flag off. +* `spec/services/saml/metadata_builder_spec.rb`. +* `spec/jobs/saml_certificate_expiry_job_spec.rb`: day 60, day 14, other + days, the next certificate. +* `spec/initializers/oidc_issuer_spec.rb` (or the existing OIDC spec): the + issuer is unchanged after `Weave.oauth_base_url`. + +#### 22. `docs/SAML.md` (Modify) + +* The metadata URL, the entity ID, and the rotation runbook with a + Mermaid sequence: add next, deploy, tell SP owners, swap, deploy. + +### Phase 3: sign-in + +#### 23. `db/migrate/_create_saml_requests.rb` (Create) + +* `handle` string, not null, unique index. +* `saml_service_provider_id` bigint, not null, foreign key to + `saml_service_providers` with `on_delete: :cascade`. +* `request_id` string, not null. +* `relay_state` string, null. +* `force_authn`, `is_passive` booleans, not null, default `false`. +* `expires_at` datetime, not null, index. +* `created_at`. + +#### 24. `db/migrate/_create_saml_sign_ins.rb` (Create) + +* `user_id` bigint, not null, foreign key to `users` with cascade. +* `saml_service_provider_id` bigint, not null, foreign key to + `saml_service_providers` with cascade. +* `request_id` string, not null. +* `result` string, not null (`success`, `refused`, `unsupported`). +* `reason` string, null. +* `created_at`; index on `(saml_service_provider_id, created_at)` and on + `(user_id, created_at)`. + +#### 25. `app/models/saml_request.rb`, `app/models/saml_sign_in.rb` (Create) + +* `SamlRequest`: `belongs_to :saml_service_provider`; + `has_secure_token :handle, length: 32`; scope `live` (`expires_at > + now`); `self.consume!(handle)`: `live.where(handle:).delete_all == 1` + after it loads the row, so two parallel resumes can not both answer. +* `SamlSignIn`: `belongs_to :user`, `belongs_to :saml_service_provider`; + enum `result`. +* `SamlServiceProvider`: add the two `has_many` lines from item 3. +* `User` (`app/models/user.rb`, Modify): `has_many :saml_sign_ins, + dependent: :delete_all`. + +#### 26. `app/services/saml/request_validator.rb` (Create) + +* Decode with `SamlIdp::Request.from_deflated_request` for both bindings. + It inflates a deflated value (Redirect binding) and uses the plain + decoded value when inflate fails (POST binding) + (`lib/saml_idp/request.rb` L8-23). +* Checks, each with an error key in `config/locales/saml.en.yml`: + * `unknown_issuer`: no enabled SP with that entity ID; + * `bad_destination`: `Destination` present and not + `/saml/sso`. A missing `Destination` is allowed, because + unsigned Redirect requests often leave it out; + * `stale`: `IssueInstant` older than 5 minutes or more than 1 minute in + the future; + * `acs_mismatch`: `AssertionConsumerServiceURL` present and not the + SP's `acs_url`. `AssertionConsumerServiceIndex` is ignored; + * `bad_binding`: `ProtocolBinding` present and not HTTP-POST; + * `relay_state_too_long`: `RelayState` over 80 bytes. Refuse, do not + cut. +* Returns `Result(sp:, request_id:, relay_state:, force_authn:, + is_passive:)` or `Result(error:)`. + +#### 27. `app/services/saml/response_builder.rb`, `app/services/saml/denied_response.rb` (Create) + +* `ResponseBuilder.call(user:, saml_request:)`: calls + `SamlIdp::SamlResponse.new(...)` directly (not the controller mixin). + The constructor takes positional arguments + (`lib/saml_idp/saml_response.rb` L27-45), in this order: + * `reference_id` and `response_id`: new UUIDs; + * `issuer_uri`: the IdP entity ID; + * `principal`: the user; NameID persistent, `user.p_id`; + * `audience_uri`: the SP's `entity_id`; + * `saml_request_id`: the stored `request_id`; + * `saml_acs_url`: the SP's `acs_url`; + * `algorithm`: `:sha256`; + * `authn_context_classref`: + `urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified`; + * `expiry`: 300 seconds; + * `asserted_attributes_opts`: the attributes from + `Saml::Attributes.for`, in the gem's attribute config shape; + * `signed_message_opts`: true, and `signed_assertion_opts`: true (the + default), so both the response and the assertion are signed; + * `encryption_opts`: nil; `compression_opts`: false. + + Returns the base64 `SAMLResponse`. +* `DeniedResponse.call(saml_request:, status:)`: builds this XML with + Builder and signs it with `SamlIdp::Signable`. The class provides the + methods that `Signable::ClassMethods` names (`raw`, `reference_id`, + `digest`, `algorithm`; `lib/saml_idp/signable.rb` L117-127), and calls + `signed`: + + ```xml + + + + + + + + + ``` + + `status` is `RequestDenied`, `NoPassive` or `RequestUnsupported`. + +#### 28. `app/controllers/saml/sso_controller.rb` (Create), views, `config/routes.rb` (Modify) + +* `class Saml::SsoController < ApplicationController`. +* Routes: `get "/saml/sso", to: "saml/sso#new"`, + `post "/saml/sso", to: "saml/sso#create"`, + `get "/saml/sso/resume", to: "saml/sso#show", as: :saml_sso_resume`. +* For `new` and `create`: + * `skip_before_action :authenticate_user!, :track_user_session`; + * `skip_around_action :attribute_privileged_changes`; + * `skip_forgery_protection only: :create`; + * `before_action { request.session_options[:skip] = true }`, so Rails + writes no session cookie; + * validate; on error render `error` (400); else create the + `SamlRequest` and `redirect_to saml_sso_resume_url(handle:), + status: :see_other`. +* For `show`: + * `skip_before_action :authenticate_user!`; the action calls + `authenticate_user!` itself after the `is_passive` check (step 4.2). + * The checks in "Request flow", step 4, in that order. + * The birthday step: `session[:birthday_return_to] = request.fullpath` + and `redirect_to slack_onboarding_path`, as + `Oauth::AuthorizationsController` does. + * Impersonation: render `error` (403) with `data_handling.impersonating`. + * Then steps 5 to 7: `SamlRequest.consume!`, the response, the + `SamlSignIn` row, render `post`. +* `include OauthClientRedirectOrigins` and + `content_security_policy(only: :show) { |policy| + policy.form_action(:self, *[redirect_origin_of(@saml_request&.saml_service_provider&.acs_url)].compact) }`. + The origin comes from the stored SP, never from a request parameter. +* `app/views/saml/sso/post.html.erb` (Create): a form with the hidden + `SAMLResponse` and `RelayState` fields, a `