diff --git a/CLAUDE.md b/CLAUDE.md index 7a05de3..d4356e3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,7 +5,7 @@ SPDX-License-Identifier: MIT # wsfed-caep -Java 25 port of the server-side WS-Federation relying party. Group `com.iyasec`, artifact `wsfed-caep`, packages under `com.iyasec.wsfed`. License MIT (`LICENSE`). A pull request merged into `main` publishes the library (`library/` only; the demo never) to Maven Central after the test workflow succeeds on that commit. A direct push does not. `publish.yml` runs `mvn -Prelease -f library/pom.xml deploy` in the Maven container: the `release` profile adds the sources and javadoc jars, a GPG signature on every file, and the Central publishing plugin, which uploads, publishes and waits until the release is live. Maven Central has no trusted publishing, so the job uses four repository secrets: `CENTRAL_TOKEN_USERNAME` and `CENTRAL_TOKEN_PASSWORD` (a Central Portal user token) and `GPG_PRIVATE_KEY` and `GPG_PASSPHRASE` (the release signing key, whose public half is on a public key server). A release happens when the library's files changed since the last release's tag: `publish.yml` takes one patch above the highest published version, publishes it, and creates the matching tag and GitHub Release. A change to tests, the demo, or the docs releases nothing. To choose a version or start a new minor, raise `VERSION`; the version is stamped in CI and is not committed, so the manifests can trail what is published. `-Dcentral.skipPublishing=true` builds and signs everything and uploads nothing. When this tree is published, `develop` and `main` are the same commit. +Java port of the server-side WS-Federation relying party. Bytecode is 17. The runtime image is `eclipse-temurin:25-jre` and the test image is `maven:3.9-eclipse-temurin-26`. Group `com.iyasec`, artifact `wsfed-caep`, packages under `com.iyasec.wsfed`. License MIT (`LICENSE`). A pull request merged into `main` publishes the library (`library/` only; the demo never) to Maven Central after the test workflow succeeds on that commit. A direct push does not. `publish.yml` runs `mvn -Prelease -f library/pom.xml deploy` in the Maven container: the `release` profile adds the sources and javadoc jars, a GPG signature on every file, and the Central publishing plugin, which uploads, publishes and waits until the release is live. Maven Central has no trusted publishing, so the job uses four repository secrets: `CENTRAL_TOKEN_USERNAME` and `CENTRAL_TOKEN_PASSWORD` (a Central Portal user token) and `GPG_PRIVATE_KEY` and `GPG_PASSPHRASE` (the release signing key, whose public half is on a public key server). A release happens when the library's files changed since the last release's tag: `publish.yml` takes one patch above the highest published version, publishes it, and creates the matching tag and GitHub Release. A change to tests, the demo, or the docs releases nothing. To choose a version or start a new minor, raise `VERSION`; the version is stamped in CI and is not committed, so the manifests can trail what is published. `-Dcentral.skipPublishing=true` builds and signs everything and uploads nothing. The embedded PEP depends on `com.iyasec:iya-pep`, which is not on Maven Central yet, so this work stays on `develop` until that artifact's first release. A merge to `main` publishes this library. ## Usage @@ -17,6 +17,23 @@ The party accepts SAML 2.0 assertions with bearer confirmation `urn:oasis:names: Omitted or `true` means on. The resolved configuration leaves `signals` null in that case. `false` is stored as `Boolean.FALSE`, does not start the receiver, and does not require transmitter metadata. The relying party never starts the receiver itself; `SignalsReceiver` is separate. Sign-in does not change when signals are off, because WS-Federation does not send OAuth scopes. A non-boolean raises a config error: `signals must be true or false`. The shipped demo omits the key. +`ssf.clientCertificate` and `ssf.clientKey` are the receiver's own TLS client identity (PEM, `file:` or `env:`, both or neither). `Resolved.ssfTlsClient()` answers that pair, else the relying party's certificate and `privateKey`, else null. The demo refuses to start the receiver when there is none. `ssf.addSubjects` defaults to true. Anything but a boolean refuses to start the receiver, with the message `ssf.addSubjects must be true or false`. `track` adds the session and then POSTs `add_subject_endpoint` `{stream_id, subject, verified: true}`. `untrack` and an event-ended session remove the subject only when no other session for that person remains. The subject is `iss_sub` (the transmitter's issuer and the session's person, which stays `nameidentifier`) else `email`. The call is inline, once, and never fails sign-in. When the embedded PEP wants events, `start` also adds the application once, `{format: opaque, id: application}`, and never removes it, so a stream that names subjects still delivers `pep-policies-changed`. + +## Embedded PEP + +iya-sts#1206. There is no feature flag. `library/pom.xml` depends on `com.iyasec:iya-pep:0.1.0`. The `test` and `build` stages of the Dockerfile clone `https://github.com/rcbj/iya-pep-java.git` branch `develop` and `mvn -B -DskipTests install` it before this library. One attempt: if that branch is not pushed, the build stops. Bytecode is 17. The runtime image is `eclipse-temurin:25-jre`. The test image is `maven:3.9-eclipse-temurin-26`. This stays on `develop` until `iya-pep` is on Maven Central. + +`com.iyasec.wsfed.pep.EmbeddedPep` builds `com.iyasec.pep.Pep` from the `pep` object. `RelyingParty.create` and `fromFile` do that after metadata is read, then `pep.start()`. + +- `pdpUrl` defaults to the identity provider's entityID, the realm issuer with `/realm/` included. `application` defaults to `realm`. `signals` is the library's (`null` or `true` is on; `Boolean.FALSE` is off). `tlsCa` is `idpCa` when that value contains a PEM certificate. A missing `mode` is `local`. An unknown member is refused. +- `assertionKey` is resolved like `privateKey` (`file:` stripped, a relative path from the configuration's directory) and left as a path. The PEM is not stored in the section. +- A PEP assertion key equal to `privateKey` is refused, and `SignalsReceiver` refuses a TLS client key equal to the PEP key. Both compare JWK thumbprints (`SigningKey.jwkThumbprint`, `SigningKey.pemThumbprint`). An empty thumbprint is not a match. +- When the PEP wants events (`Mode.LOCAL`, or `permitCacheMs` greater than 0), the receiver adds `Pep.POLICIES_CHANGED_EVENT` (`urn:iya:sts:secevent:event-type:pep-policies-changed`), calls `pep.onPolicyEvent` after SET verification, and reports the stream with `setEventStream`: `requested` or `excluded` at start and after a good poll, `down` after a failed poll and on `stop`. A reused stream that lacks the event is PATCHed; a refusal is logged and the receiver still starts. +- `decide` and `decideSession` build the subject with `EmbeddedPep.subjectOf`. The id is the `name` claim (`http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name`), else the NameID. iya-sts puts the username in both. `nameidentifier` is the opaque sub and is never the id. Properties are attributes keyed by FriendlyName, else the Name's last segment (`[A-Za-z0-9_$@:-]`, 1 to 64, no dot), then `acr`, `amr` (always an array) and `auth_time`. `decideSession` denies a session past `SessionNotOnOrAfter` (`the identity provider's session has ended`) or one the receiver no longer tracks (`no signed-in session`). No `pep` section is Unavailable, `no pep section is configured`. `decide` does not throw. `Decision.httpStatus()` is 200 only for a Permit and 403 for a Deny and an Unavailable. +- The demo answers `GET /attribute-protected` (`read` / `attribute-protected` / `attr1`) and `/orders/{id}` (`read` on GET, `write` otherwise, type `order`) with that status. No sign-in is 401, asked before the PEP. `GET /live-status` includes the PEP status under `pep`. `GET /pep-status` is that status as JSON. + +`docs/remote-pep.md` is the user guide. + ## Errors `Caught.error` records a caught exception through `java.lang.System.Logger`, including the stack, and the method then throws the `WsFedError` it already threw. The caught exception is the cause. `Caught.warn` is the same record when the method recovers and does not throw: a later signing key, a poll retry, a false verification, sign-out cleanup, or a handler that must still acknowledge the Security Event Token. A `catch (WsFedError)` that only throws that error again is not logged a second time. @@ -31,7 +48,7 @@ docker build --target test . The `test` stage runs `mvn -B test` in `maven:3.9-eclipse-temurin-26`. GitHub Actions uses that command. Do not run Maven on the host. The demo stage packages with `-DskipTests` in its own Maven image. -JUnit 5 covers the stub IdP (a signed SAML assertion the library accepts), replay, metadata, the self-signed certificate, the SSF poll receiver, the demo handler, and the trust chain (`TrustChainTest`: the install script's code and `scripts/trust_chain.py` write the four-certificate chain to `idpCa`'s path, the handshake fallback keeps every block, the library trusts the provider and a reissued leaf through that file, and refuses a forged leaf followed by the real CA certificates and the right chain under the wrong host name). The test stage installs python3 and openssl for it. The stub tests do not start iya-sts. `python3 scripts/live_iya_sts.py` does, unless `IYA_STS_URL` names one that is already running. It signs the demo in and checks two Shared Signals events on `GET /live-status`. iya-sts main sets the assertion SessionIndex to the assertion id, so a session-revoked subject that names the sign-on session matches nobody. The demo ends its one session from that handler. The nightly workflow, cron `51 6 * * *` plus workflow_dispatch, runs the unit image and that script. It never binds port 3000, 8081 or 18481-18495; its defaults are 18553 (iya-sts) and 18653 (the demo). It builds the demo the way a user does: install script first (writing the chain), then the image build, then the run with only `rp.key`, `rp.crt` and `idp-metadata.xml` mounted. No CA mount, no `idpCa` rewrite. Secrets go to docker as `-e NAME`; no log line carries a sign-in URL. `scripts/configure_iya_sts.py` is the same registration script as the Python tree; its plan is exercised there. Configure is host Python and does not import this library. +JUnit 5 covers the stub IdP (a signed SAML assertion the library accepts), replay, metadata, the self-signed certificate, the SSF poll receiver, the demo handler, and the trust chain (`TrustChainTest`: the install script's code and `scripts/trust_chain.py` write the four-certificate chain to `idpCa`'s path, the handshake fallback keeps every block, the library trusts the provider and a reissued leaf through that file, and refuses a forged leaf followed by the real CA certificates and the right chain under the wrong host name). The test stage installs python3 and openssl for it. The stub tests do not start iya-sts. `python3 scripts/live_iya_sts.py` does, unless `IYA_STS_URL` names one that is already running. It signs the demo in and checks two Shared Signals events on `GET /live-status`. iya-sts main sets the assertion SessionIndex to the assertion id, so a session-revoked subject that names the sign-on session matches nobody. The demo ends its one session from that handler. The nightly workflow, cron `51 6 * * *` plus workflow_dispatch, runs the unit image and that script. It never binds port 3000, 8081 or 18481-18495; its defaults are 18553 (iya-sts) and 18653 (the demo). It builds the demo the way a user does: install script first (writing the chain and, when signals are on, the realm-issued Shared Signals client certificate), then the image build, then the run with `rp.key`, `rp.crt` and `idp-metadata.xml` mounted file by file, plus `ssf-client.key` and `ssf-client.crt` when those files exist, and `pep-key.pem` when `--pep` (or `LIVE_PEP=1`) was set. The image's `demo/generated` is checked to hold only `idp-ca.pem`. No CA mount, no `idpCa` rewrite. `--pep` runs central, then the same image with `WSFED_CONFIG=demo/wsfed.pep-local.json`. Secrets go to docker as `-e NAME`; no log line carries a sign-in URL. `scripts/configure_iya_sts.py` is this tree's install script. It is not shared with the Python tree. Configure is host Python and does not import this library. ## Layout diff --git a/Dockerfile b/Dockerfile index 86328fa..d08c4bc 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,8 +5,9 @@ # The demo image below does not run it. FROM maven:3.9-eclipse-temurin-26 AS test # TrustChainTest runs the install script's trust-chain code: python3, and the -# openssl CLI it reads certificate names with. -RUN apt-get update && apt-get install -y --no-install-recommends python3 openssl && rm -rf /var/lib/apt/lists/* +# openssl CLI it reads certificate names with. git fetches iya-pep, which is +# not on Maven Central yet. +RUN apt-get update && apt-get install -y --no-install-recommends python3 openssl git ca-certificates && rm -rf /var/lib/apt/lists/* WORKDIR /src # Both modules: library/ (the published library) and demo/ (the demo, HttpDemoTest, # and TrustChainTest, which runs scripts/ against demo/wsfed.json). @@ -16,14 +17,29 @@ COPY demo/pom.xml demo/pom.xml COPY demo/src demo/src COPY scripts ./scripts COPY demo/wsfed.json demo/wsfed.json +# iya-pep is installed from commit d2bbf5ee73a93ec3b2aeb01219fc093fbb41c645 before this library's tests. +RUN git init /tmp/iya-pep-java \ + && git -C /tmp/iya-pep-java remote add origin https://github.com/rcbj/iya-pep-java.git \ + && git -C /tmp/iya-pep-java fetch --depth 1 origin d2bbf5ee73a93ec3b2aeb01219fc093fbb41c645 \ + && git -C /tmp/iya-pep-java checkout --detach FETCH_HEAD \ + && mvn -B -DskipTests -f /tmp/iya-pep-java/pom.xml install \ + && rm -rf /tmp/iya-pep-java RUN mvn -B test FROM maven:3.9-eclipse-temurin-26 AS build +RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates && rm -rf /var/lib/apt/lists/* WORKDIR /src COPY pom.xml . COPY library library COPY demo/pom.xml demo/pom.xml COPY demo/src demo/src +# The same install as the test stage: the demo package resolves com.iyasec:iya-pep. +RUN git init /tmp/iya-pep-java \ + && git -C /tmp/iya-pep-java remote add origin https://github.com/rcbj/iya-pep-java.git \ + && git -C /tmp/iya-pep-java fetch --depth 1 origin d2bbf5ee73a93ec3b2aeb01219fc093fbb41c645 \ + && git -C /tmp/iya-pep-java checkout --detach FETCH_HEAD \ + && mvn -B -DskipTests -f /tmp/iya-pep-java/pom.xml install \ + && rm -rf /tmp/iya-pep-java # The demo module copies its runtime dependencies, the library among them, to demo/target/dependency. RUN mvn -B -DskipTests package FROM eclipse-temurin:25-jre diff --git a/README.md b/README.md index 24d6bdf..89127aa 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ SPDX-License-Identifier: MIT Server-side WS-Federation relying party for Java 17. It accepts SAML 2.0 bearer assertions, reads identity-provider federation metadata, writes relying-party metadata, verifies XML signatures, decrypts encrypted assertions, and remembers assertion ids so a bearer token cannot be replayed. A Shared Signals poll receiver for CAEP and RISC is included. The relying party does not start that receiver. -Group `com.iyasec`, artifact `wsfed-caep`. License: MIT. A pull request merged into `main` publishes the library (`library/` only; the demo never) to Maven Central after the test workflow succeeds on that commit. A direct push does not. `publish.yml` runs `mvn -Prelease -f library/pom.xml deploy` in the Maven container: the `release` profile adds the sources and javadoc jars, a GPG signature on every file, and the Central publishing plugin, which uploads, publishes and waits until the release is live. Maven Central has no trusted publishing, so the job uses four repository secrets: `CENTRAL_TOKEN_USERNAME` and `CENTRAL_TOKEN_PASSWORD` (a Central Portal user token) and `GPG_PRIVATE_KEY` and `GPG_PASSPHRASE` (the release signing key, whose public half is on a public key server). A release happens when the library's files changed since the last release's tag: `publish.yml` takes one patch above the highest published version, publishes it, and creates the matching tag and GitHub Release. A change to tests, the demo, or the docs releases nothing. To choose a version or start a new minor, raise `VERSION`; the version is stamped in CI and is not committed, so the manifests can trail what is published. `-Dcentral.skipPublishing=true` builds and signs everything and uploads nothing. `develop` and `main` are the same commit when this tree is published; nothing here creates a remote. +Group `com.iyasec`, artifact `wsfed-caep`. License: MIT. A pull request merged into `main` publishes the library (`library/` only; the demo never) to Maven Central after the test workflow succeeds on that commit. A direct push does not. `publish.yml` runs `mvn -Prelease -f library/pom.xml deploy` in the Maven container: the `release` profile adds the sources and javadoc jars, a GPG signature on every file, and the Central publishing plugin, which uploads, publishes and waits until the release is live. Maven Central has no trusted publishing, so the job uses four repository secrets: `CENTRAL_TOKEN_USERNAME` and `CENTRAL_TOKEN_PASSWORD` (a Central Portal user token) and `GPG_PRIVATE_KEY` and `GPG_PASSPHRASE` (the release signing key, whose public half is on a public key server). A release happens when the library's files changed since the last release's tag: `publish.yml` takes one patch above the highest published version, publishes it, and creates the matching tag and GitHub Release. A change to tests, the demo, or the docs releases nothing. To choose a version or start a new minor, raise `VERSION`; the version is stamped in CI and is not committed, so the manifests can trail what is published. `-Dcentral.skipPublishing=true` builds and signs everything and uploads nothing. The embedded PEP depends on `com.iyasec:iya-pep`, which is not on Maven Central yet. This work stays on `develop` until that artifact's first release, because a merge to `main` publishes this library. ## Usage @@ -17,10 +17,14 @@ RelyingParty.LoginRequest request = rp.login(Map.of("relayState", "/")); WsFedLogin who = rp.handleReply(Map.of("method", "POST", "url", "/wsfed", "body", body), request.id); ``` -Methods are the TypeScript names: `fromFile`, `login`, `handleReply`, `resolveConfig`, `readConfigFile`. JSON keys match the Node configuration: `realm`, `replyUrl`, `idpMetadata`, `privateKey`, `certificate`, `idpCa`, `idpEntityId`, `clockSkewSeconds`, `wantAssertionsEncrypted`, `allowUnsolicited`, `requestTokenType`, `signals`, `ssf`. `file:` and `env:` prefixes are accepted. The default subject attribute is `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier`. +Methods are the TypeScript names: `fromFile`, `login`, `handleReply`, `resolveConfig`, `readConfigFile`. JSON keys match the Node configuration: `realm`, `replyUrl`, `idpMetadata`, `privateKey`, `certificate`, `idpCa`, `idpEntityId`, `clockSkewSeconds`, `wantAssertionsEncrypted`, `allowUnsolicited`, `requestTokenType`, `signals`, `ssf`, `pep`. `file:` and `env:` prefixes are accepted. The default subject attribute is `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier`. `signals` omitted or `true` is on. The resolved configuration leaves `signals` null in that case. `false` is kept as `Boolean.FALSE`, does not start a receiver, and does not require transmitter metadata. Sign-in is unchanged either way: WS-Federation does not send OAuth scopes. Any other value raises a config error whose message is `signals must be true or false`. +**Subjects (SSF 1.0 §8.1.3.2–8.1.3.3).** A subscribing application should receive CAEP and RISC events only about people signed in to it. `SignalsReceiver.track` calls the transmitter's `add_subject_endpoint` with `{stream_id, subject, verified: true}`. `untrack`, and a session ended by a received event, call `remove_subject_endpoint` only when no other local session for that person remains. The subject is `iss_sub` (the transmitter's issuer and the session person, which is `nameidentifier`) when the person is known, else `email`. Each call is made once, inline, and never fails the sign-in. A 403 is logged at warn. `ssf.addSubjects` defaults to true; anything but a boolean leaves the demo's receiver off with `ssf.addSubjects must be true or false`. A receiver given an embedded PEP that wants events also adds the application, `{format: opaque, id: }`, when it starts, and never removes it. Without that, the first sign-in would cut the PEP off from `pep-policies-changed`. + +**The receiver's TLS client identity (`ssf.clientCertificate`, `ssf.clientKey`).** The receiver authenticates its stream calls by mutual TLS. Give both or neither: `"clientCertificate": "file:generated/ssf-client.crt"` (leaf first, then the chain) and `"clientKey": "file:generated/ssf-client.key"` (PKCS#8, PKCS#1 or SEC1 PEM; RSA or EC). A relative path is taken from the configuration's directory. A pair that is not a TLS client identity is refused when the configuration is read. Without them the receiver presents the relying party's own `certificate` and `privateKey` (`Resolved.ssfTlsClient()`). The install script has the realm issue the application that certificate, so the Shared Signals identity stays separate from the WS-Federation key pair. + ```sh docker compose build docker run --rm --user "$(id -u):$(id -g)" \ @@ -37,6 +41,23 @@ docker run --rm --user "$(id -u):$(id -g)" \ The generated certificate's common name defaults to `wsfed-caep-nodejs relying party` plus the realm, cut at 64 characters. +## Embedded PEP + +Ask iya-sts's authorization policy whether a signed-in person may act on a resource, through the embedded Remote PEP (the shared [`iya-pep`](https://github.com/rcbj/iya-pep-java) library; iya-sts [#1206](https://github.com/rcbj/iya-sts/issues/1206)). **[docs/remote-pep.md](docs/remote-pep.md) is the full guide**: setting up iya-sts, choosing `central` or `local`, every configuration member, obligations, policy-change events, operating it and troubleshooting. + +The library always includes the PEP. There is no feature flag. `com.iyasec:iya-pep:0.1.0` is a dependency of `library/pom.xml`. Until that artifact is on Maven Central, the Docker `test` and `build` stages clone `iya-pep-java` branch `develop` and install it. This library stays on `develop` until then. Bytecode is 17. The runtime image is Temurin 25. The test image is `maven:3.9-eclipse-temurin-26`. + +```json +"pep": { "name": "pep-orders", "mode": "local", "assertionKey": "pep-key.pem" } +``` + +```java +Decision decision = party.decideSession(receiver, sessionId, login, Access.of("read", "order", "42")); +int status = decision.httpStatus(); // 200 for a Permit, 403 for anything else +``` + +The section is off unless present. A section without `mode` is `local`. `pdpUrl` defaults to the identity provider's entityID (the realm issuer, `/realm/` included). `application` defaults to `realm`. `signals` is the library's. `tlsCa` is `idpCa`. The PEP's key must be its own: `RelyingParty` refuses `pep.assertionKey` equal to `privateKey`, and `SignalsReceiver` refuses it equal to the receiver's TLS client key, both by JWK thumbprint. Only the claims the realm's AuthZEN catalogue declares are sent. The subject id is the `name` claim, else the NameID. `nameidentifier` is the opaque sub and is never the id. Every PEP failure (no policy yet, iya-sts unreachable, an engine fault) is Unavailable, and `httpStatus()` answers 403 like a Deny. `decide` does not throw. A `SignalsReceiver` given the PEP asks its stream for `pep-policies-changed`, adds the application as an opaque subject that is never removed, and tells the PEP whether the stream is `requested`, `excluded` or `down`. The demo protects `/orders/{id}` and `/attribute-protected` and answers each with the decision's `httpStatus()` after its own 401 for no sign-in. + ## Errors A caught exception is written to `java.lang.System.Logger` with its stack. The JDK sends that logger to `java.util.logging` unless the application installs a `System.LoggerFinder`. Where this library already threw `WsFedError`, it still throws `WsFedError`, and the caught exception is the cause. @@ -53,7 +74,76 @@ docker build --target test . The suite runs in a container. It includes a stub identity provider. It does not need a live iya-sts. XML signatures use Santuario canonicalization and JDK RSA. The Shared Signals JWS uses Nimbus. -`python3 scripts/live_iya_sts.py` is the live half. It starts a fresh iya-sts when `IYA_STS_URL` is unset (or from `IYA_STS_IMAGE`), copies the checkout to a scratch build context without `demo/generated`, builds the demo image, generates the key pair inside it, runs the install script with host `python3` (which writes `idpCa`'s chain), builds the image again so it carries that chain, checks the image holds the chain and no key, and runs the demo with only the key pair and IdP metadata mounted. It then signs in, and requires a credential-change event and a session-revoked event on `GET /live-status`. The second event ends the local session. iya-sts main sets the WS-Federation assertion SessionIndex to the assertion id. The CAEP session-revoked subject names the sign-on session, so the index lookup finds nobody. This demo then ends its one session from the event handler. The script does not bind port 3000, 8081 or 18481-18495 (defaults: `LIVE_STS_PORT=18553`, `LIVE_DEMO_PORT=18653`), passes secrets to docker as `-e NAME` only, logs each sign-in request by a fixed label rather than its URL, and does not run Java or Maven on the host. Key generation runs inside the demo image. The nightly workflow, cron `51 6 * * *` plus a manual run, runs the unit suite and this script. +`python3 scripts/live_iya_sts.py` is the live half. It starts a fresh iya-sts when `IYA_STS_URL` is unset (or from `IYA_STS_IMAGE`), copies the checkout to a scratch build context without `demo/generated`, builds the demo image, generates the key pair inside it, runs the install script with host `python3` (which writes `idpCa`'s chain), builds the image again so it carries that chain, checks the image's `demo/generated` holds only `idp-ca.pem`, and runs the demo with the key pair and IdP metadata mounted file by file, plus `ssf-client.key` and `ssf-client.crt` when the install script wrote them. `--pep` (or `LIVE_PEP=1`) also mounts `pep-key.pem`, runs central and then local (`WSFED_CONFIG=demo/wsfed.pep-local.json`), and puts `pep.central` and `pep.local` in the result. It needs an iya-sts image with #2026–#2028. The script then signs in, and requires a credential-change event and a session-revoked event on `GET /live-status`. The second event ends the local session. iya-sts main sets the WS-Federation assertion SessionIndex to the assertion id. The CAEP session-revoked subject names the sign-on session, so the index lookup finds nobody. This demo then ends its one session from the event handler. The script does not bind port 3000, 8081 or 18481-18495 (defaults: `LIVE_STS_PORT=18553`, `LIVE_DEMO_PORT=18653`), passes secrets to docker as `-e NAME` only, logs each sign-in request by a fixed label rather than its URL, and does not run Java or Maven on the host. Key generation runs inside the demo image. The nightly workflow, cron `51 6 * * *` plus a manual run, runs the unit suite and this script. + +## Demo with its embedded PEP + +**Shared Signals identity.** With an `ssf` block and signals on, the install script lets the application manage its own stream (`oauthAllowedScope` `ssf.manage`, a member of `SSF_MANAGE`). It then has the realm issue the application a TLS client certificate (`POST /admin-api/applications/issue-tls-client-certificate`, `keyAlg` `ec-p256`). The key goes to `demo/generated/ssf-client.key` (mode 0600, decrypted with the host's `openssl`, never printed). The leaf and chain go to `demo/generated/ssf-client.crt`, and the script names both in `ssf.clientKey` and `ssf.clientCertificate`. A re-run keeps a certificate the application still holds. Earlier versions pinned the relying party's self-signed certificate (`tls/trust/add` and `applications/add-certificate`). Once the new certificate is in place, the script removes both by that certificate's SHA-256. A missing anchor, or a 403, does not stop the run. `.dockerignore` keeps the key and certificate out of the image. Compose mounts `demo/generated` read-only. + +One command registers the demo and sets up its PEP: + +```sh +ADMIN_API_CLIENT_SECRET=... python3 scripts/configure_iya_sts.py --idp https://localhost:8443 --pep central +``` + +A bare `--pep` is `local`. It needs an iya-sts with embedded-PEP support (iya-sts #2026–#2028) and the host's `openssl`. Beside the registration it creates the PEP's service account (`pep-wsfed-demo`, or `--pep-name`) in `remote-peps`, makes its P-256 key in `demo/generated/pep-key.pem` (0600, never printed, never in the image), certifies it bound to the demo's application, adds the catalogue row `subject.acr` → `urn:example:acr`, gives the application its own enforced policy (read on an order needs an `acr`; read on `attribute-protected` needs the directory attribute `attr1=abc123`; anything else is denied; the realm root is never touched), and writes the `pep` section into `demo/wsfed.json` with `assertionKey` left as `file:generated/pep-key.pem`. Run it again with `--pep local` to switch modes: the account and key are kept, and so is the policy unless it is this script's own (`urn:example:wsfeddemo-orders`), which is brought up to date. The application display name stays `wsfed-caep-nodejs demo`. [docs/remote-pep.md](docs/remote-pep.md#the-demo) has the details. + +**`GET /attribute-protected`** is decided on a directory attribute rather than a claim: the policy permits `read` on `attribute-protected` when the person's `attr1` is `abc123`, and the PEP asks iya-sts's PIP for it. Defining `attr1` uses a second token, `admin:read admin:security`, and only when `--pep` is set, so a nightly run against an older iya-sts does not call that path. The page is 401 when signed out, 200 with the heading Allowed on a Permit, 403 with Not allowed on a Deny, and 403 with No decision when the PEP could not decide. `GET /orders/{id}` is `read` (a Permit may say Order) and any other method is `write`. + +## Credentials + +Every credential the library, the demo and its scripts use: what it is, where it lives, and how it is replaced. Paths are relative to `demo/`. No script prints a key, a password or a secret: only paths. + +### The application's own credentials + +These are the relying party's own credentials, for its WS-Federation registration and sign-in and for its Shared Signals stream. + +| Credential | What it is | Made or issued by | Where it lives | Used for | How iya-sts learns of it | Rotation | +|---|---|---|---|---|---|---| +| WS-Federation key pair | An RSA key and a self-signed certificate. The common name defaults to `wsfed-caep-nodejs relying party` plus the realm, cut at 64 characters. | `com.iyasec.wsfed.Cli generate-keys`, run inside the demo image. The install script tells you that command when neither file exists. It does not run Java on the host. | `privateKey` → `generated/rp.key` and `certificate` → `generated/rp.crt`. | Decrypting encrypted assertions. It is also the receiver's TLS client identity when the configuration names no `ssf.clientCertificate`. | The registration is the realm and the reply URL. The install script writes `generated/rp-metadata.xml` and does not upload it. Earlier versions pinned this certificate for Shared Signals; the current one removes that. | Run `generate-keys` again inside the image, then the install script, then restart the demo. | +| Shared Signals client certificate | An EC P-256 key and a TLS client certificate (`clientAuth`, subjectAltName `urn:sts:application:`), with its chain. | iya-sts's realm tls-client Issuing CA, through `POST /admin-api/applications/issue-tls-client-certificate` (`keyAlg` `ec-p256`), called by the install script whenever signals are on. The one-time encrypted key is decrypted with the host's `openssl`. The password is passed as `WSFED_SSF_CLIENT_KEY_PASSWORD` and is never printed. | `ssf.clientKey` → `generated/ssf-client.key` (0600) and `ssf.clientCertificate` → `generated/ssf-client.crt` (leaf, then chain). | Mutual TLS on every call the receiver makes to `/ssf/*`. | iya-sts issued it, and the application's record lists it. | Revoke it, or delete the two files, then run the install script again and restart the demo. A re-run keeps a certificate the application still holds. | +| Fallback: the WS-Federation key pair at `/ssf/*` | The row above's key pair, presented when `ssf.clientCertificate` and `ssf.clientKey` are absent. | (as above) | (as above) | Mutual TLS at `/ssf/*`. | Only if an administrator trusts that self-signed certificate. The install script no longer sets this up. | (as above) | +| Test user's password | The password of `wsfed-demo-user` (`--test-user`). | `WSFED_DEMO_USER_PASSWORD` when set; otherwise iya-sts generates one when the install script creates the user. | `generated/wsfed-demo-user.password` (0600), written only when iya-sts generated it. Only the path is printed. | Signing in at iya-sts's sign-in page. | It is iya-sts's directory entry. | Set `WSFED_DEMO_USER_PASSWORD` and run the install script again, or change it on the console. | +| Session cookie key | 32 random bytes per demo process, used for HMAC. | The demo. | Memory only. | Signing the `sid` and `wsfed_pending` cookies. | It doesn't. | Every restart. | + +The live script makes its own users and passwords for each run and keeps them in memory. They reach containers as `-e NAME`. + +### The embedded PEP's credentials + +The PEP is a separate client of iya-sts with an identity of its own; [docs/remote-pep.md](docs/remote-pep.md#credentials) has the details. + +| Credential | What it is | Made or issued by | Where it lives | Used for | Rotation | +|---|---|---|---|---|---| +| The PEP's service account | `pep-wsfed-demo` (`--pep-name`): a service account with no password (`credential: none`), owned by `admin-write`, and a member of `remote-peps`. | The install script (`--pep`), only when `GET /users?user=` says it doesn't exist. | iya-sts's directory; the `pep` section's `name`. | Being the PEP: the bound application, registration and audit name it. | Kept on every run. | +| The PEP's key | An EC P-256 key. | Made on the host with `openssl genpkey`. Only its certificate request (`CN=`) is sent, to `POST /admin-api/xacml/issue-pep-credential` with `application` = the realm. | `pep.assertionKey` → `generated/pep-key.pem` (0600). It is never printed and never in the image. | Signing the PEP's assertion for its access tokens. | `--pep` keeps an existing key and only binds it again (`set-pep-application`). To replace it, delete the file and run `--pep` again. | + +The library refuses a PEP key that is one of the application's own keys. `RelyingParty.create` refuses `pep.assertionKey` equal to `privateKey`, and `SignalsReceiver` refuses it equal to the receiver's TLS client key. Both compare JWK thumbprints. + +### Install-time only + +| Credential | What it is | Where it lives | Used for | +|---|---|---|---| +| The management client's secret | The secret of iya-sts's `sts-api-client`. | `ADMIN_API_CLIENT_SECRET` (or `STS_ADMIN_API_CLIENT_SECRET`) in the environment of `scripts/configure_iya_sts.py`. It is never written to a file or printed. | A `client_credentials` token with `admin:read admin:write` for every management call. A second token, `admin:read admin:security`, is minted only for the one `--pep` call that defines the realm's custom attribute `attr1`. | + +Neither the demo nor the library ever sees this secret. + +### Trust material + +All of it is public; none of it is a secret. + +| What | Where | What it verifies | +|---|---|---| +| iya-sts's listener CA chain | `idpCa` → `generated/idp-ca.pem`, written by the install script on every run through `scripts/trust_chain.py` and copied into the demo image. | iya-sts's TLS certificate, for the metadata fetch, every Shared Signals call, and the PEP's calls (`tlsCa` defaults to `idpCa`). | +| The identity provider's metadata | `idpMetadata` → `generated/idp-metadata.xml`. | The XML signature on every security token. | +| The transmitter's JWKS | Fetched at run time from the transmitter's `jwks_uri`. | The signature on every Security Event Token. | +| The relying party's metadata | `generated/rp-metadata.xml`, written by the install script. | Nothing here; it is for an identity provider that wants this relying party's encryption certificate. | + +### Development and product iya-sts + +- **Realm-issued certificates work in both modes.** A certificate iya-sts issues chains to its Service Root. The main port trusts that Root while issued client certificates are trusted, so nothing has to be pinned in its client-certificate truststore. +- **Why not pin the RP's certificate.** That truststore is process-wide. A self-signed certificate added there is trusted for every realm and ties the Shared Signals identity to the WS-Federation key pair. The install script has the realm issue a certificate and removes the anchor earlier versions added. +- **Development checks fewer passwords.** iya-sts's development sign-in page checks no password: the username is the identity. Product checks the test user's password. +- **The PEP's credential is the same in both modes:** its certified key and the `remote-peps` membership. ## Layout diff --git a/demo/src/main/java/com/iyasec/wsfed/demo/Demo.java b/demo/src/main/java/com/iyasec/wsfed/demo/Demo.java index a45696a..8c2c893 100644 --- a/demo/src/main/java/com/iyasec/wsfed/demo/Demo.java +++ b/demo/src/main/java/com/iyasec/wsfed/demo/Demo.java @@ -3,11 +3,15 @@ package com.iyasec.wsfed.demo; +import com.iyasec.pep.Access; +import com.iyasec.pep.Decision; import com.iyasec.wsfed.Caught; import com.iyasec.wsfed.HttpClient; import com.iyasec.wsfed.Json; import com.iyasec.wsfed.RelyingParty; +import com.iyasec.wsfed.WsFedError; import com.iyasec.wsfed.WsFedLogin; +import com.iyasec.wsfed.pep.EmbeddedPep; import com.iyasec.wsfed.ssf.Events; import com.iyasec.wsfed.ssf.SignalsReceiver; import com.sun.net.httpserver.HttpExchange; @@ -132,15 +136,22 @@ public Result handle(String method, String target, Map headers, if ("/FederationMetadata/2007-06/FederationMetadata.xml".equals(path) && "GET".equals(method)) { return text(200, "application/samlmetadata+xml", rp.metadata()); } + if ("/attribute-protected".equals(path)) return enforce(sid, Access.of("read", "attribute-protected", "attr1")); + if (path.startsWith("/orders/")) { + String id = path.substring("/orders/".length()); + if (!id.isEmpty() && !id.contains("/")) { + String action = "GET".equals(method) ? "read" : "write"; + return enforce(sid, Access.of(action, "order", id)); + } + } + if ("/pep-status".equals(path) && "GET".equals(method)) return pepStatus(); if ("/".equals(path) && "GET".equals(method)) { WsFedLogin who = sid == null ? null : sessions.get(sid); String page = who == null ? "

