Skip to content

Commit bf77ad2

Browse files
matteiusclaude
andcommitted
docs(mfa-1): mark T20/T23-T26 completed via upstream TDD; commit source PRDs
T20 (audit log call sites), T23 (service unit tests), T24 (Fernet unit tests), T25 (integration enroll/verify), and T26 (integration lockout/recovery/tenant) were all satisfied by tests written by the agents implementing T11-T16 as part of their RED-then-GREEN TDD cycles, rather than as separate sweep tasks. Plan now reflects this with explicit provenance to the upstream commits. Also commits the 9 source PRDs + index README that were drafted earlier and left untracked while MFA-1 implementation ran. Aggregate test status (2026-05-09 sandbox run, SQLite + ephemeral Fernet key): 143 passed, 1 known test-infra DetachedInstanceError flake in T21 idempotent case (production logic is correct; fixture re-fetch needed). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent a556749 commit bf77ad2

11 files changed

Lines changed: 1089 additions & 33 deletions

‎docs/prds/ENT-1-saml-sso.md‎

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
# ENT-1 — SAML SSO (per-organization Service Provider)
2+
3+
**Status:** Draft · **Owner:** TBD · **Tier:** 2 · **Depends on:** ORG-1
4+
5+
## Summary
6+
Become a SAML 2.0 Service Provider so enterprise customers can configure their IdP (Okta, Entra ID / Azure AD, Google Workspace, OneLogin, JumpCloud, Ping) to sign their users into our products. Each Organization configures its own IdP; users from that org can SP-initiated or IdP-initiated sign in, with **just-in-time provisioning** into the org.
7+
8+
## Why now
9+
- This single feature is the gate to every enterprise sale above ~$30k ACV. Auth0 charges per-user explicitly because of this.
10+
- OwlBooks accounting customers (firms) increasingly require SSO with their existing IdP.
11+
- Builds on ORG-1: the IdP config attaches to an Organization, not a Tenant.
12+
13+
## Goals
14+
1. Per-org SAML configuration: entity ID, SSO URL, X.509 cert, NameID format, attribute mapping.
15+
2. SP metadata endpoint per org (`/saml/{org_slug}/metadata.xml`) for IdP setup.
16+
3. SP-initiated login from `members.<brand>.com/saml/{org_slug}/login`.
17+
4. IdP-initiated login at the ACS endpoint.
18+
5. JIT provisioning: if the IdP-asserted user does not yet exist, create them and add to the org.
19+
6. Attribute mapping for email, given name, family name, role.
20+
7. SAML-only org enforcement: optional flag — users in this org cannot use password login.
21+
8. Audit logged.
22+
23+
## Non-goals
24+
- IdP-side metadata auto-discovery / metadata refresh polling (manual paste / re-upload is fine for v1).
25+
- Encrypted SAML assertions (signing only). Add later if a customer requires.
26+
- SAML logout (Single Logout). Defer; logout from our side is sufficient.
27+
- WS-Federation. (Don't.)
28+
29+
## Library
30+
[`python3-saml`](https://github.com/SAML-Toolkits/python3-saml) (OneLogin) — battle-tested, used by Auth0 fork projects, GitLab, etc. AGPL-incompatible? It's MIT — fine.
31+
32+
## Data model
33+
34+
```
35+
fief_organization_saml_configs
36+
id uuid pk
37+
organization_id uuid fk organizations unique
38+
enabled bool default false
39+
idp_entity_id text -- IdP's entity URI
40+
idp_sso_url text -- IdP's SSO endpoint (HTTP-Redirect or HTTP-POST)
41+
idp_slo_url text null
42+
idp_x509_cert text -- PEM
43+
name_id_format text default 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress'
44+
attr_email text default 'email'
45+
attr_given_name text default 'given_name'
46+
attr_family_name text default 'family_name'
47+
attr_role text null -- e.g. "groups"; mapped via role_mapping
48+
role_mapping jsonb default '{}' -- {"firm-admin":"admin","firm-member":"member"}
49+
default_role_id uuid fk roles
50+
enforce_saml_only bool default false -- users in this org cannot password-login
51+
jit_provisioning bool default true
52+
created_at timestamp
53+
updated_at timestamp
54+
```
55+
56+
SP signing key (one per environment, not per org) lives in env / KMS.
57+
58+
## Endpoints
59+
60+
### SP metadata + auth
61+
| Method | Path | Purpose |
62+
|--------|-----------------------------------------------|----------------------------------------|
63+
| GET | `/saml/{org_slug}/metadata.xml` | SP metadata (consumed by IdP) |
64+
| GET | `/saml/{org_slug}/login` | SP-initiated AuthnRequest redirect |
65+
| POST | `/saml/{org_slug}/acs` | Assertion Consumer Service |
66+
| GET | `/saml/{org_slug}/sls` | (Future) SLO endpoint |
67+
68+
### Admin
69+
| Method | Path | Purpose |
70+
|--------|----------------------------------------------------------------|-----------------------------------------|
71+
| GET | `/api/organizations/{id}/saml` | Read config |
72+
| PUT | `/api/organizations/{id}/saml` | Upsert (XML metadata or fields) |
73+
| DELETE | `/api/organizations/{id}/saml` | Disable |
74+
| POST | `/api/organizations/{id}/saml/test` | Generate a fresh AuthnRequest URL |
75+
76+
## Flows
77+
78+
### SP-initiated
79+
1. User visits `members.<brand>.com/saml/acme/login`.
80+
2. We redirect to IdP with a signed AuthnRequest.
81+
3. IdP authenticates user, POSTs SAMLResponse to ACS.
82+
4. We validate signature, in-response-to ID, audience, NotOnOrAfter, NotBefore.
83+
5. Resolve user by email; create if `jit_provisioning` and missing.
84+
6. Add to org with `default_role_id` (overridden by `role_mapping[asserted_role]`).
85+
7. Issue our session + redirect to original destination.
86+
87+
### IdP-initiated
88+
- IdP posts to `/saml/{org_slug}/acs` directly. We validate, treat exactly like SP-initiated minus the InResponseTo check.
89+
90+
### JIT user creation
91+
- Email is the unique key.
92+
- Email auto-marked verified (the IdP is authoritative).
93+
- No password set; `password_hash` is null. If `enforce_saml_only`, user can never set a password through our flows.
94+
95+
### SAML-only enforcement
96+
- When org has `enforce_saml_only = true` and a user tries to log in via password:
97+
- If they have any membership where the org enforces SAML, redirect them to that org's `/saml/{slug}/login`.
98+
- Edge: user is in two orgs, one enforced and one not — block password if **all** their orgs enforce; otherwise allow but the SAML org session won't activate without SSO.
99+
100+
## Org admin UI
101+
Inside ORG-1's "Organization" tab, new "Single sign-on" sub-page:
102+
1. Step-by-step: copy our SP metadata URL → paste it in your IdP → upload IdP metadata XML or paste fields → test login → flip "Enabled" toggle.
103+
2. Show a clear banner if SP signing key is rotated.
104+
105+
## Edge cases
106+
- IdP cert rotation — admin re-uploads. We do not auto-fetch (yet).
107+
- Clock skew — `python3-saml` allows tolerance; expose as `SAML_CLOCK_SKEW_SECONDS` env (default 60).
108+
- Replay — store last seen response IDs for 10 minutes; reject duplicates.
109+
- User's email asserted via SAML differs from their existing account email — match on the asserted email only; if user must merge, support intervenes.
110+
- Brand → tenant → org match — the request hostname determines the tenant/brand; the URL slug determines the org. Mismatch = 404.
111+
112+
## Security
113+
- Sign all AuthnRequests.
114+
- Require signed assertions; reject unsigned.
115+
- Validate audience = our SP entity ID.
116+
- Validate ACS URL = the request URL.
117+
- Reject if IdP cert PEM doesn't parse or doesn't match assertion signature.
118+
119+
## Telemetry
120+
- `saml.authnrequest.sent`, `saml.acs.{success,failure}`, `saml.jit_provisioned`, `saml.replay_blocked`, `saml.signature_mismatch`.
121+
122+
## Risks
123+
- python3-saml uses `xmlsec` C lib; deployment dependency. Already common; small operational risk.
124+
- Misconfigured IdP — most failures will be at setup time. Mitigation: a verbose `/saml/{slug}/test` endpoint that surfaces parse errors to the admin.
125+
126+
## Open questions
127+
- Multiple IdPs per org? Defer (uncommon).
128+
- IdP discovery for users on a public login page? Use email-domain hint: if email matches `acme.com` and an org has SAML enforced for that domain, redirect. Track as separate "Domain capture" PRD.
129+
130+
## Sequencing
131+
~2-3 sprints. Sprint 1: schema + metadata + AuthnRequest + ACS happy path. Sprint 2: JIT + role mapping + admin UI. Sprint 3: SAML-only enforcement, edge cases, hardening, customer pilot.
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
# ENT-2 — SCIM 2.0 provisioning
2+
3+
**Status:** Draft · **Owner:** TBD · **Tier:** 2 · **Depends on:** ORG-1, ENT-1
4+
5+
## Summary
6+
Expose a SCIM 2.0 ([RFC 7642 / 7643 / 7644](https://datatracker.ietf.org/doc/html/rfc7644)) endpoint per organization so customer IdPs (Okta, Entra, JumpCloud, OneLogin) can auto-provision and de-provision users and groups. The IdP authenticates with a per-org bearer token; supported resources are **Users** and **Groups** (groups → org roles).
7+
8+
## Why now
9+
- Pairs with ENT-1. Enterprise customers want both: SAML for sign-in and SCIM so removing someone from the IdP automatically revokes their access in our products.
10+
- Without it, customer admins must manually deprovision in our UI — a deal-breaker for any compliance-conscious buyer.
11+
12+
## Goals
13+
1. Per-org SCIM endpoint with bearer-token auth.
14+
2. CRUD on Users.
15+
3. CRUD on Groups, mapping `Group.displayName` → an org role (configurable mapping reused from ENT-1).
16+
4. PATCH operations (RFC 7644 §3.5.2) for active flag, name attrs, email, group memberships.
17+
5. Filtering for `userName eq` and `displayName eq` (the two filters Okta/Entra actually use).
18+
6. Pagination (`startIndex`, `count`).
19+
7. Schema discovery endpoints.
20+
8. Deprovisioning: `active=false` PATCH terminates all sessions and refresh tokens for that user in that org.
21+
9. Audit logged.
22+
23+
## Non-goals
24+
- SCIM filter language fully (just the few operators IdPs use).
25+
- Bulk operations endpoint (RFC 7644 §3.7) — defer.
26+
- ETags / If-Match concurrency control — defer.
27+
- Schema extensions (we'll only expose `User`, `Group`, `EnterpriseUser`).
28+
29+
## Library
30+
- Don't pull in a heavy SCIM library — none in Python ecosystem are great. Implement directly with FastAPI + a small `scim/schemas.py` module. ~600 LOC total.
31+
- Reference: Okta and Entra agents both stick close to the spec; test against both.
32+
33+
## Data model
34+
35+
```
36+
fief_organization_scim_tokens
37+
id uuid pk
38+
organization_id uuid fk organizations
39+
token_hash text -- SHA-256
40+
label text -- e.g. "Okta production"
41+
last_used_at timestamp null
42+
created_at timestamp
43+
revoked_at timestamp null
44+
index (organization_id, revoked_at)
45+
46+
fief_organization_scim_external_ids
47+
id uuid pk
48+
organization_id uuid fk organizations
49+
resource_type enum('user','group')
50+
resource_id uuid -- user_id or role_id
51+
external_id text -- IdP-assigned ID
52+
unique (organization_id, resource_type, resource_id)
53+
unique (organization_id, resource_type, external_id)
54+
```
55+
56+
We map SCIM Groups to existing org roles. A new Group call creates a role within the org's tenant if one doesn't already exist (configurable behavior).
57+
58+
## Endpoints (all under `/scim/v2/orgs/{org_slug}/...`)
59+
60+
| Method | Path | Notes |
61+
|--------|-------------------------------------|------------------------------------------------|
62+
| GET | `/ServiceProviderConfig` | Capabilities |
63+
| GET | `/Schemas` | Schema list |
64+
| GET | `/ResourceTypes` | |
65+
| GET | `/Users` | Filter, paginate |
66+
| POST | `/Users` | Create (or 409 if exists) |
67+
| GET | `/Users/{id}` | |
68+
| PUT | `/Users/{id}` | Replace |
69+
| PATCH | `/Users/{id}` | RFC 7644 patch ops |
70+
| DELETE | `/Users/{id}` | Soft-deactivate (sets `active=false`) |
71+
| GET | `/Groups` | |
72+
| POST | `/Groups` | |
73+
| GET | `/Groups/{id}` | |
74+
| PUT | `/Groups/{id}` | |
75+
| PATCH | `/Groups/{id}` | Common: add/remove members |
76+
| DELETE | `/Groups/{id}` | |
77+
78+
## Schemas (subset)
79+
80+
### User
81+
- `userName` → email (lowercase, unique within tenant)
82+
- `name.givenName`, `name.familyName`
83+
- `emails[primary=true].value` → email (must equal userName)
84+
- `active` → soft-deactivate flag
85+
- `externalId` → IdP-assigned
86+
- `groups` (read-only listing of role memberships within the org)
87+
88+
### Group
89+
- `displayName` → role name within the org's role table
90+
- `members[].value` → user IDs
91+
- `externalId`
92+
93+
## Auth
94+
- Bearer token in `Authorization: Bearer <token>`. Token is opaque (random 40 bytes), stored as SHA-256 hash, scoped to the org in the URL.
95+
- Token created in admin UI, copyable once on creation, never again.
96+
97+
## Behaviour details
98+
99+
### Create user (`POST /Users`)
100+
- If a user with `userName` exists in the tenant: attach to org if not already, return 200/201.
101+
- Else create new user with `active=true`, email-verified (asserted by IdP), no password.
102+
- Add membership with the org's `default_role_id`.
103+
- Honor any `groups` array by also adding/removing role memberships.
104+
105+
### Deactivate (`PATCH active=false`)
106+
- Remove user's membership from this org.
107+
- Revoke all refresh tokens issued to this user that carry this `org_id` claim.
108+
- Invalidate active session tokens with this `org_id`.
109+
- Do NOT delete the user account; they may still belong to other orgs.
110+
111+
### Group membership PATCH
112+
- Standard ops `add`, `remove`, `replace` on `members`.
113+
- Each membership change writes an audit log entry.
114+
115+
### Filtering
116+
- Support: `userName eq "x"`, `displayName eq "x"`, `externalId eq "x"`. Reject other filters with 400 + `scimType=invalidFilter`.
117+
118+
## Error format
119+
All errors per RFC 7644 §3.12: JSON body with `schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"]`, `status`, `detail`, optional `scimType`.
120+
121+
## Edge cases
122+
- IdP sends a User with `userName=Alice@FIRM.com` but our store has `alice@firm.com` — normalize to lowercase on both sides; document this clearly.
123+
- Group with same `displayName` as an existing role — match by name; if mismatch on `externalId`, treat as conflict.
124+
- User exists in two orgs: deactivation in one doesn't touch the other.
125+
- IdP-driven creation race with self-serve invitation acceptance — last-write-wins on attributes; `externalId` once set is sticky.
126+
127+
## Telemetry
128+
- `scim.request.{resource}.{op}.{status}`, `scim.user.deprovisioned`, `scim.group.member_changed`.
129+
- Surface in admin UI: "Last sync from Okta: 14 min ago, 3 changes."
130+
131+
## Risks
132+
- Spec compliance bugs that block customer onboarding. Mitigation: run [Okta SCIM compatibility test suite](https://developer.okta.com/docs/guides/scim-provisioning-integration-prepare/main/) and Entra "Validate SCIM" tool before each release.
133+
- Token theft → org-wide write access. Mitigation: tokens are per-org-scoped; UI shows last-used IP and timestamp; revoke is immediate.
134+
135+
## Open questions
136+
- Auto-create roles for unknown groups, or 400? Default: auto-create with no permissions (admin must grant). Configurable.
137+
- Should SCIM be enabled-by-default once the org has SAML configured? Recommend explicit opt-in.
138+
139+
## Sequencing
140+
~2 sprints after ENT-1. Sprint 1: ServiceProviderConfig + User CRUD + filtering + tests against Okta. Sprint 2: Group CRUD + PATCH + Entra compatibility + UI for token management.

0 commit comments

Comments
 (0)