diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c6ad1a8..8dd1777 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -53,6 +53,8 @@ jobs: --admin_email=admin@company.com --skip-email docker compose -p soca-ci --profile tools run -T --rm --no-deps cli wp plugin activate simple-oauth-cimd-access docker compose -p soca-ci --profile tools run -T --rm --no-deps cli wp eval-file /tests/wordpress.php + docker compose -p soca-ci --profile tools run -T --rm --no-deps cli wp eval-file /tests/deployment.php + docker compose -p soca-ci --profile tools run -T --rm --no-deps cli wp eval-file /tests/emergency.php docker compose -p soca-ci --profile tools run -T --rm --no-deps cli wp soca status - name: Container logs on failure if: failure() @@ -79,11 +81,11 @@ jobs: python3 tools/build.py cd dist sha256sum -c SHA256SUMS - unzip -t simple-oauth-cimd-access-0.2.0.zip - unzip -Z1 simple-oauth-cimd-access-0.2.0.zip | grep -Fx 'simple-oauth-cimd-access/simple-oauth-cimd-access.php' + unzip -t simple-oauth-cimd-access-0.3.0.zip + unzip -Z1 simple-oauth-cimd-access-0.3.0.zip | grep -Fx 'simple-oauth-cimd-access/simple-oauth-cimd-access.php' - name: Upload installable plugin ZIP uses: actions/upload-artifact@v7 with: - path: dist/simple-oauth-cimd-access-0.2.0.zip + path: dist/simple-oauth-cimd-access-0.3.0.zip archive: false if-no-files-found: error diff --git a/README.md b/README.md index 18ff81b..ce171b8 100644 --- a/README.md +++ b/README.md @@ -6,14 +6,14 @@ SOCA adds single sign-on to WordPress through an OpenID Connect provider that su - Publishes this site's client metadata and public signing keys through self-hosted URLs or a configurable HTTPS metadata proxy. - Signs client assertions with encrypted, rotating P-256 keys and validates the provider's signed ID token. -- Applies email and domain admission rules to a **verified** provider email, then selects the matching local WordPress account. Optional creation is limited to Subscriber accounts. +- Applies email and domain admission rules to a **verified** provider email, then selects an account through its approved issuer/subject identity link. Optional creation is limited to Subscriber accounts. - Provides a login button, a test-login flow, redacted diagnostics, WP-CLI maintenance commands, and a local-login recovery route. -**Security decision:** A provider that can verify an admitted administrator email can sign in as that administrator. Keep a local administrator login, review the admission rules, and test the provider before enabling automatic redirects. The browser's User-Agent is checked at callback, but it is not proof of the same browser. +**Upgrade to 0.3.0:** Existing users need administrator-approved issuer/subject links. Email alone no longer selects a local account. Ordinary SSO requires an admitted test login for the current configuration. Keep a working local administrator login during migration; see the [upgrade and configuration guide](docs/GUIDE.md). Callbacks require a short-lived secure browser cookie. ## Install and configure -Download the `simple-oauth-cimd-access-0.2.0.zip` release asset when published or build it with `python3 tools/build.py`. In WordPress, choose **Plugins → Add Plugin → Upload Plugin**, activate SOCA, then open **Settings → SOCA**. It requires WordPress 6.8+, PHP 8.1+, OpenSSL, cURL, and a public HTTPS site for self-hosted metadata. The installable ZIP contains its runtime dependency; Composer is not needed on the server. +Download the `simple-oauth-cimd-access-0.3.0.zip` release asset when published or build it with `python3 tools/build.py`. In WordPress, choose **Plugins → Add Plugin → Upload Plugin**, activate SOCA, then open **Settings → SOCA**. It requires WordPress 6.8+, PHP 8.1+, OpenSSL, cURL, and a public HTTPS site for self-hosted metadata. The installable ZIP contains its runtime dependency; Composer is not needed on the server. 1. Keep a working local administrator password and bookmark `/wp-login.php?soca_local=1`. 2. Review the configured issuer, provider name, client metadata mode, and exact admission rules. Defaults use `https://auth.resoauth.cloud`. @@ -24,6 +24,7 @@ The initial identity provider is the [RESOAuth hosted Smart Access Gateway](http ## Documentation and support +- [Shared requirements review and remaining gaps](docs/REQUIREMENTS.md) - [Operator guide](docs/GUIDE.md) - [Local development and build](docs/DEVELOPMENT.md) - [Security and protocol decisions](docs/SECURITY.md) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 3cd20be..f6ae371 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -1,5 +1,14 @@ # Release history +## 0.3.0 (unreleased) + +- Bind each ten-minute transaction to its initiating browser using an independent Secure, HttpOnly, SameSite=Lax cookie; retain encrypted WordPress transients and atomic replay checks. +- Replace email-based account selection with encrypted, unique issuer/subject associations. Add explicit administrator linking/revocation and conservative provisioning rollback. Existing users require approved links. +- Require an admitted, fresh test login before ordinary SSO becomes available. Bind evidence to candidate configuration and metadata; preserve the operator session and prevent test-side account writes. +- Add deployment overrides and locks for every supported setting, shared validation, stale form rejection, WP-CLI configuration and operator-bound test URLs. Emergency disable and deactivation invalidate pending flows and activation evidence. +- Support exact and leading `*.` domain rules, platform branding/privacy defaults, public metadata overrides and explicit proxy payload/URL limits. +- Publish a per-ID shared requirements review with remaining security, interoperability and operational gaps. + ## 0.2.0 - Standardized the PHP and vendored JWT namespaces, hooks, options, transients and configuration constants under SOCA, and removed pre-release compatibility paths. diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md new file mode 100644 index 0000000..cc2de41 --- /dev/null +++ b/docs/CONFIGURATION.md @@ -0,0 +1,114 @@ +# Deployment configuration + +SOCA 0.3.0 uses one validation path for deployment values, WP-CLI and the existing +WordPress settings screen. No settings form must be saved to apply deployment +configuration. Effective precedence is **defaults < saved site settings < +SOCA_CONFIG**. A key present in SOCA_CONFIG is locked in the GUI; crafted form +posts and CLI writes cannot replace it. Removing an override reveals the previous +saved value or the default. Multisite applies the constant on each site; use +conditional deployment code when sites need different values. + +Provision keys/salts through the host's secret-management process. Before loading +WordPress, set SOCA_ENCRYPTION_KEY to a stable secret of at least 32 random bytes +when using a separate encryption root. Otherwise the plugin derives its root from +the WordPress authentication keys/salts. Do not put private keys or secrets in +SOCA_CONFIG or the database configuration JSON. + +```php +// wp-config.php, before WordPress loads. +define('SOCA_CONFIG', [ + 'issuer' => 'https://auth.resoauth.cloud', + 'enabled' => true, + 'automatic' => false, + 'mode' => 'self', + 'key_mode' => 'uri', + 'allow_domains' => ['example.com', '*.example.com'], + 'deny_domains' => ['blocked.example.com', '*.blocked.example.com'], + 'create_users' => false, + 'tos_uri' => 'https://www.example.com/terms/', +]); +``` + +`enabled=true` requests activation; ordinary SSO remains unavailable until an +admitted operator test login succeeds for the effective candidate. Candidate +metadata is published while ordinary login is disabled. A real test validates +provider signatures, fresh authentication and admission without creating/linking +accounts, writing profiles/roles or replacing the operator's session. + +Use the CLI for setup and maintenance: + +```sh +wp plugin activate simple-oauth-cimd-access +wp soca config +wp soca configure /secure/deployment/soca.json +wp soca check +wp soca test-url --user=localadmin +wp soca status +wp soca link --user=localadmin 42 'https://auth.resoauth.cloud' 'exact-provider-subject' +wp soca unlink --user=localadmin 42 'https://auth.resoauth.cloud' 'exact-provider-subject' +wp soca maintain +wp soca disable +``` + +Identity approval and revocation require `--user=`; audit entries record the local actor and target IDs. + +`configure` accepts a JSON object containing any supported setting, with booleans, +integers, strings and string-array rule lists. Unknown names are rejected. Changes +to unlocked settings merge with previous values, so repeat deployments preserve +omitted fields. An unchanged configuration is a no-op and preserves in-flight revisions. `config` shows effective values and deployment locks, including +admission lists; restrict its output to operators. This is separate from the +redacted health/status export. The supported names are listed below. + +Open the one-use `test-url` in a browser authenticated locally as the selected +administrator. It expires after ten minutes and requires that same operator and +configuration revision. Ordinary WordPress login suffices; no settings page or +form save is needed. Interactive authentication at the provider remains necessary. +The test result and activation status are available with `wp soca status`. +Enabling automatic redirects or the button preserves an otherwise unchanged +candidate test; changing issuer, callback, admission rules, metadata or inline keys +requires a fresh test. Any settings save invalidates existing in-flight flows. + +| Setting | Default and validation | +| --- | --- | +| enabled, automatic, create_users, unrestricted | false. JSON/PHP booleans preferred; 0/1 accepted. Unrestricted bypasses allowlists, never denylists. Provisioning is fixed to Subscriber. | +| provider, button | RESOAuth; Continue with SSO. Plain text, 1–120 bytes. | +| issuer | https://auth.resoauth.cloud. Exact public HTTPS issuer, no query/userinfo/fragment. | +| scopes | openid email profile. Space-separated OAuth scope syntax, <=500 bytes; openid and email required. Request only necessary scopes. | +| mode, key_mode | Public host: self/uri; local host: proxy/inline. Allowed values self or proxy; uri or inline. | +| proxy | https://dynamic-cimd.resoauth.cloud/cimd/%s. Exactly one literal %s in an HTTPS path. Set this value to reset to the default. | +| jwks_url | Empty, deriving the site's public JWKS endpoint. Override must be public HTTPS. | +| id_alg | ES256. Explicit RS256 alternative for ID tokens; assertions remain ES256. | +| assertion_audience | issuer. Alternative token_endpoint uses its exact discovered URL. | +| cache_hours | 24; integer 1–168 hours. Confirm the provider's actual maximum cache lifetime. | +| allow_domains, deny_domains | Suggested exact site hostname in allow_domains; empty deny list. Arrays or separated text, <=200 entries and <=32000 bytes per list. Exact domains or one leading *. followed by a dotted domain. | +| allow_emails, deny_emails | Empty. Arrays or separated text, <=200 ASCII emails per list; verified email required. | +| client_name | Empty override uses the WordPress site name. Plain text <=120 bytes. | +| client_uri | Empty override uses the WordPress home URL. Explicit overrides require public HTTPS. | +| logo_uri | Empty override uses the WordPress Site Icon URL when public HTTPS; otherwise omitted. | +| policy_uri | Empty override uses WordPress's published privacy-policy URL when public HTTPS; otherwise omitted. | +| tos_uri | Empty by default, omitted. WordPress has no core terms-page API; set a published public HTTPS terms URL explicitly. | + +Metadata uses application identity, not the identity provider's branding or legal +pages. Optional unavailable/unsafe platform URLs are omitted. Explicit overrides +must pass validation. Hosted and proxy metadata share the same generation path. + +Emergency disable is independent of deployment locks: + +```php +define('SOCA_DISABLED', true); +``` + +Roll it out to every PHP worker and run `wp soca status` with the flag present. +The first observation changes the persisted security epoch, invalidating pending +ordinary/test flows and activation evidence even after the flag is removed. PHP +opcode-cache/deployment propagation is the host's responsibility. `wp soca disable` +clears unlocked enablement and invalidates the same evidence; if enabled is locked +true, the emergency constant provides durable disablement. Existing WordPress +sessions survive disable/deactivation; unlinking an identity ends all sessions for +its local account. Retest after recovery. + +Forms include a revision check and reject stale writes. Keep configuration JSON +and deployment revisions in your normal version-controlled deployment process for +rollback, excluding secrets. No automatic settings history or database rollback +engine is provided. Restoring old database backups can restore old links/evidence; +reconcile revocations and run emergency disable before restoring service. diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 00a4341..389b191 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -2,14 +2,14 @@ SOCA (Simple OAuth CIMD Access) is an open-source WordPress single sign-on plugin built and supported by RESOAuth® that can use another compatible configured provider. It uses OIDC authorization code + PKCE S256, `private_key_jwt` ES256, and self-hosted or proxy Client ID Metadata Documents (CIMD). It does **not** make WordPress an authorization server. -Install the `simple-oauth-cimd-access-0.2.0.zip` release asset using **Plugins → Add Plugin → Upload Plugin**, activate it, then open **Settings → SOCA**. PHP 8.1+, OpenSSL, cURL, and WordPress 6.8+ are required. The release contains its isolated JWT dependency; Composer is not needed on the WordPress server. +Install the `simple-oauth-cimd-access-0.3.0.zip` release asset using **Plugins → Add Plugin → Upload Plugin**, activate it, then open **Settings → SOCA**. PHP 8.1+, OpenSSL, cURL, and WordPress 6.8+ are required. The release contains its isolated JWT dependency; Composer is not needed on the WordPress server. ## Setup 1. Keep a local administrator account and password. Bookmark `/wp-login.php?soca_local=1`. Confirm WordPress uses HTTPS and has unique authentication keys/salts in `wp-config.php`. -2. Review the issuer, provider name and button label. Initial settings use the [RESOAuth Ltd hosted Smart Access Gateway](https://sag.resoauth.dev/hosted) at `https://auth.resoauth.cloud`, scopes `openid email profile`, ES256 client authentication. Its [connection guide](https://sag.resoauth.dev/hosted/connect) explains the hosted issuer, CIMD and sign-in methods. Read its [privacy notice](https://sag.resoauth.dev/hosted/privacy-notice) and [terms of service](https://sag.resoauth.dev/hosted/terms-of-service). Public HTTPS sites default to self-hosted CIMD and the derived JWKS URL, and show the login button on activation. Local sites select the [RESOAuth Dynamic CIMD](https://dynamic-cimd.resoauth.cloud/) proxy and inline public keys; their login button stays off until an admission rule is chosen. -3. Review admission rules. The suggested domain is the exact home hostname with one leading `www.` removed; localhost, IPs and reserved development names are excluded. Deny wins; either allowlist can admit. **Allow any verified email/domain** starts off and, when selected, hides the allowlists while keeping denylists active. Domains match exactly. First-login verified-email matching includes existing administrator accounts by default. Registration remains off; new accounts, when enabled, are Subscribers. -4. **Validate connection and documents → Test login.** The test keeps your current administrator session, validates a fresh upstream login and reports the saved email policy without selecting or creating an account. Automatic redirect is optional. +2. Review the issuer, provider name and button label. Initial settings use the [RESOAuth Ltd hosted Smart Access Gateway](https://sag.resoauth.dev/hosted) at `https://auth.resoauth.cloud`, scopes `openid email profile`, ES256 client authentication. Its [connection guide](https://sag.resoauth.dev/hosted/connect) explains the hosted issuer, CIMD and sign-in methods. Read its [privacy notice](https://sag.resoauth.dev/hosted/privacy-notice) and [terms of service](https://sag.resoauth.dev/hosted/terms-of-service). Public HTTPS sites default to self-hosted CIMD and the derived JWKS URL. Local sites select the [RESOAuth Dynamic CIMD](https://dynamic-cimd.resoauth.cloud/) proxy and inline public keys. Ordinary SSO starts disabled on every site. +3. Review admission rules. The suggested domain is the exact home hostname with one leading `www.` removed; localhost, IPs and reserved development names are excluded. Deny wins; either allowlist can admit. **Allow any verified email/domain** starts off and, when selected, hides the allowlists while keeping denylists active. Exact domains match only themselves. A leading `*.` matches one or more subdomain labels and excludes the apex: `*.example.com` admits `a.b.example.com`, not `example.com` or `badexample.com`. Existing users, including administrators, require approved issuer/subject links. Registration remains off; new accounts, when enabled, are Subscribers. +4. **Validate connection and documents → Test login.** The test keeps your current administrator session, validates a fresh upstream login and reports the saved email policy without selecting or creating an account. An admitted test activates the candidate evidence; then enable the login button and optional automatic redirect. A denied test cannot activate ordinary SSO. The separate **Test access rules** form explains how the saved allowed/denied email and domain rules treat an address. It links back to Access rules, keeps the tested address visible, and shows the result beside the field and button. Unsaved edits are not included. @@ -23,11 +23,30 @@ Provider acceptance of redirect origins, query-bearing client URLs, inline JWKS For local development, see [Development and validation](DEVELOPMENT.md). +## Upgrade from 0.2.0 and headless setup + +**0.3.0 intentionally ends automatic email-based account selection.** Keep local +administrator access while upgrading. Existing settings and encrypted keys are +preserved, but ordinary SSO has no current candidate-test evidence until retested. +Approve every returning user's exact issuer/subject association before rollout. +Do not import associations by matching email alone. Test a linked ordinary user, +an administrator, a changed subject and local recovery before enabling automatic +redirects. Existing WordPress sessions are preserved. + +[Deployment configuration](CONFIGURATION.md) documents every supported setting, +SOCA_CONFIG precedence/locks, WP-CLI JSON setup and operator-bound test URLs. +Metadata defaults use the site's name, home URL, public Site Icon and published +privacy policy in both modes. Override application identity/legal fields under +advanced settings or in SOCA_CONFIG. WordPress has no core terms-page API, so set +tos_uri explicitly where available. [The requirement assessment](REQUIREMENTS.md) +records capabilities and outstanding gaps. + ## Account selection and recovery -- On every login, SOCA checks the current, valid, verified email from the configured provider against the saved admission rules, then selects the unique matching WordPress user on this site. The subject is still validated as part of OIDC and used to match UserInfo, but no subject binding is stored or consulted for account selection. -- A changed pairwise subject with the same verified email selects the same account. If the provider returns a different verified email, that address selects its matching local account. SOCA does not change existing WordPress email addresses, roles or capabilities. -- A provider that verifies an admitted administrator email can access that administrator account. Choose a provider whose email verification you trust for every admitted domain. Duplicate local email rows and nonmember accounts are refused. Missing accounts are created as Subscribers only when **Create missing accounts** is enabled. +- On every login, the trusted provider's current verified email must pass admission. The exact issuer/subject then selects its approved local identity association. Email alone never grants access to an existing account. +- Approve an existing user's association in **Settings → SOCA → Approve or remove an identity link**, or run `wp soca link --user=localadmin '' ''`. Verify ownership independently and obtain the exact subject from the trusted provider. Administrator approval is the supported linking method; self-service linking is not implemented. +- A changed subject is refused until explicitly approved. A changed email never switches to another local account; existing email/profile fields, roles and capabilities remain local. Unlinked identities with an existing local email are refused, even when creation is enabled. +- Optional new-account creation is limited to Subscribers, with a random local password and identity link. Conflicts refuse login. Unlinking stores an encrypted revocation record, invalidates pending flows/activation evidence and ends all WordPress sessions for that account. It cannot automatically provision again until explicitly approved. Deleted or removed accounts are not reactivated. - `?soca_local=1` only skips automatic navigation. It does not authenticate anyone. Password recovery, reset, interim login and logout flows are preserved. Local logout ends the WordPress session only; it does not claim provider-wide logout. Emergency recovery in `wp-config.php`: @@ -36,7 +55,7 @@ Emergency recovery in `wp-config.php`: define('SOCA_DISABLED', true); ``` -Or run `wp soca disable`. Deactivating the plugin also leaves standard WordPress login available. Settings and encrypted keys are retained on deactivation and uninstall by default. To remove persistent plugin settings, signing keys and audit data during uninstall, first set `SOCA_ERASE_DATA` to `true`; this affects every site on a multisite install and does not delete WordPress users. Short-lived transients expire through WordPress. Back up beforehand and remove that constant afterward. +Or run `wp soca disable` for unlocked settings. `SOCA_DISABLED=true` overrides even a deployment-locked enablement and blocks operator tests. Ensure every worker sees it and run `wp soca status` while it is present, so the persisted security epoch invalidates pending flows even after recovery. Deactivating the plugin also leaves standard WordPress login available. Deactivation invalidates pending flows and activation evidence. Existing WordPress sessions survive disable/deactivation. Settings, encrypted keys and encrypted identity records are retained on deactivation and uninstall by default. To remove persistent plugin settings, signing keys, identity associations and audit data during uninstall, first set `SOCA_ERASE_DATA` to `true`; this affects every site on a multisite install and does not delete WordPress users. Short-lived transients expire through WordPress. Back up beforehand and remove that constant afterward. ## Rotation, proxy behavior and operations @@ -44,9 +63,9 @@ See [rotation and security details](SECURITY.md). Two P-256 keys are generated l The default provider cache safety window is **24 hours**, an operator-configurable estimate, not a measured RESOAuth cache policy. Confirm the provider's maximum caching bound and increase this setting when necessary. A window approaching/exceeding half a week conflicts with weekly rollover under the two-key limit; the plugin keeps safe overlap and reports overdue rotation through Site Health. -Proxy substitution uses one literal `%s` in the HTTPS URL path. The default is `https://dynamic-cimd.resoauth.cloud/cimd/%s`. It encodes the public metadata template as unpadded UTF-8 base64url and omits `client_id`; the service must insert the exact resulting fetch URL. Other valid `%xx` encodings are preserved. A public metadata round trip was checked against the new service on 19 October 2026. The plugin does not deploy a proxy. The proxy service is separate from the hosted identity provider; the gateway's terms and privacy notice linked above describe the gateway, not every possible proxy. Changing the template changes the `client_id`, so complete a fresh test login afterward. +Proxy substitution uses one literal `%s` in the HTTPS URL path. The default is `https://dynamic-cimd.resoauth.cloud/cimd/%s`. It serialises the public template in fixed field order with sorted public keys, unescaped Unicode/slashes and no whitespace, then uses unpadded UTF-8 base64url without `client_id`; the service must insert the exact resulting fetch URL. Other valid `%xx` encodings are preserved. The local limits are 8192 public JSON bytes and a 12288-byte resulting URL, including overlapping keys. The actual proxy/provider limits may be lower; confirm them before deployment. A public metadata round trip was checked against the new service on 19 October 2026. The plugin does not deploy a proxy. The proxy service is separate from the hosted identity provider; the gateway's terms and privacy notice linked above describe the gateway, not every possible proxy. Changing the template changes the `client_id`, so complete a fresh test login afterward. -In proxy + inline mode, staging a new public key changes the encoded document and therefore the client identifier. Consent may repeat and pairwise subjects may change. The plugin preserves in-flight client IDs/keys; account selection still uses the current verified email. A **stable public JWKS URL** keeps encoded metadata stable across key rotation. If using an external mirror, export public keys with `wp soca jwks` and publish **both** keys; an unattended weekly rotation requires an automated mirror. No private key export is provided. +In proxy + inline mode, staging a new public key changes the encoded document and therefore the client identifier. Consent may repeat and pairwise subjects may change. A changed metadata fingerprint requires an admitted test before further ordinary SSO. Old client IDs and keys are retained, but this does not provide uninterrupted inline-key rollover. A changed pairwise subject requires explicit link migration, never email-based recovery. A **stable public JWKS URL** keeps encoded metadata stable across key rotation. If using an external mirror, export public keys with `wp soca jwks` and publish **both** keys; an unattended weekly rotation requires an automated mirror. No private key export is provided. WP-Cron runs maintenance hourly. With upstream login disabled, it does not contact the provider or CIMD proxy. When upstream login is enabled, it also checks public metadata and performs safe key rotation. Use real cron on low-traffic sites: @@ -62,12 +81,12 @@ wp soca check # live discovery, actual metadata and public-key check wp soca maintain # publication verification and safe rotation wp soca jwks # public keys only, for a stable mirror wp soca audit # last 100 redacted events, including login steps, reason codes and references -wp soca disable # disable upstream button/automatic mode +wp soca disable # invalidate flows/evidence and disable unlocked button/automatic mode ``` On multisite, always select the site with `--url`. Settings, policy, encrypted keys and transactions are isolated per site. New sites initialize lazily on first request. Site Health reports missing/stale maintenance and overdue rotation; its debug export excludes secrets. Web-server/proxy logs should omit callback query strings because authorization responses contain short-lived codes and state. A failed login shows a 12-character reference; find the matching `login_failed` event in **Settings → SOCA → Recent redacted audit events** or `wp soca audit`. Its `step` and `reason` show where the attempt stopped; outbound failures include an HTTP status when an endpoint responds with an error. The audit never records emails, subjects, passwords, raw provider errors or tokens. -SOCA does not set a temporary login cookie. The callback checks the User-Agent, consumes the one-time encrypted transient, exchanges the code, validates the signed ID token and verified email, then issues normal WordPress authentication cookies. Audit events identify failed steps and reasons, including `user_agent_mismatch`. Matching User-Agents do not prove the same browser; see [SECURITY.md](SECURITY.md). +Each transaction uses an independent 256-bit browser secret in a ten-minute, host-only Secure/HttpOnly/SameSite=Lax cookie. It contains no verifier, nonce or token. An encrypted WordPress transient holds the secret hash and confidential protocol state. The callback validates the browser binding and User-Agent before atomically consuming the state; it then deletes that cookie. Abandoned cookies expire automatically. Parallel tabs have distinct cookies. No localStorage, sessionStorage or IndexedDB is used. See [SECURITY.md](SECURITY.md). Theme integration: diff --git a/docs/RELEASE.md b/docs/RELEASE.md index 6af4439..e028f2e 100644 --- a/docs/RELEASE.md +++ b/docs/RELEASE.md @@ -1,13 +1,13 @@ -# 0.2.0 directory release notes +# 0.3.0 directory release notes -The installable archive is `dist/simple-oauth-cimd-access-0.2.0.zip`; `dist/simple-oauth-cimd-access-0.2.0-source.zip` contains the repository tooling, tests and detailed documentation. Generate both with `python3 tools/build.py`, then verify `dist/SHA256SUMS`. The installable ZIP has one top-level `simple-oauth-cimd-access/` directory and includes `readme.txt`, the main plugin file, runtime source, `composer.json` and licenses. Detailed guides and test evidence remain in the repository and source archive, linked from the directory readme. +The installable archive is `dist/simple-oauth-cimd-access-0.3.0.zip`; `dist/simple-oauth-cimd-access-0.3.0-source.zip` contains the repository tooling, tests and detailed documentation. Generate both with `python3 tools/build.py`, then verify `dist/SHA256SUMS`. The installable ZIP has one top-level `simple-oauth-cimd-access/` directory and includes `readme.txt`, the main plugin file, runtime source, `composer.json` and licenses. Detailed guides and test evidence remain in the repository and source archive, linked from the directory readme. -The plugin header and directory readme both use version/stable tag `0.2.0`, WordPress 6.8, PHP 8.1, and the `simple-oauth-cimd-access` text domain. The display name is **Simple OAuth CIMD Access**, so the expected directory slug matches the plugin folder. `Author: RESOAuth` and its GitHub organization URL are in the plugin header; the plugin URI points to this repository. The Composer package is `resoauth/simple-oauth-cimd-access`. +The plugin header and directory readme both use version/stable tag `0.3.0`, WordPress 6.8, PHP 8.1, and the `simple-oauth-cimd-access` text domain. The display name is **Simple OAuth CIMD Access**, so the expected directory slug matches the plugin folder. `Author: RESOAuth` and its GitHub organization URL are in the plugin header; the plugin URI points to this repository. The Composer package is `resoauth/simple-oauth-cimd-access`. -For an initial WordPress.org submission, upload the installable ZIP through the [plugin submission page](https://wordpress.org/plugins/developers/add/). WordPress.org assigns the directory slug during review. After approval, copy the installable folder's **contents** into the assigned SVN repository's `/trunk/` (the main PHP file must sit directly in trunk), copy trunk to `/tags/0.2.0/` with `svn cp`, and commit trunk and tag together. Confirm `Stable tag: 0.2.0` in both readmes. Follow the [WordPress.org SVN instructions](https://developer.wordpress.org/plugins/wordpress-org/how-to-use-subversion/). +For an initial WordPress.org submission, upload the installable ZIP through the [plugin submission page](https://wordpress.org/plugins/developers/add/). WordPress.org assigns the directory slug during review. After approval, copy the installable folder's **contents** into the assigned SVN repository's `/trunk/` (the main PHP file must sit directly in trunk), copy trunk to `/tags/0.3.0/` with `svn cp`, and commit trunk and tag together. Confirm `Stable tag: 0.3.0` in both readmes. Follow the [WordPress.org SVN instructions](https://developer.wordpress.org/plugins/wordpress-org/how-to-use-subversion/). The WordPress.org `Contributors` field is intentionally omitted until the submitting team supplies a verified WordPress.org username. The PHP `Author` field already identifies RESOAuth. Submit from the official RESOAuth WordPress.org account associated with `wordpress@resoauth.email`, as confirmed by the plugin owner; verify that account's profile email before upload. WordPress's [developer FAQ](https://developer.wordpress.org/plugins/wordpress-org/plugin-developer-faq/#how-do-i-submit-an-official-plugin) says official organization plugins must be submitted from the organization account. The directory listing links to the [default hosted gateway documentation](https://sag.resoauth.dev/hosted), its [privacy notice](https://sag.resoauth.dev/hosted/privacy-notice) and [terms of service](https://sag.resoauth.dev/hosted/terms-of-service). The separate [RESOAuth Dynamic CIMD](https://dynamic-cimd.resoauth.cloud/) service is linked and disclosed as the default metadata proxy for local development. -The `v0.1.0` GitHub release has already been published. Version `0.2.0` intentionally resets pre-release storage names and encryption context; earlier settings and keys are not imported. Configure and test a fresh installation before submission. Against the [WordPress.org detailed plugin guidelines](https://developer.wordpress.org/plugins/wordpress-org/detailed-plugin-guidelines/), the plugin contains no payment, trial, license or quota gate for its included functionality. Its login rate limit is an abuse control. It does not download executable code or insert arbitrary PHP/JavaScript into the site. Its CIMD-based client registration and key rotation are the distinct capabilities described in the listing. Review the permanent display-name-derived slug before submission, as WordPress.org will not rename an approved slug. +The `v0.1.0` GitHub release has already been published. Version `0.2.0` reset pre-release storage names and encryption context. Version `0.3.0` preserves 0.2.0 settings/keys but requires approved identity associations and a fresh candidate test before ordinary SSO. Follow the [migration procedure](GUIDE.md#upgrade-from-020-and-headless-setup) before rollout. The 0.3.0 artefacts are unreleased candidates until deliberately published. Against the [WordPress.org detailed plugin guidelines](https://developer.wordpress.org/plugins/wordpress-org/detailed-plugin-guidelines/), the plugin contains no payment, trial, license or quota gate for its included functionality. Its login rate limit is an abuse control. It does not download executable code or insert arbitrary PHP/JavaScript into the site. Its CIMD-based client registration and key rotation are the distinct capabilities described in the listing. Review the permanent display-name-derived slug before submission, as WordPress.org will not rename an approved slug. The WordPress HTTP API sends outbound requests; its `http_api_curl` hook pins the resolved public address while checking the TLS hostname and certificate, preventing a DNS change between validation and connection. See [the current Plugin Check disposition](PLUGIN-CHECK.md) and [test evidence](TESTING.md) for the full review. The static scan is not a security audit. diff --git a/docs/REQUIREMENTS.md b/docs/REQUIREMENTS.md new file mode 100644 index 0000000..3657b46 --- /dev/null +++ b/docs/REQUIREMENTS.md @@ -0,0 +1,89 @@ +# Shared SOCA requirements assessment + +Assessed on **21 October 2026 (Europe/London)** against the local +`soca-plugins/requirements.md` at commit +[`60ea4db827457b4a4a7b11d79e86b654612a75e1`](https://github.com/RESOAuth/soca-plugins/blob/60ea4db827457b4a4a7b11d79e86b654612a75e1/requirements.md). +The assessed file's SHA-256 is +`d2db3ee4d66717152c79af1863ea6d6ed117bb20ac5875bac723e38c73c45b85`. +The [shared requirements](https://github.com/RESOAuth/soca-plugins/blob/main/requirements.md) +remain the target; this assessment does not weaken them. + +Every row below assesses **0.3.0, unreleased**, in the same commit as this document, +against base `654d517`. The result date is **21 October 2026** for every row. +“Partial” means some required behaviour or evidence is missing; “planned” means +there is no implementation. Source review alone is not a successful live login. + +| ID | Status | Versioned evidence and result | Remaining gap | +| --- | --- | --- | --- | +| F-01 | Partial | [Provider](../simple-oauth-cimd-access/includes/Provider.php), [protocol tests](../tests/protocol.php): pinned issuer, capability refusal, RESOAuth defaults. | One provider per site; no simultaneous isolated profiles. Live acceptance unverified. | +| F-02 | Supported | [Browser tests](../tests/browser.cjs), [protocol tests](../tests/protocol.php): code, S256, independent state/nonce, exact callback, ES256 private_key_jwt, copied-callback refusal. | Restricted to the declared single-provider query-response profile. | +| F-03 | Partial | Protocol and browser tests: signatures, issuer, audience, nonce, times, response issuer, UserInfo subject/conflict refusal, fresh test authentication. | Configurable assurance and ordinary-login reauthentication policy. | +| F-04 | Partial | [Metadata](../simple-oauth-cimd-access/includes/Metadata.php), protocol tests: generated identity, WordPress name/home/icon/privacy defaults, overrides, public document checks. | WordPress has no standard terms-page setting; explicit tos_uri is needed. Packaged public reachability and provider activation remain deployment checks. | +| F-05 | Partial | Protocol tests: default/custom proxy, exact returned ID, deterministic encoding without client_id, overlapping two-key payload, payload/URL refusal. Browser: synthetic proxy login. | Provider/proxy URL limits are unconfirmed; no reset button; live proxy login unverified. | +| F-06 | Supported | Protocol and WordPress tests: inline/URI public keys, private-material refusal, no admission rules in public metadata. [Privacy disclosure](../simple-oauth-cimd-access/readme.txt). | Provider permission must be confirmed for each mode. | +| F-07 | Partial | [Security](SECURITY.md), rotation tests: bounded old signing-key retention and transaction snapshots. Candidate fingerprints include client metadata. | Inline document/key changes require a fresh admitted test and explicit pairwise-subject recovery; uninterrupted identity migration is not implemented. | +| F-08 | Partial | WordPress/protocol tests: stable key IDs, non-autoloaded authenticated encryption, per-site secret context. | External/non-exportable key management and tested backup/lost-key recovery. | +| F-09 | Partial | Protocol rotation vectors: publication, warm-up, retained retiring keys, delayed ticks and fixed retirement deadlines. | Inline key-set changes invalidate activation evidence; external mirrors need separate automation. No complete emergency key-revocation workflow or fault-tested worker promotion. | +| F-10 | Partial | Protocol ES256 and RS256 signature tests; ES256/P-256 client default and independent ID-token pin. | ES384/512, PS256/384/512, fully specified EdDSA and ML-DSA profiles/vectors. No silent fallback is enabled. | +| F-11 | Partial | Protocol tests: bounded cache expiry, unknown-kid/signature retry and 60-second refresh gate. | Explicit provider-key revocation signalling and broader outage/fault evidence. | +| F-12 | Partial | Protocol/WordPress/browser tests: exact and leading *. domains, nested labels, invalid rules, deny precedence, boolean verified email, preview. Startup revalidates saved/deployment rules. | Dedicated sensitive-account controls beyond explicit identity approval and site membership. | +| F-13 | Supported | [WordPress](../tests/wordpress.php) and [multisite](../tests/multisite.php) tests: links select one eligible account, email-only/changed-subject refusal, changed email preserves identity, roles/capabilities preserved, removed/spam/nonmember refusal. | Host extensions with additional account-disable semantics need integration. | +| F-14 | Partial | WordPress tests: opt-in Subscriber creation, random password, link-failure rollback. [Concurrency](../tests/concurrency.py): one account and identity owner. | Account/link writes are compensating operations, not a database transaction; process termination or external hook side effects can leave partial state. Role is fixed to Subscriber. | +| F-15 | Partial | WordPress tests: provider role claims cannot elevate; existing local roles preserved. Link revocation destroys local sessions. | Claim mappings/ceilings, independent elevation workflow and admission-revocation propagation to existing sessions. | +| F-16 | Partial | WordPress/concurrency tests: encrypted unique issuer/subject associations, explicit admin approval, conflicting-link refusal, unlink tombstones and session revocation. | Self-service local reauthentication and a dedicated association inventory/recovery UI. Audit is not tamper-evident. | +| F-17 | Partial | WordPress tests: changed subject refuses email relinking; changed email retains linked account. Explicit unlink/reapproval supported. | Guided, independently verified issuer/client/pairwise-subject migrations. | +| F-18 | Planned | Source review: existing profile fields are preserved; no claim mapping is performed. | Profile mappings, per-field policies, preview and validation. | +| F-19 | Planned | Source review: test result contains policy outcome only; routine logs omit claims/tokens. | Opt-in, encrypted, operator/transaction-scoped claim inspection and expiry. | +| F-20 | Partial | [Configuration](CONFIGURATION.md), [deployment tests](../tests/deployment.php), browser: complete supported settings in code/CLI/UI, deployment locks, stale form refusal, candidate testing and side-effect-free test login. | Revision history/automatic rollback, comprehensive accessibility evidence and mapping preview once mapping exists. Browser authentication remains necessary for a real operator test. | +| F-21 | Partial | Browser tests: WordPress sessions/local logout, confined return URLs, automatic redirect recovery. | Configurable SSO session policy and advertised RP/back-channel logout. | +| F-22 | Partial | [Emergency tests](../tests/emergency.php), browser: local recovery, constant override, ordinary/test in-flight refusal and latched invalidation. | Strong local MFA is host-managed; full upgrade/recovery exercises remain. Deployment must ensure every worker observes the constant. | +| F-23 | Partial | Browser/multisite tests and [uninstall](../simple-oauth-cimd-access/uninstall.php): scoped state, deactivation invalidation, explicit data erasure, preserved users/permissions. | Comprehensive lifecycle/migration/rollback testing. Existing sessions survive disable/deactivation. | +| F-24 | Supported | Provider/source review and token-exchange tests: no offline scope by default, codes/access/ID tokens used only within the request, no refresh-token retention. | Operators must request only scopes needed by their deployment. Delegated access is outside this profile. | +| F-25 | Supported | WordPress/concurrency/browser tests: encrypted ten-minute transients, independent browser-secret cookies, atomic single use, replay/copy refusal, parallel tabs, new WordPress authentication token. | Additional cookie justified below; all browser coverage uses Chromium. | +| N-01 | Partial | [Security](SECURITY.md), protocol negative tests, Psalm/WordPressCS/Semgrep checks. | Independent threat-model review and a defined cryptographic dependency update process. | +| N-02 | Partial | Http source/protocol tests: DNS pinning, all-address rejection, TLS checks, no redirects, response/deadline bounds. | Complete native IPv6/mixed-DNS/slow-response/egress integration matrix. | +| N-03 | Partial | Encrypted keys/transactions/links, no token retention or telemetry, public service disclosure and redacted audits. | Automatic link/report retention policy, backup deletion and verified infrastructure access-log redaction. | +| N-04 | Partial | Multisite and concurrent-process suites pass; routine cache/key overlap tested. | Failover/restore, rolling upgrades, durable revocation after backup restore and published recovery objectives. | +| N-05 | Partial | Source/protocol tests: fixed transaction/rate/cache/response bounds and refresh throttling. | Latency/throughput/resource budgets, sustained abuse/load evidence and aggregate transaction cleanup bounds. | +| N-06 | Partial | Browser UI checks, redacted failure references, Site Health and status commands. | WCAG 2.2 AA audit, tamper-evident audit storage, retention by time and security/availability metrics. | +| N-07 | Partial | Deterministic package builder, pinned Composer runtime dependency, dependency audit and security CI. | Immutable workflow/container references, signed provenance, formal SBOM, response SLA and release-blocking vulnerability policy. | +| N-08 | Partial | [Test record](TESTING.md): protocol, WordPress, browser, concurrency, multisite, static checks. | Live logins in both metadata modes, broader browsers/platforms, conformance suite, independent review, packaged fault/recovery coverage. | +| N-09 | Partial | This revision/digest and per-ID assessment; [configuration](CONFIGURATION.md), limits below, fixtures and [dated test record](TESTING.md). | Live provider profiles, measured performance/revocation budgets and acceptance results for the planned capabilities. | + +## Tested profiles and protected surfaces + +The protected entry points are the standard WordPress login button, optional +ordinary-login redirect and the `soca_start`/`soca_callback` actions. Local login, +password recovery and logout remain WordPress-managed. REST/API authorisation, +other grants and delegated access are outside this profile. + +| Metadata mode | Provider/profile | Result on 21 October 2026 | +| --- | --- | --- | +| Self-hosted | Synthetic ES256 and RS256 token validation; public metadata/JWKS generation | Protocol tests pass. A complete current self-hosted browser/provider login has not been run. | +| Proxy, inline JWKS | Synthetic ES256 provider, code/query/S256/private_key_jwt | Browser login, candidate test, cookie/replay failures and recovery pass. | +| Default Dynamic CIMD | Public document only | Historical 19 October round trip in [standards evidence](STANDARDS.md); no current real provider login. | +| RESOAuth | Live discovery/JWKS only | Historical observations in STANDARDS.md. End-user login in both modes remains unverified. | + +## Security limits and retention + +| Item | Default / fixed bound | Operator choice and implications | +| --- | --- | --- | +| Transaction | 600 seconds; encrypted WordPress transient; single database-locked consumer | Fixed. Per-transaction `__Host-soca_tx_*` cookie, 256-bit independent secret, Secure/HttpOnly/SameSite=Lax, host-only, path /; deleted after a consumed callback, otherwise expires. The extra cookie supplies binding absent from logged-out WordPress sessions. No browser JavaScript storage. | +| Client assertion | 60 seconds; fresh 256-bit jti | Fixed ES256/P-256; issuer audience by default, token endpoint may be selected explicitly. | +| ID token | 60 seconds clock tolerance; maximum exp-iat 86400 seconds | Issued no earlier than transaction start minus tolerance. Test login requires fresh auth_time. | +| Rotation | Target 604800 seconds; hourly scheduler | Provider cache window 24 hours, allowed 1–168 hours. Unknown provider cache bound must be established by the operator. Delays extend overlap safely. | +| Retiring key | Cache window plus 720 seconds after actual promotion | Covers 600-second transaction, 60-second assertion and 60-second skew. A reduced setting cannot shorten an existing retirement promise. | +| Documents/caches | Public CIMD/JWKS 300 seconds; discovery/provider JWKS at most 3600 seconds | Honour shorter max-age/Age and no-cache/no-store; no stale trust on failure. Publication reused for at most 300 seconds. | +| Proxy encoding | 8192 UTF-8 JSON bytes; 12288 client-ID URL bytes | Fixed local ceilings, including two overlapping public keys; actual provider/proxy limits may be lower and must be checked. Fixed field order, sorted public keys, unescaped Unicode/slashes, no whitespace or client_id in encoded JSON. | +| Network | 12-second request timeout; 5-second connect timeout; 256 KiB body; 32 KiB headers; zero redirects | DNS resolver wall-clock behaviour remains platform-dependent. HTTPS callback required even on localhost. | +| Rules | 200 entries and 32000 input bytes per list; domain <=253 bytes; email <=254 bytes | Exact public ASCII/punycode DNS names or one leading *. for domain lists; no single-label suffixes. | +| Abuse | 30 starts per server-observed IP per 600 seconds; one forced JWKS refresh per issuer/URL per 60 seconds | Shared reverse proxies share a limit. Add host/edge rate controls; aggregate storage is not globally capped. | +| Diagnostics/audit | Policy-only operator test result 600 seconds; CLI test ticket 600 seconds and single use; last 100 redacted audit entries | No claim inspection is implemented. Activation evidence lasts until the candidate fingerprint changes or is invalidated. Audit is not tamper-evident or time-expired. | +| Sessions/revocation | Native WordPress lifetime; unlink destroys all sessions for the selected account | Disable/deactivation stop new SSO and invalidate pending flows, retaining existing WordPress sessions. Admission edits apply on the next login; no bounded existing-session policy propagation is claimed. | +| Identity records | Encrypted active links and revocation tombstones retained until explicit erasure | Deleted/removed users do not silently reprovision through their old links. Uninstall erases associations only with SOCA_ERASE_DATA=true; protect/reconcile backups. | + +Inline key-set changes alter the client ID and invalidate the candidate test +fingerprint. This deliberately requires an operator test before further ordinary +SSO; it does not meet unattended, uninterrupted inline-proxy rotation. Use stable +JWKS indirection for production where supported. Never recover pairwise subjects +by matching mutable email claims. diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 39cb011..600d870 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -8,7 +8,7 @@ This document describes the implemented profile, not a formal certification or s | --- | --- | --- | | User identity | OIDC Core defines authentication; OAuth alone does not | Require OIDC, exact configured issuer, subject types, code response, verified email in ID token or subject-matched UserInfo. No OAuth-only identity inference. | | PKCE and request correlation | OAuth 2.1 draft 16, RFC 9700 and RFC 7636 | Always S256, including confidential requests; also independent 256-bit state and nonce. Require advertised S256. | -| Transactions | Replay and mix-up protection; partial browser check | Ten-minute encrypted WordPress transient keyed by a hash of random state, with a database lock around one-time consumption. Snapshot issuer, endpoints, client ID, callback, nonce, verifier, key ID, settings and a hash of the server-observed User-Agent. A settings save invalidates pending transactions. No SOCA transaction cookie is set. | +| Transactions | Replay, browser and mix-up protection | Ten-minute encrypted WordPress transient keyed by a hash of random state, with a database lock around one-time consumption. Snapshot issuer, endpoints, client ID, callback, nonce, verifier, key ID, settings and a hash of the server-observed User-Agent. A per-transaction Secure/HttpOnly/SameSite=Lax cookie supplies an independent 256-bit browser secret; its hash is encrypted with the transaction. Settings saves, deactivation and emergency disable invalidate pending transactions. | | Client authentication | RFC 7523 and OIDC private_key_jwt | ES256/P-256 only, `iss=sub=client_id`, audience the configured provider issuer or its exact discovered token endpoint, random `jti`, 60-second expiry. The audience is snapshotted with the transaction. Require advertised private_key_jwt and ES256. No client secrets or downgrade. | | Token signatures | OIDC Core, RFC 8725, RFC 7517 | Administrator pins ES256 or RS256 for ID tokens. Require `kid`; reject duplicate matching keys, `none`, HMAC, remote/embedded header keys, critical JOSE extensions and non-JWT `typ`. Use only the pinned issuer's discovered JWKS; never client signing keys. | | ID token claims | OIDC Core §3.1.3.7 | Exact issuer, nonempty ASCII subject ≤255 bytes, audience membership, `azp` required with multiple audiences and checked whenever present, exact nonce, signature, expiry, future `iat`/`nbf`, and hashes when present. 60-second clock tolerance, integer times, `iat` no earlier than transaction start minus tolerance, lifetime ≤24 hours. These last age/type bounds are stricter choices. | @@ -39,26 +39,45 @@ Cron delays, an unavailable proxy/mirror, slow caching or an operator changing p Discovery that explicitly reports `client_id_metadata_document_supported: false` is refused. An absent field is treated as unconfirmed support: the document check validates the generated metadata but a real test login is needed to establish provider acceptance. No vendor-specific discovery field is interpreted. -In proxy-inline mode, **staging/removing** a key changes the encoded client document and thus its URL. Switching the active signing key alone does not change the sorted two-key document. Pending transactions retain the old client ID and signing key and can finish within their ten-minute lifetime while their callback route remains available. Old immutable proxy URLs contain only public material. A changed pairwise subject may cause fresh provider consent, but account selection continues by the current verified email. +In proxy-inline mode, **staging/removing** a key changes the encoded client document and thus its URL. Switching the active signing key alone does not change the sorted two-key document. Old client IDs and signing keys remain available for the transaction window. However, key-set changes invalidate the candidate-test fingerprint and block ordinary SSO until retested; uninterrupted inline rollover is a remaining gap. Old immutable proxy URLs contain only public material. A changed pairwise subject requires independently verified administrator migration; email cannot recover it. Do not change salts or `SOCA_ENCRYPTION_KEY` without planning key recovery. Lost roots fail closed; restoring the original root restores encrypted keys. A new key set must go through fresh publication/cache checks and may affect upstream consent. Do not delete keys to force a weekly deadline. ## Accounts, concurrency and multisite -Account matching and creation use a database advisory lock shared across plugin sites in the same WordPress network. Duplicate local emails cause refusal. Concurrent plugin registrations converge on one account. Other extensions that create users independently do not share this lock; keep account provisioning controlled and resolve ambiguous emails explicitly. +Identity association and account creation use a database advisory lock shared across plugin sites in the same WordPress network. Unique issuer/subject hashes identify encrypted, non-autoloaded association options. Conflicting link approval is refused; concurrent registrations converge on one account and link. Duplicate local emails are refused when considering unlinked identities. Other extensions that create users independently do not share this lock; keep account provisioning controlled and resolve ambiguous emails explicitly. -Account creation uses a random local password and the Subscriber role. A failed WordPress insertion refuses login. No session is issued without selecting an eligible site member or creating a valid new account. +Account creation uses a random local password and the Subscriber role. A failed insertion or link write refuses login; a failed link write triggers deletion of the newly created account. This compensation does not provide a database transaction across WordPress hooks or process termination. These failure modes remain a gap. No session is issued without selecting an eligible site member or creating a valid new account. -Every login requires a valid, verified email from the pinned provider and applies the current deny and allow rules. The email selects the matching local account, including an administrator, on every login; existing local emails, roles and capabilities are not changed. A compromised or weakly verified upstream address can grant the matched WordPress role. The subject remains mandatory and validated for OIDC, including UserInfo consistency, but it is not used as a local account key. Account creation is a separate opt-in. Rate limits are per ten-minute HMAC of the server-observed IP (30 login starts); they do not trust arbitrary forwarded IP headers. Shared reverse proxies may share a limit. Apply your normal WordPress login/edge rate controls as well. +Every login requires a valid, verified email from the pinned provider and applies the current deny and allow rules. An approved issuer/subject association selects the eligible local account. An existing email match requires independent administrator approval and never establishes ownership. Existing emails, roles and capabilities are preserved; a changed email cannot switch accounts. A changed issuer/subject requires explicit migration. Unlinking retains an encrypted revocation record, destroys all sessions for that account and invalidates transaction/activation evidence. Revoked identities cannot silently reprovision. Account creation is a separate opt-in. Rate limits are per ten-minute HMAC of the server-observed IP (30 login starts); they do not trust arbitrary forwarded IP headers. Shared reverse proxies may share a limit. Apply your normal WordPress login/edge rate controls as well. -Each site's options, encryption context, metadata URLs, transaction transients and admission rules are independent. Network-wide users are never silently added to another site. Removing a user from one site prevents matching that account on that site. Deactivation and uninstall retain plugin data by default. +Each site's options, encryption context, metadata URLs, transaction transients and admission rules are independent. Network-wide users are never silently added to another site. Removing a user from one site prevents that association from authenticating on that site. Deactivation and uninstall retain plugin data by default. -## Cookie-free callback limitation +## Browser binding and recovery -The callback requires the same server-observed User-Agent as the login start. This is a best-effort check: another browser with the same User-Agent can still use an unused callback URL to sign in as the initiator (login CSRF). IP is not bound because the site may sit behind a proxy and client IPs can change during login. WordPress sets its normal authentication cookies after a successful login. +Logged-out WordPress visitors have no authenticated platform session to bind an +OIDC transaction to. The plugin therefore uses one short-lived `__Host-soca_tx_*` +cookie per transaction, with no Domain attribute, path /, Secure, HttpOnly and +SameSite=Lax. Independent random cookie values are never placed in URLs or +JavaScript-readable storage. The encrypted transient contains only their hashes +alongside the verifier, nonce and expected context. User-Agent matching remains +an additional check. A copied callback in a browser with the same User-Agent is +refused without consuming the original browser's transaction. The cookie is +deleted after consumption or expires after ten minutes; abandoned transient data +expires through WordPress. Database locking enforces one consumer across workers. + +SOCA_CONFIG values override defaults/database values at runtime, with GUI locks. +Invalid deployment configuration hides the SSO button/redirect while preserving +local login. SOCA_DISABLED blocks ordinary and operator test login, and latches a +new persisted security epoch when observed. Host deployment/opcode-cache +propagation determines when each worker observes new code/constants. Run status +with the flag present on rollout. Disable/deactivation retain existing WordPress +sessions; general admission changes have no existing-session propagation bound. ## Data and extension boundaries -Access and refresh tokens are never saved to establish a WordPress session. A Bearer access token, if needed for UserInfo, exists only during that request and is sent only to the discovered HTTPS endpoint; UserInfo subject must exactly match the verified ID token. The last 100 audit entries contain timestamps, fixed event/step/reason codes, a random 12-character login reference, optional HTTP status or cURL error number, optional exception class for unexpected failures, and local user IDs after account selection. No claims, addresses, tokens, raw provider errors or telemetry are stored. +Access and refresh tokens are never saved to establish a WordPress session. A Bearer access token, if needed for UserInfo, exists only during that request and is sent only to the discovered HTTPS endpoint; UserInfo subject must exactly match the verified ID token. The last 100 audit entries contain timestamps, fixed event/step/reason codes, a random 12-character login reference, optional HTTP status or cURL error number, optional exception class for unexpected failures, and local actor/target user IDs. No claims, addresses, tokens, raw provider errors or telemetry are stored. + +Settings and link writes in the GUI require `manage_options` and a WordPress nonce. WP-CLI assumes a trusted deployment operator; identity changes and test URLs additionally require a named administrator and that operator’s existing local browser session. Test tickets expire in ten minutes and are consumed once. Candidate fingerprints bind activation to effective settings, callback, generated metadata and security epoch. Ordinary enable/automatic switches alone preserve otherwise unchanged test evidence. Output is escaped. Public metadata contains no policy lists, user data, private material or tokens. The `soca_http` filter allows trusted PHP integration/test code to supply a `SOCA\Http` implementation. Neither is an administrator UI or untrusted request setting. Test fixtures use this boundary and are excluded from releases. -All settings writes require `manage_options` and a WordPress nonce. Output is escaped. Public metadata contains no policy lists, user data, private material or tokens. The `soca_http` filter allows trusted PHP integration/test code to supply a `SOCA\Http` implementation. Neither is an administrator UI or untrusted request setting. Test fixtures use this boundary and are excluded from releases. +The [shared requirements assessment](REQUIREMENTS.md) records remaining security and evidence gaps. [Deployment configuration](CONFIGURATION.md) defines settings precedence and recovery. Restore can revive old links or evidence: reconcile revocations before returning a backup to service. No tamper-evident audit or restore-safe revocation ledger is claimed. diff --git a/docs/TESTING.md b/docs/TESTING.md index dc4684d..7a16239 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -1,12 +1,14 @@ # Test record and reproduction +The **0.3.0 unreleased** requirements review was validated on **20–21 October 2026 (Europe/London)** against isolated disposable WordPress 7.1.3 / PHP 8.3 installations and MariaDB 11.4. The 31-group protocol suite passed on PHP 8.1, 8.3 and 8.5; the 23-group WordPress suite, two deployment-lock checks, emergency-disable check, three concurrent-process scenarios and seven multisite groups passed. All 22 Chromium browser scenarios passed, including copied callbacks with identical User-Agents, parallel tabs, candidate gating and emergency disable during ordinary and operator-test flows. Psalm, WordPressCS and all 10 local Semgrep rule fixtures passed with no production findings. PHP/JavaScript syntax, dependency advisory audit, release metadata and deterministic ZIP checks passed. Browser tests wait for web workers to observe deployment changes through PHP opcode caching; production deployment must manage that propagation. These tests use synthetic providers; live RESOAuth user login and current self-hosted end-to-end login remain unverified. The assessed requirements revision and per-ID gaps are in [REQUIREMENTS.md](REQUIREMENTS.md). + The baseline browser and multisite runs were executed on 16 October 2026 with containerized WordPress **7.1.3**, PHP **8.3.35**, MariaDB **11.4**, and Caddy **2.10**. Browser: headless Chrome **153** through Playwright **1.56.1**. The host has Podman 5.7 / podman-compose 1.5. PHP 8.1 is the declared minimum; the shipped code was executed on PHP 8.3, not every supported PHP/WordPress combination. -For **SOCA 0.0.3**, the 27-group protocol suite, 19-group WordPress suite, two concurrency scenarios, seven-group multisite suite, PHP syntax checks, dependency advisory audit, release metadata check and ZIP checksum/structure checks passed on 18 October 2026. A real failed start request returned a reference that matched a `login_failed` audit event. The browser suite has not been rerun for 0.0.3. +For **SOCA 0.0.3**, the 27-group protocol suite, 19-group WordPress suite, two historical concurrency scenarios, seven-group multisite suite, PHP syntax checks, dependency advisory audit, release metadata check and ZIP checksum/structure checks passed on 18 October 2026. A real failed start request returned a reference that matched a `login_failed` audit event. The browser suite has not been rerun for 0.0.3. For **SOCA 0.0.4**, the 27-group protocol suite and 19-group WordPress suite passed on 18 October 2026. A real callback without the browser cookie returned `browser_cookie_missing` and reused the transaction's audit reference. The browser suite has not been rerun for 0.0.4. -For **SOCA 0.0.5**, the direct callback does not use a SOCA transaction cookie and checks the User-Agent. On 18 October 2026, the 27-group protocol suite, 19-group WordPress suite, 18-scenario browser suite, two concurrency scenarios and package checks passed against an isolated local fixture. The multisite fixture and a live RESOAuth user login were not run for this change. +For **SOCA 0.0.5**, the direct callback does not use a SOCA transaction cookie and checks the User-Agent. On 18 October 2026, the 27-group protocol suite, 19-group WordPress suite, 18-scenario browser suite, two historical concurrency scenarios and package checks passed against an isolated local fixture. The multisite fixture and a live RESOAuth user login were not run for this change. For **SOCA 0.1.0**, outbound HTTPS uses the WordPress HTTP API with cURL DNS pinning. On 19 October 2026, the 27-group protocol suite and 19-group WordPress suite passed. A live GET of RESOAuth discovery succeeded through the new transport; a public redirect returned HTTP 302 without following it, an oversized response was rejected, and a form POST reached a public echo endpoint. The new Dynamic CIMD default returned the exact fetch URL as `client_id` with all public fixture fields unchanged. PHP and JavaScript syntax checks, Composer validation/advisory audit, release metadata check, and ZIP checksum/structure checks also passed. Composer validation reported its advisory warning for the deliberately exact JWT dependency version. WordPress Plugin Check 2.1.0 found zero errors and 70 warnings against the mounted development plugin; the packaged plugin also includes `composer.json`, which addresses the missing-manifest warning. The other warnings include public callback nonce checks, direct queries for atomic transactions, and input handling that require manual context review. The official readme validator returned no errors and notes for optional Contributors, Upgrade Notice, Screenshots and Donate fields. The browser, concurrency and multisite suites have not been rerun for 0.1.0. Live RESOAuth end-user login remains unverified. @@ -19,10 +21,10 @@ For the current **SOCA 0.2.0** refactor on 19 October 2026, the 28-group protoco | Suite | Coverage | | --- | --- | | `tests/protocol.php` | PKCE published vector; strict encodings; proxy templates, exact client ID and metadata; private material rejection; public-address filtering; HTTP cache bounds; deny/allow precedence, exact domains and normalization; local redirects; discovery capability refusal; encryption/tampering/thumbprints/assertions; delayed weekly rollover and immutable retirement deadlines; unpublished active key refusal; ES256 and RS256 signatures; issuer/audience/azp/nonce/time/hash/header checks; client/provider key separation; controlled JWKS refresh; token exchange and UserInfo subject binding; URL query injection protection. | -| `tests/wordpress.php` | Non-autoloaded encrypted keys; public/local activation defaults; allow-any saves with preserved hidden allowlists and deny precedence; inline saved access-rule explanation and section anchor; renamed callback hook and absent profile panel; single-use encrypted transients and missing-state refusal; verified-email matching for ordinary and administrator accounts on every login despite subject changes; registration gating/Subscriber-only creation; ambiguous emails; existing capabilities; redacted failure steps and references. | -| `tests/concurrency.py` | Two independent PHP/WordPress processes race on one callback and on one account creation. Exactly one transaction consumer and one account. | +| `tests/wordpress.php`, `tests/deployment.php`, `tests/emergency.php` | Current regression checks cover protected identity links/revocation/rollback, browser-bound transactions, deployment precedence/locks, stale settings and activation gating. Historical checks include non-autoloaded encrypted keys; public/local activation defaults; allow-any saves with preserved hidden allowlists and deny precedence; inline saved access-rule explanation and section anchor; renamed callback hook and absent profile panel; single-use encrypted transients and missing-state refusal; approved issuer/subject account selection and refusal of email-only or changed-subject selection; registration gating/Subscriber-only creation; ambiguous emails; existing capabilities; redacted failure steps and references. | +| `tests/concurrency.py` | Independent PHP/WordPress processes race on one callback, linked-account creation and conflicting identity approval. Exactly one consumer, account and link owner. | | `tests/browser.cjs` | Real HTTPS browser/WordPress requests with a synthetic provider transport. Full authorization/code/assertion/PKCE/ID-token/session flow, replay, bad nonce/issuer/time, unverified email, cancellation, automatic mode, local recovery/password flow, redirect confinement, admin UI/bulk input, public-document validation, test login preserving admin session, absence of profile identity controls, and logout avoiding loops. | -| `tests/multisite.php` | Independent settings, keys, encryption contexts and transactions; nonmember refusal; email matching after subject changes; site removal without affecting another site's access; network deletion and spam-account refusal. | +| `tests/multisite.php` | Independent settings, keys, encryption contexts and transactions; nonmember refusal; independent approved identity links and changed-subject refusal; site removal without affecting another site's access; network deletion and spam-account refusal. | Synthetic profiles use actual OpenSSL-generated signing keys and real JWT signatures. The mock token endpoint checks code/client/redirect binding, S256 proof and the signed client assertion. It is not a fake boolean "login passed" hook. Outbound HTTP responses are supplied at the explicit trusted `soca_http` test boundary; this does **not** claim full native-transport coverage for every network fault. Native transport was additionally used to fetch live RESOAuth discovery successfully, and public documents were fetched over the running WordPress HTTPS server. Syntax checks and Composer advisory audit also passed. diff --git a/simple-oauth-cimd-access/assets/admin.js b/simple-oauth-cimd-access/assets/admin.js index 08b6544..1e7be00 100644 --- a/simple-oauth-cimd-access/assets/admin.js +++ b/simple-oauth-cimd-access/assets/admin.js @@ -2,6 +2,7 @@ // Progressive enhancement: the textarea remains the submitted, server-validated source. document.querySelectorAll('.soca-policy').forEach((box) => { const source = box.querySelector('textarea'); + if (source.disabled) return; const kind = box.dataset.kind; const editor = document.createElement('div'); const input = document.createElement('input'); @@ -13,7 +14,7 @@ document.querySelectorAll('.soca-policy').forEach((box) => { input.setAttribute('aria-describedby', feedback.id); const chips = document.createElement('ul'); chips.className = 'soca-chips'; const domain = (s) => s.length <= 253 && /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(s) && !/(^|\.)(localhost|local|test|invalid|example|internal|lan|home|localdomain)$/.test(s) && !s.endsWith('.home.arpa'); - const valid = (s) => kind === 'domain' ? domain(s) : s.length <= 254 && /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9.-]+$/.test(s) && domain(s.split('@')[1]); + const valid = (s) => kind === 'domain' ? domain(s.startsWith('*.') ? s.slice(2) : s) : s.length <= 254 && /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9.-]+$/.test(s) && domain(s.split('@')[1]); let entries = source.value.split(/[,;\s]+/).filter(Boolean); const draw = () => { source.value = entries.join('\n'); chips.replaceChildren(); @@ -49,7 +50,7 @@ if (allowAny) { const syncAllowLists = () => { document.querySelectorAll('.soca-policy[data-policy="allow"]').forEach((box) => { box.hidden = allowAny.checked; - box.querySelectorAll('input, textarea, button').forEach((control) => { control.disabled = allowAny.checked; }); + box.querySelectorAll('input, textarea, button').forEach((control) => { if (box.dataset.locked !== '1') control.disabled = allowAny.checked; }); }); }; allowAny.addEventListener('change', syncAllowLists); diff --git a/simple-oauth-cimd-access/includes/Admin.php b/simple-oauth-cimd-access/includes/Admin.php index e75f0d5..2651212 100644 --- a/simple-oauth-cimd-access/includes/Admin.php +++ b/simple-oauth-cimd-access/includes/Admin.php @@ -5,14 +5,14 @@ public static function boot(): void { add_action('admin_menu', static function () { add_options_page('Simple OAuth CIMD Access','SOCA','manage_options','simple-oauth-cimd-access',[self::class,'page']); }); add_action('admin_enqueue_scripts', static function ($hook) { if ($hook==='settings_page_simple-oauth-cimd-access') { - wp_enqueue_script('soca-admin',plugins_url('assets/admin.js',SOCA_FILE),[], '0.2.0',true); - wp_enqueue_style('soca-admin',plugins_url('assets/admin.css',SOCA_FILE),[], '0.2.0'); + wp_enqueue_script('soca-admin',plugins_url('assets/admin.js',SOCA_FILE),[], '0.3.0',true); + wp_enqueue_style('soca-admin',plugins_url('assets/admin.css',SOCA_FILE),[], '0.3.0'); } }); add_filter('site_status_tests',static function ($tests) { $tests['direct']['soca']=['label'=>'SOCA','test'=>[self::class,'health']]; return $tests; }); add_filter('debug_information',static function ($info) { $s=Settings::get(); $info['soca']=['label'=>'Simple OAuth CIMD Access','fields'=>[ - 'version'=>['label'=>'Version','value'=>'0.2.0'], 'mode'=>['label'=>'Metadata mode','value'=>$s['mode']], + 'version'=>['label'=>'Version','value'=>'0.3.0'], 'mode'=>['label'=>'Metadata mode','value'=>$s['mode']], 'enabled'=>['label'=>'Enabled','value'=>$s['enabled'] && !Settings::disabled()?'yes':'no'], 'cron'=>['label'=>'Maintenance','value'=>wp_next_scheduled('soca_maintenance')?'scheduled':'missing']]]; return $info; }); @@ -26,14 +26,15 @@ public static function health(): array { 'description'=>'