Sign in with WS-Federation

" : "

Signed in as " + esc(who.nameId) + " by " + esc(who.issuer) + ".

" + "
"; - String html = "WS-Federation" - + "
" + page + "
"; - return text(200, "text/html; charset=utf-8", html); + return text(200, "text/html; charset=utf-8", shell("

WS-Federation

" + page)); } if ("/styles.css".equals(path) && "GET".equals(method)) { try { @@ -169,11 +180,19 @@ private Result liveStatus(String sid) { body.put("subject", subject); body.put("receiver", receiverState); body.put("events", recorded); + Map pep = EmbeddedPep.statusMap(rp.pep()); + if (pep != null) body.put("pep", pep); return new Result(200, headers( new String[] {"content-type", "application/json"}, new String[] {"cache-control", "no-store"}), Json.stringify(body).getBytes(StandardCharsets.UTF_8)); } + /** Stops the receiver and the embedded PEP. Safe when either was never started. */ + public void stop() { + if (receiver != null) receiver.stop(); + if (rp.pep() != null) rp.pep().stop(); + } + public void remember(SignalsReceiver.SignalEvent event) { Map row = new LinkedHashMap<>(); row.put("type", event == null || event.type == null ? "" : event.type); @@ -191,6 +210,46 @@ public void remember(SignalsReceiver.SignalEvent event) { } } + /** + * 401 when nobody is signed in. Otherwise the PEP's status: 200 only + * for a Permit, 403 for a Deny or any failure. + */ + private Result enforce(String sid, Access access) { + WsFedLogin who = sid == null ? null : sessions.get(sid); + if (who == null) return text(401, "text/html; charset=utf-8", shell("

Sign in

Sign in to continue.

")); + Decision decision = receiver == null ? rp.decide(who, access) : rp.decideSession(receiver, sid, who, access); + String heading; + String detail; + if (decision.isPermit()) { + heading = "order".equals(access.resourceType) ? "Order" : "Allowed"; + detail = "Permitted."; + } else if (decision.kind() == Decision.Kind.DENY) { + heading = "Not allowed"; + detail = decision.why(); + } else { + heading = "No decision"; + detail = "could not decide: " + decision.why(); + } + return text(decision.httpStatus(), "text/html; charset=utf-8", shell("

" + esc(heading) + "

" + esc(detail) + "

")); + } + + private Result pepStatus() { + Map body = new LinkedHashMap<>(); + Map status = EmbeddedPep.statusMap(rp.pep()); + if (status == null) body.put("configured", Boolean.FALSE); + else body.putAll(status); + return new Result(200, headers( + new String[] {"content-type", "application/json"}, + new String[] {"cache-control", "no-store"}), Json.stringify(body).getBytes(StandardCharsets.UTF_8)); + } + + private static String shell(String main) { + return "WS-Federation" + + "" + + "
" + main + "
"; + } + private String pending(String value, int age) { return "wsfed_pending=" + value + "; Path=" + replyPath + "; HttpOnly; SameSite=None" + (secure.isEmpty() ? "; Secure" : secure) + "; Max-Age=" + age; } @@ -260,6 +319,9 @@ public static void main(String[] args) throws Exception { write(exchange, result.status, result.headers, result.body); }); server.start(); + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + if (holder[0] != null) holder[0].stop(); + })); System.out.println("wsfed-caep demo on port " + port); } @@ -277,12 +339,16 @@ static App load(Path configPath, int port, String publicUrl, boolean given) thro app.receiverState = "not configured (signals are off)"; } else if (map == null || map.get("transmitter") == null) { app.receiverState = "not configured (no ssf block in the configuration file)"; - } else if (rp.config.privateKey == null || rp.config.certificate == null) { - app.receiverState = "not running: the relying party has no private key"; + } else if (rp.config.ssfTlsClient() == null) { + app.receiverState = "not running: no TLS client identity (ssf.clientCertificate and ssf.clientKey, or the relying party's key pair)"; + } else if (map.containsKey("addSubjects") && !(map.get("addSubjects") instanceof Boolean)) { + throw new WsFedError("config", "ssf.addSubjects must be true or false"); } else { SignalsReceiver.Options options = new SignalsReceiver.Options(); Object interval = map.get("pollIntervalMs"); options.pollIntervalMs = interval instanceof Number number ? number.intValue() : 5000; + options.addSubjects = !map.containsKey("addSubjects") || Boolean.TRUE.equals(map.get("addSubjects")); + options.pep = rp.pep(); try { options.tls = clientTls(rp); } catch (Exception err) { @@ -309,19 +375,18 @@ static App load(Path configPath, int port, String publicUrl, boolean given) thro return app; } - private static HttpClient.Tls clientTls(RelyingParty rp) throws Exception { + private static HttpClient.Tls clientTls(RelyingParty rp) { + String[] pair = rp.config.ssfTlsClient(); + if (pair == null) { + throw new WsFedError("config", "no TLS client identity (ssf.clientCertificate and ssf.clientKey, or the relying party's key pair)"); + } HttpClient.Tls tls = new HttpClient.Tls(); tls.ca = rp.config.idpCa; - tls.cert = pem("CERTIFICATE", rp.config.certificate.getEncoded()); - tls.key = pem("PRIVATE KEY", rp.config.privateKey.getEncoded()); + tls.cert = pair[0]; + tls.key = pair[1]; return tls; } - private static String pem(String label, byte[] der) { - String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(der); - return "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n"; - } - public static Map endpoints(String realm, String reply, String publicUrl, boolean given, int port) { if (given && publicUrl != null && !publicUrl.isEmpty()) { URI base = URI.create(publicUrl.endsWith("/") ? publicUrl : publicUrl + "/"); diff --git a/demo/src/test/java/com/iyasec/wsfed/HttpDemoTest.java b/demo/src/test/java/com/iyasec/wsfed/HttpDemoTest.java index 5929b9e..7c8dda7 100644 --- a/demo/src/test/java/com/iyasec/wsfed/HttpDemoTest.java +++ b/demo/src/test/java/com/iyasec/wsfed/HttpDemoTest.java @@ -56,9 +56,31 @@ void start() throws Exception { @AfterEach void stop() { + if (app != null) app.stop(); if (server != null) server.stop(0); } + @Test + void protectedPagesNeedASignInAndFailClosedWithoutAPep() throws Exception { + HttpURLConnection signedOut = open("GET", "/attribute-protected", null, null); + assertEquals(401, signedOut.getResponseCode()); + assertTrue(errorBody(signedOut).contains("

Sign in

")); + assertEquals(401, open("POST", "/orders/42", "", null).getResponseCode()); + + HttpURLConnection login = open("GET", "/login", null, null); + Map params = query(URI.create(login.getHeaderField("Location")).getRawQuery()); + String pending = cookie(login, "wsfed_pending"); + String form = "wa=wsignin1.0&wresult=" + URLEncoder.encode(StubIdp.wresult(), StandardCharsets.UTF_8) + + "&wctx=" + URLEncoder.encode(params.get("wctx"), StandardCharsets.UTF_8); + String sid = cookie(open("POST", "/wsfed", form, "wsfed_pending=" + pending), "sid"); + HttpURLConnection denied = open("GET", "/orders/42", null, "sid=" + sid); + assertEquals(403, denied.getResponseCode()); + String page = errorBody(denied); + assertTrue(page.contains("

No decision

