Proposal: Identity Layer for Single Sign-On and User Provisioning #435
caseysoftware
started this conversation in
Ideas / Feature Requests
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Status: Draft v1 (proposal) · Milestone: web2project v6.0 (Phases 0–2), 6.x after · Baseline:
dev-5.0.0@179b4eaf(5.0.0-rc1)Related issues: #458 (Phase 0), #459 (Phase 1), #460 (Phase 2), #461 (Phase 3), #462 (Phase 4). Fixes that land before Phase 0: #436, #437, #439, #440, #441, #442, #444, #445; fixed as part of Phase 0: #438, #443. Open questions: #446, #447, #448, #449, #450, #451, #453, #455, #456.
Related proposal: Pluggable File Backend proposal (#404), which shares the PHP 8.2 baseline, the registry/driver pattern and the secret store (#413).
1. Goals and non-goals
Goals
Non-goals
2. Current state (
dev-5.0.0@179b4eaf)Authentication
getAuth($mode)inincludes/main_functions.php(L424) picks one authenticator from theauth_methodconfig:w2p_Authenticators_SQL,_LDAPor_PostNuke. Only one method can be active at a time.authenticate($username, $password)+userId(). A redirect-based protocol (OIDC, SAML) doesn't fit it.CAppUI::login()(L790) mixes four jobs: checking the login method, sanitizing the username ([^A-Za-z0-9._@-]stripped), authenticating, and establishing the session (ACLcheckLogin, loading user/contact fields, prefs, locale).index.phpL111–127 then callsregisterLogin()andaddHistory().fileviewer.phphas its own copy of the flow.w2p_Authenticators_LDAPdoes JIT provisioning (createsqluser()): it creates a contact from inetOrgPerson attributes and a user with no role, so the account stays inactive until an admin assigns one. It copies the directory password into the local hash. It has no group→role mapping and never deprovisions. It only works when public self-registration (activate_external_user_creation) is on, becauseCUser::canCreate()(L150) gates "externally created" users on that flag (LDAP auto-provisioning only works when public self-registration is on, which is the default #437). When creating the local user fails, it still reports success (LDAP login reports success when creating the local user fails #440).Identity data
users:user_id,user_contact,user_username(indexed but not unique,users.user_usernamehas no unique index #438),user_password(bcrypt, legacy MD5 upgraded on login),user_type,user_parent,user_department,user_company,user_signature. There is no status, external ID or source column.contactsrow (user_contact). User lists and permission checks join on it.system/login(w2p_Extensions_Permissions::checkLogin(),isUserPermitted()). To disable a user today, you remove their roles, and you lose the roles in the process.Sessions and side doors
w2p_System_Session: native PHP sessions or a DB handler (session_handling = app).session_userstores the access-log id, not the user id.Secure,HttpOnlyorSameSite.CAppUI::redirect()appends the raw session ID to every redirect URL. (All three fixed ondev-5.0.0:e445eefa,3d68dea5,c8b01906.) HTTPS behind a TLS-terminating proxy isn't detected, so the cookie isn'tSecurethere (HTTPS behind a reverse proxy isn't detected (X-Forwarded-Protoignored) #444), and the session cleanup cron can delete a just-logged-in session (Session cleanup cron can delete a session that has just logged in #445).calendar.php(guessable feed token fromuser_feeds; it doesn't check whether the user can still log in, Calendar feed tokens are guessable and keep working after a user loses access #436),fileviewer.php(its own login),newuser.php/createuser.php(self-registration, on by default), and lost password (sendNewPass(); working again sincec28135bd, but it still resets the password immediately, Lost password replaces the password immediately instead of sending a reset link #443).ldap_search_pass) are stored in plain text, andsystemconfig.phprenders them back into the page (System Configuration renders stored passwords back into the page #439).3. Recommendation
Make web2project a standards-based relying party / service provider, with one provisioning pipeline that every source feeds.
Why this order. OIDC is the modern default, and every major cloud IdP supports it with less configuration than SAML. JIT makes OIDC useful on day one. SCIM comes next because timely deprovisioning is what IT and auditors (SOC 2, ISO 27001 access reviews) actually require, and JIT can't deprovision. SAML is third because most IdPs that offer SAML also offer OIDC. Move it up if a target organization (universities, ADFS shops) needs it.
4. Architecture
Split the work that
CAppUI::login()does today into three steps, and add one shared provisioning service.4.1 New classes
Classes follow the existing
classes/w2p/<Dir>/<Name>.class.phpautoload convention.w2p_Interfaces_PasswordAuthenticatorauthenticate(string $user, string $pass): ?w2p_Auth_Identityw2p_Interfaces_FederatedProviderbeginLogin(string $returnTo): never(redirect),handleCallback(array $request): w2p_Auth_Identity,logoutUrl(?string $idTokenHint): ?string,describe()(admin form schema),healthCheck()w2p_Auth_IdentityemailVerified, given/family/display name, groups, raw claims, auth timew2p_Auth_ProviderRegistryidentity_providersrows and builds providers by type (same pattern asw2p_Storage_Registry)w2p_Auth_Provider_Oidcw2p_Auth_Provider_Samlw2p_Auth_Provider_Sql,w2p_Auth_Provider_Ldapw2p_Authenticators_SQL/_LDAP; LDAP stops creating users itself and hands off to the resolverw2p_Auth_Provider_TrustedHeaderREMOTE_USERor a configured header, accepted only from configured proxy IPs (Phase 4)w2p_Auth_AccountResolveruser_id: linked identity, then link policy, then JIT, else rejectw2p_Auth_SessionEstablisherCAppUI::login(), plussession_regenerate_id(true), auth epoch,user_last_loginw2p_Auth_Controllerauth.php(routes via PATH_INFO, so no rewrite rules needed)w2p_Provisioning_Servicecreate,update,deactivate,reactivate,syncGroups; wrapsCUser,CContactand permissions in a system context, so it doesn't depend onactivate_external_user_creationw2p_Provisioning_AttributeMapperw2p_Provisioning_RoleMapperw2p_Scim_Server+w2p_Scim_UsersResource,w2p_Scim_GroupsResource,w2p_Scim_Filter,w2p_Scim_Patch,w2p_Scim_Error,w2p_Scim_TokenStorescim.php(Phase 2)w2p_Security_SecretStoreW2P_APP_KEYfromconfig.phpor env) and resolvesenv:NAMEreferences. Shared with the file-backend spec (#413).w2p_Security_RateLimiter4.2 Components modified
classes/w2p/Core/CAppUI.class.phplogin()becomes a thin wrapper: password authenticator → resolver →SessionEstablisher.redirect()stops appending the session ID. Addlogout()(the current method is a deprecated stub) that ends the local session and returns the IdP logout URL.doLogin()unchanged.index.phpuser_statusanduser_auth_epochagainst the session (one indexed query, or cached for N seconds), so a disabled user is cut off even with PHP-native sessions. The login page lists enabled providers.includes/main_functions.phpgetAuth()becomes a deprecated shim over the registry for one release.w2p_logout_requested()unchanged.classes/w2p/Authenticators/*SQLandLDAPbecome shims over the new providers for one release. RemovePostNuke(deprecated since 3.0).classes/w2p/System/Session.class.phpSecure(when HTTPS),HttpOnly,SameSite=Lax(Lax is required so the IdP's top-level redirect back carries the cookie; SAML POST to ACS uses a short-lived state cookie withSameSite=None; Secure).session.use_strict_mode=1. AdddestroyForUser($userId)(viauser_access_log) for the DB handler.modules/users/users.class.php(CUser)isValid()allows SSO-only users with no usable password.isActive()checksuser_statusas well as roles.generateToken()usesrandom_bytes().getIdByToken()returns nothing for disabled users. FixgetIdByContactId().modules/contacts/contacts.class.php(CContact)classes/w2p/Extensions/Permissions.class.phpinsertUserRole()/deleteUserRole()go throughRoleMapperso grants record their source.checkLogin()also requiresuser_status = active.modules/system/roles/*,roles.class.php(CSystem_Role)modules/system/index.php, newmodules/system/identity/*modules/system/systemconfig.php,do_systemconfig_aed.phpauth/ldapconfig groups move to provider rows.modules/admin/viewuser.php,modules/users/view.php,addedit.php,do_user_aed.phpstyle/bootstrap/login.php,lostpass.php?login=localfor break-glass). Lost password is hidden for SSO-only users.newuser.php,createuser.phpactivate_external_user_creationdefaults tofalseon fresh installs.includes/cleanup_functions.phpsendNewPass()calendar.php,fileviewer.phpfileviewer.phpusesSessionEstablisherinstead of its own login copy.includes/config-dist.php,.htaccess, nginx exampleW2P_APP_KEY,trusted_proxies,CGIPassAuth On(Apache with PHP-FPM otherwise drops theAuthorizationheader that SCIM needs), nginxfastcgi_param HTTP_AUTHORIZATIONinstall/sql/071_identity_*.sql5. Data model
users, additive columnsuser_status'active'active/disabled. Separate from "has no roles". Reactivating restores the previous roles.user_source'local'local,jit:{provider},scim,ldapuser_external_idexternalId/ directory GUIDuser_auth_epochuser_last_loginuser_allow_local_loginAdd a UNIQUE index on
user_username, after a migration that reports and renames duplicates.user_passwordmay hold an unusable marker for SSO-only users.New tables
identity_providersprovider_id,provider_slug(unique),provider_type(sql/ldap/oidc/saml/header),provider_name,provider_enabled,provider_order,provider_config(JSON),provider_secrets(encrypted JSON),jit_enabled,jit_default_role,link_policy,role_mode(additive/authoritative),attribute_map(JSON)user_identitiesidentity_id,user_id,provider_id,subject,issuer,linked_at,last_used_at; UNIQUE(provider_id,subject)external_groupsgroup_id,group_source(provider slug orscim),group_external_id,group_display_name; UNIQUE(source, external_id)external_group_membersgroup_id,user_idexternal_group_rolesgroup_id,role_id(phpGACL role)user_role_grantsuser_id,role_id,grant_source(manual,group:{id},default:{provider}); effective roles = union, written to phpGACLscim_tokenstoken_id,token_name,token_hash(SHA-256),created_by,created_at,last_used_at,expires_at,revoked_atauth_replay_cacheUpgrade: existing users get
user_status = 'active',user_source = 'local'. Existingauth_method/ldap_*config becomesidentity_providersrows (sqlis always present). The LDAP bind password moves into encryptedprovider_secrets.6. Sign-in
6.1 OIDC (Phase 1)
auth.php/login/{slug}?return=…: storestate,nonce, PKCE verifier and the internal return path in the session, then redirect to theauthorization_endpointfrom discovery (/.well-known/openid-configuration, cached).auth.php/callback/{slug}: checkstate, exchange the code (client secret orprivate_key_jwt), and validate the ID token: signature against the cached JWKS (refetch once on unknownkid), allowed algorithms RS256/PS256/ES256 only,issexact match,audcontains client_id,azpif present,exp/iatwith 120 s skew,nonce. Call userinfo only if configured.w2p_Auth_Identityand resolve the account (6.3). ThenSessionEstablisherregenerates the session ID and redirects to the saved return path. Only internalindex.php?…paths are accepted.end_session_endpointwithid_token_hintandpost_logout_redirect_uriwhen the IdP advertises it.Provider notes for the admin docs
common/organizations. With more than about 200 groups, Entra sends a group overage claim instead of the list, so recommend app roles (rolesclaim) overgroups.groupsclaim has to be added to the authorization server or app.6.2 SAML 2.0 (Phase 3)
SP-initiated login. ACS at
auth.php/saml/acs/{slug}and metadata atauth.php/saml/metadata/{slug}. Requirements: signed assertions (or a signed response), checks onInResponseTo, audience, recipient and time conditions, a replay cache, persistent NameID or a configured immutable attribute as the subject, and SP certificate rollover (two certificates published during rollover). SLO is optional and off by default.6.3 Account resolution
In order:
user_identitiesmatch on (provider, subject). Never match on email or username once linked.admin-only):admin-only: an admin pre-links, or the user links while signed in locally from their Sign-in tab.username: link to an existing user whose username equals the mapped username.verified-email: link on email, only when the provider is marked trusted for email and the claim isemail_verified = true.Provisioning_Service::create()with the default role and any group mappings.The account must be
activeand must passcheckLogin(), the same as today.6.4 Login policy
The
auth_local_loginsetting takes one of three values:everyone(default, today's behavior),break-glass(only users withuser_allow_local_login; form at?login=local) ordisabled. When there is exactly one provider and local login is off, the login page can auto-redirect to it.7. Provisioning
7.1 JIT (Phase 1)
On every federated login,
update()refreshes the mapped fields (name, email, title, phone) from claims. Group claims updateexternal_group_membersand role grants (7.4). JIT never disables anyone, because it only sees people who sign in.7.2 SCIM 2.0 server (Phase 2)
scim.php/v2/...uses PATH_INFO. Authentication is a bearer token, stored hashed and shown once, compared in constant time and rate limited. Responses areapplication/scim+jsonwith RFC 7644 error bodies (scimType).Endpoints, limited to the subset Entra ID and Okta actually use:
GET /ServiceProviderConfig,/Schemas,/ResourceTypesGET /Users?filter=userName eq "…"(alsoexternalId eq,emails.value eq),startIndex/countpagination,GET /Users/{id}POST /Users(409uniquenesson duplicates),PUT /Users/{id},PATCH /Users/{id}(add/replace/remove). The PATCH handler must accept Entra's quirks:activesent as the string"False", path-lessreplacewith a value object, andemails[type eq "work"].valuepaths.DELETE /Users/{id}→ deactivate, never deleteGET/POST /Groups,GET /Groups?filter=displayName eq "…",PATCH /Groups/{id}(members add/remove, displayName),DELETE /Groups/{id}(removes the group and the grants that came from it)Attribute mapping (default)
iduser_id(as a string)userNameuser_username(normalized; see 9)externalIduser_external_idactiveuser_statusname.givenName/name.familyName/displayNamecontact_first_name/contact_last_name/contact_display_nameemails[primary]contact_emailphoneNumbers[work]/[mobile]contact_phone/ contact methodphone_mobiletitlecontact_jobdepartment/organizationcontact_department/contact_companyonly when "match by name" is enabled; never auto-createdgroups(read-only on User)external_group_members7.3 Deactivation semantics
Disabling a user (SCIM
active=false, SCIM DELETE, LDAP sync, or the admin UI) does all of the following:user_status = disableduser_auth_epoch, which ends PHP-native sessions on their next requestRoles, project and task ownership and assignments are kept. Admins get a "Disabled users with open tasks" report so work can be reassigned.
7.4 Roles from groups
Each provider (and SCIM) has a
role_mode:Unmapped groups are still recorded in
external_groups, so admins can map them later without waiting for a re-push. phpGACL stays the enforcement engine.user_role_grantsrecords provenance, and the effective role set is written to phpGACL.7.5 Directory sync (Phase 4)
A cron hook (
hook_cronon a new identity module) pages through users in a configured base DN/filter. It creates or updates throughProvisioning_Service, disables users that are missing or disabled in the directory (ADuserAccountControlbit 2), and syncs group membership, with nested groups viaLDAP_MATCHING_RULE_IN_CHAINon AD. Always use LDAPS or StartTLS, escape filters withldap_escape(), and stop copying directory passwords into the local hash.8. Admin UI
System Admin › Identity & Single Sign-On
role_mode.User view › Sign-in tab: status, source, linked identities (unlink), last login and method, "Sign out everywhere", disable/enable.
9. Security
random_bytes(); token-based password reset.stateandnoncesingle use; exact redirect URIs (HTTPS, exceptlocalhostin development); rejectalg: noneand HMAC algorithms on asymmetric keys.robrichards/xmlseclibs≥ 3.1.5 (CVE-2025-66475, GHSA-5j8p-438x-rgg5). Rely on php-saml's XXE and signature-wrapping protections, and keep it current.email_verifiedis true and the provider is trusted for email. For Entra, use a tenant-specific issuer.',+or non-ASCII characters. Today's code concatenates usernames into SQL and relies on regex sanitizing (CAppUI::login(), both authenticators,sendNewPass()). Phase 0 quotes or parameterizes every username query (Usernames and session ids are concatenated into SQL and LDAP filters #442). The mapper normalizes to a configurable allowlist and handles collisions (jsmith,jsmith2), while the stable subject lives inuser_identities.SecretStoreencryption orenv:references, never rendered back to the UI, never logged (including tokens and assertions).history.10. Dependencies
PHP ≥ 8.2 (same baseline as the file-backend spec). Extensions:
openssl,sodium,dom,curl;ldaponly for LDAP providers.league/oauth2-client(GenericProvider)w2p_Auth_Provider_Oidc.firebase/php-jwtJWK::parseKeySet,CachedKeySet)onelogin/php-saml4.xrobrichards/xmlseclibs^3.1.5. Ship as an optional package (e.g.web2project/identity-saml), so installs without SAML don't carry xmlseclibs.cloudstek/scim-filter-parser3.xeq/and/orsubset IdPs send. Avoidtmilos/scim-filter-parser(last release 2017).w2p_Scim_*is hand-written. The required surface is small.ext-ldapnow;symfony/ldapordirectorytree/ldaprecordfor Phase 4 syncilluminate/collectionsandilluminate/contracts.symfony/ldapis lighter. Decide in Phase 4.spomky-labs/otphp(optional)Considered and not recommended:
jumbojett/openid-connect-php: simple, but the last release is v1.0.2 (Sep 2024), it has about 138 open issues, and it pulls in phpseclib.Test infrastructure: Keycloak container in CI (OIDC and SAML). Microsoft's SCIM Validator and Okta's SCIM test suite, run manually per release. Live Entra and Okta developer tenants for a nightly or manual check.
11. Backward compatibility
getAuth(),w2p_Authenticators_SQLandw2p_Authenticators_LDAPstay for one release as shims.w2p_Authenticators_PostNukeis removed (itspnoption is dropped from theauth_methodselect list).user_status) are shown separately in the user lists.activate_external_user_creationchanges its default only for fresh installs. Upgrades keep their setting, but LDAP and JIT provisioning no longer depend on it.12. Testing
13. Phasing
All issues are in the web2project v6.0 milestone.
Already done on
dev-5.0.0:e445eefano session ID in redirect URLs;3d68dea5session_regenerate_id(true)at login;c8b01906cookieSecure/HttpOnly/SameSite=Lax;c28135bdlost password works again (contact_emaillookup, login-compatible usernames, quoted SQL,random_int()passwords).getIdByContactId(), escaping, proxy HTTPS detection, session cleanupCAppUI::login()into authenticator → resolver →SessionEstablisher(also used byfileviewer.php);user_status,user_auth_epoch,user_source,user_last_login; unique username (#438);user_identities,identity_providers;SecretStore;Provisioning_Serviceskeleton with LDAP JIT moved onto it; token-based password reset (#443); login throttling; strict session mode; remove PostNukeuser_role_grants); RP-initiated logout; login policy and break-glass; admin UI (providers, provisioning, groups → roles); user Sign-in tabscim.phpUsers and Groups, discovery endpoints, tokens UI, deactivation semantics, Apache/nginxAuthorizationpassthrough docs14. Open questions
preferred_username, email or UPN by default? (Proposed: configurable per provider; defaultpreferred_username, falling back to the email local part.)usernameorverified-emailpolicies. Do we need a bulk "pre-link from CSV" tool?additivethe right default, and shouldauthoritativemode also governuser_type?user_status/user_auth_epochon every request, or cache for 60 s in the session?All reactions