Review provider compatibility, public key publication, weekly rollover and the latest test login. Cron delays or provider caching can safely delay rollover. Inline proxy keys change the client identifier.

', 'actions'=>'Review SOCA','test'=>'soca']; } + private static function locked(string $key): string { return array_key_exists($key, Settings::deployment()) ? ' disabled' : ''; } private static function input(string $key, string $label, array $s, string $help='', string $type='text'): void { - echo '

' . esc_html($help) . '

'; + echo '

' . esc_html($help) . '

'; } private static function checkbox(string $key, string $label, array $s): void { - echo '

'; + echo '

'; } private static function select(string $key, string $label, array $choices, array $s): void { - echo ''; foreach ($choices as $v=>$text) { echo ''; } echo ''; } @@ -44,7 +45,17 @@ public static function page(): void { check_admin_referer('soca_settings'); try { $action=Support::scalar($_POST,'operation',20); - if ($action==='save') { Settings::save(wp_unslash($_POST)); $notice='Settings saved. Run connection validation, then test login.'; } + if ($action==='save') { + $input = wp_unslash($_POST); + foreach (['enabled','automatic','create_users','unrestricted'] as $key) { $input[$key] = isset($input[$key]) ? '1' : '0'; } + Settings::save($input); $notice='Settings saved. Run connection validation, then test login.'; } + elseif ($action==='link' || $action==='unlink') { + $id = filter_var(Support::scalar(wp_unslash($_POST),'link_user'), FILTER_VALIDATE_INT); + Support::need($id !== false && $id > 0, 'identity', 'Enter an existing local user ID.'); + $issuer = Support::scalar(wp_unslash($_POST),'link_issuer'); $subject = Support::scalar(wp_unslash($_POST),'link_subject',255); + if ($action==='link') { Identity::link($id,$issuer,$subject); } else { Identity::unlink($id,$issuer,$subject); } + $notice='Identity association updated.'; + } elseif ($action==='check') { $result=Plugin::check(); $notice='Discovery and published client document passed validation. A test login is still required.'; } elseif ($action==='policy') { $policyEmail=Support::scalar(wp_unslash($_POST),'test_email',254); $policyVerified=isset($_POST['verified']); @@ -63,17 +74,20 @@ public static function page(): void { echo '

The provider and site defaults are ready to review. Save any changes, validate the connection and try a test login. Local WordPress login remains available. The default issuer is the RESOAuth hosted gateway; review its privacy notice and terms of service.

'; if ($notice) { echo '

' . esc_html($notice) . '

'; } $test=get_transient('soca_test_' . get_current_user_id()); - if ($test) { echo '

Test login: cryptographic OIDC validation succeeded. Admission policy: ' . esc_html($test['message']) . ' No account or session was changed.

'; } + if ($test && ($test['revision'] ?? '') === $s['revision']) { echo '

Test login: cryptographic OIDC validation succeeded. Admission policy: ' . esc_html($test['message']) . ' No account or session was changed.

'; } if (Settings::disabled()) { echo '

SOCA is disabled by configuration. Upstream login is disabled.

'; } + if (!Plugin::verified($s)) { echo '

Ordinary SSO is unavailable until an admitted test login succeeds for this candidate configuration. Save the candidate, validate documents and complete Test login first.

'; } + if (Settings::deployment()) { echo '

Deployment-managed fields are disabled. Effective values use defaults, saved settings, then SOCA_CONFIG. Locked fields: ' . esc_html(implode(', ',array_keys(Settings::deployment()))) . '. Use wp soca config to inspect values and locks.

'; } $host=(string)wp_parse_url(home_url('/'),PHP_URL_HOST); if (Support::localHost($host)) { echo '