")); + assertTrue(page.contains("could not decide")); + assertEquals(403, open("POST", "/orders/42", "", "sid=" + sid).getResponseCode()); + } + @Test void signInCleanupAndLogout() throws Exception { HttpURLConnection health = open("GET", "/healthz", null, null); @@ -157,6 +179,12 @@ private static String body(HttpURLConnection conn) throws Exception { return new String(conn.getInputStream().readAllBytes(), StandardCharsets.UTF_8); } + private static String errorBody(HttpURLConnection conn) throws Exception { + var stream = conn.getErrorStream(); + if (stream == null) return ""; + return new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + private HttpURLConnection open(String method, String path, String body, String cookie) throws Exception { HttpURLConnection conn = (HttpURLConnection) URI.create(base + path).toURL().openConnection(); conn.setInstanceFollowRedirects(false); diff --git a/docs/remote-pep.md b/docs/remote-pep.md new file mode 100644 index 0000000..64a9fc7 --- /dev/null +++ b/docs/remote-pep.md @@ -0,0 +1,299 @@ + + +# Using the iya-sts Remote PEP + +This library can ask iya-sts's authorization policy whether a signed-in person (the `WsFedLogin` `handleReply` returned) may do something to a resource in your application, through an embedded **Remote PEP** (Policy Enforcement Point). The PEP itself is the shared [`iya-pep`](https://github.com/rcbj/iya-pep-java) library (`com.iyasec:iya-pep`); this library builds it from your configuration, turns its WS-Federation sign-in into the PEP's subject, and hands it policy-change events from its Shared Signals stream. The design is [iya-sts #1206](https://github.com/rcbj/iya-sts/issues/1206). + +The PEP never permits by default. A decision is a Permit, a Deny or Unavailable, and Unavailable (no policy held yet, iya-sts unreachable or answering badly, or an engine fault) must be treated as a refusal. Every PEP failure is a 403: `Decision.httpStatus()` is 200 for a Permit and 403 for a Deny and an Unavailable alike. `decide` and `decideSession` do not throw. + +## Choosing a mode + +| | `central` | `local` | +|---|---|---| +| Who decides | iya-sts, per request (`POST /access/v1/evaluation`) | this process, with the PEP's own XACML engine | +| How this library includes it | always; there is no feature flag | the same dependency | +| Latency | one HTTPS round trip per decision | none after the first pull | +| When iya-sts is down | every decision is Unavailable, and a Permit cache is emptied | decisions continue with the policies held | +| Policy changes | at once | on the `pep-policies-changed` event, or the next poll | +| Decision records | written by iya-sts | sent by the PEP to iya-sts's audit log | + +Pick `central` when decisions are infrequent or must reflect a change immediately, and `local` when decisions are on a hot path or must survive a short outage. Both modes give the same answer for the same request: `local` maps the request through the realm's catalogue exactly as iya-sts does. + +## Before you start: set up iya-sts + +You need an iya-sts release with embedded-PEP support (iya-sts #2026, #2027 and #2028). The steps below use the management API; `$API` is `https:///realm//admin-api` (or `https:///admin-api` for the default realm) and `$TOKEN` a token for it with write access. Every step has a console equivalent, named after it. + +```bash +api() { curl -s -H "Authorization: Bearer $TOKEN" \ + -H 'Content-Type: application/json' -d "$2" "$API/$1"; } +``` + +### 1. Register the application + +Register the WS-Federation relying party in iya-sts as usual; `scripts/configure_iya_sts.py` does it for the demo. Note its identifier: it is the `application` the PEP is bound to (`realm`, the wtrealm, by default). + +**For the demo, one command does steps 1 to 6**: `python3 scripts/configure_iya_sts.py --pep central` (or `local`); see *The demo* below. + +### 2. Create the PEP's service account + +The PEP signs in as a service account of its own, never as a person or as the application: + +```bash +api users/create '{"username":"pep-orders","invent":false, + "credential":"none","serviceAccount":true,"owners":["admin-write"], + "attributes":{"cn":"pep-orders","displayName":"pep-orders"}}' +api groups/add-member '{"group":"remote-peps","member":"pep-orders"}' +``` + +Console: **Users → New user** (tick **Service account**), then the `remote-peps` group's **Add member**. + +### 3. Make the PEP's key, certify it and bind the PEP + +Generate the key where the application runs. Only the certificate request leaves the machine: + +```bash +openssl ecparam -name prime256v1 -genkey -noout | \ + openssl pkcs8 -topk8 -nocrypt -out pep-key.pem +openssl req -new -key pep-key.pem -subj /CN=pep-orders -out pep-key.csr +api xacml/issue-pep-credential "$(jq -n --rawfile csr pep-key.csr \ + '{name: "pep-orders", csr: $csr, application: ""}')" +``` + +`application` binds the PEP to the application in the same call (`POST /admin-api/xacml/set-pep-application` does it on its own). An EC P-256 key is preferred; RSA of 2048 bits or more is accepted. **The key must be the PEP's own**: this library refuses a configuration where it is `privateKey` (the relying party's signing and decryption key) and where it is the receiver's TLS client key. Both comparisons are JWK thumbprints. + +Console: **Protocols → XACML → Remote PEPs**, **Certify the key**, then the PEP's Overview, **Embedded in an application**. + +### 4. Declare the claims your policy reads + +The PEP sends a subject's claims only through the realm's AuthZEN attribute catalogue: a claim with no catalogue row is not sent (iya-sts would refuse the whole request). Add one row per claim your policy uses, on **Protocols → XACML → AuthZEN** or with `POST /admin-api/xacml/authzen/set-attribute`. For example, to make `acr` available as `urn:example:acr`: + +```bash +api xacml/authzen/set-attribute '{"object":"subject","property":"acr","attributeId":"urn:example:acr"}' +``` + +which is the row + +| `object` | `property` | `attributeId` | +|---|---|---| +| `subject` | `acr` | `urn:example:acr` | + +The same applies to resource properties, action properties and context members you put on an `Access`. iya-sts's [AuthZEN page](https://rcbj.github.io/iya-sts/v1.2.0/authzen.html), *The realm's conversion rules*, describes the rows. + +### 5. Write the policy + +The policy that decides is the application's own fine-grained authorization policy when the application enforces fine-grained authorization, and otherwise the realm's root policy. A `local` PEP is sent that policy and everything it references, and nothing else. The subject's id arrives as XACML's `subject-id`, the action's name as `action-id` and the resource's id as `resource-id`; anything else comes through the catalogue rows of step 4, or from iya-sts's PIP for attributes on the person's directory entry. The resource's type arrives as `urn:sts:xacml:authzen:resource-type`. + +For an application that enforces no fine-grained authorization, a root that permits `read` on an `order` when the person's `acr` arrived, and denies everything else, can be written in ALFA (the console's **Policies** tab does the same): + +```bash +api xacml/import-alfa "$(jq -n --arg alfa ' +namespace orders { + attribute act { category = actionCat + id = "urn:oasis:names:tc:xacml:1.0:action:action-id" type = string } + attribute rtype { category = resourceCat + id = "urn:sts:xacml:authzen:resource-type" type = string } + attribute acr { category = subjectCat id = "urn:example:acr" type = string } + policy ordersRoot { + id = "urn:example:orders" + apply firstApplicable + rule readOrder { + permit + target clause act == "read" + target clause rtype == "order" + condition integerGreaterThan(stringBagSize(acr), 0) + } + rule otherwise { deny } + } +}' '{name: "orders", alfa: $alfa}')" +api xacml/set-root '{"name":"orders"}' +``` + +Every change to that policy, or to which policy is the root, is sent to a `local` PEP as `pep-policies-changed` (step 6). + +### 6. (`local` with signals) let the event through + +If the application's entry restricts its Shared Signals streams with `ssfAllowedEvents`, add `urn:iya:sts:secevent:event-type:pep-policies-changed` to it. Otherwise the PEP doesn't hear of a change until its fallback poll, and the application's page in the console warns about it. + +## Dependency + +```xml + + com.iyasec + iya-pep + 0.1.0 + +``` + +`library/pom.xml` already declares that dependency. The library always includes the PEP: a missing `pep` section means the PEP is off, and a present section is used. There is no build flag that refuses the section. + +`iya-pep` is not on Maven Central yet. The Dockerfile `test` stage (`maven:3.9-eclipse-temurin-26`) and the `build` stage clone `https://github.com/rcbj/iya-pep-java.git` branch `develop` and install it with `mvn -B -DskipTests install` before this library's `mvn -B test` and before the demo is packaged. The clone is one attempt. This library stays on `develop` until `iya-pep` is published, because a merge to `main` publishes `wsfed-caep`. The bytecode this library compiles is 17. The image that runs the demo is `eclipse-temurin:25-jre`. + +## Configure + +Add a `pep` section to `wsfed.json`. The PEP is off unless it is present. + +```json +"pep": { + "name": "pep-orders", + "mode": "local", + "assertionKey": "pep-key.pem" +} +``` + +| Member | Default here | What it is | +|---|---|---| +| `name` | required | The PEP's service account (step 2). | +| `mode` | `local` | `local` (the PEP pulls its application's policies, caches them in memory and decides in process) or `central` (it asks iya-sts for every decision). | +| `assertionKey` | required | The PEP's private key in PEM: a path (a `file:` prefix is allowed); a relative one is read from the configuration file's directory, like `privateKey`. The configuration stores the path. The PEM is not copied into the section. | +| `pdpUrl` | the identity provider's metadata entityID. iya-sts publishes its realm's issuer there, which is the service's base with the `/realm/` prefix | iya-sts, with `/realm/` for a realm. | +| `application` | `realm` (the wtrealm) | The application the PEP is bound to (step 3). | +| `clientId` | `sts-remote-pep` | The client the PEP's assertion is presented through. | +| `signals` | the library's `signals` | Whether a signal stream hands over policy-change events. With it on, the PEP starts as `down` until the receiver reports the stream. `null` or `true` is on. | +| `pollIntervalMs` | 15000 | `local`: the poll period while the stream does not carry the event (no stream, `down` or `excluded`). | +| `fallbackPollMs` | 300000 | `local`: the poll period while the stream carries the event (`requested`), in case one is lost. | +| `heartbeatIntervalMs` | 30000 | How often the PEP reports to iya-sts. | +| `permitCacheMs` | 0 (off) | `central` only: reuse a Permit for this long, at most 60000. The policy-change event clears it, and so does a failed evaluation or heartbeat. | +| `supportedObligations` | `[]` | The obligation types your application discharges (see *Obligations*). | +| `decisionRecords` | `true` | `local`: send each decision to iya-sts's audit log. | +| `tlsCa` | `idpCa` | PEM trust anchors for iya-sts's TLS. Inserted when `idpCa` contains a certificate and the section does not name its own. | +| `timeoutMs` | 10000 | Per request to iya-sts. | + +An unknown member is refused, so a misspelt one doesn't quietly fall back to a default. `RelyingParty.fromFile` and `RelyingParty.create` start the PEP after the identity provider's metadata is read. An unreachable service is retried on the PEP's own thread; `start` returns. + +## Decide + +```java +Decision decision = party.decideSession(receiver, sessionId, login, Access.of("read", "order", orderId)); +int status = decision.httpStatus(); // 200 for a Permit, 403 for anything else +if (decision.isPermit()) { + // discharge decision.obligations(), then serve +} else { + // 403. decision.kind() is DENY or UNAVAILABLE; decision.why() says which +} +// Without a receiver: party.decide(login, access) +``` + +Answer the request with `decision.httpStatus()` rather than your own mapping, so a failure can never become anything but a 403. Whether the person is signed in at all (a 401) is your question, asked before the PEP's. + +`Access.of(action, resourceType, resourceId)` carries the AuthZEN action and resource. The PEP always sets the application context to the bound application. + +**The subject** comes from the sign-in, never from a request header: + +- **id:** the `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name` claim, else the NameID. A blank name is skipped. iya-sts puts the directory username in both. The `nameidentifier` claim is the opaque `sub` and is never the id. (The Shared Signals session index still keys a person by `nameidentifier`. That is a different subject.) +- **properties:** each attribute keyed by its FriendlyName, else the last segment of its Name (`emailaddress`, `role`), when that name matches `[A-Za-z0-9_$@:-]` and is 1 to 64 characters. A dot is not in that set, so an OID with no usable segment is left out. Then `acr` (AuthnContextClassRef), `amr` (the `authenticationmethod` claim, always an array) and `auth_time` (AuthnInstant, epoch seconds). Empty values are skipped. The first claim URI in sorted order wins a duplicate property key; `acr`, `amr` and `auth_time` overwrite. + +Only the properties the catalogue declares are sent. + +**Ended sessions.** `party.decideSession(receiver, sessionId, login, access)` is a Deny without asking when the assertion's `SessionNotOnOrAfter` is now or in the past (`the identity provider's session has ended`), or when the receiver no longer tracks the session (`no signed-in session`): untracked, past the index expiry, or ended by a Shared Signals event such as CAEP `session-revoked`. + +**Without a `pep` section**, every decision is Unavailable (`no pep section is configured`), a 403. + +### Obligations + +A Permit can carry obligations, which your application must carry out before it grants the access (for example a `step-up` to a stronger `acr`). The PEP only hands you obligations of types you list in `supportedObligations`. A Permit carrying any other obligation is turned into a Deny, so an obligation is never silently dropped. Advice can be ignored. + +```json +"pep": { "name": "pep-orders", "assertionKey": "pep-key.pem", "supportedObligations": ["step-up"] } +``` + +## Receive policy-change events + +In `local` mode, and in `central` mode with a Permit cache (`permitCacheMs` greater than 0), the PEP wants to hear when the policies change. Give the receiver the PEP on `SignalsReceiver.Options.pep` (the demo sets it from `RelyingParty.pep()`). The receiver also refuses a PEP key that is its own TLS client key. + +The receiver then asks its stream for `urn:iya:sts:secevent:event-type:pep-policies-changed` (`Pep.POLICIES_CHANGED_EVENT`), verifies each SET like every other one, and hands the event body to `pep.onPolicyEvent`. A stream that already exists is updated with `PATCH` to ask for the event too; if the transmitter refuses, the receiver still starts, the refusal goes to the receiver's log at error, and the PEP's heartbeat reports the event as `excluded`. The event is only a hint: the PEP pulls with its own credential and never trusts the event's contents. An event naming another PEP is ignored. + +The same receiver tells the transmitter which people it cares about. When a local session starts it calls Add Subject, and when a person's last local session ends (sign-out, or a session an event ended) it calls Remove Subject. The calls follow SSF 1.0 §8.1.3.2–8.1.3.3 and are made only when the transmitter publishes those endpoints. The person subject is `iss_sub` (issuer plus `nameidentifier`) else `email`. A refusal is logged and never fails the sign-in. `ssf.addSubjects` (default true) turns this off; anything but `true` or `false` refuses to start the demo's receiver. Because iya-sts narrows a stream that names subjects to those subjects, and `pep-policies-changed` is about the application, a receiver given a PEP that wants events also adds the application (`{format: opaque, id: }`) when it starts. It never removes that subject. Otherwise the first sign-in would stop the policy events. + +The receiver keeps the PEP's view of the stream current: `requested` (or `excluded`) when it starts and after each poll that succeeds, `down` after a poll that fails and once `stop()` is called. A `local` PEP polls at `pollIntervalMs` while the stream is not `requested`, so a change still arrives while the stream cannot carry it. `status().eventStream` is that state (`none`, `requested`, `excluded` or `down`). + +## Operate it + +- **Health.** `pep.status()` reports whether the PEP is registered and running, whether it holds a policy (and which sync token), its decision counters and its current problems. It holds no secret, so it's safe on a health page. The demo's `GET /live-status` includes that map under `pep`, and `GET /pep-status` returns it alone. +- **In the console.** The PEP appears under **Protocols → XACML → Remote PEPs** with its kind (`embedded`), application, mode, protocol version and whether its stream carries policy-change events. The application's page lists the PEPs bound to it. +- **Rotating the key.** Generate a new key, certify it with `issue-pep-credential` (add `revokePrevious: true` to retire the old one), and replace the file. The tokens bound to the old key are dropped once the PEP reads the new file. +- **Audit.** In `local` mode each decision becomes an audit row in iya-sts (`authzen.remote.decision`). In `central` mode iya-sts records its own. + +## Credentials + +The PEP's half of the README's [Credentials](../README.md#credentials) section, in more detail. The headings match the README's. + +### The application's own credentials + +The relying party's WS-Federation key pair (`privateKey`, `certificate`) and its Shared Signals client certificate (`ssf.clientCertificate`, `ssf.clientKey`, issued by the realm) belong to the application, not the PEP. The README's table lists them. The PEP uses neither, and the library makes sure it can't (below). + +### The embedded PEP's credentials + +**The service account.** The PEP signs in as a service account of its own (step 2): `pep-wsfed-demo` in the demo (`--pep-name`), with no password (`credential: none`), owned by `admin-write`, and a member of `remote-peps`. The install script creates it only when `GET /admin-api/users?user=` says it doesn't exist. + +**The key.** `pep.assertionKey`, an EC P-256 private key in PEM (RSA of 2048 bits or more is accepted). In the demo it is `generated/pep-key.pem`, made on the host with `openssl genpkey` and created 0600. It is never printed and never in the image. Only its certificate request (`CN=`) leaves the machine, to `POST /admin-api/xacml/issue-pep-credential` with `application` equal to the realm. That certifies the key for the account and binds the PEP to the application in one call; `set-pep-application` binds it again on its own. + +**What the key authenticates.** iya-pep signs an RFC 7523 self-assertion with it, through the client `sts-remote-pep` (`clientId`), at iya-sts's token endpoint. It receives DPoP-bound access tokens and signs every DPoP proof with the same key. There is one token per audience: + +| Scope | Resource | Calls | +|---|---|---| +| `xacml:pep` | `/xacml/pep` | registration, heartbeat, the catalogue, the policy pull (`local`), and the PIP (`local`) | +| `xacml:pep-audit` | `/admin-api` | decision records (`local`) | +| `authzen:evaluate` | `/access/v1` | the evaluation (`central`) | + +iya-pep logs and returns no token, key or proof. + +**Separate from the application's keys.** `RelyingParty.create` refuses a `pep.assertionKey` that is `privateKey`, and `SignalsReceiver` refuses one that is the receiver's TLS client key (the realm-issued `ssf.clientKey`, or `privateKey` when that is absent). Both compare JWK thumbprints (`SigningKey.jwkThumbprint` for the relying party's RSA key, `SigningKey.pemThumbprint` for the TLS key). A null or empty thumbprint is not treated as a match. The PEP's tokens are bound to its key, so a shared key would let whoever holds the application's key obtain the PEP's tokens and act as the PEP. + +**Rotation.** The install script's `--pep` keeps an existing account and key and only binds them again. To replace the key, delete `generated/pep-key.pem` and run `--pep ` again, then revoke the old certificate on **Protocols → XACML → Remote PEPs**. + +### Install-time only + +The install script's management token comes from `sts-api-client`'s secret (`ADMIN_API_CLIENT_SECRET` or `STS_ADMIN_API_CLIENT_SECRET`, from the environment only, never stored or printed), with `admin:read admin:write`. Defining `attr1` alone uses a second token with `admin:read admin:security`, and only on a `--pep` run. The PEP never sees either. + +### Trust material + +`tlsCa` defaults to `idpCa`, the iya-sts listener CA chain the install script saves. The PEP verifies iya-sts's TLS with it on every call. A `local` PEP's policies, catalogue and PIP answers come over that verified connection with its own token. A `pep-policies-changed` event is only a hint, verified as a SET by the receiver, and the PEP pulls with its own credential. + +### Development and product iya-sts + +The PEP's credential is the same in both modes: the certified key and the `remote-peps` membership. Its TLS trust is the listener chain in `tlsCa`, whatever the mode. + +## Troubleshooting + +| What you see | Likely cause | +|---|---| +| Every decision Unavailable, `status().registered` false, a problem mentioning 403 | The PEP's entry has no binding, or is bound to another application (iya-sts `STS-XACML-0338`, `0339`). Repeat step 3 with the right `application`. | +| Unavailable and a problem naming the token endpoint (`invalid_grant`) | The key isn't certified for this account, or the account isn't in `remote-peps` (steps 2 and 3). | +| Unavailable with "no policy is held yet" (`local`) | The first pull hasn't succeeded. Check `status().lastError`: a 403 on the policy pull (`STS-XACML-0343`) means the PEP isn't registered as an embedded `local` PEP bound to that application. | +| A registration refused with 400 (`STS-XACML-0340`) | The iya-sts release doesn't support this PEP's protocol version. Upgrade iya-sts or this library. | +| Deny saying the evaluation was refused | A resource, action or context property you sent has no catalogue row (step 4). Subject claims without a row are dropped, not refused. | +| Deny although the policy should permit | The policy reads a claim that has no catalogue row, so it never arrives (step 4). Or a Permit carried an obligation type missing from `supportedObligations`. | +| Policy changes take minutes to apply (`local`) | The stream is `requested` but the event never arrives, so only the `fallbackPollMs` poll brings the change. Check `ssfAllowedEvents` (step 6) and the receiver's log for a refused stream update. | +| The configuration is refused for the assertion key | It is `privateKey`, or it is the receiver's TLS client key. The message is `pep.assertionKey is the relying party's privateKey (its signing and decryption key); the PEP needs a key of its own`, or `the receiver's TLS client key is pep.assertionKey; the PEP needs a key of its own`. | +| `pep must be an object` | The `pep` value is present and is not a JSON object. | + +## The demo + +The demo protects `/orders/{id}` and `/attribute-protected` when `demo/wsfed.json` has a `pep` section. No sign-in is 401, with the heading Sign in, and the PEP is not asked. Otherwise the response status is `decision.httpStatus()`: 200 on a Permit, and 403 on a Deny and on Unavailable. A GET of an order is `read` and any other method is `write`. A Permit on an order uses the heading Order; a Permit on `/attribute-protected` uses Allowed. A Deny uses Not allowed. Unavailable uses No decision and the words "could not decide". `GET /attribute-protected` is always `Access.of("read", "attribute-protected", "attr1")`: the demo application's policy permits it when the person's directory attribute `attr1` is `abc123`, which the PEP asks iya-sts's PIP for (it is not in the assertion). With a receiver running, both pages use `decideSession`, so a session an event ended is a Deny. + +The signed-in home page links Home, Order 42 and Attribute-protected. `GET /live-status` carries `pep.status()` under `pep` (`mode` as `local` or `central`). `GET /pep-status` is that status as JSON and holds no secret. + +The install script sets the demo up with its PEP in one command, after registering the relying party: + +```bash +ADMIN_API_CLIENT_SECRET=... python3 scripts/configure_iya_sts.py --idp https://localhost:8443 --pep central +``` + +It does steps 2 to 6 above through the management API (a bare `--pep` is `local`): the service account `pep-wsfed-demo` (`--pep-name` to choose another) in `remote-peps`; a P-256 key made with your `openssl` in `demo/generated/pep-key.pem` (0600, never printed, kept out of the image by `.dockerignore`), certified with `issue-pep-credential` and bound to the demo's application; the catalogue row `subject.acr` → `urn:example:acr`; the application's **own** policy, enforced, which permits `read` on an `order` when the sign-in carried an `acr`, and `read` on `attribute-protected` when the person's directory attribute `attr1` is `abc123`, and denies everything else; `pep-policies-changed` in `ssfAllowedEvents` if the application restricts its events. It never touches the realm root. The application's display name stays `wsfed-caep-nodejs demo`. Finally it writes the `pep` section (`name`, `mode`, `assertionKey: file:generated/pep-key.pem`) into `demo/wsfed.json`, keeping everything else. `--dry-run` lists the calls and prints no key. + +With `--pep` and a test user (the default, `wsfed-demo-user`), the script also gives that user `attr1=abc123`. Defining the realm's custom attribute `attr1` uses a second token carrying `admin:security`. A run without `--pep` does not call that path. If the definition is refused and the value cannot be set, the script says what to add on the console and carries on. + +Run it again, for example with `--pep local` to switch modes: the account and the key are kept and the binding is set again. The application's policy is rewritten while its PolicyId is `urn:example:wsfeddemo-orders`; a policy under any other PolicyId is left as it is. + +`python3 scripts/live_iya_sts.py --pep` (or `LIVE_PEP=1`) runs that install with `--pep central`, writes `demo/wsfed.pep-local.json` with `mode` `local`, creates `wsfed-demo-user-denied` with `attr1=not-abc123`, and checks both modes: `GET /attribute-protected` 200 with the heading Allowed for the test user, 403 with Not allowed (and not "could not decide") for the denied user, who still gets 200 on `GET /orders/42`; `GET /orders/42` 200 and `POST /orders/42` 403. It then rewrites the application's own policy to deny read and requires the GET to turn 403 within 30 seconds because `pep-policies-changed` was received (`via` `event`; the fallback poll stays at 300 seconds). The result JSON has `pep.central` and `pep.local`. It needs `IYA_STS_IMAGE` with iya-sts #2026–#2028. Ports default to 18553 and 18653 and are never 3000, 8081, or 18481–18495. The containers are `iya-sts-live-wsfed-caep-java` and `wsfed-caep-java-live-demo`. The image is checked to hold only `idp-ca.pem` under `demo/generated`. The key pair, IdP metadata, the Shared Signals client certificate when present, and `pep-key.pem` are mounted file by file. Passwords stay in memory or in a mode-0600 file whose path is the only thing printed. + +On every signals-on run, not only `--pep`, the install script also issues the receiver's TLS client certificate and retires a previously pinned relying-party certificate. See the README's *Demo with its embedded PEP*. + +## See also + +- [`iya-pep`'s README](https://github.com/rcbj/iya-pep-java): the library's own API (`Pep`, `PepConfig`, `Decision`, `Subject`, `Access`, `SigningKey`). +- iya-sts's [Remote PEP page](https://rcbj.github.io/iya-sts/v1.2.0/remote-pep.html), *An embedded PEP's application*: the service's side of the binding, registration and the scoped pull. +- iya-sts's [CAEP events page](https://rcbj.github.io/iya-sts/v1.2.0/caep-events.html): the `pep-policies-changed` event. diff --git a/library/pom.xml b/library/pom.xml index e8015b1..12f4529 100644 --- a/library/pom.xml +++ b/library/pom.xml @@ -46,6 +46,11 @@ nimbus-jose-jwt 10.10 + + com.iyasec + iya-pep + 0.1.0 + org.junit.jupiter junit-jupiter diff --git a/library/src/main/java/com/iyasec/wsfed/Config.java b/library/src/main/java/com/iyasec/wsfed/Config.java index 52b18e2..ae7e6d9 100644 --- a/library/src/main/java/com/iyasec/wsfed/Config.java +++ b/library/src/main/java/com/iyasec/wsfed/Config.java @@ -73,9 +73,50 @@ public static Resolved resolve(Map config, String baseDir) { } if (config.get("idpCa") instanceof String ca && !ca.isBlank()) out.idpCa = material(ca, base, "idpCa"); if (config.get("idpEntityId") instanceof String entity && !entity.isBlank()) out.idpEntityId = entity; + if (config.get("ssf") instanceof Map ssf) { + Map section = new LinkedHashMap<>(); + ssf.forEach((key, value) -> section.put(String.valueOf(key), value)); + String cert = ssfText(section, "clientCertificate"); + String key = ssfText(section, "clientKey"); + if (cert != null || key != null) { + if (cert == null || key == null) { + throw new WsFedError("config", "ssf.clientCertificate and ssf.clientKey go together: give both or neither"); + } + String certPem = material(cert, base, "ssf.clientCertificate"); + String keyPem = material(key, base, "ssf.clientKey"); + String problem = Keys.clientIdentityProblem(certPem, keyPem); + if (problem != null) { + throw new WsFedError("config", "ssf.clientCertificate and ssf.clientKey are not a TLS client identity: " + problem); + } + out.ssfClientCertificate = certPem; + out.ssfClientKey = keyPem; + } + } + if (config.containsKey("pep") && config.get("pep") != null) { + if (!(config.get("pep") instanceof Map raw)) throw new WsFedError("config", "pep must be an object"); + Map section = new LinkedHashMap<>(); + raw.forEach((key, value) -> section.put(String.valueOf(key), value)); + if (section.get("assertionKey") instanceof String key) section.put("assertionKey", assertionKeyPath(key, base)); + out.pep = section; + } return out; } + private static String ssfText(Map ssf, String name) { + if (!ssf.containsKey(name) || ssf.get(name) == null) return null; + if (!(ssf.get(name) instanceof String text) || text.isBlank()) { + throw new WsFedError("config", "ssf." + name + " must be a PEM or a file path"); + } + return text.strip(); + } + + /** {@code file:} dropped; a relative path is taken from the configuration's directory. The PEP reads the file. */ + private static String assertionKeyPath(String key, String base) { + String path = key.startsWith("file:") ? key.substring(5) : key; + if (path.isEmpty() || path.contains("-----BEGIN ") || Path.of(path).isAbsolute()) return path; + return Path.of(base).resolve(path).toString(); + } + public static Resolved readFile(String path, Map overrides) { Map parsed; try { diff --git a/library/src/main/java/com/iyasec/wsfed/HttpClient.java b/library/src/main/java/com/iyasec/wsfed/HttpClient.java index 14d5cd7..c797cfc 100644 --- a/library/src/main/java/com/iyasec/wsfed/HttpClient.java +++ b/library/src/main/java/com/iyasec/wsfed/HttpClient.java @@ -13,7 +13,10 @@ import java.security.SecureRandom; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Duration; import java.util.Collection; +import java.util.List; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManagerFactory; @@ -62,6 +65,7 @@ public static Response send(String url, String method, Map heade throw new WsFedError(code, url + " is not an http(s) URL"); } refusePlainHttpOffLoopback(uri, code); + if ("PATCH".equalsIgnoreCase(method)) return patch(uri, headers, body, tls, code); HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection(); if (conn instanceof HttpsURLConnection https && tls != null && (tls.ca != null || tls.cert != null)) { https.setSSLSocketFactory(context(tls).getSocketFactory()); @@ -182,7 +186,9 @@ private static SSLContext context(Tls tls) throws Exception { KeyStore store = KeyStore.getInstance("PKCS12"); store.load(null, null); char[] password = new char[0]; - store.setKeyEntry("client", Config.privateKey(tls.key), password, new Certificate[] {Config.certificate(tls.cert)}); + List chain = Keys.certificates(tls.cert); + if (chain.isEmpty()) throw new IllegalArgumentException("the certificate holds no CERTIFICATE block"); + store.setKeyEntry("client", Keys.loadPrivateKey(tls.key), password, chain.toArray(Certificate[]::new)); keys = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keys.init(store, password); } @@ -190,4 +196,40 @@ private static SSLContext context(Tls tls) throws Exception { context.init(keys == null ? null : keys.getKeyManagers(), trust == null ? null : trust.getTrustManagers(), new SecureRandom()); return context; } + + /** + * PATCH is not a method {@link HttpURLConnection} will send. The JDK HTTP + * client does, with the same TLS material and without following a redirect. + */ + private static Response patch(URI uri, Map headers, String body, Tls tls, String code) { + try { + java.net.http.HttpClient.Builder builder = java.net.http.HttpClient.newBuilder() + .followRedirects(java.net.http.HttpClient.Redirect.NEVER) + .connectTimeout(Duration.ofMillis(TIMEOUT_MS)); + if ("https".equalsIgnoreCase(uri.getScheme()) && tls != null && (tls.ca != null || tls.cert != null)) { + builder.sslContext(context(tls)); + } + java.net.http.HttpRequest.Builder request = java.net.http.HttpRequest.newBuilder(uri) + .timeout(Duration.ofMillis(TIMEOUT_MS)); + if (headers != null) { + for (Map.Entry entry : headers.entrySet()) request.header(entry.getKey(), entry.getValue()); + } + request.method("PATCH", body == null + ? java.net.http.HttpRequest.BodyPublishers.noBody() + : java.net.http.HttpRequest.BodyPublishers.ofString(body)); + java.net.http.HttpResponse response = builder.build().send(request.build(), java.net.http.HttpResponse.BodyHandlers.ofByteArray()); + byte[] raw = response.body() == null ? new byte[0] : response.body(); + if (raw.length > MAX_BYTES) throw new WsFedError(code, uri + " answered more than " + MAX_BYTES + " bytes"); + String type = response.headers().firstValue("content-type").orElse(""); + return new Response(response.statusCode(), type, new String(raw, StandardCharsets.UTF_8)); + } catch (WsFedError err) { + throw err; + } catch (java.net.http.HttpTimeoutException err) { + Caught.error(err); + throw new WsFedError(code, uri + " did not answer within " + (TIMEOUT_MS / 1000) + " s", err); + } catch (Exception err) { + Caught.error(err); + throw new WsFedError(code, uri + ": " + err.getMessage(), err); + } + } } diff --git a/library/src/main/java/com/iyasec/wsfed/Keys.java b/library/src/main/java/com/iyasec/wsfed/Keys.java new file mode 100644 index 0000000..abe1adf --- /dev/null +++ b/library/src/main/java/com/iyasec/wsfed/Keys.java @@ -0,0 +1,163 @@ +// SPDX-FileCopyrightText: 2026 Iya CyberSecurity Solutions, LLC +// SPDX-License-Identifier: MIT + +package com.iyasec.wsfed; + +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.PrivateKey; +import java.security.Signature; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.security.interfaces.RSAKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collection; +import java.util.List; + +/** + * PEM private keys and certificate chains for the Shared Signals receiver's + * TLS client identity. The relying party's own key stays RSA PKCS#8 + * ({@link Config#privateKey}). + */ +public final class Keys { + private Keys() {} + + /** PKCS#8 (RSA or EC), PKCS#1 RSA, or SEC1 EC P-256 ({@code BEGIN EC PRIVATE KEY}). */ + public static PrivateKey loadPrivateKey(String pem) throws Exception { + String kind = kind(pem); + byte[] der = der(pem); + if ("pkcs8".equals(kind)) { + PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(der); + try { + return KeyFactory.getInstance("RSA").generatePrivate(spec); + } catch (Exception rsa) { + return KeyFactory.getInstance("EC").generatePrivate(spec); + } + } + if ("pkcs1".equals(kind)) { + return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(wrapPkcs1(der))); + } + if ("sec1".equals(kind)) { + return KeyFactory.getInstance("EC").generatePrivate(new PKCS8EncodedKeySpec(wrapSec1(der))); + } + throw new IllegalArgumentException("the client key cannot be read"); + } + + /** Every certificate in the PEM, leaf first. */ + public static List certificates(String pem) throws Exception { + Collection parsed = CertificateFactory.getInstance("X.509") + .generateCertificates(new ByteArrayInputStream(pem.getBytes(StandardCharsets.US_ASCII))); + List out = new ArrayList<>(); + for (java.security.cert.Certificate certificate : parsed) { + if (certificate instanceof X509Certificate x509) out.add(x509); + } + return out; + } + + /** Whether the private key signs as the certificate's public key. */ + public static boolean matches(PrivateKey key, X509Certificate certificate) { + try { + String algorithm = key instanceof RSAKey ? "SHA256withRSA" : "SHA256withECDSA"; + byte[] challenge = "wsfed-tls-client".getBytes(StandardCharsets.UTF_8); + Signature signature = Signature.getInstance(algorithm); + signature.initSign(key); + signature.update(challenge); + byte[] signed = signature.sign(); + signature.initVerify(certificate.getPublicKey()); + signature.update(challenge); + return signature.verify(signed); + } catch (Exception err) { + Caught.warn(err); + return false; + } + } + + /** + * Why {@code cert} (a PEM chain, leaf first) and {@code key} cannot be a + * TLS client identity, or null when they can. The same check the first + * connection would make, at configuration time. + */ + public static String clientIdentityProblem(String cert, String key) { + try { + List chain = certificates(cert); + if (chain.isEmpty()) return "the certificate holds no CERTIFICATE block"; + PrivateKey privateKey = loadPrivateKey(key); + if (!matches(privateKey, chain.get(0))) return "the private key does not match the certificate"; + return null; + } catch (Exception err) { + Caught.warn(err); + String message = err.getMessage(); + return message == null || message.isBlank() ? "the client key cannot be read" : message; + } + } + + public static String pem(String label, byte[] der) { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(der); + return "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n"; + } + + private static String kind(String pem) { + if (pem != null && pem.contains("-----BEGIN PRIVATE KEY-----")) return "pkcs8"; + if (pem != null && pem.contains("-----BEGIN RSA PRIVATE KEY-----")) return "pkcs1"; + if (pem != null && pem.contains("-----BEGIN EC PRIVATE KEY-----")) return "sec1"; + return ""; + } + + private static byte[] der(String pem) { + int begin = pem.indexOf("-----BEGIN "); + int end = pem.indexOf("-----END "); + String body = begin < 0 || end < 0 ? pem : pem.substring(pem.indexOf('\n', begin) + 1, end); + return Base64.getMimeDecoder().decode(body.replaceAll("\\s+", "")); + } + + /** PKCS#1 RSAPrivateKey wrapped as PKCS#8 PrivateKeyInfo. */ + private static byte[] wrapPkcs1(byte[] pkcs1) { + byte[] oid = {0x06, 0x09, 0x2a, (byte) 0x86, 0x48, (byte) 0x86, (byte) 0xf7, 0x0d, 0x01, 0x01, 0x01}; + return seq(integer(0), seq(oid, new byte[] {0x05, 0x00}), octet(pkcs1)); + } + + /** SEC1 ECPrivateKey wrapped as PKCS#8 for named curve prime256v1. */ + private static byte[] wrapSec1(byte[] sec1) { + byte[] ec = {0x06, 0x07, 0x2a, (byte) 0x86, 0x48, (byte) 0xce, 0x3d, 0x02, 0x01}; + byte[] p256 = {0x06, 0x08, 0x2a, (byte) 0x86, 0x48, (byte) 0xce, 0x3d, 0x03, 0x01, 0x07}; + return seq(integer(0), seq(ec, p256), octet(sec1)); + } + + private static byte[] seq(byte[]... parts) { + int size = 0; + for (byte[] part : parts) size += part.length; + byte[] body = new byte[size]; + int offset = 0; + for (byte[] part : parts) { + System.arraycopy(part, 0, body, offset, part.length); + offset += part.length; + } + return tlv(0x30, body); + } + + private static byte[] integer(int value) { + return tlv(0x02, new byte[] {(byte) value}); + } + + private static byte[] octet(byte[] body) { + return tlv(0x04, body); + } + + private static byte[] tlv(int tag, byte[] body) { + byte[] length = length(body.length); + byte[] out = new byte[1 + length.length + body.length]; + out[0] = (byte) tag; + System.arraycopy(length, 0, out, 1, length.length); + System.arraycopy(body, 0, out, 1 + length.length, body.length); + return out; + } + + private static byte[] length(int size) { + if (size < 128) return new byte[] {(byte) size}; + if (size < 256) return new byte[] {(byte) 0x81, (byte) size}; + return new byte[] {(byte) 0x82, (byte) (size >> 8), (byte) size}; + } +} diff --git a/library/src/main/java/com/iyasec/wsfed/RelyingParty.java b/library/src/main/java/com/iyasec/wsfed/RelyingParty.java index 05963ef..8281c87 100644 --- a/library/src/main/java/com/iyasec/wsfed/RelyingParty.java +++ b/library/src/main/java/com/iyasec/wsfed/RelyingParty.java @@ -16,8 +16,16 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.time.Instant; import java.util.Set; +import com.iyasec.pep.Access; +import com.iyasec.pep.Decision; +import com.iyasec.pep.Pep; +import com.iyasec.pep.PepException; +import com.iyasec.wsfed.pep.EmbeddedPep; +import com.iyasec.wsfed.ssf.SignalsReceiver; + /** WS-Federation 1.2 passive requestor. It does not start the Shared Signals receiver. */ public final class RelyingParty { public static final int MAX_RELAY_STATE = 1024; @@ -27,6 +35,7 @@ public final class RelyingParty { public final Resolved config; private IdpMetadata idp; private final MemoryReplayCache replayCache; + private Pep pep; public RelyingParty(Resolved config, IdpMetadata idp, MemoryReplayCache replayCache) { this.config = config; @@ -53,6 +62,7 @@ public static Resolved readConfigFile(String path) { public static RelyingParty create(Map config) { RelyingParty party = new RelyingParty(resolveConfig(config), null, null); party.refreshMetadata(); + party.startPep(); return party; } @@ -63,9 +73,59 @@ public static RelyingParty fromFile(String path) { public static RelyingParty fromFile(String path, Map overrides) { RelyingParty party = new RelyingParty(readConfigFile(path, overrides), null, null); party.refreshMetadata(); + party.startPep(); return party; } + /** The embedded PEP, when the configuration has a {@code pep} section. */ + public Pep pep() { + return pep; + } + + /** + * Decides one access for a validated sign-in. With no {@code pep} section + * the answer is Unavailable: nothing here permits by default. Never throws. + */ + public Decision decide(WsFedLogin login, Access access) { + try { + if (pep == null) return EmbeddedPep.unavailable("no pep section is configured"); + return pep.decide(EmbeddedPep.subjectOf(login), access); + } catch (RuntimeException err) { + Caught.error(err); + return EmbeddedPep.unavailable(err.getMessage() == null ? "the decision failed" : err.getMessage()); + } + } + + /** + * {@link #decide} for the sign-in kept under {@code localId} and tracked + * with {@code receiver}. A session the receiver no longer tracks, or one + * whose SessionNotOnOrAfter is now or past, is denied without asking. + * A null SessionNotOnOrAfter is not denied for that reason. Never throws. + */ + public Decision decideSession(SignalsReceiver receiver, String localId, WsFedLogin login, Access access) { + try { + if (login.sessionNotOnOrAfter != null && !login.sessionNotOnOrAfter.isAfter(Instant.now())) { + return EmbeddedPep.deny("the identity provider's session has ended"); + } + if (receiver == null || !receiver.isTracked(localId)) return EmbeddedPep.deny("no signed-in session"); + return decide(login, access); + } catch (RuntimeException err) { + Caught.error(err); + return EmbeddedPep.unavailable(err.getMessage() == null ? "the decision failed" : err.getMessage()); + } + } + + private void startPep() { + String issuer = idp == null || idp.entityId == null ? "" : idp.entityId; + pep = EmbeddedPep.build(config, issuer); + if (pep == null) return; + try { + pep.start(); + } catch (PepException err) { + throw new WsFedError("config", err.detail(), err); + } + } + public IdpMetadata getIdp() { if (idp == null) throw new WsFedError("metadata", "the identity provider's metadata has not been loaded"); return idp; diff --git a/library/src/main/java/com/iyasec/wsfed/Resolved.java b/library/src/main/java/com/iyasec/wsfed/Resolved.java index a8c96bf..3fea8d5 100644 --- a/library/src/main/java/com/iyasec/wsfed/Resolved.java +++ b/library/src/main/java/com/iyasec/wsfed/Resolved.java @@ -5,6 +5,7 @@ import java.security.PrivateKey; import java.security.cert.X509Certificate; +import java.util.Map; /** * Configuration after file: and env: are read. signals is null when the receiver is on @@ -23,4 +24,38 @@ public final class Resolved { public X509Certificate certificate; public String idpCa; public String idpEntityId; + /** + * The {@code pep} section, with a relative {@code assertionKey} made absolute + * against the configuration's directory. Null when the configuration has none. + */ + public Map pep; + /** + * The Shared Signals receiver's own TLS client identity + * ({@code ssf.clientCertificate}, a PEM chain with the leaf first, and + * {@code ssf.clientKey}). Null when the configuration names none. + */ + public String ssfClientCertificate; + public String ssfClientKey; + + /** + * The certificate chain and private key (PEM) the Shared Signals receiver + * authenticates with: {@code ssf.clientCertificate} and {@code ssf.clientKey} + * when set, else the relying party's own pair. Null when there is neither. + */ + public String[] ssfTlsClient() { + if (ssfClientCertificate != null && !ssfClientCertificate.isEmpty() + && ssfClientKey != null && !ssfClientKey.isEmpty()) { + return new String[] {ssfClientCertificate, ssfClientKey}; + } + if (certificate == null || privateKey == null) return null; + try { + return new String[] { + Keys.pem("CERTIFICATE", certificate.getEncoded()), + Keys.pem("PRIVATE KEY", privateKey.getEncoded()) + }; + } catch (Exception err) { + Caught.error(err); + throw new WsFedError("config", "the relying party's key pair cannot be encoded", err); + } + } } diff --git a/library/src/main/java/com/iyasec/wsfed/pep/EmbeddedPep.java b/library/src/main/java/com/iyasec/wsfed/pep/EmbeddedPep.java new file mode 100644 index 0000000..8787381 --- /dev/null +++ b/library/src/main/java/com/iyasec/wsfed/pep/EmbeddedPep.java @@ -0,0 +1,248 @@ +// SPDX-FileCopyrightText: 2026 Iya CyberSecurity Solutions, LLC +// SPDX-License-Identifier: MIT + +package com.iyasec.wsfed.pep; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.iyasec.pep.Decision; +import com.iyasec.pep.Mode; +import com.iyasec.pep.Pep; +import com.iyasec.pep.PepConfig; +import com.iyasec.pep.PepException; +import com.iyasec.pep.key.SigningKey; +import com.iyasec.pep.Status; +import com.iyasec.pep.Subject; +import com.iyasec.wsfed.Caught; +import com.iyasec.wsfed.Json; +import com.iyasec.wsfed.Resolved; +import com.iyasec.wsfed.WsFedError; +import com.iyasec.wsfed.WsFedLogin; +import java.math.BigInteger; +import java.security.interfaces.RSAPrivateCrtKey; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeSet; + +/** + * Wires {@code com.iyasec:iya-pep} into this relying party. The PEP knows no + * WS-Federation: this class fills the {@code pep} section's defaults, refuses + * a key this library already uses, and turns a validated sign-in into the + * PEP's subject. + */ +public final class EmbeddedPep { + /** + * The claim iya-sts puts the person's username in (its directory's + * canonical uid). It is the PEP subject id. {@code nameidentifier} is the + * opaque {@code sub} and is never the id. + */ + public static final String NAME_CLAIM = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"; + /** The claim that says how the person authenticated. Its values are {@code amr}. */ + public static final String AUTHENTICATION_METHOD_CLAIM = "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod"; + + private static final ObjectMapper JSON = new ObjectMapper(); + + private EmbeddedPep() {} + + /** + * Builds the PEP from the configuration's {@code pep} section, or null + * when there is none. {@code issuer} is the identity provider's entityID, + * the default {@code pdpUrl}. Does not start it. + */ + public static Pep build(Resolved config, String issuer) { + if (config == null || config.pep == null) return null; + Map map = new LinkedHashMap<>(config.pep); + if (!map.containsKey("signals")) map.put("signals", !Boolean.FALSE.equals(config.signals)); + if (!map.containsKey("tlsCa") && config.idpCa != null && config.idpCa.contains("-----BEGIN")) { + map.put("tlsCa", config.idpCa); + } + PepConfig pepConfig; + try { + pepConfig = PepConfig.fromJson(JSON.readTree(Json.stringify(map)), issuer == null ? "" : issuer, config.realm); + } catch (PepException err) { + throw new WsFedError("config", err.detail(), err); + } catch (Exception err) { + Caught.error(err); + throw new WsFedError("config", "pep must be an object", err); + } + Pep pep; + try { + pep = Pep.create(pepConfig); + } catch (PepException err) { + throw new WsFedError("config", err.detail(), err); + } + if (config.privateKey != null) { + String thumbprint = rsaThumbprint(config.privateKey); + if (thumbprint != null && thumbprint.equals(pep.keyThumbprint())) { + throw new WsFedError("config", "pep.assertionKey is the relying party's privateKey (its signing and decryption key); the PEP needs a key of its own"); + } + } + return pep; + } + + /** Whether a receiver given this PEP asks for {@code pep-policies-changed}. */ + public static boolean wantsEvents(Pep pep) { + PepConfig section = pep.config(); + return section.mode == Mode.LOCAL || section.permitCacheMs > 0; + } + + /** + * The PEP's subject for a validated sign-in. The id is the {@code name} + * claim, else the NameID. {@code nameidentifier} is never the id. + * Properties are attributes keyed by FriendlyName, else the Name's last + * segment, then {@code acr}, {@code amr} and {@code auth_time}. No request + * header is read. + */ + public static Subject subjectOf(WsFedLogin login) { + Map properties = new LinkedHashMap<>(); + Map> attributes = login.attributes == null ? Map.of() : login.attributes; + for (String name : new TreeSet<>(attributes.keySet())) { + String key = propertyName(name, login.attributeFriendlyNames == null ? null : login.attributeFriendlyNames.get(name)); + if (key == null || properties.containsKey(key)) continue; + JsonNode value = propertyValue(attributes.get(name)); + if (value != null) properties.put(key, value); + } + if (login.authnContextClassRef != null && !login.authnContextClassRef.isEmpty()) { + properties.put("acr", JSON.valueToTree(login.authnContextClassRef)); + } + JsonNode methods = propertyValue(attributes.get(AUTHENTICATION_METHOD_CLAIM)); + if (methods != null) { + if (methods.isArray()) properties.put("amr", methods); + else { + var array = JSON.createArrayNode(); + array.add(methods.asText()); + properties.put("amr", array); + } + } + if (login.authnInstant != null) properties.put("auth_time", JSON.valueToTree(login.authnInstant.getEpochSecond())); + String id = ""; + List names = attributes.get(NAME_CLAIM); + if (names != null) { + for (String name : names) { + if (name != null && !name.isBlank()) { + id = name; + break; + } + } + } + if (id.isEmpty() && login.nameId != null) id = login.nameId; + return Subject.user(id, properties); + } + + /** A Deny that did not ask the engine. */ + public static Decision deny(String why) { + return Decision.deny(why); + } + + /** No {@code pep} section is configured, so nothing is permitted. */ + public static Decision unavailable(String why) { + return Decision.unavailable(why); + } + + /** The event body as the JSON {@link Pep#onPolicyEvent} takes. */ + public static JsonNode toJson(Object value) { + return JSON.valueToTree(value == null ? Map.of() : value); + } + + /** {@link Pep#status()} as a map a health page can write. It holds no secret. */ + public static Map statusMap(Pep pep) { + if (pep == null) return null; + try { + Status status = pep.status(); + Map out = new LinkedHashMap<>(); + out.put("name", status.name); + out.put("mode", status.mode == null ? null : status.mode.asString()); + out.put("application", status.application); + out.put("registered", status.registered); + out.put("running", status.running); + out.put("holdsPolicy", status.holdsPolicy); + out.put("policyCount", status.policyCount); + out.put("syncToken", status.syncToken); + out.put("decisions", status.decisions); + out.put("allowed", status.allowed); + out.put("refused", status.refused); + out.put("unavailable", status.unavailable); + out.put("keyThumbprint", status.keyThumbprint); + out.put("lastError", status.lastError); + out.put("pdpUrl", status.pdpUrl); + out.put("eventStream", status.eventStream == null ? null : status.eventStream.asString()); + out.put("eventsReceived", status.eventsReceived); + out.put("catalogueSubjectProperties", status.catalogueSubjectProperties); + return out; + } catch (RuntimeException err) { + Caught.warn(err); + Map out = new LinkedHashMap<>(); + out.put("error", "status could not be read"); + return out; + } + } + + /** + * An attribute's property name: its FriendlyName, else the last segment + * of its Name, when it is one the catalogue can declare + * ({@code [A-Za-z0-9_$@:-]}, 1 to 64). A dot is not in that set, so an + * OID with no usable segment is left out. + */ + static String propertyName(String name, String friendly) { + if (segment(friendly)) return friendly; + String last = name == null ? "" : name; + int slash = last.lastIndexOf('/'); + if (slash >= 0) last = last.substring(slash + 1); + return segment(last) ? last : null; + } + + private static boolean segment(String text) { + if (text == null || text.isEmpty() || text.length() > 64) return false; + for (int i = 0; i < text.length(); i++) { + char c = text.charAt(i); + boolean ok = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') + || c == '_' || c == '$' || c == '@' || c == ':' || c == '-'; + if (!ok) return false; + } + return true; + } + + /** A single remaining value is a string, several an array. Empty values are skipped. */ + private static JsonNode propertyValue(List values) { + if (values == null || values.isEmpty()) return null; + List kept = new ArrayList<>(); + for (String value : values) if (value != null && !value.isEmpty()) kept.add(value); + if (kept.isEmpty()) return null; + if (kept.size() == 1) return JSON.valueToTree(kept.get(0)); + return JSON.valueToTree(kept); + } + + /** The RFC 7638 thumbprint of an RSA key's public half, or null when it cannot be taken. */ + private static String rsaThumbprint(java.security.PrivateKey key) { + if (!(key instanceof RSAPrivateCrtKey rsa)) return null; + try { + ObjectNode jwk = JSON.createObjectNode(); + jwk.put("kty", "RSA"); + jwk.put("n", b64(unsigned(rsa.getModulus()))); + jwk.put("e", b64(unsigned(rsa.getPublicExponent()))); + String thumbprint = SigningKey.jwkThumbprint(jwk); + return thumbprint == null || thumbprint.isEmpty() ? null : thumbprint; + } catch (RuntimeException err) { + Caught.warn(err); + return null; + } + } + + private static byte[] unsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + if (bytes.length > 1 && bytes[0] == 0) { + byte[] trimmed = new byte[bytes.length - 1]; + System.arraycopy(bytes, 1, trimmed, 0, trimmed.length); + return trimmed; + } + return bytes; + } + + private static String b64(byte[] data) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(data); + } +} diff --git a/library/src/main/java/com/iyasec/wsfed/ssf/SessionIndex.java b/library/src/main/java/com/iyasec/wsfed/ssf/SessionIndex.java index 2c3de05..a6f1596 100644 --- a/library/src/main/java/com/iyasec/wsfed/ssf/SessionIndex.java +++ b/library/src/main/java/com/iyasec/wsfed/ssf/SessionIndex.java @@ -59,6 +59,16 @@ public void remove(String localId) { sessions.remove(localId); } + /** Removes the session and returns it, or null when it was not tracked. */ + public Session take(String localId) { + return sessions.remove(localId); + } + + /** Tracked, and not past its expiry. An expired session is dropped. */ + public boolean contains(String localId) { + return !find(session -> localId.equals(session.localId)).isEmpty(); + } + public List byPerson(String person) { return find(session -> person.equals(session.person)); } diff --git a/library/src/main/java/com/iyasec/wsfed/ssf/SignalsReceiver.java b/library/src/main/java/com/iyasec/wsfed/ssf/SignalsReceiver.java index 0e40d1e..68a674c 100644 --- a/library/src/main/java/com/iyasec/wsfed/ssf/SignalsReceiver.java +++ b/library/src/main/java/com/iyasec/wsfed/ssf/SignalsReceiver.java @@ -3,11 +3,15 @@ package com.iyasec.wsfed.ssf; +import com.iyasec.pep.EventStream; +import com.iyasec.pep.Pep; +import com.iyasec.pep.key.SigningKey; import com.iyasec.wsfed.Caught; import com.iyasec.wsfed.HttpClient; import com.iyasec.wsfed.Json; import com.iyasec.wsfed.WsFedError; import com.iyasec.wsfed.WsFedLogin; +import com.iyasec.wsfed.pep.EmbeddedPep; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @@ -52,6 +56,19 @@ public static final class Options { public int pollIntervalMs = 5000; public int maxEvents = 50; public Log log; + /** Add Subject and Remove Subject. Default true. The demo reads {@code ssf.addSubjects}. */ + public boolean addSubjects = true; + /** The relying party's embedded PEP. Null when there is none. */ + public Pep pep; + } + + /** What Add Subject and Remove Subject have done since the receiver was made. */ + public static final class SubjectsHealth { + public long added; + public long removed; + public long refused; + public long failed; + public String lastError = ""; } private final String transmitter; @@ -66,6 +83,13 @@ public static final class Options { private final int pollIntervalMs; private final int maxEvents; private final Log log; + private final boolean addSubjects; + /** The PEP whose policy events this stream carries. Null unless it wants them. */ + private final Pep pep; + /** What the stream carries ({@code requested} or {@code excluded}), once {@code start} knows. */ + private volatile EventStream pepStream; + private final SubjectsHealth health = new SubjectsHealth(); + private final Object healthLock = new Object(); private Map config; private Map stream; private List> keys = List.of(); @@ -92,7 +116,29 @@ public SignalsReceiver(String transmitter, OnEndSessions onEnd, Options options) this.onEnd = onEnd; this.tls = opts.tls; this.headers = opts.headers; - this.eventsRequested = opts.eventsRequested == null ? List.copyOf(Events.DEFAULT_EVENTS_REQUESTED) : List.copyOf(opts.eventsRequested); + List requested = opts.eventsRequested == null ? new ArrayList<>(Events.DEFAULT_EVENTS_REQUESTED) : new ArrayList<>(opts.eventsRequested); + Pep given = opts.pep; + Pep kept = null; + if (given != null) { + String client = opts.tls == null || opts.tls.key == null ? null : SigningKey.pemThumbprint(opts.tls.key); + String pepKey = given.keyThumbprint(); + if (client != null && !client.isEmpty() && pepKey != null && !pepKey.isEmpty() && client.equals(pepKey)) { + throw new WsFedError("config", "the receiver's TLS client key is pep.assertionKey; the PEP needs a key of its own"); + } + if (EmbeddedPep.wantsEvents(given)) { + final Pep policyPep = given; + kept = policyPep; + if (!requested.contains(Pep.POLICIES_CHANGED_EVENT)) requested.add(Pep.POLICIES_CHANGED_EVENT); + handlers.computeIfAbsent(Pep.POLICIES_CHANGED_EVENT, key -> new ArrayList<>()).add(event -> { + try { + policyPep.onPolicyEvent(EmbeddedPep.toJson(event.payload)); + } catch (RuntimeException err) { + Caught.warn(err); + } + }); + } + } + this.eventsRequested = requested; this.endOn = opts.endOn == null ? List.copyOf(Events.DEFAULT_ENDING_EVENTS) : List.copyOf(opts.endOn); this.index = opts.sessionIndex == null ? new SessionIndex() : opts.sessionIndex; this.subjectAttribute = opts.subjectAttribute; @@ -100,18 +146,51 @@ public SignalsReceiver(String transmitter, OnEndSessions onEnd, Options options) this.pollIntervalMs = opts.pollIntervalMs; this.maxEvents = opts.maxEvents; this.log = opts.log == null ? new PrintLog() : opts.log; + this.addSubjects = opts.addSubjects; + this.pep = kept; } public Map stream() { return stream; } + /** The event types this receiver asks its stream for. */ + public List eventsRequested() { + return List.copyOf(eventsRequested); + } + + /** Tracked, not untracked, not past its expiry, and not ended by an event. */ + public boolean isTracked(String localId) { + return index.contains(localId); + } + + /** What Add Subject and Remove Subject have done. */ + public SubjectsHealth subjectsHealth() { + synchronized (healthLock) { + SubjectsHealth copy = new SubjectsHealth(); + copy.added = health.added; + copy.removed = health.removed; + copy.refused = health.refused; + copy.failed = health.failed; + copy.lastError = health.lastError; + return copy; + } + } + + /** + * Tracks a local session and, when {@code addSubjects} is on and the + * receiver is running, asks the transmitter to send events about that + * person. The call is inline and never fails the sign-in. + */ public void track(String localId, WsFedLogin login) { - index.add(SessionIndex.trackedFrom(localId, login, subjectAttribute, null)); + SessionIndex.Session session = SessionIndex.trackedFrom(localId, login, subjectAttribute, null); + index.add(session); + subjectCall(true, session); } + /** Stops tracking a local session and removes the subject when it was the last one. */ public void untrack(String localId) { - index.remove(localId); + forget(localId); } public SignalsReceiver on(String eventType, Consumer handler) { @@ -129,10 +208,24 @@ public void start() { if (!(endpoint instanceof String) || ((String) endpoint).isEmpty()) { throw new WsFedError("ssf", "the stream has no poll endpoint_url"); } + if (pep != null) { + boolean carried = carries(stream, "events_delivered"); + if (!(stream.get("events_delivered") instanceof List)) carried = carries(stream, "events_requested"); + if (!(stream.get("events_delivered") instanceof List) && !(stream.get("events_requested") instanceof List)) carried = true; + EventStream state = carried ? EventStream.REQUESTED : EventStream.EXCLUDED; + pep.setEventStream(state); + pepStream = state; + } running = true; Object delivered = stream.get("events_delivered"); int count = delivered instanceof List list ? list.size() : 0; log.info("ssf: polling stream " + stream.get("stream_id") + " at " + endpoint + ", delivering " + count + " event type(s)"); + if (addSubjects && pep != null) { + Map subject = new LinkedHashMap<>(); + subject.put("format", "opaque"); + subject.put("id", pep.config().application); + sendSubject(true, subject); + } thread = new Thread(this::loop, "ssf-poll"); thread.setDaemon(true); thread.start(); @@ -140,6 +233,7 @@ public void start() { public void stop() { running = false; + reportPepStream(EventStream.DOWN); Thread current = thread; if (current != null && current != Thread.currentThread()) { current.interrupt(); @@ -178,9 +272,11 @@ public boolean pollOnce() { } try { flight.result = pollNow(); + reportPepStream(pepStream); return flight.result; } catch (RuntimeException err) { Caught.error(err); + reportPepStream(EventStream.DOWN); flight.error = err; throw err; } finally { @@ -313,7 +409,7 @@ private void handle(String jti, String token) { event.ended = false; } if (event.ended) { - for (String localId : sessions) index.remove(localId); + for (String localId : sessions) forget(localId); } } List> both = new ArrayList<>(); @@ -385,7 +481,9 @@ private Map ensureStream() { if (!(item instanceof Map raw)) continue; Map one = Json.object(item); Object delivery = one.get("delivery"); - if (delivery instanceof Map map && POLL_METHOD.equals(map.get("method")) && one.get("stream_id") != null) return one; + if (delivery instanceof Map map && POLL_METHOD.equals(map.get("method")) && one.get("stream_id") != null) { + return withRequestedEvents(one, endpoint); + } } } else if (listed.status != 404) { throw new WsFedError("ssf", "listing the streams at " + endpoint + " answered " + listed.status + ": " + clip(Json.stringify(listed.json))); @@ -402,6 +500,41 @@ private Map ensureStream() { return made; } + /** + * A stream found rather than created can predate an event type this + * receiver asks for now. PATCH merges the missing types in. A transmitter + * that refuses leaves the stream as it was; the receiver still starts. + */ + private Map withRequestedEvents(Map found, String endpoint) { + List requested = eventNames(found.get("events_requested")); + if (requested == null) requested = eventNames(found.get("events_delivered")); + if (requested == null) return found; + List missing = new ArrayList<>(); + for (String event : eventsRequested) if (!requested.contains(event)) missing.add(event); + if (missing.isEmpty()) return found; + String streamId = String.valueOf(found.get("stream_id")); + List merged = new ArrayList<>(requested); + merged.addAll(missing); + Map body = new LinkedHashMap<>(); + body.put("stream_id", streamId); + body.put("events_requested", merged); + try { + Answer updated = call("PATCH", endpoint, body); + if (updated.status == 200 && updated.json instanceof Map raw) { + Map next = Json.object(raw); + if (streamId.equals(String.valueOf(next.get("stream_id")))) { + if (!next.containsKey("delivery") && found.get("delivery") != null) next.put("delivery", found.get("delivery")); + return next; + } + } + log.error("ssf: adding " + String.join(", ", missing) + " to stream " + streamId + " answered " + updated.status + ": " + clip(Json.stringify(updated.json))); + } catch (RuntimeException err) { + Caught.error(err); + log.error("ssf: adding " + String.join(", ", missing) + " to stream " + streamId + " failed: " + err.getMessage()); + } + return found; + } + private Answer call(String method, String url, Object body) { Map header = new LinkedHashMap<>(); header.put("accept", "application/json"); @@ -423,6 +556,97 @@ private Answer call(String method, String url, Object body) { return new Answer(answer.status, parsed); } + private void forget(String localId) { + SessionIndex.Session session = index.take(localId); + if (session == null) return; + List others; + if (session.person != null && !session.person.isEmpty()) others = index.byPerson(session.person); + else if (session.email != null && !session.email.isEmpty()) others = index.byEmail(session.email); + else others = List.of(); + if (others.isEmpty()) subjectCall(false, session); + } + + /** Add Subject or Remove Subject for a tracked person. Never retried, never an error to the caller. */ + private void subjectCall(boolean add, SessionIndex.Session session) { + if (!addSubjects || !running) return; + String issuer = config == null || config.get("issuer") == null ? "" : String.valueOf(config.get("issuer")); + Map subject = subjectOfSession(session, issuer); + if (subject == null) return; + sendSubject(add, subject); + } + + private static Map subjectOfSession(SessionIndex.Session session, String issuer) { + if (session.person != null && !session.person.isEmpty() && issuer != null && !issuer.isEmpty()) { + Map subject = new LinkedHashMap<>(); + subject.put("format", "iss_sub"); + subject.put("iss", issuer); + subject.put("sub", session.person); + return subject; + } + if (session.email != null && !session.email.isEmpty()) { + Map subject = new LinkedHashMap<>(); + subject.put("format", "email"); + subject.put("email", session.email); + return subject; + } + return null; + } + + /** Add Subject or Remove Subject for {@code subject} on this stream, once. Counted, never thrown. */ + private void sendSubject(boolean add, Map subject) { + String name = add ? "add_subject_endpoint" : "remove_subject_endpoint"; + String endpoint = config == null || config.get(name) == null ? "" : String.valueOf(config.get(name)); + String streamId = stream == null || stream.get("stream_id") == null ? "" : String.valueOf(stream.get("stream_id")); + if (endpoint.isEmpty() || "null".equals(endpoint) || streamId.isEmpty() || "null".equals(streamId)) return; + Map body = new LinkedHashMap<>(); + body.put("stream_id", streamId); + body.put("subject", subject); + if (add) body.put("verified", Boolean.TRUE); + String what = add ? "adding" : "removing"; + Object format = subject.get("format"); + try { + Answer outcome = call("POST", endpoint, body); + synchronized (healthLock) { + if (outcome.status >= 200 && outcome.status < 300) { + if (add) health.added++; + else health.removed++; + return; + } + String line = "ssf: " + what + " a subject (" + format + ") on stream " + streamId + " answered " + outcome.status + ": " + clip(Json.stringify(outcome.json)); + if (outcome.status >= 400 && outcome.status < 500) health.refused++; + else health.failed++; + health.lastError = line; + if (outcome.status == 403) log.warn(line); + else log.error(line); + } + } catch (RuntimeException err) { + Caught.error(err); + String line = "ssf: " + what + " a subject (" + format + ") on stream " + streamId + " failed: " + err.getMessage(); + synchronized (healthLock) { + health.failed++; + health.lastError = line; + } + log.error(line); + } + } + + private void reportPepStream(EventStream state) { + if (pep != null && state != null) pep.setEventStream(state); + } + + private static boolean carries(Map stream, String name) { + if (!(stream.get(name) instanceof List list)) return false; + for (Object item : list) if (Pep.POLICIES_CHANGED_EVENT.equals(String.valueOf(item))) return true; + return false; + } + + private static List eventNames(Object value) { + if (!(value instanceof List list)) return null; + List out = new ArrayList<>(); + for (Object item : list) if (item != null) out.add(String.valueOf(item)); + return out; + } + private static List strings(Object value) { List out = new ArrayList<>(); if (value instanceof List list) { diff --git a/library/src/test/java/com/iyasec/wsfed/AuthzenTest.java b/library/src/test/java/com/iyasec/wsfed/AuthzenTest.java new file mode 100644 index 0000000..5bb52f1 --- /dev/null +++ b/library/src/test/java/com/iyasec/wsfed/AuthzenTest.java @@ -0,0 +1,603 @@ +// SPDX-FileCopyrightText: 2026 Iya CyberSecurity Solutions, LLC +// SPDX-License-Identifier: MIT + +package com.iyasec.wsfed; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.iyasec.pep.Access; +import com.iyasec.pep.Decision; +import com.iyasec.pep.Json; +import com.iyasec.pep.Obligation; +import com.iyasec.pep.Pep; +import com.iyasec.pep.Status; +import com.iyasec.wsfed.pep.EmbeddedPep; +import com.iyasec.wsfed.ssf.SignalsReceiver; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPairGenerator; +import java.security.spec.ECGenParameterSpec; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Predicate; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * The AuthZEN table, decided in process through {@link RelyingParty#decide} + * and {@link RelyingParty#decideSession}. The catalogue, cases and compiled + * policy documents are test resources. + */ +class AuthzenTest { + private static final String ACCESS_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"; + private static final String XS_STRING = "http://www.w3.org/2001/XMLSchema#string"; + /** The entry DN the registration answer names, written as the caller fact. */ + private static final String STUB_PEP_DN = "uid=pep-wsfed-authzen,ou=users,dc=example,dc=com"; + + @Test + void theTableCoversWhatItMustAndMatchesItsCompiledPolicies() { + JsonNode table = resource("test_authzen.json"); + JsonNode documents = resource("test_authzen_policies.json"); + assertTrue(table.path("cases").isArray()); + assertTrue(table.path("phases").isArray()); + Set ids = new HashSet<>(); + for (JsonNode kase : table.path("cases")) { + String id = kase.path("id").asText(); + assertTrue(ids.add(id), "case " + id + " twice"); + assertTrue(Set.of("Permit", "Deny", "Unavailable").contains(kase.path("expect").asText()), id); + assertTrue(listed(table.path("phases"), kase.path("phase").asText()), id); + loginFor(table, kase.path("login"), StubIdp.REALM); + accessFor(kase.path("access")); + } + for (JsonNode policy : table.path("policies")) { + String name = policy.path("name").asText(); + JsonNode held = documents.path("policies").path(name); + assertTrue(held.path("policyId").isTextual(), name + " is not compiled"); + String alfa = String.join("\n", strings(policy.get("alfa"))); + String policyId = held.get("policyId").asText(); + assertTrue(alfa.contains("id = \"" + policyId + "\""), name + "'s compiled PolicyId " + policyId + " is not in its ALFA"); + } + List kinds = new ArrayList<>(); + for (JsonNode row : table.path("catalogue")) { + JsonNode dataType = row.get("dataType"); + String type = dataType != null && dataType.isTextual() ? dataType.asText() : "string"; + kinds.add(new String[] {row.path("object").asText(), type}); + } + for (String wanted : List.of("integer", "double", "boolean", "dateTime")) { + boolean found = false; + for (String[] kind : kinds) if (wanted.equals(kind[1])) found = true; + assertTrue(found, "a " + wanted + " row"); + } + for (String object : List.of("subject", "resource", "action", "context")) { + boolean found = false; + for (String[] kind : kinds) if (object.equals(kind[0])) found = true; + assertTrue(found, "a " + object + " row"); + } + } + + @Test + void everyCaseAnswersAsTheTableSaysInLocalMode(@TempDir Path dir) throws Exception { + JsonNode table = resource("test_authzen.json"); + JsonNode documents = resource("test_authzen_policies.json"); + Pdp pdp = Pdp.open(table); + SignalsReceiver receiver = new SignalsReceiver("http://127.0.0.1:1", (sessions, event) -> { }); + try { + List failures = new ArrayList<>(); + int ran = 0; + for (JsonNode phaseNode : table.path("phases")) { + String phase = phaseNode.asText(); + pdp.serve(phase, pulledPolicies(table, documents, phase, StubIdp.REALM)); + RelyingParty party = null; + try { + party = RelyingParty.create(config(pdp.url, ecPkcs8(dir.resolve("pep-" + phase + ".pem")))); + waitFor(party, "registered and held the policy", status -> status.registered && status.holdsPolicy); + for (JsonNode kase : cases(table, phase)) { + ran++; + Decision decision = runCase(table, party, receiver, kase, StubIdp.REALM); + ObjectNode answer = answerOf(decision); + if (!asExpected(answer, kase)) { + failures.add(kase.path("id").asText() + " (" + phase + "): got " + answer + + " (" + whyOf(decision) + "), want " + kase.get("expect")); + } + } + } finally { + if (party != null && party.pep() != null) party.pep().stop(); + } + } + assertEquals(table.path("cases").size(), ran, "every case is in a phase"); + assertTrue(failures.isEmpty(), failures.size() + " of " + ran + " cases:\n" + String.join("\n", failures)); + assertEquals(0, pdp.evaluations.get(), "a local decision never asks the AuthZEN endpoint"); + } finally { + pdp.close(); + } + } + + private static JsonNode pick(JsonNode spec, JsonNode base, String key) { + if (spec != null && spec.has(key)) return spec.get(key); + if (base != null && base.has(key)) return base.get(key); + return Json.MAPPER.nullNode(); + } + + /** The base object with {@code over} laid on it. A null removes a member. */ + private static ObjectNode overlay(JsonNode base, JsonNode over) { + ObjectNode out = Json.object(); + if (base != null && base.isObject()) { + base.fields().forEachRemaining(entry -> out.set(entry.getKey(), entry.getValue().deepCopy())); + } + if (over != null && over.isObject()) { + over.fields().forEachRemaining(entry -> { + if (entry.getValue().isNull()) out.remove(entry.getKey()); + else out.set(entry.getKey(), entry.getValue().deepCopy()); + }); + } + return out; + } + + private static List strings(JsonNode value) { + List out = new ArrayList<>(); + if (value != null && value.isArray()) { + for (JsonNode item : value) if (item.isTextual()) out.add(item.asText()); + } + return out; + } + + private static String uri(JsonNode table, String shortName) { + JsonNode value = table.path("claims").get(shortName); + if (value == null || !value.isTextual()) throw new IllegalStateException("no claim called " + shortName); + return value.asText(); + } + + private static String text(JsonNode node, String key) { + JsonNode value = node == null ? null : node.get(key); + if (value == null || !value.isTextual()) throw new IllegalStateException(key); + return value.asText(); + } + + private static WsFedLogin loginFor(JsonNode table, JsonNode spec, String application) { + JsonNode base = table.path("logins").path(text(spec, "base")); + if (!base.isObject()) throw new IllegalStateException("a login names its base"); + WsFedLogin login = new WsFedLogin(); + login.attributes = new LinkedHashMap<>(); + login.attributeFriendlyNames = new LinkedHashMap<>(); + ObjectNode claims = overlay(base.get("claims"), spec.get("claims")); + claims.fields().forEachRemaining(entry -> login.attributes.put(uri(table, entry.getKey()), strings(entry.getValue()))); + List amr = strings(pick(spec, base, "amr")); + if (!amr.isEmpty()) login.attributes.put(EmbeddedPep.AUTHENTICATION_METHOD_CLAIM, amr); + ObjectNode friendly = overlay(base.get("friendly"), spec.get("friendly")); + friendly.fields().forEachRemaining(entry -> { + if (!entry.getValue().isTextual()) throw new IllegalStateException("friendly " + entry.getKey()); + login.attributeFriendlyNames.put(uri(table, entry.getKey()), entry.getValue().asText()); + }); + JsonNode authTime = pick(spec, base, "auth_time"); + if (!authTime.isIntegralNumber()) throw new IllegalStateException("auth_time"); + login.authnInstant = Instant.ofEpochSecond(authTime.asLong()); + JsonNode nameId = pick(spec, base, "name_id"); + if (!nameId.isTextual()) throw new IllegalStateException("name_id"); + login.nameId = nameId.asText(); + login.nameIdFormat = "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"; + login.issuer = "https://iya-sts.test"; + login.realm = application; + login.trustVersion = "2005/02"; + login.assertionId = "_authzen"; + login.notOnOrAfter = Instant.now().plusSeconds(3600); + login.sessionIndex = "authzen-session"; + if (spec.path("session_over").asBoolean(false)) login.sessionNotOnOrAfter = Instant.now().minusSeconds(1); + JsonNode acr = pick(spec, base, "acr"); + if (acr.isTextual()) login.authnContextClassRef = acr.asText(); + return login; + } + + private static Map mapOf(JsonNode spec, String key) { + Map out = new LinkedHashMap<>(); + JsonNode node = spec == null ? null : spec.get(key); + if (node != null && node.isObject()) { + node.fields().forEachRemaining(entry -> out.put(entry.getKey(), entry.getValue().deepCopy())); + } + return out; + } + + private static Access accessFor(JsonNode spec) { + Access access = Access.of(text(spec, "action"), text(spec, "type"), text(spec, "id")); + access.resourceProperties = mapOf(spec, "resource"); + access.actionProperties = mapOf(spec, "action_properties"); + access.context = mapOf(spec, "context"); + return access; + } + + private static Decision runCase(JsonNode table, RelyingParty party, SignalsReceiver receiver, JsonNode kase, String application) { + WsFedLogin login = loginFor(table, kase.path("login"), application); + Access access = accessFor(kase.path("access")); + JsonNode session = kase.get("session"); + if (session == null || !session.isTextual()) return party.decide(login, access); + String localId = "authzen-" + kase.path("id").asText(); + receiver.track(localId, login); + if ("ended".equals(session.asText())) receiver.untrack(localId); + return party.decideSession(receiver, localId, login, access); + } + + /** The decision the host sees. A Permit keeps each obligation's type and properties. */ + private static ObjectNode answerOf(Decision decision) { + if (decision.kind() == Decision.Kind.PERMIT) { + List handed = new ArrayList<>(); + for (Obligation obligation : decision.obligations()) { + ObjectNode one = Json.object(); + one.put("type", obligation.kind); + one.set("properties", obligation.properties.deepCopy()); + handed.add(one); + } + handed.sort((left, right) -> left.toString().compareTo(right.toString())); + ArrayNode obligations = Json.array(); + for (ObjectNode one : handed) obligations.add(one); + ObjectNode answer = Json.object(); + answer.put("decision", "Permit"); + answer.set("obligations", obligations); + return answer; + } + ObjectNode answer = Json.object(); + answer.put("decision", decision.kind() == Decision.Kind.DENY ? "Deny" : "Unavailable"); + return answer; + } + + private static String whyOf(Decision decision) { + return decision.kind() == Decision.Kind.PERMIT ? "" : decision.why(); + } + + /** The decision, and for a Permit the obligation types (none when the case lists none). */ + private static boolean asExpected(ObjectNode answer, JsonNode kase) { + if (!answer.path("decision").asText().equals(kase.path("expect").asText())) return false; + if (!"Permit".equals(answer.path("decision").asText())) return true; + List handed = new ArrayList<>(); + JsonNode obligations = answer.get("obligations"); + if (obligations != null && obligations.isArray()) { + for (JsonNode obligation : obligations) { + if (obligation.path("type").isTextual()) handed.add(obligation.get("type").asText()); + } + } + List wanted = strings(kase.has("obligations") ? kase.get("obligations") : Json.array()); + Collections.sort(handed); + Collections.sort(wanted); + return handed.equals(wanted); + } + + private static List cases(JsonNode table, String phase) { + List out = new ArrayList<>(); + for (JsonNode kase : table.path("cases")) { + if (phase.equals(kase.path("phase").asText())) out.add(kase); + } + return out; + } + + /** The phase's policies: the root first, then the policies it references. */ + private static List pulledPolicies(JsonNode table, JsonNode documents, String phase, String application) { + List rows = new ArrayList<>(); + for (JsonNode policy : table.path("policies")) { + if (!phase.equals(policy.path("phase").asText())) continue; + String name = policy.path("name").asText(); + JsonNode held = documents.path("policies").path(name); + if (!held.isObject() || !held.path("policyId").isTextual() || !held.path("document").isTextual()) { + throw new IllegalStateException("test_authzen_policies.json has no " + name); + } + ObjectNode row = Json.object(); + row.put("name", name); + row.put("policyId", held.get("policyId").asText()); + row.put("kind", held.path("kind").asText()); + row.put("version", held.path("version").asText()); + row.put("isRoot", !"referenced".equals(policy.path("role").asText())); + row.put("description", ""); + row.put("document", held.get("document").asText().replace("{{application}}", application)); + rows.add(row); + } + rows.sort((left, right) -> Boolean.compare(right.path("isRoot").asBoolean(), left.path("isRoot").asBoolean())); + return rows; + } + + private static Map config(String pdpUrl, String key) { + Map pep = new LinkedHashMap<>(); + pep.put("name", "pep-wsfed-authzen"); + pep.put("mode", "local"); + pep.put("assertionKey", key); + pep.put("pdpUrl", pdpUrl); + pep.put("pollIntervalMs", 1000); + pep.put("heartbeatIntervalMs", 60000); + pep.put("supportedObligations", List.of("step-up")); + Map config = new LinkedHashMap<>(); + config.put("realm", StubIdp.REALM); + config.put("replyUrl", StubIdp.REPLY); + config.put("signals", false); + config.put("idpMetadata", StubIdp.idpMetadata()); + config.put("pep", pep); + return config; + } + + private static String ecPkcs8(Path path) throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("EC"); + generator.initialize(new ECGenParameterSpec("secp256r1")); + var pair = generator.generateKeyPair(); + String encoded = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(pair.getPrivate().getEncoded()); + Files.writeString(path, "-----BEGIN PRIVATE KEY-----\n" + encoded + "\n-----END PRIVATE KEY-----\n"); + return path.toAbsolutePath().toString(); + } + + private static void waitFor(RelyingParty party, String what, Predicate ready) throws InterruptedException { + Pep pep = party.pep(); + assertTrue(pep != null, "a PEP"); + long deadline = System.nanoTime() + 90_000_000_000L; + while (System.nanoTime() < deadline) { + if (ready.test(pep.status())) return; + try { + Thread.sleep(200); + } catch (InterruptedException err) { + Thread.currentThread().interrupt(); + throw err; + } + } + Status status = pep.status(); + assertTrue(ready.test(status), "the " + pep.config().name + " PEP never " + what + ": " + status.lastError); + } + + private static boolean listed(JsonNode array, String text) { + if (array == null || !array.isArray()) return false; + for (JsonNode item : array) if (text.equals(item.asText())) return true; + return false; + } + + private static JsonNode resource(String name) { + try (InputStream in = AuthzenTest.class.getResourceAsStream("/" + name)) { + if (in == null) throw new IllegalStateException(name + " is not on the classpath"); + return Json.MAPPER.readTree(in); + } catch (IOException err) { + throw new IllegalStateException(name + " is not JSON", err); + } + } + + /** A stub PDP: catalogue, compiled policies, the directory's PIP, and a refused evaluation. */ + private static final class Pdp implements AutoCloseable { + final String url; + final AtomicInteger evaluations = new AtomicInteger(); + private final HttpServer server; + private final ExecutorService executor; + private final JsonNode rows; + private final JsonNode directory; + private String token = ""; + private List policies = List.of(); + private List fga = List.of(); + + private Pdp(HttpServer server, ExecutorService executor, JsonNode rows, JsonNode directory) { + this.server = server; + this.executor = executor; + this.rows = rows; + this.directory = directory; + this.url = "http://127.0.0.1:" + server.getAddress().getPort(); + } + + static Pdp open(JsonNode table) throws IOException { + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + ExecutorService executor = Executors.newCachedThreadPool(runnable -> { + Thread thread = new Thread(runnable, "authzen-pdp"); + thread.setDaemon(true); + return thread; + }); + server.setExecutor(executor); + Pdp pdp = new Pdp(server, executor, table.path("catalogue"), table.path("directory")); + server.createContext("/", pdp::handle); + server.start(); + return pdp; + } + + synchronized void serve(String phase, List policies) { + this.token = "authzen-" + phase; + this.policies = List.copyOf(policies); + this.fga = "application".equals(phase) ? List.of(StubIdp.REALM) : List.of(); + } + + @Override + public void close() { + server.stop(0); + executor.shutdownNow(); + } + + private void handle(HttpExchange exchange) { + try { + String text = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8); + String path = exchange.getRequestURI().getPath(); + if (path == null) path = ""; + Reply reply = answer(path, text); + byte[] out = reply.body.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("content-type", reply.type); + exchange.sendResponseHeaders(reply.status, out.length); + exchange.getResponseBody().write(out); + } catch (IOException err) { + try { + exchange.sendResponseHeaders(500, -1); + } catch (IOException ignored) { + // The exchange is already gone. + } + } finally { + exchange.close(); + } + } + + private Reply answer(String path, String body) { + if ("/oauth2/token".equals(path)) { + ObjectNode token = Json.object(); + token.put("access_token", "pep-token"); + token.put("token_type", "DPoP"); + token.put("expires_in", 300); + return Reply.json(200, token); + } + if ("/xacml/pep/register".equals(path)) { + ObjectNode registered = Json.object(); + registered.put("registered", true); + registered.put("identity", STUB_PEP_DN); + return Reply.json(201, registered); + } + if ("/xacml/pep/heartbeat".equals(path)) { + ObjectNode heartbeat = Json.object(); + heartbeat.put("acknowledged", true); + heartbeat.put("current", true); + return Reply.json(200, heartbeat); + } + if ("/xacml/pep/authzen-catalogue".equals(path)) return Reply.json(200, catalogue()); + if ("/xacml/pep/policies".equals(path)) return Reply.json(200, policies()); + if ("/xacml/pip".equals(path)) return new Reply(200, "application/xml", pipAnswer(directory, body)); + if ("/admin-api/pep-audit".equals(path)) { + ObjectNode audit = Json.object(); + audit.put("acknowledged", 0); + return Reply.json(200, audit); + } + if ("/access/v1/evaluation".equals(path)) { + evaluations.incrementAndGet(); + ObjectNode error = Json.object(); + error.put("error", "server_error"); + return Reply.json(500, error); + } + ObjectNode missing = Json.object(); + missing.put("error", "not_found"); + return Reply.json(404, missing); + } + + private ObjectNode catalogue() { + List applications = fga(); + ObjectNode body = Json.object(); + body.put("syncToken", "authzen-rows-" + applications.size()); + body.set("rows", rows.deepCopy()); + ArrayNode fgaApplications = Json.array(); + for (String application : applications) fgaApplications.add(application); + body.set("fgaApplications", fgaApplications); + ObjectNode settings = Json.object(); + settings.put("obligationsProfile", true); + body.set("settings", settings); + return body; + } + + private ObjectNode policies() { + String sync; + List held; + synchronized (this) { + sync = token; + held = policies; + } + ObjectNode body = Json.object(); + body.put("syncToken", sync); + JsonNode root = Json.MAPPER.nullNode(); + ArrayNode list = Json.array(); + for (ObjectNode row : held) { + list.add(row.deepCopy()); + if (root.isNull() && row.path("isRoot").asBoolean(false) && row.get("name") != null) { + root = row.get("name").deepCopy(); + } + } + if (root == null || root.isNull()) body.putNull("root"); + else body.set("root", root); + body.set("policies", list); + body.set("withheld", Json.array()); + body.put("note", ""); + return body; + } + + private synchronized List fga() { + return fga; + } + + /** The subject id's person, and each designator by its attribute name. */ + private static String pipAnswer(JsonNode directory, String query) { + String subject = ""; + int subjectAt = query.indexOf("subject:subject-id"); + if (subjectAt >= 0) { + int valueAt = query.indexOf("= 0) { + Slice span = between(query, valueAt, "\">", ""); + if (span != null) subject = span.text; + } + } + JsonNode person = null; + if (directory != null && directory.isArray()) { + for (JsonNode entry : directory) { + JsonNode username = entry.get("username"); + if (username != null && username.isTextual() && subject.equals(username.asText())) { + person = entry; + break; + } + } + } + StringBuilder attributes = new StringBuilder(); + int from = 0; + while (true) { + Slice designator = between(query, from, ""); + if (designator == null) break; + from = designator.at; + Slice id = between(designator.text, 0, "AttributeId=\"", "\""); + Slice category = between(designator.text, 0, "Category=\"", "\""); + Slice dataType = between(designator.text, 0, "DataType=\"", "\""); + String attributeId = id == null ? "" : id.text; + JsonNode value = person == null ? null : person.path("attributes").get(attributeId); + if (value == null || !value.isTextual()) continue; + if (!ACCESS_SUBJECT.equals(category == null ? "" : category.text) || !XS_STRING.equals(dataType == null ? "" : dataType.text)) { + continue; + } + attributes.append("").append(value.asText()) + .append(""); + } + return "" + attributes + ""; + } + } + + private static Slice between(String text, int from, String start, String end) { + if (text == null || from < 0 || from > text.length()) return null; + int at = text.indexOf(start, from); + if (at < 0) return null; + int value = at + start.length(); + int stop = text.indexOf(end, value); + if (stop < 0) return null; + return new Slice(text.substring(value, stop), stop); + } + + private static final class Slice { + final String text; + final int at; + + Slice(String text, int at) { + this.text = text; + this.at = at; + } + } + + private static final class Reply { + final int status; + final String type; + final String body; + + Reply(int status, String type, String body) { + this.status = status; + this.type = type; + this.body = body; + } + + static Reply json(int status, JsonNode body) { + return new Reply(status, "application/json", body.toString()); + } + } +} diff --git a/library/src/test/java/com/iyasec/wsfed/PepTest.java b/library/src/test/java/com/iyasec/wsfed/PepTest.java new file mode 100644 index 0000000..dcd3e4f --- /dev/null +++ b/library/src/test/java/com/iyasec/wsfed/PepTest.java @@ -0,0 +1,397 @@ +// SPDX-FileCopyrightText: 2026 Iya CyberSecurity Solutions, LLC +// SPDX-License-Identifier: MIT + +package com.iyasec.wsfed; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.iyasec.pep.Access; +import com.iyasec.pep.Decision; +import com.iyasec.pep.Mode; +import com.iyasec.pep.Pep; +import com.iyasec.wsfed.pep.EmbeddedPep; +import com.iyasec.wsfed.ssf.SignalsReceiver; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPairGenerator; +import java.security.spec.ECGenParameterSpec; +import java.time.Instant; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** The embedded PEP's subject, and the decisions the relying party gives. */ +class PepTest { + @Test + void subjectIdIsTheNameClaimElseTheNameId() { + WsFedLogin login = login(); + login.attributes.put(EmbeddedPep.NAME_CLAIM, List.of("alice")); + login.attributes.put("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", List.of("urn:uuid:alice")); + login.nameId = "alice"; + var subject = EmbeddedPep.subjectOf(login); + assertEquals("alice", subject.id); + assertEquals("user", subject.kind); + assertEquals("urn:uuid:alice", subject.properties.get("nameidentifier").asText()); + assertFalse(subject.id.equals(subject.properties.get("nameidentifier").asText())); + } + + @Test + void anEmptyNameClaimFallsThroughToTheNameId() { + WsFedLogin login = login(); + login.attributes.put(EmbeddedPep.NAME_CLAIM, List.of("", " ")); + login.nameId = "from-nameid"; + assertEquals("from-nameid", EmbeddedPep.subjectOf(login).id); + } + + @Test + void propertiesUseFriendlyNameElseTheLastSegmentThenAuthentication() { + WsFedLogin login = login(); + login.nameId = "alice"; + login.attributes.put("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", List.of("alice@example.com")); + login.attributeFriendlyNames.put("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", "mail"); + login.attributes.put("urn:oid:0.9.2342.19200300.100.1.1", List.of("dropped")); + login.attributes.put("http://example.test/role", List.of("one", "", "two")); + login.attributes.put("http://example.test/z-first", List.of("later")); + login.attributes.put("http://example.test/a-first", List.of("earlier")); + login.attributeFriendlyNames.put("http://example.test/z-first", "shared"); + login.attributeFriendlyNames.put("http://example.test/a-first", "shared"); + login.attributes.put(EmbeddedPep.AUTHENTICATION_METHOD_CLAIM, List.of("pwd", "")); + login.authnContextClassRef = "urn:example:acr"; + login.authnInstant = Instant.ofEpochSecond(1_700_000_000L); + login.attributes.put("http://example.test/acr", List.of("from-attribute")); + var properties = EmbeddedPep.subjectOf(login).properties; + assertEquals("alice@example.com", properties.get("mail").asText()); + assertNull(properties.get("emailaddress")); + assertNull(properties.get("urn:oid:0.9.2342.19200300.100.1.1")); + assertEquals(2, properties.get("role").size()); + assertEquals("one", properties.get("role").get(0).asText()); + assertEquals("earlier", properties.get("shared").asText()); + assertEquals("urn:example:acr", properties.get("acr").asText()); + assertTrue(properties.get("amr").isArray()); + assertEquals(1, properties.get("amr").size()); + assertEquals("pwd", properties.get("amr").get(0).asText()); + assertEquals(1_700_000_000L, properties.get("auth_time").asLong()); + } + + @Test + void aSingleAuthenticationMethodIsStillAnArray() { + WsFedLogin login = login(); + login.attributes.put(EmbeddedPep.AUTHENTICATION_METHOD_CLAIM, List.of("pwd")); + assertTrue(EmbeddedPep.subjectOf(login).properties.get("amr").isArray()); + } + + @Test + void noPepSectionIsUnavailable() { + RelyingParty party = RelyingParty.create(base()); + Decision decision = party.decide(login(), Access.of("read", "order", "42")); + assertEquals(Decision.Kind.UNAVAILABLE, decision.kind()); + assertEquals(403, decision.httpStatus()); + assertTrue(decision.why().contains("no pep section is configured")); + } + + @Test + void aSessionThatEndedOrIsUntrackedIsDenied() { + RelyingParty party = RelyingParty.create(base()); + SignalsReceiver receiver = new SignalsReceiver("http://127.0.0.1:9", (ids, event) -> { }); + WsFedLogin login = login(); + receiver.track("local", login); + WsFedLogin endedLogin = login(); + endedLogin.sessionNotOnOrAfter = Instant.now().minusSeconds(5); + Decision ended = party.decideSession(receiver, "local", endedLogin, Access.of("read", "order", "42")); + assertEquals(Decision.Kind.DENY, ended.kind()); + assertEquals(403, ended.httpStatus()); + assertTrue(ended.why().contains("session has ended")); + Decision missing = party.decideSession(receiver, "other", login, Access.of("read", "order", "42")); + assertEquals(Decision.Kind.DENY, missing.kind()); + assertTrue(missing.why().contains("no signed-in session")); + assertTrue(receiver.isTracked("local")); + } + + @Test + void pepMustBeAnObject() { + Map config = base(); + config.put("pep", "local"); + WsFedError error = assertThrows(WsFedError.class, () -> RelyingParty.create(config)); + assertTrue(error.getMessage().contains("pep must be an object")); + } + + @Test + void thePepKeyMustDifferFromTheRelyingPartyKey(@TempDir Path dir) throws Exception { + Path key = dir.resolve("same.pem"); + Files.writeString(key, StubIdp.RP_KEY); + Map config = base(); + config.put("pep", Map.of( + "name", "pep-demo", + "assertionKey", key.toString(), + "timeoutMs", 500, + "pollIntervalMs", 60000, + "fallbackPollMs", 60000, + "heartbeatIntervalMs", 60000)); + WsFedError error = assertThrows(WsFedError.class, () -> RelyingParty.create(config)); + assertTrue(error.getMessage().contains("pep.assertionKey is the relying party's privateKey")); + } + + @Test + void aSectionWithoutAModeIsLocalAndUsesTheLibraryDefaults(@TempDir Path dir) throws Exception { + Path key = dir.resolve("pep.pem"); + Files.writeString(key, StubIdp.IDP_KEY); + Map section = new LinkedHashMap<>(); + section.put("name", "pep-demo"); + section.put("assertionKey", key.toString()); + section.put("timeoutMs", 500); + section.put("pollIntervalMs", 60000); + section.put("fallbackPollMs", 60000); + section.put("heartbeatIntervalMs", 60000); + Map config = base(); + config.put("idpCa", StubIdp.IDP_CERT); + config.put("pep", section); + RelyingParty party = RelyingParty.create(config); + try { + Pep pep = party.pep(); + assertEquals(Mode.LOCAL, pep.config().mode); + assertEquals(StubIdp.IDP_ENTITY, pep.config().pdpUrl); + assertEquals(StubIdp.REALM, pep.config().application); + assertTrue(pep.config().assertionKey.endsWith("pep.pem")); + assertTrue(pep.config().tlsCa.contains("BEGIN")); + assertTrue(pep.config().signals); + assertTrue(pep.status().running); + } finally { + if (party.pep() != null) party.pep().stop(); + } + } + + @Test + void theReceiverRefusesATlsClientKeyThatIsThePepKey(@TempDir Path dir) throws Exception { + Path key = dir.resolve("pep.pem"); + Files.writeString(key, StubIdp.IDP_KEY); + Map config = base(); + config.put("pep", Map.of( + "name", "pep-demo", + "mode", "central", + "assertionKey", key.toString(), + "pdpUrl", "http://127.0.0.1:9", + "timeoutMs", 500, + "pollIntervalMs", 60000, + "fallbackPollMs", 60000, + "heartbeatIntervalMs", 60000)); + RelyingParty party = RelyingParty.create(config); + try { + SignalsReceiver.Options options = new SignalsReceiver.Options(); + options.pep = party.pep(); + options.tls = new com.iyasec.wsfed.HttpClient.Tls(); + options.tls.key = StubIdp.IDP_KEY; + options.tls.cert = StubIdp.IDP_CERT; + WsFedError error = assertThrows(WsFedError.class, () -> new SignalsReceiver("http://127.0.0.1:9", (ids, event) -> { }, options)); + assertTrue(error.getMessage().contains("the receiver's TLS client key is pep.assertionKey")); + assertFalse(party.pep().config().mode == Mode.LOCAL); + } finally { + party.pep().stop(); + } + } + + @Test + void localModeFailsClosedThenDecidesInProcess(@TempDir Path dir) throws Exception { + OrdersPdp pdp = null; + RelyingParty party = null; + try { + pdp = OrdersPdp.open(); + Map section = new LinkedHashMap<>(); + section.put("name", "pep-demo"); + section.put("mode", "local"); + section.put("signals", false); + section.put("pollIntervalMs", 1000); + section.put("heartbeatIntervalMs", 60000); + section.put("assertionKey", ecPkcs8(dir.resolve("pep.pem"))); + section.put("pdpUrl", pdp.url); + Map config = base(); + config.put("signals", false); + config.put("pep", section); + party = RelyingParty.create(config); + assertEquals(Decision.Kind.UNAVAILABLE, party.decide(login(), Access.of("read", "order", "42")).kind()); + pdp.policiesUp.set(true); + long deadline = System.nanoTime() + 8_000_000_000L; + while (System.nanoTime() < deadline && !party.pep().status().holdsPolicy) { + Thread.sleep(100); + } + assertTrue(party.pep().status().holdsPolicy, party.pep().status().lastError); + assertTrue(party.decide(login(), Access.of("read", "order", "42")).isPermit()); + assertEquals(Decision.Kind.DENY, party.decide(login(), Access.of("write", "order", "42")).kind()); + assertEquals(0, pdp.evaluations.get()); + assertTrue(pdp.policies.get() > 0); + } finally { + if (party != null && party.pep() != null) party.pep().stop(); + if (pdp != null) pdp.close(); + } + } + + /** An EC P-256 key in PKCS#8 PEM, at an absolute path, distinct from the relying party's key. */ + private static String ecPkcs8(Path path) throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("EC"); + generator.initialize(new ECGenParameterSpec("secp256r1")); + var pair = generator.generateKeyPair(); + String encoded = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(pair.getPrivate().getEncoded()); + Files.writeString(path, "-----BEGIN PRIVATE KEY-----\n" + encoded + "\n-----END PRIVATE KEY-----\n"); + return path.toAbsolutePath().toString(); + } + + private static WsFedLogin login() { + WsFedLogin login = new WsFedLogin(); + login.nameId = "alice"; + login.attributes = new LinkedHashMap<>(); + login.attributeFriendlyNames = new LinkedHashMap<>(); + return login; + } + + private static Map base() { + Map config = new LinkedHashMap<>(); + config.put("realm", StubIdp.REALM); + config.put("replyUrl", StubIdp.REPLY); + config.put("privateKey", StubIdp.RP_KEY); + config.put("certificate", StubIdp.RP_CERT); + config.put("idpMetadata", StubIdp.idpMetadata()); + return config; + } + + /** + * A loopback PDP. The policy pull is 503 until {@link #policiesUp}, then + * one root policy that permits {@code read} and nothing else. + */ + private static final class OrdersPdp implements AutoCloseable { + private static final String READ_ONLY = "read"; + + final String url; + final AtomicBoolean policiesUp = new AtomicBoolean(); + final AtomicInteger policies = new AtomicInteger(); + final AtomicInteger evaluations = new AtomicInteger(); + private final HttpServer server; + private final ExecutorService executor; + + private OrdersPdp(HttpServer server, ExecutorService executor) { + this.server = server; + this.executor = executor; + this.url = "http://127.0.0.1:" + server.getAddress().getPort(); + } + + static OrdersPdp open() throws IOException { + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + ExecutorService executor = Executors.newCachedThreadPool(runnable -> { + Thread thread = new Thread(runnable, "orders-pdp"); + thread.setDaemon(true); + return thread; + }); + server.setExecutor(executor); + OrdersPdp pdp = new OrdersPdp(server, executor); + server.createContext("/", pdp::handle); + server.start(); + return pdp; + } + + @Override + public void close() { + server.stop(0); + executor.shutdownNow(); + } + + private void handle(HttpExchange exchange) { + try { + exchange.getRequestBody().readAllBytes(); + String method = exchange.getRequestMethod(); + String path = exchange.getRequestURI().getPath(); + if (path == null) path = ""; + Reply reply = answer(method, path, exchange.getRequestHeaders().getFirst("Authorization")); + byte[] out = reply.body.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("content-type", "application/json"); + exchange.sendResponseHeaders(reply.status, out.length); + exchange.getResponseBody().write(out); + } catch (IOException err) { + try { + exchange.sendResponseHeaders(500, -1); + } catch (IOException ignored) { + // The exchange is already gone. + } + } finally { + exchange.close(); + } + } + + private Reply answer(String method, String path, String authorization) { + if (!"/oauth2/token".equals(path) && (authorization == null || !authorization.startsWith("DPoP "))) { + return new Reply(401, Json.stringify(Map.of("error", "invalid_token"))); + } + if ("POST".equals(method) && "/oauth2/token".equals(path)) { + return new Reply(200, Json.stringify(Map.of("access_token", "pep-token", "token_type", "DPoP", "expires_in", 300))); + } + if ("POST".equals(method) && "/xacml/pep/register".equals(path)) { + return new Reply(201, Json.stringify(Map.of("registered", true))); + } + if ("POST".equals(method) && "/xacml/pep/heartbeat".equals(path)) { + return new Reply(200, Json.stringify(Map.of("acknowledged", true, "current", true))); + } + if ("GET".equals(method) && "/xacml/pep/authzen-catalogue".equals(path)) { + return new Reply(200, Json.stringify(Map.of( + "syncToken", "c1", + "rows", List.of(Map.of("object", "subject", "property", "acr", "attributeId", "urn:example:acr")), + "settings", Map.of("obligationsProfile", false)))); + } + if ("GET".equals(method) && "/xacml/pep/policies".equals(path)) { + policies.incrementAndGet(); + if (!policiesUp.get()) { + Map down = new LinkedHashMap<>(); + down.put("error", "server_error"); + down.put("error_description", "not now"); + return new Reply(503, Json.stringify(down)); + } + Map policy = new LinkedHashMap<>(); + policy.put("name", "orders"); + policy.put("policyId", "orders"); + policy.put("kind", "Policy"); + policy.put("version", "1.0"); + policy.put("isRoot", Boolean.TRUE); + policy.put("description", ""); + policy.put("combiningAlgId", "urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:deny-unless-permit"); + policy.put("document", READ_ONLY); + Map body = new LinkedHashMap<>(); + body.put("syncToken", "p1"); + body.put("root", "orders"); + body.put("policies", List.of(policy)); + body.put("withheld", List.of()); + body.put("note", ""); + return new Reply(200, Json.stringify(body)); + } + if ("POST".equals(method) && "/admin-api/pep-audit".equals(path)) { + return new Reply(200, Json.stringify(Map.of("acknowledged", 0))); + } + if ("POST".equals(method) && "/access/v1/evaluation".equals(path)) { + evaluations.incrementAndGet(); + return new Reply(200, Json.stringify(Map.of("decision", true))); + } + return new Reply(404, Json.stringify(Map.of("error", "not_found"))); + } + } + + private static final class Reply { + final int status; + final String body; + + Reply(int status, String body) { + this.status = status; + this.body = body; + } + } +} diff --git a/library/src/test/resources/test_authzen.json b/library/src/test/resources/test_authzen.json new file mode 100644 index 0000000..bb694d1 --- /dev/null +++ b/library/src/test/resources/test_authzen.json @@ -0,0 +1,386 @@ +{ + "about": [ + "This library's own AuthZEN table for the embedded Remote PEP (#40). Every case runs through", + "RelyingParty::decide or decide_session with a Login and an Access. Offline, src/test_authzen.rs", + "runs it in local mode against a stub PDP serving these rows and the XACML in", + "src/test_authzen_policies.json (made from the ALFA below by iya-sts's own compiler:", + "python3 scripts/live_authzen.py --compile). Live, scripts/live_authzen.py gives iya-sts the", + "rows and the ALFA, and every case must answer the same in central and local mode, and as", + "expected here. {{application}} is the application the PEP is bound to (the realm)." + ], + "claims": { + "name": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", + "email": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", + "role": "http://schemas.microsoft.com/ws/2008/06/identity/claims/role", + "clearance": "http://schemas.example.org/claims/clearance", + "verified": "http://schemas.example.org/claims/verified", + "hired": "http://schemas.example.org/claims/hired", + "department": "http://schemas.example.org/claims/department", + "nickname": "http://schemas.example.org/claims/nickname" + }, + "catalogue": [ + {"object": "subject", "property": "acr", "attributeId": "urn:example:wsfed:acr"}, + {"object": "subject", "property": "amr", "attributeId": "urn:example:wsfed:amr", "multiplicity": "bag"}, + {"object": "subject", "property": "auth_time", "attributeId": "urn:example:wsfed:auth-time", "category": "access-subject", "dataType": "integer"}, + {"object": "subject", "property": "emailaddress", "attributeId": "urn:example:wsfed:mail"}, + {"object": "subject", "property": "dept", "attributeId": "urn:example:wsfed:dept"}, + {"object": "subject", "property": "role", "attributeId": "urn:example:wsfed:groups", "multiplicity": "bag"}, + {"object": "subject", "property": "clearance", "attributeId": "urn:example:wsfed:clearance", "dataType": "integer"}, + {"object": "subject", "property": "verified", "attributeId": "urn:example:wsfed:verified", "dataType": "boolean"}, + {"object": "subject", "property": "hired", "attributeId": "urn:example:wsfed:hired", "dataType": "dateTime"}, + {"object": "resource", "property": "amount", "attributeId": "urn:example:wsfed:amount", "dataType": "double"}, + {"object": "resource", "property": "pages", "attributeId": "urn:example:wsfed:pages", "dataType": "http://www.w3.org/2001/XMLSchema#integer"}, + {"object": "resource", "property": "confidential", "attributeId": "urn:example:wsfed:confidential", "category": "resource", "dataType": "boolean"}, + {"object": "resource", "property": "owner.country", "attributeId": "urn:example:wsfed:owner-country"}, + {"object": "action", "property": "via", "attributeId": "urn:example:wsfed:via", "category": "action"}, + {"object": "context", "property": "channel", "attributeId": "urn:example:wsfed:channel", "category": "environment"}, + {"object": "context", "property": "device.trust", "attributeId": "urn:example:wsfed:device-trust", "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:environment", "dataType": "double"}, + {"object": "context", "property": "requested_at", "attributeId": "urn:example:wsfed:requested-at", "dataType": "dateTime"} + ], + "directory": [ + {"username": "authzen-ada", "attributes": {"employeeType": "staff"}}, + {"username": "authzen-bo", "attributes": {"employeeType": "contractor"}} + ], + "policies": [ + { + "name": "wsfedauthz-root", + "role": "root", + "phase": "root", + "alfa": [ + "namespace wsfedauthz {", + " attribute act { category = actionCat id = \"urn:oasis:names:tc:xacml:1.0:action:action-id\" type = string }", + " attribute rtype { category = resourceCat id = \"urn:sts:xacml:authzen:resource-type\" type = string }", + " attribute protocol { category = environmentCat id = \"urn:sts:xacml:protocol\" type = string }", + " attribute app { category = environmentCat id = \"urn:sts:xacml:authzen:application\" type = string }", + " attribute acr { category = subjectCat id = \"urn:example:wsfed:acr\" type = string }", + " attribute amr { category = subjectCat id = \"urn:example:wsfed:amr\" type = string }", + " attribute authTime { category = subjectCat id = \"urn:example:wsfed:auth-time\" type = integer }", + " attribute dept { category = subjectCat id = \"urn:example:wsfed:dept\" type = string }", + " attribute groups { category = subjectCat id = \"urn:example:wsfed:groups\" type = string }", + " attribute clearance { category = subjectCat id = \"urn:example:wsfed:clearance\" type = integer }", + " attribute verified { category = subjectCat id = \"urn:example:wsfed:verified\" type = boolean }", + " attribute hired { category = subjectCat id = \"urn:example:wsfed:hired\" type = dateTime }", + " attribute staff { category = subjectCat id = \"employeeType\" type = string }", + " attribute amount { category = resourceCat id = \"urn:example:wsfed:amount\" type = double }", + " attribute pages { category = resourceCat id = \"urn:example:wsfed:pages\" type = integer }", + " attribute confidential { category = resourceCat id = \"urn:example:wsfed:confidential\" type = boolean }", + " attribute ownerCountry { category = resourceCat id = \"urn:example:wsfed:owner-country\" type = string }", + " attribute via { category = actionCat id = \"urn:example:wsfed:via\" type = string }", + " attribute channel { category = environmentCat id = \"urn:example:wsfed:channel\" type = string }", + " attribute deviceTrust { category = environmentCat id = \"urn:example:wsfed:device-trust\" type = double }", + " attribute requestedAt { category = environmentCat id = \"urn:example:wsfed:requested-at\" type = dateTime }", + " attribute caller { category = environmentCat id = \"urn:sts:xacml:authzen:caller\" type = string }", + " policy root {", + " id = \"urn:example:wsfedauthz:root\"", + " apply firstApplicable", + " target clause protocol == \"authzen\"", + " target clause app == \"{{application}}\"", + " target clause rtype == \"document\" or rtype == \"ledger\" or rtype == \"profile\"", + " rule readDocument {", + " permit", + " target clause act == \"read\" and rtype == \"document\"", + " condition integerGreaterThan(stringBagSize(acr), 0)", + " }", + " rule editDocument {", + " permit", + " target clause act == \"edit\" and rtype == \"document\"", + " condition stringIsIn(\"editors\", groups) && anyOf(integerLessThanOrEqual, 2, clearance)", + " }", + " rule signDocument {", + " permit", + " target clause act == \"sign\" and rtype == \"document\"", + " condition anyOf(booleanEqual, true, verified) && anyOf(integerLessThanOrEqual, 1700000000, authTime) && anyOf(dateTimeGreaterThan, dateTime(\"2025-01-01T00:00:00Z\"), hired)", + " }", + " rule stampDocument {", + " permit", + " target clause act == \"stamp\" and rtype == \"document\"", + " condition stringIsIn(\"urn:example:otp\", amr)", + " on permit {", + " obligation \"urn:sts:xacml:obligation:log\" { \"message\" = \"stamped\" }", + " }", + " }", + " rule reviewDocument {", + " permit", + " target clause act == \"review\" and rtype == \"document\"", + " condition stringIsIn(\"finance\", dept)", + " }", + " rule printDocument {", + " permit", + " target clause act == \"print\" and rtype == \"document\"", + " condition anyOf(integerGreaterThanOrEqual, 50, pages) && anyOf(booleanEqual, false, confidential)", + " }", + " rule archiveDocument {", + " permit", + " target clause act == \"archive\" and rtype == \"document\"", + " condition stringIsIn(\"batch\", via)", + " }", + " rule approveLedger {", + " permit", + " target clause act == \"approve\" and rtype == \"ledger\"", + " condition anyOf(doubleGreaterThanOrEqual, 5000.0, amount)", + " on permit {", + " obligation \"urn:sts:xacml:authzen:obligation:step-up\" { \"acr_value\" = \"urn:example:wsfed:mfa\" }", + " }", + " }", + " rule closeLedger {", + " permit", + " target clause act == \"close\" and rtype == \"ledger\"", + " on permit {", + " obligation \"urn:sts:xacml:authzen:obligation:notification\" { \"to\" = \"auditors@example.test\" \"body\" = \"a ledger was closed\" }", + " }", + " }", + " rule exportLedger {", + " permit", + " target clause act == \"export\" and rtype == \"ledger\"", + " target clause channel == \"intranet\"", + " condition anyOf(doubleLessThanOrEqual, 0.8, deviceTrust) && stringIsIn(\"NZ\", ownerCountry) && anyOf(dateTimeLessThanOrEqual, dateTime(\"2026-01-01T00:00:00Z\"), requestedAt)", + " }", + " rule inspectDocument {", + " permit", + " target clause act == \"inspect\" and rtype == \"document\"", + " condition anyOf(stringRegexpMatch, \"uid=pep-wsfed-authzen(-central|-local)?,ou=users,dc=.+\", caller)", + " }", + " rule readProfile {", + " permit", + " target clause act == \"read\" and rtype == \"profile\"", + " target clause staff == \"staff\"", + " }", + " rule otherwise {", + " deny", + " }", + " }", + "}" + ] + }, + { + "name": "wsfedauthz-shared", + "role": "referenced", + "phase": "application", + "alfa": [ + "namespace wsfedshared {", + " attribute act { category = actionCat id = \"urn:oasis:names:tc:xacml:1.0:action:action-id\" type = string }", + " attribute rtype { category = resourceCat id = \"urn:sts:xacml:authzen:resource-type\" type = string }", + " attribute acr { category = subjectCat id = \"urn:example:wsfed:acr\" type = string }", + " policy shared {", + " id = \"urn:example:wsfedauthz:shared\"", + " apply denyUnlessPermit", + " rule readReport {", + " permit", + " target clause act == \"read\" and rtype == \"report\"", + " condition integerGreaterThan(stringBagSize(acr), 0)", + " }", + " }", + "}" + ] + }, + { + "name": "{{application-policy}}", + "role": "application", + "phase": "application", + "references": ["urn:example:wsfedauthz:shared"], + "alfa": [ + "namespace wsfedapp {", + " attribute act { category = actionCat id = \"urn:oasis:names:tc:xacml:1.0:action:action-id\" type = string }", + " attribute stage { category = environmentCat id = \"urn:sts:xacml:fga:stage\" type = string }", + " attribute fgaApp { category = resourceCat id = \"urn:sts:xacml:fga:application\" type = string }", + " policyset application {", + " id = \"urn:example:wsfedauthz:application\"", + " apply firstApplicable", + " target clause stage == \"access\"", + " target clause fgaApp == \"{{application}}\"", + " policy noPurge {", + " id = \"urn:example:wsfedauthz:no-purge\"", + " apply firstApplicable", + " rule purge {", + " deny", + " target clause act == \"purge\"", + " }", + " }", + " }", + "}" + ] + } + ], + "logins": { + "ada": { + "name_id": "authzen-ada", + "acr": "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport", + "amr": ["urn:example:pwd"], + "auth_time": 1767225600, + "claims": { + "name": ["authzen-ada"], + "email": ["ada@example.test"], + "role": ["editors", "readers"], + "clearance": ["3"], + "verified": ["true"], + "hired": ["2023-05-01T09:00:00Z"], + "department": ["finance"] + }, + "friendly": {"department": "dept"} + } + }, + "phases": ["root", "application"], + "cases": [ + {"id": "permit", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "read", "type": "document", "id": "d-1"}, + "expect": "Permit"}, + {"id": "deny", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "shred", "type": "document", "id": "d-1"}, + "expect": "Deny"}, + {"id": "not-applicable", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "read", "type": "invoice", "id": "i-1"}, + "expect": "Deny"}, + {"id": "missing-claim", "phase": "root", "login": {"base": "ada", "acr": null}, + "access": {"action": "read", "type": "document", "id": "d-1"}, + "expect": "Deny"}, + {"id": "undeclared-claim-dropped", "phase": "root", "login": {"base": "ada", "claims": {"nickname": ["ace"]}}, + "access": {"action": "read", "type": "document", "id": "d-1"}, + "expect": "Permit"}, + {"id": "friendly-name-keys-the-claim", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "review", "type": "document", "id": "d-1"}, + "expect": "Permit"}, + {"id": "last-segment-undeclared-dropped", "phase": "root", "login": {"base": "ada", "friendly": {"department": null}}, + "access": {"action": "review", "type": "document", "id": "d-1"}, + "expect": "Deny"}, + {"id": "bag-and-integer-from-text", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "edit", "type": "document", "id": "d-1"}, + "expect": "Permit"}, + {"id": "bag-one-value", "phase": "root", "login": {"base": "ada", "claims": {"role": ["readers"]}}, + "access": {"action": "edit", "type": "document", "id": "d-1"}, + "expect": "Deny"}, + {"id": "integer-too-low", "phase": "root", "login": {"base": "ada", "claims": {"clearance": ["1"]}}, + "access": {"action": "edit", "type": "document", "id": "d-1"}, + "expect": "Deny"}, + {"id": "claim-not-an-integer", "phase": "root", "login": {"base": "ada", "claims": {"clearance": ["three"]}}, + "access": {"action": "edit", "type": "document", "id": "d-1"}, + "expect": "Deny"}, + {"id": "several-values-at-a-single-row", "phase": "root", "login": {"base": "ada", "claims": {"email": ["ada@example.test", "ada@elsewhere.test"]}}, + "access": {"action": "read", "type": "document", "id": "d-1"}, + "expect": "Deny"}, + {"id": "boolean-integer-datetime-claims", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "sign", "type": "document", "id": "d-1"}, + "expect": "Permit"}, + {"id": "boolean-claim-false", "phase": "root", "login": {"base": "ada", "claims": {"verified": ["false"]}}, + "access": {"action": "sign", "type": "document", "id": "d-1"}, + "expect": "Deny"}, + {"id": "boolean-claim-not-a-boolean", "phase": "root", "login": {"base": "ada", "claims": {"verified": ["yes"]}}, + "access": {"action": "sign", "type": "document", "id": "d-1"}, + "expect": "Deny"}, + {"id": "auth-time-too-early", "phase": "root", "login": {"base": "ada", "auth_time": 1600000000}, + "access": {"action": "sign", "type": "document", "id": "d-1"}, + "expect": "Deny"}, + {"id": "datetime-claim-not-a-datetime", "phase": "root", "login": {"base": "ada", "claims": {"hired": ["last spring"]}}, + "access": {"action": "sign", "type": "document", "id": "d-1"}, + "expect": "Deny"}, + {"id": "amr-bag-and-log-obligation", "phase": "root", "login": {"base": "ada", "amr": ["urn:example:pwd", "urn:example:otp"]}, + "access": {"action": "stamp", "type": "document", "id": "d-1"}, + "expect": "Permit", "obligations": []}, + {"id": "amr-without-otp", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "stamp", "type": "document", "id": "d-1"}, + "expect": "Deny"}, + {"id": "typed-resource-properties", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "print", "type": "document", "id": "d-1", "resource": {"pages": 12, "confidential": false}}, + "expect": "Permit"}, + {"id": "integer-from-a-string", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "print", "type": "document", "id": "d-1", "resource": {"pages": "12", "confidential": false}}, + "expect": "Permit"}, + {"id": "boolean-resource-true", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "print", "type": "document", "id": "d-1", "resource": {"pages": 12, "confidential": true}}, + "expect": "Deny"}, + {"id": "fraction-at-an-integer-row", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "print", "type": "document", "id": "d-1", "resource": {"pages": 12.5, "confidential": false}}, + "expect": "Deny"}, + {"id": "text-at-a-boolean-row", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "print", "type": "document", "id": "d-1", "resource": {"pages": 12, "confidential": "no"}}, + "expect": "Deny"}, + {"id": "boolean-at-an-integer-row", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "print", "type": "document", "id": "d-1", "resource": {"pages": true, "confidential": false}}, + "expect": "Deny"}, + {"id": "array-at-a-single-row", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "print", "type": "document", "id": "d-1", "resource": {"pages": [12], "confidential": false}}, + "expect": "Deny"}, + {"id": "undeclared-resource-property", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "read", "type": "document", "id": "d-1", "resource": {"colour": "red"}}, + "expect": "Deny"}, + {"id": "action-property", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "archive", "type": "document", "id": "d-1", "action_properties": {"via": "batch"}}, + "expect": "Permit"}, + {"id": "action-property-other-value", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "archive", "type": "document", "id": "d-1", "action_properties": {"via": "manual"}}, + "expect": "Deny"}, + {"id": "obligation-handed", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "approve", "type": "ledger", "id": "l-1", "resource": {"amount": 1200.5}}, + "expect": "Permit", "obligations": ["step-up"]}, + {"id": "obligation-whole-number-at-a-double-row", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "approve", "type": "ledger", "id": "l-1", "resource": {"amount": 300}}, + "expect": "Permit", "obligations": ["step-up"]}, + {"id": "double-too-large", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "approve", "type": "ledger", "id": "l-1", "resource": {"amount": 9000.25}}, + "expect": "Deny"}, + {"id": "obligation-not-declared", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "close", "type": "ledger", "id": "l-1"}, + "expect": "Deny"}, + {"id": "context-and-nested-path", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "export", "type": "ledger", "id": "l-1", "resource": {"owner": {"country": "NZ"}}, + "context": {"channel": "intranet", "device": {"trust": 0.93}, "requested_at": "2026-03-01T10:00:00Z"}}, + "expect": "Permit"}, + {"id": "context-other-channel", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "export", "type": "ledger", "id": "l-1", "resource": {"owner": {"country": "NZ"}}, + "context": {"channel": "internet", "device": {"trust": 0.93}, "requested_at": "2026-03-01T10:00:00Z"}}, + "expect": "Deny"}, + {"id": "context-datetime-too-early", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "export", "type": "ledger", "id": "l-1", "resource": {"owner": {"country": "NZ"}}, + "context": {"channel": "intranet", "device": {"trust": 0.93}, "requested_at": "2025-06-01T10:00:00Z"}}, + "expect": "Deny"}, + {"id": "nested-undeclared-leaf", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "export", "type": "ledger", "id": "l-1", "resource": {"owner": {"country": "NZ", "city": "Wellington"}}, + "context": {"channel": "intranet", "device": {"trust": 0.93}, "requested_at": "2026-03-01T10:00:00Z"}}, + "expect": "Deny"}, + {"id": "context-null", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "export", "type": "ledger", "id": "l-1", "resource": {"owner": {"country": "NZ"}}, + "context": {"channel": null, "device": {"trust": 0.93}, "requested_at": "2026-03-01T10:00:00Z"}}, + "expect": "Deny"}, + {"id": "context-application-of-another", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "read", "type": "document", "id": "d-1", "context": {"application": "https://elsewhere.example/app"}}, + "expect": "Permit"}, + {"id": "caller-is-the-peps-entry", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "inspect", "type": "document", "id": "d-1"}, + "expect": "Permit"}, + {"id": "directory-attribute", "phase": "root", "login": {"base": "ada"}, + "access": {"action": "read", "type": "profile", "id": "p-1"}, + "expect": "Permit"}, + {"id": "directory-attribute-other-value", "phase": "root", "login": {"base": "ada", "name_id": "authzen-bo", "claims": {"name": ["authzen-bo"]}}, + "access": {"action": "read", "type": "profile", "id": "p-1"}, + "expect": "Deny"}, + {"id": "directory-attribute-nobody", "phase": "root", "login": {"base": "ada", "name_id": "authzen-cy", "claims": {"name": ["authzen-cy"]}}, + "access": {"action": "read", "type": "profile", "id": "p-1"}, + "expect": "Deny"}, + {"id": "subject-id-is-the-name-claim", "phase": "root", "login": {"base": "ada", "name_id": "8c1d-opaque"}, + "access": {"action": "read", "type": "profile", "id": "p-1"}, + "expect": "Permit"}, + {"id": "subject-id-falls-back-to-the-name-id", "phase": "root", "login": {"base": "ada", "claims": {"name": null}}, + "access": {"action": "read", "type": "profile", "id": "p-1"}, + "expect": "Permit"}, + {"id": "session-tracked", "phase": "root", "login": {"base": "ada"}, "session": "tracked", + "access": {"action": "read", "type": "document", "id": "d-1"}, + "expect": "Permit"}, + {"id": "session-ended", "phase": "root", "login": {"base": "ada"}, "session": "ended", + "access": {"action": "read", "type": "document", "id": "d-1"}, + "expect": "Deny"}, + {"id": "session-past-session-not-on-or-after", "phase": "root", "login": {"base": "ada", "session_over": true}, "session": "tracked", + "access": {"action": "read", "type": "document", "id": "d-1"}, + "expect": "Deny"}, + {"id": "fga-reference-permits", "phase": "application", "login": {"base": "ada"}, + "access": {"action": "read", "type": "report", "id": "r-1"}, + "expect": "Permit"}, + {"id": "fga-reference-denies", "phase": "application", "login": {"base": "ada", "acr": null}, + "access": {"action": "read", "type": "report", "id": "r-1"}, + "expect": "Deny"}, + {"id": "fga-inline-deny-first", "phase": "application", "login": {"base": "ada"}, + "access": {"action": "purge", "type": "report", "id": "r-1"}, + "expect": "Deny"}, + {"id": "fga-not-the-root", "phase": "application", "login": {"base": "ada"}, + "access": {"action": "read", "type": "document", "id": "d-1"}, + "expect": "Deny"} + ] +} diff --git a/library/src/test/resources/test_authzen_policies.json b/library/src/test/resources/test_authzen_policies.json new file mode 100644 index 0000000..d1014de --- /dev/null +++ b/library/src/test/resources/test_authzen_policies.json @@ -0,0 +1,23 @@ +{ + "about": "Generated by python3 scripts/live_authzen.py --compile from src/test_authzen.json's ALFA, with iya-sts's xacml_alfa and xacml_xml. Do not edit by hand.", + "policies": { + "wsfedauthz-root": { + "policyId": "urn:example:wsfedauthz:root", + "kind": "Policy", + "version": "1.0", + "document": "\n\n \n \n \n \n authzen\n \n \n \n \n \n \n \n {{application}}\n \n \n \n \n \n \n \n document\n \n \n \n \n \n ledger\n \n \n \n \n \n profile\n \n \n \n \n \n \n \n \n \n \n read\n \n \n \n document\n \n \n \n \n \n \n \n \n \n \n 0\n \n \n \n \n \n \n \n \n edit\n \n \n \n document\n \n \n \n \n \n \n \n \n editors\n \n \n \n \n 2\n \n \n \n \n \n \n \n \n \n \n sign\n \n \n \n document\n \n \n \n \n \n \n \n \n \n true\n \n \n \n \n 1700000000\n \n \n \n \n 2025-01-01T00:00:00Z\n \n \n \n \n \n \n \n \n \n \n stamp\n \n \n \n document\n \n \n \n \n \n \n \n urn:example:otp\n \n \n \n \n \n \n stamped\n \n \n \n \n \n \n \n \n \n review\n \n \n \n document\n \n \n \n \n \n \n \n finance\n \n \n \n \n \n \n \n \n \n print\n \n \n \n document\n \n \n \n \n \n \n \n \n \n 50\n \n \n \n \n false\n \n \n \n \n \n \n \n \n \n \n archive\n \n \n \n document\n \n \n \n \n \n \n \n batch\n \n \n \n \n \n \n \n \n \n approve\n \n \n \n ledger\n \n \n \n \n \n \n \n \n 5000.0\n \n \n \n \n \n \n urn:example:wsfed:mfa\n \n \n \n \n \n \n \n \n \n close\n \n \n \n ledger\n \n \n \n \n \n \n \n \n auditors@example.test\n \n \n a ledger was closed\n \n \n \n \n \n \n \n \n \n export\n \n \n \n ledger\n \n \n \n \n \n \n \n intranet\n \n \n \n \n \n \n \n \n \n 0.8\n \n \n \n NZ\n \n \n \n \n 2026-01-01T00:00:00Z\n \n \n \n \n \n \n \n \n \n \n inspect\n \n \n \n document\n \n \n \n \n \n \n \n \n uid=pep-wsfed-authzen(-central|-local)?,ou=users,dc=.+\n \n \n \n \n \n \n \n \n \n read\n \n \n \n profile\n \n \n \n \n \n \n \n staff\n \n \n \n \n \n \n \n \n \n\n" + }, + "wsfedauthz-shared": { + "policyId": "urn:example:wsfedauthz:shared", + "kind": "Policy", + "version": "1.0", + "document": "\n\n \n \n \n \n \n \n read\n \n \n \n report\n \n \n \n \n \n \n \n \n \n \n 0\n \n \n \n\n" + }, + "{{application-policy}}": { + "policyId": "urn:example:wsfedauthz:application", + "kind": "PolicySet", + "version": "1.0", + "document": "\n\n \n \n \n \n access\n \n \n \n \n \n \n \n {{application}}\n \n \n \n \n \n \n \n \n \n \n \n \n purge\n \n \n \n \n \n \n \n urn:example:wsfedauthz:shared\n\n" + } + } +} diff --git a/scripts/configure_iya_sts.py b/scripts/configure_iya_sts.py index 51e495c..1c91011 100644 --- a/scripts/configure_iya_sts.py +++ b/scripts/configure_iya_sts.py @@ -13,6 +13,29 @@ the shell PORT. An explicit --public-url or PUBLIC_URL replaces the origin and keeps the path. ``signals: false`` skips Shared Signals registration even when an ssf block is present. +--pep [central|local] (local when left out) also sets the demo up with its embedded PEP, as +docs/remote-pep.md's steps 2 to 6 describe: the PEP's service account in remote-peps, a P-256 key +made here with openssl (generated/pep-key.pem beside the configuration, 0600, never printed, kept +out of the image by .dockerignore), issue-pep-credential binding it to the demo's application, the +catalogue row the demo's policy reads (subject.acr), the application's OWN policy, which it then +enforces (never the realm root), and a pep section in the configuration. Run it again to switch +the mode: the account and the key are kept, and the policy is written again with the current +rules while it is this script's own (OWN_POLICY_IDS); a policy under another PolicyId is left +alone. With --pep the test user is given attr1=abc123 (a custom attribute, defined with an +admin:security token), which GET /attribute-protected is decided on. That call is not made on a +run without --pep: an older iya-sts answers 404 and the nightly would stop. + +With an ssf block (and signals not false) the application is let manage its own stream +(oauthAllowedScope ssf.manage, SSF_MANAGE) and the realm issues it a TLS client certificate +(issue-tls-client-certificate, ec-p256, urn:sts:application:), which the receiver presents +at /ssf/* by mutual TLS: generated/ssf-client.key (0600, decrypted with openssl from the one-time +encrypted PEM, never printed) and generated/ssf-client.crt (leaf and chain), named in +ssf.clientKey and ssf.clientCertificate. It is separate from the WS-Federation key pair in the RP +metadata. A certificate the application still holds is kept on a re-run. Once it is in place, what +earlier versions set up for the RP's self-signed certificate is removed by its SHA-256: the +process-wide client-certificate trust anchor (tls/trust/remove) and the copy stored on the +application (applications/remove-certificate). A 403 on either removal does not stop the run. + Every run writes iya-sts's listener CA trust chain (leaf, TLS Issuing CA, Intermediate, Root) to the file idpCa names, through scripts/trust_chain.py. The demo image build copies that file in, so rebuild the image after running this against a different iya-sts. @@ -23,6 +46,7 @@ import json import os import ssl +import subprocess import sys import urllib.error import urllib.parse @@ -33,13 +57,81 @@ MULTIPLE_ACCOUNTS = {"key": "authn.multipleAccounts", "value": True} ROOT = Path(__file__).resolve().parent.parent +# The embedded PEP (--pep). The key's path is relative to the configuration's directory, which is +# also how the pep section names it: this library resolves assertionKey like privateKey. +PEP_MODES = ("central", "local") +# The Shared Signals receiver's own TLS client identity: a certificate the realm issues the +# application (issue-tls-client-certificate: the realm's tls-client Issuing CA, +# urn:sts:application:), which authenticates it at /ssf/* by mutual TLS. It is separate +# from the WS-Federation key pair in the RP metadata. The configuration names it in +# ssf.clientCertificate and ssf.clientKey. +SSF_CLIENT_KEY = "generated/ssf-client.key" +SSF_CLIENT_CERT = "generated/ssf-client.crt" +SSF_CLIENT_LABEL = "wsfed demo SSF receiver" +PEP_NAME = "pep-wsfed-demo" +PEP_KEY = "generated/pep-key.pem" +PEP_KEY_IN_SECTION = "file:generated/pep-key.pem" +PEP_GROUP = "remote-peps" +PEP_EVENT = "urn:iya:sts:secevent:event-type:pep-policies-changed" +ACR_ATTRIBUTE = "urn:example:acr" +# The demo's attribute-protected resource (GET /attribute-protected): the test user carries a custom +# directory attribute, and the demo application's own policy permits the resource only to a person +# whose attr1 is abc123. The PEP asks iya-sts's PIP for it (POST /xacml/pip): it is a directory +# attribute, never a claim of the assertion. +TEST_ATTRIBUTE = "attr1" +TEST_ATTRIBUTE_VALUE = "abc123" +TEST_ATTRIBUTE_ID = "urn:sts:xacml:attribute:" + TEST_ATTRIBUTE +ATTRIBUTE_PROTECTED = "attribute-protected" +# The PolicyIds of the policies this script writes. While the demo application enforces one of +# these, a run writes the current version over it; a policy an administrator wrote under another +# PolicyId is left alone. +OWN_POLICY_IDS = ("urn:example:wsfeddemo-orders",) + sys.path.insert(0, str(Path(__file__).resolve().parent)) from trust_chain import save_trust_chain # noqa: E402 +def orders_policy(namespace: str = "wsfeddemo", read_effect: str = "permit") -> str: + """ALFA for the demo application's own policy, the one its fine-grained authorization decisions + are made with (GET /orders/ is read, anything else write): + - read on an order is `read_effect`; a permit also needs the sign-in's acr (the assertion's + AuthnContextClassRef), which only the catalogue row brings, so a 200 shows the claim arrived; + - read on the attribute-protected resource is permitted when the person's directory attribute + attr1 is abc123, which the PEP asks iya-sts's PIP for; + - everything else is denied.""" + condition = " condition integerGreaterThan(stringBagSize(acr), 0)\n" if read_effect == "permit" else "" + return ( + f"namespace {namespace} {{\n" + ' attribute act { category = actionCat id = "urn:oasis:names:tc:xacml:1.0:action:action-id" type = string }\n' + ' attribute rtype { category = resourceCat id = "urn:sts:xacml:authzen:resource-type" type = string }\n' + f' attribute acr {{ category = subjectCat id = "{ACR_ATTRIBUTE}" type = string }}\n' + f' attribute {TEST_ATTRIBUTE} {{ category = subjectCat id = "{TEST_ATTRIBUTE_ID}" type = string }}\n' + f" policy {namespace}Orders {{\n" + f' id = "urn:example:{namespace}-orders"\n' + " apply firstApplicable\n" + " rule readOrder {\n" + f" {read_effect}\n" + ' target clause act == "read" and rtype == "order"\n' + f"{condition}" + " }\n" + " rule readAttributeProtected {\n" + " permit\n" + ' target clause act == "read"\n' + f' target clause rtype == "{ATTRIBUTE_PROTECTED}"\n' + f' target clause {TEST_ATTRIBUTE} == "{TEST_ATTRIBUTE_VALUE}"\n' + " }\n" + " rule otherwise {\n" + " deny\n" + " }\n" + " }\n" + "}\n" + ) + + def usage() -> str: return """Usage: python scripts/configure_iya_sts.py [--config path] [--idp url] [--public-url url] - [--test-user name | --no-test-user] [--dry-run] + [--test-user name | --no-test-user] + [--pep [central|local]] [--pep-name name] [--dry-run] --config The demo's WS-Federation configuration (default: demo/wsfed.json) --idp iya-sts's base URL; the realm's, e.g. https://host/realm/acme, for a trust realm @@ -48,9 +140,22 @@ def usage() -> str: their paths (default: unset; $PUBLIC_URL). Without it, a loopback realm and reply URL follow the running demo's PORT, then $PORT. Any other host is left as written. - --test-user The test user to create (default: wsfed-demo-user). + --test-user The test user to create (default: wsfed-demo-user). Its password is + $WSFED_DEMO_USER_PASSWORD, or one is generated and written to + generated/.password beside the configuration (mode 0600); only the + path is printed. --no-test-user Do not create a test user. - --dry-run Print what would be done, and send nothing. + --pep [MODE] Also set up the demo's embedded PEP in this mode, local (the default: it caches + the application's policies and decides in process) or central: its service + account, its key (generated/pep-key.pem beside the configuration, 0600, made + with openssl), its binding to the demo's application, the catalogue row and + the application's own policy (enforced), and a pep section written into the + configuration. A bare --pep is local. Run it again with the other mode to + switch; the account and the key are kept, and the script's own policy + (OWN_POLICY_IDS) is written again with the current rules (any other policy + is left alone). attr1 is defined and set only with --pep. + --pep-name The PEP's service account (default: pep-wsfed-demo). + --dry-run Print what would be done, and send nothing. No key and no secret is printed. The management API secret is ADMIN_API_CLIENT_SECRET or STS_ADMIN_API_CLIENT_SECRET.""" @@ -114,6 +219,8 @@ def parse_args(argv: list[str], env: dict | None = None) -> dict: "test_user": "wsfed-demo-user", "dry_run": False, "help": False, + "pep": "", + "pep_name": PEP_NAME, } i = 0 while i < len(argv): @@ -141,6 +248,19 @@ def value() -> str: out["test_user"] = "" elif arg == "--dry-run": out["dry_run"] = True + elif arg == "--pep": + # The mode may be left out: then local, iya-pep's default (the + # PEP caches the application's policies and decides in process). + if i + 1 < len(argv) and not argv[i + 1].startswith("--"): + out["pep"] = value().strip() + else: + out["pep"] = "local" + if out["pep"] not in PEP_MODES: + raise SystemExit(f"--pep must be central or local, not {out['pep']}") + elif arg == "--pep-name": + out["pep_name"] = value().strip() + if not out["pep_name"]: + raise SystemExit("--pep-name is empty") else: raise SystemExit(f"Unknown argument {arg}\n{usage()}") i += 1 @@ -187,6 +307,15 @@ def at(path, what: str) -> str: "rp_metadata": str((Path(key).parent / "rp-metadata.xml").resolve()), "ssf_transmitter": (raw.get("ssf") or {}).get("transmitter"), } + # Where the realm-issued Shared Signals client identity goes: the configuration's own + # ssf.clientKey/clientCertificate paths, else generated/ssf-client.*. An inline PEM or env: + # value is the operator's own and is left alone (None). + ssf = raw.get("ssf") if isinstance(raw.get("ssf"), dict) else {} + for name, member, default in (("ssf_client_key", "clientKey", SSF_CLIENT_KEY), ("ssf_client_cert", "clientCertificate", SSF_CLIENT_CERT)): + try: + files[name] = at(ssf.get(member) or default, "ssf." + member) + except ValueError: + files[name] = None if _signals_off(raw["signals"] if "signals" in raw else None): files["signals"] = False return files @@ -205,20 +334,37 @@ def idp_metadata_url(base: str, realm: str) -> str: return f"{base}/wsfed/metadata/{urllib.parse.quote(realm, safe='')}" -def ssf_calls(files: dict, base: str, certificate_pem: str) -> list[dict]: +def ssf_grants(files: dict, base: str) -> list[dict]: + """What lets the application manage its own stream: the scope it declares and the role that + authorizes it (what a token for it would be issued; a certificate holds the same).""" return [ {"method": "POST", "path": f"{base}/admin-api/applications/add", "why": "declare the Shared Signals write scope", "body": {"application": files["realm"], "attribute": "oauthAllowedScope", "value": "ssf.manage"}}, {"method": "POST", "path": f"{base}/admin-api/roles/add-member", "why": "hold SSF_MANAGE, which authorizes it", "body": {"role": "SSF_MANAGE", "kind": "application", "member": files["realm"]}}, - {"method": "POST", "path": f"{base}/admin-api/tls/trust/add", "why": "trust the RP certificate at the TLS handshake", - "body": {"certificates": certificate_pem}}, - {"method": "POST", "path": f"{base}/admin-api/applications/add-certificate", "why": "store the RP certificate on the application", - "body": {"application": files["realm"], "certificate": certificate_pem}}, ] -def plan_for(files: dict, base: str, test_user: str) -> list[dict]: +def ssf_calls(files: dict, base: str) -> list[dict]: + """Every Shared Signals call, as --dry-run lists them: the grants, the realm-issued TLS client + certificate, and the retirement of what earlier versions of this script set up for the RP's + self-signed certificate (a client-certificate trust anchor and a stored certificate).""" + return ssf_grants(files, base) + [ + {"method": "GET", "path": f"{base}/admin-api/applications?application={urllib.parse.quote(files['realm'], safe='')}", + "why": "is the certificate in ssf.clientCertificate one this application holds? then it is kept", "body": None}, + {"method": "POST", "path": f"{base}/admin-api/applications/issue-tls-client-certificate", + "why": f"otherwise have the realm issue the receiver its TLS client certificate into {files['ssf_client_key']} (0600) and {files['ssf_client_cert']}", + "body": {"application": files["realm"], "password": "", "keyAlg": "ec-p256", "label": SSF_CLIENT_LABEL}}, + {"method": "POST", "path": f"{base}/admin-api/tls/trust/remove", + "why": "then stop trusting the RP's self-signed certificate at the handshake (added by earlier versions)", + "body": {"fingerprint": ""}}, + {"method": "POST", "path": f"{base}/admin-api/applications/remove-certificate", + "why": "and take it off the application's entry (stored by earlier versions)", + "body": {"application": files["realm"], "sha256": ""}}, + ] + + +def plan_for(files: dict, base: str, test_user: str, with_attribute: bool = False) -> list[dict]: calls = [ {"method": "POST", "path": f"{base}/admin-api/applications/create", "why": f"register the relying party {files['realm']}", "body": {"identifier": files["realm"], "name": "wsfed-caep-nodejs demo", "protocols": ["wsfed"], @@ -229,9 +375,17 @@ def plan_for(files: dict, base: str, test_user: str) -> list[dict]: {"method": "GET", "path": idp_metadata_url(base, files["realm"]), "body": None, "why": f"fetch the IdP metadata into {files['idp_metadata']}"}, ] if files.get("signals") is not False and files.get("ssf_transmitter"): - calls[3:3] = ssf_calls(files, base, "") + calls[3:3] = ssf_calls(files, base) if test_user: calls.append({"method": "POST", "path": f"{base}/admin-api/users/create", "why": f"create the test user {test_user}", "body": {"username": test_user}}) + # attr1 is only part of a --pep run. An older iya-sts answers 404 for these paths, and the + # nightly (no --pep) must keep registering against that iya-sts. + if with_attribute: + calls.append({"method": "POST", "path": f"{base}/admin-api/policies/define-person-attribute", + "why": f"define the realm's custom attribute {TEST_ATTRIBUTE} (an admin:security token; unless it is defined)", + "body": {"name": TEST_ATTRIBUTE, "label": "Attribute 1", "syntax": "string", "multiValued": False}}) + calls.append({"method": "POST", "path": f"{base}/admin-api/users/set-attribute", "why": f"give {test_user} {TEST_ATTRIBUTE}={TEST_ATTRIBUTE_VALUE}", + "body": {"user": test_user, "attribute": TEST_ATTRIBUTE, "value": TEST_ATTRIBUTE_VALUE}}) return calls @@ -317,12 +471,323 @@ def _errors_of(body: dict) -> list[str]: return [str(item) for item in (body.get("errors") or [])] -def _generate_keys(config_path: str) -> None: +def pep_plan(files: dict, base: str, name: str, mode: str) -> list[str]: + """What --pep does, for --dry-run. No key and no request leaves here.""" + app = files["realm"] + return [ + f"GET {base}/admin-api/users?user={name} # create the service account unless it exists", + f"POST {base}/admin-api/users/create # {name}: a service account, owned by admin-write, no credential", + f"POST {base}/admin-api/groups/add-member # {name} in {PEP_GROUP}", + f"# make a P-256 key in {PEP_KEY} beside the configuration (0600) unless one is there", + f"POST {base}/admin-api/xacml/issue-pep-credential # its certificate request, bound to {app} (a new key or account)", + f"POST {base}/admin-api/xacml/set-pep-application # or, with both kept, the binding to {app} again", + f"POST {base}/admin-api/xacml/authzen/set-attribute # subject.acr -> {ACR_ATTRIBUTE}", + f"POST {base}/admin-api/applications/fga-create-policy # {app}'s own policy, unless it has one", + f"POST {base}/admin-api/xacml/import-alfa # the demo policy into it (while {app} enforces none, or this script's own)", + f"POST {base}/admin-api/applications/fga-enable # {app} enforces its own policy (the realm root is never touched)", + f"POST {base}/admin-api/applications/add # {PEP_EVENT} in ssfAllowedEvents, only if {app} restricts them", + f"# write \"pep\": {{\"name\": \"{name}\", \"mode\": \"{mode}\", \"assertionKey\": \"{PEP_KEY_IN_SECTION}\"}} into the configuration", + ] + + +def set_test_attribute(api, user: str) -> bool: + """The realm's custom attribute attr1, and the test user's value of it, which GET + /attribute-protected is decided on. + + Defining a custom attribute changes the realm's attribute policy, a Security Administrator's + change: it needs a token carrying admin:security whose subject holds SECURITY_ADMIN. iya-sts + seeds sts-api-client in that role, so the script defines attr1 itself with a token minted for + that call alone. Where an operator has taken the client out of the role the definition is + refused; that is not fatal: the value is tried anyway (attr1 may be defined already), and only + when it cannot be set does the script say what a Security Administrator does instead. Answers + whether the test user now holds the value.""" + try: + defined = api("/policies/define-person-attribute", { + "name": TEST_ATTRIBUTE, "label": "Attribute 1", "syntax": "string", "multiValued": False, + "description": "The demo's attribute-protected resource is permitted when this is abc123.", + }, security=True) + except RuntimeError as err: + # _json raises on 401 and 403; only the Security Administrator refusal is expected here. + if "403" not in str(err) or "security administrator" not in str(err).lower(): + raise + defined = {"status": 403, "body": {"errors": ["Only a Security Administrator may make this change"]}} + words = " ".join(_errors_of(defined["body"])).lower() + not_allowed = defined["status"] == 403 and "security administrator" in words + if not not_allowed and not (defined["status"] == 200 and defined["body"].get("ok") is not False): + if "already" not in words and "exists" not in words: + raise RuntimeError(f"defining the custom attribute {TEST_ATTRIBUTE}: refused ({defined['status']}): {json.dumps(defined['body'])[:400]}") + try: + answered = api("/users/set-attribute", {"user": user, "attribute": TEST_ATTRIBUTE, "value": TEST_ATTRIBUTE_VALUE}) + except RuntimeError as err: + answered = {"status": 0, "body": {"errors": [str(err)]}} + if answered["status"] == 200 and answered["body"].get("ok") is not False: + print(f"{user} has {TEST_ATTRIBUTE}={TEST_ATTRIBUTE_VALUE} (a custom attribute of the realm).") + return True + if not_allowed: + print(f"The custom attribute {TEST_ATTRIBUTE} is not defined, and this credential cannot define it:") + print("sts-api-client no longer holds SECURITY_ADMIN here (iya-sts seeds it there; an operator took it") + print("out). Put it back on Roles, or sign in to the console as a Security Administrator") + print("(the bootstrap administrator is), open Directory > Policies > Attribute policy > Custom") + print(f"attributes, and add {TEST_ATTRIBUTE} (label \"Attribute 1\", syntax string, one value). Then run") + print(f"this script again to give {user} {TEST_ATTRIBUTE}={TEST_ATTRIBUTE_VALUE}.") + else: + print(f"{user} does not have {TEST_ATTRIBUTE} yet: {' '.join(_errors_of(answered['body']))[:300]}") + return False + + +def make_pep_key(key_file: Path) -> None: + """A P-256 key made here with openssl, created 0600. Neither it nor its contents are printed; + only its certificate request (pep_csr) is ever sent.""" + key_file.parent.mkdir(parents=True, exist_ok=True) + old = os.umask(0o077) try: - from wsfed_caep.cli import main as cli_main - except ImportError as err: - raise SystemExit("generate-keys needs the wsfed-caep package on PYTHONPATH (pip install -e .) or the Java CLI") from err - cli_main(["generate-keys", "--config", config_path]) + made = subprocess.run( + ["openssl", "genpkey", "-algorithm", "EC", "-pkeyopt", "ec_paramgen_curve:P-256", "-out", str(key_file)], + check=False, capture_output=True, text=True, + ) + finally: + os.umask(old) + if made.returncode != 0: + raise RuntimeError("openssl could not make the PEP's key (is openssl installed?)") + os.chmod(key_file, 0o600) + + +def pep_csr(key_file: Path, name: str) -> str: + """The key's certificate request: the one thing about the key that leaves this machine.""" + import tempfile + + with tempfile.TemporaryDirectory() as work: + csr = Path(work) / "pep.csr" + asked = subprocess.run( + ["openssl", "req", "-new", "-key", str(key_file), "-subj", f"/CN={name}", "-out", str(csr)], + check=False, capture_output=True, text=True, + ) + if asked.returncode != 0: + raise RuntimeError("openssl could not make the PEP's certificate request from its key") + return csr.read_text(encoding="utf-8") + + +def _ok(answer: dict, what: str, allow: str = "") -> bool: + """An /admin-api act that worked (True), or one refused only because it is already so (False, + `allow` matched in the refusal's words). Anything else raises.""" + body = answer["body"] + if answer["status"] == 200 and body.get("ok") is not False: + return True + words = (" ".join(_errors_of(body)) + " " + str(body.get("why") or "")).lower() + if allow and allow in words: + return False + raise RuntimeError(f"{what}: refused ({answer['status']}): {json.dumps(body)[:400]}") + + +def pem_sha256(pem: str) -> str: + """The SHA-256 of a PEM's first certificate, lowercase hex: how iya-sts names a trust anchor + and a stored certificate.""" + import base64 + import hashlib + body = pem.split("-----BEGIN CERTIFICATE-----", 1)[1].split("-----END CERTIFICATE-----", 1)[0] + return hashlib.sha256(base64.b64decode("".join(body.split()))).hexdigest() + + +def _openssl_x509(cert_path: str, *fields: str) -> dict: + out = subprocess.run( + ["openssl", "x509", "-in", cert_path, "-noout", *fields, "-nameopt", "RFC2253"], + capture_output=True, text=True, check=False, + ) + if out.returncode != 0: + return {} + return {key.strip().lower(): value.strip() for key, _, value in (line.partition("=") for line in out.stdout.splitlines()) if _} + + +def held_serials(get, application: str) -> list[str] | None: + """The serials of the TLS client certificates the realm issued this application and has not + revoked (page.mtls.certificates), uppercase hex without leading zeros; None when this iya-sts + does not say.""" + page = (get(f"/applications?application={urllib.parse.quote(application, safe='')}") or {}).get("page") or {} + mtls = page.get("mtls") + if not isinstance(mtls, dict) or not isinstance(mtls.get("certificates"), list): + return None + return [str(one.get("serialHex") or "").upper().lstrip("0") for one in mtls["certificates"] + if isinstance(one, dict) and str(one.get("state") or "").lower() not in ("revoked", "expired")] + + +def write_ssf_client_section(config_path: str) -> None: + """ssf.clientCertificate and ssf.clientKey, unless the configuration names its own already; + every other member is kept.""" + path = Path(config_path) + raw = json.loads(path.read_text(encoding="utf-8")) + section = raw.get("ssf") if isinstance(raw.get("ssf"), dict) else {} + section.setdefault("clientCertificate", "file:" + SSF_CLIENT_CERT) + section.setdefault("clientKey", "file:" + SSF_CLIENT_KEY) + raw["ssf"] = section + path.write_text(json.dumps(raw, indent=2) + "\n", encoding="utf-8") + + +def issue_ssf_client_certificate(api, get, files: dict, config_path: str) -> bool: + """The Shared Signals receiver's TLS client certificate, issued by the realm to the + application. The key goes to ssf.clientKey (0600, decrypted with openssl from the one-time + encrypted PEM, never printed), the certificate and its chain to ssf.clientCertificate, and + the configuration names both. A certificate this application still holds is kept. Answers + whether one was issued.""" + import secrets + key_path, cert_path = files["ssf_client_key"], files["ssf_client_cert"] + if not key_path or not cert_path: + print("ssf.clientCertificate and ssf.clientKey are given inline or from the environment; they are yours and left as they are.") + return False + if os.path.exists(cert_path) and os.path.exists(key_path): + fields = _openssl_x509(cert_path, "-subject", "-issuer", "-serial") + held = held_serials(get, files["realm"]) + serial = fields.get("serial", "").upper().lstrip("0") + issued_here = bool(fields) and fields.get("subject") != fields.get("issuer") + if issued_here and (serial in held if held is not None else True): + print(f"The Shared Signals client certificate in {cert_path} is one {files['realm']} holds (serial {fields.get('serial')}); kept.") + write_ssf_client_section(config_path) + return False + password = secrets.token_urlsafe(24) + answered = api("/applications/issue-tls-client-certificate", { + "application": files["realm"], "password": password, "keyAlg": "ec-p256", "label": SSF_CLIENT_LABEL, + }) + body = answered["body"] + if not body.get("ok"): + shown = {key: value for key, value in body.items() if key != "files"} + raise RuntimeError(f"issuing {files['realm']} a TLS client certificate for Shared Signals was refused: {json.dumps(shown)[:400]}") + encrypted = ((body.get("files") or {}).get("key") or {}).get("text") or "" + issued = body.get("certificate") or {} + leaf = issued.get("certificatePem") or "" + chain = issued.get("chainPem") or [] + if not encrypted or not leaf: + raise RuntimeError("the issued certificate's answer carried no key or certificate") + Path(key_path).parent.mkdir(parents=True, exist_ok=True) + descriptor = os.open(key_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + os.close(descriptor) + env = dict(os.environ, WSFED_SSF_CLIENT_KEY_PASSWORD=password) + done = subprocess.run( + ["openssl", "pkey", "-passin", "env:WSFED_SSF_CLIENT_KEY_PASSWORD", "-out", key_path], + input=encrypted, capture_output=True, text=True, env=env, check=False, + ) + if done.returncode != 0: + raise RuntimeError(f"the issued key could not be opened: {done.stderr.strip()[:200]}") + os.chmod(key_path, 0o600) + pems = [leaf] + [pem for pem in (chain if isinstance(chain, list) else [chain]) if pem and pem.strip() != leaf.strip()] + Path(cert_path).write_text("".join(pem if pem.endswith("\n") else pem + "\n" for pem in pems), encoding="utf-8") + write_ssf_client_section(config_path) + print(f"Issued {files['realm']} a TLS client certificate from the realm's CA for Shared Signals (serial {issued.get('serialHex', '?')},") + print(f" {issued.get('implicitName') or 'urn:sts:application:' + files['realm']}); wrote {key_path} (0600) and {cert_path},") + print(" and named them in ssf.clientKey and ssf.clientCertificate.") + return True + + +def retire_pinned_certificate(api, files: dict) -> list[str]: + """What earlier versions of this script set up so the RP's self-signed certificate could + authenticate at /ssf/*: a process-wide client-certificate trust anchor and the same + certificate stored on the application's entry. Removed by the certificate's SHA-256, once + the realm-issued certificate is in place; neither being there is no error, and a 403 does + not stop the run. Answers what was removed.""" + if not os.path.exists(files["cert"]): + return [] + fingerprint = pem_sha256(Path(files["cert"]).read_text(encoding="utf-8")) + colon = ":".join(fingerprint[i:i + 2] for i in range(0, 64, 2)).upper() + removed = [] + for path, body, what, absent in ( + ("/tls/trust/remove", {"fingerprint": colon}, "the client-certificate trust anchor", ("holds no anchor", "STS-TLS-0016")), + ("/applications/remove-certificate", {"application": files["realm"], "sha256": fingerprint}, "the certificate stored on the application", ("stores no certificate", "STS-ADMIN-0900")), + ): + try: + reply = api(path, body) + except RuntimeError as err: + print(f"Could not remove {what} for the RP certificate (SHA-256 {colon}): {err}") + continue + words = " ".join(_errors_of(reply["body"])) + " " + str(reply["body"].get("code") or "") + if reply["body"].get("ok"): + removed.append(what) + elif not any(marker.lower() in words.lower() for marker in absent): + print(f"Removing {what} for the RP certificate (SHA-256 {colon}) was refused: {words.strip()[:300]}") + if removed: + print(f"Retired {' and '.join(removed)} for the RP's self-signed certificate (SHA-256 {colon}): the receiver uses the realm-issued one.") + return removed + + +def write_pep_section(config_path: str, name: str, mode: str) -> None: + """The configuration's pep section: the name, the mode and the key; other members of the + section and of the file are kept. assertionKey stays a path; the PEM is not read in.""" + path = Path(config_path) + raw = json.loads(path.read_text(encoding="utf-8")) + section = raw.get("pep") if isinstance(raw.get("pep"), dict) else {} + section.update({"name": name, "mode": mode, "assertionKey": PEP_KEY_IN_SECTION}) + raw["pep"] = section + path.write_text(json.dumps(raw, indent=2) + "\n", encoding="utf-8") + + +def setup_pep(api, get, files: dict, config_path: str, name: str, mode: str) -> None: + """docs/remote-pep.md's steps 2 to 6. Safe to run again: an account, a key and a policy that are + there are kept, and the binding is set again.""" + from urllib.parse import quote + + app = files["realm"] + made_account = get(f"/users?user={quote(name)}").get("known") is not True + if made_account: + _ok(api("/users/create", {"username": name, "invent": False, "credential": "none", "serviceAccount": True, + "owners": ["admin-write"], "attributes": {"cn": name, "displayName": name}}), + f"creating the service account {name}") + print(f"Created the PEP's service account {name}.") + else: + print(f"The PEP's service account {name} already exists.") + _ok(api("/groups/add-member", {"group": PEP_GROUP, "member": name}), f"adding {name} to {PEP_GROUP}", allow="already") + key_file = Path(config_path).resolve().parent / PEP_KEY + made_key = not key_file.exists() + if made_key: + make_pep_key(key_file) + print(f"Generated the PEP's P-256 key in {key_file} (readable by you only).") + if made_key or made_account: + _ok(api("/xacml/issue-pep-credential", {"name": name, "csr": pep_csr(key_file, name), "application": app}), + "certifying the PEP's key") + print(f"Certified the PEP's key and bound {name} to {app}.") + else: + _ok(api("/xacml/set-pep-application", {"name": name, "application": app}), f"binding {name} to {app}") + print(f"Kept the PEP's key; {name} is bound to {app}.") + _ok(api("/xacml/authzen/set-attribute", {"object": "subject", "property": "acr", "attributeId": ACR_ATTRIBUTE}), + "the catalogue row subject.acr") + page_path = f"/applications?application={quote(app, safe='')}" + page = get(page_path).get("page") or {} + fga = page.get("fga") or {} + current_id = (fga.get("policy") or {}).get("policyId") or "" + if fga.get("enforced") is True and current_id not in OWN_POLICY_IDS: + print(f"{app} already enforces a policy of its own ({current_id or 'unnamed'}); it is left as it is.") + elif fga.get("enforced") is True: + policy = (fga.get("policy") or {}).get("name") or fga.get("reference") + _ok(api("/xacml/import-alfa", {"name": policy, "alfa": orders_policy()}), f"writing {policy}") + print(f"{app} enforces this script's policy {policy}; it now holds the current version.") + else: + _ok(api("/applications/fga-create-policy", {"application": app}), f"{app}'s own policy", allow="already") + page = get(page_path).get("page") or {} + fga = page.get("fga") or {} + policy = (fga.get("policy") or {}).get("name") or fga.get("reference") + if not policy: + raise RuntimeError(f"{app}'s page names no policy of its own: {json.dumps(fga)[:300]}") + _ok(api("/xacml/import-alfa", {"name": policy, "alfa": orders_policy()}), f"writing {policy}") + _ok(api("/applications/fga-enable", {"application": app}), f"enforcing {app}'s own policy") + print(f"{app} now enforces its own policy {policy}: read on an order needs an acr; read on {ATTRIBUTE_PROTECTED} needs {TEST_ATTRIBUTE}={TEST_ATTRIBUTE_VALUE}; anything else is denied.") + allowed = (page.get("attributes") or {}).get("ssfAllowedEvents") or [] + if isinstance(allowed, str): + allowed = [allowed] + if allowed and PEP_EVENT not in allowed: + _ok(api("/applications/add", {"application": app, "attribute": "ssfAllowedEvents", "value": PEP_EVENT}), + "letting pep-policies-changed through ssfAllowedEvents", allow="already") + print(f"Added {PEP_EVENT} to {app}'s ssfAllowedEvents.") + write_pep_section(config_path, name, mode) + print(f"Wrote a {mode} pep section into {config_path}.") + + +def _generate_keys(config_path: str) -> None: + """The key pair is made by the Java CLI inside the demo image. This script does not run Java + or Maven on the host, and it does not import a Python package.""" + raise SystemExit( + "No key pair yet. Generate one inside the demo image:\n" + " docker run --rm --user \"$(id -u):$(id -g)\" \\\n" + " -v \"$PWD/demo:/app/demo\" \\\n" + " wsfed-caep-java-demo \\\n" + " java -cp 'wsfed-caep.jar:dependency/*' \\\n" + " com.iyasec.wsfed.Cli generate-keys --config demo/wsfed.json" + ) def main(argv: list[str] | None = None) -> None: @@ -343,10 +808,13 @@ def main(argv: list[str] | None = None) -> None: if files["idp_ca"]: print(f"# would save {origin}'s listener CA trust chain to {files['idp_ca']}") print(f"# would write {files['rp_metadata']}") - for call in plan_for(files, base, args["test_user"]): + for call in plan_for(files, base, args["test_user"], bool(args["pep"])): print(f"{call['method']} {call['path']} # {call['why']}") if call.get("body") is not None: print(json.dumps(call["body"], indent=2)) + if args["pep"]: + for line in pep_plan(files, base, args["pep_name"], args["pep"]): + print(line) return if not Path(files["key"]).exists() and not Path(files["cert"]).exists(): print("No key pair yet; generating one.") @@ -372,9 +840,19 @@ def main(argv: list[str] | None = None) -> None: if not secret: raise SystemExit("neither ADMIN_API_CLIENT_SECRET nor STS_ADMIN_API_CLIENT_SECRET is set, so no /admin-api token can be minted.") token = _mint(origin, base, ca, secret) - - def api(path: str, body: dict) -> dict: - return _json(f"{base}/admin-api{path}", ca, "POST", {"accept": "application/json", "content-type": "application/json", "authorization": f"Bearer {token}"}, json.dumps(body)) + security_token: list[str] = [] + + def api(path: str, body: dict, security: bool = False) -> dict: + # A change iya-sts counts as security (a Directory > Policies policy, such as the realm's + # custom attributes) needs admin:security, held through SECURITY_ADMIN, which iya-sts seeds + # sts-api-client in. That token is minted only when such a call is made, and used for it + # alone; every other call carries admin:read and admin:write. + bearer = token + if security: + if not security_token: + security_token.append(_mint(origin, base, ca, secret, "admin:read admin:security")) + bearer = security_token[0] + return _json(f"{base}/admin-api{path}", ca, "POST", {"accept": "application/json", "content-type": "application/json", "authorization": f"Bearer {bearer}"}, json.dumps(body)) create, add_reply = plan_for(files, base, args["test_user"])[:2] created = api("/applications/create", create["body"]) @@ -391,9 +869,12 @@ def api(path: str, body: dict) -> dict: if not multiple["body"].get("ok"): raise RuntimeError(f"setting authn.multipleAccounts was refused: {json.dumps(multiple['body'])[:300]}") print("authn.multipleAccounts is on: one browser may hold several signed-in people.") + + def get(path: str) -> dict: + return _json(f"{base}/admin-api{path}", ca, headers={"accept": "application/json", "authorization": f"Bearer {token}"})["body"] + if files.get("signals") is not False and files.get("ssf_transmitter"): - certificate = Path(files["cert"]).read_text(encoding="utf-8") - for call in ssf_calls(files, base, certificate): + for call in ssf_grants(files, base): path = call["path"][len(f"{base}/admin-api"):] reply = api(path, call["body"]) errors = " ".join(_errors_of(reply["body"])) @@ -401,7 +882,9 @@ def api(path: str, body: dict) -> dict: raise RuntimeError(f"{call['why']}: refused: {json.dumps(reply['body'])[:400]}") if not reply["body"].get("ok"): print(f" {call['why']}: already so ({errors[:160]})") - print(f"Shared Signals: {files['realm']} holds SSF_MANAGE and authenticates to /ssf/* with its own certificate (mutual TLS).") + issue_ssf_client_certificate(api, get, files, args["config"]) + retire_pinned_certificate(api, files) + print(f"Shared Signals: {files['realm']} holds SSF_MANAGE and authenticates to /ssf/* with the TLS client certificate its realm issued it (mutual TLS).") url = idp_metadata_url(base, files["realm"]) fetched = _request(url, headers={"accept": "application/samlmetadata+xml"}, ca=ca) if fetched["status"] != 200: @@ -411,13 +894,19 @@ def api(path: str, body: dict) -> dict: print(f"Saved the IdP metadata to {files['idp_metadata']}") if args["test_user"]: _ensure_user(base, ca, token, args["test_user"], api, Path(files["key"]).parent) + if args["pep"]: + set_test_attribute(api, args["test_user"]) + if args["pep"]: + setup_pep(api, get, files, args["config"], args["pep_name"], args["pep"]) + print(f"pep: {args['pep_name']}, {args['pep']} (GET /orders/ needs a sign-in with an acr; any other method is denied;") + print(f" GET /{ATTRIBUTE_PROTECTED} needs {TEST_ATTRIBUTE}={TEST_ATTRIBUTE_VALUE} in the directory)") print("Done. Start the demo with: docker compose up --build (the build copies idpCa's trust chain in)") -def _mint(origin: str, base: str, ca: str | None, secret: str) -> str: +def _mint(origin: str, base: str, ca: str | None, secret: str, scope: str = "admin:read admin:write") -> str: import base64 - form = urllib.parse.urlencode({"grant_type": "client_credentials", "scope": "admin:read admin:write", "resource": f"{base}/admin-api"}) + form = urllib.parse.urlencode({"grant_type": "client_credentials", "scope": scope, "resource": f"{base}/admin-api"}) basic = base64.b64encode(f"sts-api-client:{secret}".encode()).decode() reply = _json(f"{base}/oauth2/token", ca, "POST", {"content-type": "application/x-www-form-urlencoded", "authorization": f"Basic {basic}"}, form) if reply["status"] != 200 or not isinstance(reply["body"].get("access_token"), str): diff --git a/scripts/live_iya_sts.py b/scripts/live_iya_sts.py index d2906b3..e3c0482 100755 --- a/scripts/live_iya_sts.py +++ b/scripts/live_iya_sts.py @@ -27,12 +27,27 @@ trust chain where idpCa names it (demo/generated/idp-ca.pem). THEN the demo image is built again, which bakes that chain in (only the demo/ layer changes), and THEN the demo runs from it. Nothing here fetches the CA for the -demo, rewrites idpCa, or mounts a CA into the demo container: only the key -pair and the IdP metadata are mounted, file by file. This script reads the -saved chain for its own HTTPS client. Secrets reach docker and the install -script as -e NAME and through the environment, never on a command line, and -no log line carries a URL from the sign-in (its query and path hold opaque -handles): each request is logged by a fixed label. +demo, rewrites idpCa, or mounts a CA into the demo container. The key pair and +the IdP metadata are mounted, file by file, and so are ssf-client.key and +ssf-client.crt when the install script wrote them. With --pep, pep-key.pem is +mounted the same way. The image's demo/generated is checked to hold only +idp-ca.pem. This script reads the saved chain for its own HTTPS client. +Secrets reach docker and the install script as -e NAME and through the +environment, never on a command line, and no log line carries a URL from the +sign-in (its query and path hold opaque handles): each request is logged by a +fixed label. A generated password goes to a mode-0600 file and only that path +is printed. + +--pep (or LIVE_PEP=1) adds the demo's embedded PEP, and needs an iya-sts with +#2026-#2028 (IYA_STS_IMAGE). The install script runs with --pep central and +writes the pep section; a copy, demo/wsfed.pep-local.json, says local. Central +runs first (GET /orders/42 is 200, POST is 403, GET /attribute-protected is +200 for the test user and 403 for wsfed-demo-user-denied, who still reads the +order). Then the same image runs with WSFED_CONFIG naming the local copy: the +same checks, then the application's own policy is rewritten to deny read, and +within PEP_FLIP_TIMEOUT seconds (30) the GET must be 403 because +pep-policies-changed arrived (the fallback poll stays at 300 s, so via is +event). The result JSON has pep.central and pep.local. IYA_STS_URL, when set, uses an iya-sts that is already running and does not stop it. This script never removes iya-sts-live-main, iya-sts-live-probe, or a @@ -326,6 +341,8 @@ def autopost_form(payload): "/wsfed", "/login", "/live-status", + "/attribute-protected", + "/orders/", ) @@ -614,7 +631,7 @@ def prepare_sts(sts_port): return f"https://127.0.0.1:{sts_port}", name -def configure_demo(context, config, sts_origin, demo_origin, username): +def configure_demo(context, config, sts_origin, demo_origin, username, pep=None): """The install script, on the host, in the build context: it writes idpCa's file.""" env = os.environ.copy() env["PUBLIC_URL"] = demo_origin @@ -625,6 +642,7 @@ def configure_demo(context, config, sts_origin, demo_origin, username): "--idp", sts_origin, "--public-url", demo_origin, "--test-user", username, + *(["--pep", pep] if pep else []), ], cwd=str(context), env=env, @@ -649,6 +667,189 @@ def generate_keys(image, work, config): ) +# The embedded PEP: its names, key path and policy are the install script's. +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from configure_iya_sts import PEP_EVENT, PEP_KEY, TEST_ATTRIBUTE, TEST_ATTRIBUTE_VALUE, orders_policy # noqa: E402 + +PEP_LOCAL_CONFIG = "wsfed.pep-local.json" +DENIED_USER = PROFILE["test_user"] + "-denied" +DENIED_VALUE = "not-" + TEST_ATTRIBUTE_VALUE + + +def create_denied_user(client, sts_origin, secret, password): + """The denied test user, with attr1=not-abc123. Runs after the install script, which defines + the realm's custom attribute attr1. The password is never printed.""" + token = mint_admin(client, sts_origin, secret) + status, made = admin_json(client, sts_origin, token, "POST", "/admin-api/users/create", { + "username": DENIED_USER, "invent": False, "credential": "password", "password": password, "passwordConfirm": password, + "attributes": {"cn": "WS-Fed Demo denied", "givenName": "WS-Fed", "sn": "Denied", "displayName": "WS-Fed Demo denied", + "mail": DENIED_USER + "@wsfed-demo.test"}, + }) + if status != 200 or made.get("ok") is False: + made.pop("password", None) + raise RuntimeError(f"creating {DENIED_USER} answered {status}: {json.dumps(made)[:400]}") + print(f"created the denied test user {DENIED_USER}", flush=True) + admin_ok(client, sts_origin, token, "/admin-api/users/set-attribute", + {"user": DENIED_USER, "attribute": TEST_ATTRIBUTE, "value": DENIED_VALUE}, + f"{DENIED_USER} has {TEST_ATTRIBUTE}={DENIED_VALUE}") + + +def admin_ok(client, sts_origin, token, path, body, what): + status, parsed = admin_json(client, sts_origin, token, "POST", path, body) + if status != 200 or parsed.get("ok") is False: + raise RuntimeError(f"{what}: POST {path} answered {status}: {json.dumps(parsed)[:500]}") + print(f"{what}: {status}", flush=True) + return parsed + + +def local_copy(config, dest): + """The install script wrote a central pep section; a copy says local.""" + raw = json.loads(config.read_text(encoding="utf-8")) + if not isinstance(raw.get("pep"), dict) or raw["pep"].get("mode") != "central": + raise RuntimeError(f"the install script did not write a central pep section: {json.dumps(raw.get('pep'))}") + raw["pep"] = dict(raw["pep"], mode="local") + dest.write_text(json.dumps(raw, indent=2) + "\n", encoding="utf-8") + return raw["realm"] + + +def flip_policy(client, sts_origin, token, application): + """The application's own policy (the install script's) now denies read too. The realm root is + never touched.""" + status, page = admin_json(client, sts_origin, token, "GET", + "/admin-api/applications?application=" + urllib.parse.quote(application, safe="")) + fga = ((page.get("page") or {}).get("fga") or {}) if status == 200 else {} + name = (fga.get("policy") or {}).get("name") or fga.get("reference") + if not name or fga.get("enforced") is not True: + raise RuntimeError(f"the application does not enforce a policy of its own: {json.dumps(fga)[:400]}") + admin_ok(client, sts_origin, token, "/admin-api/xacml/import-alfa", + {"name": name, "alfa": orders_policy("wsfeddemolocked", "deny")}, + "the application's own policy now denies read on an order") + + +def order(driver, method): + return page(driver, method, "/orders/42") + + +def page(driver, method, path): + url = driver.demo_origin + path + status, _headers, payload = driver.client.request(method, url, body=b"" if method == "POST" else None, + headers={"accept": "text/html"}) + print(f"{method} {status} {driver.label(url)}", flush=True) + return status, payload + + +def attribute_checks(driver, allowed): + """GET /attribute-protected: the allowed user (attr1=abc123) 200, the denied user + (attr1=not-abc123) 403 by a Deny, not a failure; the denied user still reads order 42.""" + status, body = page(driver, "GET", "/attribute-protected") + text = body.decode("utf-8", "replace") + if allowed: + ok = status == 200 and "

Allowed

" in text + checks = {"attributeProtectedIs200": ok} + else: + ok = status == 403 and "

Not allowed

" in text and "could not decide" not in text + read_status, read_body = page(driver, "GET", "/orders/42") + checks = {"user": DENIED_USER, "attributeProtectedIs403": ok, "readIs200": read_status == 200} + if read_status != 200: + raise RuntimeError(f"the denied user: GET /orders/42 answered {read_status}: {read_body[:400]!r}") + if not ok: + who = "the allowed user" if allowed else "the denied user" + raise RuntimeError(f"{who}: GET /attribute-protected answered {status}: {text[:600]}") + return checks + + +def pep_checks(driver, mode): + """GET is read (Permit, 200) and POST is write (Deny, 403); GET /attribute-protected is 200.""" + deadline = time.time() + 60 + state = {} + while time.time() < deadline: + state = driver.status().get("pep") or {} + if state.get("registered") and (mode == "central" or state.get("holdsPolicy")): + break + time.sleep(1) + else: + raise RuntimeError(f"the {mode} PEP did not get ready: {json.dumps(state)[:600]}") + read_status, read_body = order(driver, "GET") + write_status, write_body = order(driver, "POST") + checks = {"mode": state.get("mode"), "registered": bool(state.get("registered")), + "readIs200": read_status == 200, "writeIs403": write_status == 403} + if mode == "local": + checks["policyCount"] = state.get("policyCount") + if state.get("mode") != mode or read_status != 200 or write_status != 403: + why = (read_body if read_status != 200 else write_body)[:400].decode("utf-8", "replace") + raise RuntimeError(f"{mode}: GET /orders/42 answered {read_status}, POST {write_status}: {why}; pep {json.dumps(state)[:600]}") + checks.update(attribute_checks(driver, allowed=True)) + return checks + + +def denied_checks(sts_origin, demo_origin, ca_file, password): + """The denied user signs in with a browser of its own (its own cookies) and is checked.""" + denied = Driver(Client(ca_file), sts_origin, demo_origin, DENIED_USER, password) + denied.sign_in() + wait_for(denied, lambda row: row.get("signedIn") is True, "the denied user signed in") + return attribute_checks(denied, allowed=False) + + +def flip_check(driver, client, sts_origin, token, application): + """local: the application's policy moves to deny read, and the PEP hears of it by event.""" + before = driver.status().get("pep") or {} + events_before = sum(1 for item in driver.status().get("events") or [] if item.get("type") == PEP_EVENT) + flipped_at = time.time() + flip_policy(client, sts_origin, token, application) + limit = float(os.environ.get("PEP_FLIP_TIMEOUT") or 30) + status = None + while time.time() - flipped_at < limit: + status, _body = order(driver, "GET") + if status == 403: + break + time.sleep(1) + after = driver.status() + state = after.get("pep") or {} + events = sum(1 for item in after.get("events") or [] if item.get("type") == PEP_EVENT) + result = { + "readIs403AfterFlip": status == 403, + "seconds": round(time.time() - flipped_at, 1), + "eventReceived": events > events_before, + "syncTokenMoved": bool(state.get("syncToken")) and state.get("syncToken") != before.get("syncToken"), + "eventStream": state.get("eventStream"), + } + # The fallback poll is left at its 300 s default, so a change applied + # within the bound, with the event received, came through the event. + result["via"] = "event" if result["eventReceived"] and result["readIs403AfterFlip"] and result["seconds"] < 300 else "poll" + if status != 403 or result["via"] != "event": + raise RuntimeError(f"local: after the flip {json.dumps(result)}; pep {json.dumps(state)[:600]}") + return result + + +def start_demo(image, demo_name, demo_port, demo_origin, mount_args, env=None): + """A fresh demo container. mount_args are already -v source:target:ro pairs.""" + docker_rm(demo_name) + args = ["run", "-d", "--name", demo_name, "--network", "host", *mount_args, + "-e", f"PORT={demo_port}", "-e", f"PUBLIC_URL={demo_origin}"] + for name, value in (env or {}).items(): + args += ["-e", f"{name}={value}"] + docker(*args, image) + deadline = time.time() + 90 + while time.time() < deadline: + try: + conn = http.client.HTTPConnection("127.0.0.1", demo_port, timeout=3) + conn.request("GET", "/healthz") + response = conn.getresponse() + body = response.read() + conn.close() + if response.status == 200 and body == b"ok": + return + except OSError: + pass + time.sleep(1) + logs = subprocess.run(["docker", "logs", demo_name], check=False, text=True, capture_output=True) + if logs.stdout: + print(logs.stdout, flush=True) + if logs.stderr: + print(logs.stderr, file=sys.stderr, flush=True) + raise RuntimeError("the demo /healthz did not answer ok") + + def main(): sts_port = int(os.environ.get("LIVE_STS_PORT") or 18553) demo_port = int(os.environ.get("LIVE_DEMO_PORT") or 18653) @@ -656,8 +857,10 @@ def main(): bound = [demo_port] if sts_given else [sts_port, demo_port] if any(port in FORBIDDEN_PORTS for port in bound) or len(set(bound)) != len(bound): raise SystemExit("LIVE_STS_PORT and LIVE_DEMO_PORT must not bind 3000, 8081, or 18481-18495") + pep = "--pep" in sys.argv[1:] or os.environ.get("LIVE_PEP", "") in ("1", "true", "yes") secret = os.environ.get("ADMIN_API_CLIENT_SECRET") or os.environ.get("STS_ADMIN_API_CLIENT_SECRET") or secrets.token_urlsafe(24) password = os.environ.get(PROFILE["password_env"]) or secrets.token_urlsafe(18) + denied_password = secrets.token_urlsafe(18) if pep else None username = PROFILE["test_user"] # Secrets reach docker and the install script from this environment, never # on a printed command line. @@ -682,10 +885,21 @@ def main(): # which changes only the demo/ layer. docker("build", "-t", image, str(context)) generate_keys(image, demo_dir, config) - configure_demo(context, config, sts_origin, demo_origin, username) + configure_demo(context, config, sts_origin, demo_origin, username, pep="central" if pep else None) ca_file = demo_dir / "generated" / "idp-ca.pem" if "BEGIN CERTIFICATE" not in (ca_file.read_text(encoding="utf-8") if ca_file.exists() else ""): raise RuntimeError(f"the install script did not write {ca_file}") + pep_result = {} + pep_key = demo_dir / PEP_KEY + if pep: + if not pep_key.exists(): + raise RuntimeError("the install script did not make the PEP's key") + written = json.loads(config.read_text(encoding="utf-8")) + if (written.get("pep") or {}).get("mode") != "central": + raise RuntimeError(f"the install script did not write a central pep section: {json.dumps(written.get('pep'))}") + pep_result["application"] = local_copy(config, demo_dir / PEP_LOCAL_CONFIG) + pep_result["name"] = written["pep"]["name"] + create_denied_user(Client(ca_file), sts_origin, secret, denied_password) docker("build", "-t", image, str(context)) baked = docker("run", "--rm", image, "cat", "/app/demo/generated/idp-ca.pem", capture_output=True).stdout if baked != ca_file.read_text(encoding="utf-8"): @@ -695,39 +909,15 @@ def main(): raise RuntimeError(f"the demo image's /app/demo/generated holds {generated}, not only the trust chain") chain_count = baked.count("BEGIN CERTIFICATE") print(f"the demo image carries the {chain_count}-certificate chain at /app/demo/generated/idp-ca.pem, and no key", flush=True) - docker_rm(demo_name) mounts = [] - for name in ("rp.key", "rp.crt", "idp-metadata.xml"): - mounts += ["-v", f"{demo_dir / 'generated' / name}:/app/demo/generated/{name}:ro"] - docker( - "run", "-d", "--name", demo_name, "--network", "host", - *mounts, - "-e", f"PORT={demo_port}", - "-e", f"PUBLIC_URL={demo_origin}", - image, - ) - deadline = time.time() + 90 - healthy = False - while time.time() < deadline: - try: - conn = http.client.HTTPConnection("127.0.0.1", demo_port, timeout=3) - conn.request("GET", "/healthz") - response = conn.getresponse() - body = response.read() - conn.close() - if response.status == 200 and body == b"ok": - healthy = True - break - except OSError: - pass - time.sleep(1) - if not healthy: - logs = subprocess.run(["docker", "logs", demo_name], check=False, text=True, capture_output=True) - if logs.stdout: - print(logs.stdout, flush=True) - if logs.stderr: - print(logs.stderr, file=sys.stderr, flush=True) - raise RuntimeError("the demo /healthz did not answer ok") + for name in ("rp.key", "rp.crt", "idp-metadata.xml", "ssf-client.key", "ssf-client.crt"): + source = demo_dir / "generated" / name + if name.startswith("ssf-client.") and not source.exists(): + continue + mounts += ["-v", f"{source}:/app/demo/generated/{name}:ro"] + if pep: + mounts += ["-v", f"{pep_key}:/app/demo/{PEP_KEY}:ro"] + start_demo(image, demo_name, demo_port, demo_origin, mounts) client = Client(ca_file) driver = Driver(client, sts_origin, demo_origin, username, password) driver.sign_in() @@ -737,6 +927,9 @@ def main(): "a signed-in demo polling its stream", ) print(f"signed in as {signed_in.get('subject')}; {signed_in.get('receiver')}", flush=True) + if pep: + pep_result["central"] = pep_checks(driver, "central") + pep_result["central"]["denied"] = denied_checks(sts_origin, demo_origin, ca_file, denied_password) token = mint_admin(client, sts_origin, secret) session_id = session_id_for(client, sts_origin, token, username) emit(client, sts_origin, token, session_id, "credential-change") @@ -755,14 +948,28 @@ def main(): ), "session-revoked to end the local session", ) - print(json.dumps({ + result = { "ok": True, "subject": signed_in.get("subject"), "idpCaInImage": chain_count, "keysInImage": False, "trustChain": "demo/generated/idp-ca.pem, baked into the demo image", + "ssfClientCertificate": (demo_dir / "generated" / "ssf-client.crt").exists(), "events": finished.get("events"), - }, indent=2)) + } + if pep: + start_demo(image, demo_name, demo_port, demo_origin, mounts, env={"WSFED_CONFIG": "demo/" + PEP_LOCAL_CONFIG}) + local_driver = Driver(Client(ca_file), sts_origin, demo_origin, username, password) + local_driver.sign_in() + wait_for(local_driver, lambda row: row.get("signedIn") is True and "polling" in str(row.get("receiver") or ""), + "a signed-in local-mode demo polling its stream") + local = pep_checks(local_driver, "local") + local["denied"] = denied_checks(sts_origin, demo_origin, ca_file, denied_password) + token = mint_admin(client, sts_origin, secret) + local["policyChange"] = flip_check(local_driver, client, sts_origin, token, pep_result["application"]) + pep_result["local"] = local + result["pep"] = pep_result + print(json.dumps(result, indent=2)) finally: docker_rm(demo_name) if sts_name: