From f5ba0596dfa6da8a07a7729378ac5b1617dfc192 Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:40:03 -0400 Subject: [PATCH 01/17] 2026-10-29-2038-remove-sso-and-scim: shaped --- .../meta.yml | 5 +++ .../references.md | 8 ++++ .../shape.md | 45 +++++++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/meta.yml create mode 100644 docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/references.md create mode 100644 docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/shape.md diff --git a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/meta.yml b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/meta.yml new file mode 100644 index 0000000..e933d5c --- /dev/null +++ b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/meta.yml @@ -0,0 +1,5 @@ +id: 2026-10-29-2038-remove-sso-and-scim +title: 'Remove SSO and SCIM' +status: shaping +created: '2026-10-29 20:38' +standards: {} diff --git a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/references.md b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/references.md new file mode 100644 index 0000000..0a3b52f --- /dev/null +++ b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/references.md @@ -0,0 +1,8 @@ +# References + +- Domains: `src/Domains/Sso/` and `src/Domains/Scim/`; registered in `src/Domains/DomainServiceProvider.php:13-14, :34-35`. +- UI: `src/Atrium/Http/Controllers/SsoUiController.php` and `ScimUiController.php`, `resources/views/ui/sso/`, and the routes in `src/Atrium/RosterPlugin.php:200-207`. +- MCP: `src/Mcp/RosterServer.php:51-60, :194+` and `src/Mcp/Concerns/DescribesSsoConnection.php`. +- Config: `config/roster.php` (sso :244, scim :268, policies :538-542, tables :576-580). +- Migrations: `database/migrations/2026_01_01_000006_create_roster_sso_tables.php` and `000007_create_roster_scim_tables.php`. +- Historic specs: `docs/agent/specs/2026-10-01-1251-sso`, `2026-10-01-1308-scim`. diff --git a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/shape.md b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/shape.md new file mode 100644 index 0000000..0cb4ca3 --- /dev/null +++ b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/shape.md @@ -0,0 +1,45 @@ +# Remove SSO and SCIM — Shaping Notes + +## Scope + +Delete SSO and SCIM from Roster now that Guardian (root spec `2026-10-29-2038-guardian-package`) owns them. + +Remove: + +- `src/Domains/Sso/` and `src/Domains/Scim/`, about 168 PHP files, and their entries in `Domains\DomainServiceProvider` +- `src/Atrium/Http/Controllers/SsoUiController.php`, `ScimUiController.php`, `resources/views/ui/sso/`, and the SSO/SCIM routes in `RosterPlugin.php:200-207` +- the `sso` and `scim` organization tabs, so `Tabs::ORGANIZATION_TABS` / the Atrium built-in list drops them. Guardian registers them instead. +- the SSO identities card on the user overview (`UserUiController:326`). Guardian registers it as a `roster.user` section. +- the SSO/SCIM MCP tools from `RosterServer` +- `Concerns/DescribesSsoConnection` +- the `sso` / `scim` config sections, `roster.tables.sso_*` / `scim_*`, and the SSO/SCIM policies +- the `socialite`, `saml2`, `php-jwt` and `microsoft-azure` suggestions from `composer.json` +- the SSO/SCIM tests +- the migrations `2026_01_01_000006_create_roster_sso_tables.php` and `000007_create_roster_scim_tables.php`. Guardian's upgrade migration renames the existing tables. + +Also add: + +- a CHANGELOG and README upgrade note: install `refactor-circus/guardian`, run its migrations (which rename `roster_sso_*` / `roster_scim_*` to `guardian_*`), and move `roster.sso.*` / `roster.scim.*` config to `guardian.*`. +- `refactor-circus/guardian` in `suggest`. + +## Decisions + +- D-001: the table data moves through Guardian's rename-upgrade migration, never dropped by Roster. Roster's removed migrations must not leave a down-migration that drops data. (User, 2026-10-29: "rename, ship upgrade".) +- D-002: Roster keeps `organizations.provisioned_status` and the seams from `auth-extension-seams`. Only SSO/SCIM-specific code leaves. +- D-003: open for spec review: whether `MembershipSource::Scim` values already stored stay readable, by keeping the value registered by Guardian through the seam. + +## Context + +- **Depends on:** + - Roster `2026-10-29-2038-auth-extension-seams` (merged) + - root `2026-10-29-2038-guardian-package` (merged) + - Roster `2026-10-29-2038-adopt-atrium-screen-registry` (merged) +- **References:** see `references.md`. + +## Standards + +- architecture/public-api: removing public classes, config and routes is breaking and needs an upgrade note. +- architecture/dependencies: no SSO/SCIM vendors are suggested by Roster any more. +- architecture/configuration: config sections are removed. +- models/migrations: migration removal and safe upgrade ordering with Guardian's rename. +- testing/test-layers: the remaining suite plus `ArchTest` stay green. From 99eb41031c730744cf5ebb2efba8cdd4f97284a2 Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:49:07 -0400 Subject: [PATCH 02/17] 2026-10-29-2038-remove-sso-and-scim: shaping decisions --- docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/shape.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/shape.md b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/shape.md index 0cb4ca3..35e6b5e 100644 --- a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/shape.md +++ b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/shape.md @@ -27,6 +27,8 @@ Also add: - D-001: the table data moves through Guardian's rename-upgrade migration, never dropped by Roster. Roster's removed migrations must not leave a down-migration that drops data. (User, 2026-10-29: "rename, ship upgrade".) - D-002: Roster keeps `organizations.provisioned_status` and the seams from `auth-extension-seams`. Only SSO/SCIM-specific code leaves. - D-003: open for spec review: whether `MembershipSource::Scim` values already stored stay readable, by keeping the value registered by Guardian through the seam. +- D-004: the `roster.sso.*` / `roster.scim.*` permissions become `guardian.sso.*` / `guardian.scim.*`, and Guardian's upgrade migration renames existing role grants. Roster's catalogue drops the old names. (User, 2026-10-29.) +- D-005: the organization tabs become `guardian.sso` / `guardian.scim`, registered by Guardian. Old `?tab=sso` and `?tab=scim` links fall back to the default tab. ## Context From 3d6451af416bf12418588398233b3bdb7c2fa6f0 Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Thu, 29 Oct 2026 23:39:43 -0400 Subject: [PATCH 03/17] 2026-10-29-2038-remove-sso-and-scim: spec written --- .../meta.yml | 7 +- .../spec.md | 198 ++++++++++++++++++ .../standards.md | 19 ++ 3 files changed, 222 insertions(+), 2 deletions(-) create mode 100644 docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/spec.md create mode 100644 docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/standards.md diff --git a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/meta.yml b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/meta.yml index e933d5c..ec337c0 100644 --- a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/meta.yml +++ b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/meta.yml @@ -1,5 +1,8 @@ id: 2026-10-29-2038-remove-sso-and-scim title: 'Remove SSO and SCIM' -status: shaping +status: written created: '2026-10-29 20:38' -standards: {} +standards: + refactor-circus/standards: + version: dev-main + reference: a5b675396232 diff --git a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/spec.md b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/spec.md new file mode 100644 index 0000000..a1cb1f8 --- /dev/null +++ b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/spec.md @@ -0,0 +1,198 @@ +# Remove SSO and SCIM + +## Goal + +Roster stops shipping SSO and SCIM, now that `refactor-circus/guardian` owns them. Roster is left with the seams from `auth-extension-seams` and `organizations.provisioned_status` (D-002). It no longer names an SSO or SCIM class, route, permission, table, config key or vendor library. Existing installs lose no data: Roster drops nothing, and Guardian's upgrade migration renames the tables and role grants (D-001, D-004). Apps get a clear upgrade path in the CHANGELOG and README. + +## Acceptance criteria + +### Code and registrations + +1. **The domains are gone.** + - `src/Domains/Sso/` and `src/Domains/Scim/` do not exist. `Domains\DomainServiceProvider::$providers` lists neither `SsoServiceProvider` nor `ScimServiceProvider`. + - `database/factories/SsoConnectionFactory.php` and `src/Mcp/Concerns/DescribesSsoConnection.php` are deleted. + - Proof: a new arch test asserts that no class under `RefactorCircus\Roster` uses `RefactorCircus\Roster\Domains\Sso` or `RefactorCircus\Roster\Domains\Scim`. A feature test asserts that `is_dir()` is false for both folders, and that `class_exists()` is false for `Domains\Sso\SsoServiceProvider`, `Domains\Scim\ScimServiceProvider` and `Mcp\Concerns\DescribesSsoConnection` (`trait_exists` for the trait). + +2. **The internal `roster.sso` / `roster.scim` registrations are gone.** They become Guardian's `guardian.*` (D-004). + - `app(Resources::class)->model('roster.sso')` and `->model('roster.scim')` answer `null`. + - `app(PermissionCatalogue::class)->all()` has no name starting with `roster.sso.` or `roster.scim.`. + - `Authorizer::check()` for `roster.sso.view` denies an organization `admin` who is not a super-admin, because an unregistered prefix resolves no policy and is denied. + - `app(MembershipSources::class)->has('scim')` is false. + - With Keen installed and `roster.audit.enabled` on, an entry written for a Roster action carries no `scim_token` context key. + - Proof: one feature test per bullet. + +3. **Permission rows already in the database are kept.** + - On a database that already has `roster.sso.view`, `roster.sso.manage` and `roster.scim.manage` as system permissions granted to `admin` (the state an upgraded install is in), `roster:sync-permissions` reports each of the three as unregistered (`expectsOutputToContain`, the seams behaviour). + - The rows and their `admin` grants still exist afterwards. + - Proof: a feature test. + +4. **Membership source `scim` stays readable** (D-003, pending Q1, written to its recommendation). + - Without a registration, a membership stored with `source = 'scim'` reads back as `'scim'`, and `sourceEnum()` answers `null`. `MemberResource` serializes `source` as `'scim'`, the member list (API, MCP `mcpTool()` with its output schema, and the Atrium members tab) answers 200 and shows `scim`, and nothing errors. + - With `scim` registered through `MembershipSources::register('scim', 'SCIM')`, as Guardian does, the same row shows `SCIM`. + - Proof: a feature test for each case. + +### Surfaces + +5. **The SSO and SCIM routes are gone.** + - `Route::has()` is false for every one of these route names: + - `roster.organizations.sso-connections.index|store` + - `roster.sso-connections.show|update|destroy` + - `roster.users.sso-identities.index` + - `roster.sso-identities.destroy` + - `roster.organizations.scim-tokens.index|store` + - `roster.scim-tokens.destroy` + - `roster.sso.discover|start|callback|metadata|link` + - `atrium.roster.sso.store|show|update|destroy` + - `atrium.roster.sso-identities.destroy` + - `atrium.roster.scim-tokens.store|revoke` + - No registered route name starts with `roster.scim.`. + - `RosterServiceProvider::registerSurfaces()` names only the `web` surface routes. It no longer names `roster.scim.`. + - Proof: a dataset feature test over the names, plus a test that iterates `Route::getRoutes()` for the prefix. + +6. **The MCP tools are gone.** + - `RosterServer`'s tool list has none of these: `ListSsoConnectionsTool`, `ShowSsoConnectionTool`, `CreateSsoConnectionTool`, `UpdateSsoConnectionTool`, `DeleteSsoConnectionTool`, `ListSsoIdentitiesTool`, `UnlinkSsoIdentityTool`, `ListScimTokensTool`, `CreateScimTokenTool`, `RevokeScimTokenTool`. + - Proof: a feature test asserts that no tool name the server lists matches `/sso|scim/i`. + +7. **The organization screen loses its `sso` and `scim` built-in tabs** (D-005). + - `roster.organization` declares exactly `members`, `teams`, `invitations`, `roles`, `settings` through `Screen::tabs()`, in that order, and `members` stays the default tab. + - The tab-permission map in `OrganizationUiController` loses its `sso` / `scim` entries, and the view's icon map loses them too. + - `GET atrium.roster.organizations.show` with `?tab=sso` or `?tab=scim`, for a viewer holding every organization permission, answers 200 with `members` open (`ResolvedScreen::$openTab === 'members'`). This is Atrium's unknown-key fallback. + - `SsoUiController`, `ScimUiController` and `resources/views/ui/sso/` are deleted, along with any `roster.sso-connection` screen declaration that `adopt-atrium-screen-registry` added. + - Proof: feature tests for the tab list and each fallback, and `class_exists()` false for both controllers. + +8. **The user overview loses its SSO identities card.** + - `UserUiController` no longer passes `ssoIdentities`. + - `ui/users/partials/overview.blade.php` (and `users/show`) render no SSO markup. Guardian places its card through the `roster.user` `aside` slot. + - Proof: a feature test asserts that the overview response has no `ssoIdentities` view data and no `unlink-sso-identity` test id. + +### Config, data and dependencies + +9. **The config is gone.** + - `config/roster.php` has no `sso` or `scim` section, and their banners are gone with them. + - `roster.tables` and `Support\Tables::DEFAULTS` have no `sso_connections`, `sso_identities`, `scim_tokens`, `scim_users` or `scim_groups` key. + - The `policies` banner no longer mentions SSO or SCIM. + - Proof: a feature test asserts that `config('roster.sso')` and `config('roster.scim')` are `null` and checks both key lists. The ArchTest `literalTableNames()` and `modelsWithoutPolicies()` checks stay green. + +10. **The migrations remove nothing.** Covers D-001. + - `2026_01_01_000006_create_roster_sso_tables.php` and `2026_01_01_000007_create_roster_scim_tables.php` are deleted. + - `2026_01_01_000010_add_roster_lookup_indexes.php` drops its `sso_connections`, `scim_tokens` and `scim_groups` entries. `2026_10_12_000001_add_roster_performance_indexes.php` drops `scim_users` and `scim_groups`. + - No remaining file under `database/migrations/` contains `drop`, `rename` or `Schema::table` for any of the five SSO/SCIM table names or keys. + - Proof: + - On a fresh database, `migrate` creates none of `roster_sso_connections`, `roster_sso_identities`, `roster_scim_tokens`, `roster_scim_users` or `roster_scim_groups`. + - An upgrade test creates the five tables with one row each (the 000006/000007 schema, built in the test). It then runs `migrate`, and runs `migrate:rollback` for the two index migrations by `--path`. All five tables and their rows still exist afterwards. + - A grep test asserts that no file under `database/` matches `/(^|[^a-z])(sso|scim)/i`. + +11. **The composer suggestions change.** + - `composer.json` `suggest` drops `laravel/socialite`, `socialiteproviders/saml2`, `firebase/php-jwt` and `socialiteproviders/microsoft-azure`. It adds `"refactor-circus/guardian": "Single sign-on (OIDC, SAML, Entra ID) and SCIM provisioning for Roster's organizations (dev-main)."`. + - `require-dev` drops the same four vendor packages, since no remaining test uses them. + - `require` is unchanged by this spec. + - `composer validate --strict` passes. + - Proof: a docs/composer feature test decodes `composer.json` and checks both lists. + +12. **No source names SSO or SCIM any more.** + - No file under `src/`, `config/`, `database/`, `lang/`, `resources/` (views, Boost skill, import templates) or `workbench/` matches `/(^|[^a-z])(sso|scim)/i`. The one exception is whatever Q2 decides the sign-in rule and its message key are called. + - Comments and descriptions that mentioned SSO/SCIM say "externally provisioned" accounts or "a registered sign-in requirement" instead. This covers `PurgeOrganizationAction`, `PurgeOrganizationTool`, `DescribesOrganization`, `CreateOrganizationData`, `OrganizationRules`, migration 000002, the email-index migration, `Roster::provisionedStatus()`, `ProvisionedStatus`, `ExternalSignIn`, `Policy`, `Audit`, `PermissionServiceProvider`, `RosterServiceProvider` and `import_users.csv`. + - Every `sso*` / `scim*` key, plus `link_sso` and `unknown_sso_connection`, leaves `lang/en/roster.php`. + - Proof: a feature grep test. `tests/` and `docs/` are not scanned. + +13. **The sign-in rule** (pending Q2, written to its recommendation). + - `NotSsoEnforced` leaves with the SSO domain. + - Roster keeps the generic rule as `RefactorCircus\Roster\Support\Rules\NoExternalSignIn implements ValidationRule`. Its body is the same: it fails when `Roster::externalSignInFor($value)` answers non-null, with the message `roster::roster.external_sign_in_required` (`:organization` from `label`, `:url` from `url`). The text is unchanged from today's `sso_required`. + - Proof: a feature test with a fake `SignInRequirement` covers each case: the rule fails with the label and url, passes for `null`, a super-admin passes, and a throwing requirement propagates. + +### Documentation and gate + +14. **The CHANGELOG `[Unreleased]` → `### Breaking` entry, "SSO and SCIM moved to refactor-circus/guardian".** + - It lists what was removed: the domains, routes, Atrium tabs and pages, MCP tools, config, table keys, permissions, `MembershipSource` registration, `NotSsoEnforced` and vendor suggestions. + - It gives the upgrade steps: + 1. Install `refactor-circus/guardian` in the same deploy as this Roster version. + 2. Delete your published copies of `create_roster_sso_tables` and `create_roster_scim_tables`, and never roll them back, because their `down()` drops the tables. Remove the SSO/SCIM keys from published copies of the two index migrations. + 3. Publish and run Guardian's migrations. They rename `roster_sso_*` / `roster_scim_*` to `guardian_*` and rename role grants of `roster.sso.*` / `roster.scim.*` to `guardian.sso.*` / `guardian.scim.*`. + 4. Move published config from `roster.sso.*` / `roster.scim.*` / `roster.tables.sso_*|scim_*` to the matching `guardian.*` keys, and check that Guardian's SCIM prefix matches what your identity providers call (Roster's default was `scim/v2`). + 5. Replace `RefactorCircus\Roster\Domains\Sso|Scim\…` classes, `roster.sso.*` / `roster.scim.*` route names and permission names (`@rosterCan`, seeders) with Guardian's. + 6. Replace `NotSsoEnforced` per Q2. + - It describes the behaviour after upgrading: + - Old `?tab=sso` and `?tab=scim` links open the default (members) tab. Guardian's tabs are `guardian.sso` / `guardian.scim`. + - Without Guardian, the tables and rows stay untouched, SSO sign-in and the SCIM endpoints answer 404, the three permission rows are kept and reported by `roster:sync-permissions`, and `scim` memberships show their raw value. + - Proof: a DocsTest asserts the entry contains `refactor-circus/guardian`, `guardian.sso`, `?tab=sso`, `?tab=scim`, `roster.sso.` and `create_roster_sso_tables`. + +15. **README and Boost skill.** + - The README's "Single sign-on", "Requiring SSO" and "SCIM provisioning" sections are replaced by one section, "SSO and SCIM (refactor-circus/guardian)". It covers the same upgrade steps, in short, and links to Guardian. + - "Extending Roster" no longer cites Roster's own SSO/SCIM as users of the seams. Its `NotSsoEnforced` / `SsoConnectionModel` mentions follow Q2. + - The config section list and the "Atrium dashboard" tab list drop `sso` / `scim`. + - The Boost skill `resources/boost/skills/roster-development/SKILL.md` gets the same changes, regenerated per `package-generate-skill`. + - The local standard `docs/agent/standards/http/authorization.md` drops "SSO/SCIM policies from their domain providers" (in favour of "package resources register their own policies"). `vendor/bin/ringside sync` is rerun. + - Proof: a DocsTest asserts that the new heading exists, that no `## Single sign-on` or `## SCIM provisioning` heading remains, and that the seams-era "Extending Roster" checks stay green. + +16. **`composer test` and `composer test:browser` pass.** + - `composer test` runs analyse, lint, type coverage and the non-browser suites. It does not include the browser suite, which is checked separately. + - Existing tests may change only where this spec forces it mechanically: removed classes, routes, tabs, config, permissions or registrations. Each changed or deleted test is listed in the PR by file and test name. + - Expected deletions, as the suite stands after the seams PR and `adopt-atrium-screen-registry`: + - `tests/Feature/Sso/`, `tests/Feature/Scim/` + - `tests/Feature/Http/SsoHttpTest.php`, `ScimTokensHttpTest.php` + - `tests/Feature/Ui/SsoPagesTest.php`, `ScimPagesTest.php` + - `tests/Browser/SsoBrowserTest.php`, `ScimBrowserTest.php` + - `tests/Modes/SsoUnavailable/` and `tests/SsoUnavailableTestCase.php`, with its `uses()` line in `tests/Pest.php` + - Expected edits (only the SSO/SCIM cases, rows or assertions): + - `tests/Pest.php`: the `SsoLoginAction` / `LinkSsoIdentityAction` `PARITY_EXCEPTIONS` + - `tests/ArchTest.php`: comments; its SSO/SCIM pattern tests stay + - `tests/Authorization/fixtures.php`, `HttpAuthorizationTest.php`, `McpAuthorizationTest.php`, `PoliciesTest.php`, `ScreenControlsTest.php` + - `tests/Feature/DocsTest.php`, `IndexesTest.php`, `Organization/MembershipSourceTest.php` (register `scim` in the test instead of relying on the SCIM domain), `PerformanceTest.php`, `Permission/PermissionSyncTest.php`, `Permission/RegisteredResourcesTest.php`, `ProvisionedStatusTest.php`, `SoftDeleteTest.php`, `StoredIdentifiersTest.php`, `Transfers/TemplateTest.php` + - the organization tab-bar and registered-tab tests (expected built-in list) + - the user registered-tabs test (the overview-only query probe moves to another overview-only table) + - `UserApprovalTest.php` + - `tests/Modes/Keen/KeenAuditTest.php`, `tests/Modes/RenamedTables/RenamedTablesTest.php` + - `tests/Unit/Organization/MembershipSourcesTest.php`, `tests/Unit/Permission/PermissionCatalogueTest.php` + +## Design + +**Rebase first.** This worktree's branch (`ring-master/2026-10-29-2038-remove-sso-and-scim`) was cut from `main` before the seams PR (#11) merged. Before building, rebase it onto `ring-master/2026-10-29-2038-auth-extension-seams`, or onto `main` once #11 has merged, and then onto `adopt-atrium-screen-registry` once that lands. Then run `composer local:install`. Every class named here (`Resources`, `PermissionCatalogue`, `MembershipSources`, `SignInRequirement`, `externalSignInFor()`) exists only after the seams PR. The Atrium screen API (`Screen::make()->tabs()`, `ResolvedScreen::$openTab`, the `aside` slot) exists only after the adopt spec. The Guardian package does not need to be installed for this build: no test or code here references it. + +**Deletion, not migration.** The work is almost all removal: + +- The domain folders, the two Atrium controllers, the `ui/sso` views, the SSO/SCIM blocks of `organizations/show.blade.php` and `users/partials/overview.blade.php`, the plugin's seven routes, ten `RosterServer` tools, `DescribesSsoConnection` and the factory all go. +- The domain providers took the `roster.sso` / `roster.scim` resources, permissions, Gate policies, the `scim` membership source and the `scim_token` `AuditHooks` closure with them. So the registrations disappear without touching `Resources`, `PermissionCatalogue`, `MembershipSources` or `Support\Audit`. +- The `@internal` `rosterResource()` / `rosterPermission()` methods stay for the core domains. + +**Organization screen.** After `adopt-atrium-screen-registry`, `OrganizationUiController` declares `Screen::make('roster.organization')->tabs([...])`. This spec removes `sso` and `scim` from that list, from the tab-permission map and from the view's icon map. With the built-in keys gone, `?tab=sso` and `?tab=scim` are unknown keys, and Atrium opens the default tab with a 200 (Atrium criterion 7). Guardian's `guardian.sso` / `guardian.scim` registrations never clashed with the built-ins (Guardian D-007), so nothing else changes. + +**Migrations.** Removing 000006/000007 from the package leaves the `migrations` rows of existing installs dangling, which Laravel ignores. Nothing in Roster drops, renames or alters the five tables, and their rows stay where they are until Guardian's rename migration moves them. The two index migrations lose their SSO/SCIM entries. Otherwise `Tables::name()` would hit a missing key on fresh installs. Existing installs already ran them, and the indexes travel with the renamed tables. + +**Membership source.** Q1's recommendation needs no code: the seams PR already renders an unregistered stored value as-is. + +**Sign-in rule.** Q2's recommendation moves the rule's body to `src/Support/Rules/NoExternalSignIn.php`, with the message key renamed. Nothing in `tests/ArchTest.php` constrains `Support/` beyond strict types and the shared presets. + +**Composer.** `suggest` and `require-dev` change as in criterion 11. `bin/composer-local.php` regenerates `composer.local.json` from it. + +## Out of scope + +- Creating Guardian, its rename migrations, its `guardian.*` permissions, tabs, the `roster.user` `aside` section, and its SCIM prefix default. All of that is the Guardian spec. +- Moving `refactor-circus/atrium` from `require` to `suggest`, the Atrium screen declarations and the Atrium-less test lane. All of that is `adopt-atrium-screen-registry`. +- `organizations.provisioned_status`, `Roster::provisionedStatus()` and the seams themselves, which stay (D-002). +- Deleting the permission rows or the tables of an install that never installs Guardian. +- Historic specs under `docs/agent/specs/` (`2026-10-01-1251-sso`, `2026-10-01-1308-scim`) and the roadmap. They stay as history. The roadmap line may note the move. + +## Risks and open questions + +**Q1. What does Roster show for a stored `scim` membership source when Guardian isn't installed?** (D-003) +- **A: the raw stored value `scim`.** This is the seams PR's existing behaviour for unregistered sources. It needs no code, and Guardian's registration restores the "SCIM" label. +- **B: a configurable label map in Roster** (`roster.membership_sources.labels`). This means new config, and `scim` would reappear in Roster's config. +- **C: a generic label such as "External".** This hides the real value. +- **Recommendation: A.** The criteria are written to it. + +**Q2. Where does the password-login rule `NotSsoEnforced` go?** It lives in the SSO domain today, but it enforces every registered `SignInRequirement`, and the seam is Roster's. +- **A: Roster keeps a generic rule,** `Support\Rules\NoExternalSignIn`, with message key `external_sign_in_required`. Apps change one `use`. Any package's requirement keeps being enforced without Guardian's help. +- **B: the rule moves to Guardian with SSO.** Apps without Guardian then have no rule, and must call `Roster::externalSignInFor()` themselves. +- **C: keep the class name `NotSsoEnforced` at a core path.** This leaves an SSO name in core, against criterion 12. +- **Recommendation: A.** The Guardian spec should then reference Roster's rule in its README rather than ship its own. + +**Q3. What about apps with published migrations?** The README tells apps to publish Roster's migrations, so most installs carry copies of 000006/000007 and of the two index migrations, which call `Tables::name('sso_connections')` and the like. With the keys gone from `Tables::DEFAULTS`, and absent from a published config, those copies throw "Undefined array key" on `migrate:fresh`, `migrate:refresh` and `migrate:rollback`. Running `migrate:fresh` with the 000006/000007 copies in place would also recreate empty `roster_sso_*` tables beside Guardian's. +- **A: rely on the CHANGELOG step** (delete the two published copies and edit the index copies). This follows the shape. +- **B: also keep the five keys in `Tables::DEFAULTS`** (not in `config/roster.php`) as deprecated, for one release, so unedited copies keep working. This breaks criterion 12's grep for `src/`. +- **Recommendation: A**, with the CHANGELOG step in bold. Spec review should confirm. + +**Other risks** + +- **Deploy ordering.** Upgrading Roster without installing Guardian turns SSO sign-in and SCIM off at once. Identity providers get 404s and enforced-SSO users fall back to passwords, because no requirement is registered any more. The CHANGELOG says to install Guardian in the same deploy. Data is safe either way. +- **Purging an organization.** It still removes Guardian's rows through their foreign keys to `roster_organizations`, which survive the rename. That is Guardian's contract, and Roster no longer documents it. +- **Briefly stale wording.** The seams-era CHANGELOG entries in `[Unreleased]` mention `Domains\Sso\…`. They are left as written, and the new Breaking entry supersedes them. diff --git a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/standards.md b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/standards.md new file mode 100644 index 0000000..be61ece --- /dev/null +++ b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/standards.md @@ -0,0 +1,19 @@ +# Standards for Remove SSO and SCIM + +| Standard | File | Source | Why it applies | +| --- | --- | --- | --- | +| architecture/public-api | vendor/refactor-circus/standards/standards/architecture/public-api.md | refactor-circus/standards@dev-main | Public classes, routes, MCP tools, config and permissions are removed: breaking, needs CHANGELOG and README upgrade notes | +| architecture/dependencies | vendor/refactor-circus/standards/standards/architecture/dependencies.md | refactor-circus/standards@dev-main | SSO vendor suggestions leave; `refactor-circus/guardian` is suggested, never required or named in code | +| architecture/configuration | vendor/refactor-circus/standards/standards/architecture/configuration.md | refactor-circus/standards@dev-main | `sso` / `scim` config sections and `roster.tables` keys are removed | +| architecture/domain-modules | vendor/refactor-circus/standards/standards/architecture/domain-modules.md | refactor-circus/standards@dev-main | Two domain modules and their providers leave `Domains\DomainServiceProvider` | +| architecture/service-providers | vendor/refactor-circus/standards/standards/architecture/service-providers.md | refactor-circus/standards@dev-main | `RosterServiceProvider` stops naming the SCIM surface; the domain providers' registrations go | +| models/migrations | vendor/refactor-circus/standards/standards/models/migrations.md | refactor-circus/standards@dev-main | Migrations 000006/000007 removed; index migrations stop naming SSO/SCIM tables; nothing drops data | +| models/models | vendor/refactor-circus/standards/standards/models/models.md | refactor-circus/standards@dev-main | Table keys and policies of the removed models | +| models/stored-identifiers | vendor/refactor-circus/standards/standards/models/stored-identifiers.md | refactor-circus/standards@dev-main | Stored `memberships.source = 'scim'` values stay readable | +| http/authorization | docs/agent/standards/http/authorization.md | local | `roster.sso` / `roster.scim` resources, permissions and policies leave; the standard's SSO/SCIM wording is updated | +| http/routes | vendor/refactor-circus/standards/standards/http/routes.md | refactor-circus/standards@dev-main | SSO/SCIM API, web, SCIM-server and Atrium routes are removed | +| roster/action-surfaces | docs/agent/standards/roster/action-surfaces.md | local | `PARITY_EXCEPTIONS` loses the two SSO entries | +| roster/mcp-tools | docs/agent/standards/roster/mcp-tools.md | local | Ten MCP tools leave `RosterServer` | +| roster/atrium-views | docs/agent/standards/roster/atrium-views.md | local | Organization and user views lose SSO/SCIM markup | +| testing/test-layers | vendor/refactor-circus/standards/standards/testing/test-layers.md | refactor-circus/standards@dev-main | SSO/SCIM suites are deleted; the rest stays green | +| testing/arch-tests | vendor/refactor-circus/standards/standards/testing/arch-tests.md | refactor-circus/standards@dev-main | Arch test that nothing in Roster references the removed domains | From 04583d5fac36aa1152b74c986adccbf158437180 Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Thu, 29 Oct 2026 23:58:21 -0400 Subject: [PATCH 04/17] 2026-10-29-2038-remove-sso-and-scim: approved: decisions folded, tasks --- .../decisions.md | 69 +++++++++++ .../meta.yml | 3 +- .../questions.yml | 1 + .../spec-review.md | 19 +++ .../spec.md | 113 ++++++++++-------- .../tasks.md | 23 ++++ 6 files changed, 174 insertions(+), 54 deletions(-) create mode 100644 docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/decisions.md create mode 100644 docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/questions.yml create mode 100644 docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/spec-review.md create mode 100644 docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/tasks.md diff --git a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/decisions.md b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/decisions.md new file mode 100644 index 0000000..ecb0f6f --- /dev/null +++ b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/decisions.md @@ -0,0 +1,69 @@ +# Decisions + +Earlier D-ids are recorded in shape.md. + +## D-008: Suite: proving the package runs without Atrium, and refusing an Atrium too old for the screen registry +- Choice: Prove it both ways: a WithoutAtrium suite inside `composer test`, and a CI lane with Atrium uninstalled. Every package that renders Atrium screens adds a composer `conflict` on refactor-circus/atrium versions older than the screen-extensions registry (Atrium PR #16). +- Rationale: The user accepted the recommendation. +- Date: 2026-10-29 +- Raised by: user, cross-spec decision (2026-10-29) + +## D-009: Suite: malformed integration config entries (screen maps, slots) at boot +- Choice: Throw InvalidArgumentException in local and testing. In production, report once, skip the entry and keep booting (same rule as Atrium D-022). +- Rationale: The user accepted the recommendation. +- Date: 2026-10-29 +- Raised by: user, cross-spec decision (2026-10-29) + +## D-010: Sequencing with Guardian +- Choice: Guardian uses a runtime handover gate plus a composer `conflict` once this removal is tagged. The upgrade note tells apps that installed Guardian early to run `guardian:upgrade-from-roster`. +- Rationale: The user accepted the recommendation. +- Date: 2026-10-29 +- Raised by: user (2026-10-29) + +## D-011: Q1 (D-003, open in shape.md): What does Roster show for a stored `scim` membership source when Guardian isn't installed? +- Choice: A: the raw stored value `scim` (existing seams behaviour for unregistered sources, no code) +- Rationale: The user accepted the recommendation. +- Date: 2026-10-29 +- Raised by: spec review; the user accepted all recommendations (2026-10-29) + +## D-012: Q2: Where does the password-login rule `NotSsoEnforced` go? +- Choice: A: Roster keeps a generic rule `Support\Rules\NoExternalSignIn` with message key `external_sign_in_required` +- Rationale: The user accepted the recommendation. +- Date: 2026-10-29 +- Raised by: spec review; the user accepted all recommendations (2026-10-29) + +## D-013: Q3: How do apps with published copies of migrations 000006/000007 and the two index migrations upgrade safely? +- Choice: A: rely on the CHANGELOG step (delete the two published copies, edit the index copies) +- Rationale: The user accepted the recommendation. +- Date: 2026-10-29 +- Raised by: spec review; the user accepted all recommendations (2026-10-29) + +## D-014: Q1. What does Roster show for a stored `scim` membership source when Guardian is not installed? +- Choice: A: the raw stored value `scim` +- Rationale: The user accepted the recommendation. +- Date: 2026-10-29 +- Raised by: spec review; the user accepted all recommendations (2026-10-29) + +## D-015: Q2. Where does the password-login rule `NotSsoEnforced` go? +- Choice: A: Roster keeps a generic `Support\Rules\NoExternalSignIn` rule with message key `external_sign_in_required` +- Rationale: The user accepted the recommendation. +- Date: 2026-10-29 +- Raised by: spec review; the user accepted all recommendations (2026-10-29) + +## D-016: Q3. How do apps with published copies of migrations 000006/000007 and of the two index migrations survive the removal of the `Tables::DEFAULTS` keys? +- Choice: A: rely on the bold CHANGELOG step (delete or edit the published copies) +- Rationale: The user accepted the recommendation. +- Date: 2026-10-29 +- Raised by: spec review; the user accepted all recommendations (2026-10-29) + +## D-017: Should Roster fail closed for SSO-enforced organizations when Guardian is absent? +- Choice: Accept fail-open and document it prominently in the CHANGELOG and README +- Rationale: The user accepted the recommendation. +- Date: 2026-10-29 +- Raised by: spec review; the user accepted all recommendations (2026-10-29) + +## D-018: Q3. How should apps with published copies of migrations 000006/000007 and the two index migrations be handled? Those copies call `Tables::name('sso_connections')` and similar, so they throw 'Undefined array key' once the keys leave `Tables::DEFAULTS`. They would also recreate empty `roster_sso_*` tables on `migrate:fresh`. The spec has no test for this regression, so the choice also decides whether anything can be tested. +- Choice: A: rely on the CHANGELOG step (delete the two published copies and edit the index copies), and add a DocsTest that the step is present and bold +- Rationale: The user accepted the recommendation. +- Date: 2026-10-29 +- Raised by: spec review; the user accepted all recommendations (2026-10-29) diff --git a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/meta.yml b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/meta.yml index ec337c0..c3aac28 100644 --- a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/meta.yml +++ b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/meta.yml @@ -1,8 +1,9 @@ id: 2026-10-29-2038-remove-sso-and-scim title: 'Remove SSO and SCIM' -status: written +status: approved created: '2026-10-29 20:38' standards: refactor-circus/standards: version: dev-main reference: a5b675396232 +review_passes: 1 diff --git a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/questions.yml b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/questions.yml new file mode 100644 index 0000000..fe51488 --- /dev/null +++ b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/questions.yml @@ -0,0 +1 @@ +[] diff --git a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/spec-review.md b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/spec-review.md new file mode 100644 index 0000000..762b05b --- /dev/null +++ b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/spec-review.md @@ -0,0 +1,19 @@ +# Spec review + +## Round 1 + +Revised `spec.md` for the Round 1 findings. Open questions Q1 (raw `scim` source), Q2 (recommendation A, `NoExternalSignIn`), Q3 (recommendation A, CHANGELOG step) and the fail-closed question are unchanged. Fail-closed is recorded as Q4 and no guard was added. + +- Criterion 2: added a positive control (other context keys present) to the `scim_token` test, and accepted that old Keen entries keep their `scim_token` key, with a render test. +- Criterion 3: the permission-sync test runs every command option, so prune/force flags cannot delete the rows. Why: silent grant loss would break D-001 and D-004. +- Criterion 4: added write, import and filter paths for a stored `scim` source. +- Criterion 5: named the observable (the `Surface` registry content) and added a route-table test over all names and URIs, covering the `roster.sso.`, `atrium.roster.sso` and `roster.scim.` prefixes. +- Criterion 6, 7, 9: tied the maps, tab bar and banners to observables or to the criterion 12 grep. +- Criterion 10: the upgrade test uses a fixture copied verbatim from the deleted migrations, runs rollback and refresh, and checks that a stray `migrations` row is harmless. The loose drop/rename sentence became the one strict grep. +- Criterion 11: added vendor-namespace greps (`Laravel\Socialite`, `SocialiteProviders`, `Firebase\JWT`), and noted that `composer validate --strict`, `composer update` and `composer analyse` are run manually or in the gate. +- Criterion 12: replaced the regex with a case-sensitive one that catches camelCase, PascalCase and upper-case names without matching "association". Stated the scanned set exactly and which files other criteria cover. The allow-list is empty under Q2's recommendation. +- Criterion 13: pinned the message text (it contains no sso/scim token, so it can stay) and named the seams registration call the fake uses. +- Criterion 14: bold warning that SSO-enforced organizations accept passwords without Guardian, bold step 2 "before running any migrate command", step 3 before `roster:sync-permissions`. The DocsTest now asserts inside the `### Breaking` slice, the ordered steps and the bold. +- Criterion 15: added `CLAUDE.md` and `AGENTS.md` updates, decided the roadmap gets a one-line note (Out of scope now matches), and added README/SKILL.md assertions. `ringside sync` is marked manual. +- Criterion 16: marked the no-weakening rule as verified by review, added a test-count and threshold requirement, and stated that the only expected browser-test edits are the two deletions. +- Risks: deploy ordering now points to the bold warning and Q4. diff --git a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/spec.md b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/spec.md index a1cb1f8..71d8f3a 100644 --- a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/spec.md +++ b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/spec.md @@ -2,7 +2,7 @@ ## Goal -Roster stops shipping SSO and SCIM, now that `refactor-circus/guardian` owns them. Roster is left with the seams from `auth-extension-seams` and `organizations.provisioned_status` (D-002). It no longer names an SSO or SCIM class, route, permission, table, config key or vendor library. Existing installs lose no data: Roster drops nothing, and Guardian's upgrade migration renames the tables and role grants (D-001, D-004). Apps get a clear upgrade path in the CHANGELOG and README. +Roster stops shipping SSO and SCIM, now that `refactor-circus/guardian` owns them. Roster is left with the seams from `auth-extension-seams` and `organizations.provisioned_status` (D-002). It no longer names an SSO or SCIM class, route, permission, table, config key or vendor library. Existing installs lose no data: Roster drops nothing, and Guardian's upgrade migration renames the tables and role grants (D-001, D-004). Apps get a clear upgrade path in the CHANGELOG and README, including `guardian:upgrade-from-roster` for apps that installed Guardian early (D-010). Without Guardian, SSO-enforced organizations accept password sign-in; this fail-open is accepted and documented prominently (D-017). ## Acceptance criteria @@ -12,23 +12,25 @@ Roster stops shipping SSO and SCIM, now that `refactor-circus/guardian` owns the - `src/Domains/Sso/` and `src/Domains/Scim/` do not exist. `Domains\DomainServiceProvider::$providers` lists neither `SsoServiceProvider` nor `ScimServiceProvider`. - `database/factories/SsoConnectionFactory.php` and `src/Mcp/Concerns/DescribesSsoConnection.php` are deleted. - Proof: a new arch test asserts that no class under `RefactorCircus\Roster` uses `RefactorCircus\Roster\Domains\Sso` or `RefactorCircus\Roster\Domains\Scim`. A feature test asserts that `is_dir()` is false for both folders, and that `class_exists()` is false for `Domains\Sso\SsoServiceProvider`, `Domains\Scim\ScimServiceProvider` and `Mcp\Concerns\DescribesSsoConnection` (`trait_exists` for the trait). + - **Guardian handover contract (D-010).** Guardian's runtime handover gate (`Upgrade\Handover::complete()`) is true once `class_exists('RefactorCircus\Roster\Domains\Sso\Models\SsoConnectionModel')` is false. A feature test asserts exactly that string is not a loadable class, so the gate opens with this release. 2. **The internal `roster.sso` / `roster.scim` registrations are gone.** They become Guardian's `guardian.*` (D-004). - `app(Resources::class)->model('roster.sso')` and `->model('roster.scim')` answer `null`. - `app(PermissionCatalogue::class)->all()` has no name starting with `roster.sso.` or `roster.scim.`. - `Authorizer::check()` for `roster.sso.view` denies an organization `admin` who is not a super-admin, because an unregistered prefix resolves no policy and is denied. - `app(MembershipSources::class)->has('scim')` is false. - - With Keen installed and `roster.audit.enabled` on, an entry written for a Roster action carries no `scim_token` context key. + - With Keen installed and `roster.audit.enabled` on, an entry written for a Roster action carries no `scim_token` context key, and carries its other context keys (for example the impersonator context, with an impersonation active) on the same entry as a positive control. Old Keen entries that already hold a `scim_token` context key are left as written. Keen's history viewer ignoring a key without a registered hook is accepted, and one test asserts that such an entry still renders. - Proof: one feature test per bullet. 3. **Permission rows already in the database are kept.** - On a database that already has `roster.sso.view`, `roster.sso.manage` and `roster.scim.manage` as system permissions granted to `admin` (the state an upgraded install is in), `roster:sync-permissions` reports each of the three as unregistered (`expectsOutputToContain`, the seams behaviour). - - The rows and their `admin` grants still exist afterwards. + - The rows and their `admin` grants still exist afterwards, also after running `roster:sync-permissions` with every option the command offers (including any prune, force or delete flag). The test reads the option list from the command definition, so a flag added later is covered. - Proof: a feature test. -4. **Membership source `scim` stays readable** (D-003, pending Q1, written to its recommendation). +4. **Membership source `scim` stays readable** (D-003, D-011, D-014: the raw stored value, no new code). - Without a registration, a membership stored with `source = 'scim'` reads back as `'scim'`, and `sourceEnum()` answers `null`. `MemberResource` serializes `source` as `'scim'`, the member list (API, MCP `mcpTool()` with its output schema, and the Atrium members tab) answers 200 and shows `scim`, and nothing errors. - With `scim` registered through `MembershipSources::register('scim', 'SCIM')`, as Guardian does, the same row shows `SCIM`. + - Write and filter paths accept a stored `scim` value without a registration: updating a membership that has `source = 'scim'`, importing a row for it, and filtering the member list by `source=scim` neither fail validation nor drop or rewrite the source. - Proof: a feature test for each case. ### Surfaces @@ -46,16 +48,16 @@ Roster stops shipping SSO and SCIM, now that `refactor-circus/guardian` owns the - `atrium.roster.sso-identities.destroy` - `atrium.roster.scim-tokens.store|revoke` - No registered route name starts with `roster.scim.`. - - `RosterServiceProvider::registerSurfaces()` names only the `web` surface routes. It no longer names `roster.scim.`. - - Proof: a dataset feature test over the names, plus a test that iterates `Route::getRoutes()` for the prefix. + - `RosterServiceProvider::registerSurfaces()` names only the `web` surface. The observable is the surface registry content on Keystone's `Surface` for Roster: it holds no `scim` entry and no prefix matching the sso/scim regex of criterion 12. + - Proof: a dataset feature test over the names, plus a route-table test that iterates `Route::getRoutes()` and asserts that no route name or URI matches the criterion 12 regex. That covers unnamed routes, `scim/v2/...`, `sso/...` and `.well-known` URIs, and the `roster.sso.`, `atrium.roster.sso` and `roster.scim.` prefixes. 6. **The MCP tools are gone.** - `RosterServer`'s tool list has none of these: `ListSsoConnectionsTool`, `ShowSsoConnectionTool`, `CreateSsoConnectionTool`, `UpdateSsoConnectionTool`, `DeleteSsoConnectionTool`, `ListSsoIdentitiesTool`, `UnlinkSsoIdentityTool`, `ListScimTokensTool`, `CreateScimTokenTool`, `RevokeScimTokenTool`. - - Proof: a feature test asserts that no tool name the server lists matches `/sso|scim/i`. + - Proof: a feature test asserts that no tool name the server lists matches the criterion 12 regex. 7. **The organization screen loses its `sso` and `scim` built-in tabs** (D-005). - `roster.organization` declares exactly `members`, `teams`, `invitations`, `roles`, `settings` through `Screen::tabs()`, in that order, and `members` stays the default tab. - - The tab-permission map in `OrganizationUiController` loses its `sso` / `scim` entries, and the view's icon map loses them too. + - The tab-permission map in `OrganizationUiController` and the view's icon map lose their `sso` / `scim` entries. This is observable as follows: `?tab=sso` is not permission-gated (a viewer without `roster.sso.view` still gets 200 with `members`), and the rendered tab bar has no sso/scim icon or test id. - `GET atrium.roster.organizations.show` with `?tab=sso` or `?tab=scim`, for a viewer holding every organization permission, answers 200 with `members` open (`ResolvedScreen::$openTab === 'members'`). This is Atrium's unknown-key fallback. - `SsoUiController`, `ScimUiController` and `resources/views/ui/sso/` are deleted, along with any `roster.sso-connection` screen declaration that `adopt-atrium-screen-registry` added. - Proof: feature tests for the tab list and each fallback, and `class_exists()` false for both controllers. @@ -68,7 +70,7 @@ Roster stops shipping SSO and SCIM, now that `refactor-circus/guardian` owns the ### Config, data and dependencies 9. **The config is gone.** - - `config/roster.php` has no `sso` or `scim` section, and their banners are gone with them. + - `config/roster.php` has no `sso` or `scim` section, and their banners are gone with them (the criterion 12 grep over `config/` covers the banners). - `roster.tables` and `Support\Tables::DEFAULTS` have no `sso_connections`, `sso_identities`, `scim_tokens`, `scim_users` or `scim_groups` key. - The `policies` banner no longer mentions SSO or SCIM. - Proof: a feature test asserts that `config('roster.sso')` and `config('roster.scim')` are `null` and checks both key lists. The ArchTest `literalTableNames()` and `modelsWithoutPolicies()` checks stay green. @@ -76,57 +78,65 @@ Roster stops shipping SSO and SCIM, now that `refactor-circus/guardian` owns the 10. **The migrations remove nothing.** Covers D-001. - `2026_01_01_000006_create_roster_sso_tables.php` and `2026_01_01_000007_create_roster_scim_tables.php` are deleted. - `2026_01_01_000010_add_roster_lookup_indexes.php` drops its `sso_connections`, `scim_tokens` and `scim_groups` entries. `2026_10_12_000001_add_roster_performance_indexes.php` drops `scim_users` and `scim_groups`. - - No remaining file under `database/migrations/` contains `drop`, `rename` or `Schema::table` for any of the five SSO/SCIM table names or keys. + - No remaining file under `database/migrations/` names any of the five SSO/SCIM tables or keys. The single strict check is the criterion 12 regex over `database/`, which subsumes any drop, rename or `Schema::table` for them. - Proof: - On a fresh database, `migrate` creates none of `roster_sso_connections`, `roster_sso_identities`, `roster_scim_tokens`, `roster_scim_users` or `roster_scim_groups`. - - An upgrade test creates the five tables with one row each (the 000006/000007 schema, built in the test). It then runs `migrate`, and runs `migrate:rollback` for the two index migrations by `--path`. All five tables and their rows still exist afterwards. - - A grep test asserts that no file under `database/` matches `/(^|[^a-z])(sso|scim)/i`. + - An upgrade test creates the five tables with one row each. The schema comes from a fixture file, `tests/Fixtures/legacy_sso_scim_schema.php`, copied verbatim from the deleted 000006/000007 files, not hand-written. It then runs the full Roster migration set, then `migrate:rollback`, `migrate:refresh` and `migrate:fresh`-style runs over the Roster migrations. The five tables and their rows still exist after the rollback and refresh runs; for `migrate:fresh` the test only asserts that no Roster migration errors or creates a second set of tables. + - A stray `migrations` row for `create_roster_sso_tables` or `create_roster_scim_tables` does not make `migrate` or `migrate:status` fail. + - A grep test asserts that no file under `database/` matches the criterion 12 regex. 11. **The composer suggestions change.** - `composer.json` `suggest` drops `laravel/socialite`, `socialiteproviders/saml2`, `firebase/php-jwt` and `socialiteproviders/microsoft-azure`. It adds `"refactor-circus/guardian": "Single sign-on (OIDC, SAML, Entra ID) and SCIM provisioning for Roster's organizations (dev-main)."`. - `require-dev` drops the same four vendor packages, since no remaining test uses them. - - `require` is unchanged by this spec. - - `composer validate --strict` passes. - - Proof: a docs/composer feature test decodes `composer.json` and checks both lists. + - `require` is unchanged by this spec, and so is the `conflict` on `refactor-circus/atrium` `<0.1.0` added by `adopt-atrium-screen-registry` (D-008); the composer test asserts it is still there. + - `composer validate --strict` passes. It is run in the PR gate by hand and is not part of `composer test`. + - `composer update` and `composer analyse` still pass after the four dev packages are dropped. + - Proof: a docs/composer feature test decodes `composer.json` and checks both lists, and a grep test asserts that `tests/`, `workbench/`, `src/`, `config/` and `resources/` reference none of `Laravel\Socialite`, `SocialiteProviders` or `Firebase\JWT`. 12. **No source names SSO or SCIM any more.** - - No file under `src/`, `config/`, `database/`, `lang/`, `resources/` (views, Boost skill, import templates) or `workbench/` matches `/(^|[^a-z])(sso|scim)/i`. The one exception is whatever Q2 decides the sign-in rule and its message key are called. + - The scanned set is exactly `src/`, `config/`, `database/`, `lang/`, `resources/` (views, Boost skill, import templates) and `workbench/`. No file in it matches this case-sensitive regex, which the test uses verbatim: `/(?tabs()`, `ResolvedScreen::$openTab`, the `aside` slot) exists only after the adopt spec. The Guardian package does not need to be installed for this build: no test or code here references it. +**Base branch.** This branch is built on top of `ring-master/2026-10-29-2038-auth-extension-seams` and `ring-master/2026-10-29-2038-adopt-atrium-screen-registry` (the orchestrator rebases it before the build; see the note at the top of `tasks.md`), then `composer local:install`. Every class named here (`Resources`, `PermissionCatalogue`, `MembershipSources`, `SignInRequirement`, `Roster::requireSignIn()`, `externalSignInFor()`) exists only after the seams PR. The Atrium screen API (`Screen::standard()->tabs()`, `ResolvedScreen::$openTab`, the `aside` slot) and the `AtriumUnavailable` mode exist only after the adopt spec. The Guardian package does not need to be installed for this build: no test or code here references it. **Deletion, not migration.** The work is almost all removal: @@ -158,9 +168,13 @@ Roster stops shipping SSO and SCIM, now that `refactor-circus/guardian` owns the **Migrations.** Removing 000006/000007 from the package leaves the `migrations` rows of existing installs dangling, which Laravel ignores. Nothing in Roster drops, renames or alters the five tables, and their rows stay where they are until Guardian's rename migration moves them. The two index migrations lose their SSO/SCIM entries. Otherwise `Tables::name()` would hit a missing key on fresh installs. Existing installs already ran them, and the indexes travel with the renamed tables. -**Membership source.** Q1's recommendation needs no code: the seams PR already renders an unregistered stored value as-is. +**Membership source (D-011, D-014).** No code: the seams PR already renders an unregistered stored value as-is. -**Sign-in rule.** Q2's recommendation moves the rule's body to `src/Support/Rules/NoExternalSignIn.php`, with the message key renamed. Nothing in `tests/ArchTest.php` constrains `Support/` beyond strict types and the shared presets. +**Sign-in rule (D-012, D-015).** The rule's body moves to `src/Support/Rules/NoExternalSignIn.php`, with the message key renamed. Nothing in `tests/ArchTest.php` constrains `Support/` beyond strict types and the shared presets. + +**Guardian handover (D-010).** Deleting `Domains\Sso\Models\SsoConnectionModel` is what opens Guardian's handover gate: from then on Guardian's upgrade migration and `guardian:upgrade-from-roster` rename the tables and grants, Guardian loads its SSO and SCIM routes, and its morph aliases take over the old class names. Roster adds nothing for this; criterion 1 pins the class name. Guardian adds its `conflict` on older Roster once this removal is tagged. + +**Integration config (D-009).** Roster adds no integration config (screen maps or slots) in this spec, so D-009's rule has no surface here. **Composer.** `suggest` and `require-dev` change as in criterion 11. `bin/composer-local.php` regenerates `composer.local.json` from it. @@ -170,29 +184,22 @@ Roster stops shipping SSO and SCIM, now that `refactor-circus/guardian` owns the - Moving `refactor-circus/atrium` from `require` to `suggest`, the Atrium screen declarations and the Atrium-less test lane. All of that is `adopt-atrium-screen-registry`. - `organizations.provisioned_status`, `Roster::provisionedStatus()` and the seams themselves, which stay (D-002). - Deleting the permission rows or the tables of an install that never installs Guardian. -- Historic specs under `docs/agent/specs/` (`2026-10-01-1251-sso`, `2026-10-01-1308-scim`) and the roadmap. They stay as history. The roadmap line may note the move. - -## Risks and open questions - -**Q1. What does Roster show for a stored `scim` membership source when Guardian isn't installed?** (D-003) -- **A: the raw stored value `scim`.** This is the seams PR's existing behaviour for unregistered sources. It needs no code, and Guardian's registration restores the "SCIM" label. -- **B: a configurable label map in Roster** (`roster.membership_sources.labels`). This means new config, and `scim` would reappear in Roster's config. -- **C: a generic label such as "External".** This hides the real value. -- **Recommendation: A.** The criteria are written to it. +- Historic specs under `docs/agent/specs/` (`2026-10-01-1251-sso`, `2026-10-01-1308-scim`) and the roadmap. They stay as history. The roadmap gets only the one-line note of criterion 15. -**Q2. Where does the password-login rule `NotSsoEnforced` go?** It lives in the SSO domain today, but it enforces every registered `SignInRequirement`, and the seam is Roster's. -- **A: Roster keeps a generic rule,** `Support\Rules\NoExternalSignIn`, with message key `external_sign_in_required`. Apps change one `use`. Any package's requirement keeps being enforced without Guardian's help. -- **B: the rule moves to Guardian with SSO.** Apps without Guardian then have no rule, and must call `Roster::externalSignInFor()` themselves. -- **C: keep the class name `NotSsoEnforced` at a core path.** This leaves an SSO name in core, against criterion 12. -- **Recommendation: A.** The Guardian spec should then reference Roster's rule in its README rather than ship its own. +## Risks -**Q3. What about apps with published migrations?** The README tells apps to publish Roster's migrations, so most installs carry copies of 000006/000007 and of the two index migrations, which call `Tables::name('sso_connections')` and the like. With the keys gone from `Tables::DEFAULTS`, and absent from a published config, those copies throw "Undefined array key" on `migrate:fresh`, `migrate:refresh` and `migrate:rollback`. Running `migrate:fresh` with the 000006/000007 copies in place would also recreate empty `roster_sso_*` tables beside Guardian's. -- **A: rely on the CHANGELOG step** (delete the two published copies and edit the index copies). This follows the shape. -- **B: also keep the five keys in `Tables::DEFAULTS`** (not in `config/roster.php`) as deprecated, for one release, so unedited copies keep working. This breaks criterion 12's grep for `src/`. -- **Recommendation: A**, with the CHANGELOG step in bold. Spec review should confirm. - -**Other risks** - -- **Deploy ordering.** Upgrading Roster without installing Guardian turns SSO sign-in and SCIM off at once. Identity providers get 404s and enforced-SSO users fall back to passwords, because no requirement is registered any more. The CHANGELOG says to install Guardian in the same deploy. Data is safe either way. +- **Fail-open without Guardian (D-017, accepted).** Upgrading Roster without installing Guardian turns SSO sign-in and SCIM off at once. Identity providers get 404s and enforced-SSO users fall back to passwords, because no requirement is registered any more. Roster adds no guard; the CHANGELOG and README open with a bold warning (criteria 14, 15), and the DocsTest asserts it. Data is safe either way. +- **Early Guardian installs (D-010).** Guardian's upgrade migration skipped while Roster still owned the tables, and its create migrations made empty `guardian_*` tables (Guardian's "stranded" state, warn-only). The upgrade note tells these apps to run `guardian:upgrade-from-roster` after upgrading Roster. +- **Published migrations (D-013, D-016, D-018).** Published copies of 000006/000007 and the two index migrations call the removed `Tables` keys and would throw, or recreate empty `roster_sso_*` tables. Roster relies on the bold CHANGELOG step 2, asserted by the DocsTest; it keeps no deprecated keys. - **Purging an organization.** It still removes Guardian's rows through their foreign keys to `roster_organizations`, which survive the rename. That is Guardian's contract, and Roster no longer documents it. - **Briefly stale wording.** The seams-era CHANGELOG entries in `[Unreleased]` mention `Domains\Sso\…`. They are left as written, and the new Breaking entry supersedes them. + +## Changelog + +- Applied D-008: the AtriumUnavailable mode, `without-atrium` lane and Atrium `conflict` stay green and in place (criteria 11, 16). +- Applied D-009: noted no integration config surface (Design). +- Applied D-010: Guardian handover contract pinned (criterion 1); upgrade step 3, README and DocsTest name `guardian:upgrade-from-roster` for early Guardian installs (criteria 14, 15, Design, Risks). +- Applied D-011, D-014: raw `scim` source (criterion 4); Q1 removed. +- Applied D-012, D-015: `Support\Rules\NoExternalSignIn` (criteria 12, 13, 14 step 6, 15); seams call named `Roster::requireSignIn()`; Q2 removed. +- Applied D-013, D-016, D-018: bold CHANGELOG step with DocsTest (criterion 14, Risks); Q3 removed. +- Applied D-017: fail-open accepted and documented in the CHANGELOG and README (Goal, criteria 14, 15, Risks); Q4 removed. diff --git a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/tasks.md b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/tasks.md new file mode 100644 index 0000000..f36b2c0 --- /dev/null +++ b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/tasks.md @@ -0,0 +1,23 @@ +# Tasks: Remove SSO and SCIM + +> **Before building:** this branch must be rebased onto the seams branch `ring-master/2026-10-29-2038-auth-extension-seams` and then the adopt branch `ring-master/2026-10-29-2038-adopt-atrium-screen-registry`, followed by `composer local:install`. The orchestrator does the rebase; it is not a task. File paths below assume that rebased tree. + +## Group 1: Remove SSO and SCIM code, surfaces, config and migrations +package: Roster +depends on: none +files: src/Domains/Sso/, src/Domains/Scim/, src/Domains/DomainServiceProvider.php, src/Mcp/Concerns/DescribesSsoConnection.php, src/Mcp/RosterServer.php, src/Atrium/Http/Controllers/SsoUiController.php, src/Atrium/Http/Controllers/ScimUiController.php, src/Atrium/Http/Controllers/OrganizationUiController.php, src/Atrium/Http/Controllers/UserUiController.php, src/Atrium/RosterPlugin.php, src/RosterServiceProvider.php, src/Support/Tables.php, src/Support/Rules/NoExternalSignIn.php, src/Support/Audit.php, src/Support/Policies/Policy.php, src/Roster.php, src/Domains/Organization/, src/Domains/Permission/PermissionServiceProvider.php, src/Data/ExternalSignIn.php, resources/views/ui/sso/, resources/views/ui/organizations/show.blade.php, resources/views/ui/users/partials/overview.blade.php, resources/views/ui/users/show.blade.php, resources/import-templates/import_users.csv, config/roster.php, lang/en/roster.php, database/factories/SsoConnectionFactory.php, database/migrations/2026_01_01_000006_create_roster_sso_tables.php, database/migrations/2026_01_01_000007_create_roster_scim_tables.php, database/migrations/2026_01_01_000010_add_roster_lookup_indexes.php, database/migrations/2026_10_12_000001_add_roster_performance_indexes.php, database/migrations/2026_01_01_000002_create_roster_organization_tables.php, workbench/, composer.json, composer.local.json, tests/Fixtures/legacy_sso_scim_schema.php, tests/Feature/RemovedSsoScimTest.php, tests/Feature/LegacySsoScimUpgradeTest.php, tests/Feature/NoExternalSignInTest.php, tests/Feature/Sso/, tests/Feature/Scim/, tests/Feature/Http/SsoHttpTest.php, tests/Feature/Http/ScimTokensHttpTest.php, tests/Feature/Ui/SsoPagesTest.php, tests/Feature/Ui/ScimPagesTest.php, tests/Browser/SsoBrowserTest.php, tests/Browser/ScimBrowserTest.php, tests/Modes/SsoUnavailable/, tests/SsoUnavailableTestCase.php, tests/Pest.php, tests/ArchTest.php, tests/Authorization/, tests/Feature/IndexesTest.php, tests/Feature/Organization/MembershipSourceTest.php, tests/Feature/PerformanceTest.php, tests/Feature/Permission/PermissionSyncTest.php, tests/Feature/Permission/RegisteredResourcesTest.php, tests/Feature/ProvisionedStatusTest.php, tests/Feature/SoftDeleteTest.php, tests/Feature/StoredIdentifiersTest.php, tests/Feature/Transfers/TemplateTest.php, tests/Feature/Ui/OrganizationTabBarTest.php, tests/Feature/Ui/OrganizationRegisteredTabsTest.php, tests/Feature/Ui/UserRegisteredTabsTest.php, tests/Feature/UserApprovalTest.php, tests/Feature/ComposerTest.php, tests/Modes/Keen/KeenAuditTest.php, tests/Modes/RenamedTables/RenamedTablesTest.php, tests/Unit/Organization/MembershipSourcesTest.php, tests/Unit/Permission/PermissionCatalogueTest.php +criteria: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 + +- [ ] 1.1 Write tests for criteria 1 to 13: `RemovedSsoScimTest` (folders and classes absent, `class_exists('RefactorCircus\Roster\Domains\Sso\Models\SsoConnectionModel')` false, the arch rule, `Resources`/`PermissionCatalogue`/`MembershipSources`/`Authorizer` answers, no `scim_token` with a positive control and an old entry still rendering, the route-name dataset and route-table regex scan, `Surface` content, MCP tool names, the five organization tabs with `?tab=sso`/`?tab=scim` opening `members`, no `ssoIdentities` on the overview, config and `Tables::DEFAULTS` keys, the criterion 12 regex scan and the vendor-namespace scan); kept permission rows across every `roster:sync-permissions` option; the raw `scim` source on read, write, import and filter paths, and `SCIM` once registered; `LegacySsoScimUpgradeTest` with the verbatim fixture through migrate, rollback, refresh and fresh plus a stray `migrations` row; `NoExternalSignInTest` through `Roster::requireSignIn()`; `ComposerTest` for `suggest`, `require-dev` and the unchanged Atrium `conflict` +- [ ] 1.2 Delete the SSO and SCIM domains, factory, `DescribesSsoConnection`, the ten MCP tools, both Atrium controllers, `ui/sso`, the plugin routes, the `sso`/`scim` tabs, icons and permission-map entries, the overview card, the `scim` surface, the config sections, `Tables` keys, lang keys and migrations 000006/000007; strip the SSO/SCIM entries from the two index migrations; add `Support\Rules\NoExternalSignIn` with `external_sign_in_required`; reword the comments listed in criterion 12; update `composer.json` `suggest`/`require-dev` and regenerate `composer.local.json`; delete and edit the tests listed in criterion 16 (only their SSO/SCIM cases) +- [ ] 1.3 Run vendor/bin/pest (including `tests/Modes/AtriumUnavailable`) and composer analyse; all green + +## Group 2: Upgrade docs and gate +package: Roster +depends on: 1 +files: CHANGELOG.md, README.md, resources/boost/skills/roster-development/SKILL.md, CLAUDE.md, AGENTS.md, docs/agent/product/roadmap.md, docs/agent/standards/http/authorization.md, tests/Feature/DocsTest.php +criteria: 14, 15, 16 + +- [ ] 2.1 Write tests for criteria 14 and 15: the DocsTest slice for "SSO and SCIM moved to refactor-circus/guardian" (bold fail-open first line, the six ordered steps with step 2 bold, `guardian:upgrade-from-roster`, `NoExternalSignIn` and the listed strings), the README section heading, bold warning and `guardian:upgrade-from-roster`, no old SSO/SCIM headings, no `NotSsoEnforced`/`SsoConnectionModel`/`Domains\Sso` outside the Guardian section in README and `SKILL.md`, no sso/scim tab entries, and `CLAUDE.md`/`AGENTS.md` free of the criterion 12 regex and `scim.php` +- [ ] 2.2 Write the CHANGELOG Breaking entry (including the step telling apps that installed Guardian early to run `php artisan guardian:upgrade-from-roster` after upgrading Roster), replace the README SSO/SCIM sections, update "Extending Roster", the config and tab lists, the Boost skill per `package-generate-skill`, `CLAUDE.md`, `AGENTS.md`, the roadmap note and the local authorization standard, then rerun `vendor/bin/ringside sync`; draft the PR description listing every changed or deleted test by file and test name and the before/after test counts +- [ ] 2.3 Run vendor/bin/pest, composer test and composer test:browser; all green From c8d55a3b47a938b8de880f3c52141492c1ff000e Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Fri, 30 Oct 2026 02:29:19 -0400 Subject: [PATCH 05/17] remove-sso-and-scim: building Co-Authored-By: Claude Opus 5.5 --- docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/meta.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/meta.yml b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/meta.yml index c3aac28..66f450d 100644 --- a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/meta.yml +++ b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/meta.yml @@ -1,6 +1,6 @@ id: 2026-10-29-2038-remove-sso-and-scim title: 'Remove SSO and SCIM' -status: approved +status: building created: '2026-10-29 20:38' standards: refactor-circus/standards: From 28a2feb8953d0ca6cf651f4ab38e131aba81a2cc Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Fri, 30 Oct 2026 02:41:00 -0400 Subject: [PATCH 06/17] 2026-10-29-2038-remove-sso-and-scim: group 1 Remove SSO and SCIM code, surfaces, config and migrations (salvaged) Co-Authored-By: Claude Opus 5.5 --- composer.json | 11 +- config/roster.php | 74 +-- database/factories/SsoConnectionFactory.php | 46 -- ...0002_create_roster_organization_tables.php | 2 +- ..._01_01_000006_create_roster_sso_tables.php | 47 -- ...01_01_000007_create_roster_scim_tables.php | 58 --- ...01_01_000010_add_roster_lookup_indexes.php | 3 - ..._000001_add_roster_performance_indexes.php | 2 +- ...002_add_roster_users_email_lower_index.php | 2 +- lang/en/roster.php | 56 +-- resources/import-templates/import_users.csv | 2 +- .../views/ui/organizations/show.blade.php | 116 ----- .../views/ui/sso/partials/fields.blade.php | 48 -- resources/views/ui/sso/show.blade.php | 47 -- .../ui/users/partials/overview.blade.php | 19 - resources/views/ui/users/show.blade.php | 1 - .../Controllers/OrganizationUiController.php | 13 - .../Http/Controllers/ScimUiController.php | 50 -- .../Http/Controllers/SsoUiController.php | 109 ----- .../Http/Controllers/UserUiController.php | 3 - src/Atrium/RosterPlugin.php | 11 - src/Data/ExternalSignIn.php | 3 +- src/Domains/DomainServiceProvider.php | 4 - .../Actions/PurgeOrganizationAction.php | 2 +- .../Concerns/OrganizationRules.php | 2 +- .../Data/CreateOrganizationData.php | 4 +- .../Mcp/Tools/PurgeOrganizationTool.php | 2 +- .../Permission/PermissionServiceProvider.php | 2 +- .../Scim/Actions/CreateScimTokenAction.php | 56 --- .../Scim/Actions/ListScimTokensAction.php | 34 -- .../Scim/Actions/RevokeScimTokenAction.php | 31 -- src/Domains/Scim/Data/CreateScimTokenData.php | 33 -- src/Domains/Scim/Data/IssuedScimToken.php | 20 - src/Domains/Scim/Data/ListScimTokensData.php | 36 -- .../Scim/Events/ScimGroupCreatedEvent.php | 32 -- .../Scim/Events/ScimGroupCreatingEvent.php | 32 -- .../Scim/Events/ScimGroupDeletedEvent.php | 32 -- .../Scim/Events/ScimGroupDeletingEvent.php | 32 -- .../Scim/Events/ScimGroupReplicatingEvent.php | 32 -- .../Scim/Events/ScimGroupRetrievedEvent.php | 32 -- .../Scim/Events/ScimGroupSavedEvent.php | 32 -- .../Scim/Events/ScimGroupSavingEvent.php | 32 -- .../Scim/Events/ScimGroupUpdatedEvent.php | 32 -- .../Scim/Events/ScimGroupUpdatingEvent.php | 32 -- .../Events/ScimTokenCreatedActionEvent.php | 23 - .../Scim/Events/ScimTokenCreatedEvent.php | 32 -- .../Events/ScimTokenCreatingActionEvent.php | 25 - .../Scim/Events/ScimTokenCreatingEvent.php | 32 -- .../Scim/Events/ScimTokenDeletedEvent.php | 32 -- .../Scim/Events/ScimTokenDeletingEvent.php | 32 -- .../Scim/Events/ScimTokenReplicatingEvent.php | 32 -- .../Scim/Events/ScimTokenRetrievedEvent.php | 32 -- .../Events/ScimTokenRevokedActionEvent.php | 23 - .../Events/ScimTokenRevokingActionEvent.php | 23 - .../Scim/Events/ScimTokenSavedEvent.php | 32 -- .../Scim/Events/ScimTokenSavingEvent.php | 32 -- .../Scim/Events/ScimTokenUpdatedEvent.php | 32 -- .../Scim/Events/ScimTokenUpdatingEvent.php | 32 -- .../Events/ScimTokensListedActionEvent.php | 25 - .../Events/ScimTokensListingActionEvent.php | 25 - .../Scim/Events/ScimUserCreatedEvent.php | 32 -- .../Scim/Events/ScimUserCreatingEvent.php | 32 -- .../Scim/Events/ScimUserDeletedEvent.php | 32 -- .../Scim/Events/ScimUserDeletingEvent.php | 32 -- .../Scim/Events/ScimUserReplicatingEvent.php | 32 -- .../Scim/Events/ScimUserRetrievedEvent.php | 32 -- .../Scim/Events/ScimUserSavedEvent.php | 32 -- .../Scim/Events/ScimUserSavingEvent.php | 32 -- .../Scim/Events/ScimUserUpdatedEvent.php | 32 -- .../Scim/Events/ScimUserUpdatingEvent.php | 32 -- src/Domains/Scim/Exceptions/ScimException.php | 68 --- .../Scim/Http/Controllers/ScimController.php | 234 ---------- .../Http/Controllers/ScimTokenController.php | 28 -- .../Http/Middleware/AuthenticateScimToken.php | 47 -- .../Http/Requests/IndexScimTokensRequest.php | 29 -- .../Http/Requests/RevokeScimTokenRequest.php | 37 -- .../Http/Requests/StoreScimTokenRequest.php | 34 -- .../Requests/CreateScimTokenMcpRequest.php | 31 -- .../Mcp/Requests/ListScimTokensMcpRequest.php | 31 -- .../Requests/RevokeScimTokenMcpRequest.php | 42 -- .../Scim/Mcp/Tools/CreateScimTokenTool.php | 39 -- .../Scim/Mcp/Tools/ListScimTokensTool.php | 37 -- .../Scim/Mcp/Tools/RevokeScimTokenTool.php | 34 -- src/Domains/Scim/Models/ScimGroupModel.php | 53 --- src/Domains/Scim/Models/ScimTokenModel.php | 75 --- src/Domains/Scim/Models/ScimUserModel.php | 67 --- src/Domains/Scim/Policies/ScimGroupPolicy.php | 26 -- src/Domains/Scim/Policies/ScimTokenPolicy.php | 20 - src/Domains/Scim/Policies/ScimUserPolicy.php | 26 -- .../Scim/Resources/ScimTokenResource.php | 60 --- src/Domains/Scim/ScimServiceProvider.php | 107 ----- src/Domains/Scim/Services/Bulk.php | 158 ------- src/Domains/Scim/Services/Discovery.php | 95 ---- src/Domains/Scim/Services/FilterParser.php | 69 --- src/Domains/Scim/Services/PatchApplier.php | 189 -------- src/Domains/Scim/Services/Scim.php | 75 --- src/Domains/Scim/Services/ScimContext.php | 50 -- src/Domains/Scim/Services/ScimGroups.php | 292 ------------ src/Domains/Scim/Services/ScimMapper.php | 119 ----- src/Domains/Scim/Services/ScimQuery.php | 38 -- src/Domains/Scim/Services/ScimUsers.php | 428 ------------------ src/Domains/Scim/routes.php | 10 - src/Domains/Scim/scim.php | 38 -- .../Sso/Actions/CreateSsoConnectionAction.php | 53 --- .../Sso/Actions/DeleteSsoConnectionAction.php | 25 - .../Sso/Actions/LinkSsoIdentityAction.php | 45 -- .../Sso/Actions/ListSsoConnectionsAction.php | 38 -- .../Sso/Actions/ListSsoIdentitiesAction.php | 47 -- .../Sso/Actions/ShowSsoConnectionAction.php | 23 - src/Domains/Sso/Actions/SsoLoginAction.php | 170 ------- .../Sso/Actions/UnlinkSsoIdentityAction.php | 26 -- .../Sso/Actions/UpdateSsoConnectionAction.php | 39 -- .../Sso/Concerns/SsoConnectionRules.php | 115 ----- .../Sso/Data/CreateSsoConnectionData.php | 53 --- src/Domains/Sso/Data/IdentityClaims.php | 21 - .../Sso/Data/ListSsoConnectionsData.php | 40 -- .../Sso/Data/ListSsoIdentitiesData.php | 42 -- .../Sso/Data/UpdateSsoConnectionData.php | 56 --- .../SsoConnectionCreatedActionEvent.php | 23 - .../Sso/Events/SsoConnectionCreatedEvent.php | 32 -- .../SsoConnectionCreatingActionEvent.php | 25 - .../Sso/Events/SsoConnectionCreatingEvent.php | 32 -- .../SsoConnectionDeletedActionEvent.php | 23 - .../Sso/Events/SsoConnectionDeletedEvent.php | 32 -- .../SsoConnectionDeletingActionEvent.php | 23 - .../Sso/Events/SsoConnectionDeletingEvent.php | 32 -- .../Events/SsoConnectionReplicatingEvent.php | 32 -- .../Events/SsoConnectionRetrievedEvent.php | 32 -- .../Sso/Events/SsoConnectionSavedEvent.php | 32 -- .../Sso/Events/SsoConnectionSavingEvent.php | 32 -- .../SsoConnectionShowingActionEvent.php | 23 - .../Events/SsoConnectionShownActionEvent.php | 23 - .../SsoConnectionUpdatedActionEvent.php | 23 - .../Sso/Events/SsoConnectionUpdatedEvent.php | 32 -- .../SsoConnectionUpdatingActionEvent.php | 25 - .../Sso/Events/SsoConnectionUpdatingEvent.php | 32 -- .../SsoConnectionsListedActionEvent.php | 23 - .../SsoConnectionsListingActionEvent.php | 23 - .../Events/SsoIdentitiesListedActionEvent.php | 23 - .../SsoIdentitiesListingActionEvent.php | 23 - .../Sso/Events/SsoIdentityCreatedEvent.php | 32 -- .../Sso/Events/SsoIdentityCreatingEvent.php | 32 -- .../Sso/Events/SsoIdentityDeletedEvent.php | 32 -- .../Sso/Events/SsoIdentityDeletingEvent.php | 32 -- .../Events/SsoIdentityLinkedActionEvent.php | 25 - .../Events/SsoIdentityLinkingActionEvent.php | 25 - .../Events/SsoIdentityReplicatingEvent.php | 32 -- .../Sso/Events/SsoIdentityRetrievedEvent.php | 32 -- .../Sso/Events/SsoIdentitySavedEvent.php | 32 -- .../Sso/Events/SsoIdentitySavingEvent.php | 32 -- .../Events/SsoIdentityUnlinkedActionEvent.php | 23 - .../SsoIdentityUnlinkingActionEvent.php | 23 - .../Sso/Events/SsoIdentityUpdatedEvent.php | 32 -- .../Sso/Events/SsoIdentityUpdatingEvent.php | 32 -- .../Sso/Events/SsoLoginFailedActionEvent.php | 25 - .../Events/SsoLoginStartingActionEvent.php | 23 - .../Events/SsoLoginSucceededActionEvent.php | 26 -- .../Sso/Exceptions/SsoLoginRefused.php | 19 - .../Exceptions/SsoUnavailableException.php | 21 - .../Sso/Http/Controllers/SsoController.php | 53 --- .../Sso/Http/Controllers/SsoWebController.php | 136 ------ .../Requests/DestroySsoConnectionRequest.php | 23 - .../Requests/DestroySsoIdentityRequest.php | 49 -- .../Requests/IndexSsoConnectionsRequest.php | 29 -- .../IndexUserSsoIdentitiesRequest.php | 35 -- .../Requests/ShowSsoConnectionRequest.php | 22 - .../Http/Requests/SsoConnectionRequest.php | 24 - .../Requests/StoreSsoConnectionRequest.php | 31 -- .../Requests/UpdateSsoConnectionRequest.php | 28 -- .../CreateSsoConnectionMcpRequest.php | 31 -- .../DeleteSsoConnectionMcpRequest.php | 23 - .../Requests/ListSsoConnectionsMcpRequest.php | 31 -- .../Requests/ListSsoIdentitiesMcpRequest.php | 37 -- .../Requests/ShowSsoConnectionMcpRequest.php | 22 - .../Mcp/Requests/SsoConnectionMcpRequest.php | 40 -- .../Requests/UnlinkSsoIdentityMcpRequest.php | 51 --- .../UpdateSsoConnectionMcpRequest.php | 28 -- .../Sso/Mcp/Tools/CreateSsoConnectionTool.php | 41 -- .../Sso/Mcp/Tools/DeleteSsoConnectionTool.php | 28 -- .../Sso/Mcp/Tools/ListSsoConnectionsTool.php | 37 -- .../Sso/Mcp/Tools/ListSsoIdentitiesTool.php | 37 -- .../Sso/Mcp/Tools/ShowSsoConnectionTool.php | 34 -- .../Sso/Mcp/Tools/UnlinkSsoIdentityTool.php | 28 -- .../Sso/Mcp/Tools/UpdateSsoConnectionTool.php | 39 -- src/Domains/Sso/Models/SsoConnectionModel.php | 135 ------ src/Domains/Sso/Models/SsoIdentityModel.php | 67 --- .../Sso/Policies/SsoConnectionPolicy.php | 25 - .../Sso/Policies/SsoIdentityPolicy.php | 26 -- .../Sso/Resources/SsoConnectionResource.php | 72 --- .../Sso/Resources/SsoIdentityResource.php | 55 --- src/Domains/Sso/Services/OidcProvider.php | 175 ------- src/Domains/Sso/Services/Sso.php | 122 ----- .../Sso/Services/SsoSignInRequirement.php | 49 -- src/Domains/Sso/SsoServiceProvider.php | 65 --- src/Domains/Sso/routes.php | 14 - src/Domains/Sso/web.php | 21 - src/Mcp/Concerns/DescribesOrganization.php | 2 +- src/Mcp/Concerns/DescribesSsoConnection.php | 34 -- src/Mcp/RosterServer.php | 24 - src/Roster.php | 6 +- src/RosterServiceProvider.php | 11 +- src/Support/Audit.php | 4 +- src/Support/Policies/Policy.php | 4 +- src/Support/ProvisionedStatus.php | 4 +- .../Rules/NoExternalSignIn.php} | 13 +- src/Support/Tables.php | 5 - tests/Browser/ScimBrowserTest.php | 18 - tests/Browser/SsoBrowserTest.php | 28 -- tests/Feature/Http/ScimTokensHttpTest.php | 30 -- tests/Feature/Http/SsoHttpTest.php | 46 -- tests/Feature/Scim/ScimAuditContextTest.php | 132 ------ tests/Feature/Scim/ScimAuthTest.php | 43 -- tests/Feature/Scim/ScimGroupsTest.php | 61 --- tests/Feature/Scim/ScimProtocolTest.php | 116 ----- tests/Feature/Scim/ScimUsersTest.php | 178 -------- tests/Feature/Scim/helpers.php | 54 --- tests/Feature/Sso/AzureFlowTest.php | 58 --- tests/Feature/Sso/OidcFlowTest.php | 65 --- tests/Feature/Sso/SsoLoginActionTest.php | 118 ----- tests/Feature/Sso/SsoWiringTest.php | 194 -------- tests/Feature/Sso/helpers.php | 82 ---- tests/Feature/Transfers/TemplateTest.php | 2 +- tests/Feature/Ui/ScimPagesTest.php | 21 - tests/Feature/Ui/SsoPagesTest.php | 51 --- .../SsoUnavailable/SsoUnavailableTest.php | 21 - tests/SsoUnavailableTestCase.php | 26 -- 226 files changed, 47 insertions(+), 9829 deletions(-) delete mode 100644 database/factories/SsoConnectionFactory.php delete mode 100644 database/migrations/2026_01_01_000006_create_roster_sso_tables.php delete mode 100644 database/migrations/2026_01_01_000007_create_roster_scim_tables.php delete mode 100644 resources/views/ui/sso/partials/fields.blade.php delete mode 100644 resources/views/ui/sso/show.blade.php delete mode 100644 src/Atrium/Http/Controllers/ScimUiController.php delete mode 100644 src/Atrium/Http/Controllers/SsoUiController.php delete mode 100644 src/Domains/Scim/Actions/CreateScimTokenAction.php delete mode 100644 src/Domains/Scim/Actions/ListScimTokensAction.php delete mode 100644 src/Domains/Scim/Actions/RevokeScimTokenAction.php delete mode 100644 src/Domains/Scim/Data/CreateScimTokenData.php delete mode 100644 src/Domains/Scim/Data/IssuedScimToken.php delete mode 100644 src/Domains/Scim/Data/ListScimTokensData.php delete mode 100644 src/Domains/Scim/Events/ScimGroupCreatedEvent.php delete mode 100644 src/Domains/Scim/Events/ScimGroupCreatingEvent.php delete mode 100644 src/Domains/Scim/Events/ScimGroupDeletedEvent.php delete mode 100644 src/Domains/Scim/Events/ScimGroupDeletingEvent.php delete mode 100644 src/Domains/Scim/Events/ScimGroupReplicatingEvent.php delete mode 100644 src/Domains/Scim/Events/ScimGroupRetrievedEvent.php delete mode 100644 src/Domains/Scim/Events/ScimGroupSavedEvent.php delete mode 100644 src/Domains/Scim/Events/ScimGroupSavingEvent.php delete mode 100644 src/Domains/Scim/Events/ScimGroupUpdatedEvent.php delete mode 100644 src/Domains/Scim/Events/ScimGroupUpdatingEvent.php delete mode 100644 src/Domains/Scim/Events/ScimTokenCreatedActionEvent.php delete mode 100644 src/Domains/Scim/Events/ScimTokenCreatedEvent.php delete mode 100644 src/Domains/Scim/Events/ScimTokenCreatingActionEvent.php delete mode 100644 src/Domains/Scim/Events/ScimTokenCreatingEvent.php delete mode 100644 src/Domains/Scim/Events/ScimTokenDeletedEvent.php delete mode 100644 src/Domains/Scim/Events/ScimTokenDeletingEvent.php delete mode 100644 src/Domains/Scim/Events/ScimTokenReplicatingEvent.php delete mode 100644 src/Domains/Scim/Events/ScimTokenRetrievedEvent.php delete mode 100644 src/Domains/Scim/Events/ScimTokenRevokedActionEvent.php delete mode 100644 src/Domains/Scim/Events/ScimTokenRevokingActionEvent.php delete mode 100644 src/Domains/Scim/Events/ScimTokenSavedEvent.php delete mode 100644 src/Domains/Scim/Events/ScimTokenSavingEvent.php delete mode 100644 src/Domains/Scim/Events/ScimTokenUpdatedEvent.php delete mode 100644 src/Domains/Scim/Events/ScimTokenUpdatingEvent.php delete mode 100644 src/Domains/Scim/Events/ScimTokensListedActionEvent.php delete mode 100644 src/Domains/Scim/Events/ScimTokensListingActionEvent.php delete mode 100644 src/Domains/Scim/Events/ScimUserCreatedEvent.php delete mode 100644 src/Domains/Scim/Events/ScimUserCreatingEvent.php delete mode 100644 src/Domains/Scim/Events/ScimUserDeletedEvent.php delete mode 100644 src/Domains/Scim/Events/ScimUserDeletingEvent.php delete mode 100644 src/Domains/Scim/Events/ScimUserReplicatingEvent.php delete mode 100644 src/Domains/Scim/Events/ScimUserRetrievedEvent.php delete mode 100644 src/Domains/Scim/Events/ScimUserSavedEvent.php delete mode 100644 src/Domains/Scim/Events/ScimUserSavingEvent.php delete mode 100644 src/Domains/Scim/Events/ScimUserUpdatedEvent.php delete mode 100644 src/Domains/Scim/Events/ScimUserUpdatingEvent.php delete mode 100644 src/Domains/Scim/Exceptions/ScimException.php delete mode 100644 src/Domains/Scim/Http/Controllers/ScimController.php delete mode 100644 src/Domains/Scim/Http/Controllers/ScimTokenController.php delete mode 100644 src/Domains/Scim/Http/Middleware/AuthenticateScimToken.php delete mode 100644 src/Domains/Scim/Http/Requests/IndexScimTokensRequest.php delete mode 100644 src/Domains/Scim/Http/Requests/RevokeScimTokenRequest.php delete mode 100644 src/Domains/Scim/Http/Requests/StoreScimTokenRequest.php delete mode 100644 src/Domains/Scim/Mcp/Requests/CreateScimTokenMcpRequest.php delete mode 100644 src/Domains/Scim/Mcp/Requests/ListScimTokensMcpRequest.php delete mode 100644 src/Domains/Scim/Mcp/Requests/RevokeScimTokenMcpRequest.php delete mode 100644 src/Domains/Scim/Mcp/Tools/CreateScimTokenTool.php delete mode 100644 src/Domains/Scim/Mcp/Tools/ListScimTokensTool.php delete mode 100644 src/Domains/Scim/Mcp/Tools/RevokeScimTokenTool.php delete mode 100644 src/Domains/Scim/Models/ScimGroupModel.php delete mode 100644 src/Domains/Scim/Models/ScimTokenModel.php delete mode 100644 src/Domains/Scim/Models/ScimUserModel.php delete mode 100644 src/Domains/Scim/Policies/ScimGroupPolicy.php delete mode 100644 src/Domains/Scim/Policies/ScimTokenPolicy.php delete mode 100644 src/Domains/Scim/Policies/ScimUserPolicy.php delete mode 100644 src/Domains/Scim/Resources/ScimTokenResource.php delete mode 100644 src/Domains/Scim/ScimServiceProvider.php delete mode 100644 src/Domains/Scim/Services/Bulk.php delete mode 100644 src/Domains/Scim/Services/Discovery.php delete mode 100644 src/Domains/Scim/Services/FilterParser.php delete mode 100644 src/Domains/Scim/Services/PatchApplier.php delete mode 100644 src/Domains/Scim/Services/Scim.php delete mode 100644 src/Domains/Scim/Services/ScimContext.php delete mode 100644 src/Domains/Scim/Services/ScimGroups.php delete mode 100644 src/Domains/Scim/Services/ScimMapper.php delete mode 100644 src/Domains/Scim/Services/ScimQuery.php delete mode 100644 src/Domains/Scim/Services/ScimUsers.php delete mode 100644 src/Domains/Scim/routes.php delete mode 100644 src/Domains/Scim/scim.php delete mode 100644 src/Domains/Sso/Actions/CreateSsoConnectionAction.php delete mode 100644 src/Domains/Sso/Actions/DeleteSsoConnectionAction.php delete mode 100644 src/Domains/Sso/Actions/LinkSsoIdentityAction.php delete mode 100644 src/Domains/Sso/Actions/ListSsoConnectionsAction.php delete mode 100644 src/Domains/Sso/Actions/ListSsoIdentitiesAction.php delete mode 100644 src/Domains/Sso/Actions/ShowSsoConnectionAction.php delete mode 100644 src/Domains/Sso/Actions/SsoLoginAction.php delete mode 100644 src/Domains/Sso/Actions/UnlinkSsoIdentityAction.php delete mode 100644 src/Domains/Sso/Actions/UpdateSsoConnectionAction.php delete mode 100644 src/Domains/Sso/Concerns/SsoConnectionRules.php delete mode 100644 src/Domains/Sso/Data/CreateSsoConnectionData.php delete mode 100644 src/Domains/Sso/Data/IdentityClaims.php delete mode 100644 src/Domains/Sso/Data/ListSsoConnectionsData.php delete mode 100644 src/Domains/Sso/Data/ListSsoIdentitiesData.php delete mode 100644 src/Domains/Sso/Data/UpdateSsoConnectionData.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionCreatedActionEvent.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionCreatedEvent.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionCreatingActionEvent.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionCreatingEvent.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionDeletedActionEvent.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionDeletedEvent.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionDeletingActionEvent.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionDeletingEvent.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionReplicatingEvent.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionRetrievedEvent.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionSavedEvent.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionSavingEvent.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionShowingActionEvent.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionShownActionEvent.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionUpdatedActionEvent.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionUpdatedEvent.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionUpdatingActionEvent.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionUpdatingEvent.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionsListedActionEvent.php delete mode 100644 src/Domains/Sso/Events/SsoConnectionsListingActionEvent.php delete mode 100644 src/Domains/Sso/Events/SsoIdentitiesListedActionEvent.php delete mode 100644 src/Domains/Sso/Events/SsoIdentitiesListingActionEvent.php delete mode 100644 src/Domains/Sso/Events/SsoIdentityCreatedEvent.php delete mode 100644 src/Domains/Sso/Events/SsoIdentityCreatingEvent.php delete mode 100644 src/Domains/Sso/Events/SsoIdentityDeletedEvent.php delete mode 100644 src/Domains/Sso/Events/SsoIdentityDeletingEvent.php delete mode 100644 src/Domains/Sso/Events/SsoIdentityLinkedActionEvent.php delete mode 100644 src/Domains/Sso/Events/SsoIdentityLinkingActionEvent.php delete mode 100644 src/Domains/Sso/Events/SsoIdentityReplicatingEvent.php delete mode 100644 src/Domains/Sso/Events/SsoIdentityRetrievedEvent.php delete mode 100644 src/Domains/Sso/Events/SsoIdentitySavedEvent.php delete mode 100644 src/Domains/Sso/Events/SsoIdentitySavingEvent.php delete mode 100644 src/Domains/Sso/Events/SsoIdentityUnlinkedActionEvent.php delete mode 100644 src/Domains/Sso/Events/SsoIdentityUnlinkingActionEvent.php delete mode 100644 src/Domains/Sso/Events/SsoIdentityUpdatedEvent.php delete mode 100644 src/Domains/Sso/Events/SsoIdentityUpdatingEvent.php delete mode 100644 src/Domains/Sso/Events/SsoLoginFailedActionEvent.php delete mode 100644 src/Domains/Sso/Events/SsoLoginStartingActionEvent.php delete mode 100644 src/Domains/Sso/Events/SsoLoginSucceededActionEvent.php delete mode 100644 src/Domains/Sso/Exceptions/SsoLoginRefused.php delete mode 100644 src/Domains/Sso/Exceptions/SsoUnavailableException.php delete mode 100644 src/Domains/Sso/Http/Controllers/SsoController.php delete mode 100644 src/Domains/Sso/Http/Controllers/SsoWebController.php delete mode 100644 src/Domains/Sso/Http/Requests/DestroySsoConnectionRequest.php delete mode 100644 src/Domains/Sso/Http/Requests/DestroySsoIdentityRequest.php delete mode 100644 src/Domains/Sso/Http/Requests/IndexSsoConnectionsRequest.php delete mode 100644 src/Domains/Sso/Http/Requests/IndexUserSsoIdentitiesRequest.php delete mode 100644 src/Domains/Sso/Http/Requests/ShowSsoConnectionRequest.php delete mode 100644 src/Domains/Sso/Http/Requests/SsoConnectionRequest.php delete mode 100644 src/Domains/Sso/Http/Requests/StoreSsoConnectionRequest.php delete mode 100644 src/Domains/Sso/Http/Requests/UpdateSsoConnectionRequest.php delete mode 100644 src/Domains/Sso/Mcp/Requests/CreateSsoConnectionMcpRequest.php delete mode 100644 src/Domains/Sso/Mcp/Requests/DeleteSsoConnectionMcpRequest.php delete mode 100644 src/Domains/Sso/Mcp/Requests/ListSsoConnectionsMcpRequest.php delete mode 100644 src/Domains/Sso/Mcp/Requests/ListSsoIdentitiesMcpRequest.php delete mode 100644 src/Domains/Sso/Mcp/Requests/ShowSsoConnectionMcpRequest.php delete mode 100644 src/Domains/Sso/Mcp/Requests/SsoConnectionMcpRequest.php delete mode 100644 src/Domains/Sso/Mcp/Requests/UnlinkSsoIdentityMcpRequest.php delete mode 100644 src/Domains/Sso/Mcp/Requests/UpdateSsoConnectionMcpRequest.php delete mode 100644 src/Domains/Sso/Mcp/Tools/CreateSsoConnectionTool.php delete mode 100644 src/Domains/Sso/Mcp/Tools/DeleteSsoConnectionTool.php delete mode 100644 src/Domains/Sso/Mcp/Tools/ListSsoConnectionsTool.php delete mode 100644 src/Domains/Sso/Mcp/Tools/ListSsoIdentitiesTool.php delete mode 100644 src/Domains/Sso/Mcp/Tools/ShowSsoConnectionTool.php delete mode 100644 src/Domains/Sso/Mcp/Tools/UnlinkSsoIdentityTool.php delete mode 100644 src/Domains/Sso/Mcp/Tools/UpdateSsoConnectionTool.php delete mode 100644 src/Domains/Sso/Models/SsoConnectionModel.php delete mode 100644 src/Domains/Sso/Models/SsoIdentityModel.php delete mode 100644 src/Domains/Sso/Policies/SsoConnectionPolicy.php delete mode 100644 src/Domains/Sso/Policies/SsoIdentityPolicy.php delete mode 100644 src/Domains/Sso/Resources/SsoConnectionResource.php delete mode 100644 src/Domains/Sso/Resources/SsoIdentityResource.php delete mode 100644 src/Domains/Sso/Services/OidcProvider.php delete mode 100644 src/Domains/Sso/Services/Sso.php delete mode 100644 src/Domains/Sso/Services/SsoSignInRequirement.php delete mode 100644 src/Domains/Sso/SsoServiceProvider.php delete mode 100644 src/Domains/Sso/routes.php delete mode 100644 src/Domains/Sso/web.php delete mode 100644 src/Mcp/Concerns/DescribesSsoConnection.php rename src/{Domains/Sso/Support/NotSsoEnforced.php => Support/Rules/NoExternalSignIn.php} (59%) delete mode 100644 tests/Browser/ScimBrowserTest.php delete mode 100644 tests/Browser/SsoBrowserTest.php delete mode 100644 tests/Feature/Http/ScimTokensHttpTest.php delete mode 100644 tests/Feature/Http/SsoHttpTest.php delete mode 100644 tests/Feature/Scim/ScimAuditContextTest.php delete mode 100644 tests/Feature/Scim/ScimAuthTest.php delete mode 100644 tests/Feature/Scim/ScimGroupsTest.php delete mode 100644 tests/Feature/Scim/ScimProtocolTest.php delete mode 100644 tests/Feature/Scim/ScimUsersTest.php delete mode 100644 tests/Feature/Scim/helpers.php delete mode 100644 tests/Feature/Sso/AzureFlowTest.php delete mode 100644 tests/Feature/Sso/OidcFlowTest.php delete mode 100644 tests/Feature/Sso/SsoLoginActionTest.php delete mode 100644 tests/Feature/Sso/SsoWiringTest.php delete mode 100644 tests/Feature/Sso/helpers.php delete mode 100644 tests/Feature/Ui/ScimPagesTest.php delete mode 100644 tests/Feature/Ui/SsoPagesTest.php delete mode 100644 tests/Modes/SsoUnavailable/SsoUnavailableTest.php delete mode 100644 tests/SsoUnavailableTestCase.php diff --git a/composer.json b/composer.json index c1f0fcb..cf10b7e 100644 --- a/composer.json +++ b/composer.json @@ -23,11 +23,9 @@ "laravel/mcp": "^1.0.1" }, "require-dev": { - "firebase/php-jwt": "^7.2.1", "larastan/larastan": "^3.13", "laravel/pao": "^1.1.5", "laravel/pint": "^1.32.1", - "laravel/socialite": "^5.31", "orchestra/testbench": "^11.3", "pestphp/pest": "^5.3.4", "pestphp/pest-plugin-browser": "^5.1.2", @@ -40,9 +38,7 @@ "refactor-circus/keen": "dev-main", "refactor-circus/pennantplus": "dev-main", "refactor-circus/ringside": "dev-main", - "refactor-circus/standards": "dev-main", - "socialiteproviders/microsoft-azure": "^5.2.1", - "socialiteproviders/saml2": "^4.10" + "refactor-circus/standards": "dev-main" }, "conflict": { "refactor-circus/atrium": "<0.1.0" @@ -50,10 +46,7 @@ "suggest": { "refactor-circus/atrium": "The Atrium dashboard: Roster's admin screens, widgets and search (dev-main).", "refactor-circus/cortex": "Lets Cortex agents use the Roster tools (dev-main).", - "laravel/socialite": "Required for SSO login (^5.31).", - "socialiteproviders/saml2": "Required for SAML SSO connections (^4.10).", - "firebase/php-jwt": "Required for OIDC SSO connections, to verify id_tokens (^7.2).", - "socialiteproviders/microsoft-azure": "Required for Microsoft Entra ID (Azure) SSO connections (^5.2).", + "refactor-circus/guardian": "Single sign-on (OIDC, SAML, Entra ID) and SCIM provisioning for Roster's organizations (dev-main).", "refactor-circus/impex": "Required for CSV import and export (dev-main).", "refactor-circus/pennantplus": "Switch Roster in Atrium on and off with the RosterSupportFeature Pennant feature (dev-main).", "refactor-circus/keen": "Records Roster's changes in the suite-wide audit log (dev-main)." diff --git a/config/roster.php b/config/roster.php index 729e60b..548d509 100644 --- a/config/roster.php +++ b/config/roster.php @@ -64,8 +64,8 @@ | `active`, or `pending` to make people who sign up through the | app's own registration (Laravel's Registered event) wait for | an approver. Admins choose per user when they create one, and - | each organization chooses for accounts its SSO or SCIM - | creates (its `provisioned_status`). + | each organization chooses for its externally provisioned + | accounts (its `provisioned_status`). | approvals.notify_approvers: | Email everyone holding `roster.users.approve` when someone is | waiting for approval. @@ -208,65 +208,6 @@ 'middleware_group' => 'web', ], - /* - |-------------------------------------------------------------------------- - | Single Sign-On - |-------------------------------------------------------------------------- - | - | Organizations can sign their people in through their own identity - | provider (OIDC, SAML or Microsoft Entra ID), configured per - | organization in Atrium or via the API. Requires the optional package - | laravel/socialite plus, per protocol, firebase/php-jwt (OIDC), - | socialiteproviders/saml2 (SAML) or socialiteproviders/microsoft-azure - | (Entra ID). - | - | redirect: Where a successful sign-in lands. - | discovery_cache_seconds: How long OIDC discovery documents and signing - | keys are cached. - | prefix / middleware: Where the sign-in routes live. - | - | SECURITY: serve the callback over HTTPS. An identity provider is only - | trusted for its organization's own domains: new accounts and automatic - | linking happen only for those emails. - | - */ - - 'sso' => [ - 'redirect' => '/', - 'discovery_cache_seconds' => 3600, - 'prefix' => 'roster/sso', - 'middleware' => ['web'], - ], - - /* - |-------------------------------------------------------------------------- - | SCIM Provisioning - |-------------------------------------------------------------------------- - | - | A SCIM 2.0 server per organization at /{prefix}/{organization}, so - | identity providers (Okta, Microsoft Entra ID, ...) can create, update - | and deprovision its members (Users) and teams (Groups). - | - | Each request needs one of the organization's SCIM tokens (issued in - | Atrium or via the API, shown once, revocable). SECURITY: a token can - | change the organization's membership; treat it like a password. It - | only ever reaches its own organization, and only claims existing - | accounts on the organization's own domains. - | - */ - - 'scim' => [ - 'enabled' => true, - 'prefix' => 'scim/v2', - 'middleware' => ['api', 'throttle:roster'], - 'default_count' => 100, - 'max_count' => 500, - 'bulk' => [ - 'max_operations' => 100, - 'max_payload_bytes' => 1048576, - ], - ], - /* |-------------------------------------------------------------------------- | CSV Import and Export @@ -503,9 +444,9 @@ | organizations, members (MembershipModel), teams, invitations and roles. | The other policies answer your own `$user->can('view', $record)` checks. | - | The SSO and SCIM models' policies are registered by those domains - | themselves; add an entry here to point one of those models at a class - | of your own, which wins over the bundled one. + | Package resources register their own policies; add an entry here to + | point one of their models at a class of your own, which wins over the + | bundled one. | | Lists that show only what falls within the caller's organizations still | work those out from Roster's permissions. Permissions blocked while @@ -561,11 +502,6 @@ 'permission_role' => 'roster_permission_role', 'role_assignments' => 'roster_role_assignments', 'impersonations' => 'roster_impersonations', - 'sso_connections' => 'roster_sso_connections', - 'sso_identities' => 'roster_sso_identities', - 'scim_tokens' => 'roster_scim_tokens', - 'scim_users' => 'roster_scim_users', - 'scim_groups' => 'roster_scim_groups', 'transfers' => 'roster_transfers', 'transfer_rows' => 'roster_transfer_rows', ], diff --git a/database/factories/SsoConnectionFactory.php b/database/factories/SsoConnectionFactory.php deleted file mode 100644 index 8f55257..0000000 --- a/database/factories/SsoConnectionFactory.php +++ /dev/null @@ -1,46 +0,0 @@ - - */ -final class SsoConnectionFactory extends Factory -{ - protected $model = SsoConnectionModel::class; - - /** - * @return array - */ - public function definition(): array - { - return [ - 'name' => 'Okta', - 'slug' => 'okta-'.Str::lower(Str::random(6)), - 'protocol' => SsoConnectionModel::OIDC, - 'config' => ['issuer' => 'https://idp.example.com', 'client_id' => 'roster-app', 'client_secret' => 'top-secret'], - ]; - } - - public function azure(): self - { - return $this->state([ - 'protocol' => SsoConnectionModel::AZURE, - 'config' => ['tenant' => '11111111-2222-3333-4444-555555555555', 'client_id' => 'roster-app', 'client_secret' => 'top-secret'], - ]); - } - - public function saml(): self - { - return $this->state([ - 'protocol' => SsoConnectionModel::SAML, - 'config' => ['entity_id' => 'https://idp.example.com/saml', 'sso_url' => 'https://idp.example.com/saml/sso', 'certificate' => 'MIIC...'], - ]); - } -} diff --git a/database/migrations/2026_01_01_000002_create_roster_organization_tables.php b/database/migrations/2026_01_01_000002_create_roster_organization_tables.php index 6d73d50..e93e710 100644 --- a/database/migrations/2026_01_01_000002_create_roster_organization_tables.php +++ b/database/migrations/2026_01_01_000002_create_roster_organization_tables.php @@ -20,7 +20,7 @@ public function up(): void UserKey::column($table, 'owner_id')->nullable()->index(); $table->boolean('personal')->default(false); $table->boolean('auto_join')->default(false); - // The status of accounts this organization's SSO or SCIM creates. + // The status this organization's externally provisioned accounts start with. $table->string('provisioned_status', 16)->default('active'); // Deleted organizations keep their slug and domains until purged. $table->softDeletes(); diff --git a/database/migrations/2026_01_01_000006_create_roster_sso_tables.php b/database/migrations/2026_01_01_000006_create_roster_sso_tables.php deleted file mode 100644 index d0c0d34..0000000 --- a/database/migrations/2026_01_01_000006_create_roster_sso_tables.php +++ /dev/null @@ -1,47 +0,0 @@ -ulid('id')->primary(); - $table->foreignUlid('organization_id')->constrained(Tables::name('organizations'))->cascadeOnDelete(); - $table->string('name'); - $table->string('slug')->unique(); - $table->string('protocol', 8); - // Encrypted JSON: issuer, client id and secret, or SAML IdP details. - $table->text('config'); - $table->boolean('jit')->default(true); - $table->boolean('enforced')->default(false); - $table->boolean('enabled')->default(true); - $table->timestamps(); - }); - - Schema::create(Tables::name('sso_identities'), function (Blueprint $table): void { - $table->ulid('id')->primary(); - $table->foreignUlid('connection_id')->constrained(Tables::name('sso_connections'))->cascadeOnDelete(); - UserKey::column($table, 'user_id')->index(); - $table->string('subject'); - $table->string('email')->nullable(); - $table->timestamp('last_login_at')->nullable(); - $table->timestamps(); - - $table->unique(['connection_id', 'subject']); - }); - } - - public function down(): void - { - Schema::dropIfExists(Tables::name('sso_identities')); - Schema::dropIfExists(Tables::name('sso_connections')); - } -}; diff --git a/database/migrations/2026_01_01_000007_create_roster_scim_tables.php b/database/migrations/2026_01_01_000007_create_roster_scim_tables.php deleted file mode 100644 index a01a85e..0000000 --- a/database/migrations/2026_01_01_000007_create_roster_scim_tables.php +++ /dev/null @@ -1,58 +0,0 @@ -ulid('id')->primary(); - $table->foreignUlid('organization_id')->constrained(Tables::name('organizations'))->cascadeOnDelete(); - $table->string('name'); - $table->string('token_hash', 64)->unique(); - $table->foreignUlid('sso_connection_id')->nullable()->constrained(Tables::name('sso_connections'))->nullOnDelete(); - UserKey::column($table, 'created_by')->nullable(); - $table->timestamp('last_used_at')->nullable(); - $table->timestamp('expires_at')->nullable(); - $table->timestamp('revoked_at')->nullable(); - $table->timestamps(); - }); - - Schema::create(Tables::name('scim_users'), function (Blueprint $table): void { - // Its id is the SCIM resource id the identity provider sees. - $table->ulid('id')->primary(); - $table->foreignUlid('organization_id')->constrained(Tables::name('organizations'))->cascadeOnDelete(); - UserKey::column($table, 'user_id'); - $table->string('external_id')->nullable(); - $table->boolean('created_by_scim')->default(false); - $table->boolean('deactivated_by_scim')->default(false); - $table->boolean('active')->default(true); - $table->timestamps(); - - $table->unique(['organization_id', 'user_id']); - $table->index(['organization_id', 'external_id']); - }); - - Schema::create(Tables::name('scim_groups'), function (Blueprint $table): void { - $table->ulid('id')->primary(); - $table->foreignUlid('organization_id')->constrained(Tables::name('organizations'))->cascadeOnDelete(); - $table->foreignUlid('team_id')->unique()->constrained(Tables::name('teams'))->cascadeOnDelete(); - $table->string('external_id')->nullable(); - $table->timestamps(); - }); - } - - public function down(): void - { - Schema::dropIfExists(Tables::name('scim_groups')); - Schema::dropIfExists(Tables::name('scim_users')); - Schema::dropIfExists(Tables::name('scim_tokens')); - } -}; diff --git a/database/migrations/2026_01_01_000010_add_roster_lookup_indexes.php b/database/migrations/2026_01_01_000010_add_roster_lookup_indexes.php index 899d3d4..505261b 100644 --- a/database/migrations/2026_01_01_000010_add_roster_lookup_indexes.php +++ b/database/migrations/2026_01_01_000010_add_roster_lookup_indexes.php @@ -23,9 +23,6 @@ 'roles' => ['organization_id'], 'profiles' => ['current_organization_id', 'current_team_id'], 'impersonations' => ['organization_id', 'created_at'], - 'sso_connections' => ['organization_id'], - 'scim_tokens' => ['organization_id', 'sso_connection_id'], - 'scim_groups' => ['organization_id'], 'transfers' => ['organization_id'], ]; diff --git a/database/migrations/2026_10_12_000001_add_roster_performance_indexes.php b/database/migrations/2026_10_12_000001_add_roster_performance_indexes.php index b724cb3..5d57482 100644 --- a/database/migrations/2026_10_12_000001_add_roster_performance_indexes.php +++ b/database/migrations/2026_10_12_000001_add_roster_performance_indexes.php @@ -17,7 +17,7 @@ /** * @var array */ - private const array TABLES = ['memberships', 'role_assignments', 'invitations', 'scim_users', 'scim_groups']; + private const array TABLES = ['memberships', 'role_assignments', 'invitations']; private const array COLUMNS = ['organization_id', 'created_at', 'id']; diff --git a/database/migrations/email-index/2026_10_12_000002_add_roster_users_email_lower_index.php b/database/migrations/email-index/2026_10_12_000002_add_roster_users_email_lower_index.php index a79a5e2..9ba5288 100644 --- a/database/migrations/email-index/2026_10_12_000002_add_roster_users_email_lower_index.php +++ b/database/migrations/email-index/2026_10_12_000002_add_roster_users_email_lower_index.php @@ -11,7 +11,7 @@ /* * Optional, for PostgreSQL apps: an expression index on lower(email) for * the users table, which serves Roster's case-insensitive email lookups - * (sign-in by SSO, SCIM provisioning, invitations, imports) when an address + * (externally provisioned accounts, invitations, imports) when an address * is stored with other casing. MySQL's case-insensitive collations already * use the plain email index, so this does nothing on other databases. * Published with the `roster-email-index-migration` tag; never loaded diff --git a/lang/en/roster.php b/lang/en/roster.php index 3fa24a8..67a9dbb 100644 --- a/lang/en/roster.php +++ b/lang/en/roster.php @@ -206,53 +206,10 @@ 'impersonate_inactive' => 'Only active users can be impersonated.', 'impersonate_super' => 'Only super-admins can impersonate super-admins.', 'impersonate_escalation' => 'You cannot impersonate someone with permissions you do not have.', - 'sso' => 'Single sign-on', - 'sso_connections' => 'SSO connections', - 'sso_identities' => 'SSO identities', - 'no_sso_connections' => 'No single sign-on connections yet.', - 'new_sso_connection' => 'New SSO connection', - 'protocol' => 'Protocol', - 'protocol_oidc' => 'OpenID Connect', - 'protocol_saml' => 'SAML 2.0', - 'protocol_azure' => 'Microsoft Entra ID', - 'jit' => 'Create accounts on first sign-in', - 'enforced' => 'Require SSO for this organization\'s domains', 'enabled' => 'Enabled', - 'callback_url' => 'Callback / ACS URL', - 'metadata_url' => 'Service provider metadata', - 'test_sign_in' => 'Test sign-in', 'unlink' => 'Unlink', - 'last_login' => 'Last sign-in', - 'sso_setting_required' => 'The :setting setting is required for this protocol.', - 'sso_https_required' => 'Identity provider URLs must use HTTPS.', - 'sso_not_found' => 'No single sign-on is set up for this email domain.', - 'sso_required' => ':organization requires single sign-on. Sign in at :url', - 'sso_linked' => 'Your single sign-on identity is linked.', - 'sso_identity_taken' => 'That identity is already linked to another account.', - 'sso_failed_disabled' => 'This sign-in method is turned off.', - 'sso_failed_inactive' => 'Your account is not active.', - 'sso_failed_untrusted_email' => 'Your identity provider cannot sign in this email address. Sign in another way and link it from your account.', - 'sso_failed_no_account' => 'There is no account for this email yet. Ask for an invitation.', - 'sso_failed_invalid_response' => 'The identity provider\'s response could not be verified.', - 'sso_connection_created' => 'SSO connection created.', - 'sso_connection_updated' => 'SSO connection updated.', - 'sso_connection_deleted' => 'SSO connection deleted.', - 'sso_identity_unlinked' => 'Identity unlinked.', - 'client_secret_hint' => 'Leave blank to keep the current secret.', - 'tenant_hint' => 'Your Entra tenant ID or verified domain. Multi-tenant values (common, organizations) are not allowed.', - 'scim' => 'SCIM provisioning', - 'scim_tokens' => 'SCIM tokens', - 'scim_base_url' => 'SCIM base URL', - 'no_scim_tokens' => 'No SCIM tokens yet.', - 'new_scim_token' => 'New SCIM token', - 'scim_token_created' => 'Copy this token now. It will not be shown again.', - 'scim_token_revoked' => 'SCIM token revoked.', - 'scim_deprovisioned' => 'Deprovisioned from :organization by its identity provider.', - 'expires_in_days' => 'Expires in (days)', + 'external_sign_in_required' => ':organization requires single sign-on. Sign in at :url', 'never' => 'Never', - 'revoked' => 'Revoked', - 'link_sso' => 'Link to SSO connection', - 'unknown_sso_connection' => 'No SSO connection in this organization has this slug.', // CSV import and export 'transfers' => 'Imports & exports', @@ -307,7 +264,7 @@ 'row_error' => 'Error', 'csv_too_large' => 'The file is larger than the allowed size.', 'csv_no_header' => 'The file has no header row.', - 'csv_no_passwords' => 'Passwords cannot be imported. Remove the password column; people set their own or sign in with SSO.', + 'csv_no_passwords' => 'Passwords cannot be imported. Remove the password column; people set their own or sign in another way.', 'csv_too_many_rows' => 'The file has more than :max rows.', 'csv_missing_columns' => 'Missing required columns: :columns.', 'csv_unknown_columns' => 'Unknown columns: :columns.', @@ -364,7 +321,6 @@ 'not_pending' => 'This account is not awaiting approval.', 'approve_instead' => 'This account is awaiting approval: approve it instead.', 'account_pending' => 'Your account is awaiting approval.', - 'sso_failed_pending' => 'Your account is awaiting approval. You will be able to sign in once it is approved.', 'awaiting_approval_subject' => ':user is waiting for approval', 'awaiting_approval_line' => ':user (:email) has an account waiting for approval.', 'awaiting_approval_action' => 'Review the account', @@ -380,8 +336,8 @@ 'user_approved' => 'Account approved.', 'user_rejected' => 'Account rejected.', 'initial_status' => 'Status', - 'provisioned_status' => 'New accounts from SSO and SCIM', - 'provisioned_status_hint' => 'Whether accounts created by this organization\'s SSO or SCIM start active or wait for approval.', + 'provisioned_status' => 'New externally provisioned accounts', + 'provisioned_status_hint' => 'Whether this organization\'s externally provisioned accounts start active or wait for approval.', 'change_status_to' => 'Change status to', 'status_reason_hint' => 'Recorded with a suspension or deactivation.', 'update_status' => 'Update status', @@ -392,7 +348,7 @@ 'delete_user_confirm' => 'I understand this permanently deletes the user', 'actions' => 'Actions', 'delete_organization' => 'Delete organization', - 'delete_organization_warning' => 'Deleting this organization removes its teams, memberships, invitations, its own roles and their assignments, SSO connections, SCIM tokens and external records for good. Its members\' user accounts stay, and the audit log keeps its history.', + 'delete_organization_warning' => 'Deleting this organization removes its teams, memberships, invitations, its own roles and their assignments and external records for good. Its members\' user accounts stay, and the audit log keeps its history.', 'delete_organization_confirm' => 'I understand this permanently deletes the organization', 'not_deleted' => 'This is not deleted.', 'delete_before_purge' => 'Delete it first; only deleted records can be deleted permanently.', @@ -413,7 +369,7 @@ 'delete_user_soft_confirm' => 'I understand this user will be deleted', 'purge_user_warning' => 'Deleting this user permanently removes their account, profile, memberships, team seats, role assignments and personal organization for good. The audit log keeps its history.', 'delete_organization_soft_title' => 'Moves the organization to Deleted', - 'delete_organization_soft_warning' => 'Deleting this organization switches it off - its members lose access, and its SSO, SCIM and auto-join stop - but keeps everything (and its slug and domains) so it can be restored from Organizations → Deleted. Deleting permanently there (or the scheduled purge) removes it all for good.', + 'delete_organization_soft_warning' => 'Deleting this organization switches it off - its members lose access, and its sign-in requirements, provisioning and auto-join stop - but keeps everything (and its slug and domains) so it can be restored from Organizations → Deleted. Deleting permanently there (or the scheduled purge) removes it all for good.', 'delete_organization_soft_confirm' => 'I understand this organization will be deleted', 'redirect_domain_input_hint' => 'A host, origin or full redirect URL; only the origin is kept.', diff --git a/resources/import-templates/import_users.csv b/resources/import-templates/import_users.csv index 126c964..61669b5 100644 --- a/resources/import-templates/import_users.csv +++ b/resources/import-templates/import_users.csv @@ -1,3 +1,3 @@ email,name,display_name -"# Rows starting with # are ignored: delete them or replace them with your own. Required: email. There is no password column: people reset their password or sign in with SSO." +"# Rows starting with # are ignored: delete them or replace them with your own. Required: email. There is no password column: people reset their password or sign in another way." #ada@example.com,Ada Lovelace,Ada diff --git a/resources/views/ui/organizations/show.blade.php b/resources/views/ui/organizations/show.blade.php index 9e697ac..57dd787 100644 --- a/resources/views/ui/organizations/show.blade.php +++ b/resources/views/ui/organizations/show.blade.php @@ -203,122 +203,6 @@ @endif - @elseif ($tab === 'sso') - @if ($ssoConnections->isEmpty()) - - @else - - - - {{ __('roster::roster.name') }} - {{ __('roster::roster.protocol') }} - {{ __('roster::roster.sso_identities') }} - - - @foreach ($ssoConnections as $connection) - - - {{ $connection->name }} - @if ($connection->enforced) - {{ __('roster::roster.enforced') }} - @endif - @unless ($connection->enabled) - {{ __('roster::roster.none') }} - @endunless - - {{ __('roster::roster.protocol_'.$connection->protocol) }} - {{ $connection->identities_count }} - - @endforeach - - - @endif - - @rosterCan('roster.sso.manage', $organization) - -
- @csrf -
- - -
- @include('roster::ui.sso.partials.fields', ['settings' => [], 'editing' => false]) -
- -
-
-
- @endrosterCan - @elseif ($tab === 'scim') - @if (session('roster_scim_token')) - - {{ session('roster_scim_token') }} - - @endif - - - {{ url(trim((string) config('roster.scim.prefix', 'scim/v2'), '/').'/'.$organization->slug) }} - - - @if ($scimTokens->isEmpty()) - - @else - - - - {{ __('roster::roster.name') }} - {{ __('roster::roster.last_login') }} - {{ __('roster::roster.expires') }} - {{ __('roster::roster.actions') }} - - - @foreach ($scimTokens as $token) - - - {{ $token->name }} - @if ($token->revoked_at) - {{ __('roster::roster.revoked') }} - @endif - - {{ $token->last_used_at?->diffForHumans() ?? __('roster::roster.never') }} - {{ $token->expires_at?->toFormattedDateString() ?? __('roster::roster.never') }} - - @unless ($token->revoked_at) -
- @csrf - @method('DELETE') - - - @endunless -
-
- @endforeach -
- - @endif - - -
- @csrf - - - - - - - -
@elseif ($tab === 'roles') @if ($assignments->isEmpty()) diff --git a/resources/views/ui/sso/partials/fields.blade.php b/resources/views/ui/sso/partials/fields.blade.php deleted file mode 100644 index e42d41d..0000000 --- a/resources/views/ui/sso/partials/fields.blade.php +++ /dev/null @@ -1,48 +0,0 @@ -{{-- - Protocol settings. With a fixed $protocol (editing) only its fields - render; without one (creating) every field renders and Alpine shows the - ones for the protocol picked in the form's `protocol` select. The Action - checks the right ones are present either way. ---}} -@php - $fields = [ - 'issuer' => ['protocols' => ['oidc'], 'label' => 'Issuer', 'hint' => null], - 'tenant' => ['protocols' => ['azure'], 'label' => 'Tenant', 'hint' => __('roster::roster.tenant_hint')], - 'client_id' => ['protocols' => ['oidc', 'azure'], 'label' => 'Client ID', 'hint' => null], - 'client_secret' => ['protocols' => ['oidc', 'azure'], 'label' => 'Client secret', 'hint' => $editing ? __('roster::roster.client_secret_hint') : null], - 'metadata_url' => ['protocols' => ['saml'], 'label' => 'Metadata URL', 'hint' => null], - 'entity_id' => ['protocols' => ['saml'], 'label' => 'Entity ID', 'hint' => null], - 'sso_url' => ['protocols' => ['saml'], 'label' => 'SSO URL', 'hint' => null], - 'certificate' => ['protocols' => ['saml'], 'label' => 'Certificate', 'hint' => null], - ]; - $protocol ??= null; -@endphp - -
- @foreach ($fields as $name => $field) - @continue($protocol !== null && ! in_array($protocol, $field['protocols'], true)) - -
$name === 'certificate'])> - @if ($name === 'certificate') - - @else - - @endif -
- @endforeach -
-
- - - -
diff --git a/resources/views/ui/sso/show.blade.php b/resources/views/ui/sso/show.blade.php deleted file mode 100644 index 927fd47..0000000 --- a/resources/views/ui/sso/show.blade.php +++ /dev/null @@ -1,47 +0,0 @@ -@php($resource = (new \RefactorCircus\Roster\Domains\Sso\Resources\SsoConnectionResource($connection))->resolve()) - - - - - - - - -
- @include('roster::impersonation-banner', ['bannerClass' => 'rounded-radius']) - - - - - {{ $resource['callback_url'] ?? __('roster::roster.none') }} - @if ($resource['metadata_url']) - {{ $resource['metadata_url'] }} - @endif - {{ $connection->identities_count }} - - @if ($resource['sign_in_url']) - - @endif - - - @rosterCan('roster.sso.manage', $connection->organization) - -
- @csrf - @method('PATCH') - - @include('roster::ui.sso.partials.fields', ['settings' => (array) $resource['settings'], 'editing' => true, 'protocol' => $connection->protocol, 'jit' => $connection->jit, 'enforced' => $connection->enforced, 'enabled' => $connection->enabled]) -
- -
- -
- -
- @csrf - @method('DELETE') - - - @endrosterCan -
-
diff --git a/resources/views/ui/users/partials/overview.blade.php b/resources/views/ui/users/partials/overview.blade.php index 06cc8f0..f6905b0 100644 --- a/resources/views/ui/users/partials/overview.blade.php +++ b/resources/views/ui/users/partials/overview.blade.php @@ -218,25 +218,6 @@
@endrosterCan - @if ($ssoIdentities->isNotEmpty()) - -
    - @foreach ($ssoIdentities as $identity) -
  • - {{ $identity->connection?->name }} — {{ $identity->email ?? $identity->subject }} {{ __('roster::roster.last_login') }}: {{ $identity->last_login_at?->diffForHumans() ?? __('roster::roster.none') }} - @rosterCan('roster.sso.manage', $identity->connection?->organization, $identity->user_id == auth()->id() ? auth()->user() : null) -
    - @csrf - @method('DELETE') - - - @endrosterCan -
  • - @endforeach -
-
- @endif - @rosterCan('roster.users.delete') @if ($directory->softDeletes()) diff --git a/resources/views/ui/users/show.blade.php b/resources/views/ui/users/show.blade.php index 1e0f888..90e658a 100644 --- a/resources/views/ui/users/show.blade.php +++ b/resources/views/ui/users/show.blade.php @@ -39,7 +39,6 @@ 'assignments' => $assignments, 'effective' => $effective, 'assignableRoles' => $assignableRoles, - 'ssoIdentities' => $ssoIdentities, ]) @if ($aside) diff --git a/src/Atrium/Http/Controllers/OrganizationUiController.php b/src/Atrium/Http/Controllers/OrganizationUiController.php index bb0ebd6..65ed6ad 100644 --- a/src/Atrium/Http/Controllers/OrganizationUiController.php +++ b/src/Atrium/Http/Controllers/OrganizationUiController.php @@ -39,10 +39,6 @@ use RefactorCircus\Roster\Domains\Role\Actions\ListRolesAction; use RefactorCircus\Roster\Domains\Role\Data\ListRoleAssignmentsData; use RefactorCircus\Roster\Domains\Role\Data\ListRolesData; -use RefactorCircus\Roster\Domains\Scim\Actions\ListScimTokensAction; -use RefactorCircus\Roster\Domains\Scim\Data\ListScimTokensData; -use RefactorCircus\Roster\Domains\Sso\Actions\ListSsoConnectionsAction; -use RefactorCircus\Roster\Domains\Sso\Data\ListSsoConnectionsData; use RefactorCircus\Roster\Domains\Team\Actions\ListTeamsAction; use RefactorCircus\Roster\Domains\Team\Data\ListTeamsData; use RefactorCircus\Roster\Support\Users; @@ -66,8 +62,6 @@ final class OrganizationUiController 'teams' => 'roster.teams.view', 'invitations' => 'roster.invitations.view', 'roles' => 'roster.roles.view', - 'sso' => 'roster.sso.view', - 'scim' => 'roster.scim.manage', 'settings' => 'roster.organizations.view', ]; @@ -79,8 +73,6 @@ final class OrganizationUiController 'teams' => 'user-group', 'invitations' => 'envelope', 'roles' => 'shield-check', - 'sso' => 'arrow-right-end-on-rectangle', - 'scim' => 'server-stack', 'settings' => 'cog', ]; @@ -192,11 +184,6 @@ public function show(Request $request, string $organization): View 'roles' => app(ListRolesAction::class)->execute(new ListRolesData(organization: $model, perPage: 100)), 'assignments' => app(ListRoleAssignmentsAction::class)->execute(new ListRoleAssignmentsData(organization: $model, perPage: 25, page: $page))->withQueryString(), ], - 'sso' => ['ssoConnections' => app(ListSsoConnectionsAction::class)->execute(new ListSsoConnectionsData(organization: $model, perPage: 25, page: $page))->withQueryString()], - 'scim' => [ - 'scimTokens' => app(ListScimTokensAction::class)->execute($model, new ListScimTokensData(perPage: 25, page: $page))->withQueryString(), - 'ssoConnections' => app(ListSsoConnectionsAction::class)->execute(new ListSsoConnectionsData(organization: $model, perPage: 100)), - ], default => [], }, ]); diff --git a/src/Atrium/Http/Controllers/ScimUiController.php b/src/Atrium/Http/Controllers/ScimUiController.php deleted file mode 100644 index 8914bc7..0000000 --- a/src/Atrium/Http/Controllers/ScimUiController.php +++ /dev/null @@ -1,50 +0,0 @@ -organization($organization); - $this->authorizeScreen('roster.scim.manage', $model); - $issued = app(CreateScimTokenAction::class)->execute( - $model, - CreateScimTokenData::from($request->all()), - $this->actor($request), - ); - - // Flashed for exactly one page view, then gone. - return redirect() - ->route('atrium.roster.organizations.show', [$model, 'tab' => 'scim']) - ->with('roster_scim_token', $issued->plain) - ->with('status', __('roster::roster.scim_token_created')); - } - - public function revoke(string $token): RedirectResponse - { - $model = ScimTokenModel::query()->whereKey($token)->firstOrFail(); - $this->authorizeScreen('roster.scim.manage', $model->organization); - - app(RevokeScimTokenAction::class)->execute($model); - - return redirect() - ->route('atrium.roster.organizations.show', [$model->organization, 'tab' => 'scim']) - ->with('status', __('roster::roster.scim_token_revoked')); - } -} diff --git a/src/Atrium/Http/Controllers/SsoUiController.php b/src/Atrium/Http/Controllers/SsoUiController.php deleted file mode 100644 index 0125195..0000000 --- a/src/Atrium/Http/Controllers/SsoUiController.php +++ /dev/null @@ -1,109 +0,0 @@ -organization($organization); - $this->authorizeScreen('roster.sso.manage', $model); - $this->booleans($request); - - $connection = app(CreateSsoConnectionAction::class)->execute($model, CreateSsoConnectionData::from($request->all())); - - return redirect() - ->route('atrium.roster.sso.show', $connection->slug) - ->with('status', __('roster::roster.sso_connection_created')); - } - - public function show(string $connection): View - { - $model = $this->find($connection); - $this->authorizeScreen('roster.sso.view', $model->organization); - - /** @var view-string $view */ - $view = 'roster::ui.sso.show'; - - return view($view, ['connection' => app(ShowSsoConnectionAction::class)->execute($model)]); - } - - public function update(Request $request, string $connection): RedirectResponse - { - $model = $this->find($connection); - $this->authorizeScreen('roster.sso.manage', $model->organization); - $this->booleans($request); - - $model = app(UpdateSsoConnectionAction::class)->execute($model, UpdateSsoConnectionData::from($request->all(), $model)); - - return redirect() - ->route('atrium.roster.sso.show', $model->slug) - ->with('status', __('roster::roster.sso_connection_updated')); - } - - public function destroy(string $connection): RedirectResponse - { - $model = $this->find($connection); - $this->authorizeScreen('roster.sso.manage', $model->organization); - $organization = $model->organization; - - app(DeleteSsoConnectionAction::class)->execute($model); - - return redirect() - ->route('atrium.roster.organizations.show', [$organization, 'tab' => 'sso']) - ->with('status', __('roster::roster.sso_connection_deleted')); - } - - public function unlink(Request $request, string $identity): RedirectResponse - { - $model = SsoIdentityModel::query()->whereKey($identity)->firstOrFail(); - $actor = $request->user(); - $actor = $actor instanceof Model ? $actor : null; - $this->authorizeScreen('roster.sso.manage', $model->connection?->organization, $model->ownedBy($actor) ? $actor : null); - - $user = $model->user; - - app(UnlinkSsoIdentityAction::class)->execute($model); - - return redirect() - ->route('atrium.roster.users.show', $user instanceof Model ? $user->getRouteKey() : 0) - ->with('status', __('roster::roster.sso_identity_unlinked')); - } - - private function find(string $slug): SsoConnectionModel - { - return SsoConnectionModel::query()->where('slug', $slug)->firstOrFail(); - } - - /** - * Unchecked boxes send nothing; treat them as false. - */ - private function booleans(Request $request): void - { - foreach (['jit', 'enforced', 'enabled'] as $field) { - $request->merge([$field => $request->boolean($field)]); - } - } -} diff --git a/src/Atrium/Http/Controllers/UserUiController.php b/src/Atrium/Http/Controllers/UserUiController.php index 5573988..38433b4 100644 --- a/src/Atrium/Http/Controllers/UserUiController.php +++ b/src/Atrium/Http/Controllers/UserUiController.php @@ -21,8 +21,6 @@ use RefactorCircus\Roster\Domains\Role\Actions\ListRoleAssignmentsAction; use RefactorCircus\Roster\Domains\Role\Data\ListRoleAssignmentsData; use RefactorCircus\Roster\Domains\Role\Models\RoleModel; -use RefactorCircus\Roster\Domains\Sso\Actions\ListSsoIdentitiesAction; -use RefactorCircus\Roster\Domains\Sso\Data\ListSsoIdentitiesData; use RefactorCircus\Roster\Domains\User\Actions\ApproveUserAction; use RefactorCircus\Roster\Domains\User\Actions\CreateUserAction; use RefactorCircus\Roster\Domains\User\Actions\DeactivateUserAction; @@ -314,7 +312,6 @@ private function overview(Model $model): array ->orderBy('scope') ->orderBy('name') ->get(), - 'ssoIdentities' => app(ListSsoIdentitiesAction::class)->execute(new ListSsoIdentitiesData(user: $model, perPage: 50)), ]; } diff --git a/src/Atrium/RosterPlugin.php b/src/Atrium/RosterPlugin.php index 75b6c13..c70bab1 100644 --- a/src/Atrium/RosterPlugin.php +++ b/src/Atrium/RosterPlugin.php @@ -22,8 +22,6 @@ use RefactorCircus\Roster\Atrium\Http\Controllers\OrganizationUiController; use RefactorCircus\Roster\Atrium\Http\Controllers\PermissionUiController; use RefactorCircus\Roster\Atrium\Http\Controllers\RoleUiController; -use RefactorCircus\Roster\Atrium\Http\Controllers\ScimUiController; -use RefactorCircus\Roster\Atrium\Http\Controllers\SsoUiController; use RefactorCircus\Roster\Atrium\Http\Controllers\TeamUiController; use RefactorCircus\Roster\Atrium\Http\Controllers\TransferUiController; use RefactorCircus\Roster\Atrium\Http\Controllers\UserUiController; @@ -189,15 +187,6 @@ public function routes(): void Route::patch('roster/permissions/{permission}', [PermissionUiController::class, 'update'])->name('permissions.update'); Route::delete('roster/permissions/{permission}', [PermissionUiController::class, 'destroy'])->name('permissions.destroy'); - Route::post('roster/organizations/{organization}/sso', [SsoUiController::class, 'store'])->name('sso.store'); - Route::get('roster/sso/{connection}', [SsoUiController::class, 'show'])->name('sso.show'); - Route::patch('roster/sso/{connection}', [SsoUiController::class, 'update'])->name('sso.update'); - Route::delete('roster/sso/{connection}', [SsoUiController::class, 'destroy'])->name('sso.destroy'); - Route::delete('roster/sso-identities/{identity}', [SsoUiController::class, 'unlink'])->name('sso-identities.destroy'); - - Route::post('roster/organizations/{organization}/scim-tokens', [ScimUiController::class, 'store'])->name('scim-tokens.store'); - Route::delete('roster/scim-tokens/{token}', [ScimUiController::class, 'revoke'])->name('scim-tokens.revoke'); - Route::post('roster/users/{user}/impersonate', [ImpersonationUiController::class, 'start'])->name('users.impersonate'); Route::get('roster/impersonations', [ImpersonationUiController::class, 'index'])->name('impersonations.index'); Route::delete('roster/impersonations/{impersonation}', [ImpersonationUiController::class, 'stop'])->name('impersonations.stop'); diff --git a/src/Data/ExternalSignIn.php b/src/Data/ExternalSignIn.php index 516aff7..d97da9b 100644 --- a/src/Data/ExternalSignIn.php +++ b/src/Data/ExternalSignIn.php @@ -10,7 +10,8 @@ * The sign-in an email must use instead of a password, as a * `SignInRequirement` answers it: a stable `key` for the sign-in, the `label` * people see (who requires it), the `url` where the sign-in starts, and the - * record behind it, if any (the SSO connection, for Roster's own). + * record behind it, if any (whatever the registered sign-in requirement + * keeps for it). */ final readonly class ExternalSignIn { diff --git a/src/Domains/DomainServiceProvider.php b/src/Domains/DomainServiceProvider.php index ef7ba14..575839a 100644 --- a/src/Domains/DomainServiceProvider.php +++ b/src/Domains/DomainServiceProvider.php @@ -10,8 +10,6 @@ use RefactorCircus\Roster\Domains\Organization\OrganizationServiceProvider; use RefactorCircus\Roster\Domains\Permission\PermissionServiceProvider; use RefactorCircus\Roster\Domains\Role\RoleServiceProvider; -use RefactorCircus\Roster\Domains\Scim\ScimServiceProvider; -use RefactorCircus\Roster\Domains\Sso\SsoServiceProvider; use RefactorCircus\Roster\Domains\Team\TeamServiceProvider; use RefactorCircus\Roster\Domains\Transfer\TransferServiceProvider; use RefactorCircus\Roster\Domains\User\UserServiceProvider; @@ -31,8 +29,6 @@ class DomainServiceProvider extends ServiceProvider RoleServiceProvider::class, PermissionServiceProvider::class, ImpersonationServiceProvider::class, - SsoServiceProvider::class, - ScimServiceProvider::class, TransferServiceProvider::class, ]; diff --git a/src/Domains/Organization/Actions/PurgeOrganizationAction.php b/src/Domains/Organization/Actions/PurgeOrganizationAction.php index 1460842..b93e50e 100644 --- a/src/Domains/Organization/Actions/PurgeOrganizationAction.php +++ b/src/Domains/Organization/Actions/PurgeOrganizationAction.php @@ -16,7 +16,7 @@ final class PurgeOrganizationAction { /** * Delete an organization for good, with its teams, memberships, - * invitations, roles, SSO connections, SCIM tokens and links. It must be + * invitations, roles and links. It must be * deleted (trashed) first; `$personal` is for purging a user's personal * organization along with them. */ diff --git a/src/Domains/Organization/Concerns/OrganizationRules.php b/src/Domains/Organization/Concerns/OrganizationRules.php index 829f90d..bbce3c9 100644 --- a/src/Domains/Organization/Concerns/OrganizationRules.php +++ b/src/Domains/Organization/Concerns/OrganizationRules.php @@ -29,7 +29,7 @@ protected static function settingsRules(?OrganizationModel $organization = null) return [ 'auto_join' => ['sometimes', 'boolean'], - // Accounts created through its SSO or SCIM: active, or waiting for approval. + // Its externally provisioned accounts: active, or waiting for approval. 'provisioned_status' => ['sometimes', Rule::in([Statuses::users()::active()->value, Statuses::users()::pending()->value])], 'status' => ['sometimes', Rule::enum(Statuses::organizations())], 'status_reason' => ['sometimes', 'nullable', 'string', 'max:1000'], diff --git a/src/Domains/Organization/Data/CreateOrganizationData.php b/src/Domains/Organization/Data/CreateOrganizationData.php index e8fe89a..2cc7da8 100644 --- a/src/Domains/Organization/Data/CreateOrganizationData.php +++ b/src/Domains/Organization/Data/CreateOrganizationData.php @@ -18,8 +18,8 @@ * Input for CreateOrganizationAction: the organization and its settings. * * Without a slug one is made from the name. `owner` is the owning user's - * route key. `provisioned_status` is the status of accounts created through - * its SSO or SCIM: active (the default), or waiting for approval. `status` + * route key. `provisioned_status` is the status its externally provisioned + * accounts start with: active (the default), or waiting for approval. `status` * is the organization's own, from `roster.statuses.organizations`; without * one it starts with the enum's default. */ diff --git a/src/Domains/Organization/Mcp/Tools/PurgeOrganizationTool.php b/src/Domains/Organization/Mcp/Tools/PurgeOrganizationTool.php index 6c4ca09..d8f2889 100644 --- a/src/Domains/Organization/Mcp/Tools/PurgeOrganizationTool.php +++ b/src/Domains/Organization/Mcp/Tools/PurgeOrganizationTool.php @@ -12,7 +12,7 @@ use RefactorCircus\Roster\Domains\Organization\Mcp\Requests\PurgeOrganizationMcpRequest; use RefactorCircus\Roster\Mcp\Concerns\DescribesOrganization; -#[Description('Permanently delete a deleted organization with its teams, memberships, invitations, roles, SSO connections and SCIM tokens. Cannot be undone. It must be deleted (delete-organization-tool) first.')] +#[Description('Permanently delete a deleted organization with its teams, memberships, invitations, roles and links. Cannot be undone. It must be deleted (delete-organization-tool) first.')] final class PurgeOrganizationTool extends Tool { use DescribesOrganization; diff --git a/src/Domains/Permission/PermissionServiceProvider.php b/src/Domains/Permission/PermissionServiceProvider.php index f553a53..147ed2b 100644 --- a/src/Domains/Permission/PermissionServiceProvider.php +++ b/src/Domains/Permission/PermissionServiceProvider.php @@ -122,7 +122,7 @@ private function registerGate(): void // request; anything that changes them (assigning a role, switching // context, joining) clears that, so later checks see the change. Only // Roster's domains that hold roles, memberships and context count: - // other packages' actions, SSO, SCIM tokens, transfers and reads leave + // other packages' actions, transfers and reads leave // the caches alone, so bulk work does not rebuild them every row. A // change confined to one user forgets only that user; the permission // names are forgotten only when a permission itself changes. diff --git a/src/Domains/Scim/Actions/CreateScimTokenAction.php b/src/Domains/Scim/Actions/CreateScimTokenAction.php deleted file mode 100644 index df6ccea..0000000 --- a/src/Domains/Scim/Actions/CreateScimTokenAction.php +++ /dev/null @@ -1,56 +0,0 @@ -ssoConnection !== null && $data->ssoConnection !== '') { - $connection = SsoConnectionModel::query() - ->where('organization_id', $organization->getKey()) - ->where('slug', $data->ssoConnection) - ->first() ?? throw ValidationException::withMessages(['sso_connection' => __('roster::roster.unknown_sso_connection')]); - } - - ScimTokenCreatingActionEvent::dispatch($organization, $data); - - $plain = 'scim_'.Str::random(48); - - $token = DB::transaction(fn (): ScimTokenModel => ScimTokenModel::query()->create([ - 'organization_id' => $organization->getKey(), - 'name' => $data->name, - 'token_hash' => hash('sha256', $plain), - 'sso_connection_id' => $connection?->getKey(), - 'created_by' => $actor?->getKey(), - 'expires_at' => $data->expiresInDays !== null ? now()->addDays($data->expiresInDays) : null, - ])); - - $token->load(['organization', 'ssoConnection']); - - ScimTokenCreatedActionEvent::dispatch($token); - - return new IssuedScimToken($token, $plain); - } -} diff --git a/src/Domains/Scim/Actions/ListScimTokensAction.php b/src/Domains/Scim/Actions/ListScimTokensAction.php deleted file mode 100644 index e648e14..0000000 --- a/src/Domains/Scim/Actions/ListScimTokensAction.php +++ /dev/null @@ -1,34 +0,0 @@ - - */ - public function execute(OrganizationModel $organization, ListScimTokensData $filters = new ListScimTokensData): LengthAwarePaginator - { - ScimTokensListingActionEvent::dispatch($organization, $filters); - - $tokens = ScimTokenModel::query() - ->where('organization_id', $organization->getKey()) - ->with(['organization', 'ssoConnection']) - ->latest() - ->latest('id') - ->paginate($filters->perPage, ['*'], 'page', $filters->page); - - ScimTokensListedActionEvent::dispatch($organization, $filters); - - return $tokens; - } -} diff --git a/src/Domains/Scim/Actions/RevokeScimTokenAction.php b/src/Domains/Scim/Actions/RevokeScimTokenAction.php deleted file mode 100644 index f071186..0000000 --- a/src/Domains/Scim/Actions/RevokeScimTokenAction.php +++ /dev/null @@ -1,31 +0,0 @@ -revoked_at !== null) { - return $token; - } - - ScimTokenRevokingActionEvent::dispatch($token); - - DB::transaction(fn () => $token->update(['revoked_at' => now()])); - - ScimTokenRevokedActionEvent::dispatch($token); - - return $token->load(['organization', 'ssoConnection']); - } -} diff --git a/src/Domains/Scim/Data/CreateScimTokenData.php b/src/Domains/Scim/Data/CreateScimTokenData.php deleted file mode 100644 index 00cfaca..0000000 --- a/src/Domains/Scim/Data/CreateScimTokenData.php +++ /dev/null @@ -1,33 +0,0 @@ -> - */ - public static function rules(): array - { - return [ - 'name' => ['required', 'string', 'max:255'], - 'expires_in_days' => ['sometimes', 'nullable', 'integer', 'min:1', 'max:3650'], - 'sso_connection' => ['sometimes', 'nullable', 'string'], - ]; - } -} diff --git a/src/Domains/Scim/Data/IssuedScimToken.php b/src/Domains/Scim/Data/IssuedScimToken.php deleted file mode 100644 index 71c0252..0000000 --- a/src/Domains/Scim/Data/IssuedScimToken.php +++ /dev/null @@ -1,20 +0,0 @@ -> - */ - public static function rules(): array - { - return [ - ] + self::pagination()->rules(); - } -} diff --git a/src/Domains/Scim/Events/ScimGroupCreatedEvent.php b/src/Domains/Scim/Events/ScimGroupCreatedEvent.php deleted file mode 100644 index 464ae2e..0000000 --- a/src/Domains/Scim/Events/ScimGroupCreatedEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimGroup; - } - - public function hook(): string - { - return 'created'; - } -} diff --git a/src/Domains/Scim/Events/ScimGroupCreatingEvent.php b/src/Domains/Scim/Events/ScimGroupCreatingEvent.php deleted file mode 100644 index aded88c..0000000 --- a/src/Domains/Scim/Events/ScimGroupCreatingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimGroup; - } - - public function hook(): string - { - return 'creating'; - } -} diff --git a/src/Domains/Scim/Events/ScimGroupDeletedEvent.php b/src/Domains/Scim/Events/ScimGroupDeletedEvent.php deleted file mode 100644 index e25b61a..0000000 --- a/src/Domains/Scim/Events/ScimGroupDeletedEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimGroup; - } - - public function hook(): string - { - return 'deleted'; - } -} diff --git a/src/Domains/Scim/Events/ScimGroupDeletingEvent.php b/src/Domains/Scim/Events/ScimGroupDeletingEvent.php deleted file mode 100644 index 52b0eb3..0000000 --- a/src/Domains/Scim/Events/ScimGroupDeletingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimGroup; - } - - public function hook(): string - { - return 'deleting'; - } -} diff --git a/src/Domains/Scim/Events/ScimGroupReplicatingEvent.php b/src/Domains/Scim/Events/ScimGroupReplicatingEvent.php deleted file mode 100644 index 47398f7..0000000 --- a/src/Domains/Scim/Events/ScimGroupReplicatingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimGroup; - } - - public function hook(): string - { - return 'replicating'; - } -} diff --git a/src/Domains/Scim/Events/ScimGroupRetrievedEvent.php b/src/Domains/Scim/Events/ScimGroupRetrievedEvent.php deleted file mode 100644 index 543f383..0000000 --- a/src/Domains/Scim/Events/ScimGroupRetrievedEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimGroup; - } - - public function hook(): string - { - return 'retrieved'; - } -} diff --git a/src/Domains/Scim/Events/ScimGroupSavedEvent.php b/src/Domains/Scim/Events/ScimGroupSavedEvent.php deleted file mode 100644 index 290ba00..0000000 --- a/src/Domains/Scim/Events/ScimGroupSavedEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimGroup; - } - - public function hook(): string - { - return 'saved'; - } -} diff --git a/src/Domains/Scim/Events/ScimGroupSavingEvent.php b/src/Domains/Scim/Events/ScimGroupSavingEvent.php deleted file mode 100644 index df49bab..0000000 --- a/src/Domains/Scim/Events/ScimGroupSavingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimGroup; - } - - public function hook(): string - { - return 'saving'; - } -} diff --git a/src/Domains/Scim/Events/ScimGroupUpdatedEvent.php b/src/Domains/Scim/Events/ScimGroupUpdatedEvent.php deleted file mode 100644 index 91fad5d..0000000 --- a/src/Domains/Scim/Events/ScimGroupUpdatedEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimGroup; - } - - public function hook(): string - { - return 'updated'; - } -} diff --git a/src/Domains/Scim/Events/ScimGroupUpdatingEvent.php b/src/Domains/Scim/Events/ScimGroupUpdatingEvent.php deleted file mode 100644 index 3ca750a..0000000 --- a/src/Domains/Scim/Events/ScimGroupUpdatingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimGroup; - } - - public function hook(): string - { - return 'updating'; - } -} diff --git a/src/Domains/Scim/Events/ScimTokenCreatedActionEvent.php b/src/Domains/Scim/Events/ScimTokenCreatedActionEvent.php deleted file mode 100644 index 065f583..0000000 --- a/src/Domains/Scim/Events/ScimTokenCreatedActionEvent.php +++ /dev/null @@ -1,23 +0,0 @@ -scimToken; - } - - public function hook(): string - { - return 'created'; - } -} diff --git a/src/Domains/Scim/Events/ScimTokenCreatingActionEvent.php b/src/Domains/Scim/Events/ScimTokenCreatingActionEvent.php deleted file mode 100644 index d90bd63..0000000 --- a/src/Domains/Scim/Events/ScimTokenCreatingActionEvent.php +++ /dev/null @@ -1,25 +0,0 @@ -scimToken; - } - - public function hook(): string - { - return 'creating'; - } -} diff --git a/src/Domains/Scim/Events/ScimTokenDeletedEvent.php b/src/Domains/Scim/Events/ScimTokenDeletedEvent.php deleted file mode 100644 index 4bf5136..0000000 --- a/src/Domains/Scim/Events/ScimTokenDeletedEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimToken; - } - - public function hook(): string - { - return 'deleted'; - } -} diff --git a/src/Domains/Scim/Events/ScimTokenDeletingEvent.php b/src/Domains/Scim/Events/ScimTokenDeletingEvent.php deleted file mode 100644 index 96568e9..0000000 --- a/src/Domains/Scim/Events/ScimTokenDeletingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimToken; - } - - public function hook(): string - { - return 'deleting'; - } -} diff --git a/src/Domains/Scim/Events/ScimTokenReplicatingEvent.php b/src/Domains/Scim/Events/ScimTokenReplicatingEvent.php deleted file mode 100644 index f8e01cb..0000000 --- a/src/Domains/Scim/Events/ScimTokenReplicatingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimToken; - } - - public function hook(): string - { - return 'replicating'; - } -} diff --git a/src/Domains/Scim/Events/ScimTokenRetrievedEvent.php b/src/Domains/Scim/Events/ScimTokenRetrievedEvent.php deleted file mode 100644 index b4f62df..0000000 --- a/src/Domains/Scim/Events/ScimTokenRetrievedEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimToken; - } - - public function hook(): string - { - return 'retrieved'; - } -} diff --git a/src/Domains/Scim/Events/ScimTokenRevokedActionEvent.php b/src/Domains/Scim/Events/ScimTokenRevokedActionEvent.php deleted file mode 100644 index 767a6cb..0000000 --- a/src/Domains/Scim/Events/ScimTokenRevokedActionEvent.php +++ /dev/null @@ -1,23 +0,0 @@ -scimToken; - } - - public function hook(): string - { - return 'saved'; - } -} diff --git a/src/Domains/Scim/Events/ScimTokenSavingEvent.php b/src/Domains/Scim/Events/ScimTokenSavingEvent.php deleted file mode 100644 index 9f53e19..0000000 --- a/src/Domains/Scim/Events/ScimTokenSavingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimToken; - } - - public function hook(): string - { - return 'saving'; - } -} diff --git a/src/Domains/Scim/Events/ScimTokenUpdatedEvent.php b/src/Domains/Scim/Events/ScimTokenUpdatedEvent.php deleted file mode 100644 index b6ff0ad..0000000 --- a/src/Domains/Scim/Events/ScimTokenUpdatedEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimToken; - } - - public function hook(): string - { - return 'updated'; - } -} diff --git a/src/Domains/Scim/Events/ScimTokenUpdatingEvent.php b/src/Domains/Scim/Events/ScimTokenUpdatingEvent.php deleted file mode 100644 index 0ce95be..0000000 --- a/src/Domains/Scim/Events/ScimTokenUpdatingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimToken; - } - - public function hook(): string - { - return 'updating'; - } -} diff --git a/src/Domains/Scim/Events/ScimTokensListedActionEvent.php b/src/Domains/Scim/Events/ScimTokensListedActionEvent.php deleted file mode 100644 index 7288d65..0000000 --- a/src/Domains/Scim/Events/ScimTokensListedActionEvent.php +++ /dev/null @@ -1,25 +0,0 @@ -scimUser; - } - - public function hook(): string - { - return 'created'; - } -} diff --git a/src/Domains/Scim/Events/ScimUserCreatingEvent.php b/src/Domains/Scim/Events/ScimUserCreatingEvent.php deleted file mode 100644 index f3f3571..0000000 --- a/src/Domains/Scim/Events/ScimUserCreatingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimUser; - } - - public function hook(): string - { - return 'creating'; - } -} diff --git a/src/Domains/Scim/Events/ScimUserDeletedEvent.php b/src/Domains/Scim/Events/ScimUserDeletedEvent.php deleted file mode 100644 index b9c1b4b..0000000 --- a/src/Domains/Scim/Events/ScimUserDeletedEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimUser; - } - - public function hook(): string - { - return 'deleted'; - } -} diff --git a/src/Domains/Scim/Events/ScimUserDeletingEvent.php b/src/Domains/Scim/Events/ScimUserDeletingEvent.php deleted file mode 100644 index 565c2d0..0000000 --- a/src/Domains/Scim/Events/ScimUserDeletingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimUser; - } - - public function hook(): string - { - return 'deleting'; - } -} diff --git a/src/Domains/Scim/Events/ScimUserReplicatingEvent.php b/src/Domains/Scim/Events/ScimUserReplicatingEvent.php deleted file mode 100644 index f4ca4d0..0000000 --- a/src/Domains/Scim/Events/ScimUserReplicatingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimUser; - } - - public function hook(): string - { - return 'replicating'; - } -} diff --git a/src/Domains/Scim/Events/ScimUserRetrievedEvent.php b/src/Domains/Scim/Events/ScimUserRetrievedEvent.php deleted file mode 100644 index dc561be..0000000 --- a/src/Domains/Scim/Events/ScimUserRetrievedEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimUser; - } - - public function hook(): string - { - return 'retrieved'; - } -} diff --git a/src/Domains/Scim/Events/ScimUserSavedEvent.php b/src/Domains/Scim/Events/ScimUserSavedEvent.php deleted file mode 100644 index d4f0104..0000000 --- a/src/Domains/Scim/Events/ScimUserSavedEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimUser; - } - - public function hook(): string - { - return 'saved'; - } -} diff --git a/src/Domains/Scim/Events/ScimUserSavingEvent.php b/src/Domains/Scim/Events/ScimUserSavingEvent.php deleted file mode 100644 index df4bcda..0000000 --- a/src/Domains/Scim/Events/ScimUserSavingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimUser; - } - - public function hook(): string - { - return 'saving'; - } -} diff --git a/src/Domains/Scim/Events/ScimUserUpdatedEvent.php b/src/Domains/Scim/Events/ScimUserUpdatedEvent.php deleted file mode 100644 index 5fec1d1..0000000 --- a/src/Domains/Scim/Events/ScimUserUpdatedEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimUser; - } - - public function hook(): string - { - return 'updated'; - } -} diff --git a/src/Domains/Scim/Events/ScimUserUpdatingEvent.php b/src/Domains/Scim/Events/ScimUserUpdatingEvent.php deleted file mode 100644 index b55b9e7..0000000 --- a/src/Domains/Scim/Events/ScimUserUpdatingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -scimUser; - } - - public function hook(): string - { - return 'updating'; - } -} diff --git a/src/Domains/Scim/Exceptions/ScimException.php b/src/Domains/Scim/Exceptions/ScimException.php deleted file mode 100644 index 4e1c1d8..0000000 --- a/src/Domains/Scim/Exceptions/ScimException.php +++ /dev/null @@ -1,68 +0,0 @@ - [Scim::ERROR], - 'status' => (string) $this->status, - 'scimType' => $this->scimType, - 'detail' => $this->getMessage(), - ], fn (mixed $value): bool => $value !== null), $this->status); - } -} diff --git a/src/Domains/Scim/Http/Controllers/ScimController.php b/src/Domains/Scim/Http/Controllers/ScimController.php deleted file mode 100644 index ded5070..0000000 --- a/src/Domains/Scim/Http/Controllers/ScimController.php +++ /dev/null @@ -1,234 +0,0 @@ -paging($request); - [$page, $total] = $this->users->list($this->filter($request), $startIndex, $count); - - return Scim::response($this->mapper->list(array_map(fn (ScimUserModel $user): array => $this->mapper->user($user), $page), $total, $startIndex)); - } - - public function showUser(Request $request, string $organization, string $id): BaseResponse - { - return $this->present($request, $this->mapper->user($this->users->find($id))); - } - - public function createUser(Request $request): JsonResponse - { - $resource = $this->mapper->user($this->users->create($this->body($request))); - - return $this->respond($resource, 201); - } - - public function replaceUser(Request $request, string $organization, string $id): JsonResponse - { - $user = $this->users->find($id); - $this->checkVersion($request, fn (): array => $this->mapper->user($user)); - - return $this->respond($this->mapper->user($this->users->replace($user, $this->body($request)))); - } - - public function patchUser(Request $request, string $organization, string $id): JsonResponse - { - $user = $this->users->find($id); - $this->checkVersion($request, fn (): array => $this->mapper->user($user)); - - return $this->respond($this->mapper->user($this->users->patch($user, $this->operations($request)))); - } - - public function deleteUser(Request $request, string $organization, string $id): Response - { - $user = $this->users->find($id); - $this->checkVersion($request, fn (): array => $this->mapper->user($user)); - $this->users->delete($user); - - return response()->noContent(); - } - - public function listGroups(Request $request): JsonResponse - { - [$startIndex, $count] = $this->paging($request); - [$page, $total] = $this->groups->list($this->filter($request), $startIndex, $count); - - return Scim::response($this->mapper->list(array_map(fn (ScimGroupModel $group): array => $this->mapper->group($group), $page), $total, $startIndex)); - } - - public function showGroup(Request $request, string $organization, string $id): BaseResponse - { - return $this->present($request, $this->mapper->group($this->groups->find($id))); - } - - public function createGroup(Request $request): JsonResponse - { - return $this->respond($this->mapper->group($this->groups->create($this->body($request))), 201); - } - - public function replaceGroup(Request $request, string $organization, string $id): JsonResponse - { - $group = $this->groups->find($id); - $this->checkVersion($request, fn (): array => $this->mapper->group($group)); - - return $this->respond($this->mapper->group($this->groups->replace($group, $this->body($request)))); - } - - public function patchGroup(Request $request, string $organization, string $id): JsonResponse - { - $group = $this->groups->find($id); - $this->checkVersion($request, fn (): array => $this->mapper->group($group)); - - return $this->respond($this->mapper->group($this->groups->patch($group, $this->operations($request)))); - } - - public function deleteGroup(Request $request, string $organization, string $id): Response - { - $group = $this->groups->find($id); - $this->checkVersion($request, fn (): array => $this->mapper->group($group)); - $this->groups->delete($group); - - return response()->noContent(); - } - - public function bulk(Request $request): JsonResponse - { - return Scim::response(app(Bulk::class)->run($this->body($request), strlen($request->getContent()))); - } - - public function serviceProviderConfig(Request $request, string $organization): JsonResponse - { - return Scim::response(Discovery::serviceProviderConfig($this->base($organization))); - } - - public function resourceTypes(Request $request, string $organization): JsonResponse - { - $types = Discovery::resourceTypes($this->base($organization)); - - return Scim::response($this->mapper->list($types, count($types), 1)); - } - - public function schemas(): JsonResponse - { - $schemas = Discovery::schemas(); - - return Scim::response($this->mapper->list($schemas, count($schemas), 1)); - } - - /** - * @param array $resource - */ - private function present(Request $request, array $resource): BaseResponse - { - $version = (string) $resource['meta']['version']; - - if (Scim::matches($request->header('If-None-Match'), $version)) { - return response('', 304, ['ETag' => $version]); - } - - return $this->respond($resource); - } - - /** - * @param array $resource - */ - private function respond(array $resource, int $status = 200): JsonResponse - { - return Scim::response($resource, $status, array_filter([ - 'ETag' => (string) $resource['meta']['version'], - 'Location' => $status === 201 ? (string) $resource['meta']['location'] : null, - ])); - } - - /** - * @param array $current - */ - /** - * Refuse a write whose If-Match names another version. The resource is - * only built when the header is there: most clients never send it, and - * building a group reads all its members. - * - * @param Closure(): array $current - */ - private function checkVersion(Request $request, Closure $current): void - { - $ifMatch = $request->header('If-Match'); - - if ($ifMatch !== null && ! Scim::matches($ifMatch, (string) $current()['meta']['version'])) { - throw ScimException::preconditionFailed(); - } - } - - /** - * @return array{0: int, 1: int} - */ - private function paging(Request $request): array - { - $startIndex = max(1, (int) $request->query('startIndex', '1')); - $count = (int) $request->query('count', (string) config('roster.scim.default_count', 100)); - - return [$startIndex, max(0, min($count, (int) config('roster.scim.max_count', 500)))]; - } - - private function filter(Request $request): ?string - { - $filter = $request->query('filter'); - - return is_string($filter) ? $filter : null; - } - - /** - * @return array - */ - private function body(Request $request): array - { - $body = $request->json()->all(); - - if ($body === []) { - throw ScimException::invalidValue('The request body must be a JSON object.'); - } - - return $body; - } - - /** - * @return array - */ - private function operations(Request $request): array - { - return array_values((array) ($this->body($request)['Operations'] ?? [])); - } - - private function base(string $organization): string - { - return url(trim((string) config('roster.scim.prefix', 'scim/v2'), '/').'/'.$organization); - } -} diff --git a/src/Domains/Scim/Http/Controllers/ScimTokenController.php b/src/Domains/Scim/Http/Controllers/ScimTokenController.php deleted file mode 100644 index 00538be..0000000 --- a/src/Domains/Scim/Http/Controllers/ScimTokenController.php +++ /dev/null @@ -1,28 +0,0 @@ -persist(); - } - - public function store(StoreScimTokenRequest $request): JsonResponse - { - return $request->persist(); - } - - public function destroy(RevokeScimTokenRequest $request): JsonResponse - { - return $request->persist(); - } -} diff --git a/src/Domains/Scim/Http/Middleware/AuthenticateScimToken.php b/src/Domains/Scim/Http/Middleware/AuthenticateScimToken.php deleted file mode 100644 index 7459075..0000000 --- a/src/Domains/Scim/Http/Middleware/AuthenticateScimToken.php +++ /dev/null @@ -1,47 +0,0 @@ -bearerToken(); - $token = $bearer === null ? null : ScimTokenModel::query()->where('token_hash', hash('sha256', $bearer))->with('organization')->first(); - - if ($token === null || ! $token->isUsable() || $token->organization?->slug !== $request->route('organization')) { - return (new ScimException(401, 'A valid SCIM token for this organization is required.'))->render() - ->header('WWW-Authenticate', 'Bearer'); - } - - if ($token->last_used_at === null || $token->last_used_at->lt(now()->subMinute())) { - $token->forceFill(['last_used_at' => now()])->saveQuietly(); - } - - $this->context->token = $token; - - try { - return $next($request); - } catch (ScimException $exception) { - return $exception->render(); - } - } -} diff --git a/src/Domains/Scim/Http/Requests/IndexScimTokensRequest.php b/src/Domains/Scim/Http/Requests/IndexScimTokensRequest.php deleted file mode 100644 index 8be9d42..0000000 --- a/src/Domains/Scim/Http/Requests/IndexScimTokensRequest.php +++ /dev/null @@ -1,29 +0,0 @@ -execute($this->organization(), ListScimTokensData::fromValidated($this->validated())))->response(); - } -} diff --git a/src/Domains/Scim/Http/Requests/RevokeScimTokenRequest.php b/src/Domains/Scim/Http/Requests/RevokeScimTokenRequest.php deleted file mode 100644 index 1a408b1..0000000 --- a/src/Domains/Scim/Http/Requests/RevokeScimTokenRequest.php +++ /dev/null @@ -1,37 +0,0 @@ -token()->organization; - } - - public function persist(): JsonResponse - { - return (new ScimTokenResource(app(RevokeScimTokenAction::class)->execute($this->token())))->response(); - } - - private function token(): ScimTokenModel - { - return $this->resolved ??= ScimTokenModel::query()->whereKey($this->route('token'))->firstOrFail(); - } -} diff --git a/src/Domains/Scim/Http/Requests/StoreScimTokenRequest.php b/src/Domains/Scim/Http/Requests/StoreScimTokenRequest.php deleted file mode 100644 index cd29573..0000000 --- a/src/Domains/Scim/Http/Requests/StoreScimTokenRequest.php +++ /dev/null @@ -1,34 +0,0 @@ -execute($this->organization(), CreateScimTokenData::fromValidated($this->validated()), $this->actor()); - - return (new ScimTokenResource($issued->token))->additional(['token' => $issued->plain])->response()->setStatusCode(201); - } -} diff --git a/src/Domains/Scim/Mcp/Requests/CreateScimTokenMcpRequest.php b/src/Domains/Scim/Mcp/Requests/CreateScimTokenMcpRequest.php deleted file mode 100644 index 9601868..0000000 --- a/src/Domains/Scim/Mcp/Requests/CreateScimTokenMcpRequest.php +++ /dev/null @@ -1,31 +0,0 @@ -organizationRules() + CreateScimTokenData::rules(); - } - - protected function handle(array $validated): ResponseFactory - { - $issued = app(CreateScimTokenAction::class)->execute($this->organization(), CreateScimTokenData::fromValidated($validated), $this->actor()); - - return (new ScimTokenResource($issued->token))->additional(['token' => $issued->plain])->toStructuredResponse(); - } -} diff --git a/src/Domains/Scim/Mcp/Requests/ListScimTokensMcpRequest.php b/src/Domains/Scim/Mcp/Requests/ListScimTokensMcpRequest.php deleted file mode 100644 index 9510cfb..0000000 --- a/src/Domains/Scim/Mcp/Requests/ListScimTokensMcpRequest.php +++ /dev/null @@ -1,31 +0,0 @@ -organizationRules() + ListScimTokensData::rules(); - } - - protected function handle(array $validated): ResponseFactory - { - $tokens = app(ListScimTokensAction::class)->execute($this->organization(), ListScimTokensData::fromValidated($validated)); - - return ScimTokenResource::collection($tokens)->toStructuredResponse(); - } -} diff --git a/src/Domains/Scim/Mcp/Requests/RevokeScimTokenMcpRequest.php b/src/Domains/Scim/Mcp/Requests/RevokeScimTokenMcpRequest.php deleted file mode 100644 index 0e15197..0000000 --- a/src/Domains/Scim/Mcp/Requests/RevokeScimTokenMcpRequest.php +++ /dev/null @@ -1,42 +0,0 @@ -token()->organization; - } - - protected function rules(): array - { - return ['token' => ['required', 'string']]; - } - - protected function handle(array $validated): ResponseFactory - { - return (new ScimTokenResource(app(RevokeScimTokenAction::class)->execute($this->token())))->toStructuredResponse(); - } - - private function token(): ScimTokenModel - { - return $this->resolved ??= ScimTokenModel::query()->whereKey($this->get('token'))->firstOrFail(); - } -} diff --git a/src/Domains/Scim/Mcp/Tools/CreateScimTokenTool.php b/src/Domains/Scim/Mcp/Tools/CreateScimTokenTool.php deleted file mode 100644 index 69bc580..0000000 --- a/src/Domains/Scim/Mcp/Tools/CreateScimTokenTool.php +++ /dev/null @@ -1,39 +0,0 @@ -persist(); - } - - public function schema(JsonSchema $schema): array - { - return $this->organizationSchema($schema) + [ - 'name' => $schema->string()->description('What uses it, e.g. Okta provisioning.')->required(), - 'expires_in_days' => $schema->integer()->description('Expire after this many days. Omit for no expiry.')->min(1), - 'sso_connection' => $schema->string()->description('An SSO connection slug: provisioned users\' externalIds become its SSO subjects.'), - ]; - } - - public function outputSchema(JsonSchema $schema): array - { - return ScimTokenResource::structuredSchema($schema) + ['token' => $schema->string()->description('The token itself. Shown only this once; give it to the identity provider.')->required()]; - } -} diff --git a/src/Domains/Scim/Mcp/Tools/ListScimTokensTool.php b/src/Domains/Scim/Mcp/Tools/ListScimTokensTool.php deleted file mode 100644 index de124f1..0000000 --- a/src/Domains/Scim/Mcp/Tools/ListScimTokensTool.php +++ /dev/null @@ -1,37 +0,0 @@ -persist(); - } - - public function schema(JsonSchema $schema): array - { - return $this->organizationSchema($schema) + [ - ] + ListScimTokensData::pagination()->schema($schema); - } - - public function outputSchema(JsonSchema $schema): array - { - return ScimTokenResource::collectionSchema($schema); - } -} diff --git a/src/Domains/Scim/Mcp/Tools/RevokeScimTokenTool.php b/src/Domains/Scim/Mcp/Tools/RevokeScimTokenTool.php deleted file mode 100644 index 5d34cef..0000000 --- a/src/Domains/Scim/Mcp/Tools/RevokeScimTokenTool.php +++ /dev/null @@ -1,34 +0,0 @@ -persist(); - } - - public function schema(JsonSchema $schema): array - { - return [ - 'token' => $schema->string()->description('The token id (not its value).')->required(), - ]; - } - - public function outputSchema(JsonSchema $schema): array - { - return ScimTokenResource::structuredSchema($schema); - } -} diff --git a/src/Domains/Scim/Models/ScimGroupModel.php b/src/Domains/Scim/Models/ScimGroupModel.php deleted file mode 100644 index 05da189..0000000 --- a/src/Domains/Scim/Models/ScimGroupModel.php +++ /dev/null @@ -1,53 +0,0 @@ - - */ - public function team(): BelongsTo - { - return $this->belongsTo(TeamModel::class, 'team_id'); - } - - /** - * @return BelongsTo - */ - public function organization(): BelongsTo - { - return $this->belongsTo(OrganizationModel::class, 'organization_id'); - } -} diff --git a/src/Domains/Scim/Models/ScimTokenModel.php b/src/Domains/Scim/Models/ScimTokenModel.php deleted file mode 100644 index b9983e4..0000000 --- a/src/Domains/Scim/Models/ScimTokenModel.php +++ /dev/null @@ -1,75 +0,0 @@ - - */ - public function organization(): BelongsTo - { - return $this->belongsTo(OrganizationModel::class, 'organization_id'); - } - - /** - * @return BelongsTo - */ - public function ssoConnection(): BelongsTo - { - return $this->belongsTo(SsoConnectionModel::class, 'sso_connection_id'); - } - - public function isUsable(): bool - { - return $this->revoked_at === null && ($this->expires_at === null || $this->expires_at->isFuture()); - } - - protected function casts(): array - { - return [ - 'last_used_at' => 'datetime', - 'expires_at' => 'datetime', - 'revoked_at' => 'datetime', - ]; - } -} diff --git a/src/Domains/Scim/Models/ScimUserModel.php b/src/Domains/Scim/Models/ScimUserModel.php deleted file mode 100644 index eeef26a..0000000 --- a/src/Domains/Scim/Models/ScimUserModel.php +++ /dev/null @@ -1,67 +0,0 @@ - - */ - public function organization(): BelongsTo - { - return $this->belongsTo(OrganizationModel::class, 'organization_id'); - } - - /** - * @return BelongsTo - */ - public function user(): BelongsTo - { - return $this->belongsTo(app(Users::class)->model(), 'user_id'); - } - - protected function casts(): array - { - return [ - 'created_by_scim' => 'boolean', - 'deactivated_by_scim' => 'boolean', - 'active' => 'boolean', - ]; - } -} diff --git a/src/Domains/Scim/Policies/ScimGroupPolicy.php b/src/Domains/Scim/Policies/ScimGroupPolicy.php deleted file mode 100644 index 7c3bb13..0000000 --- a/src/Domains/Scim/Policies/ScimGroupPolicy.php +++ /dev/null @@ -1,26 +0,0 @@ -permits($user, 'roster.scim.manage', $scimGroup); - } - - public function manage(?Model $user, ?ScimGroupModel $scimGroup = null): bool - { - return $this->permits($user, 'roster.scim.manage', $scimGroup); - } -} diff --git a/src/Domains/Scim/Policies/ScimTokenPolicy.php b/src/Domains/Scim/Policies/ScimTokenPolicy.php deleted file mode 100644 index 488169f..0000000 --- a/src/Domains/Scim/Policies/ScimTokenPolicy.php +++ /dev/null @@ -1,20 +0,0 @@ -permits($user, 'roster.scim.manage', $subject, $self); - } -} diff --git a/src/Domains/Scim/Policies/ScimUserPolicy.php b/src/Domains/Scim/Policies/ScimUserPolicy.php deleted file mode 100644 index 502954d..0000000 --- a/src/Domains/Scim/Policies/ScimUserPolicy.php +++ /dev/null @@ -1,26 +0,0 @@ -permits($user, 'roster.scim.manage', $scimUser); - } - - public function manage(?Model $user, ?ScimUserModel $scimUser = null): bool - { - return $this->permits($user, 'roster.scim.manage', $scimUser); - } -} diff --git a/src/Domains/Scim/Resources/ScimTokenResource.php b/src/Domains/Scim/Resources/ScimTokenResource.php deleted file mode 100644 index 2f285b4..0000000 --- a/src/Domains/Scim/Resources/ScimTokenResource.php +++ /dev/null @@ -1,60 +0,0 @@ - - */ - public static function schema(JsonSchema $schema): array - { - return [ - 'id' => $schema->string()->required(), - 'name' => $schema->string()->required(), - 'organization' => $schema->string()->nullable()->required(), - 'sso_connection' => $schema->string()->nullable()->required(), - 'base_url' => $schema->string()->nullable()->description('The SCIM base URL to give the identity provider.')->required(), - 'usable' => $schema->boolean()->required(), - 'last_used_at' => $schema->string()->nullable()->required(), - 'expires_at' => $schema->string()->nullable()->required(), - 'revoked_at' => $schema->string()->nullable()->required(), - 'created_at' => $schema->string()->nullable()->required(), - ]; - } - - /** - * @return array - */ - public function toArray(Request $request): array - { - $organization = $this->organization; - - return [ - 'id' => $this->id, - 'name' => $this->name, - 'organization' => $organization?->slug, - 'sso_connection' => $this->ssoConnection?->slug, - 'base_url' => $organization !== null && Route::has('roster.scim.users.index') ? str_replace('/Users', '', route('roster.scim.users.index', $organization->slug)) : null, - 'usable' => $this->isUsable(), - 'last_used_at' => $this->last_used_at?->toIso8601String(), - 'expires_at' => $this->expires_at?->toIso8601String(), - 'revoked_at' => $this->revoked_at?->toIso8601String(), - 'created_at' => $this->created_at?->toIso8601String(), - ]; - } -} diff --git a/src/Domains/Scim/ScimServiceProvider.php b/src/Domains/Scim/ScimServiceProvider.php deleted file mode 100644 index 4b40f7c..0000000 --- a/src/Domains/Scim/ScimServiceProvider.php +++ /dev/null @@ -1,107 +0,0 @@ -app->scoped(ScimContext::class); - } - - public function boot(): void - { - $this->registerAuthorization(); - - // Members SCIM provisions join with this source. - $this->app->make(MembershipSources::class)->register('scim', 'SCIM'); - - $this->registerAuditContext(); - - $this->loadApiRoutesFrom(__DIR__.'/routes.php'); - $this->loadRoutesFrom(__DIR__.'/scim.php'); - } - - /** - * While Roster audits, the SCIM token a change came through joins the - * context of Roster's own entries, through Keystone's AuditHooks as any - * other package would add it. Decided once every provider has booted, - * when `Support\Audit` registers Roster's hooks. - */ - private function registerAuditContext(): void - { - $this->app->booted(function (): void { - if (! $this->app->make(Roster::class)->auditing()) { - return; - } - - $this->app->make(AuditHooks::class)->context(fn (object $event): array => $this->auditContext($event)); - }); - } - - /** - * The SCIM token behind a Roster entry. AuditHooks runs every context - * hook for every package's events and catches nothing, so this keeps to - * Roster's events and never breaks the entry: a failure is reported and - * the entry is written without the token. - * - * @return array - */ - private function auditContext(object $event): array - { - try { - if ($this->app->make(PackageRegistry::class)->for($event)?->key !== 'roster') { - return []; - } - - $token = $this->app->make(ScimContext::class)->token; - - return $token === null ? [] : ['scim_token' => ['id' => $token->id, 'name' => $token->name]]; - } catch (Throwable $e) { - report($e); - - return []; - } - } - - /** - * The `roster.scim.manage` permission, granted to admins, answered by the - * token policy, through the same seams other packages use. An - * application's `roster.policies` entry for these models still wins: the - * package provider registers those after this boots. - */ - private function registerAuthorization(): void - { - $this->app->make(Resources::class)->rosterResource('roster.scim', ScimTokenModel::class); - - $this->app->make(PermissionCatalogue::class) - ->rosterPermission('roster.scim.manage', 'Issue and revoke SCIM provisioning tokens.', ['admin']); - - $gate = $this->app->make(Gate::class); - $gate->policy(ScimTokenModel::class, ScimTokenPolicy::class); - $gate->policy(ScimUserModel::class, ScimUserPolicy::class); - $gate->policy(ScimGroupModel::class, ScimGroupPolicy::class); - } -} diff --git a/src/Domains/Scim/Services/Bulk.php b/src/Domains/Scim/Services/Bulk.php deleted file mode 100644 index 9765d05..0000000 --- a/src/Domains/Scim/Services/Bulk.php +++ /dev/null @@ -1,158 +0,0 @@ - $request - * @return array - */ - public function run(array $request, int $payloadBytes): array - { - $operations = (array) ($request['Operations'] ?? []); - $max = (int) config('roster.scim.bulk.max_operations', 100); - - if (count($operations) > $max || $payloadBytes > (int) config('roster.scim.bulk.max_payload_bytes', 1048576)) { - throw new ScimException(413, "Bulk requests are limited to {$max} operations and ".config('roster.scim.bulk.max_payload_bytes', 1048576).' bytes.', 'tooMany'); - } - - $failOnErrors = is_numeric($request['failOnErrors'] ?? null) ? (int) $request['failOnErrors'] : null; - $ids = []; - $errors = 0; - $results = []; - - foreach ($operations as $operation) { - if ($failOnErrors !== null && $errors >= $failOnErrors) { - break; - } - - $operation = is_array($operation) ? $operation : []; - $method = strtoupper((string) ($operation['method'] ?? '')); - $bulkId = is_string($operation['bulkId'] ?? null) ? $operation['bulkId'] : null; - - try { - $path = (string) $this->resolve((string) ($operation['path'] ?? ''), $ids); - $data = (array) $this->resolve($operation['data'] ?? [], $ids); - [$status, $resource] = $this->one($method, $path, $data, is_string($operation['version'] ?? null) ? $operation['version'] : null); - - if ($bulkId !== null && $resource !== null) { - $ids[$bulkId] = $resource['id']; - } - - $results[] = array_filter([ - 'method' => $method, - 'bulkId' => $bulkId, - 'location' => $resource['meta']['location'] ?? null, - 'version' => $resource['meta']['version'] ?? null, - 'status' => (string) $status, - ], fn (mixed $value): bool => $value !== null); - } catch (ScimException $exception) { - $errors++; - $results[] = array_filter([ - 'method' => $method, - 'bulkId' => $bulkId, - 'status' => (string) $exception->status, - 'response' => array_filter([ - 'schemas' => [Scim::ERROR], - 'status' => (string) $exception->status, - 'scimType' => $exception->scimType, - 'detail' => $exception->getMessage(), - ], fn (mixed $value): bool => $value !== null), - ], fn (mixed $value): bool => $value !== null); - } - } - - return ['schemas' => [Scim::BULK_RESPONSE], 'Operations' => $results]; - } - - /** - * @param array $data - * @return array{0: int, 1: array|null} - */ - private function one(string $method, string $path, array $data, ?string $version): array - { - if (preg_match('#^/(Users|Groups)(?:/([^/]+))?$#', $path, $match) !== 1) { - throw ScimException::invalidPath($path); - } - - $users = $match[1] === 'Users'; - $id = $match[2] ?? null; - - if ($method === 'POST' && $id === null) { - $model = $users ? $this->users->create($data) : $this->groups->create($data); - - return [201, $this->present($model)]; - } - - if ($id === null) { - throw ScimException::invalidPath($path); - } - - $model = $users ? $this->users->find($id) : $this->groups->find($id); - - // Built only to compare versions: a group's view reads all its members. - if ($version !== null && ! Scim::matches($version, (string) $this->present($model)['meta']['version'])) { - throw ScimException::preconditionFailed(); - } - - return match ($method) { - 'PUT' => [200, $this->present($model instanceof ScimUserModel ? $this->users->replace($model, $data) : $this->groups->replace($model, $data))], - 'PATCH' => [200, $this->present($model instanceof ScimUserModel ? $this->users->patch($model, (array) ($data['Operations'] ?? [])) : $this->groups->patch($model, (array) ($data['Operations'] ?? [])))], - 'DELETE' => [204, $this->delete($model)], - default => throw ScimException::invalidValue("Unsupported bulk method [{$method}]."), - }; - } - - /** - * @return array - */ - private function present(ScimUserModel|ScimGroupModel $model): array - { - return $model instanceof ScimUserModel ? $this->mapper->user($model) : $this->mapper->group($model); - } - - private function delete(ScimUserModel|ScimGroupModel $model): null - { - $model instanceof ScimUserModel ? $this->users->delete($model) : $this->groups->delete($model); - - return null; - } - - /** - * Replace `bulkId:x` with the id created for that operation. - * - * @param array $ids - */ - private function resolve(mixed $value, array $ids): mixed - { - if (is_array($value)) { - return array_map(fn (mixed $item): mixed => $this->resolve($item, $ids), $value); - } - - if (! is_string($value) || ! str_contains($value, 'bulkId:')) { - return $value; - } - - return preg_replace_callback('/bulkId:([A-Za-z0-9_\-]+)/', function (array $match) use ($ids): string { - return $ids[$match[1]] ?? throw ScimException::invalidValue("Unknown bulkId [{$match[1]}]."); - }, $value); - } -} diff --git a/src/Domains/Scim/Services/Discovery.php b/src/Domains/Scim/Services/Discovery.php deleted file mode 100644 index 91ce574..0000000 --- a/src/Domains/Scim/Services/Discovery.php +++ /dev/null @@ -1,95 +0,0 @@ - - */ - public static function serviceProviderConfig(string $base): array - { - return [ - 'schemas' => [Scim::CONFIG], - 'documentationUri' => 'https://github.com/Refactor-Circus/roster#scim-provisioning', - 'patch' => ['supported' => true], - 'bulk' => [ - 'supported' => true, - 'maxOperations' => (int) config('roster.scim.bulk.max_operations', 100), - 'maxPayloadSize' => (int) config('roster.scim.bulk.max_payload_bytes', 1048576), - ], - 'filter' => ['supported' => true, 'maxResults' => (int) config('roster.scim.max_count', 500)], - 'changePassword' => ['supported' => false], - 'sort' => ['supported' => false], - 'etag' => ['supported' => true], - 'authenticationSchemes' => [[ - 'type' => 'oauthbearertoken', - 'name' => 'OAuth Bearer Token', - 'description' => "A SCIM token issued for this organization in Roster, sent as 'Authorization: Bearer '.", - 'primary' => true, - ]], - 'meta' => ['resourceType' => 'ServiceProviderConfig', 'location' => $base.'/ServiceProviderConfig'], - ]; - } - - /** - * @return array> - */ - public static function resourceTypes(string $base): array - { - return [ - ['schemas' => [Scim::RESOURCE_TYPE], 'id' => 'User', 'name' => 'User', 'endpoint' => '/Users', 'schema' => Scim::USER, 'meta' => ['resourceType' => 'ResourceType', 'location' => $base.'/ResourceTypes/User']], - ['schemas' => [Scim::RESOURCE_TYPE], 'id' => 'Group', 'name' => 'Group', 'endpoint' => '/Groups', 'schema' => Scim::GROUP, 'meta' => ['resourceType' => 'ResourceType', 'location' => $base.'/ResourceTypes/Group']], - ]; - } - - /** - * @return array> - */ - public static function schemas(): array - { - $attribute = fn (string $name, string $type = 'string', bool $required = false, string $uniqueness = 'none', array $sub = []): array => array_filter([ - 'name' => $name, - 'type' => $type, - 'multiValued' => in_array($name, ['emails', 'groups', 'members'], true), - 'required' => $required, - 'mutability' => in_array($name, ['id', 'groups'], true) ? 'readOnly' : 'readWrite', - 'returned' => 'default', - 'uniqueness' => $uniqueness, - 'caseExact' => false, - 'subAttributes' => $sub === [] ? null : $sub, - ], fn (mixed $value): bool => $value !== null); - - return [ - [ - 'schemas' => [Scim::SCHEMA], - 'id' => Scim::USER, - 'name' => 'User', - 'attributes' => [ - $attribute('userName', required: true, uniqueness: 'server'), - $attribute('name', 'complex', sub: [$attribute('formatted'), $attribute('givenName'), $attribute('familyName')]), - $attribute('displayName'), - $attribute('emails', 'complex', sub: [$attribute('value'), $attribute('type'), $attribute('primary', 'boolean')]), - $attribute('active', 'boolean'), - $attribute('groups', 'complex', sub: [$attribute('value'), $attribute('display')]), - ], - 'meta' => ['resourceType' => 'Schema'], - ], - [ - 'schemas' => [Scim::SCHEMA], - 'id' => Scim::GROUP, - 'name' => 'Group', - 'attributes' => [ - $attribute('displayName', required: true), - $attribute('members', 'complex', sub: [$attribute('value'), $attribute('display')]), - ], - 'meta' => ['resourceType' => 'Schema'], - ], - ]; - } -} diff --git a/src/Domains/Scim/Services/FilterParser.php b/src/Domains/Scim/Services/FilterParser.php deleted file mode 100644 index 1dba1e6..0000000 --- a/src/Domains/Scim/Services/FilterParser.php +++ /dev/null @@ -1,69 +0,0 @@ - $attributes the attributes allowed, lower-cased - * @return array - */ - public static function parse(string $filter, array $attributes): array - { - $conditions = []; - $rest = $filter; - - while (true) { - if (preg_match(self::PATTERN, $rest, $match) !== 1) { - throw ScimException::invalidFilter("Unsupported filter [{$filter}]. Use attribute eq|co|sw \"value\", joined by and."); - } - - $attribute = strtolower($match[1]); - - if (! in_array($attribute, $attributes, true)) { - throw ScimException::invalidFilter("Filtering on [{$match[1]}] is not supported."); - } - - $conditions[] = [ - 'attribute' => $attribute, - 'operator' => strtolower($match[2]), - 'value' => self::value($match[3]), - ]; - - $rest = substr($rest, strlen($match[0])); - - if (trim($rest) === '') { - return $conditions; - } - - if (preg_match('/^and\s+/i', $rest, $and) !== 1) { - throw ScimException::invalidFilter("Unsupported filter [{$filter}]. Only and is supported between conditions."); - } - - $rest = substr($rest, strlen($and[0])); - } - } - - private static function value(string $raw): string|bool|null - { - return match (strtolower($raw)) { - 'true' => true, - 'false' => false, - 'null' => null, - default => stripcslashes(substr($raw, 1, -1)), - }; - } -} diff --git a/src/Domains/Scim/Services/PatchApplier.php b/src/Domains/Scim/Services/PatchApplier.php deleted file mode 100644 index 488809a..0000000 --- a/src/Domains/Scim/Services/PatchApplier.php +++ /dev/null @@ -1,189 +0,0 @@ - */ - private const array SIMPLE = ['active', 'username', 'displayname', 'externalid', 'name.givenname', 'name.familyname', 'name.formatted', 'emails']; - - /** - * @param array $resource - * @param array $operations - * @return array - */ - public static function apply(array $resource, array $operations): array - { - if ($operations === []) { - throw ScimException::invalidValue('PATCH needs at least one operation.'); - } - - foreach ($operations as $operation) { - if (! is_array($operation)) { - throw ScimException::invalidValue('Each PATCH operation must be an object.'); - } - - $op = strtolower((string) ($operation['op'] ?? '')); - $path = $operation['path'] ?? null; - $value = $operation['value'] ?? null; - - if (! in_array($op, ['add', 'replace', 'remove'], true)) { - throw ScimException::invalidValue("Unsupported operation [{$op}]."); - } - - if ($path === null || $path === '') { - if (! is_array($value) || $op === 'remove') { - throw ScimException::invalidValue('An operation without a path needs an object value.'); - } - - foreach ($value as $key => $item) { - $resource = self::applyPath($resource, $op, (string) $key, $item); - } - - continue; - } - - $resource = self::applyPath($resource, $op, (string) $path, $value); - } - - return $resource; - } - - /** - * @param array $resource - * @return array - */ - private static function applyPath(array $resource, string $op, string $path, mixed $value): array - { - $normal = strtolower(preg_replace('/^urn:[^:]+(?::[^:]+)*:(User|Group):/i', '', $path) ?? $path); - - if (preg_match('/^members\[value eq "([^"]+)"\]$/i', $path, $match) === 1) { - $resource['members'] = array_values(array_filter( - (array) ($resource['members'] ?? []), - fn (mixed $member): bool => ! (is_array($member) && ($member['value'] ?? null) === $match[1]), - )); - - return $resource; - } - - if (preg_match('/^emails\[type eq "([^"]+)"\]\.value$/i', $path, $match) === 1) { - return self::setEmail($resource, $op === 'remove' ? null : (string) $value, $match[1]); - } - - if ($normal === 'members') { - return self::members($resource, $op, $value); - } - - if (! in_array($normal, self::SIMPLE, true)) { - throw ScimException::invalidPath($path); - } - - if ($normal === 'emails') { - $first = is_array($value) ? ($value[0] ?? null) : null; - - return self::setEmail($resource, $op === 'remove' ? null : (is_array($first) ? (string) ($first['value'] ?? '') : null), 'work'); - } - - if ($normal === 'active') { - $value = self::boolean($value); - } - - [$key, $sub] = array_pad(explode('.', $normal, 2), 2, null); - $key = self::canonical($key); - - if ($sub !== null) { - $sub = self::canonical($sub); - $nested = (array) ($resource[$key] ?? []); - - if ($op === 'remove') { - unset($nested[$sub]); - } else { - $nested[$sub] = $value; - } - - // A changed name part makes the old formatted name stale. - if ($key === 'name' && $sub !== 'formatted') { - unset($nested['formatted']); - } - - $resource[$key] = $nested; - - return $resource; - } - - if ($op === 'remove') { - unset($resource[$key]); - } else { - $resource[$key] = $key === 'name' && is_array($value) ? array_merge((array) ($resource['name'] ?? []), $value) : $value; - } - - return $resource; - } - - /** - * @param array $resource - * @return array - */ - private static function members(array $resource, string $op, mixed $value): array - { - $given = array_values(array_filter(array_map( - fn (mixed $member): ?string => is_array($member) && is_scalar($member['value'] ?? null) ? (string) $member['value'] : null, - is_array($value) ? $value : [], - ))); - - $current = array_map(fn (mixed $member): string => (string) (is_array($member) ? ($member['value'] ?? '') : ''), (array) ($resource['members'] ?? [])); - - $members = match ($op) { - 'add' => array_values(array_unique([...$current, ...$given])), - 'replace' => $given, - default => $given === [] ? [] : array_values(array_diff($current, $given)), - }; - - $resource['members'] = array_map(fn (string $id): array => ['value' => $id], $members); - - return $resource; - } - - /** - * @param array $resource - * @return array - */ - private static function setEmail(array $resource, ?string $email, string $type): array - { - $resource['emails'] = $email === null || $email === '' ? [] : [['value' => $email, 'type' => $type, 'primary' => true]]; - - return $resource; - } - - private static function boolean(mixed $value): bool - { - if (is_string($value)) { - return in_array(strtolower($value), ['true', '1'], true); - } - - return (bool) $value; - } - - private static function canonical(string $key): string - { - return match ($key) { - 'username' => 'userName', - 'displayname' => 'displayName', - 'externalid' => 'externalId', - 'givenname' => 'givenName', - 'familyname' => 'familyName', - default => $key, - }; - } -} diff --git a/src/Domains/Scim/Services/Scim.php b/src/Domains/Scim/Services/Scim.php deleted file mode 100644 index 0168fa7..0000000 --- a/src/Domains/Scim/Services/Scim.php +++ /dev/null @@ -1,75 +0,0 @@ - $body - * @param array $headers - */ - public static function response(array $body, int $status = 200, array $headers = []): JsonResponse - { - return new JsonResponse($body, $status, ['Content-Type' => 'application/scim+json'] + $headers, JSON_UNESCAPED_SLASHES); - } - - /** - * A weak ETag over the resource's content (everything but `meta`), so any - * change yields a new version. - * - * @param array $resource - */ - public static function version(array $resource): string - { - unset($resource['meta']); - - return 'W/"'.substr(hash('sha256', (string) json_encode($resource)), 0, 32).'"'; - } - - /** - * Whether an If-Match / If-None-Match header names this version. - */ - public static function matches(?string $header, string $version): bool - { - if ($header === null || trim($header) === '*') { - return $header !== null; - } - - $strip = fn (string $tag): string => trim(preg_replace('/^W\//', '', trim($tag)) ?? '', '"'); - - foreach (explode(',', $header) as $tag) { - if ($strip($tag) === $strip($version)) { - return true; - } - } - - return false; - } -} diff --git a/src/Domains/Scim/Services/ScimContext.php b/src/Domains/Scim/Services/ScimContext.php deleted file mode 100644 index c5d027d..0000000 --- a/src/Domains/Scim/Services/ScimContext.php +++ /dev/null @@ -1,50 +0,0 @@ -> - */ - public array $groups = []; - - /** - * Members per SCIM group id, resolved for a whole page at once. - * - * @var array> - */ - public array $members = []; - - public function organization(): OrganizationModel - { - $organization = $this->token?->organization; - - if (! $organization instanceof OrganizationModel) { - throw new ScimException(401, 'Authentication required.'); - } - - return $organization; - } - - public function active(): bool - { - return $this->token !== null; - } -} diff --git a/src/Domains/Scim/Services/ScimGroups.php b/src/Domains/Scim/Services/ScimGroups.php deleted file mode 100644 index 173d607..0000000 --- a/src/Domains/Scim/Services/ScimGroups.php +++ /dev/null @@ -1,292 +0,0 @@ -, 1: int} - */ - public function list(?string $filter, int $startIndex, int $count): array - { - $query = ScimGroupModel::query()->where('organization_id', $this->organization()->getKey())->with('team'); - - if ($filter !== null && trim($filter) !== '') { - foreach (FilterParser::parse($filter, ['displayname', 'externalid', 'id', 'members.value']) as $condition) { - $value = (string) $condition['value']; - - match ($condition['attribute']) { - 'displayname' => $query->whereHas('team', fn (Builder $team): Builder => ScimQuery::compare($team, 'name', $condition['operator'], $value)), - 'externalid' => ScimQuery::compare($query, 'external_id', $condition['operator'], $value), - 'id' => $query->where('id', $value), - default => $query->whereIn('team_id', $this->teamsOfMember($value)), - }; - } - } - - $total = (clone $query)->count(); - $page = $query->orderBy('created_at')->orderBy('id')->skip(max(0, $startIndex - 1))->take($count)->get()->all(); - - $this->preloadMembers($page); - - return [$page, $total]; - } - - /** - * Resolve the members of a page of groups in two queries, so mapping each - * one adds none. - * - * @param array $groups - */ - private function preloadMembers(array $groups): void - { - $teamIds = array_values(array_filter(array_map(fn (ScimGroupModel $group): string => (string) $group->team_id, $groups))); - - if ($teamIds === []) { - return; - } - - $memberships = Tables::name('memberships'); - $seatsTable = Tables::name('team_members'); - - $seats = TeamMemberModel::query() - ->join($memberships, $memberships.'.id', '=', $seatsTable.'.membership_id') - ->whereIn($seatsTable.'.team_id', $teamIds) - ->get([$seatsTable.'.team_id', $memberships.'.user_id']); - - $scimUsers = ScimUserModel::query() - ->where('organization_id', $this->organization()->getKey()) - ->whereIn('user_id', $seats->pluck('user_id')->unique()->all()) - ->with('user') - ->orderBy('id') - ->get() - ->groupBy(fn (ScimUserModel $scimUser): string => (string) $scimUser->user_id); - - $seatsByTeam = $seats->groupBy(fn (TeamMemberModel $seat): string => (string) $seat->team_id); - - foreach ($groups as $group) { - $userIds = ($seatsByTeam->get((string) $group->team_id) ?? collect())->pluck('user_id')->map(fn (mixed $id): string => (string) $id)->all(); - - $this->context->members[$group->id] = collect($userIds) - ->flatMap(fn (string $userId): array => $scimUsers->get($userId)?->all() ?? []) - ->sortBy('id') - ->values() - ->all(); - } - } - - public function find(string $id): ScimGroupModel - { - return ScimGroupModel::query() - ->where('organization_id', $this->organization()->getKey()) - ->whereKey($id) - ->with('team') - ->first() ?? throw ScimException::notFound('Group'); - } - - /** - * @param array $data - */ - public function create(array $data): ScimGroupModel - { - $name = $this->displayName($data); - $organization = $this->organization(); - $externalId = is_scalar($data['externalId'] ?? null) ? (string) $data['externalId'] : null; - - if ($organization->teams()->where('name', $name)->whereIn('id', ScimGroupModel::query()->where('organization_id', $organization->getKey())->select('team_id'))->exists()) { - throw ScimException::uniqueness("A group named [{$name}] already exists."); - } - - return DB::transaction(function () use ($data, $name, $organization, $externalId): ScimGroupModel { - $team = app(CreateTeamAction::class)->execute($organization, new CreateTeamData(name: $name)); - - $group = ScimGroupModel::query()->create([ - 'organization_id' => $organization->getKey(), - 'team_id' => $team->getKey(), - 'external_id' => $externalId, - ]); - - $this->syncMembers($team, $this->memberIds($data)); - - return $group->refresh()->load('team'); - }); - } - - /** - * @param array $data - */ - public function replace(ScimGroupModel $group, array $data, bool $members = true): ScimGroupModel - { - $team = $group->team ?? throw ScimException::notFound('Group'); - $name = $this->displayName($data); - - return DB::transaction(function () use ($group, $team, $data, $name, $members): ScimGroupModel { - if ($team->name !== $name) { - app(UpdateTeamAction::class)->execute($team, new UpdateTeamData(name: $name)); - } - - if (array_key_exists('externalId', $data)) { - $group->update(['external_id' => is_scalar($data['externalId']) ? (string) $data['externalId'] : null]); - } - - if ($members) { - $this->syncMembers($team, $this->memberIds($data)); - } - - $group->touch(); - - return $group->refresh()->load('team'); - }); - } - - /** - * @param array $operations - */ - public function patch(ScimGroupModel $group, array $operations): ScimGroupModel - { - $view = app(ScimMapper::class)->group($group); - - return $this->replace($group, PatchApplier::apply($view, $operations)); - } - - public function delete(ScimGroupModel $group): void - { - $team = $group->team; - - DB::transaction(function () use ($group, $team): void { - $group->delete(); - - if ($team instanceof TeamModel) { - app(DeleteTeamAction::class)->execute($team); - } - }); - } - - /** - * Make the team's seats match exactly the given SCIM users. - * - * @param array $scimUserIds - */ - private function syncMembers(TeamModel $team, array $scimUserIds): void - { - $wanted = ScimUserModel::query() - ->where('organization_id', $this->organization()->getKey()) - ->whereIn('id', $scimUserIds) - ->with('user') - ->get(); - - if ($wanted->count() !== count(array_unique($scimUserIds))) { - throw ScimException::invalidValue('Every member must be a user provisioned in this organization.'); - } - - // Loaded once: the seats before any change, and which of them SCIM - // manages, rather than a query per seat on every group PATCH. - $seated = $team->memberships()->with('user')->get(); - $current = $seated->map(fn (MembershipModel $membership): string => (string) $membership->user_id)->all(); - $managed = ScimUserModel::query() - ->where('organization_id', $this->organization()->getKey()) - ->whereIn('user_id', $seated->pluck('user_id')->all()) - ->pluck('user_id') - ->map(fn (mixed $id): string => (string) $id) - ->all(); - $wantedUsers = $wanted->filter(fn (ScimUserModel $scimUser): bool => $scimUser->active && $scimUser->user instanceof Model); - - foreach ($wantedUsers as $scimUser) { - $user = $scimUser->user; - - if ($user instanceof Model && ! in_array((string) $scimUser->user_id, $current, true)) { - $this->attempt(fn () => app(AddTeamMemberAction::class)->execute($team, new AddTeamMemberData(user: $user))); - } - } - - $keep = $wantedUsers->map(fn (ScimUserModel $scimUser): string => (string) $scimUser->user_id)->all(); - - foreach ($seated as $membership) { - // Only seats SCIM can see are SCIM's to remove. - $userId = (string) $membership->user_id; - - if (in_array($userId, $managed, true) && ! in_array($userId, $keep, true) && $membership->user instanceof Model) { - $this->attempt(fn () => app(RemoveTeamMemberAction::class)->execute($team, $membership->user)); - } - } - } - - /** - * @param array $data - * @return array - */ - private function memberIds(array $data): array - { - return array_values(array_filter(array_map( - fn (mixed $member): ?string => is_array($member) && is_scalar($member['value'] ?? null) ? (string) $member['value'] : null, - (array) ($data['members'] ?? []), - ))); - } - - /** - * @return array - */ - private function teamsOfMember(string $scimUserId): array - { - $scimUser = ScimUserModel::query()->where('organization_id', $this->organization()->getKey())->whereKey($scimUserId)->first(); - $membership = $scimUser?->user instanceof Model ? $this->organization()->membershipFor($scimUser->user) : null; - - return $membership === null ? [] : $membership->teams()->pluck(Tables::name('teams').'.id')->map(fn (mixed $id): string => (string) $id)->all(); - } - - /** - * @param array $data - */ - private function displayName(array $data): string - { - $name = $data['displayName'] ?? null; - - if (! is_string($name) || trim($name) === '') { - throw ScimException::invalidValue('displayName is required.'); - } - - return trim($name); - } - - private function attempt(callable $callback): void - { - try { - $callback(); - } catch (ValidationException $exception) { - throw ScimException::invalidValue((string) collect($exception->errors())->flatten()->first()); - } - } - - private function organization(): OrganizationModel - { - return $this->context->organization(); - } -} diff --git a/src/Domains/Scim/Services/ScimMapper.php b/src/Domains/Scim/Services/ScimMapper.php deleted file mode 100644 index 0deae4f..0000000 --- a/src/Domains/Scim/Services/ScimMapper.php +++ /dev/null @@ -1,119 +0,0 @@ - - */ - public function user(ScimUserModel $scimUser): array - { - $user = $scimUser->user; - $email = $user instanceof Model ? $this->users->email($user) : null; - $name = $user instanceof Model ? ($this->users->name($user) ?? $email) : null; - [$given, $family] = array_pad(explode(' ', (string) $name, 2), 2, null); - $display = $user instanceof Model ? ($this->users->profileIfExists($user)->display_name ?? $name) : null; - - $resource = [ - 'schemas' => [Scim::USER], - 'id' => $scimUser->id, - 'externalId' => $scimUser->external_id, - 'userName' => $email, - 'name' => array_filter(['formatted' => $name, 'givenName' => $given, 'familyName' => $family], fn (mixed $value): bool => $value !== null && $value !== ''), - 'displayName' => $display, - 'emails' => $email === null ? [] : [['value' => $email, 'type' => 'work', 'primary' => true]], - 'active' => $scimUser->active, - 'groups' => array_map(fn (ScimGroupModel $group): array => [ - 'value' => $group->id, - 'display' => $group->team?->name, - '$ref' => $this->location('Groups', $group->id), - ], app(ScimUsers::class)->groupsOf($scimUser)), - ]; - - $resource = array_filter($resource, fn (mixed $value): bool => $value !== null); - - return $resource + ['meta' => [ - 'resourceType' => 'User', - 'created' => $scimUser->created_at?->toIso8601String(), - 'lastModified' => $scimUser->updated_at?->toIso8601String(), - 'location' => $this->location('Users', $scimUser->id), - 'version' => Scim::version($resource), - ]]; - } - - /** - * @return array - */ - public function group(ScimGroupModel $group): array - { - $team = $group->team; - $members = []; - - if ($team instanceof TeamModel) { - $scimUsers = $this->context->members[$group->id] - ?? ScimUserModel::query()->where('organization_id', $group->organization_id)->whereIn('user_id', $team->memberships()->pluck('user_id'))->with('user')->orderBy('id')->get()->all(); - - foreach ($scimUsers as $scimUser) { - $user = $scimUser->user; - $members[] = [ - 'value' => $scimUser->id, - 'display' => $user instanceof Model ? ($this->users->name($user) ?? $this->users->email($user)) : null, - '$ref' => $this->location('Users', $scimUser->id), - ]; - } - } - - $resource = array_filter([ - 'schemas' => [Scim::GROUP], - 'id' => $group->id, - 'externalId' => $group->external_id, - 'displayName' => $team?->name, - 'members' => $members, - ], fn (mixed $value): bool => $value !== null); - - return $resource + ['meta' => [ - 'resourceType' => 'Group', - 'created' => $group->created_at?->toIso8601String(), - 'lastModified' => max($group->updated_at?->toIso8601String(), $team?->updated_at?->toIso8601String()), - 'location' => $this->location('Groups', $group->id), - 'version' => Scim::version($resource), - ]]; - } - - /** - * @param array> $resources - * @return array - */ - public function list(array $resources, int $total, int $startIndex): array - { - return [ - 'schemas' => [Scim::LIST], - 'totalResults' => $total, - 'startIndex' => $startIndex, - 'itemsPerPage' => count($resources), - 'Resources' => $resources, - ]; - } - - private function location(string $type, string $id): string - { - return route('roster.scim.'.strtolower($type).'.show', [$this->context->organization()->slug, $id]); - } -} diff --git a/src/Domains/Scim/Services/ScimQuery.php b/src/Domains/Scim/Services/ScimQuery.php deleted file mode 100644 index 7f5afe5..0000000 --- a/src/Domains/Scim/Services/ScimQuery.php +++ /dev/null @@ -1,38 +0,0 @@ - $builder - * @return Builder - */ - public static function compare(Builder $builder, string $column, string $operator, string $value): Builder - { - if ($operator === 'co') { - return $builder->whereLike($column, '%'.$value.'%'); - } - - if ($operator === 'sw') { - return $builder->whereLike($column, $value.'%'); - } - - return CaseInsensitive::where($builder, $column, $value); - } -} diff --git a/src/Domains/Scim/Services/ScimUsers.php b/src/Domains/Scim/Services/ScimUsers.php deleted file mode 100644 index d26dfe6..0000000 --- a/src/Domains/Scim/Services/ScimUsers.php +++ /dev/null @@ -1,428 +0,0 @@ -, 1: int} - */ - public function list(?string $filter, int $startIndex, int $count): array - { - $query = ScimUserModel::query()->where('organization_id', $this->organization()->getKey())->with('user.rosterProfile'); - - if ($filter !== null && trim($filter) !== '') { - $email = $this->users->column('email') ?? 'email'; - - foreach (FilterParser::parse($filter, ['username', 'externalid', 'emails.value', 'id', 'emails']) as $condition) { - $value = (string) $condition['value']; - $like = fn (string $column, Builder $builder): Builder => ScimQuery::compare($builder, $column, $condition['operator'], $value); - - match ($condition['attribute']) { - 'externalid' => $condition['operator'] === 'eq' ? $query->where('external_id', $value) : $like('external_id', $query), - 'id' => $query->where('id', $value), - default => $query->whereHas('user', fn (Builder $user): Builder => $like($email, $user)), - }; - } - } - - $total = (clone $query)->count(); - $page = $query->orderBy('created_at')->orderBy('id')->skip(max(0, $startIndex - 1))->take($count)->get()->all(); - - $this->preloadGroups($page); - - return [$page, $total]; - } - - public function find(string $id): ScimUserModel - { - return ScimUserModel::query() - ->where('organization_id', $this->organization()->getKey()) - ->whereKey($id) - ->with('user') - ->first() ?? throw ScimException::notFound('User'); - } - - /** - * @param array $data - */ - public function create(array $data): ScimUserModel - { - $email = $this->email($data); - $externalId = $this->string($data['externalId'] ?? null); - $organization = $this->organization(); - - if ($externalId !== null && ScimUserModel::query()->where('organization_id', $organization->getKey())->where('external_id', $externalId)->exists()) { - throw ScimException::uniqueness("A user with externalId [{$externalId}] already exists."); - } - - $this->guardDomain($email); - - return DB::transaction(function () use ($data, $email, $externalId, $organization): ScimUserModel { - $user = $this->findByEmail($email); - $created = false; - - if ($user !== null && ScimUserModel::query()->where('organization_id', $organization->getKey())->where('user_id', $user->getKey())->exists()) { - throw ScimException::uniqueness("A user with userName [{$email}] already exists."); - } - - if ($user === null) { - // The organization decides whether its new accounts need approval. - $user = app(CreateUserAction::class)->execute(new CreateUserData(email: $email, name: $this->name($data, $email), status: app(Roster::class)->provisionedStatus($organization))); - $created = true; - } - - $scimUser = ScimUserModel::query()->create([ - 'organization_id' => $organization->getKey(), - 'user_id' => $user->getKey(), - 'external_id' => $externalId, - 'created_by_scim' => $created, - 'active' => true, - ]); - - $this->join($organization, $user, 'scim'); - $this->profile($user, $data); - $this->linkIdentity($user, $externalId, $email); - - if (array_key_exists('active', $data) && ! $this->boolean($data['active'])) { - $this->deprovision($scimUser); - } - - return $scimUser->refresh()->load('user'); - }); - } - - /** - * Apply a full SCIM User (PUT) or a patched view to an existing user. - * - * @param array $data - */ - public function replace(ScimUserModel $scimUser, array $data): ScimUserModel - { - $user = $scimUser->user ?? throw ScimException::notFound('User'); - $email = $this->email($data); - - return DB::transaction(function () use ($scimUser, $user, $data, $email): ScimUserModel { - $emailChanged = strcasecmp((string) $this->users->email($user), $email) !== 0; - - if ($emailChanged) { - $this->guardDomain($email); - } - - $name = $this->name($data, $email); - $nameChanged = $this->users->column('name') !== null && $this->users->name($user) !== $name; - - $changes = new UpdateUserData( - name: $nameChanged ? $name : new Missing, - email: $emailChanged ? $email : new Missing, - ); - - if ($emailChanged || $nameChanged) { - try { - app(UpdateUserAction::class)->execute($user, $changes); - } catch (ValidationException $exception) { - throw ScimException::uniqueness((string) collect($exception->errors())->flatten()->first()); - } - } - - $this->profile($user, $data); - - $externalId = $this->string($data['externalId'] ?? null); - - if ($externalId !== $scimUser->external_id) { - $scimUser->update(['external_id' => $externalId]); - $this->linkIdentity($user, $externalId, $email); - } - - $active = array_key_exists('active', $data) ? $this->boolean($data['active']) : $scimUser->active; - - if ($active && ! $scimUser->active) { - $this->restore($scimUser); - } elseif (! $active && $scimUser->active) { - $this->deprovision($scimUser); - } - - $scimUser->touch(); - - return $scimUser->refresh()->load('user'); - }); - } - - /** - * @param array $operations - */ - public function patch(ScimUserModel $scimUser, array $operations): ScimUserModel - { - $view = app(ScimMapper::class)->user($scimUser); - - return $this->replace($scimUser, PatchApplier::apply($view, $operations)); - } - - /** - * DELETE: deprovision and forget the SCIM resource. - */ - public function delete(ScimUserModel $scimUser): void - { - DB::transaction(function () use ($scimUser): void { - if ($scimUser->active) { - $this->deprovision($scimUser); - } - - $scimUser->delete(); - }); - } - - private function deprovision(ScimUserModel $scimUser): void - { - $user = $scimUser->user; - $organization = $this->organization(); - - if (! $user instanceof Model) { - return; - } - - if ($organization->isOwnedBy($user)) { - throw ScimException::mutability("The organization's owner cannot be deprovisioned. Transfer ownership first."); - } - - if ($organization->membershipFor($user) !== null) { - app(RemoveMemberAction::class)->execute($organization, $user); - } - - $orphaned = ! MembershipModel::query()->where('user_id', $user->getKey())->exists(); - $deactivate = $scimUser->created_by_scim && $orphaned && $this->users->status($user)->allowsAccess(); - - if ($deactivate) { - app(DeactivateUserAction::class)->execute($user, new DeactivateUserData(reason: __('roster::roster.scim_deprovisioned', ['organization' => $organization->name]))); - } - - $scimUser->update(['active' => false, 'deactivated_by_scim' => $deactivate || $scimUser->deactivated_by_scim]); - } - - private function restore(ScimUserModel $scimUser): void - { - $user = $scimUser->user; - - if (! $user instanceof Model) { - return; - } - - if ($scimUser->deactivated_by_scim && $this->users->status($user) === Statuses::users()::deactivated()) { - app(ReactivateUserAction::class)->execute($user); - } - - $this->join($this->organization(), $user, 'scim'); - - $scimUser->update(['active' => true, 'deactivated_by_scim' => false]); - } - - /** - * @param array $data - */ - private function profile(Model $user, array $data): void - { - $display = $this->string($data['displayName'] ?? null); - - // The SCIM view shows the account name when no display name is set; - // echoing that back is not a change. - $current = $this->users->profileIfExists($user)->display_name ?? $this->users->name($user); - - if ($display !== null && $display !== $current) { - app(UpdateProfileAction::class)->execute($user, new UpdateProfileData(displayName: $display)); - } - } - - /** - * Record the IdP's id as the SSO subject, so a later SSO sign-in through - * the token's connection lands on this account. - */ - private function linkIdentity(Model $user, ?string $externalId, string $email): void - { - $connection = $this->context->token?->ssoConnection; - - if ($connection === null || $externalId === null) { - return; - } - - $existing = SsoIdentityModel::query()->where('connection_id', $connection->getKey())->where('subject', $externalId)->first(); - - if ($existing !== null && (string) $existing->user_id !== (string) $user->getKey()) { - throw ScimException::uniqueness("externalId [{$externalId}] is already linked to another account."); - } - - SsoIdentityModel::query()->updateOrCreate( - ['connection_id' => $connection->getKey(), 'subject' => $externalId], - ['user_id' => $user->getKey(), 'email' => $email], - ); - } - - /** - * SCIM may only claim or move accounts onto the organization's domains. - */ - private function guardDomain(string $email): void - { - $domain = strtolower(substr($email, (int) strrpos($email, '@') + 1)); - - if (! $this->organization()->domains()->where('domain', $domain)->exists()) { - throw ScimException::invalidValue("[{$domain}] is not one of the organization's domains."); - } - } - - /** - * @param array $data - */ - private function email(array $data): string - { - $candidates = [$data['userName'] ?? null]; - - foreach ((array) ($data['emails'] ?? []) as $email) { - if (is_array($email)) { - $candidates[] = $email['value'] ?? null; - } - } - - foreach ($candidates as $candidate) { - if (is_string($candidate) && filter_var($candidate, FILTER_VALIDATE_EMAIL) !== false) { - return strtolower($candidate); - } - } - - throw ScimException::invalidValue('userName (or a primary email) must be an email address.'); - } - - /** - * @param array $data - */ - private function name(array $data, string $email): string - { - $name = (array) ($data['name'] ?? []); - $parts = array_filter([$this->string($name['givenName'] ?? null), $this->string($name['familyName'] ?? null)]); - - return $this->string($name['formatted'] ?? null) - ?? ($parts !== [] ? implode(' ', $parts) : null) - ?? $this->string($data['displayName'] ?? null) - ?? Str::before($email, '@'); - } - - private function findByEmail(string $email): ?Model - { - return $this->users->findByEmail($email); - } - - private function organization(): OrganizationModel - { - return $this->context->organization(); - } - - private function boolean(mixed $value): bool - { - return is_string($value) ? in_array(strtolower($value), ['true', '1'], true) : (bool) $value; - } - - private function string(mixed $value): ?string - { - return is_scalar($value) && trim((string) $value) !== '' ? trim((string) $value) : null; - } - - /** - * Resolve the groups of a page of users in two queries, so mapping each - * one adds none. - * - * @param array $scimUsers - */ - private function preloadGroups(array $scimUsers): void - { - $userIds = array_values(array_filter(array_map(fn (ScimUserModel $scimUser): mixed => $scimUser->user_id, $scimUsers))); - - if ($userIds === []) { - return; - } - - $teams = MembershipModel::query() - ->where('organization_id', $this->organization()->getKey()) - ->whereIn('user_id', $userIds) - ->with('teams:id') - ->get() - ->mapWithKeys(fn (MembershipModel $membership): array => [(string) $membership->user_id => $membership->teams->modelKeys()]); - - $groups = ScimGroupModel::query() - ->where('organization_id', $this->organization()->getKey()) - ->whereIn('team_id', $teams->flatten()->unique()->all()) - ->with('team') - ->get(); - - foreach ($scimUsers as $scimUser) { - $mine = $teams->get((string) $scimUser->user_id, []); - $this->context->groups[$scimUser->id] = $groups->filter(fn (ScimGroupModel $group): bool => in_array($group->team_id, $mine, true))->values()->all(); - } - } - - /** - * Groups this user is in, for the `groups` attribute. - * - * @return array - */ - public function groupsOf(ScimUserModel $scimUser): array - { - if (array_key_exists($scimUser->id, $this->context->groups)) { - return $this->context->groups[$scimUser->id]; - } - - $membership = $scimUser->user instanceof Model ? $this->organization()->membershipFor($scimUser->user) : null; - - if ($membership === null) { - return []; - } - - return ScimGroupModel::query() - ->where('organization_id', $this->organization()->getKey()) - ->whereIn('team_id', $membership->teams()->pluck(Tables::name('teams').'.id')) - ->with('team') - ->get() - ->all(); - } -} diff --git a/src/Domains/Scim/routes.php b/src/Domains/Scim/routes.php deleted file mode 100644 index 99a4c1c..0000000 --- a/src/Domains/Scim/routes.php +++ /dev/null @@ -1,10 +0,0 @@ -name('organizations.scim-tokens.index'); -Route::post('organizations/{organization}/scim-tokens', [ScimTokenController::class, 'store'])->name('organizations.scim-tokens.store'); -Route::delete('scim-tokens/{token}', [ScimTokenController::class, 'destroy'])->name('scim-tokens.destroy'); diff --git a/src/Domains/Scim/scim.php b/src/Domains/Scim/scim.php deleted file mode 100644 index 09e1ecd..0000000 --- a/src/Domains/Scim/scim.php +++ /dev/null @@ -1,38 +0,0 @@ - $middleware */ -$middleware = config('roster.scim.middleware', ['api', 'throttle:roster']); - -Route::middleware([...$middleware, AuthenticateScimToken::class]) - ->prefix(trim((string) config('roster.scim.prefix', 'scim/v2'), '/').'/{organization}') - ->name('roster.scim.') - ->group(function (): void { - Route::get('Users', [ScimController::class, 'listUsers'])->name('users.index'); - Route::post('Users', [ScimController::class, 'createUser'])->name('users.store'); - Route::get('Users/{id}', [ScimController::class, 'showUser'])->name('users.show'); - Route::put('Users/{id}', [ScimController::class, 'replaceUser'])->name('users.replace'); - Route::patch('Users/{id}', [ScimController::class, 'patchUser'])->name('users.patch'); - Route::delete('Users/{id}', [ScimController::class, 'deleteUser'])->name('users.destroy'); - - Route::get('Groups', [ScimController::class, 'listGroups'])->name('groups.index'); - Route::post('Groups', [ScimController::class, 'createGroup'])->name('groups.store'); - Route::get('Groups/{id}', [ScimController::class, 'showGroup'])->name('groups.show'); - Route::put('Groups/{id}', [ScimController::class, 'replaceGroup'])->name('groups.replace'); - Route::patch('Groups/{id}', [ScimController::class, 'patchGroup'])->name('groups.patch'); - Route::delete('Groups/{id}', [ScimController::class, 'deleteGroup'])->name('groups.destroy'); - - Route::post('Bulk', [ScimController::class, 'bulk'])->name('bulk'); - Route::get('ServiceProviderConfig', [ScimController::class, 'serviceProviderConfig'])->name('config'); - Route::get('ResourceTypes', [ScimController::class, 'resourceTypes'])->name('resource-types'); - Route::get('Schemas', [ScimController::class, 'schemas'])->name('schemas'); - }); diff --git a/src/Domains/Sso/Actions/CreateSsoConnectionAction.php b/src/Domains/Sso/Actions/CreateSsoConnectionAction.php deleted file mode 100644 index 0c33dee..0000000 --- a/src/Domains/Sso/Actions/CreateSsoConnectionAction.php +++ /dev/null @@ -1,53 +0,0 @@ -protocol; - $settings = $this->settings($protocol, $data); - - SsoConnectionCreatingActionEvent::dispatch($organization, $data); - - $connection = DB::transaction(fn (): SsoConnectionModel => SsoConnectionModel::query()->create([ - 'organization_id' => $organization->getKey(), - 'name' => $data->name, - 'slug' => $data->slug !== null && $data->slug !== '' - ? $data->slug - : Slugs::unique($organization->slug.'-'.$data->name, SsoConnectionModel::query()), - 'protocol' => $protocol, - 'config' => $settings, - 'jit' => $data->jit, - 'enforced' => $data->enforced, - 'enabled' => $data->enabled, - ])); - - $connection->load('organization')->loadCount('identities'); - - SsoConnectionCreatedActionEvent::dispatch($connection); - - return $connection; - } -} diff --git a/src/Domains/Sso/Actions/DeleteSsoConnectionAction.php b/src/Domains/Sso/Actions/DeleteSsoConnectionAction.php deleted file mode 100644 index 410690f..0000000 --- a/src/Domains/Sso/Actions/DeleteSsoConnectionAction.php +++ /dev/null @@ -1,25 +0,0 @@ - $connection->delete()); - - SsoConnectionDeletedActionEvent::dispatch($connection); - } -} diff --git a/src/Domains/Sso/Actions/LinkSsoIdentityAction.php b/src/Domains/Sso/Actions/LinkSsoIdentityAction.php deleted file mode 100644 index c950ce8..0000000 --- a/src/Domains/Sso/Actions/LinkSsoIdentityAction.php +++ /dev/null @@ -1,45 +0,0 @@ -where('connection_id', $connection->getKey()) - ->where('subject', $claims->subject) - ->where('user_id', '!=', $user->getKey()) - ->exists(); - - if ($taken) { - throw ValidationException::withMessages(['sso' => __('roster::roster.sso_identity_taken')]); - } - - SsoIdentityLinkingActionEvent::dispatch($user, $connection); - - $identity = DB::transaction(fn (): SsoIdentityModel => SsoIdentityModel::query()->updateOrCreate( - ['connection_id' => $connection->getKey(), 'subject' => $claims->subject], - ['user_id' => $user->getKey(), 'email' => $claims->email], - )); - - SsoIdentityLinkedActionEvent::dispatch($user, $connection); - - return $identity; - } -} diff --git a/src/Domains/Sso/Actions/ListSsoConnectionsAction.php b/src/Domains/Sso/Actions/ListSsoConnectionsAction.php deleted file mode 100644 index 7e1538b..0000000 --- a/src/Domains/Sso/Actions/ListSsoConnectionsAction.php +++ /dev/null @@ -1,38 +0,0 @@ - - */ - public function execute(ListSsoConnectionsData $filters = new ListSsoConnectionsData): LengthAwarePaginator - { - SsoConnectionsListingActionEvent::dispatch($filters); - - $query = SsoConnectionModel::query()->with('organization')->withCount('identities'); - $organization = $this->organizationFrom($filters->organization); - - if ($organization !== null) { - $query->where('organization_id', $organization->getKey()); - } - - $connections = $query->orderBy('name')->orderBy('id')->paginate($filters->perPage, ['*'], 'page', $filters->page); - - SsoConnectionsListedActionEvent::dispatch($filters); - - return $connections; - } -} diff --git a/src/Domains/Sso/Actions/ListSsoIdentitiesAction.php b/src/Domains/Sso/Actions/ListSsoIdentitiesAction.php deleted file mode 100644 index d1a044a..0000000 --- a/src/Domains/Sso/Actions/ListSsoIdentitiesAction.php +++ /dev/null @@ -1,47 +0,0 @@ - - */ - public function execute(ListSsoIdentitiesData $filters = new ListSsoIdentitiesData): LengthAwarePaginator - { - SsoIdentitiesListingActionEvent::dispatch($filters); - - $query = SsoIdentityModel::query()->with(['connection.organization', 'user']); - - if ($filters->user !== null) { - $query->where('user_id', $this->users->resolve($filters->user)->getKey()); - } - - $organization = $this->organizationFrom($filters->organization); - - if ($organization !== null) { - $query->whereHas('connection', fn (Builder $connection): Builder => $connection->where('organization_id', $organization->getKey())); - } - - $identities = $query->latest()->latest('id')->paginate($filters->perPage, ['*'], 'page', $filters->page); - - SsoIdentitiesListedActionEvent::dispatch($filters); - - return $identities; - } -} diff --git a/src/Domains/Sso/Actions/ShowSsoConnectionAction.php b/src/Domains/Sso/Actions/ShowSsoConnectionAction.php deleted file mode 100644 index c613c69..0000000 --- a/src/Domains/Sso/Actions/ShowSsoConnectionAction.php +++ /dev/null @@ -1,23 +0,0 @@ -loadMissing('organization')->loadCount('identities'); - - SsoConnectionShownActionEvent::dispatch($connection); - - return $connection; - } -} diff --git a/src/Domains/Sso/Actions/SsoLoginAction.php b/src/Domains/Sso/Actions/SsoLoginAction.php deleted file mode 100644 index f46f10a..0000000 --- a/src/Domains/Sso/Actions/SsoLoginAction.php +++ /dev/null @@ -1,170 +0,0 @@ -enabled) { - SsoLoginFailedActionEvent::dispatch($connection, $claims->email, 'disabled'); - - throw ValidationException::withMessages(['sso' => __('roster::roster.sso_failed_disabled')]); - } - - try { - [$user, $method] = $this->signIn($connection, $claims); - - // After the transaction: an account waiting for approval (just - // created, or earlier) is kept, linked and a member - only the - // sign-in is refused. - if ($this->users->status($user) === Statuses::users()::pending()) { - $this->fail($connection, $claims, 'pending'); - } - } catch (SsoLoginRefused $refused) { - // Recorded outside the transaction, so the rollback cannot erase it. - SsoLoginFailedActionEvent::dispatch($connection, $claims->email, $refused->reason); - - throw ValidationException::withMessages(['sso' => __('roster::roster.sso_failed_'.$refused->reason)]); - } - - SsoLoginSucceededActionEvent::dispatch($user, $connection, $method); - - return [$user, $method]; - } - - /** - * @return array{0: Model, 1: string} - */ - private function signIn(SsoConnectionModel $connection, IdentityClaims $claims): array - { - return DB::transaction(function () use ($connection, $claims): array { - $identity = SsoIdentityModel::query() - ->where('connection_id', $connection->getKey()) - ->where('subject', $claims->subject) - ->first(); - - if ($identity !== null && $identity->user instanceof Model) { - [$user, $method] = [$identity->user, self::BY_IDENTITY]; - } else { - [$user, $method] = $this->linkOrCreate($connection, $claims); - } - - $status = $this->users->status($user); - - if (! $status->allowsAccess() && $status !== Statuses::users()::pending()) { - $this->fail($connection, $claims, 'inactive'); - } - - /** @var OrganizationModel $organization */ - $organization = $connection->organization; - $this->join($organization, $user, MembershipSource::Domain); - - SsoIdentityModel::query()->updateOrCreate( - ['connection_id' => $connection->getKey(), 'subject' => $claims->subject], - ['user_id' => $user->getKey(), 'email' => $claims->email, 'last_login_at' => now()], - ); - - return [$user, $method]; - }); - } - - /** - * @return array{0: Model, 1: string} - */ - private function linkOrCreate(SsoConnectionModel $connection, IdentityClaims $claims): array - { - $email = $claims->email; - - if ($email === null || ! $connection->trusts($email)) { - $this->fail($connection, $claims, 'untrusted_email'); - } - - $existing = $this->findByEmail($email); - - if ($existing !== null) { - return [$existing, self::BY_LINK]; - } - - if (! $connection->jit) { - $this->fail($connection, $claims, 'no_account'); - } - - /** @var OrganizationModel $organization */ - $organization = $connection->organization; - - $user = app(CreateUserAction::class)->execute(new CreateUserData( - email: $email, - name: $claims->name ?? Str::before($email, '@'), - // The organization decides whether its new accounts need approval. - status: app(Roster::class)->provisionedStatus($organization), - )); - - // The identity provider is authoritative for this domain, so the - // address counts as verified (where the users table tracks that). - if ($this->hasVerifiedColumn($user) && $user->getAttribute('email_verified_at') === null) { - $user->forceFill(['email_verified_at' => now()])->save(); - } - - return [$user, self::BY_JIT]; - } - - private function hasVerifiedColumn(Model $user): bool - { - return $user->getConnection()->getSchemaBuilder()->hasColumn($user->getTable(), 'email_verified_at'); - } - - private function findByEmail(string $email): ?Model - { - return $this->users->findByEmail($email); - } - - private function fail(SsoConnectionModel $connection, IdentityClaims $claims, string $reason): never - { - throw new SsoLoginRefused($reason); - } -} diff --git a/src/Domains/Sso/Actions/UnlinkSsoIdentityAction.php b/src/Domains/Sso/Actions/UnlinkSsoIdentityAction.php deleted file mode 100644 index 1e2eb9b..0000000 --- a/src/Domains/Sso/Actions/UnlinkSsoIdentityAction.php +++ /dev/null @@ -1,26 +0,0 @@ - $identity->delete()); - - SsoIdentityUnlinkedActionEvent::dispatch($identity); - } -} diff --git a/src/Domains/Sso/Actions/UpdateSsoConnectionAction.php b/src/Domains/Sso/Actions/UpdateSsoConnectionAction.php deleted file mode 100644 index 77075ec..0000000 --- a/src/Domains/Sso/Actions/UpdateSsoConnectionAction.php +++ /dev/null @@ -1,39 +0,0 @@ -settings($connection->protocol, $data, $connection->config); - - SsoConnectionUpdatingActionEvent::dispatch($connection, $data); - - DB::transaction(fn () => $connection->update( - Arr::only($data->toArray(), ['name', 'slug', 'jit', 'enforced', 'enabled']) + ['config' => $settings], - )); - - $connection = $connection->refresh()->load('organization')->loadCount('identities'); - - SsoConnectionUpdatedActionEvent::dispatch($connection); - - return $connection; - } -} diff --git a/src/Domains/Sso/Concerns/SsoConnectionRules.php b/src/Domains/Sso/Concerns/SsoConnectionRules.php deleted file mode 100644 index c4ff559..0000000 --- a/src/Domains/Sso/Concerns/SsoConnectionRules.php +++ /dev/null @@ -1,115 +0,0 @@ -> */ - private const array SETTINGS = [ - SsoConnectionModel::OIDC => ['issuer', 'client_id', 'client_secret'], - SsoConnectionModel::AZURE => ['tenant', 'client_id', 'client_secret'], - SsoConnectionModel::SAML => ['metadata_url', 'entity_id', 'sso_url', 'certificate'], - ]; - - /** - * @return array> - */ - protected static function settingRules(): array - { - return [ - 'issuer' => ['sometimes', 'nullable', 'url', 'max:2048'], - 'tenant' => ['sometimes', 'nullable', 'string', 'max:255', Rule::notIn(['common', 'organizations', 'consumers'])], - 'client_id' => ['sometimes', 'nullable', 'string', 'max:255'], - 'client_secret' => ['sometimes', 'nullable', 'string', 'max:2048'], - 'metadata_url' => ['sometimes', 'nullable', 'url', 'max:2048'], - 'entity_id' => ['sometimes', 'nullable', 'string', 'max:2048'], - 'sso_url' => ['sometimes', 'nullable', 'url', 'max:2048'], - 'certificate' => ['sometimes', 'nullable', 'string', 'max:20000'], - 'jit' => ['sometimes', 'boolean'], - 'enforced' => ['sometimes', 'boolean'], - 'enabled' => ['sometimes', 'boolean'], - ]; - } - - /** - * The protocol's settings from input over the current ones. A blank - * client secret keeps the stored one. - * - * @param array $current - * @return array - */ - private function settings(string $protocol, CreateSsoConnectionData|UpdateSsoConnectionData $data, array $current = []): array - { - $settings = []; - - foreach (self::SETTINGS[$protocol] ?? [] as $key) { - $given = self::given($data, $key); - $value = ! $given instanceof Missing && ! ($key === 'client_secret' && blank($given)) - ? $given - : ($current[$key] ?? null); - - if (is_string($value) && $value !== '') { - $settings[$key] = trim($value); - } - } - - $this->guardSettings($protocol, $settings); - - return $settings; - } - - /** - * The input's value for a setting; Missing when it was left out. - */ - private static function given(CreateSsoConnectionData|UpdateSsoConnectionData $data, string $key): string|Missing|null - { - return match ($key) { - 'issuer' => $data->issuer, - 'tenant' => $data->tenant, - 'client_id' => $data->clientId, - 'client_secret' => $data->clientSecret, - 'metadata_url' => $data->metadataUrl, - 'entity_id' => $data->entityId, - 'sso_url' => $data->ssoUrl, - 'certificate' => $data->certificate, - default => new Missing, - }; - } - - /** - * @param array $settings - */ - private function guardSettings(string $protocol, array $settings): void - { - $required = match ($protocol) { - SsoConnectionModel::OIDC => ['issuer', 'client_id', 'client_secret'], - SsoConnectionModel::AZURE => ['tenant', 'client_id', 'client_secret'], - default => isset($settings['metadata_url']) ? ['metadata_url'] : ['entity_id', 'sso_url', 'certificate'], - }; - - foreach ($required as $key) { - if (! isset($settings[$key])) { - throw ValidationException::withMessages([$key => __('roster::roster.sso_setting_required', ['setting' => $key])]); - } - } - - // Identity providers must be reached over HTTPS, outside local work. - foreach (['issuer', 'metadata_url', 'sso_url'] as $key) { - if (isset($settings[$key]) && ! str_starts_with($settings[$key], 'https://') && ! app()->environment('local', 'testing')) { - throw ValidationException::withMessages([$key => __('roster::roster.sso_https_required')]); - } - } - } -} diff --git a/src/Domains/Sso/Data/CreateSsoConnectionData.php b/src/Domains/Sso/Data/CreateSsoConnectionData.php deleted file mode 100644 index 23601a9..0000000 --- a/src/Domains/Sso/Data/CreateSsoConnectionData.php +++ /dev/null @@ -1,53 +0,0 @@ -> - */ - public static function rules(): array - { - return [ - 'name' => ['required', 'string', 'max:255'], - 'slug' => ['sometimes', 'nullable', 'string', 'alpha_dash', 'max:255', Rule::unique(SsoConnectionModel::class, 'slug')], - 'protocol' => ['required', Rule::in(SsoConnectionModel::PROTOCOLS)], - ] + self::settingRules(); - } -} diff --git a/src/Domains/Sso/Data/IdentityClaims.php b/src/Domains/Sso/Data/IdentityClaims.php deleted file mode 100644 index 83b0b04..0000000 --- a/src/Domains/Sso/Data/IdentityClaims.php +++ /dev/null @@ -1,21 +0,0 @@ - $raw - */ - public function __construct( - public string $subject, - public ?string $email, - public ?string $name, - public array $raw = [], - ) {} -} diff --git a/src/Domains/Sso/Data/ListSsoConnectionsData.php b/src/Domains/Sso/Data/ListSsoConnectionsData.php deleted file mode 100644 index 8323c98..0000000 --- a/src/Domains/Sso/Data/ListSsoConnectionsData.php +++ /dev/null @@ -1,40 +0,0 @@ -> - */ - public static function rules(): array - { - return [ - 'organization' => ['sometimes', 'nullable', 'string'], - ] + self::pagination()->rules(); - } -} diff --git a/src/Domains/Sso/Data/ListSsoIdentitiesData.php b/src/Domains/Sso/Data/ListSsoIdentitiesData.php deleted file mode 100644 index 4e7eebd..0000000 --- a/src/Domains/Sso/Data/ListSsoIdentitiesData.php +++ /dev/null @@ -1,42 +0,0 @@ -> - */ - public static function rules(): array - { - return [ - 'user' => ['sometimes', 'nullable'], - 'organization' => ['sometimes', 'nullable', 'string'], - ] + self::pagination()->rules(); - } -} diff --git a/src/Domains/Sso/Data/UpdateSsoConnectionData.php b/src/Domains/Sso/Data/UpdateSsoConnectionData.php deleted file mode 100644 index b3da478..0000000 --- a/src/Domains/Sso/Data/UpdateSsoConnectionData.php +++ /dev/null @@ -1,56 +0,0 @@ -> - */ - public static function rules(?SsoConnectionModel $connection = null): array - { - $slug = Rule::unique(SsoConnectionModel::class, 'slug'); - - if ($connection !== null) { - $slug->ignore($connection->getKey()); - } - - return [ - 'name' => ['sometimes', 'required', 'string', 'max:255'], - 'slug' => ['sometimes', 'required', 'string', 'alpha_dash', 'max:255', $slug], - ] + self::settingRules(); - } -} diff --git a/src/Domains/Sso/Events/SsoConnectionCreatedActionEvent.php b/src/Domains/Sso/Events/SsoConnectionCreatedActionEvent.php deleted file mode 100644 index 8f1f480..0000000 --- a/src/Domains/Sso/Events/SsoConnectionCreatedActionEvent.php +++ /dev/null @@ -1,23 +0,0 @@ -ssoConnection; - } - - public function hook(): string - { - return 'created'; - } -} diff --git a/src/Domains/Sso/Events/SsoConnectionCreatingActionEvent.php b/src/Domains/Sso/Events/SsoConnectionCreatingActionEvent.php deleted file mode 100644 index c1ed5af..0000000 --- a/src/Domains/Sso/Events/SsoConnectionCreatingActionEvent.php +++ /dev/null @@ -1,25 +0,0 @@ -ssoConnection; - } - - public function hook(): string - { - return 'creating'; - } -} diff --git a/src/Domains/Sso/Events/SsoConnectionDeletedActionEvent.php b/src/Domains/Sso/Events/SsoConnectionDeletedActionEvent.php deleted file mode 100644 index 3ceda7e..0000000 --- a/src/Domains/Sso/Events/SsoConnectionDeletedActionEvent.php +++ /dev/null @@ -1,23 +0,0 @@ -ssoConnection; - } - - public function hook(): string - { - return 'deleted'; - } -} diff --git a/src/Domains/Sso/Events/SsoConnectionDeletingActionEvent.php b/src/Domains/Sso/Events/SsoConnectionDeletingActionEvent.php deleted file mode 100644 index 4afc29c..0000000 --- a/src/Domains/Sso/Events/SsoConnectionDeletingActionEvent.php +++ /dev/null @@ -1,23 +0,0 @@ -ssoConnection; - } - - public function hook(): string - { - return 'deleting'; - } -} diff --git a/src/Domains/Sso/Events/SsoConnectionReplicatingEvent.php b/src/Domains/Sso/Events/SsoConnectionReplicatingEvent.php deleted file mode 100644 index a51df9f..0000000 --- a/src/Domains/Sso/Events/SsoConnectionReplicatingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -ssoConnection; - } - - public function hook(): string - { - return 'replicating'; - } -} diff --git a/src/Domains/Sso/Events/SsoConnectionRetrievedEvent.php b/src/Domains/Sso/Events/SsoConnectionRetrievedEvent.php deleted file mode 100644 index 16505e0..0000000 --- a/src/Domains/Sso/Events/SsoConnectionRetrievedEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -ssoConnection; - } - - public function hook(): string - { - return 'retrieved'; - } -} diff --git a/src/Domains/Sso/Events/SsoConnectionSavedEvent.php b/src/Domains/Sso/Events/SsoConnectionSavedEvent.php deleted file mode 100644 index 3acb979..0000000 --- a/src/Domains/Sso/Events/SsoConnectionSavedEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -ssoConnection; - } - - public function hook(): string - { - return 'saved'; - } -} diff --git a/src/Domains/Sso/Events/SsoConnectionSavingEvent.php b/src/Domains/Sso/Events/SsoConnectionSavingEvent.php deleted file mode 100644 index 51aa96d..0000000 --- a/src/Domains/Sso/Events/SsoConnectionSavingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -ssoConnection; - } - - public function hook(): string - { - return 'saving'; - } -} diff --git a/src/Domains/Sso/Events/SsoConnectionShowingActionEvent.php b/src/Domains/Sso/Events/SsoConnectionShowingActionEvent.php deleted file mode 100644 index bbe39a7..0000000 --- a/src/Domains/Sso/Events/SsoConnectionShowingActionEvent.php +++ /dev/null @@ -1,23 +0,0 @@ -ssoConnection; - } - - public function hook(): string - { - return 'updated'; - } -} diff --git a/src/Domains/Sso/Events/SsoConnectionUpdatingActionEvent.php b/src/Domains/Sso/Events/SsoConnectionUpdatingActionEvent.php deleted file mode 100644 index 59e8783..0000000 --- a/src/Domains/Sso/Events/SsoConnectionUpdatingActionEvent.php +++ /dev/null @@ -1,25 +0,0 @@ -ssoConnection; - } - - public function hook(): string - { - return 'updating'; - } -} diff --git a/src/Domains/Sso/Events/SsoConnectionsListedActionEvent.php b/src/Domains/Sso/Events/SsoConnectionsListedActionEvent.php deleted file mode 100644 index 9ae00bd..0000000 --- a/src/Domains/Sso/Events/SsoConnectionsListedActionEvent.php +++ /dev/null @@ -1,23 +0,0 @@ -ssoIdentity; - } - - public function hook(): string - { - return 'created'; - } -} diff --git a/src/Domains/Sso/Events/SsoIdentityCreatingEvent.php b/src/Domains/Sso/Events/SsoIdentityCreatingEvent.php deleted file mode 100644 index 18208ef..0000000 --- a/src/Domains/Sso/Events/SsoIdentityCreatingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -ssoIdentity; - } - - public function hook(): string - { - return 'creating'; - } -} diff --git a/src/Domains/Sso/Events/SsoIdentityDeletedEvent.php b/src/Domains/Sso/Events/SsoIdentityDeletedEvent.php deleted file mode 100644 index 611d6d8..0000000 --- a/src/Domains/Sso/Events/SsoIdentityDeletedEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -ssoIdentity; - } - - public function hook(): string - { - return 'deleted'; - } -} diff --git a/src/Domains/Sso/Events/SsoIdentityDeletingEvent.php b/src/Domains/Sso/Events/SsoIdentityDeletingEvent.php deleted file mode 100644 index d27edcf..0000000 --- a/src/Domains/Sso/Events/SsoIdentityDeletingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -ssoIdentity; - } - - public function hook(): string - { - return 'deleting'; - } -} diff --git a/src/Domains/Sso/Events/SsoIdentityLinkedActionEvent.php b/src/Domains/Sso/Events/SsoIdentityLinkedActionEvent.php deleted file mode 100644 index 2e5c7b0..0000000 --- a/src/Domains/Sso/Events/SsoIdentityLinkedActionEvent.php +++ /dev/null @@ -1,25 +0,0 @@ -ssoIdentity; - } - - public function hook(): string - { - return 'replicating'; - } -} diff --git a/src/Domains/Sso/Events/SsoIdentityRetrievedEvent.php b/src/Domains/Sso/Events/SsoIdentityRetrievedEvent.php deleted file mode 100644 index 13fd261..0000000 --- a/src/Domains/Sso/Events/SsoIdentityRetrievedEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -ssoIdentity; - } - - public function hook(): string - { - return 'retrieved'; - } -} diff --git a/src/Domains/Sso/Events/SsoIdentitySavedEvent.php b/src/Domains/Sso/Events/SsoIdentitySavedEvent.php deleted file mode 100644 index 3e259bf..0000000 --- a/src/Domains/Sso/Events/SsoIdentitySavedEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -ssoIdentity; - } - - public function hook(): string - { - return 'saved'; - } -} diff --git a/src/Domains/Sso/Events/SsoIdentitySavingEvent.php b/src/Domains/Sso/Events/SsoIdentitySavingEvent.php deleted file mode 100644 index 63d655a..0000000 --- a/src/Domains/Sso/Events/SsoIdentitySavingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -ssoIdentity; - } - - public function hook(): string - { - return 'saving'; - } -} diff --git a/src/Domains/Sso/Events/SsoIdentityUnlinkedActionEvent.php b/src/Domains/Sso/Events/SsoIdentityUnlinkedActionEvent.php deleted file mode 100644 index c1d4ce2..0000000 --- a/src/Domains/Sso/Events/SsoIdentityUnlinkedActionEvent.php +++ /dev/null @@ -1,23 +0,0 @@ -ssoIdentity; - } - - public function hook(): string - { - return 'updated'; - } -} diff --git a/src/Domains/Sso/Events/SsoIdentityUpdatingEvent.php b/src/Domains/Sso/Events/SsoIdentityUpdatingEvent.php deleted file mode 100644 index 4d39a57..0000000 --- a/src/Domains/Sso/Events/SsoIdentityUpdatingEvent.php +++ /dev/null @@ -1,32 +0,0 @@ -ssoIdentity; - } - - public function hook(): string - { - return 'updating'; - } -} diff --git a/src/Domains/Sso/Events/SsoLoginFailedActionEvent.php b/src/Domains/Sso/Events/SsoLoginFailedActionEvent.php deleted file mode 100644 index 587cf29..0000000 --- a/src/Domains/Sso/Events/SsoLoginFailedActionEvent.php +++ /dev/null @@ -1,25 +0,0 @@ - 'laravel/socialite socialiteproviders/saml2', - 'azure' => 'laravel/socialite socialiteproviders/microsoft-azure', - default => 'laravel/socialite firebase/php-jwt', - }; - - return new self("Single sign-on with [{$protocol}] needs: composer require {$packages}"); - } -} diff --git a/src/Domains/Sso/Http/Controllers/SsoController.php b/src/Domains/Sso/Http/Controllers/SsoController.php deleted file mode 100644 index 809849a..0000000 --- a/src/Domains/Sso/Http/Controllers/SsoController.php +++ /dev/null @@ -1,53 +0,0 @@ -persist(); - } - - public function store(StoreSsoConnectionRequest $request): JsonResponse - { - return $request->persist(); - } - - public function show(ShowSsoConnectionRequest $request): JsonResponse - { - return $request->persist(); - } - - public function update(UpdateSsoConnectionRequest $request): JsonResponse - { - return $request->persist(); - } - - public function destroy(DestroySsoConnectionRequest $request): Response - { - return $request->persist(); - } - - public function identities(IndexUserSsoIdentitiesRequest $request): JsonResponse - { - return $request->persist(); - } - - public function unlink(DestroySsoIdentityRequest $request): Response - { - return $request->persist(); - } -} diff --git a/src/Domains/Sso/Http/Controllers/SsoWebController.php b/src/Domains/Sso/Http/Controllers/SsoWebController.php deleted file mode 100644 index 5d9d8ef..0000000 --- a/src/Domains/Sso/Http/Controllers/SsoWebController.php +++ /dev/null @@ -1,136 +0,0 @@ -validate(['email' => ['required', 'email']])['email']; - $domain = strtolower(substr($email, (int) strrpos($email, '@') + 1)); - - $connection = SsoConnectionModel::query() - ->where('enabled', true) - ->whereHas('organization.domains', fn (Builder $query): Builder => $query->where('domain', $domain)) - ->orderByDesc('enforced') - ->first(); - - if ($connection === null) { - throw ValidationException::withMessages(['email' => __('roster::roster.sso_not_found')]); - } - - return redirect()->route('roster.sso.start', $connection->slug); - } - - public function start(Request $request, string $connection): Response - { - $model = $this->connection($connection); - $request->session()->put(self::INTENT, 'login'); - - return $this->sso->provider($model)->redirect(); - } - - /** - * Prove an identity at the provider and link it to the signed-in account. - */ - public function link(Request $request, string $connection): Response - { - $model = $this->connection($connection); - $request->session()->put(self::INTENT, 'link'); - - return $this->sso->provider($model)->redirect(); - } - - public function callback(Request $request, string $connection): RedirectResponse - { - $model = $this->connection($connection); - $intent = $request->session()->pull(self::INTENT, 'login'); - - try { - $claims = $this->sso->claims($model, $this->sso->provider($model)->user()); - } catch (Throwable) { - SsoLoginFailedActionEvent::dispatch($model, null, 'invalid_response'); - - return $this->failed(__('roster::roster.sso_failed_invalid_response')); - } - - try { - if ($intent === 'link') { - $user = $request->user(); - abort_unless($user instanceof Model, 401); - - app(LinkSsoIdentityAction::class)->execute($user, $model, $claims); - - return redirect((string) config('roster.sso.redirect', '/'))->with('status', __('roster::roster.sso_linked')); - } - - [$user] = app(SsoLoginAction::class)->execute($model, $claims); - } catch (ValidationException $exception) { - return $this->failed((string) collect($exception->errors())->flatten()->first()); - } - - if ($user instanceof Authenticatable) { - Auth::guard()->login($user); - $request->session()->regenerate(); - } - - return redirect()->intended((string) config('roster.sso.redirect', '/')); - } - - /** - * SAML service provider metadata for the identity provider's admin. - */ - public function metadata(string $connection): Response - { - $model = $this->connection($connection); - abort_unless($model->protocol === SsoConnectionModel::SAML, 404); - - /** @var Provider $provider */ - $provider = $this->sso->provider($model); - - return $provider->getServiceProviderMetadata(); - } - - private function connection(string $slug): SsoConnectionModel - { - $connection = SsoConnectionModel::query()->where('slug', $slug)->firstOrFail(); - - abort_unless($connection->enabled, 404); - - return $connection; - } - - private function failed(string $message): RedirectResponse - { - return redirect((string) config('roster.sso.redirect', '/'))->withErrors(['sso' => $message]); - } -} diff --git a/src/Domains/Sso/Http/Requests/DestroySsoConnectionRequest.php b/src/Domains/Sso/Http/Requests/DestroySsoConnectionRequest.php deleted file mode 100644 index e4ac47d..0000000 --- a/src/Domains/Sso/Http/Requests/DestroySsoConnectionRequest.php +++ /dev/null @@ -1,23 +0,0 @@ -execute($this->connection()); - - return response()->noContent(); - } -} diff --git a/src/Domains/Sso/Http/Requests/DestroySsoIdentityRequest.php b/src/Domains/Sso/Http/Requests/DestroySsoIdentityRequest.php deleted file mode 100644 index 931a0f6..0000000 --- a/src/Domains/Sso/Http/Requests/DestroySsoIdentityRequest.php +++ /dev/null @@ -1,49 +0,0 @@ -identity()->connection?->organization; - } - - /** - * Anyone may unlink their own identity. - */ - protected function self(): ?Model - { - $actor = $this->actor(); - - return $this->identity()->ownedBy($actor) ? $actor : null; - } - - private function identity(): SsoIdentityModel - { - return $this->resolved ??= SsoIdentityModel::query()->whereKey($this->route('identity'))->firstOrFail(); - } - - public function persist(): Response - { - app(UnlinkSsoIdentityAction::class)->execute($this->identity()); - - return response()->noContent(); - } -} diff --git a/src/Domains/Sso/Http/Requests/IndexSsoConnectionsRequest.php b/src/Domains/Sso/Http/Requests/IndexSsoConnectionsRequest.php deleted file mode 100644 index f2cd8fd..0000000 --- a/src/Domains/Sso/Http/Requests/IndexSsoConnectionsRequest.php +++ /dev/null @@ -1,29 +0,0 @@ -execute(ListSsoConnectionsData::fromValidated(['organization' => $this->organization()->slug] + $this->validated())))->response(); - } -} diff --git a/src/Domains/Sso/Http/Requests/IndexUserSsoIdentitiesRequest.php b/src/Domains/Sso/Http/Requests/IndexUserSsoIdentitiesRequest.php deleted file mode 100644 index 17969ec..0000000 --- a/src/Domains/Sso/Http/Requests/IndexUserSsoIdentitiesRequest.php +++ /dev/null @@ -1,35 +0,0 @@ -targetUser(); - } - - public function rules(): array - { - return ListSsoIdentitiesData::rules(); - } - - public function persist(): JsonResponse - { - return SsoIdentityResource::collection(app(ListSsoIdentitiesAction::class)->execute(ListSsoIdentitiesData::fromValidated(['user' => $this->targetUser()->getRouteKey()] + $this->validated())))->response(); - } -} diff --git a/src/Domains/Sso/Http/Requests/ShowSsoConnectionRequest.php b/src/Domains/Sso/Http/Requests/ShowSsoConnectionRequest.php deleted file mode 100644 index 0ed72b9..0000000 --- a/src/Domains/Sso/Http/Requests/ShowSsoConnectionRequest.php +++ /dev/null @@ -1,22 +0,0 @@ -execute($this->connection())))->response(); - } -} diff --git a/src/Domains/Sso/Http/Requests/SsoConnectionRequest.php b/src/Domains/Sso/Http/Requests/SsoConnectionRequest.php deleted file mode 100644 index 35d105a..0000000 --- a/src/Domains/Sso/Http/Requests/SsoConnectionRequest.php +++ /dev/null @@ -1,24 +0,0 @@ -resolved ??= SsoConnectionModel::query()->where('slug', $this->route('connection'))->firstOrFail(); - } - - protected function scope(): ?OrganizationModel - { - return $this->connection()->organization; - } -} diff --git a/src/Domains/Sso/Http/Requests/StoreSsoConnectionRequest.php b/src/Domains/Sso/Http/Requests/StoreSsoConnectionRequest.php deleted file mode 100644 index 7caa370..0000000 --- a/src/Domains/Sso/Http/Requests/StoreSsoConnectionRequest.php +++ /dev/null @@ -1,31 +0,0 @@ -execute($this->organization(), CreateSsoConnectionData::fromValidated($this->validated())); - - return (new SsoConnectionResource($connection))->response()->setStatusCode(201); - } -} diff --git a/src/Domains/Sso/Http/Requests/UpdateSsoConnectionRequest.php b/src/Domains/Sso/Http/Requests/UpdateSsoConnectionRequest.php deleted file mode 100644 index 2a87adf..0000000 --- a/src/Domains/Sso/Http/Requests/UpdateSsoConnectionRequest.php +++ /dev/null @@ -1,28 +0,0 @@ -connection()); - } - - public function persist(): JsonResponse - { - return (new SsoConnectionResource(app(UpdateSsoConnectionAction::class)->execute($this->connection(), UpdateSsoConnectionData::fromValidated($this->validated()))))->response(); - } -} diff --git a/src/Domains/Sso/Mcp/Requests/CreateSsoConnectionMcpRequest.php b/src/Domains/Sso/Mcp/Requests/CreateSsoConnectionMcpRequest.php deleted file mode 100644 index 3dd144c..0000000 --- a/src/Domains/Sso/Mcp/Requests/CreateSsoConnectionMcpRequest.php +++ /dev/null @@ -1,31 +0,0 @@ -organizationRules() + CreateSsoConnectionData::rules(); - } - - protected function handle(array $validated): ResponseFactory - { - $connection = app(CreateSsoConnectionAction::class)->execute($this->organization(), CreateSsoConnectionData::fromValidated($validated)); - - return (new SsoConnectionResource($connection))->toStructuredResponse(); - } -} diff --git a/src/Domains/Sso/Mcp/Requests/DeleteSsoConnectionMcpRequest.php b/src/Domains/Sso/Mcp/Requests/DeleteSsoConnectionMcpRequest.php deleted file mode 100644 index 02a80c4..0000000 --- a/src/Domains/Sso/Mcp/Requests/DeleteSsoConnectionMcpRequest.php +++ /dev/null @@ -1,23 +0,0 @@ -execute($this->connection()); - - return Response::text('SSO connection deleted.'); - } -} diff --git a/src/Domains/Sso/Mcp/Requests/ListSsoConnectionsMcpRequest.php b/src/Domains/Sso/Mcp/Requests/ListSsoConnectionsMcpRequest.php deleted file mode 100644 index ab66cc5..0000000 --- a/src/Domains/Sso/Mcp/Requests/ListSsoConnectionsMcpRequest.php +++ /dev/null @@ -1,31 +0,0 @@ -organizationRules() + ListSsoConnectionsData::rules(); - } - - protected function handle(array $validated): ResponseFactory - { - $connections = app(ListSsoConnectionsAction::class)->execute(ListSsoConnectionsData::fromValidated($validated)); - - return SsoConnectionResource::collection($connections)->toStructuredResponse(); - } -} diff --git a/src/Domains/Sso/Mcp/Requests/ListSsoIdentitiesMcpRequest.php b/src/Domains/Sso/Mcp/Requests/ListSsoIdentitiesMcpRequest.php deleted file mode 100644 index a662b50..0000000 --- a/src/Domains/Sso/Mcp/Requests/ListSsoIdentitiesMcpRequest.php +++ /dev/null @@ -1,37 +0,0 @@ -targetUser(); - } - - protected function rules(): array - { - return $this->userRules() + ListSsoIdentitiesData::rules(); - } - - protected function handle(array $validated): ResponseFactory - { - $identities = app(ListSsoIdentitiesAction::class)->execute(ListSsoIdentitiesData::fromValidated(['user' => $this->targetUser()->getRouteKey()] + $validated)); - - return SsoIdentityResource::collection($identities)->toStructuredResponse(); - } -} diff --git a/src/Domains/Sso/Mcp/Requests/ShowSsoConnectionMcpRequest.php b/src/Domains/Sso/Mcp/Requests/ShowSsoConnectionMcpRequest.php deleted file mode 100644 index 5b5c53b..0000000 --- a/src/Domains/Sso/Mcp/Requests/ShowSsoConnectionMcpRequest.php +++ /dev/null @@ -1,22 +0,0 @@ -execute($this->connection())))->toStructuredResponse(); - } -} diff --git a/src/Domains/Sso/Mcp/Requests/SsoConnectionMcpRequest.php b/src/Domains/Sso/Mcp/Requests/SsoConnectionMcpRequest.php deleted file mode 100644 index 952edbe..0000000 --- a/src/Domains/Sso/Mcp/Requests/SsoConnectionMcpRequest.php +++ /dev/null @@ -1,40 +0,0 @@ -resolved ??= SsoConnectionModel::query()->where('slug', $this->get('connection'))->firstOrFail(); - } - - protected function scope(): ?OrganizationModel - { - return $this->connection()->organization; - } - - /** - * @return array> - */ - protected function connectionRules(): array - { - return ['connection' => ['required', 'string']]; - } - - /** - * Every connection tool names its connection by slug. - */ - protected function rules(): array - { - return $this->connectionRules(); - } -} diff --git a/src/Domains/Sso/Mcp/Requests/UnlinkSsoIdentityMcpRequest.php b/src/Domains/Sso/Mcp/Requests/UnlinkSsoIdentityMcpRequest.php deleted file mode 100644 index a377fad..0000000 --- a/src/Domains/Sso/Mcp/Requests/UnlinkSsoIdentityMcpRequest.php +++ /dev/null @@ -1,51 +0,0 @@ -identity()->connection?->organization; - } - - protected function self(): ?Model - { - $actor = $this->actor(); - - return $this->identity()->ownedBy($actor) ? $actor : null; - } - - private function identity(): SsoIdentityModel - { - return $this->resolved ??= SsoIdentityModel::query()->whereKey($this->get('identity'))->firstOrFail(); - } - - protected function rules(): array - { - return ['identity' => ['required', 'string']]; - } - - protected function handle(array $validated): Response - { - app(UnlinkSsoIdentityAction::class)->execute($this->identity()); - - return Response::text('Identity unlinked.'); - } -} diff --git a/src/Domains/Sso/Mcp/Requests/UpdateSsoConnectionMcpRequest.php b/src/Domains/Sso/Mcp/Requests/UpdateSsoConnectionMcpRequest.php deleted file mode 100644 index eb598a1..0000000 --- a/src/Domains/Sso/Mcp/Requests/UpdateSsoConnectionMcpRequest.php +++ /dev/null @@ -1,28 +0,0 @@ -connectionRules() + UpdateSsoConnectionData::rules($this->connection()); - } - - protected function handle(array $validated): ResponseFactory - { - return (new SsoConnectionResource(app(UpdateSsoConnectionAction::class)->execute($this->connection(), UpdateSsoConnectionData::fromValidated($validated))))->toStructuredResponse(); - } -} diff --git a/src/Domains/Sso/Mcp/Tools/CreateSsoConnectionTool.php b/src/Domains/Sso/Mcp/Tools/CreateSsoConnectionTool.php deleted file mode 100644 index 615f086..0000000 --- a/src/Domains/Sso/Mcp/Tools/CreateSsoConnectionTool.php +++ /dev/null @@ -1,41 +0,0 @@ -persist(); - } - - public function schema(JsonSchema $schema): array - { - return $this->organizationSchema($schema) + [ - 'name' => $schema->string()->description('Display name, e.g. Okta.')->required(), - 'slug' => $schema->string()->description('URL identifier. Omit to generate one.'), - 'protocol' => $schema->string()->description('oidc, azure or saml.')->required(), - ] + $this->ssoConnectionSettingsSchema($schema); - } - - public function outputSchema(JsonSchema $schema): array - { - return SsoConnectionResource::structuredSchema($schema); - } -} diff --git a/src/Domains/Sso/Mcp/Tools/DeleteSsoConnectionTool.php b/src/Domains/Sso/Mcp/Tools/DeleteSsoConnectionTool.php deleted file mode 100644 index f086753..0000000 --- a/src/Domains/Sso/Mcp/Tools/DeleteSsoConnectionTool.php +++ /dev/null @@ -1,28 +0,0 @@ -persist(); - } - - public function schema(JsonSchema $schema): array - { - return [ - 'connection' => $schema->string()->description('The connection slug.')->required(), - ]; - } -} diff --git a/src/Domains/Sso/Mcp/Tools/ListSsoConnectionsTool.php b/src/Domains/Sso/Mcp/Tools/ListSsoConnectionsTool.php deleted file mode 100644 index 28b4419..0000000 --- a/src/Domains/Sso/Mcp/Tools/ListSsoConnectionsTool.php +++ /dev/null @@ -1,37 +0,0 @@ -persist(); - } - - public function schema(JsonSchema $schema): array - { - return $this->organizationSchema($schema) + [ - ] + ListSsoConnectionsData::pagination()->schema($schema); - } - - public function outputSchema(JsonSchema $schema): array - { - return SsoConnectionResource::collectionSchema($schema); - } -} diff --git a/src/Domains/Sso/Mcp/Tools/ListSsoIdentitiesTool.php b/src/Domains/Sso/Mcp/Tools/ListSsoIdentitiesTool.php deleted file mode 100644 index ca7faef..0000000 --- a/src/Domains/Sso/Mcp/Tools/ListSsoIdentitiesTool.php +++ /dev/null @@ -1,37 +0,0 @@ -persist(); - } - - public function schema(JsonSchema $schema): array - { - return $this->userSchema($schema) + [ - ] + ListSsoIdentitiesData::pagination()->schema($schema); - } - - public function outputSchema(JsonSchema $schema): array - { - return SsoIdentityResource::collectionSchema($schema); - } -} diff --git a/src/Domains/Sso/Mcp/Tools/ShowSsoConnectionTool.php b/src/Domains/Sso/Mcp/Tools/ShowSsoConnectionTool.php deleted file mode 100644 index 295a6b9..0000000 --- a/src/Domains/Sso/Mcp/Tools/ShowSsoConnectionTool.php +++ /dev/null @@ -1,34 +0,0 @@ -persist(); - } - - public function schema(JsonSchema $schema): array - { - return [ - 'connection' => $schema->string()->description('The connection slug.')->required(), - ]; - } - - public function outputSchema(JsonSchema $schema): array - { - return SsoConnectionResource::structuredSchema($schema); - } -} diff --git a/src/Domains/Sso/Mcp/Tools/UnlinkSsoIdentityTool.php b/src/Domains/Sso/Mcp/Tools/UnlinkSsoIdentityTool.php deleted file mode 100644 index f95205b..0000000 --- a/src/Domains/Sso/Mcp/Tools/UnlinkSsoIdentityTool.php +++ /dev/null @@ -1,28 +0,0 @@ -persist(); - } - - public function schema(JsonSchema $schema): array - { - return [ - 'identity' => $schema->string()->description('The identity id.')->required(), - ]; - } -} diff --git a/src/Domains/Sso/Mcp/Tools/UpdateSsoConnectionTool.php b/src/Domains/Sso/Mcp/Tools/UpdateSsoConnectionTool.php deleted file mode 100644 index 74de3fe..0000000 --- a/src/Domains/Sso/Mcp/Tools/UpdateSsoConnectionTool.php +++ /dev/null @@ -1,39 +0,0 @@ -persist(); - } - - public function schema(JsonSchema $schema): array - { - return [ - 'connection' => $schema->string()->description('The connection slug.')->required(), - 'name' => $schema->string()->description('Display name.'), - 'slug' => $schema->string()->description('New URL identifier.'), - ] + $this->ssoConnectionSettingsSchema($schema); - } - - public function outputSchema(JsonSchema $schema): array - { - return SsoConnectionResource::structuredSchema($schema); - } -} diff --git a/src/Domains/Sso/Models/SsoConnectionModel.php b/src/Domains/Sso/Models/SsoConnectionModel.php deleted file mode 100644 index 9625b12..0000000 --- a/src/Domains/Sso/Models/SsoConnectionModel.php +++ /dev/null @@ -1,135 +0,0 @@ - $config - * @property bool $jit - * @property bool $enforced - * @property bool $enabled - * @property Carbon|null $created_at - * @property Carbon|null $updated_at - */ -final class SsoConnectionModel extends Model -{ - use DispatchesModelEvents; - - /** @use HasFactory */ - use HasFactory; - - use HasUlids; - - public const string OIDC = 'oidc'; - - public const string SAML = 'saml'; - - public const string AZURE = 'azure'; - - /** @var array */ - public const array PROTOCOLS = [self::OIDC, self::SAML, self::AZURE]; - - protected $fillable = ['organization_id', 'name', 'slug', 'protocol', 'config', 'jit', 'enforced', 'enabled']; - - protected $hidden = ['config']; - - protected $attributes = [ - 'jit' => true, - 'enforced' => false, - 'enabled' => true, - ]; - - public function getTable(): string - { - return Tables::name('sso_connections'); - } - - public function getRouteKeyName(): string - { - return 'slug'; - } - - /** - * @return BelongsTo - */ - public function organization(): BelongsTo - { - return $this->belongsTo(OrganizationModel::class, 'organization_id'); - } - - /** - * @return HasMany - */ - public function identities(): HasMany - { - return $this->hasMany(SsoIdentityModel::class, 'connection_id'); - } - - public function setting(string $key): ?string - { - $value = $this->config[$key] ?? null; - - return is_string($value) && $value !== '' ? $value : null; - } - - /** - * Whether the connection's organization owns the email's domain, which - * makes its identity provider authoritative for that address. - */ - public function trusts(string $email): bool - { - $domain = strtolower(substr($email, (int) strrpos($email, '@') + 1)); - - return str_contains($email, '@') - && $this->organization()->first()?->domains()->where('domain', $domain)->exists() === true; - } - - /** - * A deleted organization's connections can't be used or managed until - * it's restored. - */ - protected static function booted(): void - { - self::addGlobalScope('live_organization', fn (Builder $query): Builder => $query->whereHas('organization')); - } - - protected static function newFactory(): SsoConnectionFactory - { - return SsoConnectionFactory::new(); - } - - protected function casts(): array - { - return [ - 'config' => 'encrypted:array', - 'jit' => 'boolean', - 'enforced' => 'boolean', - 'enabled' => 'boolean', - ]; - } -} diff --git a/src/Domains/Sso/Models/SsoIdentityModel.php b/src/Domains/Sso/Models/SsoIdentityModel.php deleted file mode 100644 index cddd65e..0000000 --- a/src/Domains/Sso/Models/SsoIdentityModel.php +++ /dev/null @@ -1,67 +0,0 @@ - - */ - public function connection(): BelongsTo - { - return $this->belongsTo(SsoConnectionModel::class, 'connection_id'); - } - - /** - * @return BelongsTo - */ - public function user(): BelongsTo - { - return $this->belongsTo(app(Users::class)->model(), 'user_id'); - } - - protected function casts(): array - { - return ['last_login_at' => 'datetime']; - } - - /** - * Whether the sign-in is the user's own. - */ - public function ownedBy(?Model $user): bool - { - return $user !== null && (string) $this->user_id === (string) $user->getKey(); - } -} diff --git a/src/Domains/Sso/Policies/SsoConnectionPolicy.php b/src/Domains/Sso/Policies/SsoConnectionPolicy.php deleted file mode 100644 index 754d712..0000000 --- a/src/Domains/Sso/Policies/SsoConnectionPolicy.php +++ /dev/null @@ -1,25 +0,0 @@ -permits($user, 'roster.sso.view', $subject, $self); - } - - public function manage(?Model $user, ?Model $subject = null, ?Model $self = null): bool - { - return $this->permits($user, 'roster.sso.manage', $subject, $self); - } -} diff --git a/src/Domains/Sso/Policies/SsoIdentityPolicy.php b/src/Domains/Sso/Policies/SsoIdentityPolicy.php deleted file mode 100644 index 06c075d..0000000 --- a/src/Domains/Sso/Policies/SsoIdentityPolicy.php +++ /dev/null @@ -1,26 +0,0 @@ -permits($user, 'roster.sso.view', $identity?->connection); - } - - public function manage(?Model $user, ?SsoIdentityModel $identity = null): bool - { - return $this->permits($user, 'roster.sso.manage', $identity?->connection); - } -} diff --git a/src/Domains/Sso/Resources/SsoConnectionResource.php b/src/Domains/Sso/Resources/SsoConnectionResource.php deleted file mode 100644 index 13316cf..0000000 --- a/src/Domains/Sso/Resources/SsoConnectionResource.php +++ /dev/null @@ -1,72 +0,0 @@ - - */ - public static function schema(JsonSchema $schema): array - { - return [ - 'slug' => $schema->string()->required(), - 'name' => $schema->string()->required(), - 'protocol' => $schema->string()->enum(SsoConnectionModel::PROTOCOLS)->required(), - 'organization' => $schema->string()->nullable()->required(), - 'settings' => $schema->object()->description('The non-secret settings: issuer, tenant, client_id, metadata_url, entity_id, sso_url.')->required(), - 'client_secret' => $schema->string()->enum(['set', null])->nullable()->description('"set" when a client secret is stored.')->required(), - 'certificate' => $schema->string()->enum(['set', null])->nullable()->description('"set" when a certificate is stored.')->required(), - 'jit' => $schema->boolean()->required(), - 'enforced' => $schema->boolean()->required(), - 'enabled' => $schema->boolean()->required(), - 'sign_in_url' => $schema->string()->nullable()->required(), - 'callback_url' => $schema->string()->nullable()->required(), - 'metadata_url' => $schema->string()->nullable()->required(), - 'identities_count' => $schema->integer()->description('When counted.'), - 'created_at' => $schema->string()->nullable()->required(), - ]; - } - - /** - * @return array - */ - public function toArray(Request $request): array - { - $settings = array_intersect_key($this->config, array_flip(['issuer', 'tenant', 'client_id', 'metadata_url', 'entity_id', 'sso_url'])); - ksort($settings); - - return [ - 'slug' => $this->slug, - 'name' => $this->name, - 'protocol' => $this->protocol, - 'organization' => $this->organization?->slug, - 'settings' => (object) $settings, - 'client_secret' => isset($this->config['client_secret']) ? 'set' : null, - 'certificate' => isset($this->config['certificate']) ? 'set' : null, - 'jit' => $this->jit, - 'enforced' => $this->enforced, - 'enabled' => $this->enabled, - 'sign_in_url' => Route::has('roster.sso.start') ? route('roster.sso.start', $this->slug) : null, - 'callback_url' => Route::has('roster.sso.callback') ? route('roster.sso.callback', $this->slug) : null, - 'metadata_url' => $this->protocol === SsoConnectionModel::SAML && Route::has('roster.sso.metadata') ? route('roster.sso.metadata', $this->slug) : null, - 'identities_count' => $this->whenCounted('identities'), - 'created_at' => $this->created_at?->toIso8601String(), - ]; - } -} diff --git a/src/Domains/Sso/Resources/SsoIdentityResource.php b/src/Domains/Sso/Resources/SsoIdentityResource.php deleted file mode 100644 index 2e37383..0000000 --- a/src/Domains/Sso/Resources/SsoIdentityResource.php +++ /dev/null @@ -1,55 +0,0 @@ - - */ - public static function schema(JsonSchema $schema): array - { - return [ - 'id' => $schema->string()->required(), - 'connection' => $schema->string()->nullable()->required(), - 'organization' => $schema->string()->nullable()->required(), - 'user' => $schema->object(UserSummaryResource::schema($schema))->nullable()->required(), - 'subject' => $schema->string()->required(), - 'email' => $schema->string()->nullable()->required(), - 'last_login_at' => $schema->string()->nullable()->required(), - 'linked_at' => $schema->string()->nullable()->required(), - ]; - } - - /** - * @return array - */ - public function toArray(Request $request): array - { - $user = $this->user; - - return [ - 'id' => $this->id, - 'connection' => $this->connection?->slug, - 'organization' => $this->connection?->organization?->slug, - 'user' => $user instanceof Model ? (new UserSummaryResource($user))->resolve($request) : null, - 'subject' => $this->subject, - 'email' => $this->email, - 'last_login_at' => $this->last_login_at?->toIso8601String(), - 'linked_at' => $this->created_at?->toIso8601String(), - ]; - } -} diff --git a/src/Domains/Sso/Services/OidcProvider.php b/src/Domains/Sso/Services/OidcProvider.php deleted file mode 100644 index ea56a66..0000000 --- a/src/Domains/Sso/Services/OidcProvider.php +++ /dev/null @@ -1,175 +0,0 @@ - - */ - protected $scopes = ['openid', 'email', 'profile']; - - protected $scopeSeparator = ' '; - - public function __construct( - Request $request, - private readonly string $issuer, - string $clientId, - string $clientSecret, - string $redirectUrl, - ) { - parent::__construct($request, $clientId, $clientSecret, $redirectUrl); - } - - /** - * @return array - */ - public function discovery(): array - { - $issuer = rtrim($this->issuer, '/'); - - /** @var array */ - return Cache::remember( - 'roster.sso.discovery.'.hash('sha256', $issuer), - (int) config('roster.sso.discovery_cache_seconds', 3600), - fn (): array => (array) Http::acceptJson()->get($issuer.'/.well-known/openid-configuration')->throw()->json(), - ); - } - - public function user(): User - { - if ($this->hasInvalidState()) { - throw new InvalidStateException; - } - - $response = $this->getAccessTokenResponse($this->getCode()); - $idToken = $response['id_token'] ?? null; - - if (! is_string($idToken)) { - throw new RuntimeException('The identity provider returned no id_token.'); - } - - $claims = $this->verify($idToken); - - return (new User)->setRaw($claims)->map([ - 'id' => (string) $claims['sub'], - 'email' => is_string($claims['email'] ?? null) ? $claims['email'] : null, - 'name' => is_string($claims['name'] ?? null) ? $claims['name'] : null, - ])->setToken(is_string($response['access_token'] ?? null) ? $response['access_token'] : ''); - } - - /** - * Verify an id_token and return its claims. - * - * @return array - */ - public function verify(string $idToken): array - { - $discovery = $this->discovery(); - $nonce = $this->request->session()->pull(self::NONCE_KEY); - - try { - JWT::$leeway = 60; - $claims = (array) JWT::decode($idToken, JWK::parseKeySet($this->jwks((string) $discovery['jwks_uri']), 'RS256')); - } catch (Throwable $exception) { - throw new RuntimeException('The id_token could not be verified: '.$exception->getMessage(), 0, $exception); - } - - $audience = (array) ($claims['aud'] ?? []); - - if (($claims['iss'] ?? null) !== ($discovery['issuer'] ?? null)) { - throw new RuntimeException('The id_token was issued by an unexpected issuer.'); - } - - if (! in_array($this->clientId, $audience, true)) { - throw new RuntimeException('The id_token is not meant for this application.'); - } - - if (! is_string($nonce) || ! is_string($claims['nonce'] ?? null) || ! hash_equals($nonce, $claims['nonce'])) { - throw new RuntimeException('The id_token nonce does not match this sign-in.'); - } - - if (! is_scalar($claims['sub'] ?? null)) { - throw new RuntimeException('The id_token has no subject.'); - } - - return $claims; - } - - protected function getAuthUrl($state): string - { - $nonce = Str::random(40); - $this->request->session()->put(self::NONCE_KEY, $nonce); - $this->with(['nonce' => $nonce]); - - return $this->buildAuthUrlFromBase((string) $this->discovery()['authorization_endpoint'], $state); - } - - protected function getTokenUrl(): string - { - return (string) $this->discovery()['token_endpoint']; - } - - /** - * Exchange the code through Laravel's HTTP client. - * - * @return array - */ - public function getAccessTokenResponse($code): array - { - /** @var array */ - return (array) Http::asForm()->acceptJson()->post($this->getTokenUrl(), $this->getTokenFields($code))->throw()->json(); - } - - /** - * @return array - */ - protected function getUserByToken($token): array - { - return []; - } - - /** - * @param array $user - */ - protected function mapUserToObject(array $user): User - { - return (new User)->setRaw($user); - } - - /** - * @return array - */ - private function jwks(string $uri): array - { - /** @var array */ - return Cache::remember( - 'roster.sso.jwks.'.hash('sha256', $uri), - (int) config('roster.sso.discovery_cache_seconds', 3600), - fn (): array => (array) Http::acceptJson()->get($uri)->throw()->json(), - ); - } -} diff --git a/src/Domains/Sso/Services/Sso.php b/src/Domains/Sso/Services/Sso.php deleted file mode 100644 index fa4f8a9..0000000 --- a/src/Domains/Sso/Services/Sso.php +++ /dev/null @@ -1,122 +0,0 @@ - $socialite && class_exists(JWT::class), - SsoConnectionModel::SAML => $socialite && class_exists(Saml2Provider::class), - SsoConnectionModel::AZURE => $socialite && class_exists(AzureProvider::class), - default => $socialite && (class_exists(JWT::class) || class_exists(Saml2Provider::class) || class_exists(AzureProvider::class)), - }; - } - - public function provider(SsoConnectionModel $connection): Provider - { - if (! $this->available($connection->protocol)) { - throw SsoUnavailableException::forProtocol($connection->protocol); - } - - $callback = route('roster.sso.callback', $connection->slug); - - if ($connection->protocol === SsoConnectionModel::OIDC) { - return new OidcProvider( - $this->request, - (string) $connection->setting('issuer'), - (string) $connection->setting('client_id'), - (string) $connection->setting('client_secret'), - $callback, - ); - } - - if ($connection->protocol === SsoConnectionModel::AZURE) { - $clientId = (string) $connection->setting('client_id'); - $secret = (string) $connection->setting('client_secret'); - - $provider = (new AzureProvider($this->request, $clientId, $secret, $callback)) - ->setConfig(new Config($clientId, $secret, $callback, ['tenant' => (string) $connection->setting('tenant')])); - - // Tests (and apps needing a proxy) can supply the HTTP client. - if (app()->bound('roster.sso.http')) { - $provider->setHttpClient(app('roster.sso.http')); - } - - return $provider; - } - - return (new Saml2Provider($this->request))->setConfig(new Config('', '', $callback, $this->samlConfig($connection))); - } - - /** - * Map a Socialite user from any protocol to the claims Roster trusts. - */ - public function claims(SsoConnectionModel $connection, User $user): IdentityClaims - { - $raw = method_exists($user, 'getRaw') ? (array) $user->getRaw() : []; - - $email = match ($connection->protocol) { - // Never Entra's `mail`: tenant admins can set it to anything. - // A userPrincipalName must sit on a domain the tenant verified. - SsoConnectionModel::AZURE => is_string($raw['userPrincipalName'] ?? null) ? $raw['userPrincipalName'] : null, - default => $user->getEmail(), - }; - - return new IdentityClaims( - subject: (string) $user->getId(), - email: $email === null ? null : strtolower($email), - name: $user->getName(), - raw: $raw, - ); - } - - /** - * @return array - */ - public function samlConfig(SsoConnectionModel $connection): array - { - $idp = $connection->setting('metadata_url') !== null - ? ['metadata' => $connection->setting('metadata_url')] - : [ - 'entityid' => $connection->setting('entity_id'), - 'acs' => $connection->setting('sso_url'), - 'certificate' => $connection->setting('certificate'), - ]; - - return $idp + [ - 'sp_entityid' => route('roster.sso.metadata', $connection->slug), - 'sp_acs' => ltrim((string) parse_url(route('roster.sso.callback', $connection->slug), PHP_URL_PATH), '/'), - 'sp_default_binding_method' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST', - ]; - } -} diff --git a/src/Domains/Sso/Services/SsoSignInRequirement.php b/src/Domains/Sso/Services/SsoSignInRequirement.php deleted file mode 100644 index 737894c..0000000 --- a/src/Domains/Sso/Services/SsoSignInRequirement.php +++ /dev/null @@ -1,49 +0,0 @@ -where('enforced', true) - ->where('enabled', true) - ->whereHas('organization.domains', fn (Builder $query): Builder => $query->where('domain', $domain)) - ->first(); - - if ($connection === null) { - return null; - } - - return new ExternalSignIn( - key: $connection->slug, - label: (string) $connection->organization?->name, - url: Route::has('roster.sso.start') ? route('roster.sso.start', $connection->slug) : '', - record: $connection, - ); - } -} diff --git a/src/Domains/Sso/SsoServiceProvider.php b/src/Domains/Sso/SsoServiceProvider.php deleted file mode 100644 index 72ed406..0000000 --- a/src/Domains/Sso/SsoServiceProvider.php +++ /dev/null @@ -1,65 +0,0 @@ -registerAuthorization(); - - // Enforced connections hold their domains to single sign-on, whether - // or not the sign-in routes are available here. - $this->app->make(Roster::class)->requireSignIn(SsoSignInRequirement::class); - - $this->loadApiRoutesFrom(__DIR__.'/routes.php'); - - if (! $this->app->make(Sso::class)->available()) { - return; - } - - $this->loadRoutesFrom(__DIR__.'/web.php'); - - // SAML identity providers post the signed assertion cross-site; - // the assertion's signature, not a CSRF token, protects it. - ValidateCsrfToken::except([trim((string) $this->app->make(Repository::class)->get('roster.sso.prefix', 'roster/sso'), '/').'/*/callback']); - } - - /** - * The `roster.sso.*` permissions, granted to admins, answered by the - * connection policy, through the same seams other packages use. An - * application's `roster.policies` entry for these models still wins: the - * package provider registers those after this boots. - */ - private function registerAuthorization(): void - { - $this->app->make(Resources::class)->rosterResource('roster.sso', SsoConnectionModel::class); - - $this->app->make(PermissionCatalogue::class) - ->rosterPermission('roster.sso.view', "View an organization's single sign-on connections.", ['admin']) - ->rosterPermission('roster.sso.manage', 'Configure single sign-on connections.', ['admin']); - - $gate = $this->app->make(Gate::class); - $gate->policy(SsoConnectionModel::class, SsoConnectionPolicy::class); - $gate->policy(SsoIdentityModel::class, SsoIdentityPolicy::class); - } -} diff --git a/src/Domains/Sso/routes.php b/src/Domains/Sso/routes.php deleted file mode 100644 index 46131f5..0000000 --- a/src/Domains/Sso/routes.php +++ /dev/null @@ -1,14 +0,0 @@ -name('organizations.sso-connections.index'); -Route::post('organizations/{organization}/sso-connections', [SsoController::class, 'store'])->name('organizations.sso-connections.store'); -Route::get('sso-connections/{connection}', [SsoController::class, 'show'])->name('sso-connections.show'); -Route::patch('sso-connections/{connection}', [SsoController::class, 'update'])->name('sso-connections.update'); -Route::delete('sso-connections/{connection}', [SsoController::class, 'destroy'])->name('sso-connections.destroy'); -Route::get('users/{user}/sso-identities', [SsoController::class, 'identities'])->name('users.sso-identities.index'); -Route::delete('sso-identities/{identity}', [SsoController::class, 'unlink'])->name('sso-identities.destroy'); diff --git a/src/Domains/Sso/web.php b/src/Domains/Sso/web.php deleted file mode 100644 index 4c84ab6..0000000 --- a/src/Domains/Sso/web.php +++ /dev/null @@ -1,21 +0,0 @@ - $middleware */ -$middleware = config('roster.sso.middleware', ['web']); - -Route::middleware($middleware) - ->prefix((string) config('roster.sso.prefix', 'roster/sso')) - ->name('roster.sso.') - ->group(function (): void { - Route::get('/', [SsoWebController::class, 'discover'])->name('discover'); - Route::get('{connection}', [SsoWebController::class, 'start'])->name('start'); - // SAML posts the assertion back (ACS); OIDC redirects with a code. - Route::match(['get', 'post'], '{connection}/callback', [SsoWebController::class, 'callback'])->name('callback'); - Route::get('{connection}/metadata', [SsoWebController::class, 'metadata'])->name('metadata'); - Route::post('{connection}/link', [SsoWebController::class, 'link'])->middleware('auth')->name('link'); - }); diff --git a/src/Mcp/Concerns/DescribesOrganization.php b/src/Mcp/Concerns/DescribesOrganization.php index 6e93518..ed53473 100644 --- a/src/Mcp/Concerns/DescribesOrganization.php +++ b/src/Mcp/Concerns/DescribesOrganization.php @@ -28,7 +28,7 @@ protected function organizationSettingsSchema(JsonSchema $schema): array { return [ 'auto_join' => $schema->boolean()->description('Let users who verify an email on one of the domains join automatically. Defaults to false.'), - 'provisioned_status' => $schema->string()->description('active or pending: whether accounts created by this organization\'s SSO or SCIM start active or wait for approval. Defaults to active.'), + 'provisioned_status' => $schema->string()->description('active or pending: whether this organization\'s externally provisioned accounts start active or wait for approval. Defaults to active.'), 'domains' => $schema->array()->items($schema->string())->description('Email domains for auto-join, e.g. ["example.com"]. Replaces the whole list. A domain can belong to one organization only.'), ] + $this->statusSchema($schema, Statuses::organizations(), 'organization'); } diff --git a/src/Mcp/Concerns/DescribesSsoConnection.php b/src/Mcp/Concerns/DescribesSsoConnection.php deleted file mode 100644 index d6015ca..0000000 --- a/src/Mcp/Concerns/DescribesSsoConnection.php +++ /dev/null @@ -1,34 +0,0 @@ - - */ - protected function ssoConnectionSettingsSchema(JsonSchema $schema): array - { - return [ - 'issuer' => $schema->string()->description('OIDC: the issuer URL (https), e.g. https://example.okta.com.'), - 'tenant' => $schema->string()->description('Microsoft Entra ID: the tenant ID or verified domain. common/organizations/consumers are refused.'), - 'client_id' => $schema->string()->description('OIDC / Entra ID: the application (client) id.'), - 'client_secret' => $schema->string()->description('OIDC / Entra ID: the client secret. Never returned; omit on update to keep it.'), - 'metadata_url' => $schema->string()->description('SAML: the identity provider metadata URL (preferred).'), - 'entity_id' => $schema->string()->description('SAML without metadata: the IdP entity ID.'), - 'sso_url' => $schema->string()->description('SAML without metadata: the IdP single sign-on URL.'), - 'certificate' => $schema->string()->description('SAML without metadata: the IdP x509 signing certificate.'), - 'jit' => $schema->boolean()->description('Create accounts on first sign-in for the organization\'s domains. Defaults to true.'), - 'enforced' => $schema->boolean()->description('Require SSO for the organization\'s domains. Defaults to false.'), - 'enabled' => $schema->boolean()->description('Defaults to true.'), - ]; - } -} diff --git a/src/Mcp/RosterServer.php b/src/Mcp/RosterServer.php index fdc96e4..2ed6675 100644 --- a/src/Mcp/RosterServer.php +++ b/src/Mcp/RosterServer.php @@ -48,16 +48,6 @@ use RefactorCircus\Roster\Domains\Role\Mcp\Tools\RevokeRoleTool; use RefactorCircus\Roster\Domains\Role\Mcp\Tools\ShowRoleTool; use RefactorCircus\Roster\Domains\Role\Mcp\Tools\UpdateRoleTool; -use RefactorCircus\Roster\Domains\Scim\Mcp\Tools\CreateScimTokenTool; -use RefactorCircus\Roster\Domains\Scim\Mcp\Tools\ListScimTokensTool; -use RefactorCircus\Roster\Domains\Scim\Mcp\Tools\RevokeScimTokenTool; -use RefactorCircus\Roster\Domains\Sso\Mcp\Tools\CreateSsoConnectionTool; -use RefactorCircus\Roster\Domains\Sso\Mcp\Tools\DeleteSsoConnectionTool; -use RefactorCircus\Roster\Domains\Sso\Mcp\Tools\ListSsoConnectionsTool; -use RefactorCircus\Roster\Domains\Sso\Mcp\Tools\ListSsoIdentitiesTool; -use RefactorCircus\Roster\Domains\Sso\Mcp\Tools\ShowSsoConnectionTool; -use RefactorCircus\Roster\Domains\Sso\Mcp\Tools\UnlinkSsoIdentityTool; -use RefactorCircus\Roster\Domains\Sso\Mcp\Tools\UpdateSsoConnectionTool; use RefactorCircus\Roster\Domains\Team\Mcp\Tools\AddTeamMemberTool; use RefactorCircus\Roster\Domains\Team\Mcp\Tools\CreateTeamTool; use RefactorCircus\Roster\Domains\Team\Mcp\Tools\DeleteTeamTool; @@ -190,20 +180,6 @@ final class RosterServer extends Server RevokeRoleTool::class, ListUserPermissionsTool::class, - // Single sign-on - ListSsoConnectionsTool::class, - ShowSsoConnectionTool::class, - CreateSsoConnectionTool::class, - UpdateSsoConnectionTool::class, - DeleteSsoConnectionTool::class, - ListSsoIdentitiesTool::class, - UnlinkSsoIdentityTool::class, - - // SCIM provisioning - ListScimTokensTool::class, - CreateScimTokenTool::class, - RevokeScimTokenTool::class, - // Impersonation StartImpersonationTool::class, ListImpersonationsTool::class, diff --git a/src/Roster.php b/src/Roster.php index 9f56ead..90519a4 100644 --- a/src/Roster.php +++ b/src/Roster.php @@ -144,9 +144,9 @@ public function externalSignInFor(string $email): ?ExternalSignIn } /** - * The status the organization's externally provisioned users (SSO - * just-in-time accounts, SCIM) start with: its `provisioned_status`, - * resolved through the app's user statuses. No stored value starts them + * The status the organization's externally provisioned accounts start + * with: its `provisioned_status`, resolved through the app's user + * statuses. No stored value starts them * active; a value that is not one of those statuses starts them active * too, and is reported, so provisioning never fails and a bad value is * never silent. Resolved by `Support\ProvisionedStatus` against diff --git a/src/RosterServiceProvider.php b/src/RosterServiceProvider.php index 60a353e..016d476 100644 --- a/src/RosterServiceProvider.php +++ b/src/RosterServiceProvider.php @@ -100,7 +100,7 @@ public function boot(): void $this->registerCortex(); // Core models' policies, from `roster.policies`: Roster's own checks ask - // them. The SSO and SCIM domains register theirs in their providers. + // them. Package resources register their own policies. $this->registerPolicies(); $this->registerRateLimiter(); $this->registerNotFoundResponses(); @@ -161,15 +161,14 @@ public function boot(): void } /** - * Roster's routes outside its JSON API: SCIM, and the signed pages a - * person opens from an email. The shared surface is scoped, so name them - * each time it is resolved. + * Roster's routes outside its JSON API: the signed pages a person opens + * from an email. The shared surface is scoped, so name them each time it + * is resolved. */ private function registerSurfaces(): void { $this->app->afterResolving(Surface::class, function (Surface $surface): void { - $surface->route('roster.scim.', 'scim') - ->route('roster.invitations.page', 'web') + $surface->route('roster.invitations.page', 'web') ->route('roster.invitations.show', 'web') ->route('roster.impersonation.', 'web'); }); diff --git a/src/Support/Audit.php b/src/Support/Audit.php index 5332bf4..d32cb48 100644 --- a/src/Support/Audit.php +++ b/src/Support/Audit.php @@ -157,8 +157,8 @@ private function subject(array $models): ?Model /** * Who was really acting when the change came from an impersonated - * session, and the import it came through. The SCIM domain adds the - * token a change came through itself, on AuditHooks. + * session, and the import it came through. Other packages add their own + * context on AuditHooks. * * @return array */ diff --git a/src/Support/Policies/Policy.php b/src/Support/Policies/Policy.php index 26e4b8c..b588ef9 100644 --- a/src/Support/Policies/Policy.php +++ b/src/Support/Policies/Policy.php @@ -13,8 +13,8 @@ /** * Shared checks for the bundled policies. * - * Core policies are registered from `roster.policies`, and the SSO and SCIM - * domains register theirs from their providers; either way an application + * Core policies are registered from `roster.policies`, and package + * resources register theirs from their providers; either way an application * swaps one by pointing its model at another class in `roster.policies`. The bundled policies * answer with Roster's own permissions: a method asks whether the user holds * the permission in the organization or team the subject belongs to. diff --git a/src/Support/ProvisionedStatus.php b/src/Support/ProvisionedStatus.php index 3add4fd..49fa29c 100644 --- a/src/Support/ProvisionedStatus.php +++ b/src/Support/ProvisionedStatus.php @@ -9,8 +9,8 @@ use RefactorCircus\Roster\Domains\Organization\Models\OrganizationModel; /** - * Resolves the status an organization's externally provisioned users (SSO - * just-in-time accounts, SCIM) start with, against one user-status enum. + * Resolves the status an organization's externally provisioned accounts + * start with, against one user-status enum. * `Roster::provisionedStatus()` builds it from `roster.statuses.users`. */ final readonly class ProvisionedStatus diff --git a/src/Domains/Sso/Support/NotSsoEnforced.php b/src/Support/Rules/NoExternalSignIn.php similarity index 59% rename from src/Domains/Sso/Support/NotSsoEnforced.php rename to src/Support/Rules/NoExternalSignIn.php index 8a95e45..9f75c10 100644 --- a/src/Domains/Sso/Support/NotSsoEnforced.php +++ b/src/Support/Rules/NoExternalSignIn.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace RefactorCircus\Roster\Domains\Sso\Support; +namespace RefactorCircus\Roster\Support\Rules; use Closure; use Illuminate\Contracts\Validation\ValidationRule; @@ -10,13 +10,12 @@ /** * For the app's password login form: fails when the email must sign in - * elsewhere (an organization's enforced SSO, or any other registered - * sign-in requirement), pointing the user at it. A requirement that throws - * is not caught, so the login fails closed. + * elsewhere (a registered sign-in requirement claims it), pointing the user + * at it. A requirement that throws is not caught, so the login fails closed. * - * 'email' => ['required', 'email', new NotSsoEnforced], + * 'email' => ['required', 'email', new NoExternalSignIn], */ -final class NotSsoEnforced implements ValidationRule +final class NoExternalSignIn implements ValidationRule { public function validate(string $attribute, mixed $value, Closure $fail): void { @@ -30,7 +29,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void return; } - $fail(__('roster::roster.sso_required', [ + $fail(__('roster::roster.external_sign_in_required', [ 'organization' => $signIn->label, 'url' => $signIn->url, ])); diff --git a/src/Support/Tables.php b/src/Support/Tables.php index 9f0fe1a..bc86c9e 100644 --- a/src/Support/Tables.php +++ b/src/Support/Tables.php @@ -36,11 +36,6 @@ final class Tables extends KeystoneTables 'permission_role' => 'roster_permission_role', 'role_assignments' => 'roster_role_assignments', 'impersonations' => 'roster_impersonations', - 'sso_connections' => 'roster_sso_connections', - 'sso_identities' => 'roster_sso_identities', - 'scim_tokens' => 'roster_scim_tokens', - 'scim_users' => 'roster_scim_users', - 'scim_groups' => 'roster_scim_groups', 'transfers' => 'roster_transfers', 'transfer_rows' => 'roster_transfer_rows', ]; diff --git a/tests/Browser/ScimBrowserTest.php b/tests/Browser/ScimBrowserTest.php deleted file mode 100644 index 4fda31a..0000000 --- a/tests/Browser/ScimBrowserTest.php +++ /dev/null @@ -1,18 +0,0 @@ - signInAsSuperAdmin()); - -it('issues a SCIM token and shows it once', function (): void { - organization(attributes: ['name' => 'Acme']); - - visit('/atrium/roster/organizations/acme?tab=scim') - ->assertSee('/scim/v2/acme') - ->type('#scim-token-name', 'Okta') - ->click('@create-scim-token') - ->assertSee('Copy this token now') - ->assertPresent('@scim-token'); -}); diff --git a/tests/Browser/SsoBrowserTest.php b/tests/Browser/SsoBrowserTest.php deleted file mode 100644 index 93c1b8e..0000000 --- a/tests/Browser/SsoBrowserTest.php +++ /dev/null @@ -1,28 +0,0 @@ - signInAsSuperAdmin()); - -it('creates an Entra ID connection and shows its callback URL', function (): void { - organization(attributes: ['name' => 'Acme']); - - visit('/atrium/roster/organizations/acme?tab=sso') - ->assertVisible('[data-sso-field="issuer"]') - ->assertMissing('[data-sso-field="tenant"]') - ->assertMissing('[data-sso-field="metadata_url"]') - ->select('protocol', 'saml') - ->assertVisible('[data-sso-field="metadata_url"]') - ->assertMissing('[data-sso-field="client_id"]') - ->type('name', 'Entra') - ->select('protocol', 'azure') - ->assertMissing('[data-sso-field="issuer"]') - ->type('tenant', 'acme.onmicrosoft.com') - ->type('client_id', 'app') - ->type('client_secret', 'secret') - ->click('@create-sso') - ->assertSee('SSO connection created.') - ->assertSee('/roster/sso/acme-entra/callback'); -}); diff --git a/tests/Feature/Http/ScimTokensHttpTest.php b/tests/Feature/Http/ScimTokensHttpTest.php deleted file mode 100644 index 2ff79dc..0000000 --- a/tests/Feature/Http/ScimTokensHttpTest.php +++ /dev/null @@ -1,30 +0,0 @@ - 'Acme']); - - $response = $this->postJson(route('roster.organizations.scim-tokens.store', 'acme'), ['name' => 'Okta', 'expires_in_days' => 30]) - ->assertCreated() - ->assertJsonPath('data.usable', true) - ->assertJsonPath('data.base_url', url('scim/v2/acme')); - - $token = (string) $response->json('token'); - - expect($token)->toStartWith('scim_') - ->and(ScimTokenModel::query()->sole()->token_hash)->toBe(hash('sha256', $token)); - - $this->getJson(route('roster.organizations.scim-tokens.index', 'acme'))->assertOk()->assertJsonMissingPath('token')->assertDontSee($token); - - mcpTool(ListScimTokensTool::class, ['organization' => 'acme'])->assertOk()->assertDontSee($token); - mcpTool(CreateScimTokenTool::class, ['organization' => 'acme', 'name' => 'Entra'])->assertOk()->assertSee('scim_'); - - $this->deleteJson(route('roster.scim-tokens.destroy', ScimTokenModel::query()->where('name', 'Okta')->sole()->id))->assertOk()->assertJsonPath('data.usable', false); - mcpTool(RevokeScimTokenTool::class, ['token' => ScimTokenModel::query()->where('name', 'Entra')->sole()->id])->assertOk(); -}); diff --git a/tests/Feature/Http/SsoHttpTest.php b/tests/Feature/Http/SsoHttpTest.php deleted file mode 100644 index f5a4c88..0000000 --- a/tests/Feature/Http/SsoHttpTest.php +++ /dev/null @@ -1,46 +0,0 @@ - 'Acme']); - - $this->postJson(route('roster.organizations.sso-connections.store', 'acme'), [ - 'name' => 'Entra', 'slug' => 'acme-entra', 'protocol' => 'azure', - 'tenant' => 'acme.onmicrosoft.com', 'client_id' => 'app', 'client_secret' => 'top-secret', - ]) - ->assertCreated() - ->assertJsonPath('data.settings.tenant', 'acme.onmicrosoft.com') - ->assertJsonPath('data.client_secret', 'set') - ->assertJsonPath('data.callback_url', route('roster.sso.callback', 'acme-entra')); - - $this->patchJson(route('roster.sso-connections.update', 'acme-entra'), ['enforced' => true])->assertOk()->assertJsonPath('data.enforced', true); - - mcpTool(ShowSsoConnectionTool::class, ['connection' => 'acme-entra']) - ->assertOk() - ->assertStructuredContent(test()->getJson(route('roster.sso-connections.show', 'acme-entra'))->json()) - ->assertDontSee('top-secret'); - - mcpTool(CreateSsoConnectionTool::class, ['organization' => 'acme', 'name' => 'Okta', 'protocol' => 'oidc', 'issuer' => 'https://idp.test', 'client_id' => 'a', 'client_secret' => 'b'])->assertOk(); - - $this->getJson(route('roster.organizations.sso-connections.index', 'acme'))->assertOk()->assertJsonPath('meta.total', 2); - $this->deleteJson(route('roster.sso-connections.destroy', 'acme-entra'))->assertNoContent(); -}); - -it('lists and unlinks identities', function (): void { - require_once dirname(__DIR__).'/Sso/helpers.php'; - $connection = acmeWithSso(); - $ada = user(); - $identity = SsoIdentityModel::query()->create(['connection_id' => $connection->id, 'user_id' => $ada->getKey(), 'subject' => 's1', 'email' => 'ada@acme.test']); - - $this->getJson(route('roster.users.sso-identities.index', $ada->getRouteKey()))->assertOk()->assertJsonPath('data.0.subject', 's1'); - mcpTool(ListSsoIdentitiesTool::class, ['user' => $ada->getRouteKey()])->assertOk()->assertSee('s1'); - - $this->deleteJson(route('roster.sso-identities.destroy', $identity->id))->assertNoContent(); - expect(SsoIdentityModel::query()->count())->toBe(0); -}); diff --git a/tests/Feature/Scim/ScimAuditContextTest.php b/tests/Feature/Scim/ScimAuditContextTest.php deleted file mode 100644 index 9bc5ff5..0000000 --- a/tests/Feature/Scim/ScimAuditContextTest.php +++ /dev/null @@ -1,132 +0,0 @@ - - */ - protected function getPackageProviders($app): array - { - return [ - ...parent::getPackageProviders($app), - KeenServiceProvider::class, - ]; - } -} - -uses(InstallsKeenForScimAudit::class); - -/** - * The SCIM domain adds its token to Roster's audit entries itself, through - * Keystone's AuditHooks; Roster's own audit hooks know nothing of SCIM. - */ -function scimAuditEntry(string $action): AuditEntryModel -{ - return AuditEntryModel::query()->where('action', $action)->latest('id')->firstOrFail(); -} - -function oktaToken(): ScimTokenModel -{ - scimOrg(); - - return ScimTokenModel::query()->where('name', 'Okta')->sole(); -} - -it('records the SCIM token a change came through, with the same shape', function (): void { - [, $this->scimToken] = scimOrg(); - $token = ScimTokenModel::query()->where('name', 'Okta')->sole(); - - scim('POST', '/Users', oktaUser())->assertCreated(); - - $entry = scimAuditEntry('user.created'); - - expect($entry->surface)->toBe('scim') - ->and($entry->context['scim_token']['name'])->toBe('Okta') - ->and($entry->context['scim_token'])->toBe(['id' => $token->id, 'name' => 'Okta']); -}); - -it('adds the SCIM token to Roster entries only, not to other packages\' events', function (): void { - app(PackageRegistry::class)->register(Package::make('billing', 'RefactorCircus\Roster\Tests\Fixtures\Billing')); - $token = oktaToken(); - $ada = user(['name' => 'Ada']); - organization($ada); - - app(ScimContext::class)->token = $token; - - event(new InvoicePayingActionEvent($ada)); - event(new InvoicePaidActionEvent($ada)); - app(SuspendUserAction::class)->execute($ada); - - $invoice = scimAuditEntry('invoice.paid'); - - expect($invoice->source)->toBe('billing') - ->and($invoice->context ?? [])->not->toHaveKey('scim_token') - ->and(scimAuditEntry('user.suspended')->context['scim_token'])->toBe(['id' => $token->id, 'name' => 'Okta']); -}); - -it('writes the entry without the SCIM token, and reports why, when the SCIM context throws', function (): void { - Exceptions::fake(); - $grace = user(['name' => 'Grace']); - - app()->bind(ScimContext::class, fn (): never => throw new RuntimeException('SCIM context unavailable')); - - app(SuspendUserAction::class)->execute($grace); - - $entry = scimAuditEntry('user.suspended'); - - expect($entry->subject_id)->toBe((string) $grace->getKey()) - ->and($entry->context ?? [])->not->toHaveKey('scim_token'); - - Exceptions::assertReported(fn (RuntimeException $e): bool => $e->getMessage() === 'SCIM context unavailable'); -}); - -it('registers the SCIM audit context only while Roster audits', function (bool $enabled, array $expected): void { - $token = oktaToken(); - config()->set('roster.audit.enabled', $enabled); - - // Boot the SCIM domain again, on fresh hooks and registries: booted - // callbacks run at once on a booted application. - app()->instance(AuditHooks::class, $hooks = new AuditHooks); - - foreach ([Resources::class, PermissionCatalogue::class, MembershipSources::class] as $registry) { - app()->forgetInstance($registry); - } - - (new ScimServiceProvider(app()))->boot(); - - app(ScimContext::class)->token = $token; - - $context = $hooks->contextFor(new UserCreatedEvent(new UserModel), null); - - expect($context)->toBe(array_map(fn (string $name): array => ['id' => $token->id, 'name' => $name], $expected)); -})->with([ - 'auditing' => [true, ['scim_token' => 'Okta']], - 'roster.audit.enabled off' => [false, []], -]); diff --git a/tests/Feature/Scim/ScimAuthTest.php b/tests/Feature/Scim/ScimAuthTest.php deleted file mode 100644 index 407ac61..0000000 --- a/tests/Feature/Scim/ScimAuthTest.php +++ /dev/null @@ -1,43 +0,0 @@ -scimToken] = scimOrg(); -}); - -it('accepts a valid token and stamps its use', function (): void { - scim('GET', '/Users')->assertOk()->assertHeader('Content-Type', 'application/scim+json'); - - expect(ScimTokenModel::query()->sole()->last_used_at)->not->toBeNull(); -}); - -it('refuses missing, wrong, revoked, expired and other-organization tokens', function (string $case): void { - $token = match ($case) { - 'missing' => '', - 'wrong' => 'scim_nope', - 'revoked' => (function (): string { - app(RevokeScimTokenAction::class)->execute(ScimTokenModel::query()->sole()); - - return $this->scimToken; - })(), - 'expired' => (function (): string { - ScimTokenModel::query()->update(['expires_at' => now()->subDay()]); - - return $this->scimToken; - })(), - 'other organization' => app(CreateScimTokenAction::class)->execute(organization(attributes: ['name' => 'Globex']), new CreateScimTokenData(name: 'x'))->plain, - }; - - scim('GET', '/Users', token: $token) - ->assertUnauthorized() - ->assertJsonPath('schemas.0', 'urn:ietf:params:scim:api:messages:2.0:Error') - ->assertJsonPath('status', '401'); -})->with(['missing', 'wrong', 'revoked', 'expired', 'other organization']); diff --git a/tests/Feature/Scim/ScimGroupsTest.php b/tests/Feature/Scim/ScimGroupsTest.php deleted file mode 100644 index 53e9628..0000000 --- a/tests/Feature/Scim/ScimGroupsTest.php +++ /dev/null @@ -1,61 +0,0 @@ -acme, $this->scimToken] = scimOrg(); - $this->ada = (string) scim('POST', '/Users', oktaUser())->json('id'); - $this->grace = (string) scim('POST', '/Users', oktaUser('grace@acme.test', '00u2'))->json('id'); -}); - -it('creates a group as a team with members', function (): void { - $group = scim('POST', '/Groups', ['schemas' => ['urn:ietf:params:scim:schemas:core:2.0:Group'], 'displayName' => 'Engineering', 'members' => [['value' => $this->ada]]]) - ->assertCreated() - ->assertJsonPath('displayName', 'Engineering') - ->assertJsonPath('members.0.value', $this->ada) - ->json(); - - $team = TeamModel::query()->sole(); - - expect($team->name)->toBe('Engineering') - ->and($team->hasMember(User::query()->where('email', 'ada@acme.test')->sole()))->toBeTrue(); - - scim('GET', '/Users/'.$this->ada)->assertJsonPath('groups.0.value', $group['id']); -}); - -it('adds, removes and replaces members with PATCH', function (): void { - $id = (string) scim('POST', '/Groups', ['displayName' => 'Engineering'])->json('id'); - - scim('PATCH', '/Groups/'.$id, patchOps([['op' => 'add', 'path' => 'members', 'value' => [['value' => $this->ada], ['value' => $this->grace]]]])) - ->assertOk() - ->assertJsonCount(2, 'members'); - - scim('PATCH', '/Groups/'.$id, patchOps([['op' => 'remove', 'path' => 'members[value eq "'.$this->ada.'"]']])) - ->assertOk() - ->assertJsonCount(1, 'members') - ->assertJsonPath('members.0.value', $this->grace); - - scim('PATCH', '/Groups/'.$id, patchOps([['op' => 'replace', 'path' => 'displayName', 'value' => 'Platform']])) - ->assertOk() - ->assertJsonPath('displayName', 'Platform'); - - scim('GET', '/Groups?filter='.urlencode('members.value eq "'.$this->grace.'"'))->assertJsonPath('totalResults', 1); - scim('GET', '/Groups?filter='.urlencode('displayName eq "platform"'))->assertJsonPath('totalResults', 1); -}); - -it('refuses members from outside the organization', function (): void { - scim('POST', '/Groups', ['displayName' => 'Eng', 'members' => [['value' => '01JAAAAAAAAAAAAAAAAAAAAAAA']]])->assertStatus(400); -}); - -it('deletes a group and its team', function (): void { - $id = (string) scim('POST', '/Groups', ['displayName' => 'Engineering'])->json('id'); - - scim('DELETE', '/Groups/'.$id)->assertNoContent(); - - expect(TeamModel::query()->count())->toBe(0); -}); diff --git a/tests/Feature/Scim/ScimProtocolTest.php b/tests/Feature/Scim/ScimProtocolTest.php deleted file mode 100644 index c1ea81f..0000000 --- a/tests/Feature/Scim/ScimProtocolTest.php +++ /dev/null @@ -1,116 +0,0 @@ -acme, $this->scimToken] = scimOrg(); -}); - -it('rejects unsupported filters', function (string $filter): void { - scim('GET', '/Users?filter='.urlencode($filter))->assertStatus(400)->assertJsonPath('scimType', 'invalidFilter'); -})->with([ - 'unknown attribute' => 'title eq "x"', - 'unknown operator' => 'userName gt "x"', - 'or' => 'userName eq "a" or userName eq "b"', - 'garbage' => 'userName eq "x"; DROP TABLE users', - 'unterminated' => 'userName eq "x', -]); - -it('pages with startIndex and count', function (): void { - foreach (['a', 'b', 'c'] as $name) { - scim('POST', '/Users', oktaUser($name.'@acme.test', $name))->assertCreated(); - } - - scim('GET', '/Users?startIndex=2&count=1') - ->assertOk() - ->assertJsonPath('totalResults', 3) - ->assertJsonPath('startIndex', 2) - ->assertJsonPath('itemsPerPage', 1) - ->assertJsonPath('Resources.0.userName', 'b@acme.test'); -}); - -it('honours ETags', function (): void { - $created = scim('POST', '/Users', oktaUser()); - $id = (string) $created->json('id'); - $etag = (string) $created->headers->get('ETag'); - - expect($etag)->toStartWith('W/"')->toBe($created->json('meta.version')); - - test()->call('GET', '/scim/v2/acme/Users/'.$id, [], [], [], ['HTTP_AUTHORIZATION' => 'Bearer '.$this->scimToken, 'HTTP_IF_NONE_MATCH' => $etag])->assertStatus(304); - - scim('PATCH', '/Users/'.$id, patchOps([['op' => 'replace', 'path' => 'displayName', 'value' => 'X']]), headers: ['If-Match' => 'W/"stale"']) - ->assertStatus(412); - - scim('PATCH', '/Users/'.$id, patchOps([['op' => 'replace', 'path' => 'displayName', 'value' => 'X']]), headers: ['If-Match' => $etag]) - ->assertOk(); -}); - -it('runs bulk requests with bulkId references', function (): void { - $response = scim('POST', '/Bulk', [ - 'schemas' => ['urn:ietf:params:scim:api:messages:2.0:BulkRequest'], - 'Operations' => [ - ['method' => 'POST', 'path' => '/Users', 'bulkId' => 'ada', 'data' => oktaUser()], - ['method' => 'POST', 'path' => '/Groups', 'bulkId' => 'eng', 'data' => ['displayName' => 'Engineering', 'members' => [['value' => 'bulkId:ada']]]], - ['method' => 'PATCH', 'path' => '/Users/bulkId:ada', 'data' => patchOps([['op' => 'replace', 'path' => 'displayName', 'value' => 'Countess']])], - ], - ])->assertOk(); - - expect(collect($response->json('Operations'))->pluck('status')->all())->toBe(['201', '201', '200']); - - scim('GET', '/Groups')->assertJsonPath('Resources.0.members.0.value', ScimUserModel::query()->sole()->id); -}); - -it('stops bulk work after failOnErrors', function (): void { - $response = scim('POST', '/Bulk', [ - 'failOnErrors' => 1, - 'Operations' => [ - ['method' => 'POST', 'path' => '/Users', 'data' => oktaUser('eve@gmail.test')], - ['method' => 'POST', 'path' => '/Users', 'data' => oktaUser()], - ], - ])->assertOk(); - - expect($response->json('Operations'))->toHaveCount(1) - ->and($response->json('Operations.0.status'))->toBe('400') - ->and(ScimUserModel::query()->count())->toBe(0); -}); - -it('limits bulk size', function (): void { - config()->set('roster.scim.bulk.max_operations', 1); - - scim('POST', '/Bulk', ['Operations' => [ - ['method' => 'POST', 'path' => '/Users', 'data' => oktaUser()], - ['method' => 'POST', 'path' => '/Users', 'data' => oktaUser('b@acme.test', 'b')], - ]])->assertStatus(413)->assertJsonPath('scimType', 'tooMany'); -}); - -it('describes itself', function (): void { - scim('GET', '/ServiceProviderConfig') - ->assertOk() - ->assertJsonPath('patch.supported', true) - ->assertJsonPath('bulk.supported', true) - ->assertJsonPath('etag.supported', true) - ->assertJsonPath('changePassword.supported', false) - ->assertJsonPath('authenticationSchemes.0.type', 'oauthbearertoken'); - - scim('GET', '/ResourceTypes')->assertOk()->assertJsonPath('totalResults', 2)->assertJsonPath('Resources.0.endpoint', '/Users'); - scim('GET', '/Schemas')->assertOk()->assertJsonPath('Resources.0.id', 'urn:ietf:params:scim:schemas:core:2.0:User'); -}); - -it('matches eq filters exactly, even with LIKE wildcards in the value', function (): void { - scim('POST', '/Users', oktaUser('a_b@acme.test', 'ext-1'))->assertCreated(); - scim('POST', '/Users', oktaUser('axb@acme.test', 'ext-2'))->assertCreated(); - - scim('GET', '/Users?filter='.urlencode('userName eq "A_B@acme.test"')) - ->assertOk() - ->assertJsonPath('totalResults', 1) - ->assertJsonPath('Resources.0.userName', 'a_b@acme.test'); - - scim('GET', '/Users?filter='.urlencode('userName eq "AXB@ACME.TEST"')) - ->assertOk() - ->assertJsonPath('totalResults', 1) - ->assertJsonPath('Resources.0.userName', 'axb@acme.test'); -}); diff --git a/tests/Feature/Scim/ScimUsersTest.php b/tests/Feature/Scim/ScimUsersTest.php deleted file mode 100644 index 3aa7db2..0000000 --- a/tests/Feature/Scim/ScimUsersTest.php +++ /dev/null @@ -1,178 +0,0 @@ -acme, $this->scimToken] = scimOrg(); -}); - -function createAda(): string -{ - return (string) scim('POST', '/Users', oktaUser())->assertCreated()->json('id'); -} - -it('provisions a new member from Okta', function (): void { - $response = scim('POST', '/Users', oktaUser()) - ->assertCreated() - ->assertHeader('Location') - ->assertHeader('ETag') - ->assertJsonPath('userName', 'ada@acme.test') - ->assertJsonPath('name.formatted', 'Ada Lovelace') - ->assertJsonPath('displayName', 'Ada Lovelace') - ->assertJsonPath('externalId', '00u1okta') - ->assertJsonPath('active', true) - ->assertJsonPath('meta.resourceType', 'User'); - - $user = User::query()->where('email', 'ada@acme.test')->sole(); - - expect($this->acme->membershipFor($user)?->source)->toBe('scim') - ->and(ScimUserModel::query()->sole()->id)->toBe($response->json('id')) - ->and(ScimUserModel::query()->sole()->created_by_scim)->toBeTrue(); -}); - -it('gets, lists and filters users the way identity providers probe', function (): void { - $id = createAda(); - - scim('GET', '/Users/'.$id)->assertOk()->assertJsonPath('id', $id); - scim('GET', '/Users?filter='.urlencode('userName eq "ADA@acme.test"'))->assertOk()->assertJsonPath('totalResults', 1); - scim('GET', '/Users?filter='.urlencode('externalId eq "00u1okta"'))->assertOk()->assertJsonPath('Resources.0.id', $id); - scim('GET', '/Users?filter='.urlencode('userName eq "nobody@acme.test"'))->assertOk()->assertJsonPath('totalResults', 0)->assertJsonPath('Resources', []); - scim('GET', '/Users/01JAAAAAAAAAAAAAAAAAAAAAAA')->assertNotFound()->assertJsonPath('status', '404'); -}); - -it('never matches a different account through LIKE wildcards', function (): void { - scim('POST', '/Users', oktaUser('axb@acme.test', 'x1'))->assertCreated(); - - scim('GET', '/Users?filter='.urlencode('userName eq "a_b@acme.test"'))->assertOk()->assertJsonPath('totalResults', 0); -}); - -it('links an existing account on the organization\'s domain', function (): void { - $ada = user(['email' => 'ada@acme.test']); - - scim('POST', '/Users', oktaUser())->assertCreated(); - - expect(ScimUserModel::query()->sole()->user_id)->toBe($ada->getKey()) - ->and(ScimUserModel::query()->sole()->created_by_scim)->toBeFalse(); -}); - -it('refuses emails outside the organization\'s domains', function (): void { - user(['email' => 'victim@gmail.test']); - - scim('POST', '/Users', oktaUser('victim@gmail.test'))->assertStatus(400)->assertJsonPath('scimType', 'invalidValue'); - - expect(ScimUserModel::query()->count())->toBe(0); -}); - -it('refuses duplicates', function (): void { - createAda(); - - scim('POST', '/Users', oktaUser())->assertStatus(409)->assertJsonPath('scimType', 'uniqueness'); -}); - -it('deprovisions with Okta\'s PATCH and restores', function (): void { - $id = createAda(); - $ada = User::query()->where('email', 'ada@acme.test')->sole(); - - scim('PATCH', '/Users/'.$id, patchOps([['op' => 'replace', 'value' => ['active' => false]]]))->assertOk()->assertJsonPath('active', false); - - // Created by SCIM and in no other organization: deactivated, never deleted. - expect($this->acme->membershipFor($ada))->toBeNull() - ->and(app(Users::class)->status($ada->refresh()))->toBe(UserStatus::Deactivated) - ->and(User::query()->whereKey($ada->getKey())->exists())->toBeTrue(); - - scim('PATCH', '/Users/'.$id, patchOps([['op' => 'replace', 'value' => ['active' => true]]]))->assertOk()->assertJsonPath('active', true); - - expect($this->acme->membershipFor($ada))->not->toBeNull() - ->and(app(Users::class)->status($ada->refresh()))->toBe(UserStatus::Active); -}); - -it('deprovisions with Entra\'s capitalised ops and string booleans', function (): void { - $id = createAda(); - - scim('PATCH', '/Users/'.$id, patchOps([['op' => 'Replace', 'path' => 'active', 'value' => 'False']]))->assertOk()->assertJsonPath('active', false); -}); - -it('keeps accounts that belong to other organizations active', function (): void { - $ada = user(['email' => 'ada@acme.test']); - app(AddMemberAction::class)->execute(organization(attributes: ['name' => 'Globex']), new AddMemberData(user: $ada->getRouteKey())); - $id = (string) scim('POST', '/Users', oktaUser())->json('id'); - - scim('DELETE', '/Users/'.$id)->assertNoContent(); - - expect($this->acme->membershipFor($ada))->toBeNull() - ->and(app(Users::class)->status($ada))->toBe(UserStatus::Active); - - scim('GET', '/Users/'.$id)->assertNotFound(); -}); - -it('protects the organization\'s owner', function (): void { - $owner = $this->acme->owner; - $owner->update(['email' => 'boss@acme.test']); - $id = (string) scim('POST', '/Users', oktaUser('boss@acme.test', 'boss'))->json('id'); - - scim('PATCH', '/Users/'.$id, patchOps([['op' => 'replace', 'path' => 'active', 'value' => false]])) - ->assertStatus(409) - ->assertJsonPath('scimType', 'mutability'); -}); - -it('replaces a user with PUT', function (): void { - $id = createAda(); - - scim('PUT', '/Users/'.$id, ['userName' => 'ada.king@acme.test', 'name' => ['formatted' => 'Ada King'], 'displayName' => 'Countess', 'active' => true, 'externalId' => '00u1okta']) - ->assertOk() - ->assertJsonPath('userName', 'ada.king@acme.test') - ->assertJsonPath('name.formatted', 'Ada King') - ->assertJsonPath('displayName', 'Countess'); - - scim('PUT', '/Users/'.$id, ['userName' => 'ada@elsewhere.test'])->assertStatus(400); -}); - -it('patches names and emails by path', function (): void { - $id = createAda(); - - scim('PATCH', '/Users/'.$id, patchOps([ - ['op' => 'replace', 'path' => 'name.familyName', 'value' => 'King'], - ['op' => 'replace', 'path' => 'emails[type eq "work"].value', 'value' => 'ada.k@acme.test'], - ['op' => 'replace', 'path' => 'userName', 'value' => 'ada.k@acme.test'], - ]))->assertOk()->assertJsonPath('name.formatted', 'Ada King')->assertJsonPath('userName', 'ada.k@acme.test'); - - scim('PATCH', '/Users/'.$id, patchOps([['op' => 'replace', 'path' => 'nickName', 'value' => 'x']])) - ->assertStatus(400) - ->assertJsonPath('scimType', 'invalidPath'); -}); - -it('links the SSO identity from externalId when the token names a connection', function (): void { - $connection = SsoConnectionModel::factory()->create(['organization_id' => $this->acme->id, 'slug' => 'acme-okta']); - [, $this->scimToken] = [null, app(CreateScimTokenAction::class)->execute($this->acme, new CreateScimTokenData(name: 'Okta SSO', ssoConnection: 'acme-okta'))->plain]; - - createAda(); - - expect(SsoIdentityModel::query()->sole()->only(['connection_id', 'subject']))->toBe(['connection_id' => $connection->id, 'subject' => '00u1okta']); -}); - -it('writes nothing for a PATCH that only echoes the current view', function (): void { - $id = (string) scim('POST', '/Users', ['userName' => 'grace@acme.test', 'name' => ['formatted' => 'Grace Hopper']])->json('id'); - $changes = 0; - Event::listen(ActionFinishedEvent::class, function () use (&$changes): void { - $changes++; - }); - - scim('PATCH', '/Users/'.$id, patchOps([['op' => 'replace', 'path' => 'externalId', 'value' => null]]))->assertOk(); - - expect($changes)->toBe(0); -}); diff --git a/tests/Feature/Scim/helpers.php b/tests/Feature/Scim/helpers.php deleted file mode 100644 index 005d27c..0000000 --- a/tests/Feature/Scim/helpers.php +++ /dev/null @@ -1,54 +0,0 @@ - 'Acme', 'domains' => ['acme.test']]); - $issued = app(CreateScimTokenAction::class)->execute($acme, CreateScimTokenData::from(['name' => 'Okta'] + $token)); - - return [$acme, $issued->plain]; -} - -function scim(string $method, string $path, array $body = [], ?string $token = null, array $headers = []): TestResponse -{ - $token ??= test()->scimToken; - - return test()->json($method, '/scim/v2/acme'.$path, $body, ['Authorization' => 'Bearer '.$token, 'Content-Type' => 'application/scim+json'] + $headers); -} - -/** - * The user Okta sends when assigning someone to the app. - * - * @return array - */ -function oktaUser(string $email = 'ada@acme.test', string $externalId = '00u1okta'): array -{ - return [ - 'schemas' => ['urn:ietf:params:scim:schemas:core:2.0:User'], - 'userName' => $email, - 'name' => ['givenName' => 'Ada', 'familyName' => 'Lovelace'], - 'emails' => [['primary' => true, 'value' => $email, 'type' => 'work']], - 'displayName' => 'Ada Lovelace', - 'externalId' => $externalId, - 'active' => true, - ]; -} - -/** - * @return array - */ -function patchOps(array $operations): array -{ - return ['schemas' => ['urn:ietf:params:scim:api:messages:2.0:PatchOp'], 'Operations' => $operations]; -} diff --git a/tests/Feature/Sso/AzureFlowTest.php b/tests/Feature/Sso/AzureFlowTest.php deleted file mode 100644 index fb5ed36..0000000 --- a/tests/Feature/Sso/AzureFlowTest.php +++ /dev/null @@ -1,58 +0,0 @@ -connection = acmeWithSso(protocol: 'azure'); -}); - -function graphReturns(array $me): void -{ - app()->instance('roster.sso.http', new Client(['handler' => HandlerStack::create(new MockHandler([ - new Response(200, [], (string) json_encode(['access_token' => 'at', 'token_type' => 'Bearer'])), - new Response(200, [], (string) json_encode($me)), - ]))])); -} - -it('signs in through Microsoft Entra ID using the tenant-specific authority', function (): void { - $location = (string) $this->get(route('roster.sso.start', 'acme-sso'))->headers->get('Location'); - - expect($location)->toStartWith('https://login.microsoftonline.com/11111111-2222-3333-4444-555555555555/oauth2/v2.0/authorize?'); - - graphReturns(['id' => 'oid-1', 'displayName' => 'Ada', 'userPrincipalName' => 'Ada@acme.test', 'mail' => 'ada@acme.test']); - - $this->get(route('roster.sso.callback', ['acme-sso', 'code' => 'c', 'state' => queryOf($location)['state']]))->assertRedirect('/'); - - expect(Auth::user()?->getAttribute('email'))->toBe('ada@acme.test'); -}); - -it('trusts the userPrincipalName, never the mail attribute', function (): void { - // A tenant admin can set `mail` to anyone's address; the UPN must be on a - // domain the tenant verified. - user(['email' => 'ceo@acme.test']); - $location = (string) $this->get(route('roster.sso.start', 'acme-sso'))->headers->get('Location'); - - graphReturns(['id' => 'oid-evil', 'displayName' => 'Eve', 'userPrincipalName' => 'eve@evil.test', 'mail' => 'ceo@acme.test']); - - $this->get(route('roster.sso.callback', ['acme-sso', 'code' => 'c', 'state' => queryOf($location)['state']])) - ->assertSessionHasErrors('sso'); - - expect(Auth::check())->toBeFalse(); -}); - -it('refuses multi-tenant authorities', function (string $tenant): void { - app(CreateSsoConnectionAction::class)->execute($this->connection->organization, CreateSsoConnectionData::from([ - 'name' => 'Entra', 'protocol' => 'azure', 'tenant' => $tenant, 'client_id' => 'x', 'client_secret' => 'y', - ])); -})->with(['common', 'organizations', 'consumers'])->throws(ValidationException::class); diff --git a/tests/Feature/Sso/OidcFlowTest.php b/tests/Feature/Sso/OidcFlowTest.php deleted file mode 100644 index 9247660..0000000 --- a/tests/Feature/Sso/OidcFlowTest.php +++ /dev/null @@ -1,65 +0,0 @@ -idp = new FakeIdp; - $this->connection = acmeWithSso(); -}); - -function startOidc(): array -{ - $location = (string) test()->get(route('roster.sso.start', 'acme-sso'))->assertRedirect()->headers->get('Location'); - - expect($location)->toStartWith('https://idp.test/authorize?'); - - return queryOf($location); -} - -it('signs a user in end to end', function (): void { - $query = startOidc(); - - expect($query['client_id'])->toBe('roster-app') - ->and($query['scope'])->toBe('openid email profile') - ->and($query['redirect_uri'])->toBe(route('roster.sso.callback', 'acme-sso')); - - $this->idp->idToken = $this->idp->sign(['sub' => 'okta-1', 'email' => 'ada@acme.test', 'name' => 'Ada', 'nonce' => $query['nonce']]); - - $this->get(route('roster.sso.callback', ['acme-sso', 'code' => 'c', 'state' => $query['state']]))->assertRedirect('/'); - - expect(Auth::user()?->getAttribute('email'))->toBe('ada@acme.test'); -}); - -it('discovers the connection from an email domain', function (): void { - $this->get(route('roster.sso.discover', ['email' => 'ada@acme.test']))->assertRedirect(route('roster.sso.start', 'acme-sso')); - $this->get(route('roster.sso.discover', ['email' => 'ada@nowhere.test']))->assertSessionHasErrors('email'); -}); - -it('refuses tokens that fail verification', function (string $case): void { - $query = startOidc(); - $claims = ['sub' => 'okta-1', 'email' => 'ada@acme.test', 'nonce' => $query['nonce']]; - $state = $query['state']; - - $this->idp->idToken = match ($case) { - 'forged signature' => $this->idp->sign($claims, (new FakeIdp)->privateKey), - 'wrong audience' => $this->idp->sign(['aud' => 'someone-else'] + $claims), - 'wrong nonce' => $this->idp->sign(['nonce' => 'replayed'] + $claims), - 'expired' => $this->idp->sign(['exp' => time() - 3600, 'iat' => time() - 7200] + $claims), - 'wrong issuer' => $this->idp->sign(['iss' => 'https://evil.test'] + $claims), - 'bad state' => $this->idp->sign($claims), - }; - - if ($case === 'bad state') { - $state = 'tampered'; - } - - $this->get(route('roster.sso.callback', ['acme-sso', 'code' => 'c', 'state' => $state])) - ->assertRedirect('/') - ->assertSessionHasErrors('sso'); - - expect(Auth::check())->toBeFalse(); -})->with(['forged signature', 'wrong audience', 'wrong nonce', 'expired', 'wrong issuer', 'bad state']); diff --git a/tests/Feature/Sso/SsoLoginActionTest.php b/tests/Feature/Sso/SsoLoginActionTest.php deleted file mode 100644 index 49aa87a..0000000 --- a/tests/Feature/Sso/SsoLoginActionTest.php +++ /dev/null @@ -1,118 +0,0 @@ -execute($connection, claims()); - - expect($method)->toBe('jit') - ->and($user->getAttribute('email'))->toBe('ada@acme.test') - ->and($user->getAttribute('email_verified_at'))->not->toBeNull() - ->and($connection->organization->membershipFor($user))->not->toBeNull() - ->and(SsoIdentityModel::query()->sole()->subject)->toBe('sub-1'); - - Event::assertDispatched(SsoLoginSucceededActionEvent::class, fn (SsoLoginSucceededActionEvent $event): bool => $event->method === 'jit'); -}); - -it('matches returning users by subject, even after an email change', function (): void { - $connection = acmeWithSso(); - [$first] = app(SsoLoginAction::class)->execute($connection, claims()); - - [$again, $method] = app(SsoLoginAction::class)->execute($connection, claims('renamed@elsewhere.test')); - - expect($method)->toBe('identity')->and($again->is($first))->toBeTrue(); -}); - -it('links an existing account on a trusted domain', function (): void { - $connection = acmeWithSso(); - $ada = user(['email' => 'Ada@acme.test']); - - [$user, $method] = app(SsoLoginAction::class)->execute($connection, claims()); - - expect($method)->toBe('linked')->and($user->is($ada))->toBeTrue(); -}); - -it('refuses emails outside the organization\'s domains', function (): void { - $connection = acmeWithSso(); - user(['email' => 'eve@gmail.test']); - - app(SsoLoginAction::class)->execute($connection, claims('eve@gmail.test')); -})->throws(ValidationException::class); - -it('records refused sign-ins', function (): void { - Event::fake([SsoLoginFailedActionEvent::class]); - $connection = acmeWithSso(); - - try { - app(SsoLoginAction::class)->execute($connection, claims('eve@gmail.test')); - } catch (ValidationException) { - } - - Event::assertDispatched(SsoLoginFailedActionEvent::class, fn (SsoLoginFailedActionEvent $event): bool => $event->reason === 'untrusted_email' && $event->email === 'eve@gmail.test'); -}); - -it('refuses new accounts when just-in-time is off', function (): void { - $connection = acmeWithSso(['jit' => false]); - - app(SsoLoginAction::class)->execute($connection, claims()); -})->throws(ValidationException::class); - -it('refuses inactive users and disabled connections', function (string $case): void { - $connection = acmeWithSso($case === 'disabled' ? ['enabled' => false] : []); - - if ($case === 'inactive') { - app(SuspendUserAction::class)->execute(user(['email' => 'ada@acme.test'])); - } - - app(SsoLoginAction::class)->execute($connection, claims()); -})->with(['inactive', 'disabled'])->throws(ValidationException::class); - -it('creates no duplicate users across logins', function (): void { - $connection = acmeWithSso(); - - app(SsoLoginAction::class)->execute($connection, claims()); - app(SsoLoginAction::class)->execute($connection, claims()); - - expect(User::query()->where('email', 'ada@acme.test')->count())->toBe(1); -}); - -it('keeps a just-in-time account the organization wants approved, and refuses its sign-in until then', function (): void { - $connection = acmeWithSso(); - $connection->organization->update(['provisioned_status' => 'pending']); - - expect(fn () => app(SsoLoginAction::class)->execute($connection, claims())) - ->toThrow(ValidationException::class, 'awaiting approval'); - - $ada = User::query()->where('email', 'ada@acme.test')->sole(); - - expect($ada->rosterStatus()->value)->toBe('pending') - ->and($connection->organization->membershipFor($ada))->not->toBeNull() - ->and(SsoIdentityModel::query()->sole()->user_id)->toBe($ada->id); - - app(ApproveUserAction::class)->execute($ada); - - [$user, $method] = app(SsoLoginAction::class)->execute($connection, claims()); - - expect($method)->toBe('identity')->and($user->is($ada))->toBeTrue(); -}); diff --git a/tests/Feature/Sso/SsoWiringTest.php b/tests/Feature/Sso/SsoWiringTest.php deleted file mode 100644 index f67afd1..0000000 --- a/tests/Feature/Sso/SsoWiringTest.php +++ /dev/null @@ -1,194 +0,0 @@ -instance(Sso::class, new class(request(), $subject, $email) extends Sso - { - public function __construct($request, private string $subject, private string $email) - { - parent::__construct($request); - } - - public function provider(SsoConnectionModel $connection): Provider - { - $user = (new SocialiteUser)->setRaw([])->map(['id' => $this->subject, 'email' => $this->email, 'name' => 'Someone']); - - return new class($user) implements Provider - { - public function __construct(private SocialiteUser $user) {} - - public function redirect() - { - return redirect('https://idp.test/authorize'); - } - - public function user() - { - return $this->user; - } - }; - } - }); -} - -it('maps SAML connections to the provider config and serves SP metadata', function (): void { - $connection = acmeWithSso(protocol: 'saml'); - $config = app(Sso::class)->samlConfig($connection); - - expect($config['entityid'])->toBe('https://idp.example.com/saml') - ->and($config['acs'])->toBe('https://idp.example.com/saml/sso') - ->and($config['sp_acs'])->toBe('roster/sso/acme-sso/callback'); - - $connection->update(['config' => ['metadata_url' => 'https://idp.example.com/metadata']]); - - expect(app(Sso::class)->samlConfig($connection->refresh()))->toHaveKey('metadata', 'https://idp.example.com/metadata') - ->not->toHaveKey('acs'); - - $this->get(route('roster.sso.metadata', 'acme-sso')) - ->assertOk() - ->assertSee('entityID="'.route('roster.sso.metadata', 'acme-sso').'"', false) - ->assertSee(route('roster.sso.callback', 'acme-sso'), false); -}); - -it('accepts the SAML assertion post without a CSRF token', function (): void { - acmeWithSso(protocol: 'saml'); - idpVouchesFor('name-id-1', 'ada@acme.test'); - - $this->post(route('roster.sso.callback', 'acme-sso'), ['SAMLResponse' => 'stub'])->assertRedirect('/'); - - expect(Auth::user()?->getAttribute('email'))->toBe('ada@acme.test'); -}); - -it('links an identity to the signed-in account', function (): void { - acmeWithSso(); - $ada = user(['email' => 'ada@gmail.test']); - $this->actingAs($ada); - idpVouchesFor('okta-ada', 'ada@acme.test'); - - $this->post(route('roster.sso.link', 'acme-sso'))->assertRedirect('https://idp.test/authorize'); - $this->get(route('roster.sso.callback', 'acme-sso'))->assertRedirect('/')->assertSessionHas('status'); - - expect(SsoIdentityModel::query()->sole()->user_id)->toBe($ada->getKey()); - - // Someone else cannot claim the same identity. - $this->actingAs(user()); - $this->post(route('roster.sso.link', 'acme-sso')); - $this->get(route('roster.sso.callback', 'acme-sso'))->assertSessionHasErrors('sso'); -}); - -it('enforces SSO for the organization\'s domains, except for super-admins', function (): void { - $connection = acmeWithSso(['enforced' => true]); - - expect(app(Roster::class)->externalSignInFor('ada@acme.test')?->record?->is($connection))->toBeTrue() - ->and(app(Roster::class)->externalSignInFor('ada@gmail.test'))->toBeNull() - ->and(validator(['email' => 'ada@acme.test'], ['email' => [new NotSsoEnforced]])->errors()->first('email'))->toContain('requires single sign-on'); - - $boss = user(['email' => 'boss@acme.test']); - grant($boss, 'super-admin'); - - expect(app(Roster::class)->externalSignInFor('boss@acme.test'))->toBeNull(); -}); - -it('points the enforced sign-in at the connection\'s start page, in the same message', function (): void { - acmeWithSso(['enforced' => true]); - - $signIn = app(Roster::class)->externalSignInFor('ada@acme.test'); - - expect($signIn)->toBeInstanceOf(ExternalSignIn::class) - ->and($signIn?->key)->toBe('acme-sso') - ->and($signIn?->label)->toBe('Acme') - ->and($signIn?->url)->toBe(route('roster.sso.start', 'acme-sso')) - ->and(validator(['email' => 'ada@acme.test'], ['email' => [new NotSsoEnforced]])->errors()->first('email')) - ->toBe(__('roster::roster.sso_required', ['organization' => 'Acme', 'url' => route('roster.sso.start', 'acme-sso')])); -}); - -it('ignores connections that are not enforced or not enabled, and values that are not emails', function (): void { - $connection = acmeWithSso(['enforced' => false]); - - expect(app(Roster::class)->externalSignInFor('ada@acme.test'))->toBeNull(); - - $connection->update(['enforced' => true, 'enabled' => false]); - - expect(app(Roster::class)->externalSignInFor('ada@acme.test'))->toBeNull() - ->and(app(Roster::class)->externalSignInFor('acme.test'))->toBeNull() - ->and(validator(['email' => ['ada@acme.test']], ['email' => [new NotSsoEnforced]])->passes())->toBeTrue(); -}); - -it('registers SSO enforcement as a sign-in requirement', function (): void { - acmeWithSso(['enforced' => true]); - - expect(app(SsoSignInRequirement::class)->for('ada@acme.test')?->key)->toBe('acme-sso') - ->and(app(SsoSignInRequirement::class)->for('ada@gmail.test'))->toBeNull() - ->and(method_exists(Roster::class, 'ssoRequiredFor'))->toBeFalse(); -}); - -it('fails the password login closed when a sign-in requirement throws', function (): void { - app(Roster::class)->requireSignIn(new class implements SignInRequirement - { - public function for(string $email): ?ExternalSignIn - { - throw new RuntimeException('identity provider unreachable'); - } - }); - - expect(fn () => validator(['email' => 'ada@acme.test'], ['email' => [new NotSsoEnforced]])->validate()) - ->toThrow(RuntimeException::class, 'identity provider unreachable'); -}); - -it('keeps secrets encrypted, hidden and redacted', function (): void { - $acme = organization(attributes: ['name' => 'Acme']); - - $connection = app(CreateSsoConnectionAction::class)->execute($acme, new CreateSsoConnectionData( - name: 'Okta', - protocol: 'oidc', - issuer: 'https://idp.test', - clientId: 'app', - clientSecret: 'top-secret', - )); - - $raw = (string) DB::table('roster_sso_connections')->value('config'); - - expect($raw)->not->toContain('top-secret') - ->and(json_encode((new SsoConnectionResource($connection))->resolve()))->not->toContain('top-secret'); - - // A blank secret keeps the old one; a new one replaces it. - app(UpdateSsoConnectionAction::class)->execute($connection, new UpdateSsoConnectionData(clientSecret: '')); - expect($connection->refresh()->setting('client_secret'))->toBe('top-secret'); - - app(UpdateSsoConnectionAction::class)->execute($connection, new UpdateSsoConnectionData(clientSecret: 'rotated')); - expect($connection->refresh()->setting('client_secret'))->toBe('rotated'); -}); - -it('validates the settings each protocol needs', function (array $data): void { - app(CreateSsoConnectionAction::class)->execute(organization(), CreateSsoConnectionData::from(['name' => 'X'] + $data)); -})->with([ - 'oidc without secret' => [['protocol' => 'oidc', 'issuer' => 'https://idp.test', 'client_id' => 'a']], - 'azure without tenant' => [['protocol' => 'azure', 'client_id' => 'a', 'client_secret' => 'b']], - 'saml without anything' => [['protocol' => 'saml']], -])->throws(ValidationException::class); diff --git a/tests/Feature/Sso/helpers.php b/tests/Feature/Sso/helpers.php deleted file mode 100644 index 24d9145..0000000 --- a/tests/Feature/Sso/helpers.php +++ /dev/null @@ -1,82 +0,0 @@ -idToken. - */ -final class FakeIdp -{ - public string $idToken = ''; - - public string $privateKey; - - /** @var array */ - public array $jwk; - - public function __construct(public string $issuer = 'https://idp.test') - { - $key = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]); - openssl_pkey_export($key, $pem); - $this->privateKey = (string) $pem; - $details = openssl_pkey_get_details($key)['rsa']; - - $b64 = fn (string $bin): string => rtrim(strtr(base64_encode($bin), '+/', '-_'), '='); - $this->jwk = ['kty' => 'RSA', 'kid' => 'k1', 'use' => 'sig', 'alg' => 'RS256', 'n' => $b64($details['n']), 'e' => $b64($details['e'])]; - - Http::fake([ - $issuer.'/.well-known/openid-configuration' => Http::response([ - 'issuer' => $issuer, - 'authorization_endpoint' => $issuer.'/authorize', - 'token_endpoint' => $issuer.'/token', - 'jwks_uri' => $issuer.'/jwks', - ]), - $issuer.'/jwks' => Http::response(['keys' => [$this->jwk]]), - $issuer.'/token' => fn () => Http::response(['access_token' => 'at', 'id_token' => $this->idToken, 'token_type' => 'Bearer']), - ]); - } - - /** - * @param array $claims - */ - public function sign(array $claims, ?string $privateKey = null): string - { - return JWT::encode($claims + [ - 'iss' => $this->issuer, - 'aud' => 'roster-app', - 'iat' => time(), - 'exp' => time() + 300, - ], $privateKey ?? $this->privateKey, 'RS256', 'k1'); - } -} - -function acmeWithSso(array $connection = [], string $protocol = 'oidc'): SsoConnectionModel -{ - /** @var OrganizationModel $acme */ - $acme = organization(attributes: ['name' => 'Acme', 'domains' => ['acme.test']]); - - $factory = SsoConnectionModel::factory(); - $factory = match ($protocol) { - 'azure' => $factory->azure(), - 'saml' => $factory->saml(), - default => $factory->state(['config' => ['issuer' => 'https://idp.test', 'client_id' => 'roster-app', 'client_secret' => 'top-secret']]), - }; - - return $factory->create(['organization_id' => $acme->id, 'slug' => 'acme-sso'] + $connection); -} - -/** - * @return array - */ -function queryOf(string $url): array -{ - parse_str((string) parse_url($url, PHP_URL_QUERY), $query); - - return $query; -} diff --git a/tests/Feature/Transfers/TemplateTest.php b/tests/Feature/Transfers/TemplateTest.php index 71a2240..0d92a3b 100644 --- a/tests/Feature/Transfers/TemplateTest.php +++ b/tests/Feature/Transfers/TemplateTest.php @@ -95,5 +95,5 @@ $this->get(route('atrium.roster.organizations.show', 'acme'))->assertSee($transfers, false)->assertSee('aria-label="'.__('roster::roster.import_export').'"', false); $this->get(route('atrium.roster.organizations.show', ['acme', 'tab' => 'teams']))->assertSee($transfers, false); $this->get(route('atrium.roster.organizations.show', ['acme', 'tab' => 'settings']))->assertDontSee($transfers, false); - $this->get(route('atrium.roster.organizations.show', ['acme', 'tab' => 'sso']))->assertDontSee($transfers, false); + $this->get(route('atrium.roster.organizations.show', ['acme', 'tab' => 'roles']))->assertDontSee($transfers, false); }); diff --git a/tests/Feature/Ui/ScimPagesTest.php b/tests/Feature/Ui/ScimPagesTest.php deleted file mode 100644 index 529c4bb..0000000 --- a/tests/Feature/Ui/ScimPagesTest.php +++ /dev/null @@ -1,21 +0,0 @@ -actingAs(user()); - organization(attributes: ['name' => 'Acme']); - - $this->get(route('atrium.roster.organizations.show', ['acme', 'tab' => 'scim']))->assertOk()->assertSee(url('scim/v2/acme')); - - $this->post(route('atrium.roster.scim-tokens.store', 'acme'), ['name' => 'Okta'])->assertRedirect(); - - $page = $this->get(route('atrium.roster.organizations.show', ['acme', 'tab' => 'scim']))->assertOk()->assertSee('scim_'); - $this->get(route('atrium.roster.organizations.show', ['acme', 'tab' => 'scim']))->assertOk()->assertDontSee('data-testid="scim-token"', false); - - $this->delete(route('atrium.roster.scim-tokens.revoke', ScimTokenModel::query()->sole()->id))->assertRedirect(); - - expect(ScimTokenModel::query()->sole()->revoked_at)->not->toBeNull(); -}); diff --git a/tests/Feature/Ui/SsoPagesTest.php b/tests/Feature/Ui/SsoPagesTest.php deleted file mode 100644 index c2721c3..0000000 --- a/tests/Feature/Ui/SsoPagesTest.php +++ /dev/null @@ -1,51 +0,0 @@ -actingAs(user()); - organization(attributes: ['name' => 'Acme']); - - $this->get(route('atrium.roster.organizations.show', ['acme', 'tab' => 'sso']))->assertOk()->assertSee('Microsoft Entra ID'); - - $this->post(route('atrium.roster.sso.store', 'acme'), [ - 'name' => 'Okta', 'protocol' => 'oidc', 'issuer' => 'https://idp.test', 'client_id' => 'a', 'client_secret' => 'b', 'jit' => '1', 'enabled' => '1', - ])->assertRedirect(); - - $connection = SsoConnectionModel::query()->sole(); - - $this->get(route('atrium.roster.sso.show', $connection->slug))->assertOk()->assertSee(route('roster.sso.callback', $connection->slug)); - - $this->patch(route('atrium.roster.sso.update', $connection->slug), ['name' => 'Okta prod', 'client_secret' => '', 'enabled' => '1'])->assertRedirect(); - - expect($connection->refresh()->name)->toBe('Okta prod') - ->and($connection->jit)->toBeFalse() - ->and($connection->setting('client_secret'))->toBe('b'); - - $this->delete(route('atrium.roster.sso.destroy', $connection->slug))->assertRedirect(); - expect(SsoConnectionModel::query()->count())->toBe(0); -}); - -it('shows only the connection\'s own protocol settings when editing', function (string $protocol, array $shown, array $hidden): void { - $this->actingAs(user()); - $connection = SsoConnectionModel::factory()->create([ - 'organization_id' => organization(attributes: ['name' => 'Acme'])->id, - 'protocol' => $protocol, - ]); - - $page = $this->get(route('atrium.roster.sso.show', $connection->slug))->assertOk(); - - foreach ($shown as $field) { - $page->assertSee('data-sso-field="'.$field.'"', false); - } - - foreach ($hidden as $field) { - $page->assertDontSee('data-sso-field="'.$field.'"', false); - } -})->with([ - 'oidc' => ['oidc', ['issuer', 'client_id', 'client_secret'], ['tenant', 'metadata_url', 'certificate']], - 'azure' => ['azure', ['tenant', 'client_id', 'client_secret'], ['issuer', 'entity_id']], - 'saml' => ['saml', ['metadata_url', 'entity_id', 'sso_url', 'certificate'], ['issuer', 'tenant', 'client_id']], -]); diff --git a/tests/Modes/SsoUnavailable/SsoUnavailableTest.php b/tests/Modes/SsoUnavailable/SsoUnavailableTest.php deleted file mode 100644 index b2554e8..0000000 --- a/tests/Modes/SsoUnavailable/SsoUnavailableTest.php +++ /dev/null @@ -1,21 +0,0 @@ -toBeFalse() - ->and(Route::has('roster.sso-connections.show'))->toBeTrue(); - - $this->postJson(route('roster.organizations.sso-connections.store', organization(attributes: ['name' => 'Acme'])->slug), [ - 'name' => 'Entra', 'protocol' => 'azure', 'tenant' => 'acme.onmicrosoft.com', 'client_id' => 'a', 'client_secret' => 'b', - ])->assertCreated()->assertJsonPath('data.callback_url', null); -}); - -it('explains which packages to install', function (): void { - app(Sso::class)->provider(SsoConnectionModel::factory()->azure()->create(['organization_id' => organization()->id])); -})->throws(SsoUnavailableException::class, 'composer require laravel/socialite socialiteproviders/microsoft-azure'); diff --git a/tests/SsoUnavailableTestCase.php b/tests/SsoUnavailableTestCase.php deleted file mode 100644 index d775fb2..0000000 --- a/tests/SsoUnavailableTestCase.php +++ /dev/null @@ -1,26 +0,0 @@ -bind(Sso::class, fn ($app) => new class($app->make('request')) extends Sso - { - public function available(?string $protocol = null): bool - { - return false; - } - }); - } -} From ae5ce3f1a25f9fab965358192318399a3a5b7a5d Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Fri, 30 Oct 2026 02:47:22 -0400 Subject: [PATCH 07/17] group 1: salvaged work in progress Co-Authored-By: Claude Opus 5.5 --- .../boost/skills/roster-development/SKILL.md | 45 +++++-------- tests/ArchTest.php | 7 +- tests/Authorization/HttpAuthorizationTest.php | 2 +- tests/Authorization/McpAuthorizationTest.php | 5 -- tests/Authorization/PoliciesTest.php | 4 +- tests/Authorization/ScreenControlsTest.php | 4 +- tests/Authorization/fixtures.php | 20 +----- tests/Feature/DocsTest.php | 2 +- tests/Feature/IndexesTest.php | 6 +- .../Organization/MembershipSourceTest.php | 67 ++++++++++++++++++- tests/Feature/PerformanceTest.php | 66 +----------------- .../Feature/Permission/PermissionSyncTest.php | 55 ++++++++++++--- .../Permission/RegisteredResourcesTest.php | 11 --- tests/Feature/ProvisionedStatusTest.php | 27 +------- tests/Feature/SoftDeleteTest.php | 12 +--- tests/Feature/StoredIdentifiersTest.php | 10 --- .../Ui/OrganizationRegisteredTabsTest.php | 12 ++-- tests/Feature/Ui/OrganizationTabBarTest.php | 6 +- tests/Feature/Ui/ScreenDeclarationsTest.php | 2 +- tests/Feature/Ui/UserRegisteredTabsTest.php | 6 +- tests/Feature/UserApprovalTest.php | 14 ++-- tests/Modes/Keen/KeenAuditTest.php | 66 +++++++++++------- .../Modes/RenamedTables/RenamedTablesTest.php | 15 ----- tests/Pest.php | 6 -- .../Organization/MembershipSourcesTest.php | 6 +- .../Permission/PermissionCatalogueTest.php | 10 --- 26 files changed, 206 insertions(+), 280 deletions(-) diff --git a/resources/boost/skills/roster-development/SKILL.md b/resources/boost/skills/roster-development/SKILL.md index 8640569..8942415 100644 --- a/resources/boost/skills/roster-development/SKILL.md +++ b/resources/boost/skills/roster-development/SKILL.md @@ -4,7 +4,7 @@ description: > Configure and apply the Roster package in Laravel applications: user CRUD, profiles, suspend/deactivate/reactivate, organizations, teams, invitations, domain auto-join, current org/team context, roles and permissions through - Laravel's Gate, audit history (through refactor-circus/keen), impersonation, SSO, SCIM, CSV import/export, + Laravel's Gate, audit history (through refactor-circus/keen), impersonation, CSV import/export, the roster.active and roster.organization middleware, Roster's HTTP API, MCP server and Atrium screens, and extending Roster from another package (resources, permissions, membership sources, sign-in requirements). @@ -73,7 +73,7 @@ php artisan migrate ### 6. Auditing -- Roster has no audit log or audit code of its own. Install refactor-circus/keen (`composer require refactor-circus/keen`, `php artisan migrate`) and Keen records every Roster change, labelled, diffed (profile fields, role permissions, organization domains), scoped to its organization, and with the impersonator, import or SCIM token in its context. Without Keen there is no history anywhere in Roster. +- Roster has no audit log or audit code of its own. Install refactor-circus/keen (`composer require refactor-circus/keen`, `php artisan migrate`) and Keen records every Roster change, labelled, diffed (profile fields, role permissions, organization domains), scoped to its organization, and with the impersonator or import in its context. Without Keen there is no history anywhere in Roster. - Turn it off with `roster.audit.enabled => false` (Keen then records nothing of Roster's). `Roster::auditing()` says whether Roster audits now. - While it does, read history in Keen (which adds it to Roster's Atrium screens through Atrium's screen extensions; Roster renders none itself), or through `GET /roster/history` and `list-roster-history-tool` (global `roster.audit.view`). Roster defines the `viewAuditLog` Gate ability as global `roster.audit.view` unless the app defines it. - Record the app's own events with Keen: `Keen::record('invoice.paid')->on($model)->in($organization)->with([...])->save();`. Add app secrets to `keen.redact`. @@ -85,27 +85,19 @@ php artisan migrate - Find organizations with `ListOrganizationsAction(new ListOrganizationsData(source: 'erp', accountNumber: 'A-42'))`. Each organization's `links` holds `source`, `external_id`, `account_number` and `synced_at`. - Synced organizations may have no owner; assign one with `TransferOwnershipAction`. Give the integration user `roster.organizations.sync`. -### 8. Single sign-on +### 8. Single sign-on and provisioning -- Install the protocol packages you need: `laravel/socialite` plus `firebase/php-jwt` (OIDC), `socialiteproviders/microsoft-azure` (Entra ID) or `socialiteproviders/saml2` (SAML). -- Create connections per organization with `CreateSsoConnectionAction($organization, new CreateSsoConnectionData(name: ..., protocol: 'oidc'|'azure'|'saml', clientId: ..., /* other settings */))`, and register the returned `callback_url` at the provider. -- Link people to `route('roster.sso.discover', ['email' => $email])` or `route('roster.sso.start', $connection->slug)`. -- When an organization enforces SSO, add `new \RefactorCircus\Roster\Domains\Sso\Support\NotSsoEnforced` to the app's password login validation. +- Roster ships neither: install refactor-circus/guardian, which adds them to Roster's organizations through Roster's seams. +- Without it, register your own sign-in requirement with `Roster::requireSignIn()`, and add `new \RefactorCircus\Roster\Support\Rules\NoExternalSignIn` to the app's password login validation. -### 9. SCIM provisioning - -- Issue a token with `CreateScimTokenAction($organization, new CreateScimTokenData(name: 'Okta', ssoConnection: $slug))`; `$issued->plain` is the only copy. The provider's base URL is `url('scim/v2/'.$organization->slug)`. -- The organization must own its email domains (`domains`), or SCIM refuses its users. -- SCIM changes run through Roster's Actions: listen to the normal Action events, and find them in Keen's audit log under surface `scim`. - -### 10. Impersonation +### 9. Impersonation - Grant `roster.users.impersonate` explicitly. Start with `StartImpersonationAction($user, new StartImpersonationData(reason: ...), actor: $admin)` and redirect the impersonator's browser to `$started->url`. - Schedule `roster:end-expired-impersonations` (every five minutes) so sessions the impersonator abandons, and unused links, are ended as `expired` on the record. - Add `@include('roster::impersonation-banner')` to the app layout (Atrium's standalone banner when Atrium is installed, a plain one otherwise; both styled inline). List app abilities that must never run while impersonating in `roster.impersonation.blocked` (wildcards allowed). - Use `app(RefactorCircus\Roster\Domains\Impersonation\Services\ImpersonationContext::class)->active()` to detect an impersonated request. -### 11. CSV import and export +### 10. CSV import and export - Requires `refactor-circus/impex`: `composer require refactor-circus/impex`, `php artisan vendor:publish --tag="impex-migrations"`, migrate, and run a queue worker and the scheduler. Schedule `roster:prune-transfers`. - Start with `StartImportAction(new StartImportData(type: TransferType::ImportMembers /* ImportUsers, ImportTeams, ImportOrganizations */, organization: slug, file: $upload /* or content: $csv */), $user)`. It only previews: read `$transfer->rows()` (`action` is create/link/invite/update/skip/error). @@ -115,12 +107,12 @@ php artisan migrate - Columns: members `email,name,display_name,teams,role`; users `email,name,display_name`; teams `name,slug,members`; organizations `source,external_id,name,account_number,slug,domains,owner`. - Without Impex, these Actions throw `RefactorCircus\Roster\Domains\Transfer\Exceptions\TransfersUnavailableException`. -### 12. Guard routes and surfaces +### 11. Guard routes and surfaces - Add `roster.active` middleware to routes only active users may use, and `roster.organization` to routes that need a tenant. - The HTTP API (`roster.routes.enabled`) and MCP (`roster.mcp.web.enabled`, `roster.mcp.local.enabled`) are off by default and do **no authorization** themselves. Only enable them with auth plus admin-only middleware in the `middleware` config. -### 13. Screen extensions +### 12. Screen extensions - Atrium is optional (`composer require refactor-circus/atrium` for the screens). Every Roster dashboard screen declares itself with `Screen::standard()` on Atrium's screen extensions registry; add tabs and sections to it with `Atrium::screens()` from a service provider's `boot()` (never `register()`, middleware or controllers: the registry lives for the whole process), behind `class_exists(Atrium::class)`. Atrium's README ("Screen extensions") has the full rules. @@ -141,14 +133,14 @@ Atrium::screens() - list: `roster.users`, `roster.organizations`, `roster.roles`, `roster.permissions`, `roster.impersonations`, `roster.transfers` (no record; each row is the row slot's `$record`) - detail without a record: `roster.user-create`, `roster.organization-create` - detail with a record: `roster.user` (the user), `roster.organization` (the organization), `roster.team` (the team), `roster.role` (the role), `roster.transfer` (the transfer), `roster.invitation` (the invitation page) -- Built-in tabs: `overview` on every screen but the organization (the tab bar shows only once a registered tab is visible); on `roster.organization`, `members`, `teams`, `invitations`, `roles`, `sso`, `scim`, `settings`, each shown only with its permission in the organization, the first shown being the default. All seven are reserved for every viewer: a registered tab with one of those keys is skipped and reported. Use `vendor.key` (`acme.orders`) keys. +- Built-in tabs: `overview` on every screen but the organization (the tab bar shows only once a registered tab is visible); on `roster.organization`, `members`, `teams`, `invitations`, `roles`, `settings`, each shown only with its permission in the organization, the first shown being the default. All five are reserved for every viewer: a registered tab with one of those keys is skipped and reported. Use `vendor.key` (`acme.orders`) keys. - `permission()` extensions are checked by `ScreenAccess::allowsOn($permission, $record)`: `OrganizationModel` / `TeamModel` in that scope; the configured `roster.users.model` about that user; `RoleModel`, `ImpersonationModel` and `InvitationModel` in `$record->organization` (globally without one); `TransferModel` in `$record->organization` about `$record->requester`; no record (list and create screens) without a scope; any other model is refused. - Visibility is default-deny: `permission()`, an `authorize(fn (Request, ?Model, Screen): bool)` closure (both must pass when both are set), or `public()`. A hidden tab's `?tab=` answers 403; an unknown key, including the old `activity` and `mcp`, opens the default tab. Roster authorizes the screen first, so your closures never run for a refused viewer or on deleted pages. - A view gets the resolver's data with Atrium's `screen`, `record` and `tab` over it; a component gets one `data` prop. In tests use `RefactorCircus\Atrium\Testing\ResetsScreenExtensions`. Apps that published `roster-views` must re-publish them. -### 14. Extending Roster +### 13. Extending Roster -- Packages and apps add to Roster through registration points, always from a service provider's `boot()` (each registry is a process-wide singleton, and registering the same thing twice throws). Roster's own SSO and SCIM domains use the same seams. +- Packages and apps add to Roster through registration points, always from a service provider's `boot()` (each registry is a process-wide singleton, and registering the same thing twice throws). - `roster.*` is reserved for Roster's own domains: `resource()` and `permission()` throw `InvalidArgumentException` for any `roster.*` prefix or name. Use your package's prefix (`acme.widgets`). - Resources and permissions: @@ -196,10 +188,10 @@ final class PartnerSignIn implements SignInRequirement Roster::requireSignIn(PartnerSignIn::class); // in boot() Roster::externalSignInFor($email)?->url; // first answer, in registration order; null for super-admins -Roster::provisionedStatus($organization); // the AccountStatus SSO/SCIM-style accounts start with +Roster::provisionedStatus($organization); // the AccountStatus externally provisioned accounts start with ``` -- Requirements must not overlap. A throwing requirement fails closed: the login or registration (`NotSsoEnforced`) fails and Laravel reports it. Ask whether an email must use SSO with `externalSignInFor()` (its `record` is the `SsoConnectionModel` for Roster's SSO). +- Requirements must not overlap. A throwing requirement fails closed: the login or registration (`NoExternalSignIn`) fails and Laravel reports it. Ask whether an email must sign in elsewhere with `externalSignInFor()` (its `record` is whatever the registered sign-in requirement keeps for it). - Audit context is not a Roster API: register on Keystone's `AuditHooks`, filter to Roster's entries and never throw (`AuditHooks` runs every closure for every package and spreads each result, so return `[]`, never null): ```php @@ -229,7 +221,7 @@ $this->app->booted(function (): void { ## Rules, References, and Templates -- Config: `config/roster.php` (users, authorization, super_admins, roles, impersonation, sso, scim, transfers, organizations, statuses, invitations, routes, mcp). +- Config: `config/roster.php` (users, authorization, super_admins, roles, impersonation, transfers, organizations, statuses, invitations, routes, mcp). - Statuses: `roster.statuses` names a string-backed enum per record. Users default to `RefactorCircus\Roster\Domains\User\Enums\UserStatus` (`Active`, `Pending`, `Suspended`, `Deactivated`), implementing `Contracts\AccountStatus` (`active()`, `pending()`, `suspended()`, `deactivated()`, `allowsAccess()`); a user with no profile row has the `active()` status. Organizations and teams default to `OrganizationStatus` / `TeamStatus` (`Active`, `Inactive`), implementing `Contracts\Status`; set them with `status` / `status_reason` on the create, update and sync Data, filter lists by `status`. They are data only: Roster refuses nothing by them. Read the configured enum with `RefactorCircus\Roster\Support\Statuses` (`Statuses::users()::pending()`). - Deletes are soft: - Add `SoftDeletes` (and a `deleted_at` column) to the user model so deleted users can be restored; without it, users are deleted permanently. @@ -238,11 +230,11 @@ $this->app->booted(function (): void { - Manual acceptance: - Set `roster.users.registration_status` to `pending` for self-registration. - Pass `status: UserStatus::Pending` in `CreateUserData`. - - Set an organization's `provisioned_status` for its SSO and SCIM accounts. + - Set an organization's `provisioned_status` for its externally provisioned accounts. - Accept with `ApproveUserAction`, or turn down with `RejectUserAction` (which deactivates). - Events: every Action fires `RefactorCircus\Roster\Domains\{Domain}\Events\*ActionEvent` before (`...ingActionEvent`) and after (`...edActionEvent`); listen to `RefactorCircus\Keystone\Contracts\ActionStartingEvent` / `ActionFinishedEvent` (shared by every Refactor Circus package; Roster's events are under `RefactorCircus\Roster\`) to see every action. Each Action makes its writes in one transaction; finished events fire after it commits, so a write that rolls back (or an outer transaction that does) fires none. CSV steps fire `ImportValidating`/`Validated`, `ImportRowApplying`/`Applied`, `ExportBuilding`/`Built` and `TransferFinishing`/`Finished` action events too. - Model events: every model fires `{Entity}{Hook}Event` per Eloquent hook (`TeamCreatingEvent`, `OrganizationTrashedEvent`), implementing `RefactorCircus\Keystone\Contracts\ModelLifecycleEvent`; return `false` from a `creating`/`updating`/`saving`/`deleting` listener to stop the write. -- Policies: every core model's policy is set in `roster.policies` (the SSO and SCIM domains register theirs with the Gate themselves; a `roster.policies` entry for one of their models still wins); swap one by pointing the model at your class (extend the bundled `Domains\{Domain}\Policies\*Policy`). Roster's API, MCP and Atrium checks ask the policy of the permission's resource (`roster.organizations.update` → `OrganizationModel` policy `update(?Model $user, ?Model $subject, ?Model $self)`, `roster.users.manage-status` → `UserModel` policy `manageStatus()`), so app `Gate::before` callbacks apply. Impersonation-blocked permissions are refused first. +- Policies: every core model's policy is set in `roster.policies` (package resources register theirs with the Gate themselves; a `roster.policies` entry for one of their models still wins); swap one by pointing the model at your class (extend the bundled `Domains\{Domain}\Policies\*Policy`). Roster's API, MCP and Atrium checks ask the policy of the permission's resource (`roster.organizations.update` → `OrganizationModel` policy `update(?Model $user, ?Model $subject, ?Model $self)`, `roster.users.manage-status` → `UserModel` policy `manageStatus()`), so app `Gate::before` callbacks apply. Impersonation-blocked permissions are refused first. - HTTP routes are named `roster.users.*`, `roster.organizations.*`, `roster.invitations.*`; `{user}` is the user model's route key, organizations and teams use slugs. - Atrium (optional; without it the `atrium.roster.*` routes don't exist): Users at `atrium.roster.users.index`, Organizations at `atrium.roster.organizations.index`. Access uses Atrium's `viewAtrium` gate. Lists of organizations, roles, impersonations and transfers, asked without an `organization`, open to users holding the permission in any organization and hold only what falls within those (`Authorizer::organizationsWith()`); Atrium's navigation follows. Pages show only the controls the viewer may use and organization tabs need their own permission; published views use `@rosterCan($permission, $scope, $self)`, the same check the screens make. Hide it with `atrium.disabled => ['roster']`, or by feature flag through `roster.atrium.features` (navigation, widgets and search hide and pages 404 while a feature is off; Atrium's feature resolver, e.g. refactor-circus/pennantplus, decides). The default is `RefactorCircus\Roster\Atrium\Features\RosterSupportFeature`, a PennantPlus `OnLayeredFeature` checked globally only; subclass it to change its default, and it is skipped when refactor-circus/pennantplus is not installed. @@ -299,9 +291,6 @@ In app tests, assert with `expect($user->rosterStatus())->toBe(UserStatus::Suspe - Publishing Roster's views to add a tab or section to a Roster screen; register it with `Atrium::screens()` instead. - Logging users in as someone else with `Auth::login()` for support. Use impersonation, which is time-limited, blocked from sensitive abilities, and audited. - Emailing or posting impersonation links. They only work in the impersonator's own browser. -- Using multi-tenant Entra authorities (`common`, `organizations`) or the Entra `mail` attribute for identity. Roster refuses both. -- Writing your own OIDC/SAML verification. Use Roster's connections, which verify tokens and assertions with proven libraries. -- Storing or logging SCIM tokens. They are shown once; issue a new one and revoke the old if lost. - Checking roles by slug in app code (`hasRole('admin')`-style). Check permissions with `$user->can()` instead. - Writing `roster_role_assignments` rows directly, which skips the scope and escalation guards. - Changing `roster.users.key_type` after `roster_profiles` has been migrated. diff --git a/tests/ArchTest.php b/tests/ArchTest.php index f975a93..2ffd4a0 100644 --- a/tests/ArchTest.php +++ b/tests/ArchTest.php @@ -16,7 +16,8 @@ /** * Roster's core: the classes that must name neither the SSO nor the SCIM - * domain, which reach them only through the registration seams. + * domain. Both now live in refactor-circus/guardian, which reaches Roster + * only through the registration seams. */ const ROSTER_CORE = [ 'RefactorCircus\Roster\Domains\Permission\Services\Authorizer' => 'src/Domains/Permission/Services/Authorizer.php', @@ -72,8 +73,8 @@ function policiesSource(): string } /** - * The policies registered with the Gate once Roster has booted: the SSO and - * SCIM domains register their models' policies themselves, outside + * The policies registered with the Gate once Roster has booted, including + * any a domain or package resource registers itself, outside * `roster.policies`. Boots the test application and tears it down again. * * @return array diff --git a/tests/Authorization/HttpAuthorizationTest.php b/tests/Authorization/HttpAuthorizationTest.php index 172bec9..9243604 100644 --- a/tests/Authorization/HttpAuthorizationTest.php +++ b/tests/Authorization/HttpAuthorizationTest.php @@ -11,7 +11,7 @@ it('covers every roster API route', function (): void { $names = collect(Route::getRoutes()->getRoutesByName()) ->keys() - ->filter(fn (string $name): bool => str_starts_with($name, 'roster.') && ! str_starts_with($name, 'roster.invitations.') && ! str_starts_with($name, 'roster.impersonation.') && ! str_starts_with($name, 'roster.sso.') && ! str_starts_with($name, 'roster.scim.') && $name !== 'roster.transfers.file' && $name !== 'roster.history.index') + ->filter(fn (string $name): bool => str_starts_with($name, 'roster.') && ! str_starts_with($name, 'roster.invitations.') && ! str_starts_with($name, 'roster.impersonation.') && $name !== 'roster.transfers.file' && $name !== 'roster.history.index') ->map(fn (string $name): string => substr($name, 7)) ->sort() ->values() diff --git a/tests/Authorization/McpAuthorizationTest.php b/tests/Authorization/McpAuthorizationTest.php index ecb4c29..77a9dce 100644 --- a/tests/Authorization/McpAuthorizationTest.php +++ b/tests/Authorization/McpAuthorizationTest.php @@ -41,11 +41,6 @@ function toolArguments(): array 'RemoveTeamMemberTool' => fn (array $w): array => $team() + $user($w), 'ShowRoleTool', 'UpdateRoleTool', 'DeleteRoleTool' => fn (array $w): array => ['role' => $w['role']->id], 'UpdatePermissionTool', 'DeletePermissionTool' => fn (): array => ['name' => 'invoices.edit'], - 'ListSsoConnectionsTool', 'CreateSsoConnectionTool', 'ListScimTokensTool', 'CreateScimTokenTool' => $org, - 'RevokeScimTokenTool' => fn (array $w): array => ['token' => $w['scimToken']->id], - 'ShowSsoConnectionTool', 'UpdateSsoConnectionTool', 'DeleteSsoConnectionTool' => fn (): array => ['connection' => 'acme-okta'], - 'ListSsoIdentitiesTool' => $user, - 'UnlinkSsoIdentityTool' => fn (array $w): array => ['identity' => $w['identity']->id], 'StopImpersonationTool' => fn (array $w): array => ['impersonation' => $w['impersonation']->id], 'StartImpersonationTool' => fn (array $w): array => $user($w) + ['reason' => 'Ticket 1'], 'ShowImportTemplateTool' => fn (): array => ['type' => 'import_users'], diff --git a/tests/Authorization/PoliciesTest.php b/tests/Authorization/PoliciesTest.php index 8b3c274..c75bb24 100644 --- a/tests/Authorization/PoliciesTest.php +++ b/tests/Authorization/PoliciesTest.php @@ -30,8 +30,8 @@ function rosterModels(): array } it('registers a configurable policy for every model', function (): void { - // Core models from `roster.policies`; the SSO and SCIM domains register - // their own models' policies with the Gate when they boot. + // Core models from `roster.policies`, plus any policy a domain registers + // with the Gate itself when it boots. $policies = config('roster.policies') + array_filter( Gate::policies(), fn (string $model): bool => str_starts_with($model, 'RefactorCircus\\Roster\\'), diff --git a/tests/Authorization/ScreenControlsTest.php b/tests/Authorization/ScreenControlsTest.php index f00d01b..ae118b1 100644 --- a/tests/Authorization/ScreenControlsTest.php +++ b/tests/Authorization/ScreenControlsTest.php @@ -50,7 +50,6 @@ function testId(string $id): string ->assertDontSee(testId('domain-join'), false) ->assertDontSee(testId('roles-card'), false) ->assertDontSee(testId('impersonate-card'), false) - ->assertDontSee(testId('unlink-sso-identity'), false) ->assertDontSee(testId('danger-zone'), false); }); @@ -129,12 +128,11 @@ function testId(string $id): string ->assertOk() ->assertSee(testId('tab-members'), false) ->assertSee(testId('tab-settings'), false) - ->assertDontSee(testId('tab-scim'), false) ->assertDontSee(testId('tab-roles'), false) ->assertDontSee(testId('add-member'), false) ->assertDontSee(testId('remove-member'), false); - $this->actingAs($viewer)->get(route('atrium.roster.organizations.show', ['acme', 'tab' => 'scim']))->assertForbidden(); + $this->actingAs($viewer)->get(route('atrium.roster.organizations.show', ['acme', 'tab' => 'roles']))->assertForbidden(); // Activity is no longer a built-in tab: the old link opens the default tab. $this->actingAs($viewer)->get(route('atrium.roster.organizations.show', ['acme', 'tab' => 'activity']))->assertOk(); }); diff --git a/tests/Authorization/fixtures.php b/tests/Authorization/fixtures.php index c56f49f..13314ef 100644 --- a/tests/Authorization/fixtures.php +++ b/tests/Authorization/fixtures.php @@ -9,9 +9,6 @@ use RefactorCircus\Roster\Domains\Permission\Models\PermissionModel; use RefactorCircus\Roster\Domains\Role\Models\RoleAssignmentModel; use RefactorCircus\Roster\Domains\Role\Models\RoleModel; -use RefactorCircus\Roster\Domains\Scim\Models\ScimTokenModel; -use RefactorCircus\Roster\Domains\Sso\Models\SsoConnectionModel; -use RefactorCircus\Roster\Domains\Sso\Models\SsoIdentityModel; use RefactorCircus\Roster\Domains\Team\Actions\AddTeamMemberAction; use RefactorCircus\Roster\Domains\Team\Actions\CreateTeamAction; use RefactorCircus\Roster\Domains\Team\Data\AddTeamMemberData; @@ -40,11 +37,6 @@ function authorizationWorld(): array $impersonation = ImpersonationModel::factory()->create(['impersonator_id' => user()->getKey(), 'user_id' => $target->getKey()]); - $connection = SsoConnectionModel::factory()->create(['organization_id' => $acme->id, 'slug' => 'acme-okta']); - $identity = SsoIdentityModel::query()->create(['connection_id' => $connection->id, 'user_id' => $target->getKey(), 'subject' => 'sub-1']); - - $scimToken = ScimTokenModel::query()->create(['organization_id' => $acme->id, 'name' => 'Okta', 'token_hash' => hash('sha256', 'x')]); - $acme->links()->create(['source' => 'erp', 'external_id' => 'C-1']); $transfer = TransferModel::factory()->create([ @@ -54,7 +46,7 @@ function authorizationWorld(): array 'requested_by' => user()->getKey(), ]); - return compact('acme', 'target', 'ops', 'invitation', 'role', 'assignment', 'impersonation', 'connection', 'identity', 'scimToken', 'transfer'); + return compact('acme', 'target', 'ops', 'invitation', 'role', 'assignment', 'impersonation', 'transfer'); } /** @@ -128,16 +120,6 @@ function apiRoutes(): array 'users.roles.store' => ['POST', 'roster.users.roles.store', $user, ['role' => 'x']], 'users.roles.destroy' => ['DELETE', 'roster.users.roles.destroy', fn (array $w): array => [$w['target']->getRouteKey(), $w['assignment']->id], []], 'users.permissions' => ['GET', 'roster.users.permissions', $user, []], - 'sso-connections.index' => ['GET', 'roster.organizations.sso-connections.index', $org, []], - 'sso-connections.store' => ['POST', 'roster.organizations.sso-connections.store', $org, ['name' => 'X', 'protocol' => 'oidc']], - 'sso-connections.show' => ['GET', 'roster.sso-connections.show', fn (): array => ['acme-okta'], []], - 'sso-connections.update' => ['PATCH', 'roster.sso-connections.update', fn (): array => ['acme-okta'], ['name' => 'Y']], - 'sso-connections.destroy' => ['DELETE', 'roster.sso-connections.destroy', fn (): array => ['acme-okta'], []], - 'users.sso-identities.index' => ['GET', 'roster.users.sso-identities.index', $user, []], - 'sso-identities.destroy' => ['DELETE', 'roster.sso-identities.destroy', fn (array $w): array => [$w['identity']->id], []], - 'scim-tokens.index' => ['GET', 'roster.organizations.scim-tokens.index', $org, []], - 'scim-tokens.store' => ['POST', 'roster.organizations.scim-tokens.store', $org, ['name' => 'Okta']], - 'scim-tokens.destroy' => ['DELETE', 'roster.scim-tokens.destroy', fn (array $w): array => [$w['scimToken']->id], []], 'users.impersonate' => ['POST', 'roster.users.impersonate', $user, ['reason' => 'Ticket 1']], 'impersonations.index' => ['GET', 'roster.impersonations.index', $none, []], 'impersonations.destroy' => ['DELETE', 'roster.impersonations.destroy', fn (array $w): array => [$w['impersonation']->id], []], diff --git a/tests/Feature/DocsTest.php b/tests/Feature/DocsTest.php index 2952ac8..30f9b1b 100644 --- a/tests/Feature/DocsTest.php +++ b/tests/Feature/DocsTest.php @@ -97,7 +97,7 @@ function unreleasedChangelog(): string 'roster.organization', 'roster.team', 'roster.roles', 'roster.role', 'roster.permissions', 'roster.impersonations', 'roster.transfers', 'roster.transfer', 'roster.invitation', ]; - $builtInTabs = ['members', 'teams', 'invitations', 'roles', 'sso', 'scim', 'settings', 'overview']; + $builtInTabs = ['members', 'teams', 'invitations', 'roles', 'settings', 'overview']; $slots = ['header.actions', 'before', 'after', 'aside', 'row.actions']; $records = ['OrganizationModel', 'TeamModel', 'roster.users.model', 'RoleModel', 'ImpersonationModel', 'TransferModel', 'InvitationModel']; diff --git a/tests/Feature/IndexesTest.php b/tests/Feature/IndexesTest.php index b3c6241..207c4e2 100644 --- a/tests/Feature/IndexesTest.php +++ b/tests/Feature/IndexesTest.php @@ -15,13 +15,9 @@ ['profiles', 'current_team_id'], ['impersonations', 'organization_id'], ['impersonations', 'created_at'], - ['sso_connections', 'organization_id'], - ['scim_tokens', 'organization_id'], - ['scim_tokens', 'sso_connection_id'], - ['scim_groups', 'organization_id'], ['transfers', 'organization_id'], ]); it('indexes the organization-scoped lists in page order', function (string $table): void { expect(Schema::hasIndex(Tables::name($table), ['organization_id', 'created_at', 'id']))->toBeTrue(); -})->with(['memberships', 'role_assignments', 'invitations', 'scim_users', 'scim_groups']); +})->with(['memberships', 'role_assignments', 'invitations']); diff --git a/tests/Feature/Organization/MembershipSourceTest.php b/tests/Feature/Organization/MembershipSourceTest.php index 15cd9ed..6bf6714 100644 --- a/tests/Feature/Organization/MembershipSourceTest.php +++ b/tests/Feature/Organization/MembershipSourceTest.php @@ -13,6 +13,14 @@ use RefactorCircus\Roster\Domains\Organization\Models\OrganizationModel; use RefactorCircus\Roster\Domains\Organization\Resources\MemberResource; use RefactorCircus\Roster\Domains\Organization\Services\MembershipSources; +use RefactorCircus\Roster\Domains\Team\Actions\AddTeamMemberAction; +use RefactorCircus\Roster\Domains\Team\Actions\CreateTeamAction; +use RefactorCircus\Roster\Domains\Team\Data\AddTeamMemberData; +use RefactorCircus\Roster\Domains\Team\Data\CreateTeamData; +use RefactorCircus\Roster\Domains\Transfer\Actions\ConfirmImportAction; +use RefactorCircus\Roster\Domains\Transfer\Actions\StartImportAction; +use RefactorCircus\Roster\Domains\Transfer\Data\StartImportData; +use RefactorCircus\Roster\Domains\Transfer\Enums\TransferType; use RefactorCircus\Roster\Support\Tables; use Workbench\App\Models\User; @@ -107,7 +115,9 @@ function membershipSourceEnumUses(array $files): array ->and($membership->sourceEnum())->toBe(MembershipSource::Direct); }); -it('reads a membership stored as scim back as scim and shows SCIM', function (): void { +it('reads a membership stored as scim back as scim and shows SCIM once registered', function (): void { + // As Guardian does: Roster itself no longer registers scim. + app(MembershipSources::class)->register('scim', 'SCIM'); $organization = organization(); $membership = storedMembership($organization, user(), 'scim'); @@ -131,6 +141,7 @@ function membershipSourceEnumUses(array $files): array }); it('passes the member tool output schema with registered and unregistered sources', function (): void { + app(MembershipSources::class)->register('scim', 'SCIM'); app(MembershipSources::class)->register('acme-sync', 'Acme sync'); $organization = organization(); storedMembership($organization, user(), 'scim'); @@ -143,6 +154,7 @@ function membershipSourceEnumUses(array $files): array }); it('lists members with the registered label', function (): void { + app(MembershipSources::class)->register('scim', 'SCIM'); app(MembershipSources::class)->register('acme-sync', 'Acme sync'); $organization = organization(); storedMembership($organization, user(), 'scim'); @@ -160,6 +172,7 @@ function membershipSourceEnumUses(array $files): array }); it('joins with a built-in case, a built-in value or a registered source', function (): void { + app(MembershipSources::class)->register('scim', 'SCIM'); app(MembershipSources::class)->register('acme-sync', 'Acme sync'); $organization = organization(); @@ -169,6 +182,58 @@ function membershipSourceEnumUses(array $files): array ->and(membershipJoiner()->joinAs($organization, user(), 'scim')->fresh()?->source)->toBe('scim'); }); +it('reads a stored scim membership as scim, with no enum case, while nothing registers it', function (): void { + $membership = storedMembership(organization(), user(), 'scim'); + + expect(app(MembershipSources::class)->has('scim'))->toBeFalse() + ->and($membership->source)->toBe('scim') + ->and($membership->sourceEnum())->toBeNull() + ->and((new MemberResource($membership))->resolve()['source'])->toBe('scim'); +}); + +it('lists an unregistered scim member through the API, MCP and the members tab', function (): void { + $owner = user(); + $organization = organization($owner); + storedMembership($organization, user(['name' => 'Okta Provisioned', 'email' => 'okta@acme.test']), 'scim'); + + $sources = collect($this->getJson(route('roster.organizations.members.index', $organization->slug))->assertOk()->json('data'))->pluck('source')->sort()->values()->all(); + + expect($sources)->toBe(['direct', 'scim']); + + mcpTool(ListMembersTool::class, ['organization' => $organization->slug])->assertOk()->assertSee('scim'); + + $this->actingAs($owner) + ->get(route('atrium.roster.organizations.show', [$organization, 'tab' => 'members'])) + ->assertOk() + ->assertSee('Okta Provisioned') + ->assertSeeInOrder(['Okta Provisioned', 'scim']); +}); + +it('keeps an unregistered scim source through filtering, a team change and an import', function (): void { + $owner = user(); + $organization = organization($owner, ['name' => 'Acme']); + $ada = user(['email' => 'ada@acme.test']); + $membership = storedMembership($organization, $ada, 'scim'); + + // Filtering the list by the stored value neither fails validation nor drops it. + $filtered = $this->getJson(route('roster.organizations.members.index', [$organization->slug, 'source' => 'scim']))->assertOk()->json('data'); + + expect(collect($filtered)->pluck('source')->all())->toContain('scim'); + + // A write that touches the membership: seating the member on a team. + $ops = app(CreateTeamAction::class)->execute($organization, new CreateTeamData(name: 'Ops')); + app(AddTeamMemberAction::class)->execute($ops, new AddTeamMemberData(user: $ada->getRouteKey())); + + expect($membership->fresh()?->source)->toBe('scim'); + + // An import row for the same person. + $transfer = app(StartImportAction::class)->execute(new StartImportData(type: TransferType::ImportMembers, organization: 'acme', content: "email,name\nada@acme.test,Ada"), $owner); + app(ConfirmImportAction::class)->execute($transfer, $owner); + + expect($membership->fresh()?->source)->toBe('scim') + ->and(MembershipModel::query()->where('user_id', $ada->getKey())->count())->toBe(1); +}); + it('refuses to join with a source nothing registers, naming it', function (): void { $organization = organization(); $ada = user(); diff --git a/tests/Feature/PerformanceTest.php b/tests/Feature/PerformanceTest.php index 9af65b9..6b82bc7 100644 --- a/tests/Feature/PerformanceTest.php +++ b/tests/Feature/PerformanceTest.php @@ -2,8 +2,6 @@ declare(strict_types=1); -require_once __DIR__.'/Scim/helpers.php'; - use Illuminate\Support\Facades\DB; use RefactorCircus\Roster\Atrium\RosterPlugin; use RefactorCircus\Roster\Domains\Organization\Actions\AddMemberAction; @@ -19,8 +17,6 @@ use RefactorCircus\Roster\Domains\Permission\Services\Permissions; use RefactorCircus\Roster\Domains\Role\Actions\AssignRoleAction; use RefactorCircus\Roster\Domains\Role\Data\AssignRoleData; -use RefactorCircus\Roster\Domains\Scim\Actions\CreateScimTokenAction; -use RefactorCircus\Roster\Domains\Scim\Data\CreateScimTokenData; use RefactorCircus\Roster\Domains\Team\Actions\AddTeamMemberAction; use RefactorCircus\Roster\Domains\Team\Actions\CreateTeamAction; use RefactorCircus\Roster\Domains\Team\Data\AddTeamMemberData; @@ -106,7 +102,7 @@ function crowd(int $count): array $count = queries(function () use ($admin, $scopes): void { $authorizer = app(Authorizer::class); - foreach (['roster.members.view', 'roster.teams.manage', 'roster.roles.view', 'roster.sso.manage', 'roster.invitations.manage'] as $permission) { + foreach (['roster.members.view', 'roster.teams.manage', 'roster.roles.view', 'roster.invitations.manage'] as $permission) { $authorizer->organizationsWith($admin, $permission); foreach ($scopes as $scope) { @@ -131,7 +127,7 @@ function crowd(int $count): array $this->actingAs($owner); expect(queries(fn () => $this->get(route('atrium.roster.organizations.show', ['acme', 'tab' => $tab]))->assertOk()))->toBeLessThanOrEqual(16); -})->with(['members', 'teams', 'invitations', 'roles', 'sso', 'scim', 'activity', 'settings']); +})->with(['members', 'teams', 'invitations', 'roles', 'activity', 'settings']); it('lists transfers in a fixed number of queries', function (int $size): void { $owner = user(); @@ -182,64 +178,6 @@ function crowd(int $count): array expect(queries(fn () => app(SyncOrganizationsAction::class)->execute(new SyncOrganizationsData(records: $records))))->toBeLessThanOrEqual(4); }); -it('serves a SCIM users page in a fixed number of queries', function (int $size): void { - [, $acme] = crowd(0); - $token = app(CreateScimTokenAction::class)->execute($acme, new CreateScimTokenData(name: 'Okta'))->plain; - - foreach (range(1, $size) as $i) { - $this->postJson('/scim/v2/acme/Users', oktaUser("s{$i}@acme.test", "ext{$i}"), ['Authorization' => 'Bearer '.$token])->assertCreated(); - } - - expect(queries(fn () => $this->getJson('/scim/v2/acme/Users?count=100', ['Authorization' => 'Bearer '.$token])->assertOk()->assertJsonPath('totalResults', $size))) - ->toBeLessThanOrEqual(10); -})->with([3, 30]); - -it('serves a SCIM groups page in a fixed number of queries', function (int $size): void { - [, $acme] = crowd(0); - $token = app(CreateScimTokenAction::class)->execute($acme, new CreateScimTokenData(name: 'Okta'))->plain; - $headers = ['Authorization' => 'Bearer '.$token]; - $ids = []; - - foreach (range(1, 4) as $i) { - $ids[] = ['value' => $this->postJson('/scim/v2/acme/Users', oktaUser("s{$i}@acme.test", "ext{$i}"), $headers)->assertCreated()->json('id')]; - } - - foreach (range(1, $size) as $i) { - $this->postJson('/scim/v2/acme/Groups', [ - 'schemas' => ['urn:ietf:params:scim:schemas:core:2.0:Group'], - 'displayName' => "Group {$i}", - 'members' => $ids, - ], $headers)->assertCreated(); - } - - expect(queries(fn () => $this->getJson('/scim/v2/acme/Groups?count=100', $headers)->assertOk()->assertJsonPath('totalResults', $size)->assertJsonCount(4, 'Resources.0.members'))) - ->toBeLessThanOrEqual(10); -})->with([2, 15]); - -it('adds a member to a SCIM group without a query per existing member', function (int $size): void { - [, $acme] = crowd(0); - $token = app(CreateScimTokenAction::class)->execute($acme, new CreateScimTokenData(name: 'Okta'))->plain; - $headers = ['Authorization' => 'Bearer '.$token]; - $ids = []; - - foreach (range(1, $size + 1) as $i) { - $ids[] = ['value' => $this->postJson('/scim/v2/acme/Users', oktaUser("s{$i}@acme.test", "ext{$i}"), $headers)->assertCreated()->json('id')]; - } - - $group = $this->postJson('/scim/v2/acme/Groups', [ - 'schemas' => ['urn:ietf:params:scim:schemas:core:2.0:Group'], - 'displayName' => 'Engineering', - 'members' => array_slice($ids, 0, $size), - ], $headers)->assertCreated()->json('id'); - - // How Okta and Entra send one membership change. - $patch = fn () => $this->patchJson('/scim/v2/acme/Groups/'.$group, patchOps([['op' => 'add', 'path' => 'members', 'value' => [end($ids)]]]), $headers) - ->assertOk() - ->assertJsonCount($size + 1, 'members'); - - expect(queries($patch))->toBeLessThanOrEqual(30); -})->with([2, 20]); - it('finds a user by email with one indexed lookup, and by other casing after it', function (): void { $ada = user(['email' => 'ada@example.com']); $grace = user(['email' => 'Grace@Example.com']); diff --git a/tests/Feature/Permission/PermissionSyncTest.php b/tests/Feature/Permission/PermissionSyncTest.php index 28bd879..2e8db80 100644 --- a/tests/Feature/Permission/PermissionSyncTest.php +++ b/tests/Feature/Permission/PermissionSyncTest.php @@ -48,13 +48,47 @@ function permissionSnapshot(): array expect(array_intersect(array_keys(BuiltInRoles::PERMISSIONS), DOMAIN_PERMISSIONS))->toBe([]); }); -it('creates the registered SSO and SCIM permissions as system permissions', function (): void { - PermissionModel::query()->whereIn('name', DOMAIN_PERMISSIONS)->delete(); - +it('no longer creates the SSO and SCIM permissions', function (): void { BuiltInRoles::sync(); - expect(PermissionModel::query()->whereIn('name', DOMAIN_PERMISSIONS)->where('system', true)->orderBy('name')->pluck('name')->all()) - ->toBe(DOMAIN_PERMISSIONS); + expect(PermissionModel::query()->whereIn('name', DOMAIN_PERMISSIONS)->exists())->toBeFalse(); +}); + +/** + * An upgraded install: the three SSO and SCIM permissions Roster used to + * register, still stored as system permissions and granted to admin. + */ +function legacySsoScimPermissions(): RoleModel +{ + $admin = builtInRole('admin'); + + foreach (DOMAIN_PERMISSIONS as $name) { + $admin?->permissions()->attach(PermissionModel::query()->create(['name' => $name, 'description' => 'Old.', 'system' => true])); + } + + return $admin ?? throw new RuntimeException('No built-in admin role.'); +} + +it('reports the stored SSO and SCIM permissions as unregistered, and keeps them and their admin grants', function (): void { + $admin = legacySsoScimPermissions(); + $command = Artisan::all()['roster:sync-permissions']; + $global = array_keys($command->getApplication()?->getDefinition()->getOptions() ?? []); + // Every option the command itself offers (prune, force, delete, ...), one run each. + $options = array_values(array_diff(array_keys($command->getDefinition()->getOptions()), $global)); + + foreach ([[], ...array_map(fn (string $option): array => ['--'.$option => true], $options)] as $parameters) { + $run = $this->artisan('roster:sync-permissions', $parameters); + + foreach (DOMAIN_PERMISSIONS as $name) { + $run->expectsOutputToContain($name); + } + + $run->assertSuccessful(); + $run->run(); + + expect(PermissionModel::query()->whereIn('name', DOMAIN_PERMISSIONS)->where('system', true)->count())->toBe(3) + ->and(heldBy($admin->fresh() ?? $admin))->toContain(...DOMAIN_PERMISSIONS); + } }); it('grants registered permissions to a built-in role sync creates', function (): void { @@ -67,19 +101,19 @@ function permissionSnapshot(): array expect($admin)->not->toBeNull() ->and($admin->system)->toBeTrue() - ->and(heldBy($admin))->toContain(...DOMAIN_PERMISSIONS, ...['acme.widgets.approve']) + ->and(heldBy($admin))->toContain('acme.widgets.approve') ->and(heldBy(builtInRole('member')))->not->toContain('acme.widgets.approve'); }); it('keeps the grants of an admin role the application edited', function (): void { $admin = builtInRole('admin'); - $admin->permissions()->detach(PermissionModel::query()->where('name', 'roster.sso.view')->pluck('id')); + $admin->permissions()->detach(PermissionModel::query()->where('name', 'roster.organizations.update')->pluck('id')); $edited = heldBy($admin); BuiltInRoles::sync(); expect(heldBy($admin))->toBe($edited) - ->and(heldBy($admin))->not->toContain('roster.sso.view'); + ->and(heldBy($admin))->not->toContain('roster.organizations.update'); }); it('leaves an install that already has every permission unchanged', function (): void { @@ -128,8 +162,7 @@ function permissionSnapshot(): array $admin = builtInRole('admin'); - expect(PermissionModel::query()->whereIn('name', [...DOMAIN_PERMISSIONS, 'acme.widgets.approve'])->where('system', true)->count())->toBe(4) + expect(PermissionModel::query()->whereIn('name', [...DOMAIN_PERMISSIONS, 'acme.widgets.approve'])->where('system', true)->pluck('name')->all())->toBe(['acme.widgets.approve']) ->and($admin)->not->toBeNull() - ->and(heldBy($admin))->toContain(...DOMAIN_PERMISSIONS, ...['acme.widgets.approve']) - ->and(array_values(array_intersect(heldBy(builtInRole('lead')), DOMAIN_PERMISSIONS)))->toBe([]); + ->and(heldBy($admin))->toContain('acme.widgets.approve'); }); diff --git a/tests/Feature/Permission/RegisteredResourcesTest.php b/tests/Feature/Permission/RegisteredResourcesTest.php index 51e2d2e..ac6d326 100644 --- a/tests/Feature/Permission/RegisteredResourcesTest.php +++ b/tests/Feature/Permission/RegisteredResourcesTest.php @@ -15,10 +15,6 @@ use RefactorCircus\Roster\Domains\Permission\Services\Permissions; use RefactorCircus\Roster\Domains\Permission\Services\Resources; use RefactorCircus\Roster\Domains\Role\Models\RoleAssignmentModel; -use RefactorCircus\Roster\Domains\Scim\Models\ScimTokenModel; -use RefactorCircus\Roster\Domains\Scim\Policies\ScimTokenPolicy; -use RefactorCircus\Roster\Domains\Sso\Models\SsoConnectionModel; -use RefactorCircus\Roster\Domains\Sso\Policies\SsoConnectionPolicy; use RefactorCircus\Roster\Support\Policies\Policy; use RefactorCircus\Roster\Tests\Fixtures\Policies\OpenPolicy; use Workbench\App\Models\User; @@ -256,13 +252,6 @@ function rootCause(Throwable $exception): Throwable ->and(trim(Blade::render($view, ['scope' => $acme])))->toBe(''); }); -it('registers the SSO and SCIM resources and policies from their own domains', function (): void { - expect(app(Resources::class)->model('roster.sso'))->toBe(SsoConnectionModel::class) - ->and(app(Resources::class)->model('roster.scim'))->toBe(ScimTokenModel::class) - ->and(Gate::getPolicyFor(SsoConnectionModel::class))->toBeInstanceOf(SsoConnectionPolicy::class) - ->and(Gate::getPolicyFor(ScimTokenModel::class))->toBeInstanceOf(ScimTokenPolicy::class); -}); - it('leaves the impersonation-blocked list to the application', function (): void { $blocked = config('roster.impersonation.blocked'); diff --git a/tests/Feature/ProvisionedStatusTest.php b/tests/Feature/ProvisionedStatusTest.php index d4be4c2..77ba63c 100644 --- a/tests/Feature/ProvisionedStatusTest.php +++ b/tests/Feature/ProvisionedStatusTest.php @@ -3,12 +3,8 @@ declare(strict_types=1); use Illuminate\Support\Facades\Exceptions; -use RefactorCircus\Roster\Domains\Sso\Actions\SsoLoginAction; -use RefactorCircus\Roster\Domains\Sso\Data\IdentityClaims; use RefactorCircus\Roster\Domains\User\Enums\UserStatus; use RefactorCircus\Roster\Roster; -use RefactorCircus\Roster\Support\Users; -use Workbench\App\Models\User; it('reads the status a saved organization stores', function (): void { $acme = organization(attributes: ['name' => 'Acme']); @@ -17,29 +13,12 @@ expect(app(Roster::class)->provisionedStatus($acme->refresh()))->toBe(UserStatus::Pending); }); -it('provisions just-in-time SSO accounts through it, so a bad stored value never fails the sign-in', function (): void { - require_once __DIR__.'/Sso/helpers.php'; +it('starts externally provisioned accounts active on a bad stored value, and reports it', function (): void { Exceptions::fake(); - $connection = acmeWithSso(); - $connection->organization->update(['provisioned_status' => 'bogus']); - - [$user] = app(SsoLoginAction::class)->execute($connection, new IdentityClaims('sub-1', 'ada@acme.test', 'Ada Lovelace')); - - expect(app(Users::class)->status($user))->toBe(UserStatus::Active); - Exceptions::assertReported(fn (InvalidArgumentException $exception): bool => str_contains($exception->getMessage(), '[bogus]')); -}); - -it('provisions SCIM accounts through it, so a bad stored value never fails provisioning', function (): void { - require_once __DIR__.'/Scim/helpers.php'; - Exceptions::fake(); - - [$acme, $token] = scimOrg(); + $acme = organization(attributes: ['name' => 'Acme']); $acme->update(['provisioned_status' => 'bogus']); - test()->scimToken = $token; - - scim('POST', '/Users', oktaUser('one@acme.test', 'e1'))->assertCreated(); - expect(app(Users::class)->status(User::query()->where('email', 'one@acme.test')->sole()))->toBe(UserStatus::Active); + expect(app(Roster::class)->provisionedStatus($acme->refresh()))->toBe(UserStatus::Active); Exceptions::assertReported(fn (InvalidArgumentException $exception): bool => str_contains($exception->getMessage(), '[bogus]')); }); diff --git a/tests/Feature/SoftDeleteTest.php b/tests/Feature/SoftDeleteTest.php index c781916..af6d05f 100644 --- a/tests/Feature/SoftDeleteTest.php +++ b/tests/Feature/SoftDeleteTest.php @@ -2,9 +2,6 @@ declare(strict_types=1); -require_once __DIR__.'/Scim/helpers.php'; -require_once __DIR__.'/Sso/helpers.php'; - use Illuminate\Support\Facades\Auth; use Illuminate\Support\Str; use Illuminate\Validation\ValidationException; @@ -18,7 +15,6 @@ use RefactorCircus\Roster\Domains\Organization\Data\CreateOrganizationData; use RefactorCircus\Roster\Domains\Organization\Data\SwitchContextData; use RefactorCircus\Roster\Domains\Organization\Models\OrganizationModel; -use RefactorCircus\Roster\Domains\Sso\Models\SsoConnectionModel; use RefactorCircus\Roster\Domains\User\Actions\DeleteUserAction; use RefactorCircus\Roster\Domains\User\Actions\PurgeUserAction; use RefactorCircus\Roster\Roster; @@ -38,21 +34,18 @@ }); it('turns a deleted organization off everywhere until it is restored', function (): void { - [$acme, $token] = scimOrg(); + $acme = organization(attributes: ['name' => 'Acme', 'domains' => ['acme.test']]); $acme->update(['auto_join' => true]); $member = user(['email' => 'member@example.com']); app(AddMemberAction::class)->execute($acme, new AddMemberData(user: $member->getRouteKey())); app(SwitchContextAction::class)->execute($member, new SwitchContextData(organization: 'acme')); - SsoConnectionModel::factory()->create(['organization_id' => $acme->id, 'slug' => 'acme-okta']); app(DeleteOrganizationAction::class)->execute($acme); app()->forgetScopedInstances(); $this->actingAs(user())->getJson(route('roster.organizations.show', 'acme'))->assertNotFound(); - $this->getJson('/scim/v2/acme/Users', ['Authorization' => 'Bearer '.$token])->assertUnauthorized(); - expect(SsoConnectionModel::query()->where('slug', 'acme-okta')->exists())->toBeFalse() - ->and(app(Roster::class)->organization($member->fresh()))->toBeNull() + expect(app(Roster::class)->organization($member->fresh()))->toBeNull() ->and(app(JoinOrganizationsByDomainAction::class)->execute(user(['email' => 'new@acme.test', 'email_verified_at' => now()])))->toHaveCount(0); // Its slug and domains stay reserved. @@ -63,7 +56,6 @@ app()->forgetScopedInstances(); expect(app(Roster::class)->organization($member->fresh())?->slug)->toBe('acme'); - $this->getJson('/scim/v2/acme/Users', ['Authorization' => 'Bearer '.$token])->assertOk(); }); it('only purges deleted records', function (): void { diff --git a/tests/Feature/StoredIdentifiersTest.php b/tests/Feature/StoredIdentifiersTest.php index c40b8bd..b892a55 100644 --- a/tests/Feature/StoredIdentifiersTest.php +++ b/tests/Feature/StoredIdentifiersTest.php @@ -11,11 +11,6 @@ use RefactorCircus\Roster\Domains\Permission\Models\PermissionModel; use RefactorCircus\Roster\Domains\Role\Models\RoleAssignmentModel; use RefactorCircus\Roster\Domains\Role\Models\RoleModel; -use RefactorCircus\Roster\Domains\Scim\Models\ScimGroupModel; -use RefactorCircus\Roster\Domains\Scim\Models\ScimTokenModel; -use RefactorCircus\Roster\Domains\Scim\Models\ScimUserModel; -use RefactorCircus\Roster\Domains\Sso\Models\SsoConnectionModel; -use RefactorCircus\Roster\Domains\Sso\Models\SsoIdentityModel; use RefactorCircus\Roster\Domains\Team\Models\TeamMemberModel; use RefactorCircus\Roster\Domains\Team\Models\TeamModel; use RefactorCircus\Roster\Domains\Transfer\Models\TransferModel; @@ -36,11 +31,6 @@ ProfileModel::class, RoleModel::class, RoleAssignmentModel::class, - ScimGroupModel::class, - ScimTokenModel::class, - ScimUserModel::class, - SsoConnectionModel::class, - SsoIdentityModel::class, TeamModel::class, TeamMemberModel::class, TransferModel::class, diff --git a/tests/Feature/Ui/OrganizationRegisteredTabsTest.php b/tests/Feature/Ui/OrganizationRegisteredTabsTest.php index d877356..faccb0c 100644 --- a/tests/Feature/Ui/OrganizationRegisteredTabsTest.php +++ b/tests/Feature/Ui/OrganizationRegisteredTabsTest.php @@ -293,7 +293,7 @@ function organizationReads(Collection $queries, string $table): bool expect($this->calls->resolve)->toBe(0); Exceptions::assertReportedCount(1); Exceptions::assertReported(fn (InvalidArgumentException $exception): bool => str_contains($exception->getMessage(), '['.$key.']')); -})->with(['members', 'teams', 'invitations', 'roles', 'sso', 'scim']); +})->with(['members', 'teams', 'invitations', 'roles']); it('loads only the open built-in tab\'s data, and none while a registered tab is open', function (): void { Atrium::screens()->tab('roster.organization', countedOrganizationTab($this->calls)->public()); @@ -302,16 +302,14 @@ function organizationReads(Collection $queries, string $table): bool $this->get(route('atrium.roster.organizations.show', [$this->organization, 'tab' => 'invitations']))->assertOk(); - expect(organizationReads($queries, 'invitations'))->toBeTrue() - ->and(organizationReads($queries, 'scim_tokens'))->toBeFalse() - ->and(organizationReads($queries, 'sso_connections'))->toBeFalse(); + expect(organizationReads($queries, 'invitations'))->toBeTrue(); $queries->splice(0); app()->forgetScopedInstances(); - $this->get(route('atrium.roster.organizations.show', [$this->organization, 'tab' => 'scim']))->assertOk(); + $this->get(route('atrium.roster.organizations.show', [$this->organization, 'tab' => 'teams']))->assertOk(); - expect(organizationReads($queries, 'scim_tokens'))->toBeTrue() + expect(organizationReads($queries, 'teams'))->toBeTrue() ->and(organizationReads($queries, 'invitations'))->toBeFalse(); $queries->splice(0); @@ -322,7 +320,7 @@ function organizationReads(Collection $queries, string $table): bool expect($queries)->not->toBeEmpty(); // The tables only a built-in tab reads; the members list is the default's. - foreach (['invitations', 'scim_tokens', 'sso_connections'] as $table) { + foreach (['invitations'] as $table) { expect(organizationReads($queries, $table))->toBeFalse("the {$table} table is not read while a registered tab is open"); } }); diff --git a/tests/Feature/Ui/OrganizationTabBarTest.php b/tests/Feature/Ui/OrganizationTabBarTest.php index e1f4cb1..04d5f06 100644 --- a/tests/Feature/Ui/OrganizationTabBarTest.php +++ b/tests/Feature/Ui/OrganizationTabBarTest.php @@ -13,7 +13,7 @@ */ function organizationBuiltInTabs(): array { - return ['members', 'teams', 'invitations', 'roles', 'sso', 'scim', 'settings']; + return ['members', 'teams', 'invitations', 'roles', 'settings']; } /** @@ -90,11 +90,11 @@ function organizationTabBarViewer(array $permissions): void }); it('shows exactly the built-in tabs the viewer may see', function (): void { - organizationTabBarViewer(['roster.organizations.view', 'roster.members.view', 'roster.sso.view']); + organizationTabBarViewer(['roster.organizations.view', 'roster.members.view', 'roster.roles.view']); $links = organizationTabBarLinks($this->get(route('atrium.roster.organizations.show', $this->organization))->assertOk()); - expect(array_map(strval(...), array_keys($links)))->toBe(['members', 'sso', 'settings']); + expect(array_map(strval(...), array_keys($links)))->toBe(['members', 'roles', 'settings']); }); it('shows no tab bar while the viewer may open only one built-in tab', function (): void { diff --git a/tests/Feature/Ui/ScreenDeclarationsTest.php b/tests/Feature/Ui/ScreenDeclarationsTest.php index 1f70c02..e2532bd 100644 --- a/tests/Feature/Ui/ScreenDeclarationsTest.php +++ b/tests/Feature/Ui/ScreenDeclarationsTest.php @@ -152,7 +152,7 @@ function declaredTestIdCount(TestResponse $response, string $testId): int preg_match_all('/data-testid="tab-([^"]+)"/', (string) $response->getContent(), $tabs); $response->assertSee('data-testid="screen-tabs"', false); - expect($tabs[1])->toBe(['members', 'teams', 'invitations', 'roles', 'sso', 'scim', 'settings']); + expect($tabs[1])->toBe(['members', 'teams', 'invitations', 'roles', 'settings']); } else { $response->assertDontSee('data-testid="screen-tabs"', false) ->assertDontSee('data-testid="tab-', false); diff --git a/tests/Feature/Ui/UserRegisteredTabsTest.php b/tests/Feature/Ui/UserRegisteredTabsTest.php index 24b767f..c94ced3 100644 --- a/tests/Feature/Ui/UserRegisteredTabsTest.php +++ b/tests/Feature/Ui/UserRegisteredTabsTest.php @@ -473,13 +473,13 @@ function userScreenTabs(TestResponse $response): array it('does not load the overview\'s data while a registered tab is open', function (): void { Atrium::screens()->tab('roster.user', countedUserTab($this->calls)->public()); - // Only the overview reads the SSO identities table. - $table = Tables::name('sso_identities'); + // Only the overview lists the user's memberships of live organizations. + $table = Tables::name('memberships'); $queries = collect(); DB::listen(function (QueryExecuted $query) use ($queries): void { $queries->push($query->sql); }); - $reads = fn (): bool => $queries->contains(fn (string $sql): bool => str_contains($sql, $table)); + $reads = fn (): bool => $queries->contains(fn (string $sql): bool => str_contains($sql, $table) && str_contains($sql, 'exists (')); assertUserTabOpen($this->get(route('atrium.roster.users.show', $this->target->getRouteKey()))->assertOk(), 'overview'); diff --git a/tests/Feature/UserApprovalTest.php b/tests/Feature/UserApprovalTest.php index ca70197..052d596 100644 --- a/tests/Feature/UserApprovalTest.php +++ b/tests/Feature/UserApprovalTest.php @@ -21,6 +21,7 @@ use RefactorCircus\Roster\Domains\User\Notifications\UserApprovedNotification; use RefactorCircus\Roster\Domains\User\Notifications\UserAwaitingApprovalNotification; use RefactorCircus\Roster\Domains\User\Notifications\UserRejectedNotification; +use RefactorCircus\Roster\Roster; use RefactorCircus\Roster\Support\Users; use Workbench\App\Models\User; @@ -109,17 +110,14 @@ function pendingUser(array $attributes = []): User $this->actingAs(pendingUser())->get('/approval-check')->assertForbidden()->assertSee('awaiting approval'); }); -it('lets organizations choose whether their SCIM accounts need approval', function (): void { - require_once __DIR__.'/Scim/helpers.php'; - [$acme, $token] = scimOrg(); - test()->scimToken = $token; +it('lets organizations choose whether their externally provisioned accounts need approval', function (): void { + $acme = organization(attributes: ['name' => 'Acme', 'domains' => ['acme.test']]); + + expect(app(Roster::class)->provisionedStatus($acme))->toBe(UserStatus::Active); - scim('POST', '/Users', oktaUser('one@acme.test', 'e1'))->assertCreated(); app(UpdateOrganizationAction::class)->execute($acme, new UpdateOrganizationData(provisionedStatus: UserStatus::Pending)); - scim('POST', '/Users', oktaUser('two@acme.test', 'e2'))->assertCreated(); - expect(app(Users::class)->status(User::query()->where('email', 'one@acme.test')->sole()))->toBe(UserStatus::Active) - ->and(app(Users::class)->status(User::query()->where('email', 'two@acme.test')->sole()))->toBe(UserStatus::Pending); + expect(app(Roster::class)->provisionedStatus($acme->refresh()))->toBe(UserStatus::Pending); }); it('approves and rejects over http and mcp', function (): void { diff --git a/tests/Modes/Keen/KeenAuditTest.php b/tests/Modes/Keen/KeenAuditTest.php index 8b7c04f..66d8336 100644 --- a/tests/Modes/Keen/KeenAuditTest.php +++ b/tests/Modes/Keen/KeenAuditTest.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Gate; use RefactorCircus\Keen\Domains\Audit\Models\AuditEntryModel; use RefactorCircus\Keystone\Audit\History; @@ -14,10 +15,6 @@ use RefactorCircus\Roster\Domains\Role\Data\AssignRoleData; use RefactorCircus\Roster\Domains\Role\Data\UpdateRoleData; use RefactorCircus\Roster\Domains\Role\Models\RoleModel; -use RefactorCircus\Roster\Domains\Sso\Actions\CreateSsoConnectionAction; -use RefactorCircus\Roster\Domains\Sso\Actions\UpdateSsoConnectionAction; -use RefactorCircus\Roster\Domains\Sso\Data\CreateSsoConnectionData; -use RefactorCircus\Roster\Domains\Sso\Data\UpdateSsoConnectionData; use RefactorCircus\Roster\Domains\Transfer\Enums\TransferType; use RefactorCircus\Roster\Domains\Transfer\Models\TransferModel; use RefactorCircus\Roster\Domains\Transfer\Services\TransferContext; @@ -32,8 +29,6 @@ use RefactorCircus\Roster\Tests\Fixtures\Billing\InvoicePaidActionEvent; use RefactorCircus\Roster\Tests\Fixtures\Billing\InvoicePayingActionEvent; -require_once dirname(__DIR__, 2).'/Feature/Scim/helpers.php'; - function keenEntry(string $action): AuditEntryModel { return AuditEntryModel::query()->where('action', $action)->latest('id')->firstOrFail(); @@ -94,38 +89,57 @@ function keenEntry(string $action): AuditEntryModel expect(keenEntry('profile.updated')->changes['profile.display_name'])->toBe([null, 'Countess']); }); -it('redacts passwords and connection secrets', function (): void { +it('redacts passwords', function (): void { $ada = user(['name' => 'Ada']); app(UpdateUserAction::class)->execute($ada, new UpdateUserData(password: 'correct-horse-battery')); expect(keenEntry('user.updated')->changes['password'] ?? null)->toBe(['[redacted]', '[redacted]']); - $connection = app(CreateSsoConnectionAction::class)->execute(organization(), new CreateSsoConnectionData( - name: 'Okta', - protocol: 'oidc', - issuer: 'https://idp.test', - clientId: 'app', - clientSecret: 'top-secret', - )); - app(UpdateSsoConnectionAction::class)->execute($connection, new UpdateSsoConnectionData(clientSecret: 'rotated')); - $log = json_encode(AuditEntryModel::query()->get()->toArray()); - expect($log)->not->toContain('top-secret') - ->and($log)->not->toContain('rotated') - ->and($log)->not->toContain('correct-horse-battery') - ->and(keenEntry('sso_connection.updated')->changes['config'][1]['client_secret'])->toBe('[redacted]'); + expect($log)->not->toContain('correct-horse-battery'); +}); + +it('adds no scim_token context to Roster\'s entries, but still its other context', function (): void { + $admin = user(['name' => 'Admin']); + grant($admin, 'super-admin'); + $ada = user(['name' => 'Ada']); + grant($ada, 'super-admin'); + $grace = user(['name' => 'Grace']); + + $this->actingAs($admin); + $started = app(StartImpersonationAction::class)->execute($ada, new StartImpersonationData(reason: 'Ticket 42'), $admin); + $this->get($started->url); + + app(SuspendUserAction::class)->execute($grace, new SuspendUserData(reason: 'Spam')); + + $context = keenEntry('user.suspended')->context; + + // The positive control: the impersonator context lands on the same entry. + expect($context)->toHaveKey('impersonator') + ->and($context['impersonator'])->toBe(['id' => (string) $admin->getKey(), 'label' => 'Admin']) + ->and($context)->not->toHaveKey('scim_token'); }); -it('records SCIM changes with the token that made them, through the scim surface', function (): void { - [, $this->scimToken] = scimOrg(); +it('leaves an old entry\'s scim_token context as written, and still serves it', function (): void { + app(SuspendUserAction::class)->execute(user(['name' => 'Grace'])); + $entry = keenEntry('user.suspended'); + + // Written by an older Roster, whose SCIM domain added the token. + DB::table($entry->getTable())->where('id', $entry->getKey())->update([ + 'context' => json_encode([...(array) $entry->context, 'scim_token' => ['id' => 7, 'name' => 'Okta']]), + ]); + + expect(keenEntry('user.suspended')->context['scim_token'] ?? null)->toBe(['id' => 7, 'name' => 'Okta']); - scim('POST', '/Users', oktaUser())->assertCreated(); + $this->getJson(route('roster.history.index')) + ->assertOk() + ->assertJsonPath('data.0.action', 'user.suspended'); - $entry = keenEntry('user.created'); + grant($auditor = user(), 'super-admin'); + $this->actingAs($auditor); - expect($entry->surface)->toBe('scim') - ->and($entry->context['scim_token']['name'])->toBe('Okta'); + mcpTool(ListRosterHistoryTool::class)->assertOk()->assertSee('user.suspended'); }); it('records the import a change came from', function (): void { diff --git a/tests/Modes/RenamedTables/RenamedTablesTest.php b/tests/Modes/RenamedTables/RenamedTablesTest.php index 54a1623..b1cae0b 100644 --- a/tests/Modes/RenamedTables/RenamedTablesTest.php +++ b/tests/Modes/RenamedTables/RenamedTablesTest.php @@ -2,8 +2,6 @@ declare(strict_types=1); -require_once __DIR__.'/../../Feature/Scim/helpers.php'; - use Illuminate\Support\Facades\Schema; use RefactorCircus\Roster\Domains\Organization\Actions\AddMemberAction; use RefactorCircus\Roster\Domains\Organization\Data\AddMemberData; @@ -16,7 +14,6 @@ use RefactorCircus\Roster\Domains\Team\Actions\CreateTeamAction; use RefactorCircus\Roster\Domains\Team\Data\AddTeamMemberData; use RefactorCircus\Roster\Domains\Team\Data\CreateTeamData; -use RefactorCircus\Roster\Domains\Team\Models\TeamModel; use RefactorCircus\Roster\Support\Tables; it('migrates every table under its configured name', function (): void { @@ -51,15 +48,3 @@ ->and(validator(['name' => 'Ok', 'scope' => 'organization', 'permissions' => ['roster.members.view', 'nope']], CreateRoleData::rules())->errors()->keys())->toBe(['permissions.1']) ->and(validator(['name' => 'Ops', 'slug' => 'ops'], CreateTeamData::rules($acme))->fails())->toBeTrue(); }); - -it('serves SCIM groups from renamed tables', function (): void { - [$this->acme, $this->scimToken] = scimOrg(); - $ada = (string) scim('POST', '/Users', oktaUser())->json('id'); - - scim('POST', '/Groups', ['displayName' => 'Engineering', 'members' => [['value' => $ada]]])->assertCreated(); - - scim('GET', '/Groups')->assertOk()->assertJsonPath('Resources.0.members.0.value', $ada); - scim('GET', '/Users/'.$ada)->assertJsonPath('groups.0.display', 'Engineering'); - - expect(TeamModel::query()->sole()->getTable())->toBe('crm_teams'); -}); diff --git a/tests/Pest.php b/tests/Pest.php index d42a30f..dbdfa04 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -25,7 +25,6 @@ use RefactorCircus\Roster\Tests\KeenTestCase; use RefactorCircus\Roster\Tests\PennantPlusTestCase; use RefactorCircus\Roster\Tests\RenamedTablesTestCase; -use RefactorCircus\Roster\Tests\SsoUnavailableTestCase; use RefactorCircus\Roster\Tests\TestCase; use RefactorCircus\Roster\Tests\TraitlessTestCase; use RefactorCircus\Roster\Tests\TransfersUnavailableTestCase; @@ -60,7 +59,6 @@ uses(AtriumFeaturesTestCase::class)->in('Modes/AtriumFeatures'); uses(KeenTestCase::class)->in('Modes/Keen'); uses(PennantPlusTestCase::class)->in('Modes/PennantPlus'); -uses(SsoUnavailableTestCase::class)->in('Modes/SsoUnavailable'); uses(TransfersUnavailableTestCase::class)->in('Modes/TransfersUnavailable'); uses(AtriumUnavailableTestCase::class)->in('Modes/AtriumUnavailable'); uses(RenamedTablesTestCase::class)->in('Modes/RenamedTables'); @@ -133,10 +131,6 @@ function organization(?User $owner = null, array $attributes = []): Organization // Using the one-time link swaps a browser session; it has no API or // MCP meaning. Start, list and stop are on every surface. 'EnterImpersonationAction' => ['http', 'mcp'], - // Signing in and linking happen in the browser, between Roster and the - // identity provider; there is nothing for an API caller to send. - 'SsoLoginAction' => ['http', 'mcp'], - 'LinkSsoIdentityAction' => ['http', 'mcp'], // Machine-to-machine sync from an ERP or CRM. In Atrium the same results // come from the organization CSV import (bulk) and the link form. 'SyncOrganizationAction' => ['ui'], diff --git a/tests/Unit/Organization/MembershipSourcesTest.php b/tests/Unit/Organization/MembershipSourcesTest.php index 908fb1a..35ebd2c 100644 --- a/tests/Unit/Organization/MembershipSourcesTest.php +++ b/tests/Unit/Organization/MembershipSourcesTest.php @@ -65,7 +65,7 @@ 'longer than 32 characters' => str_repeat('a', 33), ]); -it('has the SCIM domain register scim with its label', function (): void { - expect(app(MembershipSources::class)->has('scim'))->toBeTrue() - ->and(app(MembershipSources::class)->label('scim'))->toBe('SCIM'); +it('no longer registers scim, and shows a stored scim as-is', function (): void { + expect(app(MembershipSources::class)->has('scim'))->toBeFalse() + ->and(app(MembershipSources::class)->label('scim'))->toBe('scim'); }); diff --git a/tests/Unit/Permission/PermissionCatalogueTest.php b/tests/Unit/Permission/PermissionCatalogueTest.php index baa661d..95833a6 100644 --- a/tests/Unit/Permission/PermissionCatalogueTest.php +++ b/tests/Unit/Permission/PermissionCatalogueTest.php @@ -24,16 +24,6 @@ ->and($catalogue->grantedTo('member'))->toBe([]); }); -it('registers the SSO and SCIM permissions from their domains, granted to admin', function (): void { - $catalogue = app(PermissionCatalogue::class); - - expect($catalogue->all())->toMatchArray([ - 'roster.sso.view' => ['description' => "View an organization's single sign-on connections.", 'grantTo' => ['admin']], - 'roster.sso.manage' => ['description' => 'Configure single sign-on connections.', 'grantTo' => ['admin']], - 'roster.scim.manage' => ['description' => 'Issue and revoke SCIM provisioning tokens.', 'grantTo' => ['admin']], - ]); -}); - it('rejects a name registered twice, naming it', function (): void { $catalogue = (new PermissionCatalogue)->permission('acme.widgets.approve', 'Approve widgets.'); From 323b001aa87c2e21d0b851852cf9a7de1c201fcb Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Fri, 30 Oct 2026 02:57:19 -0400 Subject: [PATCH 08/17] 2026-10-29-2038-remove-sso-and-scim: group 1 Remove SSO and SCIM code, surfaces, config and migrations Co-Authored-By: Claude Opus 5.5 --- .../build.md | 33 ++ .../tasks.md | 6 +- tests/Feature/ComposerTest.php | 13 + tests/Feature/LegacySsoScimUpgradeTest.php | 222 ++++++++++++ tests/Feature/NoExternalSignInTest.php | 81 +++++ tests/Feature/RemovedSsoScimTest.php | 332 ++++++++++++++++++ tests/Feature/Ui/SharedTabBarTest.php | 2 +- tests/Fixtures/legacy_sso_scim_schema.php | 106 ++++++ 8 files changed, 791 insertions(+), 4 deletions(-) create mode 100644 docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/build.md create mode 100644 tests/Feature/LegacySsoScimUpgradeTest.php create mode 100644 tests/Feature/NoExternalSignInTest.php create mode 100644 tests/Feature/RemovedSsoScimTest.php create mode 100644 tests/Fixtures/legacy_sso_scim_schema.php diff --git a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/build.md b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/build.md new file mode 100644 index 0000000..6fd51a2 --- /dev/null +++ b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/build.md @@ -0,0 +1,33 @@ +# Build: Remove SSO and SCIM + +## Group 1 + +Remove SSO and SCIM code, surfaces, config and migrations (criteria 1 to 13). + +### Files + +- Deleted: `src/Domains/Sso/`, `src/Domains/Scim/`, `src/Mcp/Concerns/DescribesSsoConnection.php`, `src/Atrium/Http/Controllers/SsoUiController.php`, `src/Atrium/Http/Controllers/ScimUiController.php`, `resources/views/ui/sso/`, `database/factories/SsoConnectionFactory.php`, `database/migrations/2026_01_01_000006_create_roster_sso_tables.php`, `database/migrations/2026_01_01_000007_create_roster_scim_tables.php`. +- Added: `src/Support/Rules/NoExternalSignIn.php` (message key `external_sign_in_required`, the old `sso_required` text unchanged). +- Edited: `src/Domains/DomainServiceProvider.php`, `src/Mcp/RosterServer.php` (ten tools), `src/Atrium/RosterPlugin.php` (seven routes), `src/Atrium/Http/Controllers/OrganizationUiController.php` (tabs, permission and icon maps, tab data), `src/Atrium/Http/Controllers/UserUiController.php`, `src/RosterServiceProvider.php` (`scim` surface, comments), `src/Support/Tables.php`, `src/Support/Audit.php`, `src/Support/Policies/Policy.php`, `src/Support/ProvisionedStatus.php`, `src/Roster.php`, `src/Data/ExternalSignIn.php`, `src/Domains/Permission/PermissionServiceProvider.php`, `src/Mcp/Concerns/DescribesOrganization.php`, `src/Domains/Organization/` (purge action and tool, `CreateOrganizationData`, `OrganizationRules` comments), `resources/views/ui/organizations/show.blade.php`, `resources/views/ui/users/partials/overview.blade.php`, `resources/views/ui/users/show.blade.php`, `resources/import-templates/import_users.csv`, `resources/boost/skills/roster-development/SKILL.md` (SSO/SCIM wording only, so the criterion 12 scan over `resources/` holds), `config/roster.php`, `lang/en/roster.php`, migrations 000002, 000010, `2026_10_12_000001` and the email-index migration, `composer.json` (`suggest`, `require-dev`), and `composer.local.json` (git-ignored, mirrored by hand). +- Tests added: `tests/Feature/RemovedSsoScimTest.php`, `tests/Feature/LegacySsoScimUpgradeTest.php`, `tests/Feature/NoExternalSignInTest.php`, `tests/Fixtures/legacy_sso_scim_schema.php` (000006/000007 verbatim). +- Tests deleted: `tests/Feature/Sso/`, `tests/Feature/Scim/`, `tests/Feature/Http/SsoHttpTest.php`, `tests/Feature/Http/ScimTokensHttpTest.php`, `tests/Feature/Ui/SsoPagesTest.php`, `tests/Feature/Ui/ScimPagesTest.php`, `tests/Browser/SsoBrowserTest.php`, `tests/Browser/ScimBrowserTest.php`, `tests/Modes/SsoUnavailable/`, `tests/SsoUnavailableTestCase.php`. +- Tests edited (SSO/SCIM cases only): `tests/Pest.php`, `tests/ArchTest.php`, `tests/Authorization/` (fixtures, HTTP, MCP, policies, screen controls), `tests/Feature/ComposerTest.php`, `DocsTest.php` (one line), `IndexesTest.php`, `Organization/MembershipSourceTest.php`, `PerformanceTest.php`, `Permission/PermissionSyncTest.php`, `Permission/RegisteredResourcesTest.php`, `ProvisionedStatusTest.php`, `SoftDeleteTest.php`, `StoredIdentifiersTest.php`, `Transfers/TemplateTest.php`, `Ui/OrganizationTabBarTest.php`, `Ui/OrganizationRegisteredTabsTest.php`, `Ui/ScreenDeclarationsTest.php`, `Ui/SharedTabBarTest.php` (built-in list), `Ui/UserRegisteredTabsTest.php`, `UserApprovalTest.php`, `tests/Modes/Keen/KeenAuditTest.php`, `tests/Modes/RenamedTables/RenamedTablesTest.php`, `tests/Unit/Organization/MembershipSourcesTest.php`, `tests/Unit/Permission/PermissionCatalogueTest.php`. + +### Tests + +- Criterion 1: `RemovedSsoScimTest` (folders, provider list, `class_exists`/`trait_exists`, the `SsoConnectionModel` handover string, and an `arch()` rule that nothing under `RefactorCircus\Roster` uses either domain). +- Criterion 2: `RemovedSsoScimTest` (`Resources`, `PermissionCatalogue`, `Authorizer` for an organization admin, `MembershipSources`); `KeenAuditTest` (no `scim_token` with the impersonator context as positive control; an old entry with `scim_token` still served by the history route and tool). +- Criterion 3: `PermissionSyncTest` (unregistered report, rows and admin grants kept for every option the command defines). +- Criterion 4: `MembershipSourceTest` (raw `scim` on read, resource, API, MCP and members tab; filter, team write and import; `SCIM` once registered). +- Criteria 5 to 9 and 12: `RemovedSsoScimTest` (route-name dataset, route-table regex scan over names and URIs, `Surface` registry content, MCP tool names, the five organization tabs with members default, `?tab=sso`/`?tab=scim` fallbacks, controllers, overview view data, config and `Tables::DEFAULTS`, the criterion 12 regex scan and a regex self-check). +- Criterion 10: `LegacySsoScimUpgradeTest` (fresh migrate creates none of the five; upgraded install through migrate, status, rollback, re-migrate and refresh keeps the five tables and rows; `migrate:fresh` errors nowhere and creates no second set; stray `migrations` rows). +- Criterion 11: `ComposerTest` (`suggest`, `require-dev`, unchanged Atrium `conflict` `<0.1.0`) and the vendor-namespace scan in `RemovedSsoScimTest`. +- Criterion 13: `NoExternalSignInTest` through `Roster::requireSignIn()`. +- Run here: the four new files plus `MembershipSourceTest`, `PermissionSyncTest`, `KeenAuditTest` and `SharedTabBarTest` (122 tests, green); `vendor/bin/pint --test` on the new files and `phpstan analyse` (green). The full suite is left to the gate. + +### Deviations and notes + +- `LegacySsoScimUpgradeTest` runs on its own in-memory SQLite connection with foreign keys off. With them on, SQLite turns dropping `roster_organizations` during rollback into an implicit delete that cascades into the legacy rows (MySQL and PostgreSQL refuse the drop instead). The test checks what Roster's migrations do to the five tables. The fixture's `Tables::name()` calls resolve because the test names the five keys in `roster.tables`, as an upgraded install's published config does. +- `Authorizer::check()` sends an unregistered prefix to the raw permission check (`permits()`), not a flat deny. On a fresh install the admin holds no `roster.sso.view`, so the check denies, which is what the test pins. On an upgraded install without Guardian, the kept legacy grant would still pass a raw `roster.sso.view` check. Nothing in Roster asks for it any more. +- `tests/Unit` is not a PHPUnit test suite in `phpunit.xml.dist`, and `tests/Pest.php` binds no test case to it, so its files (including the edited `MembershipSourcesTest` and `PermissionCatalogueTest`, and the seams' `SignInRequirementsTest`) do not run in `composer test`. This predates this spec and is left unchanged. +- For group 2: criterion 12 scans `resources/`, including the Boost skill, so `SKILL.md` must keep its Guardian section free of the criterion 12 tokens (the current text says "Single sign-on and provisioning"). diff --git a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/tasks.md b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/tasks.md index f36b2c0..fb96b8a 100644 --- a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/tasks.md +++ b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/tasks.md @@ -8,9 +8,9 @@ depends on: none files: src/Domains/Sso/, src/Domains/Scim/, src/Domains/DomainServiceProvider.php, src/Mcp/Concerns/DescribesSsoConnection.php, src/Mcp/RosterServer.php, src/Atrium/Http/Controllers/SsoUiController.php, src/Atrium/Http/Controllers/ScimUiController.php, src/Atrium/Http/Controllers/OrganizationUiController.php, src/Atrium/Http/Controllers/UserUiController.php, src/Atrium/RosterPlugin.php, src/RosterServiceProvider.php, src/Support/Tables.php, src/Support/Rules/NoExternalSignIn.php, src/Support/Audit.php, src/Support/Policies/Policy.php, src/Roster.php, src/Domains/Organization/, src/Domains/Permission/PermissionServiceProvider.php, src/Data/ExternalSignIn.php, resources/views/ui/sso/, resources/views/ui/organizations/show.blade.php, resources/views/ui/users/partials/overview.blade.php, resources/views/ui/users/show.blade.php, resources/import-templates/import_users.csv, config/roster.php, lang/en/roster.php, database/factories/SsoConnectionFactory.php, database/migrations/2026_01_01_000006_create_roster_sso_tables.php, database/migrations/2026_01_01_000007_create_roster_scim_tables.php, database/migrations/2026_01_01_000010_add_roster_lookup_indexes.php, database/migrations/2026_10_12_000001_add_roster_performance_indexes.php, database/migrations/2026_01_01_000002_create_roster_organization_tables.php, workbench/, composer.json, composer.local.json, tests/Fixtures/legacy_sso_scim_schema.php, tests/Feature/RemovedSsoScimTest.php, tests/Feature/LegacySsoScimUpgradeTest.php, tests/Feature/NoExternalSignInTest.php, tests/Feature/Sso/, tests/Feature/Scim/, tests/Feature/Http/SsoHttpTest.php, tests/Feature/Http/ScimTokensHttpTest.php, tests/Feature/Ui/SsoPagesTest.php, tests/Feature/Ui/ScimPagesTest.php, tests/Browser/SsoBrowserTest.php, tests/Browser/ScimBrowserTest.php, tests/Modes/SsoUnavailable/, tests/SsoUnavailableTestCase.php, tests/Pest.php, tests/ArchTest.php, tests/Authorization/, tests/Feature/IndexesTest.php, tests/Feature/Organization/MembershipSourceTest.php, tests/Feature/PerformanceTest.php, tests/Feature/Permission/PermissionSyncTest.php, tests/Feature/Permission/RegisteredResourcesTest.php, tests/Feature/ProvisionedStatusTest.php, tests/Feature/SoftDeleteTest.php, tests/Feature/StoredIdentifiersTest.php, tests/Feature/Transfers/TemplateTest.php, tests/Feature/Ui/OrganizationTabBarTest.php, tests/Feature/Ui/OrganizationRegisteredTabsTest.php, tests/Feature/Ui/UserRegisteredTabsTest.php, tests/Feature/UserApprovalTest.php, tests/Feature/ComposerTest.php, tests/Modes/Keen/KeenAuditTest.php, tests/Modes/RenamedTables/RenamedTablesTest.php, tests/Unit/Organization/MembershipSourcesTest.php, tests/Unit/Permission/PermissionCatalogueTest.php criteria: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 -- [ ] 1.1 Write tests for criteria 1 to 13: `RemovedSsoScimTest` (folders and classes absent, `class_exists('RefactorCircus\Roster\Domains\Sso\Models\SsoConnectionModel')` false, the arch rule, `Resources`/`PermissionCatalogue`/`MembershipSources`/`Authorizer` answers, no `scim_token` with a positive control and an old entry still rendering, the route-name dataset and route-table regex scan, `Surface` content, MCP tool names, the five organization tabs with `?tab=sso`/`?tab=scim` opening `members`, no `ssoIdentities` on the overview, config and `Tables::DEFAULTS` keys, the criterion 12 regex scan and the vendor-namespace scan); kept permission rows across every `roster:sync-permissions` option; the raw `scim` source on read, write, import and filter paths, and `SCIM` once registered; `LegacySsoScimUpgradeTest` with the verbatim fixture through migrate, rollback, refresh and fresh plus a stray `migrations` row; `NoExternalSignInTest` through `Roster::requireSignIn()`; `ComposerTest` for `suggest`, `require-dev` and the unchanged Atrium `conflict` -- [ ] 1.2 Delete the SSO and SCIM domains, factory, `DescribesSsoConnection`, the ten MCP tools, both Atrium controllers, `ui/sso`, the plugin routes, the `sso`/`scim` tabs, icons and permission-map entries, the overview card, the `scim` surface, the config sections, `Tables` keys, lang keys and migrations 000006/000007; strip the SSO/SCIM entries from the two index migrations; add `Support\Rules\NoExternalSignIn` with `external_sign_in_required`; reword the comments listed in criterion 12; update `composer.json` `suggest`/`require-dev` and regenerate `composer.local.json`; delete and edit the tests listed in criterion 16 (only their SSO/SCIM cases) -- [ ] 1.3 Run vendor/bin/pest (including `tests/Modes/AtriumUnavailable`) and composer analyse; all green +- [x] 1.1 Write tests for criteria 1 to 13: `RemovedSsoScimTest` (folders and classes absent, `class_exists('RefactorCircus\Roster\Domains\Sso\Models\SsoConnectionModel')` false, the arch rule, `Resources`/`PermissionCatalogue`/`MembershipSources`/`Authorizer` answers, no `scim_token` with a positive control and an old entry still rendering, the route-name dataset and route-table regex scan, `Surface` content, MCP tool names, the five organization tabs with `?tab=sso`/`?tab=scim` opening `members`, no `ssoIdentities` on the overview, config and `Tables::DEFAULTS` keys, the criterion 12 regex scan and the vendor-namespace scan); kept permission rows across every `roster:sync-permissions` option; the raw `scim` source on read, write, import and filter paths, and `SCIM` once registered; `LegacySsoScimUpgradeTest` with the verbatim fixture through migrate, rollback, refresh and fresh plus a stray `migrations` row; `NoExternalSignInTest` through `Roster::requireSignIn()`; `ComposerTest` for `suggest`, `require-dev` and the unchanged Atrium `conflict` +- [x] 1.2 Delete the SSO and SCIM domains, factory, `DescribesSsoConnection`, the ten MCP tools, both Atrium controllers, `ui/sso`, the plugin routes, the `sso`/`scim` tabs, icons and permission-map entries, the overview card, the `scim` surface, the config sections, `Tables` keys, lang keys and migrations 000006/000007; strip the SSO/SCIM entries from the two index migrations; add `Support\Rules\NoExternalSignIn` with `external_sign_in_required`; reword the comments listed in criterion 12; update `composer.json` `suggest`/`require-dev` and regenerate `composer.local.json`; delete and edit the tests listed in criterion 16 (only their SSO/SCIM cases) +- [x] 1.3 Run vendor/bin/pest (including `tests/Modes/AtriumUnavailable`) and composer analyse; all green ## Group 2: Upgrade docs and gate package: Roster diff --git a/tests/Feature/ComposerTest.php b/tests/Feature/ComposerTest.php index efcc57c..b6ea407 100644 --- a/tests/Feature/ComposerTest.php +++ b/tests/Feature/ComposerTest.php @@ -35,6 +35,19 @@ function rosterComposer(): array ->toHaveKey('refactor-circus/keen', "Records Roster's changes in the suite-wide audit log (dev-main)."); }); +it('suggests Guardian for single sign-on and SCIM, and no SSO vendor library', function (): void { + $suggest = (array) rosterComposer()['suggest']; + + expect($suggest) + ->toHaveKey('refactor-circus/guardian', "Single sign-on (OIDC, SAML, Entra ID) and SCIM provisioning for Roster's organizations (dev-main).") + ->not->toHaveKeys(['laravel/socialite', 'socialiteproviders/saml2', 'firebase/php-jwt', 'socialiteproviders/microsoft-azure']); +}); + +it('no longer needs the SSO vendor libraries for its own tests', function (): void { + expect((array) rosterComposer()['require-dev']) + ->not->toHaveKeys(['laravel/socialite', 'socialiteproviders/saml2', 'firebase/php-jwt', 'socialiteproviders/microsoft-azure']); +}); + it('refuses an Atrium older than the screen registry', function (): void { expect(rosterComposer()['conflict'] ?? null)->toBe(['refactor-circus/atrium' => '<0.1.0']); }); diff --git a/tests/Feature/LegacySsoScimUpgradeTest.php b/tests/Feature/LegacySsoScimUpgradeTest.php new file mode 100644 index 0000000..55437c4 --- /dev/null +++ b/tests/Feature/LegacySsoScimUpgradeTest.php @@ -0,0 +1,222 @@ + 'roster_sso_connections', + 'sso_identities' => 'roster_sso_identities', + 'scim_tokens' => 'roster_scim_tokens', + 'scim_users' => 'roster_scim_users', + 'scim_groups' => 'roster_scim_groups', +]; + +/** + * The `migrations` rows the removed 000006 / 000007 files left behind. + */ +const LEGACY_SSO_SCIM_MIGRATIONS = [ + '2026_01_01_000006_create_roster_sso_tables', + '2026_01_01_000007_create_roster_scim_tables', +]; + +/** + * The full Roster migration set an app runs: Laravel's own tables, the + * workbench's users columns, Roster's migrations and its optional + * email-index migration. + * + * @return list + */ +function legacyMigrationPaths(): array +{ + $root = dirname(__DIR__, 2); + + return [ + default_migration_path(), + $root.'/workbench/database/migrations', + $root.'/database/migrations', + $root.'/database/migrations/email-index', + ]; +} + +/** + * Run a migrate command over the Roster migrations on the upgrade test's own + * database, asserting it succeeds. + */ +function legacyMigrate(string $command): void +{ + $options = ['--database' => 'legacy', '--path' => legacyMigrationPaths(), '--realpath' => true]; + + if ($command !== 'migrate:status') { + $options['--force'] = true; + } + + $status = Artisan::call($command, $options); + + expect($status)->toBe(0, "{$command} failed:\n".Artisan::output()); +} + +function legacyHasTable(string $table): bool +{ + return Schema::connection('legacy')->hasTable($table); +} + +/** + * The five tables that exist on the upgrade test's database, with their row + * counts. + * + * @return array + */ +function legacyRows(): array +{ + $rows = []; + + foreach (LEGACY_SSO_SCIM_TABLES as $table) { + if (legacyHasTable($table)) { + $rows[$table] = DB::connection('legacy')->table($table)->count(); + } + } + + return $rows; +} + +/** + * Bring the upgrade test's database to an upgraded install's state: Roster's + * tables, the five SSO and SCIM tables from the verbatim fixture with one row + * each, and the `migrations` rows of the two removed files. + */ +function legacyInstall(): void +{ + legacyMigrate('migrate'); + + /** @var array{sso: Migration, scim: Migration} $legacy */ + $legacy = require dirname(__DIR__).'/Fixtures/legacy_sso_scim_schema.php'; + + DB::setDefaultConnection('legacy'); + $legacy['sso']->up(); + $legacy['scim']->up(); + + $db = DB::connection('legacy'); + $now = now(); + $userId = $db->table('users')->insertGetId(['name' => 'Ada', 'email' => 'ada@acme.test', 'password' => 'x', 'created_at' => $now, 'updated_at' => $now]); + $organizationId = (string) Str::ulid(); + $teamId = (string) Str::ulid(); + $connectionId = (string) Str::ulid(); + + $db->table('roster_organizations')->insert(['id' => $organizationId, 'name' => 'Acme', 'slug' => 'acme', 'created_at' => $now, 'updated_at' => $now]); + $db->table('roster_teams')->insert(['id' => $teamId, 'organization_id' => $organizationId, 'name' => 'Ops', 'slug' => 'ops', 'created_at' => $now, 'updated_at' => $now]); + $db->table('roster_sso_connections')->insert(['id' => $connectionId, 'organization_id' => $organizationId, 'name' => 'Okta', 'slug' => 'acme-okta', 'protocol' => 'oidc', 'config' => 'encrypted', 'created_at' => $now, 'updated_at' => $now]); + $db->table('roster_sso_identities')->insert(['id' => (string) Str::ulid(), 'connection_id' => $connectionId, 'user_id' => $userId, 'subject' => 'okta|ada', 'created_at' => $now, 'updated_at' => $now]); + $db->table('roster_scim_tokens')->insert(['id' => (string) Str::ulid(), 'organization_id' => $organizationId, 'name' => 'Okta', 'token_hash' => str_repeat('a', 64), 'sso_connection_id' => $connectionId, 'created_at' => $now, 'updated_at' => $now]); + $db->table('roster_scim_users')->insert(['id' => (string) Str::ulid(), 'organization_id' => $organizationId, 'user_id' => $userId, 'external_id' => 'okta-ada', 'created_at' => $now, 'updated_at' => $now]); + $db->table('roster_scim_groups')->insert(['id' => (string) Str::ulid(), 'organization_id' => $organizationId, 'team_id' => $teamId, 'external_id' => 'okta-ops', 'created_at' => $now, 'updated_at' => $now]); + + // They ran in the same batch as the rest of Roster's migrations. + $batch = (int) $db->table('migrations')->max('batch'); + + foreach (LEGACY_SSO_SCIM_MIGRATIONS as $migration) { + $db->table('migrations')->insert(['migration' => $migration, 'batch' => $batch]); + } +} + +beforeEach(function (): void { + // The upgrade runs on a database of its own, outside the suite's shared + // one. Foreign keys are not enforced: SQLite would turn dropping a parent + // table into an implicit delete cascading into the SSO and SCIM rows + // (MySQL and PostgreSQL refuse to drop it instead), and this test is about + // what Roster's migrations themselves do to those tables. + config()->set('database.connections.legacy', [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + 'foreign_key_constraints' => false, + ]); + + // An upgraded install's published config still names the five tables. + foreach (LEGACY_SSO_SCIM_TABLES as $key => $table) { + config()->set('roster.tables.'.$key, $table); + } +}); + +afterEach(function (): void { + DB::setDefaultConnection('testing'); +}); + +it('creates none of the SSO and SCIM tables on a fresh database', function (): void { + legacyMigrate('migrate'); + + expect(legacyHasTable('roster_organizations'))->toBeTrue() + ->and(legacyRows())->toBe([]); +}); + +it('keeps the SSO and SCIM tables and rows of an upgraded install through migrate, rollback and refresh', function (): void { + legacyInstall(); + + $kept = array_fill_keys(LEGACY_SSO_SCIM_TABLES, 1); + + expect(legacyRows())->toBe($kept); + + // The stray migrations rows fail neither migrate nor migrate:status. + legacyMigrate('migrate'); + legacyMigrate('migrate:status'); + + expect(legacyRows())->toBe($kept); + + // Rolling Roster back drops its own tables and leaves the five alone. + legacyMigrate('migrate:rollback'); + + expect(legacyHasTable('roster_organizations'))->toBeFalse() + ->and(legacyRows())->toBe($kept); + + // The full Roster migration set runs on a database holding the five. + legacyMigrate('migrate'); + + expect(legacyHasTable('roster_organizations'))->toBeTrue() + ->and(legacyRows())->toBe($kept); + + legacyMigrate('migrate:refresh'); + + expect(legacyHasTable('roster_organizations'))->toBeTrue() + ->and(legacyRows())->toBe($kept); +}); + +it('runs migrate:fresh on an upgraded install without error, creating no second set of tables', function (): void { + legacyInstall(); + + legacyMigrate('migrate:fresh'); + + expect(legacyHasTable('roster_organizations'))->toBeTrue() + ->and(legacyRows())->toBe([]); +}); + +it('ignores the stray migrations rows of the removed SSO and SCIM migrations', function (): void { + legacyMigrate('migrate'); + + $db = DB::connection('legacy'); + + foreach (LEGACY_SSO_SCIM_MIGRATIONS as $migration) { + $db->table('migrations')->insert(['migration' => $migration, 'batch' => 1]); + } + + legacyMigrate('migrate'); + legacyMigrate('migrate:status'); + + expect($db->table('migrations')->whereIn('migration', LEGACY_SSO_SCIM_MIGRATIONS)->count())->toBe(2) + ->and(legacyRows())->toBe([]); +}); + +it('ships neither removed migration', function (): void { + foreach (LEGACY_SSO_SCIM_MIGRATIONS as $migration) { + expect(glob(dirname(__DIR__, 2).'/database/migrations/{,*/}'.$migration.'.php', GLOB_BRACE))->toBe([]); + } +}); diff --git a/tests/Feature/NoExternalSignInTest.php b/tests/Feature/NoExternalSignInTest.php new file mode 100644 index 0000000..682eae4 --- /dev/null +++ b/tests/Feature/NoExternalSignInTest.php @@ -0,0 +1,81 @@ +> + */ +function noExternalSignInErrors(mixed $email): array +{ + return Validator::make(['email' => $email], ['email' => ['nullable', new NoExternalSignIn]])->errors()->toArray(); +} + +it('fails with the translated message, naming the organization and the url', function (): void { + Roster::requireSignIn(new DomainSignInRequirement); + + expect(noExternalSignInErrors('ada@acme.test')) + ->toBe(['email' => ['Acme Corp requires single sign-on. Sign in at https://idp.acme.test/start']]) + ->and(__('roster::roster.external_sign_in_required', ['organization' => 'Acme Corp', 'url' => 'https://idp.acme.test/start'])) + ->toBe('Acme Corp requires single sign-on. Sign in at https://idp.acme.test/start'); +}); + +it('passes when the requirement answers null for the email', function (): void { + Roster::requireSignIn(new DomainSignInRequirement); + + expect(noExternalSignInErrors('grace@elsewhere.test'))->toBe([]); +}); + +it('passes when no requirement is registered', function (): void { + expect(noExternalSignInErrors('ada@acme.test'))->toBe([]); +}); + +it('passes a super-admin the requirement would claim', function (): void { + grant(user(['email' => 'boss@acme.test']), 'super-admin'); + Roster::requireSignIn(new DomainSignInRequirement); + + expect(noExternalSignInErrors('boss@acme.test'))->toBe([]); +}); + +it('lets a throwing requirement propagate, so the login fails closed', function (): void { + Roster::requireSignIn(new UnreachableSignInRequirement); + + noExternalSignInErrors('ada@acme.test'); +})->throws(RuntimeException::class, 'identity provider unreachable'); + +it('keeps the generic rule in Support, not in a domain', function (): void { + expect(class_exists('RefactorCircus\Roster\Domains\Sso\Rules\NotSsoEnforced'))->toBeFalse() + ->and(new NoExternalSignIn)->toBeInstanceOf(ValidationRule::class) + ->and(__('roster::roster.sso_required'))->toBe('roster::roster.sso_required'); +}); diff --git a/tests/Feature/RemovedSsoScimTest.php b/tests/Feature/RemovedSsoScimTest.php new file mode 100644 index 0000000..509f0aa --- /dev/null +++ b/tests/Feature/RemovedSsoScimTest.php @@ -0,0 +1,332 @@ + $folders + * @param list $skip paths (relative to the package root) to leave out + * @return list + */ +function removedSsoScimHits(array $folders, string $pattern, array $skip = []): array +{ + $root = dirname(__DIR__, 2); + $hits = []; + + foreach ($folders as $folder) { + if (! is_dir($root.'/'.$folder)) { + continue; + } + + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root.'/'.$folder, FilesystemIterator::SKIP_DOTS)) as $file) { + /** @var SplFileInfo $file */ + $path = substr($file->getPathname(), strlen($root) + 1); + + if (array_filter($skip, fn (string $prefix): bool => str_starts_with($path, $prefix)) !== []) { + continue; + } + + foreach (file($file->getPathname()) ?: [] as $number => $line) { + if (preg_match($pattern, $line) === 1) { + $hits[] = $path.':'.($number + 1).': '.trim($line); + } + } + } + } + + return $hits; +} + +/** + * The organization screen as resolved for a request. + */ +function removedSsoScimScreen(TestResponse $response): ResolvedScreen +{ + $resolved = $response->viewData('resolved'); + + expect($resolved)->toBeInstanceOf(ResolvedScreen::class); + + return $resolved; +} + +/** + * Turn authorization on and sign in a user holding these permissions in + * the organization. + * + * @param list $permissions + */ +function removedSsoScimViewer(OrganizationModel $organization, array $permissions): void +{ + config()->set('roster.authorization', true); + $viewer = user(); + + RoleAssignmentModel::query()->create([ + 'role_id' => roleWith($permissions, 'organization')->id, + 'user_id' => $viewer->getKey(), + 'organization_id' => $organization->getKey(), + ]); + + app(Permissions::class)->flush(); + test()->actingAs($viewer); +} + +// Criterion 1: the domains are gone. + +it('has no SSO or SCIM domain folder, provider, factory or MCP trait', function (): void { + $root = dirname(__DIR__, 2); + + expect(is_dir($root.'/src/Domains/Sso'))->toBeFalse() + ->and(is_dir($root.'/src/Domains/Scim'))->toBeFalse() + ->and(is_file($root.'/database/factories/SsoConnectionFactory.php'))->toBeFalse() + ->and(is_file($root.'/src/Mcp/Concerns/DescribesSsoConnection.php'))->toBeFalse() + ->and(class_exists('RefactorCircus\Roster\Domains\Sso\SsoServiceProvider'))->toBeFalse() + ->and(class_exists('RefactorCircus\Roster\Domains\Scim\ScimServiceProvider'))->toBeFalse() + ->and(trait_exists('RefactorCircus\Roster\Mcp\Concerns\DescribesSsoConnection'))->toBeFalse() + ->and(class_exists('RefactorCircus\Roster\Database\Factories\SsoConnectionFactory'))->toBeFalse(); +}); + +it('registers no SSO or SCIM domain provider', function (): void { + $providers = (new ReflectionProperty(DomainServiceProvider::class, 'providers'))->getValue(new DomainServiceProvider(app())); + + expect($providers)->toBeArray()->not->toBeEmpty() + ->and(array_values(preg_grep(REMOVED_SSO_SCIM, (array) $providers) ?: []))->toBe([]) + ->and(array_values(preg_grep(REMOVED_SSO_SCIM, array_keys(app()->getLoadedProviders())) ?: []))->toBe([]); +}); + +it('opens Guardian\'s handover gate: the old SSO connection model is not a loadable class', function (): void { + expect(class_exists('RefactorCircus\Roster\Domains\Sso\Models\SsoConnectionModel'))->toBeFalse(); +}); + +arch('no class in Roster uses the SSO or SCIM domain') + ->expect('RefactorCircus\Roster') + ->not->toUse(['RefactorCircus\Roster\Domains\Sso', 'RefactorCircus\Roster\Domains\Scim']); + +// Criterion 2: the roster.sso / roster.scim registrations are gone. + +it('registers no roster.sso or roster.scim resource', function (): void { + expect(app(Resources::class)->model('roster.sso'))->toBeNull() + ->and(app(Resources::class)->model('roster.scim'))->toBeNull() + ->and(app(Resources::class)->model('roster.organizations'))->not->toBeNull(); +}); + +it('catalogues no roster.sso. or roster.scim. permission', function (): void { + $names = array_keys(app(PermissionCatalogue::class)->all()); + + expect(array_values(array_filter( + $names, + fn (string $name): bool => str_starts_with($name, 'roster.sso.') || str_starts_with($name, 'roster.scim.'), + )))->toBe([]); +}); + +it('denies roster.sso.view to an organization admin who is not a super-admin', function (): void { + config()->set('roster.authorization', true); + $admin = user(); + $acme = organization(attributes: ['name' => 'Acme']); + grant($admin, 'admin', $acme); + + // The admin can use the organization, so the denial is about the prefix. + expect(app(Authorizer::class)->check($admin, 'roster.organizations.update', $acme))->toBeTrue() + ->and(app(Authorizer::class)->check($admin, 'roster.sso.view', $acme))->toBeFalse() + ->and(app(Authorizer::class)->check($admin, 'roster.scim.manage', $acme))->toBeFalse(); +}); + +it('registers no scim membership source', function (): void { + expect(app(MembershipSources::class)->has('scim'))->toBeFalse(); +}); + +// Criterion 5: the SSO and SCIM routes are gone. + +it('has no route named :dataset', function (string $name): void { + expect(Route::has($name))->toBeFalse(); +})->with([ + 'roster.organizations.sso-connections.index', + 'roster.organizations.sso-connections.store', + 'roster.sso-connections.show', + 'roster.sso-connections.update', + 'roster.sso-connections.destroy', + 'roster.users.sso-identities.index', + 'roster.sso-identities.destroy', + 'roster.organizations.scim-tokens.index', + 'roster.organizations.scim-tokens.store', + 'roster.scim-tokens.destroy', + 'roster.sso.discover', + 'roster.sso.start', + 'roster.sso.callback', + 'roster.sso.metadata', + 'roster.sso.link', + 'atrium.roster.sso.store', + 'atrium.roster.sso.show', + 'atrium.roster.sso.update', + 'atrium.roster.sso.destroy', + 'atrium.roster.sso-identities.destroy', + 'atrium.roster.scim-tokens.store', + 'atrium.roster.scim-tokens.revoke', +]); + +it('has no route whose name or URI names SSO or SCIM, named or not', function (): void { + $routes = collect(Route::getRoutes()->getRoutes()); + + // The positive control: Roster's API and Atrium routes are mounted. + expect(Route::has('roster.organizations.members.index'))->toBeTrue() + ->and(Route::has('atrium.roster.organizations.show'))->toBeTrue() + ->and($routes->map(fn (RegisteredRoute $route): string => $route->uri())->filter(fn (string $uri): bool => preg_match(REMOVED_SSO_SCIM, $uri) === 1)->values()->all())->toBe([]) + ->and($routes->map(fn (RegisteredRoute $route): string => (string) $route->getName())->filter(fn (string $name): bool => preg_match(REMOVED_SSO_SCIM, $name) === 1)->values()->all())->toBe([]) + ->and($routes->map(fn (RegisteredRoute $route): string => (string) $route->getName())->filter(fn (string $name): bool => str_starts_with($name, 'roster.scim.'))->values()->all())->toBe([]); +}); + +it('names only the web surface for Roster\'s routes, and no scim one', function (): void { + /** @var array $routes */ + $routes = (new ReflectionProperty(Surface::class, 'routes'))->getValue(app(Surface::class)); + $roster = array_filter($routes, fn (string $prefix): bool => str_starts_with($prefix, 'roster.'), ARRAY_FILTER_USE_KEY); + + expect($roster)->not->toBeEmpty() + ->and(array_values(array_unique($roster)))->toBe(['web']) + ->and($routes)->not->toContain('scim') + ->and(array_values(preg_grep(REMOVED_SSO_SCIM, array_keys($routes)) ?: []))->toBe([]); +}); + +// Criterion 6: the MCP tools are gone. + +it('lists no MCP tool naming SSO or SCIM', function (): void { + $tools = collect(RosterServer::TOOLS); + $names = $tools->map(fn (string $tool): string => app($tool)->name()); + + expect($names)->toContain('list-members-tool') + ->and($names->filter(fn (string $name): bool => preg_match(REMOVED_SSO_SCIM, $name) === 1)->values()->all())->toBe([]) + ->and($tools->filter(fn (string $tool): bool => preg_match(REMOVED_SSO_SCIM, class_basename($tool)) === 1)->values()->all())->toBe([]); +}); + +// Criterion 7: the organization screen loses its sso and scim tabs. + +it('declares exactly members, teams, invitations, roles and settings, with members the default', function (): void { + $this->actingAs(user()); + $organization = organization(attributes: ['name' => 'Acme']); + + $resolved = removedSsoScimScreen($this->get(route('atrium.roster.organizations.show', $organization))->assertOk()); + + expect($resolved->screen->key)->toBe('roster.organization') + ->and(array_map(fn (TabDefinition $tab): string => $tab->key, $resolved->tabs))->toBe(['members', 'teams', 'invitations', 'roles', 'settings']) + ->and(array_map(fn (TabDefinition $tab): string => $tab->icon, $resolved->tabs))->not->toContain('arrow-right-end-on-rectangle')->not->toContain('server-stack') + ->and($resolved->openTab)->toBe('members'); +}); + +it('opens members for ?tab=:dataset, for a viewer holding every organization permission', function (string $tab): void { + $organization = organization(attributes: ['name' => 'Acme']); + removedSsoScimViewer($organization, PermissionModel::query()->pluck('name')->all()); + + $response = $this->get(route('atrium.roster.organizations.show', [$organization, 'tab' => $tab]))->assertOk(); + + expect(removedSsoScimScreen($response)->openTab)->toBe('members'); + + $response->assertDontSee('data-testid="tab-sso"', false) + ->assertDontSee('data-testid="tab-scim"', false) + ->assertSee('data-testid="tab-members"', false); +})->with(['sso', 'scim']); + +it('no longer gates ?tab=sso: a viewer without roster.sso.view gets members', function (): void { + $organization = organization(attributes: ['name' => 'Acme']); + removedSsoScimViewer($organization, ['roster.organizations.view', 'roster.members.view']); + + $response = $this->get(route('atrium.roster.organizations.show', [$organization, 'tab' => 'sso']))->assertOk(); + + expect(removedSsoScimScreen($response)->openTab)->toBe('members'); +}); + +it('has no SSO or SCIM Atrium controller or page', function (): void { + expect(class_exists('RefactorCircus\Roster\Atrium\Http\Controllers\SsoUiController'))->toBeFalse() + ->and(class_exists('RefactorCircus\Roster\Atrium\Http\Controllers\ScimUiController'))->toBeFalse() + ->and(is_dir(dirname(__DIR__, 2).'/resources/views/ui/sso'))->toBeFalse(); +}); + +// Criterion 8: the user overview loses its SSO identities card. + +it('shows the user overview without SSO identities', function (): void { + $this->actingAs(user()); + $target = user(['name' => 'Ada']); + organization($target, ['name' => 'Acme']); + + $this->get(route('atrium.roster.users.show', [$target->getRouteKey(), 'tab' => 'overview'])) + ->assertOk() + ->assertViewHas('memberships') + ->assertViewMissing('ssoIdentities') + ->assertDontSee('unlink-sso-identity', false); +}); + +// Criterion 9: the config is gone. + +it('has no sso or scim config, nor their table keys', function (): void { + expect(config('roster.sso'))->toBeNull() + ->and(config('roster.scim'))->toBeNull() + ->and((array) config('roster.tables'))->toHaveKey('organizations')->not->toHaveKeys(REMOVED_SSO_SCIM_TABLES) + ->and(Tables::DEFAULTS)->toHaveKey('organizations')->not->toHaveKeys(REMOVED_SSO_SCIM_TABLES); + + $config = require dirname(__DIR__, 2).'/config/roster.php'; + + expect($config)->not->toHaveKeys(['sso', 'scim']) + ->and($config['tables'])->not->toHaveKeys(REMOVED_SSO_SCIM_TABLES); +}); + +// Criterion 12: no source names SSO or SCIM. + +it('names SSO or SCIM nowhere in src, config, database, lang, resources or workbench', function (): void { + expect(removedSsoScimHits(['src', 'config', 'database', 'lang', 'resources', 'workbench'], REMOVED_SSO_SCIM))->toBe([]); +}); + +it('catches each form of the names it looks for, but not other words', function (string $text, bool $caught): void { + expect(preg_match(REMOVED_SSO_SCIM, $text) === 1)->toBe($caught); +})->with([ + 'snake_case' => ['sso_connections', true], + 'kebab-case' => ['scim-tokens', true], + 'a leading word' => ['sso is on', true], + 'camelCase' => ['ssoIdentities', true], + 'PascalCase' => ['ScimTokenModel', true], + 'an embedded PascalCase' => ['NotSsoEnforced', true], + 'upper case' => ['SSO and SCIM', true], + 'a dotted prefix' => ['roster.scim.users', true], + 'association' => ['association', false], + 'an upper-case run' => ['ASSOCIATE', false], +]); + +// Criterion 11: no SSO vendor library is referenced. + +it('references no SSO vendor library in tests, workbench, src, config or resources', function (): void { + $pattern = '/'.implode('|', array_map(fn (string $name): string => preg_quote($name, '/'), ['Laravel\\Socialite', 'SocialiteProviders', 'Firebase\\JWT'])).'/'; + + expect(removedSsoScimHits( + ['tests', 'workbench', 'src', 'config', 'resources'], + $pattern, + ['tests/Feature/RemovedSsoScimTest.php', 'tests/Browser/Screenshots', 'tests/Browser/Traces'], + ))->toBe([]); +}); diff --git a/tests/Feature/Ui/SharedTabBarTest.php b/tests/Feature/Ui/SharedTabBarTest.php index 1f05f06..18758ff 100644 --- a/tests/Feature/Ui/SharedTabBarTest.php +++ b/tests/Feature/Ui/SharedTabBarTest.php @@ -77,7 +77,7 @@ function sharedTabBarCurrent(TestResponse $response): array $registered = ['acme.orders', 'acme.invoices']; - $builtIn = ['members', 'teams', 'invitations', 'roles', 'sso', 'scim', 'settings']; + $builtIn = ['members', 'teams', 'invitations', 'roles', 'settings']; expect(array_map(strval(...), array_keys(array_diff_key($organization, array_flip($builtIn)))))->toBe($registered) ->and(array_map(strval(...), array_keys(array_diff_key($user, ['overview' => true]))))->toBe($registered); diff --git a/tests/Fixtures/legacy_sso_scim_schema.php b/tests/Fixtures/legacy_sso_scim_schema.php new file mode 100644 index 0000000..052b175 --- /dev/null +++ b/tests/Fixtures/legacy_sso_scim_schema.php @@ -0,0 +1,106 @@ + new class extends Migration + { + public function up(): void + { + Schema::create(Tables::name('sso_connections'), function (Blueprint $table): void { + $table->ulid('id')->primary(); + $table->foreignUlid('organization_id')->constrained(Tables::name('organizations'))->cascadeOnDelete(); + $table->string('name'); + $table->string('slug')->unique(); + $table->string('protocol', 8); + // Encrypted JSON: issuer, client id and secret, or SAML IdP details. + $table->text('config'); + $table->boolean('jit')->default(true); + $table->boolean('enforced')->default(false); + $table->boolean('enabled')->default(true); + $table->timestamps(); + }); + + Schema::create(Tables::name('sso_identities'), function (Blueprint $table): void { + $table->ulid('id')->primary(); + $table->foreignUlid('connection_id')->constrained(Tables::name('sso_connections'))->cascadeOnDelete(); + UserKey::column($table, 'user_id')->index(); + $table->string('subject'); + $table->string('email')->nullable(); + $table->timestamp('last_login_at')->nullable(); + $table->timestamps(); + + $table->unique(['connection_id', 'subject']); + }); + } + + public function down(): void + { + Schema::dropIfExists(Tables::name('sso_identities')); + Schema::dropIfExists(Tables::name('sso_connections')); + } + }, + + 'scim' => new class extends Migration + { + public function up(): void + { + Schema::create(Tables::name('scim_tokens'), function (Blueprint $table): void { + $table->ulid('id')->primary(); + $table->foreignUlid('organization_id')->constrained(Tables::name('organizations'))->cascadeOnDelete(); + $table->string('name'); + $table->string('token_hash', 64)->unique(); + $table->foreignUlid('sso_connection_id')->nullable()->constrained(Tables::name('sso_connections'))->nullOnDelete(); + UserKey::column($table, 'created_by')->nullable(); + $table->timestamp('last_used_at')->nullable(); + $table->timestamp('expires_at')->nullable(); + $table->timestamp('revoked_at')->nullable(); + $table->timestamps(); + }); + + Schema::create(Tables::name('scim_users'), function (Blueprint $table): void { + // Its id is the SCIM resource id the identity provider sees. + $table->ulid('id')->primary(); + $table->foreignUlid('organization_id')->constrained(Tables::name('organizations'))->cascadeOnDelete(); + UserKey::column($table, 'user_id'); + $table->string('external_id')->nullable(); + $table->boolean('created_by_scim')->default(false); + $table->boolean('deactivated_by_scim')->default(false); + $table->boolean('active')->default(true); + $table->timestamps(); + + $table->unique(['organization_id', 'user_id']); + $table->index(['organization_id', 'external_id']); + }); + + Schema::create(Tables::name('scim_groups'), function (Blueprint $table): void { + $table->ulid('id')->primary(); + $table->foreignUlid('organization_id')->constrained(Tables::name('organizations'))->cascadeOnDelete(); + $table->foreignUlid('team_id')->unique()->constrained(Tables::name('teams'))->cascadeOnDelete(); + $table->string('external_id')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists(Tables::name('scim_groups')); + Schema::dropIfExists(Tables::name('scim_users')); + Schema::dropIfExists(Tables::name('scim_tokens')); + } + }, +]; From d18f2e8f539cfd33c299cd5eec96b90bdf0df208 Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Fri, 30 Oct 2026 02:58:50 -0400 Subject: [PATCH 09/17] 2026-10-29-2038-remove-sso-and-scim: group 1 Remove SSO and SCIM code, surfaces, config and migrations Co-Authored-By: Claude Opus 5.5 --- .../agent/specs/2026-10-29-2038-remove-sso-and-scim/build.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/build.md b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/build.md index 6fd51a2..2587913 100644 --- a/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/build.md +++ b/docs/agent/specs/2026-10-29-2038-remove-sso-and-scim/build.md @@ -31,3 +31,8 @@ Remove SSO and SCIM code, surfaces, config and migrations (criteria 1 to 13). - `Authorizer::check()` sends an unregistered prefix to the raw permission check (`permits()`), not a flat deny. On a fresh install the admin holds no `roster.sso.view`, so the check denies, which is what the test pins. On an upgraded install without Guardian, the kept legacy grant would still pass a raw `roster.sso.view` check. Nothing in Roster asks for it any more. - `tests/Unit` is not a PHPUnit test suite in `phpunit.xml.dist`, and `tests/Pest.php` binds no test case to it, so its files (including the edited `MembershipSourcesTest` and `PermissionCatalogueTest`, and the seams' `SignInRequirementsTest`) do not run in `composer test`. This predates this spec and is left unchanged. - For group 2: criterion 12 scans `resources/`, including the Boost skill, so `SKILL.md` must keep its Guardian section free of the criterion 12 tokens (the current text says "Single sign-on and provisioning"). + +### Retry + +- Re-checked the committed work against tasks 1.1 to 1.3; nothing was missing, so no code or test changed. The criterion 12 regex over `src/`, `config/`, `database/`, `lang/`, `resources/` and `workbench/` has no hits. The vendor-namespace scan hits only `RemovedSsoScimTest`'s own needles, which the test skips. The SSO/SCIM names left under `tests/` are negative assertions, the kept-permission fixture in `PermissionSyncTest` and the ArchTest pattern self-checks. +- `composer.local.json` is git-ignored and was mirrored by hand (Guardian suggested, no Socialite/JWT packages); it was not regenerated and `composer update` was not run. It still predates `adopt-atrium-screen-registry` (Atrium in `require`, no `conflict`), which is outside this spec's change; `ComposerTest` reads `composer.json`, where the `conflict` is exactly `<0.1.0`. From 758a771432161db8456e24bf591ae8248d098f3c Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Fri, 30 Oct 2026 03:01:56 -0400 Subject: [PATCH 10/17] 2026-10-29-2038-remove-sso-and-scim: group 2 Upgrade docs and gate Task 2.1: DocsTest for the Guardian CHANGELOG entry, README section, Boost skill, tab lists, Extending Roster and the agent guides. Co-Authored-By: Claude Opus 5.5 --- tests/Feature/DocsTest.php | 218 +++++++++++++++++++++++++++++++++++++ 1 file changed, 218 insertions(+) diff --git a/tests/Feature/DocsTest.php b/tests/Feature/DocsTest.php index 30f9b1b..2657a0d 100644 --- a/tests/Feature/DocsTest.php +++ b/tests/Feature/DocsTest.php @@ -145,6 +145,224 @@ function unreleasedChangelog(): string ->toContain('roster-views'); }); +/** + * The bold title of the CHANGELOG entry, and the README section, that tell + * apps SSO and SCIM moved to refactor-circus/guardian. + */ +const GUARDIAN_ENTRY = 'SSO and SCIM moved to refactor-circus/guardian'; + +const GUARDIAN_SECTION = 'SSO and SCIM (refactor-circus/guardian)'; + +/** + * The fail-open warning both open with (D-017). + */ +const FAIL_OPEN_WARNING = '**Without Guardian, organizations that enforce SSO accept password sign-in.**'; + +/** + * The criterion 12 regex, verbatim: any SSO or SCIM token. + */ +const DOCS_SSO_SCIM = '/(? + */ +function numberedSteps(string $text): array +{ + preg_match_all('/^\s*(\d+)\.\s+(.*)$/m', $text, $matches, PREG_SET_ORDER); + + return array_map(fn (array $match): array => [(int) $match[1], $match[2]], $matches); +} + +/** + * A markdown text without the section under the heading $title. + */ +function withoutSection(string $markdown, string $title): string +{ + $section = markdownSection($markdown, $title); + + return $section === null || $section === '' ? $markdown : str_replace($section, '', $markdown); +} + +it('finds a changelog entry by its bold title, up to the next top-level bullet', function (): void { + $markdown = <<<'MD' + - **Other.** Not this one. + - **Moved away.** + + **Warning.** + + 1. First + 2. **Second** + - **Next.** Outside. + MD; + + $entry = (string) changelogEntry($markdown, 'Moved away'); + + expect(firstLine($entry))->toBe('**Warning.**') + ->and(numberedSteps($entry))->toBe([[1, 'First'], [2, '**Second**']]) + ->and($entry)->not->toContain('Outside')->not->toContain('Not this one') + ->and(changelogEntry($markdown, 'Missing'))->toBeNull() + ->and(withoutSection("## A\nkeep\n## B\ndrop\n## C\nkeep too", 'B'))->not->toContain('drop')->toContain('keep too'); +}); + +it('writes the Guardian upgrade entry in the Unreleased Breaking section of the CHANGELOG', function (): void { + $entry = changelogEntry((string) markdownSection(unreleasedChangelog(), 'Breaking'), GUARDIAN_ENTRY); + + expect($entry)->not->toBeNull('the Unreleased Breaking section has no "'.GUARDIAN_ENTRY.'" entry') + ->and(firstLine((string) $entry))->toStartWith(FAIL_OPEN_WARNING); + + foreach ([ + 'refactor-circus/guardian', 'guardian.sso', '?tab=sso', '?tab=scim', 'roster.sso.', 'create_roster_sso_tables', + 'guardian:upgrade-from-roster', 'NoExternalSignIn', + // What was removed. + 'NotSsoEnforced', 'MembershipSource', 'laravel/socialite', 'roster.tables', + // The behaviour without Guardian. + '404', 'roster:sync-permissions', '`scim`', + ] as $needle) { + expect($entry)->toContain($needle); + } +}); + +it('gives the six upgrade steps in order, with step 2 bold', function (): void { + $steps = numberedSteps((string) changelogEntry((string) markdownSection(unreleasedChangelog(), 'Breaking'), GUARDIAN_ENTRY)); + + expect(array_column($steps, 0))->toBe([1, 2, 3, 4, 5, 6]); + + [$install, $published, $migrate, $config, $names, $rule] = array_column($steps, 1); + + expect($install)->toContain('refactor-circus/guardian')->toContain('same deploy') + ->and($published)->toStartWith('**Before running any migrate command**') + ->toContain('create_roster_sso_tables')->toContain('create_roster_scim_tables')->toContain('down()') + ->and($migrate)->toContain('roster:sync-permissions')->toContain('guardian.sso.*') + ->toContain('**If you installed Guardian before this Roster version**')->toContain('php artisan guardian:upgrade-from-roster') + ->and($config)->toContain('roster.sso.*')->toContain('guardian.*')->toContain('scim/v2') + ->and($names)->toContain('RefactorCircus\Roster\Domains\Sso')->toContain('@rosterCan') + ->and($rule)->toContain('NotSsoEnforced')->toContain('RefactorCircus\Roster\Support\Rules\NoExternalSignIn')->toContain('external_sign_in_required'); +}); + +it('replaces the README single sign-on and SCIM sections with one Guardian section', function (): void { + $readme = readme(); + $section = markdownSection($readme, GUARDIAN_SECTION); + + expect($section)->not->toBeNull('the README has no "'.GUARDIAN_SECTION.'" heading') + ->and(firstLine((string) $section))->toStartWith(FAIL_OPEN_WARNING) + ->and($section)->toContain('https://github.com/Refactor-Circus/Guardian') + ->toContain('guardian:upgrade-from-roster') + ->toContain('create_roster_sso_tables') + ->toContain('roster:sync-permissions') + ->toContain('NoExternalSignIn') + ->and(markdownSection($readme, 'Single sign-on'))->toBeNull('the README still has a Single sign-on heading') + ->and(markdownSection($readme, 'Requiring SSO'))->toBeNull('the README still has a Requiring SSO heading') + ->and(markdownSection($readme, 'SCIM provisioning'))->toBeNull('the README still has a SCIM provisioning heading'); +}); + +it('points the Boost skill at Guardian for single sign-on and provisioning', function (): void { + $section = markdownSection(packageFile(BOOST_SKILL), 'Single sign-on and provisioning'); + + expect($section)->not->toBeNull('the Boost skill has no Single sign-on and provisioning heading') + ->toContain('refactor-circus/guardian') + ->toContain('guardian:upgrade-from-roster') + ->toContain('NoExternalSignIn'); +}); + +it('names no removed SSO class outside the Guardian section', function (string $file): void { + $outside = withoutSection(packageFile($file), GUARDIAN_SECTION); + + expect($outside)->not->toContain('NotSsoEnforced') + ->not->toContain('SsoConnectionModel') + ->not->toContain('Domains\Sso'); +})->with([ + 'README' => 'README.md', + 'Boost skill' => BOOST_SKILL, +]); + +it('documents no removed SSO or SCIM surface outside the Guardian section of the README', function (): void { + $outside = withoutSection(readme(), GUARDIAN_SECTION); + + foreach (['sso-connections', 'sso-identit', 'scim-tokens', 'scim_token', 'roster.sso', 'roster.scim', 'SsoConnection', 'ScimToken', 'scim/v2', 'scim.php'] as $needle) { + expect($outside)->not->toContain($needle); + } +}); + +it('lists no sso or scim tab', function (string $file, string $title): void { + $section = markdownSection(packageFile($file), $title); + + expect($section)->not->toBeNull("{$file} has no {$title} heading") + ->and(preg_match('/`(?:sso|scim)`|\*\*(?:SSO|SCIM)\*\* tab/', (string) $section))->toBe(0); +})->with([ + 'README dashboard' => ['README.md', 'Atrium dashboard'], + 'README screen extensions' => ['README.md', 'Screen extensions'], + 'Boost skill screen extensions' => [BOOST_SKILL, 'Screen extensions'], +]); + +it('no longer cites Roster SSO or SCIM as users of the extension seams', function (string $file): void { + $section = (string) markdownSection(packageFile($file), 'Extending Roster'); + + expect(array_values(preg_grep(DOCS_SSO_SCIM, preg_split('/\R/', $section) ?: []) ?: []))->toBe([]) + ->and($section)->toContain('NoExternalSignIn') + ->toContain('a registered sign-in requirement'); +})->with([ + 'README' => 'README.md', + 'Boost skill' => BOOST_SKILL, +]); + +it('keeps the agent guides free of SSO and SCIM', function (string $file): void { + $guide = packageFile($file); + + expect(array_values(preg_grep(DOCS_SSO_SCIM, preg_split('/\R/', $guide) ?: []) ?: []))->toBe([]) + ->and($guide)->not->toContain('scim.php'); +})->with(['CLAUDE.md', 'AGENTS.md']); + /** * The README's promise about built-in roles and registered permissions. */ From a56f55773ce2156eb282896f1b21e02934a156bc Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Fri, 30 Oct 2026 03:05:42 -0400 Subject: [PATCH 11/17] 2026-10-29-2038-remove-sso-and-scim: group 2 Upgrade docs and gate Task 2.2: CHANGELOG Breaking entry for the move to refactor-circus/guardian, README Guardian section, Extending Roster, tab lists, Boost skill, AGENTS.md (CLAUDE.md), roadmap note and the local authorization standard; ringside sync rerun. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 10 +- CHANGELOG.md | 20 +++ README.md | 147 +++++------------- docs/agent/product/roadmap.md | 2 + docs/agent/standards/http/authorization.md | 8 +- .../boost/skills/roster-development/SKILL.md | 9 +- 6 files changed, 77 insertions(+), 119 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 26bfb57..921e997 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,17 +13,17 @@ This repository is a Laravel package. Keep the package focused, idiomatic, and e ## Architecture - Roster stands on `refactor-circus/keystone`, the suite's shared runtime. `RosterServiceProvider` extends `RefactorCircus\Keystone\Support\PackageServiceProvider`, describes the package in `definition()` (key `roster`, `RosterServer`, authorization on by default, history guarded by `roster.audit.view`), calls `registerPackage()` right after merging config, and boots the MCP server, Cortex and the shared history route (`GET {prefix}/history`, `roster.history.index`) through the base helpers. Action events implement `RefactorCircus\Keystone\Contracts\ActionStartingEvent` / `ActionFinishedEvent`; finished events wait for the surrounding transaction to commit. -- Code lives in domain modules under `src/Domains/{Domain}` (User, Organization, Team, Invitation, Role, Permission, Impersonation, Sso, Scim, Transfer), mirroring the `mono` domain-module standard. Each domain has a `{Domain}ServiceProvider` (extending `RefactorCircus\Keystone\Support\ServiceProvider`) registered by `src/Domains/DomainServiceProvider.php`, its JSON API routes in `routes.php` (loaded with `loadApiRoutesFrom()`), any browser routes in `web.php` (`scim.php` for the SCIM protocol), and only the subdirectories it uses. +- Code lives in domain modules under `src/Domains/{Domain}` (User, Organization, Team, Invitation, Role, Permission, Impersonation, Transfer), mirroring the `mono` domain-module standard. Each domain has a `{Domain}ServiceProvider` (extending `RefactorCircus\Keystone\Support\ServiceProvider`) registered by `src/Domains/DomainServiceProvider.php`, its JSON API routes in `routes.php` (loaded with `loadApiRoutesFrom()`), any browser routes in `web.php`, and only the subdirectories it uses. Single sign-on and provisioning are not Roster's: refactor-circus/guardian adds them through the extension seams, and Roster's code never names Guardian. - Action input is a `final readonly` `{Action}Data` in the domain's `Data/` (on `RefactorCircus\Keystone\Data\Data`), never an array: fields are promoted constructor properties (camelCase of the input keys; enums for enum values; `T|Missing = new Missing` for partial updates), `rules()` lives on the Data (with any context args), and the starting/finished events that took input carry the Data (the status events carry just the reason). HTTP and MCP requests validate once: their `rules()` return the identifier rules plus `XData::rules(...context)` (identifiers first, so they win), and `persist()`/`handle()` build with `XData::fromValidated($this->validated() / $validated)` - never `XData::from()` in a request (ArchTest). Atrium controllers and other untrusted input use `XData::from($request->all(), ...context)`, which validates; code that vouches for its values uses `new XData(...)`. `tests/ArchTest.php` rejects array input on `execute()`. - API resources extend `RefactorCircus\Keystone\Http\Resources\JsonResource` and declare `schema(JsonSchema $schema)` next to `toArray()` (always-present fields `required()`, conditional ones not, `nullable()`, enum values listed; nullable enums include `null`). MCP requests answer with `(new XResource($m))->additional([...])->toStructuredResponse()` / `XResource::collection($page)->toStructuredResponse()`, and each tool declares `outputSchema()` as `XResource::structuredSchema($schema)` / `collectionSchema($schema)` plus its extra keys. `mcpTool()` in tests checks every structured answer against the tool's schema with Keystone's `Testing\StructuredSchema`, and `tests/Feature/Mcp/OutputSchemaTest.php` requires the declaration. - Models use Keystone's `DispatchesModelEvents` (one `{Entity}{Hook}Event` per Eloquent hook, soft-delete hooks only on soft-deleting models) and resolve their table with `getTable()` from `Support\Tables` (`roster.tables`, on Keystone's `Database\Tables`); migrations, pivots, `Rule::unique`/`exists` (by model class) and joins use the same keys, never literal `roster_*` names (`tests/ArchTest.php` checks with `Arch::literalTableNames()`, and that every model has a policy, in `roster.policies` or Gate-registered by its domain provider, with `Arch::modelsWithoutPolicies()`). Every Action and Impex flow step dispatches a starting and a finished event, the starting one before and the finished one after a `DB::transaction()` that holds all of its writes (side effects that must not survive a rollback - Impex signals, jobs, mail - go after it or `afterCommit`). `tests/ArchTest.php` checks all three with Keystone's `Testing\Arch` (`actionEventGaps()`, `writesOutsideTransactions()` and `modelEventGaps()` over every model); `parityGaps()` uses `Testing\Parity`, and `mcpTool()` is `Testing\McpTools::call()`. - Models are named `{Entity}Model`; their pre-domain class names (`RefactorCircus\Roster\Models\{Entity}`) are kept as morph aliases in each domain provider, so stored subject types and other stored values keep the same string. -- Authorization: `Http\Request` and `Mcp\Request` extend Keystone's request bases and use `Support\Concerns\AuthorizesWithRoster`, whose `authorize()` checks the request's `ability()`, `scope()` and `self()` through `Domains\Permission\Services\Authorizer` (Keystone's base answers guests 401). The domain request bases carry the defaults: organization requests are scoped to `organization()`, each MCP base's `rules()` returns its identifier rules (`userRules()`, `organizationRules()`, `teamRules()`, `roleRules()`, `connectionRules()`, `transferRules()`), and the User/Organization bases find deleted records with `trashedUser()` / `trashedOrganization()`; a request only overrides what differs. `Authorizer::check()` refuses impersonation-blocked permissions, then sends `{prefix}.{verb}` to the Gate policy of the model registered for the prefix (everything before the last dot) in the `Domains\Permission\Services\Resources` singleton (method = camel-cased verb, arguments `[ModelClass, $scope, $self]`); an unregistered prefix is denied, and a package resource whose model has no policy throws. `Authorizer::RESOURCES` holds only the six core resources, registered as `roster.*` by `PermissionServiceProvider::register()`; the SSO and SCIM providers register `roster.sso` / `roster.scim`, their permissions (`PermissionCatalogue`, merged into `BuiltInRoles::sync()`) and their models' Gate policies themselves in `boot()`, through the `@internal` `rosterResource()` / `rosterPermission()`. Other packages use `resource()` / `permission()`, which refuse `roster.*`. The bundled core policies (`Domains/{Domain}/Policies`, on `Support\Policies\Policy`, registered from `roster.policies` by `registerPolicies()`, which lists only core models) answer with `Authorizer::permits()`, the raw permission check. Every model has a policy. `Authorizer::check()` answers are remembered for the request and dropped whenever `Permissions` forgets anything (`generation()`) or a resource is registered (`Resources::generation()`); policies asked with a record get its organization/team from `Authorizer::parentOf()`. Writes that change one user's access call `Permissions::flushUser()`, not `flush()`; `roster.permission_cache` optionally keeps permission names and grants in the cache store, cleared by the same listener. MCP tools extend `RefactorCircus\Keystone\Mcp\Tool`; `RosterServer` extends `RefactorCircus\Keystone\Mcp\Server` and lists `Mcp\Tools\ListRosterHistoryTool`. -- Roster has no audit code beyond its Keen integration, and that only runs while Roster audits: Keystone's `Package::audits()` (refactor-circus/keen installed and `roster.audit.enabled` on; `Roster::auditing()` asks it). Then, once every provider has booted, `Support\Audit` registers what Roster knows on Keystone's `AuditHooks` (labels, snapshot extras - profile fields, role permissions, organization domains, assignment slugs - the subject picker and organization scope for Roster's events, the impersonator/transfer context for every entry, and the password column's redaction). At the same moment the SCIM domain provider registers its own `AuditHooks::context()` closure adding `scim_token` to Roster's entries only (it checks `PackageRegistry::for($event)?->key === 'roster'` itself, catches and `report()`s any throw, and returns `[]`). `viewAuditLog` is defined as global `roster.audit.view` unless the app defines it. Otherwise Keen ignores Roster's events, the history route answers 404, the history tool is not offered, and Atrium shows no history. Never add audit tables, writers or audit APIs to Roster. `RosterServiceProvider` names the `scim` and `web` route surfaces on Keystone's `Surface` either way. +- Authorization: `Http\Request` and `Mcp\Request` extend Keystone's request bases and use `Support\Concerns\AuthorizesWithRoster`, whose `authorize()` checks the request's `ability()`, `scope()` and `self()` through `Domains\Permission\Services\Authorizer` (Keystone's base answers guests 401). The domain request bases carry the defaults: organization requests are scoped to `organization()`, each MCP base's `rules()` returns its identifier rules (`userRules()`, `organizationRules()`, `teamRules()`, `roleRules()`, `transferRules()`), and the User/Organization bases find deleted records with `trashedUser()` / `trashedOrganization()`; a request only overrides what differs. `Authorizer::check()` refuses impersonation-blocked permissions, then sends `{prefix}.{verb}` to the Gate policy of the model registered for the prefix (everything before the last dot) in the `Domains\Permission\Services\Resources` singleton (method = camel-cased verb, arguments `[ModelClass, $scope, $self]`); an unregistered prefix is denied, and a package resource whose model has no policy throws. `Authorizer::RESOURCES` holds only the six core resources, registered as `roster.*` by `PermissionServiceProvider::register()` through the `@internal` `rosterResource()` (core permissions go through the `@internal` `rosterPermission()`). Other packages register their resources, permissions (`PermissionCatalogue`, merged into `BuiltInRoles::sync()`) and their models' Gate policies themselves in `boot()`, through `resource()` / `permission()`, which refuse `roster.*`; a system permission nothing registers any more is reported by `roster:sync-permissions` and kept. The bundled core policies (`Domains/{Domain}/Policies`, on `Support\Policies\Policy`, registered from `roster.policies` by `registerPolicies()`, which lists only core models) answer with `Authorizer::permits()`, the raw permission check. Every model has a policy. `Authorizer::check()` answers are remembered for the request and dropped whenever `Permissions` forgets anything (`generation()`) or a resource is registered (`Resources::generation()`); policies asked with a record get its organization/team from `Authorizer::parentOf()`. Writes that change one user's access call `Permissions::flushUser()`, not `flush()`; `roster.permission_cache` optionally keeps permission names and grants in the cache store, cleared by the same listener. MCP tools extend `RefactorCircus\Keystone\Mcp\Tool`; `RosterServer` extends `RefactorCircus\Keystone\Mcp\Server` and lists `Mcp\Tools\ListRosterHistoryTool`. +- Roster has no audit code beyond its Keen integration, and that only runs while Roster audits: Keystone's `Package::audits()` (refactor-circus/keen installed and `roster.audit.enabled` on; `Roster::auditing()` asks it). Then, once every provider has booted, `Support\Audit` registers what Roster knows on Keystone's `AuditHooks` (labels, snapshot extras - profile fields, role permissions, organization domains, assignment slugs - the subject picker and organization scope for Roster's events, the impersonator/transfer context for every entry, and the password column's redaction). Other packages add their own context with an `AuditHooks::context()` closure for Roster's entries only (it checks `PackageRegistry::for($event)?->key === 'roster'` itself, catches and `report()`s any throw, and returns `[]`). `viewAuditLog` is defined as global `roster.audit.view` unless the app defines it. Otherwise Keen ignores Roster's events, the history route answers 404, the history tool is not offered, and Atrium shows no history. Never add audit tables, writers or audit APIs to Roster. `RosterServiceProvider` names the `web` route surface on Keystone's `Surface` either way. - Atrium owns every component and style. Roster ships no stylesheet and no Blade component namespace: views use `x-atrium::*` components and the utilities safelisted in Atrium's stylesheet only, with no `