Local development detected. Use HTTPS with a certificate your browser trusts. Proxy + inline public keys are selected because a cloud provider cannot fetch localhost metadata or JWKS. Add an allowed email/domain or select Allow any verified email, then enable login. Rotating inline keys changes the client identifier and may require fresh provider consent.

'; } $recoveryUrl=Plugin::recoveryUrl(); echo '

Recovery URL: ' . esc_html($recoveryUrl) . '

'; - echo '
'; wp_nonce_field('soca_settings'); echo '

Provider and public metadata

'; + echo ''; wp_nonce_field('soca_settings'); echo '

Provider and public metadata

'; self::input('provider','Provider display name',$s); self::input('button','Login button label',$s,'Edit this label when changing provider.'); self::input('issuer','Exact issuer',$s,'HTTPS issuer from the provider. Never inferred from email or incoming requests.','url'); echo '
Client metadata and advanced provider settings'; + foreach (['client_name'=>'Application name','client_uri'=>'Application home URL','logo_uri'=>'Application logo URL','policy_uri'=>'Privacy policy URL','tos_uri'=>'Terms of service URL'] as $key=>$label) { self::input($key,$label,$s,'Leave blank to use an available WordPress default. Optional unavailable fields are omitted. Public HTTPS URLs only.'); } self::input('scopes','Scopes',$s,'Space separated. openid and email are required. Verified email claims must be in the ID token or subject-matched UserInfo.'); self::select('id_alg','ID token signature',['ES256'=>'ES256 / P-256','RS256'=>'RS256 / RSA ≥ 2048 bits'],$s); self::select('assertion_audience','Client assertion audience',['issuer'=>'Provider issuer','token_endpoint'=>'Token endpoint URL'],$s); @@ -84,13 +98,13 @@ public static function page(): void { self::input('cache_hours','Provider cache safety window (hours)',$s,'Default 24 hours. Confirm the provider’s maximum metadata/JWKS cache duration; use at least that long. 1–168 hours. Longer overlap can delay weekly rollover.','number'); echo '
'; echo '

Proxy + inline keys changes the client identifier when published keys rotate. A stable public JWKS URL keeps that identifier stable. Connection validation checks the actual published document.

'; - echo '

Access rules

Only verified emails are admitted. Deny rules always win. Domains match exactly; subdomains need separate entries. Emails are matched case-insensitively. Use ASCII or punycode domains.

'; + echo '

Access rules

Only verified emails are admitted. Deny rules always win. Exact domains match only themselves. *.example.com matches one or more subdomain labels, including a.b.example.com, and excludes example.com. Emails are matched case-insensitively. Use ASCII or punycode domains.

'; self::checkbox('unrestricted','Allow any verified email/domain (deny rules still apply)',$s); foreach (['allow_domains'=>'Allowed domains','deny_domains'=>'Denied domains','allow_emails'=>'Allowed emails','deny_emails'=>'Denied emails'] as $key=>$label) { - echo '

One per line, or paste entries separated by commas, spaces or semicolons. Maximum 200 entries.

'; + echo '

One per line, or paste entries separated by commas, spaces or semicolons. Maximum 200 entries.

'; } - echo '

Accounts and login

On every login, a verified email from this configured provider selects the matching local account, including an administrator. The local account’s role is preserved. A changed provider subject does not require relinking. Use a provider you trust to verify the emails in your allow policy.

'; - self::checkbox('create_users','Create missing accounts as Subscribers after verified-email policy admission. Existing roles are never changed.',$s); + echo '

Accounts and login

Returning users are selected by an administrator-approved issuer/subject link. Verified email is used for admission only. An existing email match never grants access by itself. Changed subjects require explicit linking; roles and local profile fields are preserved.

'; + self::checkbox('create_users','Create missing accounts and identity links as Subscribers after verified-email policy admission. Existing roles are never changed.',$s); self::checkbox('enabled','Enable the upstream button on the standard WordPress login screen.',$s); self::checkbox('automatic','Automatically redirect ordinary GET visits to wp-login.php upstream. The recovery URL, logout, reset, interim and reauthentication flows remain local.',$s); submit_button('Save settings'); echo '
'; @@ -110,6 +124,8 @@ public static function page(): void { echo '' . esc_html(($policyResult['allowed']?'Allowed':'Denied') . ' for ' . $policyEmail . ': ' . $policyResult['message']) . ''; } echo ''; + echo '

Approve or remove an identity link

Verify ownership independently before approving. Obtain the exact subject from your trusted provider. Unlinking ends all sessions for this local account and invalidates pending SOCA transactions and activation evidence. Local account credentials are preserved.

'; wp_nonce_field('soca_settings'); + echo '

'; echo '

Operations

Signing keys rotate weekly after the replacement has been published for the cache safety window. Old keys remain for the window plus 12 minutes. A missed cron or unreachable mirror delays rotation. Keep WordPress salts stable, protect database backups, and run wp soca maintain hourly using real cron on low-traffic sites.

'; echo '

To recover, use the recovery URL above, wp soca disable, or set define(\'SOCA_DISABLED\', true); in wp-config.php. A failed login shows a reference that matches a redacted audit event below. Logout ends the WordPress session only.

'; try { echo '
Key publication and maintenance details
' . esc_html(json_encode(Plugin::status(),JSON_PRETTY_PRINT)) . '
'; } catch (\Throwable $e) { echo '

Cannot read keys. Restore encryption configuration from backup.

'; } diff --git a/simple-oauth-cimd-access/includes/Http.php b/simple-oauth-cimd-access/includes/Http.php index 1c44295..e88f82c 100644 --- a/simple-oauth-cimd-access/includes/Http.php +++ b/simple-oauth-cimd-access/includes/Http.php @@ -41,7 +41,7 @@ public function request(string $url, ?array $form = null, ?string $bearer = null } $args = ['method'=>$form === null ? 'GET' : 'POST', 'headers'=>$headers, 'timeout'=>12, 'redirection'=>0, 'sslverify'=>true, 'blocking'=>true, - 'decompress'=>false, 'limit_response_size'=>262145, 'user-agent'=>'SOCA/0.2.0']; + 'decompress'=>false, 'limit_response_size'=>262145, 'user-agent'=>'SOCA/0.3.0']; if ($form !== null) { $args['headers']['Content-Type'] = 'application/x-www-form-urlencoded'; $args['body'] = http_build_query($form, '', '&', PHP_QUERY_RFC3986); diff --git a/simple-oauth-cimd-access/includes/Identity.php b/simple-oauth-cimd-access/includes/Identity.php index eb735a0..6539f3d 100644 --- a/simple-oauth-cimd-access/includes/Identity.php +++ b/simple-oauth-cimd-access/includes/Identity.php @@ -3,28 +3,75 @@ final class Identity { private static function eligible(\WP_User $user): void { Support::need(empty($user->spam) && empty($user->deleted), 'account_blocked', 'The local account is marked as spam or deleted.'); + Support::need(is_user_member_of_blog($user->ID) && $user->exists() && (bool)$user->roles && $user->has_cap('read'), 'account_missing', 'The linked local account has no access to this site.'); + } + private static function key(string $issuer, string $subject): string { + Http::url($issuer); + Support::need($subject !== '' && strlen($subject) <= 255 && !preg_match('/[^\x20-\x7e]/', $subject), 'subject', 'Enter the exact OIDC subject, 1–255 ASCII bytes.'); + return 'soca_link_' . hash('sha256', Support::json([$issuer,$subject])); + } + /** Called only after an authorised local administrator approves the exact identity. */ + public static function link(int $userId, string $issuer, string $subject): void { + Store::locked('accounts', static function () use ($userId,$issuer,$subject) { + $key = self::key($issuer,$subject); $old = get_option($key); + $user = get_user_by('id', $userId); + Support::need($user instanceof \WP_User, 'account_missing', 'The local account does not exist.'); self::eligible($user); + if ($old) { + $previous = Store::open($old); + if (empty($previous['revoked'])) { + Support::need($previous['user'] === $userId, 'identity_conflict', 'This identity is already linked to another account. Unlink it explicitly first.'); + return; + } + Support::need(update_option($key, Store::seal(['issuer'=>$issuer,'subject'=>$subject,'user'=>$userId]), false), 'identity_conflict', 'The revoked identity could not be approved.'); + Support::audit('identity_linked', $userId); return; + } + Support::need(add_option($key, Store::seal(['issuer'=>$issuer,'subject'=>$subject,'user'=>$userId]), '', false), 'identity_conflict', 'The identity was linked concurrently.'); + Support::audit('identity_linked', $userId); + }); + } + public static function unlink(int $userId, string $issuer, string $subject): void { + Store::locked('accounts', static function () use ($userId,$issuer,$subject) { + $key = self::key($issuer,$subject); $old = get_option($key); + Support::need(is_string($old) && Store::open($old)['user'] === $userId, 'identity_conflict', 'The specified account does not own this link.'); + Support::need(update_option($key, Store::seal(['issuer'=>$issuer,'subject'=>$subject,'user'=>$userId,'revoked'=>true]), false), 'identity_conflict', 'The identity link could not be revoked.'); + \WP_Session_Tokens::get_instance($userId)->destroy_all(); + Settings::invalidate(); + Support::audit('identity_unlinked', $userId); + }); } public static function resolve(array $claims, array $s): \WP_User { $email = Policy::email(is_string($claims['email'] ?? null) ? $claims['email'] : ''); [$allowed,$why] = Policy::test($s, $email, ($claims['email_verified'] ?? false) === true); Support::need($allowed, 'access_denied', $why); - return Store::locked('accounts', static function () use ($email,$s) { - // WordPress does not enforce unique email addresses at the database level. - $ids = get_users(['search'=>$email, 'search_columns'=>['user_email'], 'fields'=>'ID', 'number'=>3, 'blog_id'=>0]); - Support::need(count($ids) <= 1, 'ambiguous_email', 'Multiple local accounts have this email; resolve the duplicate before login.'); - if ($ids) { - $user = get_user_by('id', $ids[0]); - Support::need($user instanceof \WP_User && is_user_member_of_blog($user->ID), 'account_missing', 'Matching local account is unavailable on this site.'); - self::eligible($user); - return $user; + Support::need(($claims['iss'] ?? null) === $s['issuer'], 'issuer', 'Identity issuer does not match this profile.'); + $key = self::key($s['issuer'], Support::scalar($claims, 'sub')); + return Store::locked('accounts', static function () use ($email,$s,$key,$claims) { + $sealed = get_option($key); + if ($sealed) { + $link = Store::open($sealed); + Support::need(empty($link['revoked']), 'identity_revoked', 'This identity was unlinked. Administrator approval is required before reuse.'); + $user = get_user_by('id', $link['user']); + Support::need($user instanceof \WP_User, 'account_missing', 'The linked account was removed. Administrator recovery is required.'); + self::eligible($user); return $user; } - Support::need($s['create_users'], 'registration_disabled', 'No local account exists. Plugin registration is disabled.'); - $id = wp_insert_user(['user_login'=>'soca_' . substr(hash('sha256', $email),0,24),'user_pass'=>wp_generate_password(48,true,true),'user_email'=>$email,'role'=>'subscriber']); + // Email can suggest an account, but cannot establish ownership of it. + $ids = get_users(['search'=>$email, 'search_columns'=>['user_email'], 'fields'=>'ID', 'number'=>3, 'blog_id'=>0]); + Support::need(count($ids) <= 1, 'ambiguous_email', 'Multiple local accounts have this email; resolve the duplicate before linking.'); + Support::need(!$ids, 'identity_unlinked', 'This identity needs an administrator-approved link to the existing account.'); + Support::need($s['create_users'], 'registration_disabled', 'No linked account exists. Plugin registration is disabled.'); + $id = wp_insert_user(['user_login'=>'soca_' . substr(hash('sha256', $key),0,24),'user_pass'=>wp_generate_password(48,true,true),'user_email'=>$email,'role'=>'subscriber']); Support::need(!is_wp_error($id), 'account_create', 'Could not create the local subscriber account.'); - $user = get_user_by('id', $id); - Support::need($user instanceof \WP_User, 'account_create', 'The created local account could not be loaded.'); - self::eligible($user); - Support::audit('account_created', $user->ID); + try { + $user = get_user_by('id', $id); + Support::need($user instanceof \WP_User, 'account_create', 'The created local account could not be loaded.'); self::eligible($user); + Support::need(add_option($key, Store::seal(['issuer'=>$s['issuer'],'subject'=>$claims['sub'],'user'=>(int)$id]), '', false), 'identity_conflict', 'The identity was linked concurrently.'); + } catch (\Throwable $e) { + require_once ABSPATH . 'wp-admin/includes/user.php'; + if (is_multisite()) { require_once ABSPATH . 'wp-admin/includes/ms.php'; wpmu_delete_user((int)$id); } + else { wp_delete_user((int)$id); } + throw $e; + } + Support::audit('account_created', (int)$id); Support::audit('identity_linked', (int)$id); return $user; }); } diff --git a/simple-oauth-cimd-access/includes/Metadata.php b/simple-oauth-cimd-access/includes/Metadata.php index 83dbab9..8bde4a6 100644 --- a/simple-oauth-cimd-access/includes/Metadata.php +++ b/simple-oauth-cimd-access/includes/Metadata.php @@ -11,10 +11,17 @@ public static function proxyTemplate(string $template): void { Http::url(str_replace('%s', 'e30', $template)); } public static function template(array $s): array { - $doc = ['client_name'=>get_bloginfo('name'), 'client_uri'=>home_url('/'), + $doc = ['client_name'=>$s['client_name'] ?: wp_strip_all_tags(get_bloginfo('name')), 'client_uri'=>$s['client_uri'] ?: home_url('/'), 'redirect_uris'=>[self::callback()], 'grant_types'=>['authorization_code'], 'response_types'=>['code'], 'scope'=>$s['scopes'], 'application_type'=>'web', 'token_endpoint_auth_method'=>'private_key_jwt', 'token_endpoint_auth_signing_alg'=>'ES256', 'id_token_signed_response_alg'=>$s['id_alg']]; + $optional = ['logo_uri'=>get_site_icon_url(), 'policy_uri'=>get_privacy_policy_url(), 'tos_uri'=>'']; + foreach ($optional as $key=>$default) { + $url = $s[$key] ?: $default; + if ($url === '') { continue; } + try { Http::url($url); $doc[$key] = $url; } + catch (Failure $e) { Support::need($s[$key] === '', 'metadata_url', 'Metadata overrides require public HTTPS URLs.'); } + } if ($s['key_mode'] === 'inline') { $doc['jwks'] = Keys::jwks(); } else { $doc['jwks_uri'] = $s['jwks_url'] ?: self::jwksUrl(); } return $doc; @@ -22,7 +29,10 @@ public static function template(array $s): array { public static function clientId(array $s): string { if ($s['mode'] === 'self') { return self::url(); } self::proxyTemplate($s['proxy']); - $url = str_replace('%s', Support::b64(Support::json(self::template($s))), $s['proxy']); + $json = Support::json(self::template($s)); + Support::need(strlen($json) <= 8192, 'proxy_size', 'Proxy metadata exceeds the 8192-byte public JSON limit. Use a stable JWKS URL or reduce metadata.'); + $url = str_replace('%s', Support::b64($json), $s['proxy']); + Support::need(strlen($url) <= 12288, 'proxy_size', 'Proxy client identifier exceeds the 12288-byte URL limit.'); Http::url($url); return $url; } public static function document(array $s, bool $self = false): array { diff --git a/simple-oauth-cimd-access/includes/Plugin.php b/simple-oauth-cimd-access/includes/Plugin.php index 4b492a2..bf69ad9 100644 --- a/simple-oauth-cimd-access/includes/Plugin.php +++ b/simple-oauth-cimd-access/includes/Plugin.php @@ -27,13 +27,35 @@ public static function boot(): void { $cli = static function ($args) { $command = $args[0] ?? 'status'; try { - if ($command === 'disable') { $s=Settings::get(); $s['enabled']=false; $s['automatic']=false; $s['revision']=Support::random(); update_option('soca_settings',$s,false); \WP_CLI::success('SOCA login disabled.'); } + if ($command === 'disable') { Settings::save(['enabled'=>false,'automatic'=>false]); Settings::invalidate(); \WP_CLI::success('Pending transactions invalidated. SOCA_DISABLED=true overrides deployment-locked enablement.'); } + elseif ($command === 'configure') { + Support::need(isset($args[1]) && is_file($args[1]), 'configuration', 'Usage: wp soca configure /path/to/settings.json'); + $json = file_get_contents($args[1]); + Support::need(is_string($json), 'configuration', 'Cannot read settings JSON.'); + $input = Support::object($json); + Support::need(!array_diff(array_keys($input), array_keys(Settings::defaults())), 'configuration', 'Unknown configuration setting.'); + Settings::save($input); \WP_CLI::success('Settings validated and saved. Deployment locks still apply.'); + } + elseif ($command === 'config') { \WP_CLI::log(Support::json(['effective'=>Settings::get(),'locked'=>array_keys(Settings::deployment()),'emergency_disabled'=>Settings::disabled()])); } + elseif ($command === 'test-url') { + Support::need(current_user_can('manage_options'), 'authorization', 'Use --user= to authorise a test login.'); + $ticket = Support::random(); $s = Settings::get(); + set_transient('soca_test_ticket_' . hash('sha256',$ticket), ['operator'=>get_current_user_id(),'revision'=>$s['revision']],600); + \WP_CLI::log(Support::query(admin_url('admin-post.php'), ['action'=>'soca_start','purpose'=>'test','ticket'=>$ticket])); + } + elseif ($command === 'link' || $command === 'unlink') { + Support::need(current_user_can('manage_options'), 'authorization', 'Use --user= to approve identity association changes.'); + Support::need(count($args) === 4 && ctype_digit($args[1]) && (int)$args[1] > 0, 'identity', 'Usage: wp soca '); + if ($command === 'link') { Identity::link((int)$args[1], $args[2], $args[3]); } + else { Identity::unlink((int)$args[1], $args[2], $args[3]); } + \WP_CLI::success('Identity association updated.'); + } elseif ($command === 'check') { \WP_CLI::log(Support::json(self::check())); } elseif ($command === 'maintain') { self::maintenance(); \WP_CLI::log(Support::json(get_option('soca_maintenance_status',[]))); } elseif ($command === 'status') { \WP_CLI::log(Support::json(self::status())); } elseif ($command === 'jwks') { \WP_CLI::log(Support::json(Keys::jwks())); } elseif ($command === 'audit') { \WP_CLI::log(Support::json(get_option('soca_audit',[]))); } - else { \WP_CLI::error('Usage: wp soca . Select a multisite site using --url.'); } + else { \WP_CLI::error('Usage: wp soca . Select a multisite site using --url.'); } } catch (\Throwable $e) { \WP_CLI::error($e instanceof Failure ? $e->getMessage() : 'Internal failure; inspect the runtime configuration.'); } }; \WP_CLI::add_command('soca', $cli); @@ -53,8 +75,8 @@ public static function activate(bool $network = false): void { } public static function deactivate(bool $network = false): void { if ($network && is_multisite()) { - foreach (get_sites(['fields'=>'ids','number'=>0]) as $id) { switch_to_blog($id); wp_clear_scheduled_hook('soca_maintenance'); restore_current_blog(); } - } else { wp_clear_scheduled_hook('soca_maintenance'); } + foreach (get_sites(['fields'=>'ids','number'=>0]) as $id) { switch_to_blog($id); wp_clear_scheduled_hook('soca_maintenance'); Settings::invalidate(); restore_current_blog(); } + } else { wp_clear_scheduled_hook('soca_maintenance'); Settings::invalidate(); } } public static function documents(): void { if (!isset($_GET['soca_doc'])) { return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only public client metadata and JWKS endpoint. @@ -79,7 +101,8 @@ public static function documents(): void { } catch (\Throwable $e) { status_header(503); header('Cache-Control: no-store'); header('Content-Type: application/json'); echo '{"error":"metadata_unavailable"}'; exit; } } public static function button(string $destination = ''): string { - $s = Settings::get(); if (!$s['enabled'] || Settings::disabled()) { return ''; } + try { $s = Settings::get(); if (!self::loginReady($s)) { return ''; } } + catch (\Throwable $e) { return ''; } // Invalid deployment settings must leave local recovery usable. $url = Support::query(admin_url('admin-post.php'), ['action'=>'soca_start','redirect_to'=>Support::destination($destination)]); return ''; } @@ -89,8 +112,9 @@ public static function recoveryUrl(bool $error = false, string $ref = ''): strin return add_query_arg($args, wp_login_url()); } public static function automatic(): void { - $s = Settings::get(); - if (!$s['enabled'] || !$s['automatic'] || Settings::disabled() || is_user_logged_in() || Support::serverString('REQUEST_METHOD') !== 'GET') { return; } + try { $s = Settings::get(); if (!self::loginReady($s)) { return; } } + catch (\Throwable $e) { return; } + if (!$s['automatic'] || is_user_logged_in() || Support::serverString('REQUEST_METHOD') !== 'GET') { return; } // A narrow allowlist preserves recovery, reset, logout, interim, reauth and plugin-specific flows. if (array_diff(array_keys($_GET), ['redirect_to','action']) || (isset($_GET['action']) && $_GET['action'] !== 'login')) { return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public login initiation; the callback requires one-time OAuth state and PKCE. wp_safe_redirect(Support::query(admin_url('admin-post.php'), ['action'=>'soca_start','redirect_to'=>Support::destination(Support::scalar(wp_unslash($_GET),'redirect_to'))])); exit; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public login initiation; the callback requires one-time OAuth state and PKCE. @@ -126,11 +150,19 @@ public static function maintenance(): void { } public static function status(): array { $s=Settings::get(); $k=Keys::get(); - return ['enabled'=>$s['enabled'] && !Settings::disabled(),'mode'=>$s['mode'],'key_mode'=>$s['key_mode'],'active_kid'=>$k['active'], + return ['enabled'=>self::loginReady($s),'requested_enabled'=>$s['enabled'],'test_login_current'=>self::verified($s),'locked'=>array_keys(Settings::deployment()),'mode'=>$s['mode'],'key_mode'=>$s['key_mode'],'active_kid'=>$k['active'], 'active_since'=>$k['since'],'public_keys'=>array_map(static fn($x)=>array_intersect_key($x,array_flip(['kid','published','retired'])), $k['items']), 'maintenance'=>get_option('soca_maintenance_status',[]),'next_cron'=>wp_next_scheduled('soca_maintenance'), 'inline_client_id_changes'=>$s['mode']==='proxy' && $s['key_mode']==='inline']; } + public static function verified(array $s): bool { + return (get_option('soca_verified', [])['profile'] ?? '') === Settings::profile($s); + } + public static function loginReady(array $s): bool { return $s['enabled'] && !Settings::disabled() && self::verified($s); } + public static function cookieName(string $state): string { return '__Host-soca_tx_' . substr(hash('sha256', $state), 0, 32); } + private static function browserCookie(string $state, string $value, int $expires): void { + Support::need(setcookie(self::cookieName($state), $value, ['expires'=>$expires,'path'=>'/','secure'=>true,'httponly'=>true,'samesite'=>'Lax']), 'browser_cookie', 'Cannot set the secure login transaction cookie.'); + } private static function userAgentHash(): string { return hash('sha256', Support::serverString('HTTP_USER_AGENT')); } public static function start(): void { $ref = bin2hex(random_bytes(6)); $flow = 'login'; $step = 'request'; @@ -141,7 +173,14 @@ public static function start(): void { $flow = $purpose; if ($purpose==='test') { Support::need(current_user_can('manage_options'),'authorization','Administrator access required.'); - Support::need((bool) wp_verify_nonce(Support::scalar(wp_unslash($_GET),'_wpnonce',100), 'soca_test'), 'nonce', 'Invalid test-login nonce.'); + $ticket = Support::scalar(wp_unslash($_GET),'ticket',100); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- A one-use CLI test ticket is checked against the authenticated operator and revision. + if ($ticket !== '') { + Support::need((bool)preg_match('/^[A-Za-z0-9_-]{43}$/D',$ticket), 'nonce', 'Invalid test ticket.'); + Store::locked('test-ticket/' . hash('sha256',$ticket), static function () use ($ticket) { + $key='soca_test_ticket_' . hash('sha256',$ticket); $record=get_transient($key); + Support::need(is_array($record) && $record['operator']===get_current_user_id() && $record['revision']===Settings::get()['revision'] && delete_transient($key), 'nonce', 'Test ticket expired, used, or belongs to another operator or revision.'); + }); + } else { Support::need((bool) wp_verify_nonce(Support::scalar(wp_unslash($_GET),'_wpnonce',100), 'soca_test'), 'nonce', 'Invalid test-login nonce.'); } } self::begin($purpose,$ref,$step); } catch (\Throwable $e) { self::fail($e,$flow,$step,$ref); } @@ -149,7 +188,7 @@ public static function start(): void { private static function begin(string $purpose, string $ref, string &$step): void { $step = 'configuration'; $s=Settings::get(); Support::need(!Settings::disabled(),'disabled','Upstream login is disabled by configuration.'); - Support::need($s['enabled'] || $purpose!=='login','disabled','Upstream login is not enabled.'); self::rate('start',30); + Support::need($purpose!=='login' || self::loginReady($s),'disabled','Ordinary SSO requires enablement and a successful test login for the current candidate.'); self::rate('start',30); Support::need(is_ssl() && wp_parse_url(Metadata::callback(),PHP_URL_SCHEME)==='https','https','HTTPS is required for browser transactions.'); $step = 'discovery'; $http=self::http(); $d=(new Provider($http))->discover($s); $context=Metadata::context($s); $checked=get_option('soca_checked',[]); @@ -163,7 +202,9 @@ private static function begin(string $purpose, string $ref, string &$step): void 'nonce'=>$nonce,'verifier'=>$verifier,'user_agent'=>self::userAgentHash(),'started'=>time(),'purpose'=>$purpose,'reauth'=>$purpose!=='login', 'user'=>$purpose==='login'?0:get_current_user_id(),'session'=>$purpose==='login'?'':hash('sha256',wp_get_session_token()), 'destination'=>Support::destination(Support::scalar(wp_unslash($_GET),'redirect_to')),'audit_ref'=>$ref]; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public login destination is restricted to this site before storage and redirect. - Store::createTransaction($state,$tx); + $browser = Support::random(); + Store::createTransaction($state,$tx,$browser); + self::browserCookie($state,$browser,time()+600); Support::audit('login_started', $purpose==='test' ? get_current_user_id() : 0, ['flow'=>$purpose,'step'=>'redirect','ref'=>$ref]); $step = 'redirect'; $params=['response_type'=>'code','response_mode'=>'query','client_id'=>$tx['client'],'redirect_uri'=>$tx['callback'],'scope'=>$s['scopes'], @@ -193,13 +234,15 @@ public static function callback(): void { $names=[]; foreach (explode('&',$queryString) as $pair) { $name=urldecode(explode('=',$pair,2)[0]); Support::need(!in_array($name,$names,true),'duplicate_parameter','Duplicate callback parameter.'); $names[]=$name; } $step = 'transaction'; $state=Support::scalar(wp_unslash($_GET),'state',100); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- OAuth callback consumes one-time state bound to the browser transaction. - $tx=Store::consumeTransaction($state,self::userAgentHash()); + $browser = Support::scalar(wp_unslash($_COOKIE),self::cookieName($state),100); + $tx=Store::consumeTransaction($state,self::userAgentHash(),$browser); + self::browserCookie($state,'',time()-3600); $ref = is_string($tx['audit_ref'] ?? null) && preg_match('/^[a-f0-9]{12}$/D', $tx['audit_ref']) ? $tx['audit_ref'] : $ref; $flow = ($tx['purpose'] ?? '') === 'test' ? 'test' : 'login'; Support::audit('callback_received', 0, ['flow'=>$flow,'step'=>'configuration','ref'=>$ref]); $step = 'configuration'; $s=Settings::get(); - Support::need(!Settings::disabled() && $s['revision']===$tx['settings']['revision'] && ($s['enabled'] || $tx['purpose']!=='login'),'configuration_changed','Configuration changed during login. Start again.'); + Support::need(!Settings::disabled() && $s['revision']===$tx['settings']['revision'] && Metadata::callback()===$tx['callback'] && ($tx['purpose']!=='login' || self::loginReady($s)),'configuration_changed','Configuration changed during login. Start again.'); $step = 'authorization_response'; $iss=Support::scalar(wp_unslash($_GET),'iss'); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- OAuth callback validates the response issuer against the stored provider. Support::need(($iss==='' && empty($tx['discovery']['authorization_response_iss_parameter_supported'])) || $iss===$tx['settings']['issuer'],'response_issuer','Authorization response issuer mismatch or missing.'); @@ -210,12 +253,16 @@ public static function callback(): void { } $step = 'token_exchange'; $claims=(new Provider(self::http()))->exchange($tx,$code); + // Refresh request-local option caches: another worker may have revoked this flow. + $s=Settings::get(true); + Support::need(!Settings::disabled() && $s['revision']===$tx['settings']['revision'] && Metadata::callback()===$tx['callback'], 'configuration_changed', 'Configuration changed during token exchange. Start again.'); Support::audit('claims_verified', 0, ['flow'=>$flow,'step'=>'access_policy','ref'=>$ref]); if ($tx['purpose']==='test') { $step = 'access_policy'; Support::need(current_user_can('manage_options'),'authorization','Administrator access required.'); [$allowed,$reason]=Policy::test($s,is_string($claims['email']??null)?$claims['email']:'',($claims['email_verified']??false)===true); - set_transient('soca_test_' . get_current_user_id(),['time'=>time(),'policy'=>$allowed,'message'=>$reason],600); + set_transient('soca_test_' . get_current_user_id(),['time'=>time(),'policy'=>$allowed,'message'=>$reason,'revision'=>$s['revision']],600); + if ($allowed) { update_option('soca_verified',['time'=>time(),'profile'=>Settings::profile($s),'operator'=>get_current_user_id()],false); } Support::audit('test_login_verified',get_current_user_id(),['flow'=>$flow,'ref'=>$ref]); wp_safe_redirect(admin_url('options-general.php?page=simple-oauth-cimd-access&tested=1')); exit; } diff --git a/simple-oauth-cimd-access/includes/Policy.php b/simple-oauth-cimd-access/includes/Policy.php index 9ec771b..449cc4e 100644 --- a/simple-oauth-cimd-access/includes/Policy.php +++ b/simple-oauth-cimd-access/includes/Policy.php @@ -19,21 +19,35 @@ public static function entries(string $text, bool $email): array { Support::need(strlen($text) <= 32000, 'policy_size', 'Too many policy entries.'); $out = []; foreach (preg_split('/[\s,;]+/', trim($text), -1, PREG_SPLIT_NO_EMPTY) as $value) { - $out[] = $email ? self::email($value) : self::domain($value); + $out[] = $email ? self::email($value) : self::rule($value); } $out = array_values(array_unique($out)); Support::need(count($out) <= 200, 'policy_size', 'Limit each list to 200 entries.'); sort($out, SORT_STRING); return $out; } + public static function rule(string $value): string { + $value = strtolower(trim($value)); + return str_starts_with($value, '*.') ? '*.' . self::domain(substr($value, 2)) : self::domain($value); + } + private static function matches(string $domain, array $rules): bool { + $match = false; + foreach ($rules as $rule) { + $rule = self::rule($rule); + $match = $match || (str_starts_with($rule, '*.') ? str_ends_with($domain, substr($rule, 1)) : $domain === $rule); + } + return $match; + } public static function test(array $s, string $email, bool $verified): array { if (!$verified) { return [false, 'A verified email is required.']; } $email = self::email($email); $domain = explode('@', $email, 2)[1]; if (in_array($email, $s['deny_emails'], true)) { return [false, 'Email deny rule wins.']; } - if (in_array($domain, $s['deny_domains'], true)) { return [false, 'Exact domain deny rule wins.']; } + $denyDomain = self::matches($domain, $s['deny_domains']); + $allowDomain = self::matches($domain, $s['allow_domains']); + if ($denyDomain) { return [false, 'Domain deny rule wins.']; } if ($s['unrestricted']) { return [true, 'Any verified email is allowed; no deny rule matched.']; } if (in_array($email, $s['allow_emails'], true)) { return [true, 'Email allow rule matches; no deny rule matched.']; } - if (in_array($domain, $s['allow_domains'], true)) { return [true, 'Exact domain allow rule matches; no deny rule matched.']; } - if ($s['allow_emails'] || $s['allow_domains']) { return [false, 'Neither allowlist matched. Subdomains do not match parent domains.']; } + if ($allowDomain) { return [true, 'Domain allow rule matches; no deny rule matched.']; } + if ($s['allow_emails'] || $s['allow_domains']) { return [false, 'Neither allowlist matched. Subdomains require an explicit rule or a leading *. rule.']; } return [false, 'No allowlist matched. Add a domain/email or enable Allow any verified email.']; } } diff --git a/simple-oauth-cimd-access/includes/Settings.php b/simple-oauth-cimd-access/includes/Settings.php index fb35c7a..d4e7595 100644 --- a/simple-oauth-cimd-access/includes/Settings.php +++ b/simple-oauth-cimd-access/includes/Settings.php @@ -4,46 +4,89 @@ final class Settings { public static function defaults(): array { $host = (string) wp_parse_url(home_url('/'), PHP_URL_HOST); $domain = preg_replace('/^www\./i', '', $host); try { $suggested = [Policy::domain($domain)]; } catch (Failure $e) { $suggested = []; } - $ready = !Support::localHost($host) && wp_parse_url(home_url('/'), PHP_URL_SCHEME) === 'https' && (bool)$suggested; - return ['enabled'=>$ready, 'automatic'=>false, 'provider'=>'RESOAuth', 'issuer'=>'https://auth.resoauth.cloud', + return ['enabled'=>false, 'automatic'=>false, 'provider'=>'RESOAuth', 'issuer'=>'https://auth.resoauth.cloud', 'button'=>'Continue with SSO', 'scopes'=>'openid email profile', 'mode'=>Support::localHost($host)?'proxy':'self', 'key_mode'=>Support::localHost($host)?'inline':'uri', 'jwks_url'=>'', 'proxy'=>'https://dynamic-cimd.resoauth.cloud/cimd/%s', 'id_alg'=>'ES256', 'assertion_audience'=>'issuer', + 'client_name'=>'', 'client_uri'=>'', 'logo_uri'=>'', 'policy_uri'=>'', 'tos_uri'=>'', 'cache_hours'=>24, 'create_users'=>false, - 'unrestricted'=>false, 'allow_domains'=>$suggested, 'allow_emails'=>[], 'deny_domains'=>[], 'deny_emails'=>[], 'revision'=>Support::random()]; + 'unrestricted'=>false, 'allow_domains'=>$suggested, 'allow_emails'=>[], 'deny_domains'=>[], 'deny_emails'=>[]]; } - public static function get(): array { - $s = get_option('soca_settings'); - if (!is_array($s)) { $s = self::defaults(); add_option('soca_settings', $s, '', false); } + public static function deployment(): array { + $config = defined('SOCA_CONFIG') ? SOCA_CONFIG : []; + Support::need(is_array($config) && !array_diff(array_keys($config), array_keys(self::defaults())), 'configuration', 'SOCA_CONFIG must be an array containing only documented setting names.'); + return $config; + } + public static function get(bool $fresh = false): array { + if ($fresh) { + foreach (['soca_settings','soca_epoch','soca_verified','soca_disabled_latched','notoptions'] as $key) { wp_cache_delete($key,'options'); } + } + $stored = get_option('soca_settings'); + if (!is_array($stored)) { $stored = self::defaults(); $stored['revision'] = Support::random(); add_option('soca_settings', $stored, '', false); } + // Latch emergency disable so transactions cannot resume after it is removed. + if (self::disabled() && !get_option('soca_disabled_latched')) { self::invalidate(); update_option('soca_disabled_latched', true, false); } + if (!self::disabled()) { delete_option('soca_disabled_latched'); } + $s = self::validate(array_replace(self::defaults(), $stored, self::deployment())); + $s['revision'] = hash('sha256', Support::json($s) . ($stored['revision'] ?? '') . get_option('soca_epoch', '') . home_url('/') . admin_url('admin-post.php')); return $s; } - public static function disabled(): bool { - return defined('SOCA_DISABLED') && SOCA_DISABLED; + public static function disabled(): bool { return defined('SOCA_DISABLED') && SOCA_DISABLED; } + public static function invalidate(): void { + update_option('soca_epoch', Support::random(), false); + delete_option('soca_checked'); delete_option('soca_verified'); } - public static function save(array $input): array { - $s = self::get(); - foreach (['enabled','automatic','create_users','unrestricted'] as $key) { $s[$key] = !empty($input[$key]); } - foreach (['provider','issuer','button','scopes','mode','key_mode','jwks_url','proxy','id_alg','assertion_audience'] as $key) { $s[$key] = trim(Support::scalar($input, $key)); } - foreach (['provider','button'] as $key) { Support::need(strlen($s[$key]) > 0 && strlen($s[$key]) <= 120 && wp_strip_all_tags($s[$key]) === $s[$key], 'settings', 'Provider name and button label must be plain text, 1–120 bytes.'); } + /** Candidate revision excludes only the switches used to activate a tested profile. */ + public static function profile(array $s): string { + unset($s['enabled'], $s['automatic'], $s['revision']); + return hash('sha256', Support::json($s) . Metadata::context($s) . Metadata::callback() . get_option('soca_epoch', '')); + } + public static function validate(array $input): array { + $s = array_intersect_key($input, self::defaults()); + foreach (['enabled','automatic','create_users','unrestricted'] as $key) { + Support::need(in_array($s[$key], [true,false,0,1,'0','1',''], true), 'settings', 'Boolean settings accept only true, false, 0 or 1.'); + $s[$key] = (bool)$s[$key]; + } + foreach (['provider','issuer','button','scopes','mode','key_mode','jwks_url','proxy','id_alg','assertion_audience','client_name','client_uri','logo_uri','policy_uri','tos_uri'] as $key) { $s[$key] = trim(Support::scalar($s, $key)); } + foreach (['provider','button','client_name'] as $key) { Support::need(($key === 'client_name' || strlen($s[$key]) > 0) && strlen($s[$key]) <= 120 && wp_strip_all_tags($s[$key]) === $s[$key], 'settings', 'Names and labels must be plain text, at most 120 bytes.'); } Http::url($s['issuer']); - $p = wp_parse_url($s['issuer']); Support::need(!isset($p['query']), 'issuer', 'Issuer must not have a query. Preserve the provider’s exact issuer, including any trailing slash.'); + Support::need(wp_parse_url($s['issuer'], PHP_URL_QUERY) === null, 'issuer', 'Issuer must not have a query. Preserve the exact issuer, including any trailing slash.'); Support::need(in_array($s['mode'], ['self','proxy'], true) && in_array($s['key_mode'], ['uri','inline'], true), 'settings', 'Invalid metadata/key mode.'); Support::need(in_array($s['id_alg'], ['ES256','RS256'], true), 'algorithm', 'Select ES256 or RS256 for ID tokens.'); Support::need(in_array($s['assertion_audience'], ['issuer','token_endpoint'], true), 'assertion_audience', 'Select the provider issuer or token endpoint as the client assertion audience.'); Support::need((bool) preg_match('/^[\x21\x23-\x5b\x5d-\x7e]+(?: [\x21\x23-\x5b\x5d-\x7e]+)*$/D', $s['scopes']) && strlen($s['scopes']) <= 500, 'scopes', 'Enter space-separated OAuth scopes.'); Support::need(in_array('openid', explode(' ', $s['scopes']), true) && in_array('email', explode(' ', $s['scopes']), true), 'scopes', 'openid and email scopes are required.'); Metadata::proxyTemplate($s['proxy']); - if ($s['jwks_url']) { Http::url($s['jwks_url']); } - $hours = filter_var($input['cache_hours'] ?? null, FILTER_VALIDATE_INT); - Support::need($hours !== false && $hours >= 1 && $hours <= 168, 'cache_window', 'Provider cache window must be 1–168 hours. Longer windows may delay weekly rotation.'); + foreach (['jwks_url','client_uri','logo_uri','policy_uri','tos_uri'] as $key) { if ($s[$key] !== '') { Http::url($s[$key]); } } + $hours = filter_var($s['cache_hours'], FILTER_VALIDATE_INT); + Support::need($hours !== false && $hours >= 1 && $hours <= 168, 'cache_window', 'Provider cache window must be 1–168 hours.'); $s['cache_hours'] = $hours; foreach (['allow_domains','deny_domains','allow_emails','deny_emails'] as $key) { - if ($s['unrestricted'] && str_starts_with($key, 'allow_') && !array_key_exists($key, $input)) { continue; } - $s[$key] = Policy::entries(Support::scalar($input, $key, 32000), str_ends_with($key, 'emails')); + if (is_array($s[$key])) { + Support::need(array_is_list($s[$key]) && count(array_filter($s[$key], 'is_string')) === count($s[$key]), 'policy', 'Policy lists must contain strings.'); + $s[$key] = implode("\n", $s[$key]); + } + $s[$key] = Policy::entries(Support::scalar($s, $key, 32000), str_ends_with($key, 'emails')); } - $s['revision'] = Support::random(); - update_option('soca_settings', $s, false); - delete_option('soca_checked'); // A configuration change invalidates pending transactions and previous tests. - Support::audit('settings_changed', get_current_user_id()); return $s; } + /** Partial writes are shared by WP-CLI and the form. Locked values are never persisted. */ + public static function save(array $input): array { + return Store::locked('settings/' . get_current_blog_id(), static function () use ($input) { + $current = self::get(true); + if (isset($input['revision'])) { Support::need($input['revision'] === $current['revision'], 'stale_settings', 'Settings changed. Reload before saving.'); } + $s = array_replace(self::defaults(), (array)get_option('soca_settings'), array_intersect_key($input, self::defaults())); + foreach (self::deployment() as $key=>$value) { $s[$key] = $current[$key]; } + $s = self::validate($s); + $stored = (array)get_option('soca_settings'); + foreach (self::deployment() as $key=>$value) { + if (array_key_exists($key,$stored)) { $s[$key] = $stored[$key]; } else { unset($s[$key]); } + } + $previous = array_replace(self::defaults(),$stored); unset($previous['revision']); + if ($s === $previous) { return $current; } + $s['revision'] = Support::random(); + update_option('soca_settings', $s, false); + delete_option('soca_checked'); + Support::audit('settings_changed', get_current_user_id()); + return self::get(); + }); + } } diff --git a/simple-oauth-cimd-access/includes/Store.php b/simple-oauth-cimd-access/includes/Store.php index e9b838a..1c5c980 100644 --- a/simple-oauth-cimd-access/includes/Store.php +++ b/simple-oauth-cimd-access/includes/Store.php @@ -37,17 +37,24 @@ public static function open(string $data): array { Support::need(is_string($plain), 'encryption', 'Unable to unlock signing keys/transaction. Restore the original WordPress salts or configured encryption key.'); return Support::object($plain); } - public static function createTransaction(string $state, array $data): void { + public static function createTransaction(string $state, array $data, string $browser): void { + Support::need((bool) preg_match('/^[A-Za-z0-9_-]{43}$/D', $browser), 'browser_binding', 'Invalid browser binding.'); + $data['browser'] = hash('sha256', $browser); + $data['expires'] = time() + 600; $key = 'soca_tx_' . hash('sha256', $state); Support::need(set_transient($key, self::seal($data), 600), 'storage', 'Cannot store login transaction.'); } - public static function consumeTransaction(string $state, string $userAgentHash): array { + public static function consumeTransaction(string $state, string $userAgentHash, string $browser): array { Support::need((bool) preg_match('/^[A-Za-z0-9_-]{43}$/D', $state), 'state', 'Invalid or expired login state.'); $key = 'soca_tx_' . hash('sha256', $state); - return self::locked($key, static function () use ($key, $userAgentHash) { + return self::locked($key, static function () use ($key, $userAgentHash, $browser) { $sealed = get_transient($key); Support::need(is_string($sealed), 'state', 'Invalid or expired login state.'); $tx = self::open($sealed); + Support::need(($tx['expires'] ?? 0) > time(), 'state', 'Invalid or expired login state.'); + if (!preg_match('/^[A-Za-z0-9_-]{43}$/D', $browser) || !is_string($tx['browser'] ?? null) || !hash_equals($tx['browser'], hash('sha256', $browser))) { + throw new Failure('browser_binding', 'The initiating browser cookie is required.', ['ref'=>$tx['audit_ref'] ?? '', 'flow'=>$tx['purpose'] ?? '']); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Diagnostic values are validated and redacted before display. + } if (!is_string($tx['user_agent'] ?? null) || !hash_equals($tx['user_agent'], $userAgentHash)) { throw new Failure('user_agent_mismatch', 'The browser User-Agent changed during login.', ['ref'=>$tx['audit_ref'] ?? '', 'flow'=>$tx['purpose'] ?? '']); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Diagnostic values are validated/redacted before display. } diff --git a/simple-oauth-cimd-access/includes/Support.php b/simple-oauth-cimd-access/includes/Support.php index 8a6e569..82aa9fd 100644 --- a/simple-oauth-cimd-access/includes/Support.php +++ b/simple-oauth-cimd-access/includes/Support.php @@ -13,6 +13,7 @@ public static function serverString(string $key): string { $value = wp_unslash($_SERVER[$key] ?? ''); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Callers validate fixed fields or hash opaque values. return is_string($value) ? $value : ''; } + /** @psalm-taint-specialize */ public static function b64(string $s): string { return rtrim(strtr(base64_encode($s), '+/', '-_'), '='); } public static function unb64(string $s): string { self::need((bool) preg_match('/^[A-Za-z0-9_-]+$/D', $s), 'encoding', 'Invalid base64url.'); @@ -68,7 +69,7 @@ public static function audit(string $event, int $user = 0, array $context = []): if (!preg_match('/^[a-z_]{1,48}$/D', $event)) { $event = 'internal_error'; } $log = get_option('soca_audit', []); if (!is_array($log)) { $log = []; } - $entry = ['time'=>gmdate('c'), 'event'=>$event, 'user'=>$user]; + $entry = ['time'=>gmdate('c'), 'event'=>$event, 'user'=>$user, 'actor'=>get_current_user_id()]; foreach (['flow','step','reason'] as $key) { if (isset($context[$key]) && is_string($context[$key]) && preg_match('/^[a-z_]{1,48}$/D', $context[$key])) { $entry[$key] = $context[$key]; } } diff --git a/simple-oauth-cimd-access/readme.txt b/simple-oauth-cimd-access/readme.txt index ee1c9d6..66e8dad 100644 --- a/simple-oauth-cimd-access/readme.txt +++ b/simple-oauth-cimd-access/readme.txt @@ -3,7 +3,7 @@ Tags: single sign on, openid connect, oauth, login, authentication Requires at least: 6.8 Tested up to: 7.1 Requires PHP: 8.1 -Stable tag: 0.2.0 +Stable tag: 0.3.0 License: AGPL-3.0-only License URI: https://www.gnu.org/licenses/agpl-3.0.html @@ -16,11 +16,11 @@ SOCA connects a WordPress site to one configured OpenID Connect (OIDC) identity Features: * Self-hosted or configurable HTTPS proxy client metadata, with public JWKS and encrypted, rotating signing keys. -* Verified-email and exact-domain admission rules, including deny rules. Existing accounts are selected by the current verified email on every login; roles are not changed. +* Verified-email and exact/wildcard domain admission rules, with deny precedence. Approved issuer/subject links select existing accounts; roles are preserved. * Optional creation of missing Subscriber accounts, off by default. * Login button, provider test flow, local-login recovery, redacted audit events, Site Health checks and WP-CLI maintenance. -An identity provider that verifies an allowed administrator email can sign in to that administrator account. Review the provider and admission rules before enabling login. Keep a local administrator password and test recovery. A successful metadata check does not prove end-to-end login: a real login with the chosen provider is required. Live RESOAuth end-user login has not yet been verified; no interoperability certification is claimed. +Upgrading to 0.3.0 requires administrator-approved identity links for existing users and a successful candidate test login. Email alone no longer selects an account. Review the provider and admission rules before enabling login. Keep a local administrator password and test recovery. A successful metadata check does not prove end-to-end login: a real login with the chosen provider is required. Live RESOAuth end-user login has not yet been verified; no interoperability certification is claimed. The [source repository](https://github.com/RESOAuth/wordpress-soca-plugin) contains the [operator guide](https://github.com/RESOAuth/wordpress-soca-plugin/blob/main/docs/GUIDE.md), [security notes](https://github.com/RESOAuth/wordpress-soca-plugin/blob/main/docs/SECURITY.md), build tools and readable source for the bundled JWT library. Report problems in [GitHub Issues](https://github.com/RESOAuth/wordpress-soca-plugin/issues). @@ -32,13 +32,13 @@ During connection checks, login and hourly maintenance while upstream login is e For local development, proxy mode defaults to [RESOAuth Dynamic CIMD](https://dynamic-cimd.resoauth.cloud/), a separate service that serves a Client ID Metadata Document from data encoded in its URL. That URL contains this site's public client metadata and, when inline keys are selected, public signing keys. The service receives the requesting server's IP address during validation, login and enabled-site maintenance; its public URL can also be fetched by the configured identity provider. SOCA sends it no WordPress passwords, private signing keys or returned identity claims. Public production sites default to self-hosted metadata; the proxy template is configurable. The [operator guide](https://github.com/RESOAuth/wordpress-soca-plugin/blob/main/docs/GUIDE.md) explains proxy choices. -SOCA stores encrypted private signing keys and settings on the WordPress site. During login it temporarily stores a one-time transaction and processes the verified email and provider subject to select an account. Its redacted audit omits emails, subjects and tokens. It does not add third-party tracking assets or send usage telemetry. Site owners should describe their chosen identity provider in their own privacy policy. +SOCA stores settings, encrypted private signing keys and encrypted issuer/subject identity associations on the WordPress site. Revoked links remain as encrypted records to prevent automatic reuse. Login uses a ten-minute encrypted transaction and a Secure, HttpOnly, SameSite=Lax browser cookie that is deleted after callback or expires. Verified email controls admission; the identity link selects the local account. Its redacted audit omits emails, subjects and tokens. It does not add third-party tracking assets or send usage telemetry. Site owners should describe their chosen identity provider in their own privacy policy. == Installation == 1. Install and activate SOCA on WordPress 6.8+ with PHP 8.1+, OpenSSL and cURL. Use HTTPS and retain a local administrator login. 2. Open Settings > SOCA. Check the issuer, metadata mode, signing-key publication and email/domain admission rules. Defaults use RESOAuth; public HTTPS sites initially suggest the site's own domain. -3. Run Validate connection and documents, then Test login with the chosen provider. Confirm a real sign-in and local recovery at /wp-login.php?soca_local=1 before enabling automatic redirection. +3. Run Validate connection and documents, then Test login with the chosen provider. Approve existing users’ identity links and enable ordinary SSO only after an admitted test succeeds. Confirm local recovery at /wp-login.php?soca_local=1. 4. For provider-specific settings, key rotation or multisite, follow the [operator guide](https://github.com/RESOAuth/wordpress-soca-plugin/blob/main/docs/GUIDE.md). == Frequently Asked Questions == @@ -50,13 +50,16 @@ Yes, if it supports this plugin's OIDC, PKCE, ES256 private_key_jwt and CIMD pro Open /wp-login.php?soca_local=1 to skip automatic navigation, then use your existing WordPress credentials. For emergency recovery, set SOCA_DISABLED to true in wp-config.php or run wp soca disable. The URL alone does not authenticate anyone. = How are existing accounts selected? = -The current verified provider email must pass the saved admission rules and uniquely match a WordPress account. This includes administrators, so use a provider whose email verification you trust. A changed provider subject does not relink the account, and SOCA does not change its role. +A verified email must pass admission, then the exact issuer/subject must have an approved link to an eligible WordPress account. An administrator can approve links in Settings > SOCA or with wp soca link. Changed subjects require explicit approval; changed emails never select a different account. Optional new Subscriber accounts receive a link on creation. = Is data removed on uninstall? = -Settings and encrypted keys are retained by default for recovery. Define SOCA_ERASE_DATA as true before uninstall to remove persistent settings, signing keys and audit data. Short-lived transients expire through WordPress. WordPress users are never deleted by uninstall. +Settings and encrypted keys are retained by default for recovery. Define SOCA_ERASE_DATA as true before uninstall to remove persistent settings, signing keys, identity associations and audit data. Short-lived transients expire through WordPress. WordPress users are never deleted by uninstall. == Changelog == += 0.3.0 = +Bind callbacks to a secure browser cookie and accounts to approved issuer/subject links. Gate ordinary SSO on a candidate test login. Add deployment-managed configuration, wildcard admission and application branding/legal metadata. Existing installations require identity-link migration. + = 0.2.0 = Standardize SOCA naming and replace the custom transaction table with encrypted WordPress transients. Use WordPress user APIs for account lookup and safe redirects for authorization. diff --git a/simple-oauth-cimd-access/simple-oauth-cimd-access.php b/simple-oauth-cimd-access/simple-oauth-cimd-access.php index 0d7b56e..1dd5fcc 100644 --- a/simple-oauth-cimd-access/simple-oauth-cimd-access.php +++ b/simple-oauth-cimd-access/simple-oauth-cimd-access.php @@ -3,7 +3,7 @@ * Plugin Name: Simple OAuth CIMD Access * Plugin URI: https://github.com/RESOAuth/wordpress-soca-plugin * Description: Single sign-on for WordPress with OpenID Connect, PKCE and CIMD. - * Version: 0.2.0 + * Version: 0.3.0 * Requires at least: 6.8 * Requires PHP: 8.1 * Author: RESOAuth diff --git a/simple-oauth-cimd-access/uninstall.php b/simple-oauth-cimd-access/uninstall.php index a4e669a..356a066 100644 --- a/simple-oauth-cimd-access/uninstall.php +++ b/simple-oauth-cimd-access/uninstall.php @@ -5,9 +5,13 @@ foreach ($socaSites as $socaSite) { if (is_multisite()) { switch_to_blog($socaSite); } wp_clear_scheduled_hook('soca_maintenance'); - foreach (['soca_settings','soca_keys','soca_checked','soca_maintenance_status','soca_audit'] as $socaOption) { + foreach (['soca_settings','soca_keys','soca_checked','soca_verified','soca_epoch','soca_disabled_latched','soca_maintenance_status','soca_audit'] as $socaOption) { delete_option($socaOption); } + global $wpdb; + // Explicit erasure includes the encrypted, site-local identity associations. + $socaLinks = $wpdb->get_col($wpdb->prepare("SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like('soca_link_') . '%')); + foreach ($socaLinks as $socaLink) { delete_option($socaLink); } // WordPress expires short-lived SOCA transients without plugin-specific cleanup. if (is_multisite()) { restore_current_blog(); } } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index e53e475..7372bc9 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -7,6 +7,7 @@ function get_option($k,$d=false) { return $GLOBALS['test_options'][$k]??$d; } function update_option($k,$v,$autoload=null) { $GLOBALS['test_options'][$k]=$v; return true; } function add_option($k,$v,$deprecated='',$autoload=null) { if (isset($GLOBALS['test_options'][$k])) return false; return update_option($k,$v); } function delete_option($k) { unset($GLOBALS['test_options'][$k]); } + function wp_cache_delete($k,$group='') { return true; } function get_transient($k) { $r=$GLOBALS['test_transients'][$k]??null; return $r && $r[1]>time()?$r[0]:false; } function set_transient($k,$v,$t) { $GLOBALS['test_transients'][$k]=[$v,time()+$t]; return true; } function delete_transient($k) { if (!isset($GLOBALS['test_transients'][$k])) return false; unset($GLOBALS['test_transients'][$k]); return true; } @@ -19,6 +20,8 @@ function wp_parse_url($v,$component=-1) { return parse_url($v,$component); } function wp_strip_all_tags($v) { return trim(strip_tags($v)); } function wp_unslash($v) { return is_array($v) ? array_map('wp_unslash', $v) : stripslashes($v); } function get_bloginfo($k) { return 'Test WordPress'; } + function get_site_icon_url() { return get_option('test_icon', ''); } + function get_privacy_policy_url() { return get_option('test_privacy', ''); } function add_query_arg($a,$b,$c=null) { if (is_array($a)) { $args=$a; $url=$b; } else { $args=[$a=>$b]; $url=$c; } return $url . (str_contains($url,'?')?'&':'?') . http_build_query($args,'','&',PHP_QUERY_RFC3986); diff --git a/tests/browser.cjs b/tests/browser.cjs index 156eb24..ef827e6 100644 --- a/tests/browser.cjs +++ b/tests/browser.cjs @@ -16,10 +16,33 @@ const test = async (name, fn) => { await fn(); passed++; console.log('PASS ' + n page.on('request',r=>{if(r.url().includes('action=soca_callback'))lastCallback=r.url();}); async function upstream(destination='/') { await page.goto(base+'/wp-admin/admin-post.php?action=soca_start&redirect_to='+encodeURIComponent(base+destination)); await page.waitForLoadState(); } async function startRequest() { const userAgent=await page.evaluate(()=>navigator.userAgent); return context.request.get(base+'/wp-admin/admin-post.php?action=soca_start',{maxRedirects:0,headers:{'User-Agent':userAgent}}); } + async function emergency(value) { + if(value)cli('config','set','SOCA_DISABLED','true','--raw');else cli('config','delete','SOCA_DISABLED'); + // Wait for web workers to observe deployment changes through their PHP opcode cache. + for(let attempt=0;attempt<50;attempt++){ + const r=await context.request.get(base+'/?soca_fixture_status=1'); + if((await r.json()).disabled===value)return; + await page.waitForTimeout(150); + } + throw new Error('Web workers did not observe emergency configuration'); + } await test('WP-CLI exposes the soca command',async()=>{ const current=JSON.parse(cli('soca','status')); assert(current.active_kid && current.mode); }); + await test('candidate configuration needs an admitted test login before ordinary SSO',async()=>{ + const usersBefore=cli('user','list','--field=user_email'); + const attempt=await context.request.get(base+'/wp-admin/admin-post.php?action=soca_start',{maxRedirects:0}); + assert.equal(attempt.status(),302);assert(attempt.headers().location.includes('soca_error')); + await page.goto(base+'/wp-login.php?soca_local=1');await page.locator('#user_login').fill('localadmin');await page.locator('#user_pass').fill('Local-fixture-password-749!');await page.locator('#wp-submit').click();await page.waitForURL('**/wp-admin/**'); + const before=(await context.cookies()).find(c=>c.name.startsWith('wordpress_logged_in_')).value; + const ticket=cli('soca','test-url','--user=1');await page.goto(ticket);await page.waitForLoadState(); + assert(page.url().includes('tested=1'));assert.equal((await context.cookies()).find(c=>c.name.startsWith('wordpress_logged_in_')).value,before); + assert.equal(JSON.parse(cli('soca','status')).test_login_current,true); + await page.goto(ticket);assert(page.url().includes('soca_error')); + assert.equal(cli('user','list','--field=user_email'),usersBefore); + await context.clearCookies(); + }); await test('authorization, assertion, PKCE, ID token and WordPress session end to end',async()=>{ await upstream('/?signed-in=1'); assert.equal(new URL(page.url()).searchParams.get('signed-in'),'1'); const cookies=await context.cookies();assert(cookies.some(c=>c.name.startsWith('wordpress_logged_in_')));assert(!cookies.some(c=>c.name.startsWith('__Host-soca_'))); @@ -30,25 +53,43 @@ const test = async (name, fn) => { await fn(); passed++; console.log('PASS ' + n scenario(mode);await upstream();assert(page.url().includes('soca_local=1'));assert.match(new URL(page.url()).searchParams.get('soca_error'),/^[a-f0-9]{12}$/);assert(!(await context.cookies()).some(c=>c.name.startsWith('wordpress_logged_in_'))); }); scenario('valid'); - await test('a direct callback can finish in another browser and remains single-use',async()=>{ + await test('a copied callback fails in another browser with an identical User-Agent',async()=>{ const start=await startRequest();assert.equal(start.status(),302); const auth=start.headers().location;const other=await browser.newContext({ignoreHTTPSErrors:true});const stolen=await other.newPage(); - await stolen.goto(auth);assert(!(new URL(stolen.url()).searchParams.has('soca_error')));assert((await other.cookies()).some(c=>c.name.startsWith('wordpress_logged_in_')));await other.close(); - await page.goto(auth);const ref=new URL(page.url()).searchParams.get('soca_error');assert.match(ref,/^[a-f0-9]{12}$/);const events=JSON.parse(cli('soca','audit'));assert(events.some(e=>e.event==='login_failed'&&e.ref===ref&&e.reason==='state'));await context.clearCookies(); + await stolen.goto(auth);const ref=new URL(stolen.url()).searchParams.get('soca_error');assert.match(ref,/^[a-f0-9]{12}$/);assert(!(await other.cookies()).some(c=>c.name.startsWith('wordpress_logged_in_'))); + const events=JSON.parse(cli('soca','audit'));assert(events.some(e=>e.event==='login_failed'&&e.ref===ref&&e.reason==='browser_binding'));await other.close(); + const txCookies=(await context.cookies()).filter(c=>c.name.startsWith('__Host-soca_tx_'));assert(txCookies.length===1 && txCookies[0].httpOnly && txCookies[0].secure && txCookies[0].sameSite==='Lax'); + await page.goto(auth);assert(!new URL(page.url()).searchParams.has('soca_error'));await context.clearCookies(); }); await test('a changed User-Agent is rejected before consuming the transaction',async()=>{ const start=await startRequest();assert.equal(start.status(),302); - const auth=start.headers().location;const other=await browser.newContext({ignoreHTTPSErrors:true,userAgent:'SOCA-different-browser'});const stolen=await other.newPage(); + const auth=start.headers().location;const other=await browser.newContext({ignoreHTTPSErrors:true,userAgent:'SOCA-different-browser'});await other.addCookies(await context.cookies());const stolen=await other.newPage(); await stolen.goto(auth);const ref=new URL(stolen.url()).searchParams.get('soca_error');assert.match(ref,/^[a-f0-9]{12}$/); const events=JSON.parse(cli('soca','audit'));assert(events.some(e=>e.event==='login_failed'&&e.ref===ref&&e.reason==='user_agent_mismatch')); assert(!(await other.cookies()).some(c=>c.name.startsWith('wordpress_logged_in_')));await other.close(); await page.goto(auth);assert(!new URL(page.url()).searchParams.has('soca_error'));await context.clearCookies(); }); + await test('parallel tabs retain independent browser bindings',async()=>{ + const a=await startRequest(),b=await startRequest();assert.equal(a.status(),302);assert.equal(b.status(),302); + assert.equal((await context.cookies()).filter(c=>c.name.startsWith('__Host-soca_tx_')).length,2); + const second=await context.newPage();await page.goto(a.headers().location);await second.goto(b.headers().location); + assert(!page.url().includes('soca_error')&&!second.url().includes('soca_error'));await second.close();await context.clearCookies(); + }); await test('a settings change invalidates an in-flight transaction',async()=>{ const start=await startRequest();assert.equal(start.status(),302); cli('eval',"$s=SOCA\\Settings::get();$s['revision']=SOCA\\Support::random();update_option('soca_settings',$s,false);"); await page.goto(start.headers().location);assert(new URL(page.url()).searchParams.has('soca_error'));assert(!(await context.cookies()).some(c=>c.name.startsWith('wordpress_logged_in_'))); }); + await test('emergency disable blocks an in-flight login and does not revive it on re-enable',async()=>{ + const start=await startRequest();assert.equal(start.status(),302); + await emergency(true); + try{await page.goto(start.headers().location);assert(page.url().includes('soca_error'));assert(!(await context.cookies()).some(c=>c.name.startsWith('wordpress_logged_in_')));} + finally{await emergency(false);} + assert.equal(JSON.parse(cli('soca','status')).test_login_current,false); + await page.goto(start.headers().location);assert(page.url().includes('soca_error')); + await page.goto(base+'/wp-login.php?soca_local=1');await page.locator('#user_login').fill('localadmin');await page.locator('#user_pass').fill('Local-fixture-password-749!');await page.locator('#wp-submit').click();await page.waitForURL('**/wp-admin/**'); + await page.goto(cli('soca','test-url','--user=1'));assert(page.url().includes('tested=1'));await context.clearCookies(); + }); await test('automatic mode and recovery/password flows',async()=>{ cli('eval',"$s=SOCA\\Settings::get();$s['automatic']=true;update_option('soca_settings',$s,false);"); await page.goto(base+'/wp-login.php?soca_local=1');assert(await page.locator('#user_login').isVisible()); @@ -80,6 +121,14 @@ const test = async (name, fn) => { await fn(); passed++; console.log('PASS ' + n await page.getByRole('link',{name:'Test login (keeps this admin session)',exact:true}).click();await page.waitForLoadState(); assert(page.url().includes('tested=1'));assert.equal((await context.cookies()).find(c=>c.name.startsWith('wordpress_logged_in_')).value,before); }); + await test('emergency disable also blocks an operator test already in flight',async()=>{ + const ticket=cli('soca','test-url','--user=1');const userAgent=await page.evaluate(()=>navigator.userAgent); + const start=await context.request.get(ticket,{maxRedirects:0,headers:{'User-Agent':userAgent}});assert.equal(start.status(),302); + await emergency(true); + try{await page.goto(start.headers().location);assert(page.url().includes('soca_error'));assert.equal(JSON.parse(cli('soca','status')).enabled,false);} + finally{await emergency(false);} + await page.goto(cli('soca','test-url','--user=1'));assert(page.url().includes('tested=1')); + }); await test('user profile has no separate plugin identity controls',async()=>{ await page.goto(base+'/wp-admin/profile.php'); assert.equal(await page.getByRole('heading',{name:'SOCA identity'}).count(),0); diff --git a/tests/concurrency-worker.php b/tests/concurrency-worker.php index 7afdf57..b8cb533 100644 --- a/tests/concurrency-worker.php +++ b/tests/concurrency-worker.php @@ -3,9 +3,11 @@ $job=$args[0]??''; try { if($job==='transaction') { - $r=get_option('soca_concurrency');SOCA\Store::consumeTransaction($r['state'],$r['user_agent']);echo 'consumed'; + $r=get_option('soca_concurrency');SOCA\Store::consumeTransaction($r['state'],$r['user_agent'],$r['browser']);echo 'consumed'; + } elseif($job==='link') { + SOCA\Identity::link((int)$args[1],'https://concurrency.company.com','link-race-sub');echo 'linked:'.$args[1]; } else { - $s=SOCA\Settings::get();$s['allow_domains']=['company.com'];$s['create_users']=true; + $s=SOCA\Settings::get();$s['issuer']='https://concurrency.company.com';$s['allow_domains']=['company.com'];$s['create_users']=true; $user=SOCA\Identity::resolve(['iss'=>'https://concurrency.company.com','sub'=>'race-sub','email'=>'race@company.com','email_verified'=>true],$s); echo 'user:'.$user->ID; } diff --git a/tests/concurrency.py b/tests/concurrency.py index 7784c4f..43838f6 100644 --- a/tests/concurrency.py +++ b/tests/concurrency.py @@ -4,7 +4,7 @@ container=os.environ.get('SOCA_CONTAINER','soca-local_wordpress_1') def cli(*args): return subprocess.check_output([engine,'exec','-u','www-data',container,'php','/tmp/wp-cli.phar',*args],text=True).strip() -cli('eval',"$state=SOCA\\Support::random();$ua=hash('sha256','fixture-agent');SOCA\\Store::createTransaction($state,['verifier'=>'fixture','user_agent'=>$ua]);update_option('soca_concurrency',['state'=>$state,'user_agent'=>$ua],false);") +cli('eval',"$state=SOCA\\Support::random();$ua=hash('sha256','fixture-agent');$browser=SOCA\\Support::random();SOCA\\Store::createTransaction($state,['verifier'=>'fixture','user_agent'=>$ua],$browser);update_option('soca_concurrency',['state'=>$state,'user_agent'=>$ua,'browser'=>$browser],false);") with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: results=list(pool.map(lambda _:cli('eval-file','/tmp/tests/concurrency-worker.php','transaction'),range(2))) assert results.count('consumed')==1 and sum(r.startswith('rejected:') for r in results)==1,results @@ -13,5 +13,15 @@ def cli(*args): results=list(pool.map(lambda _:cli('eval-file','/tmp/tests/concurrency-worker.php','identity'),range(2))) assert results[0].startswith('user:') and results[0]==results[1],results assert cli('eval',"global $wpdb;echo $wpdb->get_var(\"SELECT COUNT(*) FROM {$wpdb->users} WHERE user_email='race@company.com'\");")=='1' -cli('eval',"require_once ABSPATH.'wp-admin/includes/user.php';wp_delete_user("+results[0].split(':')[1]+");delete_option('soca_concurrency');") -print('PASS concurrent email-based creation produces exactly one account') +cli('eval',"require_once ABSPATH.'wp-admin/includes/user.php';wp_delete_user("+results[0].split(':')[1]+");delete_option('soca_link_'.hash('sha256',SOCA\\Support::json(['https://concurrency.company.com','race-sub'])));delete_option('soca_concurrency');") +print('PASS concurrent linked-account creation produces exactly one account') + +users=[cli('user','create','soca-link-race-'+str(i),'link-race-'+str(i)+'@company.com','--role=subscriber','--porcelain') for i in range(2)] +try: + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + results=list(pool.map(lambda user:cli('eval-file','/tmp/tests/concurrency-worker.php','link',user),users)) + assert sum(r.startswith('linked:') for r in results)==1 and results.count('rejected:identity_conflict')==1,results + print('PASS concurrent conflicting identity links have exactly one owner') +finally: + cli('eval',"delete_option('soca_link_'.hash('sha256',SOCA\\Support::json(['https://concurrency.company.com','link-race-sub'])));") + for user in users: cli('user','delete',user,'--yes') diff --git a/tests/deployment.php b/tests/deployment.php new file mode 100644 index 0000000..49a7c9a --- /dev/null +++ b/tests/deployment.php @@ -0,0 +1,26 @@ +'https://locked.company.com','enabled'=>false,'allow_domains'=>['*.company.com'],'client_name'=>'Deployment branding']); +try { + test('deployment configuration overrides previously saved settings and locks writes',function()use($stored){ + $s=Settings::get();expect($s['issuer']===SOCA_CONFIG['issuer'] && $s['allow_domains']===['*.company.com'] && !$s['enabled']); + Settings::save(['issuer'=>'http://invalid','enabled'=>true,'allow_domains'=>'*company.com','button'=>'Deployment test']); + $s=Settings::get();expect($s['issuer']===SOCA_CONFIG['issuer'] && !$s['enabled'] && $s['button']==='Deployment test'); + expect(get_option('soca_settings')['issuer']===$stored['issuer']); + $revision=$s['revision'];expect(Settings::get()['revision']===$revision); + }); + test('deployment fields render disabled in the WordPress settings screen',function(){ + $user=get_current_user_id();wp_set_current_user(1); + try{ob_start();\SOCA\Admin::page();$html=ob_get_clean(); + expect((bool)preg_match('/name="issuer"[^>]* disabled/',$html)); + expect((bool)preg_match('/name="enabled"[^>]* disabled/',$html)); + expect((bool)preg_match('/name="allow_domains"[^>]* disabled/',$html)); + }finally{wp_set_current_user($user);} + }); +} finally {update_option('soca_settings',$stored,false);} +echo ($GLOBALS['passed']??0).' passed, '.($GLOBALS['failed']??0)." failed\n"; +if(!empty($GLOBALS['failed']))\WP_CLI::halt(1); diff --git a/tests/emergency.php b/tests/emergency.php new file mode 100644 index 0000000..69690cf --- /dev/null +++ b/tests/emergency.php @@ -0,0 +1,15 @@ +Settings::profile($s)],false); +define('SOCA_DISABLED',true); +test('emergency disable invalidates activation and pending-transaction revisions once',function()use($epoch,$s){ + $disabled=Settings::get();$first=get_option('soca_epoch'); + expect(Settings::disabled() && $first!==$epoch && $disabled['revision']!==$s['revision']); + expect(!get_option('soca_verified') && !Plugin::loginReady($disabled)); + Settings::get();expect(get_option('soca_epoch')===$first); +}); +echo ($GLOBALS['passed']??0).' passed, '.($GLOBALS['failed']??0)." failed\n"; +if(!empty($GLOBALS['failed']))\WP_CLI::halt(1); diff --git a/tests/fixture-setup.php b/tests/fixture-setup.php index 3657f83..375ac6b 100644 --- a/tests/fixture-setup.php +++ b/tests/fixture-setup.php @@ -1,6 +1,6 @@ new SOCA_Mock_HTTP()); add_action('init',static function(){ + if(isset($_GET['soca_fixture_status'])){\SOCA\Settings::get();wp_send_json(['disabled'=>\SOCA\Settings::disabled()]);} if(!isset($_GET['soca_fixture_authorize']))return; $record=[];foreach(['client_id','redirect_uri','code_challenge','nonce','state']as$key)$record[$key]=\SOCA\Support::scalar($_GET,$key,16384); if(($_GET['code_challenge_method']??'')!=='S256'||($_GET['response_type']??'')!=='code'||($_GET['response_mode']??'')!=='query')wp_die('Invalid fixture request'); diff --git a/tests/multisite.php b/tests/multisite.php index 3415d5c..281c524 100644 --- a/tests/multisite.php +++ b/tests/multisite.php @@ -5,26 +5,27 @@ $site=(int)wp_insert_site(['domain'=>'network.company.com','path'=>'/second/','network_id'=>get_current_network_id()]); expect($site>1,'Failed to create test site'); $root=get_current_blog_id();$rootSettings=Settings::get();$rootKeys=Keys::get();$rootCipher=get_option('soca_keys'); -$state=Support::random();$userAgent=hash('sha256','fixture-agent');Store::createTransaction($state,['verifier'=>'fixture','user_agent'=>$userAgent]); +$browser=Support::random();$state=Support::random();$userAgent=hash('sha256','fixture-agent');Store::createTransaction($state,['verifier'=>'fixture','user_agent'=>$userAgent],$browser); $user=wp_insert_user(['user_login'=>'multisite_fixture','user_pass'=>wp_generate_password(),'user_email'=>'multisite@company.com','role'=>'subscriber']);expect(!is_wp_error($user)); -$s=$rootSettings;$s['allow_domains']=['company.com'];$s['deny_domains']=[];$s['deny_emails']=[]; +$s=$rootSettings;$s['issuer']='https://network-provider.company.com';$s['allow_domains']=['company.com'];$s['deny_domains']=[];$s['deny_emails']=[]; $claims=['iss'=>'https://network-provider.company.com','sub'=>'network-subject','email'=>'multisite@company.com','email_verified'=>true]; -Identity::resolve($claims,$s); +Identity::link((int)$user,$claims['iss'],$claims['sub']);Identity::resolve($claims,$s); switch_to_blog($site);Plugin::initialize(); test('multisite has separate settings, key pairs and encryption context',function()use($rootSettings,$rootKeys,$rootCipher){ $other=Settings::get();expect($other['revision']!==$rootSettings['revision']);expect(Keys::get()['active']!==$rootKeys['active']); $other['provider']='Second site';update_option('soca_settings',$other,false);expect(parse_url(home_url('/'),PHP_URL_PATH)==='/second/');rejects(fn()=>Store::open($rootCipher),'encryption'); }); -test('site cannot consume another site transaction',function()use($state,$userAgent){rejects(fn()=>Store::consumeTransaction($state,$userAgent),'state');}); -test('site cannot authenticate a matching network user who is not a member',function()use($claims,$s){rejects(fn()=>Identity::resolve($claims,$s),'account_missing');}); +test('site cannot consume another site transaction',function()use($state,$userAgent,$browser){rejects(fn()=>Store::consumeTransaction($state,$userAgent,$browser),'state');}); +test('site cannot authenticate a matching network user who is not a member',function()use($claims,$s){rejects(fn()=>Identity::resolve($claims,$s),'identity_unlinked');}); add_user_to_blog($site,(int)$user,'subscriber'); -test('site independently matches the current verified email',function()use($claims,$s,$user){expect(Identity::resolve($claims,$s)->ID===$user);$changed=$claims;$changed['sub']='new-pairwise-subject';expect(Identity::resolve($changed,$s)->ID===$user);}); +Identity::link((int)$user,$claims['iss'],$claims['sub']); +test('site independently resolves the approved identity',function()use($claims,$s,$user){expect(Identity::resolve($claims,$s)->ID===$user);$changed=$claims;$changed['sub']='new-pairwise-subject';rejects(fn()=>Identity::resolve($changed,$s),'identity_unlinked');}); test('removal from one site prevents login on that site',function()use($user,$claims,$s){require_once ABSPATH.'wp-admin/includes/user.php';wp_delete_user((int)$user);rejects(fn()=>Identity::resolve($claims,$s),'account_missing');}); restore_current_blog(); -test('original site settings, key and account access remain intact',function()use($rootSettings,$rootKeys,$user,$state,$userAgent,$claims,$s){expect(Settings::get()===$rootSettings);expect(Keys::get()['active']===$rootKeys['active']);expect(Identity::resolve($claims,$s)->ID===$user);Store::consumeTransaction($state,$userAgent);}); +test('original site settings, key and account access remain intact',function()use($rootSettings,$rootKeys,$user,$state,$userAgent,$browser,$claims,$s){expect(Settings::get()===$rootSettings);expect(Keys::get()['active']===$rootKeys['active']);expect(Identity::resolve($claims,$s)->ID===$user);Store::consumeTransaction($state,$userAgent,$browser);}); test('a network spam flag prevents authentication of the matching account',function()use($claims,$s,$user){ global $wpdb;$wpdb->update($wpdb->users,['spam'=>1],['ID'=>$user]);clean_user_cache($user);rejects(fn()=>Identity::resolve($claims,$s),'account_blocked'); $wpdb->update($wpdb->users,['spam'=>0],['ID'=>$user]);clean_user_cache($user); }); -require_once ABSPATH.'wp-admin/includes/ms.php';wpmu_delete_user((int)$user);rejects(fn()=>Identity::resolve($claims,$s),'registration_disabled');wp_delete_site($site); +require_once ABSPATH.'wp-admin/includes/ms.php';wpmu_delete_user((int)$user);rejects(fn()=>Identity::resolve($claims,$s),'account_missing');delete_option('soca_link_'.hash('sha256',Support::json([$claims['iss'],$claims['sub']])));switch_to_blog($site);delete_option('soca_link_'.hash('sha256',Support::json([$claims['iss'],$claims['sub']])));restore_current_blog();wp_delete_site($site); echo ($GLOBALS['passed']??0).' passed, '.($GLOBALS['failed']??0)." failed\n";if(!empty($GLOBALS['failed']))WP_CLI::halt(1); diff --git a/tests/protocol.php b/tests/protocol.php index 352d98b..9f4728a 100644 --- a/tests/protocol.php +++ b/tests/protocol.php @@ -42,7 +42,35 @@ expect(Policy::entries("Company.com, company.com;other.com\n",false)===['company.com','other.com']); foreach (['*.company.com','company.com.','company.com/','@company.com','localhost','127.0.0.1','аpple.com'] as $v) rejects(fn()=>Policy::domain($v)); }); -test('public HTTPS defaults enable self-hosted login for the exact hostname',function(){ $s=Settings::defaults();expect($s['allow_domains']===['client.company.com'] && $s['mode']==='self' && $s['key_mode']==='uri' && $s['enabled'] && !$s['unrestricted'] && $s['assertion_audience']==='issuer' && $s['button']==='Continue with SSO' && $s['proxy']==='https://dynamic-cimd.resoauth.cloud/cimd/%s'); }); +test('wildcard domain rules respect DNS label boundaries and deny precedence',function(){ + $s=settings();$s['allow_domains']=['*.example.com'];$s['deny_domains']=['*.blocked.example.com']; + expect(Policy::test($s,'a@x.example.com',true)[0]);expect(Policy::test($s,'a@a.b.example.com',true)[0]); + expect(!Policy::test($s,'a@example.com',true)[0]);expect(!Policy::test($s,'a@badexample.com',true)[0]); + expect(!Policy::test($s,'a@x.blocked.example.com',true)[0]); + expect(Policy::entries('*.EXAMPLE.COM example.com',false)===['*.example.com','example.com']); + foreach(['*example.com','*.*.example.com','a.*.example.com','*.com','https://example.com','a@example.com','a..example.com']as$rule) rejects(fn()=>Policy::entries($rule,false),'domain'); + $s['deny_domains']=['*example.com'];rejects(fn()=>Policy::test($s,'a@x.example.com',true),'domain'); + $s['deny_domains']=[];$s['allow_domains']=['example.com'];expect(!Policy::test($s,'a@x.example.com',true)[0]); +}); +test('metadata inherits available branding and legal URLs in both modes',function(){ + update_option('test_icon','https://www.client.company.com/icon.png');update_option('test_privacy','https://www.client.company.com/privacy/'); + try { + foreach(['self','proxy']as$mode){ + $s=settings();$s['mode']=$mode;$doc=Metadata::document($s); + expect($doc['logo_uri']==='https://www.client.company.com/icon.png' && $doc['policy_uri']==='https://www.client.company.com/privacy/' && !isset($doc['tos_uri'])); + $s['client_name']='Custom site';$s['logo_uri']='https://www.client.company.com/brand.png';$s['tos_uri']='https://www.client.company.com/terms/'; + $doc=Metadata::document($s);expect($doc['client_name']==='Custom site' && $doc['logo_uri']===$s['logo_uri'] && $doc['tos_uri']===$s['tos_uri']); + } + update_option('test_icon','http://www.client.company.com/icon.png');expect(!isset(Metadata::template(settings())['logo_uri'])); + }finally{delete_option('test_icon');delete_option('test_privacy');} +}); +test('proxy encoding is deterministic, excludes client_id and rejects oversized metadata',function(){ + $s=settings();$s['mode']='proxy';$s['key_mode']='inline';$id=Metadata::clientId($s);expect(Metadata::clientId($s)===$id); + $encoded=substr($id,strlen('https://dynamic-cimd.resoauth.cloud/cimd/'));$payload=Support::object(Support::unb64($encoded)); + expect(!isset($payload['client_id']) && count($payload['jwks']['keys'])===2); + $s['logo_uri']='https://www.client.company.com/'.str_repeat('a',3000);$s['policy_uri']=$s['logo_uri'];$s['tos_uri']=$s['logo_uri'];$s=Settings::validate($s);rejects(fn()=>Metadata::clientId($s),'proxy_size'); +}); +test('public HTTPS defaults require activation before self-hosted login for the exact hostname',function(){ $s=Settings::defaults();expect($s['allow_domains']===['client.company.com'] && $s['mode']==='self' && $s['key_mode']==='uri' && !$s['enabled'] && !$s['unrestricted'] && $s['assertion_audience']==='issuer' && $s['button']==='Continue with SSO' && $s['proxy']==='https://dynamic-cimd.resoauth.cloud/cimd/%s'); }); test('settings initialize with current names and defaults',function(){ $s=Settings::get(); expect($s['assertion_audience']==='issuer' && is_array(get_option('soca_settings'))); diff --git a/tests/wordpress.php b/tests/wordpress.php index c66cee0..d7b1e5a 100644 --- a/tests/wordpress.php +++ b/tests/wordpress.php @@ -6,6 +6,7 @@ $before=Settings::get();$created=[]; $make=function($name,$email,$role='subscriber')use(&$created){$id=wp_insert_user(['user_login'=>$name,'user_pass'=>'Test-only-password!','user_email'=>$email,'role'=>$role]);expect(!is_wp_error($id),is_wp_error($id)?$id->get_error_message():'');$created[]=$id;return (int)$id;}; $s=$before;$s['allow_domains']=['company.com'];$s['allow_emails']=[];$s['deny_domains']=[];$s['deny_emails']=[];$s['unrestricted']=false;$s['create_users']=false; +$s['issuer']='https://fixture.company.com'; $c=['iss'=>'https://fixture.company.com','sub'=>'wp-test-1','email'=>'ordinary@company.com','email_verified'=>true]; try { test('localhost defaults keep login off and infer no domain',function(){ @@ -32,7 +33,7 @@ } }); test('allow-any save preserves hidden allowlists while deny rules still win',function()use($before){ - $input=$before; + $input=$before;$input['revision']=Settings::get()['revision']; foreach (['allow_domains','allow_emails','deny_domains','deny_emails'] as $key) { $input[$key]=implode("\n",$before[$key]); } unset($input['allow_domains'],$input['allow_emails']); $input['unrestricted']='1'; $input['deny_domains']='blocked.company.com'; @@ -43,6 +44,18 @@ expect(!Policy::test($saved,'person@blocked.company.com',true)[0]); } finally { update_option('soca_settings',$before,false); } }); + test('stale settings edits are rejected and candidate evidence gates login',function()use($before){ + try { + $current=Settings::get();$saved=Settings::save(['button'=>'A fresh label','revision'=>$current['revision']]); + rejects(fn()=>Settings::save(['button'=>'A stale label','revision'=>$current['revision']]),'stale_settings'); + expect(Settings::get()['button']==='A fresh label'); + expect(Settings::save(['button'=>'A fresh label'])['revision'] === $saved['revision']); + $saved=Settings::save(['enabled'=>true]);expect(!Plugin::loginReady($saved)); + update_option('soca_verified',['profile'=>Settings::profile($saved)],false);expect(Plugin::loginReady($saved)); + $saved=Settings::save(['automatic'=>true]);expect(Plugin::loginReady($saved)); + $saved=Settings::save(['allow_domains'=>['*.company.com']]);expect(!Plugin::loginReady($saved)); + } finally { update_option('soca_settings',$before,false);delete_option('soca_verified'); } + }); test('keys are encrypted and not autoloaded',function(){global $wpdb;expect(count(Keys::get()['items'])===2);$row=$wpdb->get_row("SELECT option_value,autoload FROM {$wpdb->options} WHERE option_name='soca_keys'",ARRAY_A);expect(!str_contains($row['option_value'],'PRIVATE KEY'));expect(in_array($row['autoload'],['off','no','auto-off'],true));}); test('new callback hook is registered and profile identity controls are absent',function(){ expect(plugin_basename(SOCA_FILE)==='simple-oauth-cimd-access/simple-oauth-cimd-access.php'); @@ -75,11 +88,13 @@ finally { remove_filter('soca_http',$current); } }); test('single-use and encrypted transactions',function(){ - $state=Support::random();$ref='abcdef123456';$ua=hash('sha256','fixture-agent');Store::createTransaction($state,['verifier'=>'confidential-verifier','audit_ref'=>$ref,'purpose'=>'login','user_agent'=>$ua]); + $browser=Support::random();$state=Support::random();$ref='abcdef123456';$ua=hash('sha256','fixture-agent');Store::createTransaction($state,['verifier'=>'confidential-verifier','audit_ref'=>$ref,'purpose'=>'login','user_agent'=>$ua],$browser); $key='soca_tx_'.hash('sha256',$state);$raw=get_transient($key);expect(is_string($raw) && !str_contains($raw,'confidential-verifier')); - rejects(fn()=>Store::consumeTransaction($state,hash('sha256','different-agent')),'user_agent_mismatch'); - expect(Store::consumeTransaction($state,$ua)['verifier']==='confidential-verifier');rejects(fn()=>Store::consumeTransaction($state,$ua),'state'); - $state=Support::random();Store::createTransaction($state,['user_agent'=>$ua]);delete_transient('soca_tx_'.hash('sha256',$state));rejects(fn()=>Store::consumeTransaction($state,$ua),'state'); + rejects(fn()=>Store::consumeTransaction($state,hash('sha256','different-agent'),$browser),'user_agent_mismatch'); + rejects(fn()=>Store::consumeTransaction($state,$ua,Support::random()),'browser_binding'); + rejects(fn()=>Store::consumeTransaction($state,$ua,''),'browser_binding'); + expect(Store::consumeTransaction($state,$ua,$browser)['verifier']==='confidential-verifier');rejects(fn()=>Store::consumeTransaction($state,$ua,$browser),'state'); + $state=Support::random();Store::createTransaction($state,['user_agent'=>$ua],$browser);delete_transient('soca_tx_'.hash('sha256',$state));rejects(fn()=>Store::consumeTransaction($state,$ua,$browser),'state'); }); $ordinary=$make('soca-test-ordinary','ordinary@company.com');$admin=$make('soca-test-admin','privileged@company.com','administrator'); $ordinary2=$make('soca-test-ordinary2','ordinary2@company.com'); @@ -98,7 +113,7 @@ expect(str_contains($html,'action="#soca-access-test"') && str_contains($html,'value="ordinary@company.com"')); $result=strpos($html,'id="soca-policy-result"'); $input=strpos($html,'id="test_email"'); $operations=strpos($html,'

Operations

'); expect($result!==false && $input!==false && $operations!==false && $input<$result && $result<$operations); - expect(str_contains($html,'Allowed for ordinary@company.com: Exact domain allow rule matches')); + expect(str_contains($html,'Allowed for ordinary@company.com: Domain allow rule matches')); $configured['deny_emails']=['ordinary@company.com']; update_option('soca_settings',$configured,false); ob_start(); \SOCA\Admin::page(); $denied=ob_get_clean(); expect(str_contains($denied,'Denied for ordinary@company.com: Email deny rule wins')); @@ -109,21 +124,48 @@ if ($originalMethod===null) { unset($_SERVER['REQUEST_METHOD']); } else { $_SERVER['REQUEST_METHOD']=$originalMethod; } } }); - test('verified email selects an existing account on every login',function()use($c,$s,$ordinary){expect(Identity::resolve($c,$s)->ID===$ordinary);expect(Identity::resolve($c,$s)->ID===$ordinary);}); - test('a changed subject still selects the same verified email account',function()use($c,$s,$ordinary){$changed=$c;$changed['sub']='wp-test-changed';expect(Identity::resolve($changed,$s)->ID===$ordinary);}); - test('a changed verified email selects its current local account',function()use($c,$s,$ordinary,$ordinary2){$changed=$c;$changed['email']='ordinary2@company.com';expect(Identity::resolve($changed,$s)->ID===$ordinary2);expect(get_userdata($ordinary)->user_email==='ordinary@company.com');}); - test('verified email also selects an administrator by default',function()use($c,$s,$admin){$c['email']='privileged@company.com';$c['sub']='wp-admin-sub';expect(Identity::resolve($c,$s)->ID===$admin);expect(in_array('administrator',get_userdata($admin)->roles,true));}); - test('verified email matches another ordinary account',function()use($c,$s,$ordinary2){$c['sub']='wp-ordinary2';$c['email']='ordinary2@company.com';expect(Identity::resolve($c,$s)->ID===$ordinary2);}); + test('email alone cannot select an existing ordinary or administrator account',function()use($c,$s){ + rejects(fn()=>Identity::resolve($c,$s),'identity_unlinked'); + $c['email']='privileged@company.com'; rejects(fn()=>Identity::resolve($c,$s),'identity_unlinked'); + }); + test('administrator-approved issuer and subject select the linked account',function()use($c,$s,$ordinary,$ordinary2){ + Identity::link($ordinary,$c['iss'],$c['sub']); + expect(Identity::resolve($c,$s)->ID===$ordinary); + Identity::link($ordinary,$c['iss'],$c['sub']); + rejects(fn()=>Identity::link($ordinary2,$c['iss'],$c['sub']),'identity_conflict'); + }); + test('a changed subject cannot silently relink by email',function()use($c,$s){$c['sub']='changed-subject';rejects(fn()=>Identity::resolve($c,$s),'identity_unlinked');}); + test('a changed email never selects a different local account',function()use($c,$s,$ordinary){$c['email']='ordinary2@company.com';expect(Identity::resolve($c,$s)->ID===$ordinary);}); + test('privileged accounts require explicit approval and retain their role',function()use($c,$s,$admin){$c['sub']='wp-admin-sub';$c['email']='privileged@company.com';Identity::link($admin,$c['iss'],$c['sub']);expect(Identity::resolve($c,$s)->ID===$admin);expect(in_array('administrator',get_userdata($admin)->roles,true));}); + Identity::link($ordinary2,$c['iss'],'wp-ordinary2'); test('registration off; explicit controlled creation is subscriber only',function()use($c,$s,&$created){$c['sub']='wp-new';$c['email']='new@company.com';rejects(fn()=>Identity::resolve($c,$s),'registration_disabled');$s['create_users']=true;$c['role']='administrator';$c['roles']=['administrator'];$u=Identity::resolve($c,$s);$created[]=$u->ID;expect($u->roles===['subscriber']);}); test('email_verified must be boolean true and denial applies on every login',function()use($c,$s){$c['email_verified']='true';rejects(fn()=>Identity::resolve($c,$s),'access_denied');$c['email_verified']=true;$s['deny_domains']=['company.com'];rejects(fn()=>Identity::resolve($c,$s),'access_denied');}); $dup=$make('soca-test-duplicate','temporary@company.com'); test('ambiguous local emails rejected',function()use($c,$s,$dup){global $wpdb;$wpdb->update($wpdb->users,['user_email'=>'ordinary2@company.com'],['ID'=>$dup]);try {$c['email']='ordinary2@company.com';$c['sub']='ambiguous-sub';rejects(fn()=>Identity::resolve($c,$s),'ambiguous_email');} finally {$wpdb->update($wpdb->users,['user_email'=>'temporary@company.com'],['ID'=>$dup]);clean_user_cache($dup);}}); test('existing custom capabilities remain unchanged',function()use($ordinary2,$c,$s){$u=get_userdata($ordinary2);$u->add_cap('edit_posts');$c['sub']='wp-ordinary2';$c['email']='ordinary2@company.com';expect(Identity::resolve($c,$s)->ID===$ordinary2);expect(get_userdata($ordinary2)->has_cap('edit_posts'));$u->remove_cap('edit_posts');}); + test('unlink revokes identity reuse and all local sessions until explicit approval',function()use($c,$s,$ordinary){ + $token=WP_Session_Tokens::get_instance($ordinary)->create(time()+3600); + Identity::unlink($ordinary,$c['iss'],$c['sub']); + expect(!WP_Session_Tokens::get_instance($ordinary)->verify($token)); + $changed=$c;$changed['email']='changed-new@company.com';$allow=$s;$allow['create_users']=true; + rejects(fn()=>Identity::resolve($changed,$allow),'identity_revoked'); + Identity::link($ordinary,$c['iss'],$c['sub']);expect(Identity::resolve($c,$s)->ID===$ordinary); + }); + test('failed identity-link storage rolls back a newly created account',function()use($c,$s,$ordinary){ + $c['sub']='rollback-sub';$c['email']='rollback@company.com';$s['create_users']=true; + $key='soca_link_'.hash('sha256',Support::json([$c['iss'],$c['sub']])); + $interfere=static function($id)use($key,$ordinary,$c){add_option($key,Store::seal(['issuer'=>$c['iss'],'subject'=>$c['sub'],'user'=>$ordinary]),'',false);}; + add_action('user_register',$interfere); + try{rejects(fn()=>Identity::resolve($c,$s),'identity_conflict');expect(!email_exists('rollback@company.com'));} + finally{remove_action('user_register',$interfere);delete_option($key);} + }); test('redacted audit keeps failure step, reason and reference',function(){Support::audit('login_started',0,['flow'=>'login','ref'=>'abcdef123456']);Support::audit('login_failed',0,['flow'=>'login','step'=>'token_exchange','reason'=>'token_http_status','ref'=>'abcdef123456','http_status'=>401,'email'=>'secret@company.com','token'=>'access_token']);$log=get_option('soca_audit');$last=end($log);expect($last['event']==='login_failed' && $last['step']==='token_exchange' && $last['reason']==='token_http_status' && $last['ref']==='abcdef123456' && $last['http_status']===401);$json=Support::json($log);expect(!str_contains($json,'@company.com') && !str_contains($json,'wp-test-1') && !str_contains($json,'access_token'));}); test('public metadata exposes public keys only and no access policy',function(){ $d=Metadata::document(Settings::get(),true);Metadata::noPrivateKeys($d);$j=Support::json($d);expect(!str_contains($j,'allow_domains') && !str_contains($j,'PRIVATE KEY')); }); } finally { require_once ABSPATH.'wp-admin/includes/user.php'; foreach($created as $id) wp_delete_user($id); + global $wpdb; + foreach ($wpdb->get_col($wpdb->prepare("SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s",$wpdb->esc_like('soca_link_').'%')) as $key) { $link=Store::open(get_option($key)); if (in_array($link['user'],$created,true)) delete_option($key); } update_option('soca_settings',$before,false); } echo ($GLOBALS['passed']??0).' passed, '.($GLOBALS['failed']??0)." failed\n"; diff --git a/tools/build.py b/tools/build.py index 479aae6..141c25b 100644 --- a/tools/build.py +++ b/tools/build.py @@ -3,7 +3,7 @@ import hashlib, json, pathlib, re, zipfile root=pathlib.Path(__file__).resolve().parents[1] out=root/'dist';out.mkdir(exist_ok=True) -version='0.2.0' +version='0.3.0' def archive(path,items): with zipfile.ZipFile(path,'w',zipfile.ZIP_DEFLATED,compresslevel=9) as z: for target,source in sorted(items): diff --git a/tools/check_release.py b/tools/check_release.py index b6855a2..f6348ca 100644 --- a/tools/check_release.py +++ b/tools/check_release.py @@ -9,7 +9,7 @@ readme = (root / 'simple-oauth-cimd-access/readme.txt').read_text() build = (root / 'tools/build.py').read_text() version = re.search(r'^ \* Version: (\S+)$', header, re.M).group(1) -assert version == '0.2.0', f'unexpected release version {version}' +assert version == '0.3.0', f'unexpected release version {version}' assert f'Stable tag: {version}' in readme assert f"version='{version}'" in build assert 'Author: RESOAuth' in header