diff --git a/CLAUDE.md b/CLAUDE.md index ca2cb6b..a3ef010 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,6 +1,6 @@ # saml2-sp -Java service provider for SAML 2.0 Web Browser SSO, plus a Shared Signals poll receiver. MIT. `develop` and `main` are one commit. 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. +Java service provider for SAML 2.0 Web Browser SSO, plus a Shared Signals poll receiver and an embedded iya-sts PEP. MIT. This work stays on `develop` until `com.iyasec:iya-pep:0.1.0` is on Maven Central: a merge to `main` publishes the library, and that publish cannot depend on a git pin. `develop` is ahead of `origin/main`. 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. ## Usage @@ -20,7 +20,7 @@ Request bindings are `redirect` and `post`. Response bindings are `post`, `redir docker build --target test . ``` -The `test` stage runs `mvn -B test` in `maven:3.9-eclipse-temurin-26`, with `python3` and `openssl` installed for `TrustChainTest` (the install script's code and `scripts/trust_chain.py` write the four-certificate chain to `idpCa`'s path; 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). GitHub Actions uses that command. Do not run Maven on the host. The demo stage packages with `-DskipTests` in its own Maven image. Signatures and decryption are real (JDK ciphers, Apache Santuario exclusive canonicalization). Nimbus JOSE verifies Shared Signals JWS only. The stub identity provider is in `src/test/java/com/iyasec/saml/StubIdp.java`. The stub tests do not start iya-sts. Java 25. +The `test` stage runs `mvn -B test` in `maven:3.9-eclipse-temurin-26`, with `git`, `ca-certificates`, `python3` and `openssl`. Before the suite it clones `https://github.com/rcbj/iya-pep-java.git` branch `develop` and runs `mvn -B -f /opt/iya-pep/pom.xml -DskipTests install`. One clone; a missing `develop` is not retried. The build stage does the same install before `mvn -B -DskipTests package`, or the demo image cannot compile. `TrustChainTest` uses `python3` and `openssl` (the install script's code and `scripts/trust_chain.py` write the four-certificate chain to `idpCa`'s path; 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). GitHub Actions uses `docker build --target test`. Do not run Maven or javac on the host. Signatures and decryption are real (JDK ciphers, Apache Santuario exclusive canonicalization). Nimbus JOSE verifies Shared Signals JWS only. The stub identity provider is `library/src/test-fixtures/java/com/iyasec/saml/StubIdp.java`. The stub tests do not start iya-sts. Bytecode is 17 (`maven.compiler.release` 17). The test image is `maven:3.9-eclipse-temurin-26`. The demo runtime image stays `eclipse-temurin:25-jre`. `python3 scripts/live_iya_sts.py` signs the demo in to iya-sts and checks credential-change and session-revoked on `GET /live-status`. It builds the demo the way a user does: in a scratch copy of the checkout, the install script first (writing the key pair, the metadata and the `idpCa` chain; its Java CLI runs in the demo image), then the image build, then the run with only `sp.key`, `sp.crt` and `idp-metadata.xml` mounted. No CA mount, no `idpCa` rewrite; it checks the image holds the chain and no key. Secrets go to docker as `-e NAME`; no log line carries a sign-in URL. The nightly workflow runs the unit suite and that script once every 24 hours. Neither binds port 3000, 8081 or 18481-18495; the defaults are 18555 and 18655. Push CI stays the unit suite. @@ -28,14 +28,34 @@ The `test` stage runs `mvn -B test` in `maven:3.9-eclipse-temurin-26`, with `pyt **Plain http (#17).** `Backchannel.send` is the one place every fetch goes through (metadata URL, `ArtifactResolve`, SSF configuration, JWKS, stream and poll). `refusePlainHttpOffLoopback` refuses plain `http://` to a host that is not loopback (`127.0.0.0/8`, `::1`, `localhost`) before connecting, without resolving a name, naming only the scheme and host[:port]; userinfo is never loopback. Redirects are followed by hand (`Redirect.NEVER`, at most five hops, the JDK's method rules, never https to http) so each hop gets the same check. A URL or `Location` holding whitespace or a control character is refused first (`refuseWhitespaceOrControl`), so no two parsers can disagree about the host. No opt-out. `PlainHttpTest` covers it; `http://0.0.0.0:` reaches a 127.0.0.1 listener on Linux, so an empty backlog proves no connection was opened. +## Embedded PEP + +The PEP is `com.iyasec:iya-pep` 0.1.0. This library wires it in `com.iyasec.saml.pep.SamlPep`. A `pep` section is off unless present. There is no feature flag: the dependency is always on the classpath. A missing `mode` is `local`. + +`ServiceProvider.create` and `fromFile` build and start it after `refreshMetadata`. `pdpUrl` defaults to the identity provider's entityID (iya-sts's realm issuer). `application` defaults to `entityId`. `tlsCa` defaults to the `idpCa` PEM. `signals` defaults to whether the receiver runs (an `ssf` object, and `signals` not `false`). A relative `assertionKey` is joined to the configuration directory; the PEP reads the file itself. + +`SamlPep.build` refuses a PEP key whose JWK thumbprint equals `privateKey` or `ssf.clientKey`. `SignalsReceiver.start` refuses again when the TLS client key it will use (`ssf.clientKey`, else the SP `privateKey`) matches `pep.keyThumbprint()`. + +The subject id is `SamlLogin.username()`: `username`, else `preferred_username`, else `urn:oid:0.9.2342.19200300.100.1.1`, else `uid`, else `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name`, else the NameID. `SamlPep.subjectOf` puts every attribute (and FriendlyName, when it is not also a Name) on the subject, plus `acr` from `AuthnContextClassRef`, `amr` from `amr` or the AD FS authnmethodsreferences claim, and `auth_time` as epoch seconds from `AuthnInstant`. + +`decide(SamlLogin, Access)` asks the PEP. With no `pep` section it is Unavailable, `no pep section is configured`. `decideSession(MemorySessionIndex, localId, login, access)` is a Deny, `no signed-in session`, when the index does not hold that id or the session has expired, and it does not ask the engine. `Decision.httpStatus()` is 200 only for a Permit, otherwise 403. + +`SignalsReceiver.pep(Pep)` asks for `Pep.POLICIES_CHANGED_EVENT` when the mode is `local` or `permitCacheMs` is greater than 0 (`SamlPep.wantsEvents`). A reused stream is PATCHed with the types it lacks; a refusal is logged and the receiver still starts. The stream state is `requested` or `excluded` at start and after a good poll, and `down` after a failed poll and on `stop()`. A verified event body goes to `onPolicyEvent`. Add Subject (`iss_sub` and `email`) is queued on `track`; Remove Subject is queued from `untrack` and from an ending event (`forget` / `MemorySessionIndex.take`) when that identifier has no session left. The application's opaque subject `{format: opaque, id: application}` is added at start and never removed. `ssf.addSubjects` defaults to true. Without the transmitter's add and remove endpoints, nothing is sent. A 403 is a warning, stored on `subjectError()`, and not retried. + +`ssf.clientCertificate` and `ssf.clientKey` are both or neither (PEM or a path). The demo presents that pair for mutual TLS, else the SP key pair, plus `idpCa`. + +The demo's `GET /attribute-protected` (`read` / `attribute-protected` / `attr1`) and `/orders/` (`read` on GET, `write` otherwise, type `order`) use `decideSession` and `httpStatus()`. Signed out is 401. A Deny, an Unavailable decision, or a service provider that will not load is 403. `GET /live-status` includes `pep` (from `status()`) when the file has a `pep` section. `GET /pep-status` is that status as JSON and needs a sign-in. The three-tab pane UI, `pep.js`, the AuthZEN case table and the Playwright live UI are not in this library. + +`scripts/configure_iya_sts.py --pep` (`local` when the mode is left out, `--pep-name` default `pep-saml-demo`) creates the `remote-peps` account, a P-256 key at `generated/pep-key.pem` (0600, never printed), `issue-pep-credential` or `set-pep-application`, the catalogue row `subject.acr` → `urn:example:acr`, the application's own policy (never the realm root), and `attr1=abc123` on the test user. It writes the `pep` section and keeps other members. With an `ssf` block it issues the receiver's own TLS client certificate (`issue-tls-client-certificate`) into `generated/ssf-client.key` (0600) and `ssf-client.crt`, and retires an earlier SP trust anchor. It does not add the SP certificate to the process-wide truststore. No secret is printed. + ## Layout -Two Maven modules under an aggregator `pom.xml`, which builds both and is never published; keep its version, the library's and the demo's equal to `VERSION`. `library/` is `com.iyasec:saml2-sp`, the library alone: its `pom.xml` inherits nothing, so it is complete as published, and its jar carries no demo class. `library/src/main/java/com/iyasec/saml/` library, `ssf/` receiver, `library/src/test/java/`; `library/src/test-fixtures` holds `StubIdp`, which both modules' tests compile (build-helper) and no published jar carries. `demo/` is `com.iyasec:saml2-sp-demo`, never published: `com.iyasec.saml.demo.Demo`, and `TrustChainTest` (run from the repository root); its jar and `target/dependency` (the library among them) are what the image runs as `saml2-sp.jar:dependency/*`. Then `scripts/configure_iya_sts.py`, `scripts/live_iya_sts.py`, `Dockerfile`, `docker-compose.yml`, `.github/workflows/nightly.yml`. The image name is `saml2-sp-java-demo`. Compose uses `network_mode: host`, service `saml-demo`, and `ENV PORT=3000` in the image. The health check is `http://127.0.0.1:${PORT}/healthz`. The live script never binds port 3000 or 8081. +Two Maven modules under an aggregator `pom.xml`, which builds both and is never published; keep its version, the library's and the demo's equal to `VERSION`. `library/` is `com.iyasec:saml2-sp`, the library alone: its `pom.xml` inherits nothing, so it is complete as published, and its jar carries no demo class. `library/src/main/java/com/iyasec/saml/` library, `ssf/` receiver, `library/src/test/java/`; `library/src/test-fixtures/java/com/iyasec/saml/StubIdp.java` is the stub identity provider, which both modules' tests compile (build-helper) and no published jar carries. `demo/` is `com.iyasec:saml2-sp-demo`, never published: `com.iyasec.saml.demo.Demo`, and `TrustChainTest` (run from the repository root); its jar and `target/dependency` (the library among them) are what the image runs as `saml2-sp.jar:dependency/*`. Then `scripts/configure_iya_sts.py`, `scripts/live_iya_sts.py`, `Dockerfile`, `docker-compose.yml`, `.github/workflows/nightly.yml`. The image name is `saml2-sp-java-demo`. Compose uses `network_mode: host`, service `saml-demo`, and `ENV PORT=3000` in the image. The health check is `http://127.0.0.1:${PORT}/healthz`. The live script never binds port 3000 or 8081. ## Demo -`docker compose up --build`. `GET /healthz` is `200` with body `ok` and does not load the service provider. Pages: sign-in, `/login` (redirect or POST form), `/saml/acs`, logout of one account or every account, metadata, and per-account Shared Signals events. `GET /live-status` does not need an account id. It is JSON: `signedIn` is true when any local account session exists, plus `subject`, the receiver state, and accepted events (`type` and `jti` only). No tokens. Loopback entityID and assertion-consumer URLs follow `PORT`. Other hosts stay as written. `PUBLIC_URL` or `--public-url` replaces the origin and keeps the path. The default `http://localhost:3000` is not an explicit public URL. `demo/saml.json` uses `file:` placeholders and omits `signals`. Do not commit `demo/generated/`. The live script and the nightly workflow never bind port 3000 or 8081. +`docker compose up --build`. `GET /healthz` is `200` with body `ok` and does not load the service provider. Pages: sign-in, `/login` (redirect or POST form), `/saml/acs`, logout of one account or every account, metadata, per-account Shared Signals events, `/attribute-protected` and `/orders/`. `GET /live-status` does not need an account id. It is JSON: `signedIn` is true when any local account session exists, plus `subject` (the username, else the NameID), the receiver state, and accepted events (`type` and `jti` only). With a `pep` section it also has `pep`. No tokens. Loopback entityID and assertion-consumer URLs follow `PORT`. Other hosts stay as written. `PUBLIC_URL` or `--public-url` replaces the origin and keeps the path. The default `http://localhost:3000` is not an explicit public URL. `demo/saml.json` uses `file:` placeholders and omits `signals`. Do not commit `demo/generated/`. The live script and the nightly workflow never bind port 3000 or 8081. ## Signals -With an `ssf` block and without `"signals": false`, the demo starts one poll receiver on the service provider's certificate (mutual TLS). The first poll runs on a background thread so a down transmitter does not block a page. `scripts/configure_iya_sts.py` registers the SP metadata, pins AES-256-GCM / RSA-OAEP, turns on multiple accounts, and, unless signals are off, grants `ssf.manage`. The container `PORT` wins over the shell `PORT` at registration. The assertion SessionIndex is not the CAEP session id. On `session-revoked`, the event handler ends this demo's one session and says so. `session-revoked` leaves `signedIn` false. +With an `ssf` block and without `"signals": false`, the demo starts one poll receiver. Mutual TLS uses `ssf.clientCertificate` and `ssf.clientKey` when both are set, otherwise the service provider's certificate and key, plus `idpCa`. The first poll runs on a background thread so a down transmitter does not block a page. The receiver and the demo share one `MemorySessionIndex`. `scripts/configure_iya_sts.py` registers the SP metadata, pins AES-256-GCM / RSA-OAEP, turns on multiple accounts, and, unless signals are off, grants `ssf.manage` and has the realm issue the receiver's TLS client certificate. It does not put the SP certificate in the process-wide truststore. The container `PORT` wins over the shell `PORT` at registration. The assertion SessionIndex is not the CAEP session id. On `session-revoked`, the event handler ends this demo's one session and says so. `session-revoked` leaves `signedIn` false. diff --git a/Dockerfile b/Dockerfile index 8afc890..c344374 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,8 +6,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 at the +# pinned commit, which is not on Maven Central yet; one attempt, not retried. +RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates python3 openssl && rm -rf /var/lib/apt/lists/* WORKDIR /src # Both modules: library/ (the published library) and demo/ (the demo, and # TrustChainTest, which runs scripts/ against demo/saml.json). @@ -17,16 +18,28 @@ COPY demo/pom.xml demo/pom.xml COPY demo/src demo/src COPY scripts scripts COPY demo/saml.json demo/saml.json -RUN mvn -B test +RUN git init /opt/iya-pep \ + && git -C /opt/iya-pep remote add origin https://github.com/rcbj/iya-pep-java.git \ + && git -C /opt/iya-pep fetch --depth 1 origin d2bbf5ee73a93ec3b2aeb01219fc093fbb41c645 \ + && git -C /opt/iya-pep checkout --detach FETCH_HEAD \ + && mvn -B -f /opt/iya-pep/pom.xml -DskipTests install \ + && 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 demo module copies its runtime dependencies, the library among them, to demo/target/dependency. -RUN mvn -B -DskipTests package +# iya-pep is installed from the same pinned commit as the test stage. +RUN git init /opt/iya-pep \ + && git -C /opt/iya-pep remote add origin https://github.com/rcbj/iya-pep-java.git \ + && git -C /opt/iya-pep fetch --depth 1 origin d2bbf5ee73a93ec3b2aeb01219fc093fbb41c645 \ + && git -C /opt/iya-pep checkout --detach FETCH_HEAD \ + && mvn -B -f /opt/iya-pep/pom.xml -DskipTests install \ + && mvn -B -DskipTests package FROM eclipse-temurin:25-jre WORKDIR /app # The demo's jar under the name the image has always run, and beside it every diff --git a/README.md b/README.md index 4e47d18..7843f1c 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Server-side SAML 2.0 service provider for Java. It sends a signed `AuthnRequest` on HTTP-Redirect or HTTP-POST, accepts a `Response` on HTTP-POST, HTTP-Redirect, or HTTP-Artifact, verifies XML signatures, decrypts encrypted assertions, and can poll a Shared Signals transmitter for CAEP and RISC events. -License: MIT. `develop` and `main` are one commit. 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. +License: MIT. This line of work stays on `develop` until `com.iyasec:iya-pep:0.1.0` is on Maven Central. A merge to `main` publishes the library, and that publish cannot depend on a git pin. `develop` is ahead of `origin/main`. 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. ## Usage @@ -42,6 +42,74 @@ receiver.start(); The receiver lives in `com.iyasec.saml.ssf`. It discovers the transmitter, keeps one poll stream (`urn:ietf:rfc:8936`), and verifies each Security Event Token against the published JWKS. By default a session ends on `session-revoked`, `account-disabled`, `account-purged`, `credential-compromise`, and `sessions-revoked`. +With `ssf.clientCertificate` and `ssf.clientKey` (both, or neither), the receiver presents that pair. Without them it presents the service provider's key pair. `ssf.addSubjects` defaults to true: each `track` queues Add Subject, and the last local session for a person queues Remove Subject. + +## Embedded PEP + +Ask iya-sts whether a signed-in person may act on a resource. The PEP is [`com.iyasec:iya-pep`](https://github.com/rcbj/iya-pep-java) 0.1.0 (iya-sts [#1206](https://github.com/rcbj/iya-sts/issues/1206)). **[docs/remote-pep.md](docs/remote-pep.md)** is the guide: setting up iya-sts, `central` or `local`, configuration, obligations, policy-change events and troubleshooting. + +```json +"pep": { "name": "pep-orders", "mode": "local", "assertionKey": "pep-key.pem" } +``` + +```java +Decision decision = sp.decideSession(receiver.sessionIndex(), localId, login, Access.of("read", "order", "42")); +int status = decision.httpStatus(); // 200 for a Permit, 403 for anything else +``` + +The section is off unless present. There is no separate build flag. A missing `mode` is `local`. `pdpUrl` defaults to the identity provider's entityID and `application` to `entityId`. The subject's id is `SamlLogin.username()`, else the NameID. `decideSession` denies an untracked or expired session without asking the engine. `SignalsReceiver.pep` asks the stream for `pep-policies-changed` when the PEP wants events, and tells the PEP whether the stream is up. The demo protects `GET /attribute-protected` and `/orders/` with `httpStatus()`: 401 signed out, 403 on a Deny or any failure. + +```bash +docker compose build +docker run --rm --network host --user "$(id -u):$(id -g)" \ + -v "$PWD/demo:/app/demo" -e ADMIN_API_CLIENT_SECRET -e IYA_STS_URL \ + saml2-sp-java-demo python3 scripts/configure_iya_sts.py --pep local +docker compose up --build +``` + +`--pep` with no mode is `local`. `--pep central` switches the mode and keeps the account, the key (`demo/generated/pep-key.pem`, 0600) and the application's own policy. The realm root is not changed. `GET /orders/42` is allowed when the sign-in carried an AuthnContextClassRef. Any other method on that order is denied. `GET /attribute-protected` is allowed when the directory attribute `attr1` is `abc123`. + +## Credentials + +Every key, certificate and secret the demo and its install script use, with who makes each one, where it is kept, and what it proves. No value appears here. Paths under `demo/generated/` are relative to the checkout. That directory is never committed, and only `idp-ca.pem` from it goes into the demo image. + +### The application's own credentials + +| Credential | Type | Made or issued by | Where it lives | Used for | How iya-sts learns of it | Rotation | +|---|---|---|---|---|---|---| +| SP key pair | RSA-3072 key (the CLI default), self-signed certificate valid 1095 days, subject `CN=` the entity host or `saml2-sp service provider` | `com.iyasec.saml.Cli generate-keys`, run by the install script inside the demo image | `privateKey` → `demo/generated/sp.key` (0600), `certificate` → `demo/generated/sp.crt` | Signing the AuthnRequest and the `ArtifactResolve`; decrypting the encrypted assertion (AES-256-GCM, the key wrapped with RSA-OAEP) | In the SP metadata the install script registers | Replace the files with `--force` and register the new metadata before the next sign-in. This script has no `--new-sp-keys` | +| Shared Signals client certificate | EC P-256 key and a certificate from the realm's TLS client Issuing CA, named `urn:sts:application:` | iya-sts: `/admin-api/applications/issue-tls-client-certificate` (`keyAlg` `ec-p256`). The key comes back once, encrypted, and the script opens it with `openssl pkey -passin env:` | `ssf.clientKey` → `demo/generated/ssf-client.key` (0600, never printed), `ssf.clientCertificate` → `demo/generated/ssf-client.crt` | Mutual TLS for the receiver's calls to `/ssf/*` | iya-sts issued it and lists it on the application. Nothing is added to the process-wide client-certificate truststore | Kept while the application's page lists it valid. Otherwise the next run issues a new one | +| Fallback for Shared Signals | The SP key pair | — | — | Without `ssf.clientCertificate` and `ssf.clientKey`, the demo presents the SP key pair | The install script removes an anchor and stored copy an earlier run added | — | +| Test user's password | Password | `$SAML_DEMO_USER_PASSWORD`, or iya-sts generates one when the user is created | Generated: beside the key pair, `demo/generated/.password` (created 0600). Only the path is printed | Signing in to the demo as `saml-demo-user` | iya-sts holds the user | Set `SAML_DEMO_USER_PASSWORD` and run the script again | +| Demo session key | Random bytes, or `$SESSION_SECRET` | The demo, at start | In memory | HMAC on the demo's `aset` cookie | iya-sts never sees it | A restart makes a new one, unless `SESSION_SECRET` is set | + +### The embedded PEP's credentials + +| Credential | Type | Made or issued by | Where it lives | Used for | Rotation | +|---|---|---|---|---|---| +| Service account `pep-saml-demo` (`--pep-name`) | A directory account with no password, owned by `admin-write`, in the group `remote-peps` | The install script (`/admin-api/users/create` when unknown; `/admin-api/groups/add-member`) | iya-sts | The PEP's identity. Its key is bound to it, and through it to the application (the entityID) | Delete it in iya-sts and run the script again | +| PEP key | EC P-256 key | `openssl genpkey` in the install script, only when the file is missing | `pep.assertionKey` → `demo/generated/pep-key.pem` (0600, never printed, kept out of the image) | The PEP's RFC 7523 self-assertion and each DPoP proof | Certified by `/admin-api/xacml/issue-pep-credential` when the key or the account is new. Otherwise `/admin-api/xacml/set-pep-application` binds the kept key. Delete the file and run the script again for a new key | + +`ServiceProvider` refuses a PEP key whose JWK thumbprint equals `privateKey` or `ssf.clientKey`. `SignalsReceiver.start` refuses when the TLS client key it presents is that same key. + +### Install-time only + +| Credential | Type | Where it lives | Used for | +|---|---|---|---| +| Management client secret | `ADMIN_API_CLIENT_SECRET` or `STS_ADMIN_API_CLIENT_SECRET` | The environment, never a file this script writes | Minting the token for `/admin-api`. Defining `attr1` uses a separate token with `admin:read admin:security` for that call alone | +| One-time key password | Random, for the issued SSF client key and not stored | Passed to `openssl` through the environment | Opening the encrypted PKCS#8 once. It is never printed | + +### Trust material + +| Material | Where it lives | Used for | +|---|---|---| +| iya-sts listener CA chain | `idpCa` → `demo/generated/idp-ca.pem` (the one generated file the image copies in) | TLS to iya-sts for metadata, artifact resolution, Shared Signals and the PEP (`tlsCa` defaults to this PEM) | +| Transmitter JWKS | Fetched, not stored | Verifying Security Event Tokens, including `pep-policies-changed` | + +### Development and product iya-sts + +The PEP's credential is the same in both: a certified key and a DPoP-bound token. The receiver's realm-issued TLS client certificate is checked the same way. The install script's `--idp` is the realm URL (`https://host/realm/` or the default realm). + ## 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 `SamlError`, it still throws `SamlError`, and the caught exception is the cause. @@ -63,7 +131,7 @@ The suite includes `TrustChainTest`, which runs the install script's trust-chain ## Layout - `library/` the library, `com.iyasec:saml2-sp`, nothing else in its jar: `library/src/main/java/com/iyasec/saml/` (`ServiceProvider`, metadata, bindings, signatures, encryption, the replay cache, `ssf/`) -- `library/src/test/java/com/iyasec/saml/` JUnit 5; `library/src/test-fixtures` the stub identity provider, shared with the demo's tests +- `library/src/test/java/com/iyasec/saml/` JUnit 5; `library/src/test-fixtures/java/com/iyasec/saml/StubIdp.java` the stub identity provider, shared with the demo's tests - `demo/` the demo module, never published: `demo/src/main/java/com/iyasec/saml/demo/Demo.java` - `scripts/configure_iya_sts.py` registers that demo with iya-sts and writes `idpCa` - `scripts/trust_chain.py` fetches and saves the iya-sts listener CA trust chain @@ -77,7 +145,7 @@ The suite includes `TrustChainTest`, which runs the install script's trust-chain docker compose up --build ``` -`PORT` defaults to 3000. `GET /healthz` returns `200` and the body `ok` even when the identity provider metadata is not on disk yet. The home page offers sign-in. `/login` answers a signed AuthnRequest (redirect, or a POST form). `/saml/acs` is the assertion consumer. `/saml/metadata` is this service provider's metadata. `GET /live-status` does not need an account id. It is JSON: `signedIn` (true when any local account session exists), `subject`, the receiver state, and the Shared Signals events this process has accepted (`type` and `jti` only). No tokens. If the assertion SessionIndex is not the CAEP session id, the event handler ends this demo's one session and says so. `session-revoked` leaves `signedIn` false. A loopback `entityId` and assertion consumer URL follow `PORT`. Any other host stays as written. `PUBLIC_URL` or `--public-url` replaces the origin and keeps the path; the default `http://localhost:3000` is not treated as an explicit public URL. The live script never binds port 3000 or 8081. +`PORT` defaults to 3000. `GET /healthz` returns `200` and the body `ok` even when the identity provider metadata is not on disk yet. The home page offers sign-in. `/login` answers a signed AuthnRequest (redirect, or a POST form). `/saml/acs` is the assertion consumer. `/saml/metadata` is this service provider's metadata. Once signed in, the page links `/attribute-protected` and `/orders/42`. Those pages are 401 without a sign-in and otherwise the PEP's `httpStatus()` (200 only for a Permit, 403 on a Deny or any failure). `GET /live-status` does not need an account id. It is JSON: `signedIn` (true when any local account session exists), `subject`, the receiver state, and the Shared Signals events this process has accepted (`type` and `jti` only). A `pep` section adds `pep`, the PEP's status. `GET /pep-status` is that status as JSON and needs a sign-in. No tokens. If the assertion SessionIndex is not the CAEP session id, the event handler ends this demo's one session and says so. `session-revoked` leaves `signedIn` false. A loopback `entityId` and assertion consumer URL follow `PORT`. Any other host stays as written. `PUBLIC_URL` or `--public-url` replaces the origin and keeps the path; the default `http://localhost:3000` is not treated as an explicit public URL. The live script never binds port 3000 or 8081. `demo/saml.json` points at `file:` paths under `demo/generated/` and does not contain a key. Generate the key pair and, against a running iya-sts, register the application with: diff --git a/demo/src/main/java/com/iyasec/saml/demo/Demo.java b/demo/src/main/java/com/iyasec/saml/demo/Demo.java index f15aa04..1b257f8 100644 --- a/demo/src/main/java/com/iyasec/saml/demo/Demo.java +++ b/demo/src/main/java/com/iyasec/saml/demo/Demo.java @@ -2,12 +2,16 @@ // SPDX-License-Identifier: MIT package com.iyasec.saml.demo; +import com.iyasec.pep.Access; +import com.iyasec.pep.Decision; import com.iyasec.saml.Caught; import com.iyasec.saml.Json; import com.iyasec.saml.SamlError; import com.iyasec.saml.SamlLogin; import com.iyasec.saml.ServiceProvider; +import com.iyasec.saml.pep.SamlPep; import com.iyasec.saml.ssf.Events; +import com.iyasec.saml.ssf.MemorySessionIndex; import com.iyasec.saml.ssf.SignalEvent; import com.iyasec.saml.ssf.SignalsReceiver; import com.sun.net.httpserver.Headers; @@ -194,6 +198,7 @@ static final class App { final Map> listeners = new LinkedHashMap<>(); final Map verificationsAsked = new LinkedHashMap<>(); ServiceProvider provider; + final MemorySessionIndex tracked = new MemorySessionIndex(); volatile SignalsReceiver receiver; volatile String receiverState; final List> liveEvents = new CopyOnWriteArrayList<>(); @@ -390,7 +395,7 @@ void route(HttpExchange exchange, boolean[] started) throws Exception { } if (here != null && "/logout".equals(sub) && "POST".equals(method)) { synchronized (state) { endSession(here.sid); } - if (receiver != null) receiver.untrack(here.sid); + dropTracked(here.sid); tell(here.sid, "signed-out", Map.of()); redirect(exchange, "/", 303, null, started); return; @@ -399,15 +404,99 @@ void route(HttpExchange exchange, boolean[] started) throws Exception { List all = accountsOfSet(cookies(exchange).get("aset")); for (Held item : all) { synchronized (state) { endSession(item.sid); } - if (receiver != null) receiver.untrack(item.sid); + dropTracked(item.sid); tell(item.sid, "signed-out", Map.of()); } redirect(exchange, "/", 303, List.of(cookie("aset", "", "/", 0, "Lax")), started); return; } + if ("/attribute-protected".equals(path) || orderId(path) != null) { + protect(exchange, path, method, started); + return; + } + if ("/pep-status".equals(path) && "GET".equals(method)) { + pepStatus(exchange, started); + return; + } send(exchange, 404, page("Not found", "

Not found

").getBytes(StandardCharsets.UTF_8), null, null, started); } + /** The order id of {@code /orders/}, or null when the path is not one order. */ + String orderId(String path) { + if (path == null || !path.startsWith("/orders/")) return null; + String id = path.substring("/orders/".length()); + if (id.isEmpty() || id.contains("/")) return null; + return id; + } + + /** + * A page the embedded PEP protects. No sign-in is 401. A Deny, an + * Unavailable decision, or no service provider to ask is 403. + */ + void protect(HttpExchange exchange, String path, String method, boolean[] started) throws Exception { + Held held = current(exchange); + if (held == null) { + send(exchange, 401, page("Sign in", "

Sign in first

Sign in

").getBytes(StandardCharsets.UTF_8), null, null, started); + return; + } + ServiceProvider sp; + try { + sp = serviceProvider(); + } catch (Exception err) { + Caught.error(err); + send(exchange, 403, page("Forbidden", "

Not allowed

No decision could be asked for: the service provider is not configured: " + + esc(messageOf(err)) + "

").getBytes(StandardCharsets.UTF_8), null, null, started); + return; + } + boolean attribute = "/attribute-protected".equals(path); + String action = attribute || "GET".equals(method) ? "read" : "write"; + String type = attribute ? "attribute-protected" : "order"; + String id = attribute ? "attr1" : orderId(path); + Decision decision = sp.decideSession(tracked, held.sid, held.session.login, Access.of(action, type, id)); + String note = "

The demo application's policy permits read on attribute-protected when your directory attribute attr1 is abc123. The PEP asked iya-sts's PIP for it: it is not in your SAML assertion.

"; + String html; + if (decision.isPermit()) { + html = attribute + ? page("Attribute-protected", "

Allowed

The PEP permitted it: your attr1 is abc123.

" + note) + : page("Order", "

Order " + esc(id) + "

The PEP permitted " + esc(action) + ".

"); + } else if (decision.kind() == Decision.Kind.DENY) { + html = page("Forbidden", "

Not allowed

The PEP denied it: " + esc(decision.why()) + "

" + (attribute ? note : "")); + } else { + html = page("Forbidden", "

No decision

The PEP could not decide: " + esc(decision.why()) + "

" + (attribute ? note : "")); + } + send(exchange, decision.httpStatus(), html.getBytes(StandardCharsets.UTF_8), null, null, started); + } + + void pepStatus(HttpExchange exchange, boolean[] started) throws Exception { + if (current(exchange) == null) { + send(exchange, 401, Json.stringify(Map.of("signedIn", false)).getBytes(StandardCharsets.UTF_8), + Map.of("content-type", "application/json", "cache-control", "no-store"), null, started); + return; + } + Object pep = null; + try { + ServiceProvider sp = serviceProvider(); + if (sp.pep() != null) pep = SamlPep.statusMap(sp.pep()); + } catch (Exception err) { + Caught.warn(err); + pep = Map.of("error", "the service provider is not configured"); + } + Map body = new LinkedHashMap<>(); + body.put("pep", pep); + send(exchange, 200, Json.stringify(body).getBytes(StandardCharsets.UTF_8), + Map.of("content-type", "application/json", "cache-control", "no-store"), null, started); + } + + Held current(HttpExchange exchange) { + List accounts = accountsOfSet(cookies(exchange).get("aset")); + return accounts.isEmpty() ? null : accounts.get(0); + } + + void dropTracked(String sid) { + if (receiver != null) receiver.untrack(sid); + else tracked.remove(sid); + } + void liveStatus(HttpExchange exchange, boolean[] started) throws IOException { boolean signedIn = false; String subject = null; @@ -416,7 +505,8 @@ void liveStatus(HttpExchange exchange, boolean[] started) throws IOException { for (Session session : sessions.values()) { if (session.expires <= now) continue; signedIn = true; - String name = session.login.nameId; + String name = session.login.username(); + if (name == null || name.isEmpty()) name = session.login.nameId; if (subject == null && name != null && !name.isEmpty()) subject = name; } } @@ -425,6 +515,15 @@ void liveStatus(HttpExchange exchange, boolean[] started) throws IOException { body.put("subject", subject); body.put("receiver", receiverState == null ? "" : receiverState); body.put("events", new ArrayList<>(liveEvents)); + if (file.get("pep") instanceof Map) { + try { + ServiceProvider sp = serviceProvider(); + body.put("pep", sp.pep() == null ? null : SamlPep.statusMap(sp.pep())); + } catch (Exception err) { + Caught.warn(err); + body.put("pep", Map.of("error", "the service provider is not configured")); + } + } send(exchange, 200, Json.stringify(body).getBytes(StandardCharsets.UTF_8), Map.of("content-type", "application/json"), null, started); } @@ -550,7 +649,7 @@ void acs(HttpExchange exchange, String path, String rawQuery, boolean[] started) String account = existing != null ? existing.session.account : b64(random(9)); if (existing != null) { synchronized (state) { endSession(existing.sid); } - if (receiver != null) receiver.untrack(existing.sid); + dropTracked(existing.sid); tell(existing.sid, "replaced", Map.of()); } String setId = b64(random(32)); @@ -566,6 +665,7 @@ void acs(HttpExchange exchange, String path, String rawQuery, boolean[] started) sessions.put(sid, new Session(login, account, until, setId)); } if (receiver != null) receiver.track(sid, login, Instant.ofEpochMilli(until)); + else tracked.add(MemorySessionIndex.trackedFrom(sid, login, null, Instant.ofEpochMilli(until))); System.out.println("signed in " + login.nameId + " by " + login.binding + " (assertion " + login.assertionId + "); " + order.size() + " account(s) in this browser"); long longest = until; synchronized (state) { @@ -630,8 +730,13 @@ void startReceiver(ServiceProvider sp) { if (ssf == null || receiver != null) return; Map tls = new LinkedHashMap<>(); if (sp.config.idpCa != null) tls.put("ca", sp.config.idpCa); - tls.put("cert", sp.config.certificatePem); - tls.put("key", sp.config.privateKeyPem); + if (sp.config.ssfClientKey != null) { + tls.put("cert", sp.config.ssfClientCertificate); + tls.put("key", sp.config.ssfClientKey); + } else { + tls.put("cert", sp.config.certificatePem); + tls.put("key", sp.config.privateKeyPem); + } int interval = 5000; if (ssf.get("pollIntervalMs") instanceof Number number && number.intValue() != 0) interval = number.intValue(); SignalsReceiver built = new SignalsReceiver(String.valueOf(ssf.get("transmitter")), (ids, event) -> { @@ -649,7 +754,9 @@ void startReceiver(ServiceProvider sp) { tell(sid, "signed-out", data); } System.out.println("ssf: " + shortType(event.type) + " ended " + ids.size() + " local session(s)"); - }).tls(tls).description("saml2-sp demo (" + sp.config.entityId + ")").pollIntervalMs(interval); + }).tls(tls).sessionIndex(tracked).addSubjects(SignalsReceiver.addSubjectsSetting(ssf)) + .description("saml2-sp demo (" + sp.config.entityId + ")").pollIntervalMs(interval); + if (sp.pep() != null) built.pep(sp.pep()); built.on("*", this::onEvent); receiver = built; Thread thread = new Thread(() -> { @@ -737,7 +844,7 @@ void endUnmatchedRevocation(SignalEvent event) { } if (java.util.Objects.equals(sessionIndex, caepSession)) return; synchronized (state) { endSession(sid); } - if (receiver != null) receiver.untrack(sid); + dropTracked(sid); Object reason = null; if (event.payload != null) { if (event.payload.get("reason_user") != null) reason = event.payload.get("reason_user"); @@ -800,21 +907,20 @@ void endSession(String sid) { List accountsOfSet(String setId) { List out = new ArrayList<>(); - List expired = new ArrayList<>(); long now = System.currentTimeMillis(); synchronized (state) { for (String sid : new ArrayList<>(accountSets.getOrDefault(setId, List.of()))) { Session found = sessions.get(sid); if (found == null) continue; if (found.expires <= now) { + // Expiry drops the cookie session only. Remove Subject is for + // sign-out and an ending event, not a session that merely lapses. endSession(sid); - expired.add(sid); continue; } out.add(new Held(sid, found)); } } - for (String sid : expired) if (receiver != null) receiver.untrack(sid); return out; } @@ -900,7 +1006,9 @@ String home(Session session, ServiceProvider sp, String problem, String tab, Str int last = session.signals.isEmpty() ? 0 : ((Number) session.signals.get(0).get("id")).intValue(); String panel = "events".equals(tab) ? eventsPanel(base, session, notice) : identity; String goneRow = gone == null ? "" : "

" + esc(gone) + "

"; - return page("Signed in", "

Signed in as " + esc(login.nameId) + "

" + accountBar(accounts, session) + goneRow + return page("Signed in", "

Signed in as " + esc(login.nameId) + "

" + + "

Attribute-protected · Order 42

" + + accountBar(accounts, session) + goneRow + tabs(base, tab, count) + "" + "
" + panel + "
"); diff --git a/docs/remote-pep.md b/docs/remote-pep.md new file mode 100644 index 0000000..7f900ee --- /dev/null +++ b/docs/remote-pep.md @@ -0,0 +1,238 @@ +# Using the iya-sts Remote PEP + +This library can ask iya-sts's authorization policy whether a signed-in person (a validated `SamlLogin`) may do something to a resource in your application, through an embedded **Remote PEP** (Policy Enforcement Point). The PEP itself is [`com.iyasec:iya-pep`](https://github.com/rcbj/iya-pep-java) 0.1.0. This library builds it from your configuration (`com.iyasec.saml.pep.SamlPep`), turns a SAML 2.0 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 a failure while deciding, which the PEP catches) must be treated as a refusal. `decision.httpStatus()` is 200 for a Permit and 403 for a Deny and for Unavailable alike, never a 5xx a client might retry into a different answer. Whether the person is signed in at all (401) is your application's question, asked before the PEP's. + +`decide` does not throw. A failure is an Unavailable decision. + +## Choosing a mode + +| | `central` | `local` | +|---|---|---| +| Who decides | iya-sts, per request (`POST /access/v1/evaluation`) | this process, with the PEP's own XACML engine | +| Dependency | `com.iyasec:iya-pep` (always on the classpath; there is no feature flag) | the same jar. `local` is the default mode | +| Latency | one HTTPS round trip per decision | none after the first pull | +| When iya-sts is down | every decision is Unavailable, and the Permit cache (if on) 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. `scripts/configure_iya_sts.py --pep` does steps 2 to 6 for the demo. + +```bash +api() { curl -s -H "Authorization: Bearer $TOKEN" \ + -H 'Content-Type: application/json' -d "$2" "$API/$1"; } +``` + +### 1. Register the application + +Register the service provider from its metadata (`/admin-api/applications/create`, or `/admin-api/saml2/upload-metadata` when it already exists). The install script does this. The application's identifier is this library's `entityId`, which is the PEP's `application` unless you set one. + +### 2. Create the PEP's service account + +A directory account with no password, owned by `admin-write`, in the group `remote-peps`. The demo's account is `pep-saml-demo` (`--pep-name`). + +### 3. Make the PEP's key, certify it and bind the PEP + +An EC P-256 key the PEP alone holds, mode 0600. Certify it from its own certificate request and bind it to the application: + +```bash +api xacml/issue-pep-credential '{"name":"pep-orders","csr":"","application":""}' +``` + +With the key and the account both kept, `xacml/set-pep-application` binds the account again. + +### 4. Declare the claims your policy reads + +The realm's AuthZEN catalogue has one row per claim. Subject claims without a row are dropped, not refused. Resource, action and context members without a row are refused, so the decision is a Deny. The demo's install script writes `subject.acr` → `urn:example:acr`, the row every sibling demo shares, and relies on `urn:sts:xacml:attribute:attr1` for the directory attribute `attr1`. + +### 5. Write the policy + +The demo writes an ALFA policy onto the application's own fine-grained authorization policy and enforces that policy. It does not call `xacml/set-root`. A policy under another PolicyId is left alone. The script's PolicyId is `urn:saml-sp-demo:samlspdemo:orders`. + +`read` on an `order` is permitted when the sign-in carried an AuthnContextClassRef. `read` on `attribute-protected` is permitted when `attr1` is `abc123`. Anything else, including `write` on an order, is denied. + +### 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. The install script adds the event only when the application already restricts events. + +## Build + +Depend on `com.iyasec:iya-pep:0.1.0` (this library's `library/pom.xml` already does). Until that artifact is on Maven Central, the image clones `https://github.com/rcbj/iya-pep-java.git` branch `develop` and installs it before `mvn test` or `mvn package`. A failed clone is not retried. Do not run Maven on the host. + +There is no Cargo-style feature. A `pep` section is ignored only when it is absent. A section that names no `mode` is `local`. + +## Configure + +Add a `pep` section to `saml.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 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 relative one is read from the configuration file's directory, like `privateKey`. The PEP reads the file itself, and again when it changes. | +| `pdpUrl` | the identity provider's entityID. iya-sts's SAML entityID is the realm's issuer, so this is the service's URL with the realm prefix | iya-sts, with `/realm/` for a realm. When that entityID is not an http(s) URL, name the service here. | +| `application` | `entityId` | The application the PEP is bound to (step 3). | +| `clientId` | `sts-remote-pep` | The client the PEP's assertion is presented through. | +| `signals` | on when this library's receiver runs (an `ssf` object, and `signals` not `false`) | Whether a signal stream hands over policy-change events. Without one, `local` polls at `pollIntervalMs`. | +| `pollIntervalMs` | 15000 | `local` without a signal stream. | +| `fallbackPollMs` | 300000 | `local` with one, in case an event 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. A policy-change event clears it, and so does a failed evaluation or a failed heartbeat. | +| `supportedObligations` | `[]` | The obligation types your application discharges. | +| `decisionRecords` | `true` | `local`: send each decision to iya-sts's audit log. | +| `tlsCa` | `idpCa` (the PEM) | PEM trust anchors for iya-sts's TLS. | +| `timeoutMs` | 10000 | Per request to iya-sts. | + +An unknown member is refused. `ServiceProvider.create` and `fromFile` start the PEP after the identity provider's metadata is read (the `pdpUrl` default needs its entityID). `start` registers and, in `local` mode, pulls once. An unreachable service is retried on the PEP's own thread. Decisions are Unavailable until then. + +`ssf.clientCertificate` and `ssf.clientKey` are the receiver's own TLS client identity: both or neither (PEM, a path relative to the configuration, or a placeholder). They must parse as a certificate and a PKCS#8 key. The demo presents that pair, and falls back to the SP key pair. + +## Decide + +```java +ServiceProvider sp = ServiceProvider.fromFile("saml.json"); +Access access = Access.of("read", "order", orderId); +Decision decision = sp.decideSession(receiver.sessionIndex(), localId, login, access); +int status = decision.httpStatus(); // 200 for a Permit, 403 for anything else +if (decision.isPermit()) { + serve(decision.obligations()); +} else if (decision.kind() == Decision.Kind.DENY) { + forbidden(status, decision.why()); +} else { + forbidden(status, decision.why()); // Unavailable: fail closed +} +// Without a receiver: sp.decide(login, access) +``` + +`httpStatus()` is the rule rather than a convention. The demo's two protected pages take their status from it. + +`Access.of(action, resourceType, resourceId)` carries the AuthZEN action and resource. `actionProperties`, `resourceProperties` and `context` are public maps of JSON values, each declared in the catalogue (step 4). The PEP sets `context.application` to the bound application. + +**The subject** comes from the sign-in, never from a request header (`SamlPep.subjectOf`): + +- **id:** `SamlLogin.username()`: the first non-empty value of `username`, `preferred_username`, `urn:oid:0.9.2342.19200300.100.1.1`, `uid` and `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name`, else the NameID. iya-sts's PIP resolves a username, a DN or a certificate subject. A transient NameID names nobody it can resolve. +- **properties:** the attributes (by Name, and by FriendlyName when that is not also a Name): one value as a string, several as an array. `AuthnContextClassRef` is `acr`. `amr`, or the AD FS claim `http://schemas.microsoft.com/claims/authnmethodsreferences`, is `amr`. `AuthnInstant` is `auth_time` in epoch seconds. + +Only the properties the catalogue declares are sent. + +**Ended sessions.** `decideSession` checks the session index first (`MemorySessionIndex.contains`). A session that is not tracked, or whose `expiresAt` is in the past, is a Deny (`no signed-in session`). iya-sts is not asked. Sign-out calls `untrack`. An ending CAEP or RISC event calls the same removal (`forget`). + +**Without a `pep` section**, every decision is Unavailable (`no pep section is configured`). `httpStatus()` is still 403. + +### Obligations + +A Permit can carry obligations, which your application must carry out before it grants the access. The PEP only hands you obligations of types you list in `supportedObligations`. A Permit carrying any other obligation is turned into a Deny. 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 (`SamlPep.wantsEvents`), the PEP wants to hear when the policies change. Give the receiver the PEP: + +```java +SignalsReceiver receiver = new SignalsReceiver(transmitterUrl, this::endSessions) + .tls(tls) + .sessionIndex(sessions) + .pep(sp.pep()); +receiver.start(); +``` + +`start` checks the TLS client key before any network call. It then asks the stream for `Pep.POLICIES_CHANGED_EVENT` (`urn:iya:sts:secevent:event-type:pep-policies-changed`), verifies each SET like every other one, and hands the event body to `onPolicyEvent`. A stream that already exists is updated with PATCH to ask for the missing types. If the transmitter refuses, the receiver still starts, the refusal goes to the receiver's log at error, and the PEP is told the event is excluded. The event is only a hint: the PEP pulls with its own credential. + +The receiver tells the PEP how its stream is doing: `requested` or `excluded` at start and after each good poll, and `down` after a failed poll and on `stop()`. + +It also tells the transmitter whose events it wants. Each `track` queues Add Subject for the person's `iss_sub` (the subject attribute) and `email`, with `verified: true`. `untrack`, and an event that ends the session, queue Remove Subject for each identifier no other local session holds. Both go out on the poll thread, once, and are never retried. A 403 is a warning (the transmitter may not know an active session yet). Other failures are errors. The latest is `subjectError()`. At most 1000 calls are queued. `"ssf": {"addSubjects": false}` turns this off. A transmitter without `add_subject_endpoint` and `remove_subject_endpoint` gets nothing. + +The application's opaque subject `{format: opaque, id: }` is added at start, ahead of the people, and is never removed. `pep-policies-changed` is about that application. Once people are added, a stream that names subjects would otherwise stop carrying it. + +## Operate it + +- **Health.** `pep.status()` reports whether the PEP is registered and running, whether it holds a policy, its decision counters and its current problems. `SamlPep.statusMap` turns that into a map. It holds no secret. The demo puts it on `GET /live-status` under `pep` when the file has a `pep` section, and on `GET /pep-status` (401 without a sign-in). +- **In the console.** The PEP appears under **Protocols → XACML → Remote PEPs**. The application's page lists the PEPs bound to it. +- **Rotating the key.** Generate a new key, certify it with `issue-pep-credential`, and replace the file. The PEP reads the file again when it changes. +- **Audit.** In `local` mode each decision becomes an audit row in iya-sts. In `central` mode iya-sts records its own. + +## Credentials + +The README's [Credentials](../README.md#credentials) section covers every credential the demo uses. This section covers the embedded PEP's. + +### The application's own credentials + +The SAML key pair (`privateKey` / `certificate`) signs AuthnRequests and decrypts assertions. iya-sts learns it from the SP metadata. The Shared Signals receiver presents its own TLS client certificate, which the realm issues the application (`ssf.clientCertificate` / `ssf.clientKey`), and falls back to the SAML key pair without one. The PEP uses neither. + +### The embedded PEP's credentials + +- **The service account** (step 2): a directory account with no password, in `remote-peps`. It is the PEP's identity. The key is bound to it, and through it to one application (`application`, by default this SP's `entityId`). +- **The key** (`assertionKey`, step 3): an EC P-256 key the PEP alone holds. Make it yourself and keep it 0600. iya-sts certifies it from its CSR (`issue-pep-credential`). With an unchanged key, `set-pep-application` binds the account again. +- **What it authenticates:** every call the PEP makes. It signs an RFC 7523 self-assertion for a DPoP-bound (RFC 9449) access token, and signs each DPoP proof. No token, key or proof is logged. +- **Not the application's keys.** `SamlPep.build` refuses a configuration whose `assertionKey` has the JWK thumbprint of `privateKey` (signing, decryption, and the receiver's TLS key when there is no `ssf.clientKey`) or of `ssf.clientKey`. `SignalsReceiver.start` refuses a PEP whose key is the TLS client key the receiver will present. The error names both keys. +- **Rotation:** replace the key file and certify the new key. With the demo, delete `demo/generated/pep-key.pem` and run the install script again. + +### Install-time only + +The steps above are management calls. Their token comes from `ADMIN_API_CLIENT_SECRET` or `STS_ADMIN_API_CLIENT_SECRET` (the environment, never stored). Defining the realm's custom attribute `attr1` uses a token minted with `admin:read admin:security` for that call alone. The PEP never sees those secrets. The one-time password that opens the issued SSF client key is not printed and is not stored. + +### Trust material + +`tlsCa` (default the `idpCa` PEM, iya-sts's TLS listener chain) verifies iya-sts for the PEP's calls. A `pep-policies-changed` event reaches the PEP only through the receiver, which verified the SET against the transmitter's JWKS. The PEP then pulls the policies with its own token. + +### Development and product iya-sts + +The PEP's credential is the same in both modes: a certified key and a DPoP-bound token. The receiver's realm-issued TLS client certificate is checked the same way in both. + +## 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. 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 doesn't carry the event: 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 `ssf.clientKey`, or the receiver's TLS client key. The PEP needs a key of its own. | +| `pep.pdpUrl` and the identity provider's entityID | That entityID is not an http(s) URL. Name the service in `pep.pdpUrl`. | + +## Testing central against local + +The Rust library compares `central` and `local` with an AuthZEN case table and `scripts/live_authzen.py`. This Java library does not carry that table or that script. `docker build --target test .` runs the SAML wiring tests (subject id, section defaults, the two key refusals, and a Deny for an untracked or expired session). It does not start a PEP against a PDP. + +## The demo + +With a `pep` section, the demo protects `GET /attribute-protected` (`Access.of("read", "attribute-protected", "attr1")`) and `/orders/` (`read` on GET, `write` on any other method, type `order`, id the path segment). No sign-in is 401. The status after that is `decision.httpStatus()`: 200 on a Permit, 403 on a Deny and on Unavailable. When the service provider will not load, the page is 403 as well. The first non-expired account in the `aset` cookie is the subject. `decideSession` uses the index the receiver shares, so a session that was signed out or ended by an event is a Deny even if a cookie still names it. + +One command sets the demo up: `python3 scripts/configure_iya_sts.py --pep local` (or a bare `--pep`) or `--pep central` (`--pep-name`, default `pep-saml-demo`). After registering the service provider it does steps 2 to 6, gives the test user `attr1=abc123`, and writes the `pep` section (`name`, `mode`, `assertionKey: generated/pep-key.pem`), keeping other members. The Shared Signals receiver's TLS client certificate is the one the realm issues (`generated/ssf-client.key` mode 0600 and `generated/ssf-client.crt`). The SP certificate is not added to the process-wide truststore. An anchor an earlier run added is removed. `--dry-run` lists every call and prints no secret. + +```sh +docker compose build +docker run --rm --network host --user "$(id -u):$(id -g)" \ + -v "$PWD/demo:/app/demo" -e ADMIN_API_CLIENT_SECRET -e IYA_STS_URL \ + saml2-sp-java-demo python3 scripts/configure_iya_sts.py --pep local +docker compose up --build +``` + +Run it again against the same iya-sts to switch the mode: the account, the key and an administrator's policy are kept, and the PEP is bound again. `GET /live-status` includes the PEP's status under `pep`. The image copies `demo/saml.json` in when it is built, so rebuild after the script writes the section. Compose mounts `demo/generated`, which holds the PEP's key and the receiver's key. Neither enters the image (`.dockerignore` admits only `idp-ca.pem`). + +The signed-in home page links the two protected pages. `GET /pep-status` returns `{pep: ...}` as JSON and is 401 without a sign-in. This demo does not have the Rust demo's three tabs, collapsible panes, or `pep.js`. It does not have a Playwright UI test (`live_ui.py`) or a live script that flips the policy and checks a denied user. Those remain in the Rust library. + +## See also + +- [`iya-pep`'s README](https://github.com/rcbj/iya-pep-java#readme): the package's own API and every configuration member. +- iya-sts's [Remote PEP page](https://rcbj.github.io/iya-sts/v1.2.0/remote-pep.html): 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 a07b614..a75dc9b 100644 --- a/library/pom.xml +++ b/library/pom.xml @@ -45,6 +45,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/saml/Config.java b/library/src/main/java/com/iyasec/saml/Config.java index 083c705..8a68f03 100644 --- a/library/src/main/java/com/iyasec/saml/Config.java +++ b/library/src/main/java/com/iyasec/saml/Config.java @@ -2,12 +2,18 @@ // SPDX-License-Identifier: MIT package com.iyasec.saml; +import com.iyasec.saml.pep.SamlPep; +import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.security.KeyFactory; import java.security.PrivateKey; +import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPrivateKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.util.Base64; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; @@ -40,11 +46,18 @@ public static final class Resolved { public final String nameIdFormat; /** Null when the receiver stays on. {@code false} when it is off. */ public final Boolean signals; + /** The {@code pep} section with this library's defaults filled in, or null when there is none. */ + public final Map pep; + /** The receiver's own TLS client certificate (PEM), or null to use the SP certificate. */ + public final String ssfClientCertificate; + /** The receiver's own TLS client key (PEM), or null to use the SP key. */ + public final String ssfClientKey; Resolved(String entityId, String acsUrl, PrivateKey privateKey, String privateKeyPem, X509Certificate certificate, String certificatePem, String idpMetadata, String requestBinding, String responseBinding, int clockSkewMs, boolean wantAssertionsSigned, boolean wantAssertionsEncrypted, boolean allowUnsolicited, String idpCa, - String idpEntityId, String nameIdFormat, Boolean signals) { + String idpEntityId, String nameIdFormat, Boolean signals, Map pep, + String ssfClientCertificate, String ssfClientKey) { this.entityId = entityId; this.acsUrl = acsUrl; this.privateKey = privateKey; @@ -62,6 +75,9 @@ public static final class Resolved { this.idpEntityId = idpEntityId; this.nameIdFormat = nameIdFormat; this.signals = signals; + this.pep = pep; + this.ssfClientCertificate = ssfClientCertificate; + this.ssfClientKey = ssfClientKey; } public boolean contains(String key) { @@ -115,12 +131,15 @@ public static Resolved resolveConfig(Map config, String baseDir) String idpCa = config.get("idpCa") instanceof String ca && !ca.isBlank() ? material(ca, base, "idpCa") : null; String idpEntityId = config.get("idpEntityId") instanceof String id && !id.isBlank() ? id : null; String nameIdFormat = config.get("nameIdFormat") instanceof String format && !format.isBlank() ? format : null; + String[] ssfClient = ssfClient(config.get("ssf"), base); + Map pep = SamlPep.section(config, base, idpCa == null ? "" : idpCa); return new Resolved( entityId, acsUrl, privateKey, Keys.privateKeyPem(privateKey), certificate, Keys.certificatePem(certificate), idpMetadata, oneOf(config.get("requestBinding"), REQUEST, "redirect", "requestBinding"), oneOf(config.get("responseBinding"), RESPONSE, "post", "responseBinding"), skew.intValue() * 1000, flag(config, "wantAssertionsSigned", true), flag(config, "wantAssertionsEncrypted", false), - flag(config, "allowUnsolicited", false), idpCa, idpEntityId, nameIdFormat, signals + flag(config, "allowUnsolicited", false), idpCa, idpEntityId, nameIdFormat, signals, pep, + ssfClient == null ? null : ssfClient[0], ssfClient == null ? null : ssfClient[1] ); } @@ -143,7 +162,8 @@ public static Resolved readConfigFile(String path, Map overrides return resolveConfig(merged, Path.of(path).toAbsolutePath().getParent().toString()); } - static String expand(String value) { + /** An {@code env:} or {@code file:} placeholder, followed at most four times. */ + public static String expand(String value) { int seen = 0; while (value.startsWith("env:") || value.startsWith("file:")) { seen += 1; @@ -173,6 +193,56 @@ static String material(String value, String baseDir, String what) { } } + /** + * {@code ssf.clientCertificate} and {@code ssf.clientKey}: both or neither. + * PEM text, a path relative to the configuration, or a placeholder. The pair + * must parse as a certificate and a PKCS#8 key (RSA or EC). A key that is + * not the certificate's is refused by the TLS handshake, not here. + */ + private static String[] ssfClient(Object ssf, String base) { + if (!(ssf instanceof Map block)) return null; + for (String name : new String[] {"clientCertificate", "clientKey"}) { + if (block.containsKey(name) && block.get(name) != null && !(block.get(name) instanceof String)) { + throw new SamlError("config", "ssf." + name + " must be a PEM, a file path or a placeholder"); + } + } + String cert = text(block, "clientCertificate"); + String key = text(block, "clientKey"); + if (cert == null && key == null) return null; + if (cert == null || key == null) { + throw new SamlError("config", "ssf.clientCertificate and ssf.clientKey go together: give both, or neither to use the SP key pair"); + } + String certPem = material(cert, base, "ssf.clientCertificate"); + String keyPem = material(key, base, "ssf.clientKey"); + requireTlsClientIdentity(certPem, keyPem); + return new String[] {certPem, keyPem}; + } + + private static String text(Map block, String name) { + Object value = block.get(name); + if (!(value instanceof String text) || text.isBlank()) return null; + return text.strip(); + } + + private static void requireTlsClientIdentity(String certPem, String keyPem) { + try { + var certificates = CertificateFactory.getInstance("X.509").generateCertificates(new ByteArrayInputStream(certPem.getBytes(StandardCharsets.UTF_8))); + if (certificates.isEmpty()) throw new IllegalArgumentException("no certificate"); + String body = keyPem.replaceAll("-----BEGIN [^-]+-----", "").replaceAll("-----END [^-]+-----", "").replaceAll("\\s", ""); + byte[] der = Base64.getDecoder().decode(body); + PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(der); + try { + KeyFactory.getInstance("EC").generatePrivate(spec); + } catch (Exception ignored) { + KeyFactory.getInstance("RSA").generatePrivate(spec); + } + } catch (SamlError err) { + throw err; + } catch (Exception err) { + throw new SamlError("config", "ssf.clientCertificate and ssf.clientKey are not a usable TLS client identity: " + err.getMessage(), err); + } + } + private static String absoluteUrl(Object value, String what) { if (!(value instanceof String text) || text.isBlank()) throw new SamlError("config", what + " is required"); if (!text.matches("(?i)https?://.*")) throw new SamlError("config", what + " must be an absolute http(s) URL, not " + text); diff --git a/library/src/main/java/com/iyasec/saml/SamlLogin.java b/library/src/main/java/com/iyasec/saml/SamlLogin.java index 17413bc..b2e66ac 100644 --- a/library/src/main/java/com/iyasec/saml/SamlLogin.java +++ b/library/src/main/java/com/iyasec/saml/SamlLogin.java @@ -26,4 +26,34 @@ public class SamlLogin { public boolean encrypted; public String responseId; public String assertionId; + + /** + * Attributes the subject's id is read from, in order: {@code username}, + * else {@code preferred_username}, else iya-sts's spellings of the username + * (the X.500 {@code uid} OID, the bare {@code uid}, and the AD FS name claim). + */ + public static final List USERNAME_ATTRIBUTES = List.of( + "username", + "preferred_username", + "urn:oid:0.9.2342.19200300.100.1.1", + "uid", + "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" + ); + + /** + * The username: the first non-empty value of the first of + * {@link #USERNAME_ATTRIBUTES} the assertion carries, or null when it + * carries none. A transient NameID is not a username. + */ + public String username() { + if (attributes == null) return null; + for (String name : USERNAME_ATTRIBUTES) { + List values = attributes.get(name); + if (values == null) continue; + for (String value : values) { + if (value != null && !value.isEmpty()) return value; + } + } + return null; + } } diff --git a/library/src/main/java/com/iyasec/saml/ServiceProvider.java b/library/src/main/java/com/iyasec/saml/ServiceProvider.java index 4581a28..01f9912 100644 --- a/library/src/main/java/com/iyasec/saml/ServiceProvider.java +++ b/library/src/main/java/com/iyasec/saml/ServiceProvider.java @@ -2,6 +2,12 @@ // SPDX-License-Identifier: MIT package com.iyasec.saml; +import com.iyasec.pep.Access; +import com.iyasec.pep.Decision; +import com.iyasec.pep.Pep; +import com.iyasec.pep.PepException; +import com.iyasec.saml.pep.SamlPep; +import com.iyasec.saml.ssf.MemorySessionIndex; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -31,6 +37,7 @@ public final class ServiceProvider { public final Config.Resolved config; private Metadata.IdpMetadata idp; private final MemoryReplayCache replayCache; + private Pep pep; public ServiceProvider(Config.Resolved config, Metadata.IdpMetadata idp, MemoryReplayCache replayCache) { this.config = config; @@ -41,6 +48,7 @@ public ServiceProvider(Config.Resolved config, Metadata.IdpMetadata idp, MemoryR public static ServiceProvider create(Map config, String baseDir, MemoryReplayCache replayCache) { ServiceProvider provider = new ServiceProvider(Config.resolveConfig(config, baseDir), null, replayCache); provider.refreshMetadata(); + provider.startPep(); return provider; } @@ -51,6 +59,7 @@ public static ServiceProvider create(Map config) { public static ServiceProvider fromFile(String path, Map overrides, MemoryReplayCache replayCache) { ServiceProvider provider = new ServiceProvider(Config.readConfigFile(path, overrides), null, replayCache); provider.refreshMetadata(); + provider.startPep(); return provider; } @@ -62,6 +71,47 @@ public static String postFormHtml(String action, Map fields, Str return Bindings.postFormHtml(action, fields, nonce, null); } + /** + * Builds and starts the embedded PEP once the identity provider's entityID + * (the {@code pdpUrl} default) is known. An unreachable service is retried + * on the PEP's own thread. The constructor does not do this. + */ + private void startPep() { + if (config.pep == null) return; + String entityId = idp == null || idp.entityId == null ? "" : idp.entityId; + pep = SamlPep.build(config.pep, entityId, config.entityId, config.privateKeyPem, config.ssfClientKey); + try { + pep.start(); + } catch (PepException err) { + throw new SamlError("config", err.detail(), err); + } + } + + /** 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. + */ + public Decision decide(SamlLogin login, Access access) { + if (pep == null) return SamlPep.unavailable("no pep section is configured"); + return pep.decide(SamlPep.subjectOf(login), access); + } + + /** + * {@link #decide} for the local session {@code localId} in {@code sessions} + * (the receiver's index). A session that ended is denied without asking. + */ + public Decision decideSession(MemorySessionIndex sessions, String localId, SamlLogin login, Access access) { + if (sessions == null || localId == null || !sessions.contains(localId)) { + return SamlPep.deny("no signed-in session"); + } + return decide(login, access); + } + public Metadata.IdpMetadata idp() { if (idp == null) throw new SamlError("metadata", "the identity provider's metadata has not been loaded"); return idp; diff --git a/library/src/main/java/com/iyasec/saml/pep/SamlPep.java b/library/src/main/java/com/iyasec/saml/pep/SamlPep.java new file mode 100644 index 0000000..6562998 --- /dev/null +++ b/library/src/main/java/com/iyasec/saml/pep/SamlPep.java @@ -0,0 +1,227 @@ +// SPDX-FileCopyrightText: 2026 Iya CyberSecurity Solutions, LLC +// SPDX-License-Identifier: MIT +package com.iyasec.saml.pep; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +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.Subject; +import com.iyasec.pep.key.SigningKey; +import com.iyasec.saml.Caught; +import com.iyasec.saml.Keys; +import com.iyasec.saml.SamlError; +import com.iyasec.saml.SamlLogin; +import java.math.BigInteger; +import java.nio.file.Path; +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 the shared {@code com.iyasec:iya-pep} package into this service provider. + * The PEP knows no SAML: 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 SamlPep { + /** Attributes read as {@code amr}, in order. The Microsoft claim is AD FS. */ + public static final List AMR_ATTRIBUTES = List.of( + "amr", + "http://schemas.microsoft.com/claims/authnmethodsreferences" + ); + + private static final ObjectMapper JSON = new ObjectMapper(); + + private SamlPep() {} + + /** + * The {@code pep} section with this library's defaults filled in, or null + * when there is none. {@code pdpUrl} and {@code application} are filled + * later, once the identity provider's entityID is known. + */ + public static Map section(Map config, String baseDir, String idpCaPem) { + if (config == null || !config.containsKey("pep") || config.get("pep") == null) return null; + if (!(config.get("pep") instanceof Map raw)) throw new SamlError("config", "pep must be an object"); + Map map = new LinkedHashMap<>(); + raw.forEach((key, value) -> map.put(String.valueOf(key), value)); + if (map.get("assertionKey") instanceof String key) { + String expanded = com.iyasec.saml.Config.expand(key); + if (!expanded.isEmpty() && !Path.of(expanded).isAbsolute()) { + String root = baseDir == null ? "" : baseDir; + map.put("assertionKey", Path.of(root).resolve(expanded).normalize().toAbsolutePath().toString()); + } else { + map.put("assertionKey", expanded); + } + } + if (!map.containsKey("signals")) { + boolean receiver = config.get("ssf") instanceof Map && !Boolean.FALSE.equals(config.get("signals")); + map.put("signals", receiver); + } + if (!map.containsKey("tlsCa") && idpCaPem != null && !idpCaPem.isEmpty()) { + map.put("tlsCa", idpCaPem); + } + return map; + } + + /** + * Builds the PEP from the resolved section. Checks that its key is not + * the service provider's and not the receiver's TLS client key. Sends + * nothing; {@link Pep#start()} does. + */ + public static Pep build(Map section, String idpEntityId, String entityId, String spKeyPem, String ssfClientKeyPem) { + JsonNode node = JSON.valueToTree(section); + PepConfig config; + try { + config = PepConfig.fromJson(node, idpEntityId == null ? "" : idpEntityId, entityId == null ? "" : entityId); + } catch (PepException err) { + String detail = err.detail(); + if (!section.containsKey("pdpUrl") && detail != null && detail.startsWith("pep.pdpUrl")) { + detail = detail + ": the identity provider's entityID is not iya-sts's URL, so name the service in pep.pdpUrl"; + } + throw new SamlError("config", detail, err); + } + Pep pep; + try { + pep = Pep.create(config); + } catch (PepException err) { + throw new SamlError("config", err.detail(), err); + } + if (sameThumbprint(spKeyPem, pep.keyThumbprint())) { + throw new SamlError("config", "pep.assertionKey is the service provider's privateKey (its signing, decryption and TLS client key); the PEP needs a key of its own"); + } + if (ssfClientKeyPem != null && sameThumbprint(ssfClientKeyPem, pep.keyThumbprint())) { + throw new SamlError("config", "pep.assertionKey is ssf.clientKey (the Shared Signals receiver's TLS client 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 config = pep.config(); + return config.mode == Mode.LOCAL || config.permitCacheMs > 0; + } + + /** + * The PEP's subject for a validated SAML sign-in. The id is the username + * ({@link SamlLogin#username()}), else the NameID. Attributes, {@code acr}, + * {@code amr} and {@code auth_time} are properties. No request header is read. + */ + public static Subject subjectOf(SamlLogin login) { + String id = login.username(); + if (id == null || id.isEmpty()) id = login.nameId == null ? "" : login.nameId; + Map properties = new LinkedHashMap<>(); + Map> attributes = login.attributes == null ? Map.of() : login.attributes; + for (String name : new TreeSet<>(attributes.keySet())) { + properties.put(name, JSON.valueToTree(oneOrMany(attributes.get(name)))); + } + if (login.attributeFriendlyNames != null) { + for (String name : new TreeSet<>(attributes.keySet())) { + String friendly = login.attributeFriendlyNames.get(name); + if (friendly != null && !friendly.isEmpty() && !properties.containsKey(friendly)) { + properties.put(friendly, JSON.valueToTree(oneOrMany(attributes.get(name)))); + } + } + } + for (String name : AMR_ATTRIBUTES) { + if (attributes.containsKey(name)) { + List values = attributes.get(name); + properties.put("amr", JSON.valueToTree(values == null ? List.of() : List.copyOf(values))); + break; + } + } + if (login.authnContextClassRef != null && !login.authnContextClassRef.isEmpty()) { + properties.put("acr", JSON.valueToTree(login.authnContextClassRef)); + } + if (login.authnInstant != null && login.authnInstant.toEpochMilli() > 0) { + properties.put("auth_time", JSON.valueToTree(login.authnInstant.getEpochSecond())); + } + return Subject.user(id, properties); + } + + /** A Deny that did not ask the engine: no session, or one that has ended. */ + public static Decision deny(String why) { + return Decision.deny(why); + } + + /** No PEP is configured, so nothing is permitted. */ + public static Decision unavailable(String why) { + return Decision.unavailable(why); + } + + /** The event body as the JSON the PEP's {@code 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) { + try { + JsonNode node = JSON.valueToTree(pep.status()); + Map out = new LinkedHashMap<>(); + node.fields().forEachRemaining(field -> out.put(field.getKey(), JSON.convertValue(field.getValue(), Object.class))); + return out; + } catch (RuntimeException err) { + Caught.warn(err); + Map out = new LinkedHashMap<>(); + out.put("error", "status could not be read"); + return out; + } + } + + /** True when {@code pem}'s JWK thumbprint is {@code thumbprint}. */ + public static boolean sameThumbprint(String pem, String thumbprint) { + if (pem == null || pem.isEmpty() || thumbprint == null || thumbprint.isEmpty()) return false; + String fromPem; + try { + fromPem = SigningKey.pemThumbprint(pem); + } catch (Exception err) { + Caught.warn(err); + fromPem = null; + } + if (thumbprint.equals(fromPem)) return true; + String fromJwk = rsaJwkThumbprint(pem); + return thumbprint.equals(fromJwk); + } + + private static String rsaJwkThumbprint(String pem) { + try { + if (!(Keys.loadPrivateKey(pem) instanceof RSAPrivateCrtKey rsa)) return null; + var jwk = JSON.createObjectNode(); + jwk.put("kty", "RSA"); + jwk.put("n", b64(unsigned(rsa.getModulus()))); + jwk.put("e", b64(unsigned(rsa.getPublicExponent()))); + return SigningKey.jwkThumbprint(jwk); + } catch (Exception err) { + Caught.warn(err); + return null; + } + } + + private static Object oneOrMany(List values) { + if (values == null || values.isEmpty()) return List.of(); + if (values.size() == 1) return values.get(0); + return new ArrayList<>(values); + } + + 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/saml/ssf/MemorySessionIndex.java b/library/src/main/java/com/iyasec/saml/ssf/MemorySessionIndex.java index 340618b..277fa05 100644 --- a/library/src/main/java/com/iyasec/saml/ssf/MemorySessionIndex.java +++ b/library/src/main/java/com/iyasec/saml/ssf/MemorySessionIndex.java @@ -48,6 +48,20 @@ public void remove(String localId) { synchronized (lock) { sessions.remove(localId); } } + /** Removes {@code localId} and returns it, even when it has already expired. */ + public Tracked take(String localId) { + synchronized (lock) { return sessions.remove(localId); } + } + + /** Whether {@code localId} is tracked and has not expired. Does not remove it. */ + public boolean contains(String localId) { + if (localId == null) return false; + synchronized (lock) { + Tracked found = sessions.get(localId); + return found != null && (found.expiresAt == null || found.expiresAt.toEpochMilli() > Instant.now().toEpochMilli()); + } + } + public List byPerson(String person) { synchronized (lock) { return find(session -> person.equals(session.person)); } } diff --git a/library/src/main/java/com/iyasec/saml/ssf/SignalsReceiver.java b/library/src/main/java/com/iyasec/saml/ssf/SignalsReceiver.java index ed00db7..567e958 100644 --- a/library/src/main/java/com/iyasec/saml/ssf/SignalsReceiver.java +++ b/library/src/main/java/com/iyasec/saml/ssf/SignalsReceiver.java @@ -2,11 +2,14 @@ // SPDX-License-Identifier: MIT package com.iyasec.saml.ssf; +import com.iyasec.pep.EventStream; +import com.iyasec.pep.Pep; import com.iyasec.saml.Backchannel; import com.iyasec.saml.Caught; import com.iyasec.saml.Json; import com.iyasec.saml.SamlError; import com.iyasec.saml.SamlLogin; +import com.iyasec.saml.pep.SamlPep; import java.time.Instant; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -72,6 +75,12 @@ public interface Log { private final Map> handlers = new LinkedHashMap<>(); private CompletableFuture inflight; private final Object gate = new Object(); + private Pep pep; + private boolean addSubjects = true; + private volatile String subjectError; + private volatile EventStream pepStream; + private final List subjectCalls = new ArrayList<>(); + private static final int MAX_SUBJECT_CALLS = 1000; public SignalsReceiver(String transmitter, EndSessions onEndSessions) { if (onEndSessions == null) throw new SamlError("config", "onEndSessions is required"); @@ -92,16 +101,42 @@ public SignalsReceiver(String transmitter, EndSessions onEndSessions) { public SignalsReceiver pollIntervalMs(int pollIntervalMs) { this.pollIntervalMs = pollIntervalMs; return this; } public SignalsReceiver maxEvents(int maxEvents) { this.maxEvents = maxEvents; return this; } public SignalsReceiver log(Log log) { this.log = log; return this; } + /** The embedded PEP. Policy events are wired when {@link #start()} runs, and only when it wants them. */ + public SignalsReceiver pep(Pep pep) { this.pep = pep; return this; } + /** Whether sign-in and sign-out send Add Subject and Remove Subject. On unless set false. */ + public SignalsReceiver addSubjects(boolean addSubjects) { this.addSubjects = addSubjects; return this; } public Map stream() { return stream; } + /** The index of tracked local sessions ({@code ServiceProvider.decideSession}). */ + public MemorySessionIndex sessionIndex() { return index; } + + /** The event types this receiver asks its stream for. */ + public List eventsRequested() { return List.copyOf(eventsRequested); } + + /** The last Add/Remove Subject refusal or failure. These are never fatal and never retried. */ + public String subjectError() { return subjectError; } + + /** + * What an {@code ssf} block's {@code addSubjects} says: true when it is + * absent, an error when it is not a boolean. + */ + public static boolean addSubjectsSetting(Object ssf) { + if (!(ssf instanceof Map block) || !block.containsKey("addSubjects") || block.get("addSubjects") == null) return true; + if (!(block.get("addSubjects") instanceof Boolean on)) throw new SamlError("config", "ssf.addSubjects must be true or false"); + return on; + } + public void track(String localId, SamlLogin login) { track(localId, login, null); } public void track(String localId, SamlLogin login, Instant expiresAt) { - index.add(MemorySessionIndex.trackedFrom(localId, login, subjectAttribute, expiresAt)); + MemorySessionIndex.Tracked record = MemorySessionIndex.trackedFrom(localId, login, subjectAttribute, expiresAt); + index.add(record); + if (!addSubjects) return; + for (String[] identifier : identifiers(record)) queueSubject(new SubjectCall(true, identifier[0], identifier[1])); } - public void untrack(String localId) { index.remove(localId); } + public void untrack(String localId) { forget(localId); } public SignalsReceiver on(String eventType, Handler handler) { handlers.computeIfAbsent(eventType, key -> new ArrayList<>()).add(handler); @@ -110,14 +145,17 @@ public SignalsReceiver on(String eventType, Handler handler) { public void start() { if (running) return; + armPep(); config = discover(); jwks(true); stream = ensureStream(); + reportStreamAtStart(); Object delivery = stream.get("delivery"); if (!(delivery instanceof Map map) || !(map.get("endpoint_url") instanceof String)) { throw new SamlError("ssf", "the stream has no poll endpoint_url"); } running = true; + queueApplicationSubject(); 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 " + map.get("endpoint_url") + ", delivering " + count + " event type(s)"); @@ -128,6 +166,7 @@ public void stop() { running = false; if (timer != null) timer.cancel(false); timer = null; + if (pep != null) setPepStream(EventStream.DOWN); } public boolean pollOnce() { @@ -153,10 +192,12 @@ public boolean pollOnce() { } try { boolean result = pollNow(); + reportPepStream(true); mine.complete(result); return result; } catch (RuntimeException err) { Caught.error(err); + reportPepStream(false); mine.completeExceptionally(err); throw err; } finally { @@ -188,6 +229,7 @@ private void iteration() { } private boolean pollNow() { + sendSubjectCalls(); Object delivery = stream.get("delivery"); String url = String.valueOf(((Map) delivery).get("endpoint_url")); List pendingAck = new ArrayList<>(ack); @@ -285,7 +327,7 @@ private void handle(String jti, String token) { log.error("ssf: onEndSessions threw for " + eventType + " (SET " + jti + " is still acknowledged): " + err); event.ended = false; } - if (event.ended) for (String localId : sessions) index.remove(localId); + if (event.ended) for (String localId : sessions) forget(localId); } List both = new ArrayList<>(); if (handlers.get(eventType) != null) both.addAll(handlers.get(eventType)); @@ -346,7 +388,7 @@ private Map ensureStream() { if (item instanceof Map map) { Object delivery = map.get("delivery"); if (delivery instanceof Map method && POLL_METHOD.equals(method.get("method")) && map.get("stream_id") != null) { - return cast(map); + return withRequestedEvents(cast(map), endpoint); } } } @@ -365,6 +407,193 @@ private Map ensureStream() { return stream; } + /** + * 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 = stringList(found.get("events_requested")); + if (requested == null) requested = stringList(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); + String added = String.join(", ", missing); + try { + Reply patched = call("PATCH", endpoint, body); + if (patched.status == 200 && patched.json instanceof Map map && streamId.equals(String.valueOf(map.get("stream_id")))) { + Map updated = cast(map); + if (!updated.containsKey("delivery") && found.get("delivery") != null) updated.put("delivery", found.get("delivery")); + return updated; + } + log.error("ssf: adding " + added + " to stream " + streamId + " answered " + patched.status + ": " + clip(patched.json)); + } catch (RuntimeException err) { + Caught.error(err); + log.error("ssf: adding " + added + " to stream " + streamId + " failed: " + err); + } + return found; + } + + private void armPep() { + if (pep == null) return; + String tlsKey = tls.get("key"); + String thumbprint; + try { + thumbprint = pep.keyThumbprint(); + } catch (RuntimeException err) { + throw err; + } catch (Exception err) { + throw new SamlError("config", err.getMessage(), err); + } + if (tlsKey != null && SamlPep.sameThumbprint(tlsKey, thumbprint)) { + throw new SamlError("config", "the receiver's TLS client key (ssf.clientKey, or the SP's privateKey it falls back to) is pep.assertionKey; the PEP needs a key of its own"); + } + if (!SamlPep.wantsEvents(pep)) { + pep = null; + return; + } + if (!eventsRequested.contains(Pep.POLICIES_CHANGED_EVENT)) eventsRequested.add(Pep.POLICIES_CHANGED_EVENT); + Pep bound = pep; + on(Pep.POLICIES_CHANGED_EVENT, event -> { + try { + bound.onPolicyEvent(SamlPep.toJson(event.payload)); + } catch (Exception err) { + Caught.error(err); + log.error("ssf: the PEP refused a policy event (the SET is still acknowledged): " + err); + } + }); + } + + private void reportStreamAtStart() { + if (pep == null) return; + Boolean delivered = listed(stream.get("events_delivered")); + Boolean requested = listed(stream.get("events_requested")); + boolean carried = delivered != null ? delivered : requested != null ? requested : true; + EventStream state = carried ? EventStream.REQUESTED : EventStream.EXCLUDED; + pepStream = state; + setPepStream(state); + } + + /** Whether the event list carries the policy event, or null when it is not a list. */ + private Boolean listed(Object events) { + if (!(events instanceof List list)) return null; + for (Object item : list) if (Pep.POLICIES_CHANGED_EVENT.equals(String.valueOf(item))) return true; + return false; + } + + private void reportPepStream(boolean ok) { + if (pep == null) return; + if (ok) { + if (pepStream != null) setPepStream(pepStream); + } else { + setPepStream(EventStream.DOWN); + } + } + + private void setPepStream(EventStream state) { + try { + pep.setEventStream(state); + } catch (Exception err) { + Caught.warn(err); + log.warn("ssf: the PEP was not told the stream is " + state.asString() + ": " + err); + } + } + + private void queueApplicationSubject() { + if (!addSubjects || pep == null) return; + String application = pep.config().application; + if (application == null || application.isEmpty()) return; + synchronized (subjectCalls) { + subjectCalls.add(0, new SubjectCall(true, "opaque", application)); + } + } + + private void forget(String localId) { + MemorySessionIndex.Tracked record = index.take(localId); + if (record == null || !addSubjects) return; + for (String[] identifier : identifiers(record)) { + List others = "email".equals(identifier[0]) ? index.byEmail(identifier[1]) : index.byPerson(identifier[1]); + if (others.isEmpty()) queueSubject(new SubjectCall(false, identifier[0], identifier[1])); + } + } + + private void queueSubject(SubjectCall call) { + synchronized (subjectCalls) { + if (subjectCalls.size() >= MAX_SUBJECT_CALLS) { + subjectCalls.remove(0); + log.warn("ssf: too many Add/Remove Subject calls waiting for the transmitter; dropped the oldest"); + } + subjectCalls.add(call); + } + } + + private void sendSubjectCalls() { + String addEndpoint = text(config, "add_subject_endpoint"); + String removeEndpoint = text(config, "remove_subject_endpoint"); + String issuer = text(config, "issuer"); + String streamId = stream == null || stream.get("stream_id") == null ? "" : String.valueOf(stream.get("stream_id")); + if (streamId.isEmpty()) return; + List calls; + synchronized (subjectCalls) { + calls = new ArrayList<>(subjectCalls); + subjectCalls.clear(); + } + for (SubjectCall call : calls) { + String endpoint = call.add ? addEndpoint : removeEndpoint; + String what = call.add ? "adding" : "removing"; + if (endpoint.isEmpty()) continue; + Map subject = new LinkedHashMap<>(); + subject.put("format", call.format); + if ("email".equals(call.format)) subject.put("email", call.value); + else if ("opaque".equals(call.format)) subject.put("id", call.value); + else { + subject.put("iss", issuer); + subject.put("sub", call.value); + } + Map body = new LinkedHashMap<>(); + body.put("stream_id", streamId); + body.put("subject", subject); + if (call.add) body.put("verified", true); + boolean unexpected = true; + String line; + try { + Reply reply = call("POST", endpoint, body); + if (reply.status == 200 || reply.status == 204) continue; + if (reply.status == 403) { + unexpected = false; + line = "ssf: " + what + " an " + call.format + " subject on stream " + streamId + " was refused (403; the transmitter may know no active session for it yet); not retried"; + } else { + line = "ssf: " + what + " an " + call.format + " subject on stream " + streamId + " answered " + reply.status + ": " + clip(reply.json); + } + } catch (RuntimeException err) { + Caught.error(err); + line = "ssf: " + what + " an " + call.format + " subject on stream " + streamId + " failed: " + err; + } + if (unexpected) log.error(line); + else log.warn(line); + subjectError = line; + } + } + + private static String text(Map source, String name) { + if (source == null || source.get(name) == null) return ""; + return String.valueOf(source.get(name)); + } + + private static List identifiers(MemorySessionIndex.Tracked record) { + List out = new ArrayList<>(); + if (record.person() != null && !record.person().isEmpty()) out.add(new String[] {"iss_sub", record.person()}); + if (record.email() != null && !record.email().isEmpty()) out.add(new String[] {"email", record.email()}); + return out; + } + private Reply call(String method, String url, Object body) { Map requestHeaders = new LinkedHashMap<>(); requestHeaders.put("accept", "application/json"); @@ -388,6 +617,14 @@ private Reply call(String method, String url, Object body) { return new Reply(answer.status(), parsed); } + /** The value as a list of strings, or null when it is not a list (so a missing key is left alone). */ + private static List stringList(Object value) { + if (!(value instanceof List list)) return null; + List out = new ArrayList<>(); + for (Object item : list) out.add(String.valueOf(item)); + return out; + } + private static List strings(Object value) { if (value instanceof List list) { List out = new ArrayList<>(); @@ -410,4 +647,6 @@ private static String clip(Object value) { } private record Reply(int status, Object json) {} + + private record SubjectCall(boolean add, String format, String value) {} } diff --git a/library/src/test/java/com/iyasec/saml/pep/AuthzenTest.java b/library/src/test/java/com/iyasec/saml/pep/AuthzenTest.java new file mode 100644 index 0000000..8f317a6 --- /dev/null +++ b/library/src/test/java/com/iyasec/saml/pep/AuthzenTest.java @@ -0,0 +1,429 @@ +// SPDX-FileCopyrightText: 2026 Iya CyberSecurity Solutions, LLC +// SPDX-License-Identifier: MIT +package com.iyasec.saml.pep; + +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.ObjectMapper; +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.Obligation; +import com.iyasec.pep.Pep; +import com.iyasec.saml.SamlLogin; +import com.iyasec.saml.ServiceProvider; +import com.iyasec.saml.StubIdp; +import com.iyasec.saml.ssf.MemorySessionIndex; +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.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.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.junit.jupiter.api.Test; + +/** The AuthZEN case table, decided by a local service provider. */ +class AuthzenTest { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String SESSION = "L-authzen"; + private static final Pattern SUBJECT = Pattern.compile("subject-id\"[^>]*>\\s*]*>([^<]*)<"); + private static final Pattern DESIGNATOR = Pattern.compile("]*Category=\"([^\"]*)\"[^>]*AttributeId=\"([^\"]*)\"[^>]*DataType=\"([^\"]*)\""); + + private static final byte[] TOKEN = "{\"access_token\":\"azn-token\",\"token_type\":\"DPoP\",\"expires_in\":300}".getBytes(StandardCharsets.UTF_8); + private static final byte[] REGISTERED = "{\"registered\":true,\"identity\":\"uid=pep-azn,ou=users,dc=azn\"}".getBytes(StandardCharsets.UTF_8); + private static final byte[] HEARTBEAT = "{\"acknowledged\":true,\"current\":true}".getBytes(StandardCharsets.UTF_8); + private static final byte[] AUDIT = "{\"acknowledged\":0}".getBytes(StandardCharsets.UTF_8); + private static final byte[] UNAUTHORIZED = "{\"error\":\"invalid_token\"}".getBytes(StandardCharsets.UTF_8); + private static final byte[] NOT_FOUND = "{\"error\":\"not_found\"}".getBytes(StandardCharsets.UTF_8); + + @Test + void theTableDecidesAsItSaysOffline() throws Exception { + JsonNode table = JSON.readTree(textResource("cases.json")); + assertTrue(table.path("cases").isArray(), "authzen/cases.json has no cases"); + List failures = new ArrayList<>(); + int run = 0; + for (String phase : List.of("root", "application")) { + byte[] catalogue = catalogueOf(table, phase); + byte[] policies = policiesOf(table, phase); + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + ExecutorService executor = Executors.newCachedThreadPool(runnable -> { + Thread thread = new Thread(runnable, "saml-authzen"); + thread.setDaemon(true); + return thread; + }); + server.createContext("/", exchange -> answer(exchange, table, catalogue, policies)); + server.setExecutor(executor); + server.start(); + Path key = null; + ServiceProvider provider = null; + try { + key = ecKey("azn-" + phase); + provider = provider(server.getAddress().getPort(), key, table); + waitHeld(provider.pep()); + assertEquals(subjectRoots(table), provider.pep().status().catalogueSubjectProperties, "every subject row of the table was read: " + provider.pep().status().lastError); + for (JsonNode one : table.get("cases")) { + if (!phase.equals(phaseOf(one))) continue; + run++; + Decision decision = ask(provider, table, one); + boolean matches = expected(decision, one.get("expect")); + JsonNode defect = one.get("knownLocalDefect"); + if (defect != null && defect.isTextual()) { + if (matches) { + failures.add(one.path("name").asText() + ": local now answers as expected; remove knownLocalDefect"); + } + } else if (!matches) { + failures.add(one.path("name").asText() + " [" + phase + "]: " + described(decision) + ", the table says " + one.get("expect")); + } + } + } finally { + if (provider != null && provider.pep() != null) { + try { + provider.pep().stop(); + } catch (RuntimeException ignored) { + // Still close the stub. + } + } + server.stop(0); + executor.shutdownNow(); + if (key != null) { + try { + Files.deleteIfExists(key); + } catch (IOException ignored) { + // The key file is in the temporary directory. + } + } + } + } + assertEquals(table.get("cases").size(), run, "every case has a phase this runner knows"); + assertTrue(failures.isEmpty(), failures.size() + " of " + run + " cases:\n" + String.join("\n", failures)); + } + + private static ServiceProvider provider(int port, Path key, JsonNode table) { + List obligations = new ArrayList<>(); + for (JsonNode item : table.path("supportedObligations")) { + if (item.isTextual()) obligations.add(item.asText()); + } + Map section = new LinkedHashMap<>(); + section.put("name", "pep-azn"); + section.put("mode", "local"); + section.put("assertionKey", key.toString()); + section.put("pdpUrl", "http://127.0.0.1:" + port + "/realm/azn"); + section.put("heartbeatIntervalMs", 60000); + section.put("pollIntervalMs", 60000); + section.put("decisionRecords", false); + section.put("supportedObligations", obligations); + Map config = base(); + config.put("pep", section); + return ServiceProvider.create(config); + } + + private static void waitHeld(Pep pep) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(20); + while (System.nanoTime() < deadline) { + if (pep.status().holdsPolicy) return; + Thread.sleep(100); + } + assertTrue(pep.status().holdsPolicy, "the local PEP did not hold the table's policy: " + pep.status().lastError); + } + + private static int subjectRoots(JsonNode table) { + Set roots = new HashSet<>(); + for (JsonNode row : table.path("catalogue")) { + if (!"subject".equals(row.path("object").asText())) continue; + String property = row.path("property").asText(); + int dot = property.indexOf('.'); + roots.add(dot < 0 ? property : property.substring(0, dot)); + } + return roots.size(); + } + + private static String phaseOf(JsonNode one) { + JsonNode phase = one.get("phase"); + if (phase != null && phase.isTextual()) return phase.asText(); + return "root"; + } + + private static Decision ask(ServiceProvider provider, JsonNode table, JsonNode one) { + String name = one.path("login").asText(); + JsonNode base = table.path("logins").path(name); + assertTrue(base.isObject(), "no login " + name); + SamlLogin login = loginOf(base, one); + Access access = accessOf(one.path("access")); + JsonNode session = one.get("session"); + if (session == null || !session.isTextual()) return provider.decide(login, access); + MemorySessionIndex index = new MemorySessionIndex(); + if ("tracked".equals(session.asText())) { + index.add(new MemorySessionIndex.Tracked(SESSION, "azn", null, "IDP-AZN", null)); + } + return provider.decideSession(index, SESSION, login, access); + } + + private static SamlLogin loginOf(JsonNode base, JsonNode one) { + Map> attributes = new LinkedHashMap<>(); + mergeAttributes(attributes, base.get("attributes")); + mergeAttributes(attributes, one.get("attributes")); + Map friendly = new LinkedHashMap<>(); + mergeFriendly(friendly, base.get("friendlyNames")); + mergeFriendly(friendly, one.get("friendlyNames")); + String acr = ""; + JsonNode acrNode = one.has("acr") ? one.get("acr") : base.get("acr"); + if (acrNode != null && acrNode.isTextual()) acr = acrNode.asText(); + SamlLogin login = new SamlLogin(); + login.nameId = base.path("nameId").asText(""); + login.nameIdFormat = "urn:oasis:names:tc:SAML:2.0:nameid-format:transient"; + login.sessionIndex = "IDP-AZN"; + login.authnInstant = Instant.ofEpochMilli(1_760_000_000_000L); + login.authnContextClassRef = acr; + login.attributes = attributes; + login.attributeFriendlyNames = friendly; + login.issuer = StubIdp.IDP_ENTITY; + return login; + } + + private static void mergeAttributes(Map> attributes, JsonNode source) { + if (source == null || !source.isObject()) return; + source.fields().forEachRemaining(field -> { + if (field.getValue().isNull()) attributes.remove(field.getKey()); + else attributes.put(field.getKey(), strings(field.getValue())); + }); + } + + private static void mergeFriendly(Map friendly, JsonNode source) { + if (source == null || !source.isObject()) return; + source.fields().forEachRemaining(field -> friendly.put(field.getKey(), field.getValue().asText(""))); + } + + 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 Access accessOf(JsonNode access) { + Access out = Access.of(access.path("action").asText(""), access.path("type").asText(""), access.path("id").asText("")); + out.resourceProperties = properties(access.get("resource")); + out.actionProperties = properties(access.get("actionProperties")); + out.context = properties(access.get("context")); + return out; + } + + private static Map properties(JsonNode node) { + Map out = new LinkedHashMap<>(); + if (node != null && node.isObject()) { + node.fields().forEachRemaining(field -> out.put(field.getKey(), field.getValue().deepCopy())); + } + return out; + } + + private static boolean expected(Decision decision, JsonNode expect) { + if (expect == null || !expect.isObject()) return false; + String want = expect.path("decision").asText(); + String got = decision.kind() == Decision.Kind.PERMIT ? "Permit" : decision.kind() == Decision.Kind.DENY ? "Deny" : "Unavailable"; + if (!got.equals(want)) return false; + if (!"Permit".equals(want)) return true; + JsonNode wantObligations = expect.get("obligations"); + int count = wantObligations != null && wantObligations.isArray() ? wantObligations.size() : 0; + List obligations = decision.obligations(); + if (obligations.size() != count) return false; + for (int i = 0; i < count; i++) { + JsonNode wanted = wantObligations.get(i); + Obligation obligation = obligations.get(i); + if (!obligation.kind.equals(wanted.path("type").asText())) return false; + JsonNode properties = wanted.get("properties"); + if (properties == null || properties.isNull()) { + if (!obligation.properties.isEmpty()) return false; + } else if (!obligation.properties.equals(properties)) return false; + } + return true; + } + + private static String described(Decision decision) { + if (decision.kind() == Decision.Kind.PERMIT) { + StringBuilder out = new StringBuilder("Permit"); + if (!decision.obligations().isEmpty()) { + out.append(" ["); + boolean first = true; + for (Obligation obligation : decision.obligations()) { + if (!first) out.append(", "); + first = false; + out.append(obligation.kind).append(' ').append(obligation.properties); + } + out.append(']'); + } + return out.toString(); + } + String name = decision.kind() == Decision.Kind.DENY ? "Deny" : "Unavailable"; + if (decision.why() == null || decision.why().isEmpty()) return name; + return name + " (" + decision.why() + ")"; + } + + private static byte[] catalogueOf(JsonNode table, String phase) throws Exception { + ObjectNode body = JSON.createObjectNode(); + body.put("syncToken", "azn-c"); + body.put("realm", "azn"); + body.set("rows", table.get("catalogue")); + ArrayNode applications = body.putArray("fgaApplications"); + if ("application".equals(phase)) applications.add(StubIdp.SP_ENTITY); + body.putObject("settings").put("obligationsProfile", true); + return JSON.writeValueAsBytes(body); + } + + private static byte[] policiesOf(JsonNode table, String phase) throws Exception { + ObjectNode body = JSON.createObjectNode(); + body.put("syncToken", "azn-" + phase); + body.put("scope", "bound-application"); + body.put("source", "root".equals(phase) ? "root" : "application"); + ArrayNode policies = body.putArray("policies"); + if ("root".equals(phase)) policies.add(policyRow(table, "root", true)); + else { + policies.add(policyRow(table, "application", true)); + policies.add(policyRow(table, "shared", false)); + } + body.putArray("withheld"); + body.put("note", ""); + return JSON.writeValueAsBytes(body); + } + + private static ObjectNode policyRow(JsonNode table, String key, boolean root) { + JsonNode policy = table.path("policies").path(key); + String id = policy.path("policyId").asText(); + String file = policy.path("xacml").asText(); + String document = textResource(file); + assertTrue(document.contains(id), file + " does not contain " + id); + ObjectNode row = JSON.createObjectNode(); + JsonNode name = policy.get("name"); + row.put("name", name != null && name.isTextual() ? name.asText() : key); + row.put("policyId", id); + row.put("kind", policy.path("kind").asText()); + row.put("version", "1.0"); + row.put("isRoot", root); + row.put("description", ""); + row.put("document", document); + return row; + } + + private static String pipAnswer(JsonNode table, String query) { + Matcher subject = SUBJECT.matcher(query); + String id = subject.find() ? subject.group(1) : ""; + JsonNode person = table.path("directory").path(id); + StringBuilder out = new StringBuilder(""); + Matcher designators = DESIGNATOR.matcher(query); + while (designators.find()) { + JsonNode value = person.get(designators.group(2)); + if (value == null || !value.isTextual()) continue; + out.append("") + .append(xml(value.asText())) + .append(""); + } + out.append(""); + return out.toString(); + } + + private static String xml(String value) { + return value.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """); + } + + private static void answer(HttpExchange exchange, JsonNode table, byte[] catalogue, byte[] policies) { + try { + byte[] raw = exchange.getRequestBody().readAllBytes(); + String path = route(exchange.getRequestURI().getPath()); + String authorization = exchange.getRequestHeaders().getFirst("Authorization"); + if (!"/oauth2/token".equals(path) && (authorization == null || !authorization.startsWith("DPoP "))) { + send(exchange, 401, "application/json", UNAUTHORIZED); + return; + } + if ("/oauth2/token".equals(path)) send(exchange, 200, "application/json", TOKEN); + else if ("/xacml/pep/register".equals(path)) send(exchange, 201, "application/json", REGISTERED); + else if ("/xacml/pep/heartbeat".equals(path)) send(exchange, 200, "application/json", HEARTBEAT); + else if ("/xacml/pep/authzen-catalogue".equals(path)) send(exchange, 200, "application/json", catalogue); + else if ("/xacml/pep/policies".equals(path)) send(exchange, 200, "application/json", policies); + else if ("/xacml/pip".equals(path)) send(exchange, 200, "application/xml", pipAnswer(table, new String(raw, StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8)); + else if ("/admin-api/pep-audit".equals(path)) send(exchange, 200, "application/json", AUDIT); + else send(exchange, 404, "application/json", NOT_FOUND); + } catch (Exception err) { + try { + byte[] body = String.valueOf(err).getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(500, body.length); + exchange.getResponseBody().write(body); + } catch (Exception ignored) { + // The exchange is already gone. + } + } finally { + exchange.close(); + } + } + + private static String route(String path) { + String prefix = "/realm/azn"; + if (path != null && path.startsWith(prefix)) path = path.substring(prefix.length()); + if (path == null || path.isEmpty()) return "/"; + return path; + } + + private static void send(HttpExchange exchange, int status, String type, byte[] body) throws IOException { + exchange.getResponseHeaders().set("Content-Type", type); + exchange.sendResponseHeaders(status, body.length); + exchange.getResponseBody().write(body); + } + + private static String textResource(String name) { + String path = "/authzen/" + name; + try (InputStream in = AuthzenTest.class.getResourceAsStream(path)) { + if (in == null) throw new AssertionError("missing test resource " + path); + return new String(in.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException err) { + throw new AssertionError(path, err); + } + } + + private static Path ecKey(String tag) throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("EC"); + generator.initialize(new ECGenParameterSpec("secp256r1")); + byte[] encoded = generator.generateKeyPair().getPrivate().getEncoded(); + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(encoded); + String pem = "-----BEGIN PRIVATE KEY-----\n" + body + "\n-----END PRIVATE KEY-----\n"; + Path path = Path.of(System.getProperty("java.io.tmpdir"), "saml2-sp-pep-" + tag + "-" + ProcessHandle.current().pid() + "-" + System.nanoTime() + ".pem"); + Files.writeString(path, pem); + return path.toAbsolutePath(); + } + + private static Map base() { + Map out = new LinkedHashMap<>(); + out.put("entityId", StubIdp.SP_ENTITY); + out.put("acsUrl", StubIdp.ACS); + out.put("privateKey", StubIdp.SP_KEY); + out.put("certificate", StubIdp.SP_CERT); + out.put("idpMetadata", StubIdp.idpMetadata(null)); + return out; + } +} diff --git a/library/src/test/java/com/iyasec/saml/pep/LocalModeTest.java b/library/src/test/java/com/iyasec/saml/pep/LocalModeTest.java new file mode 100644 index 0000000..cd2ddc0 --- /dev/null +++ b/library/src/test/java/com/iyasec/saml/pep/LocalModeTest.java @@ -0,0 +1,199 @@ +// SPDX-FileCopyrightText: 2026 Iya CyberSecurity Solutions, LLC +// SPDX-License-Identifier: MIT +package com.iyasec.saml.pep; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.iyasec.pep.Access; +import com.iyasec.pep.Decision; +import com.iyasec.saml.SamlLogin; +import com.iyasec.saml.ServiceProvider; +import com.iyasec.saml.StubIdp; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +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.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.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Test; + +/** A local PEP fails closed until it holds a policy, then decides in process. */ +class LocalModeTest { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String READ_ONLY = "read"; + + private static final byte[] TOKEN = json("{\"access_token\":\"pep-token\",\"token_type\":\"DPoP\",\"expires_in\":300}"); + private static final byte[] REGISTERED = json("{\"registered\":true}"); + private static final byte[] HEARTBEAT = json("{\"acknowledged\":true,\"current\":true}"); + private static final byte[] CATALOGUE = json("{\"syncToken\":\"c1\",\"rows\":[{\"object\":\"subject\",\"property\":\"acr\",\"attributeId\":\"urn:example:acr\"}],\"settings\":{\"obligationsProfile\":false}}"); + private static final byte[] AUDIT = json("{\"acknowledged\":0}"); + private static final byte[] PERMIT = json("{\"decision\":true}"); + private static final byte[] UNAUTHORIZED = json("{\"error\":\"invalid_token\"}"); + private static final byte[] NOT_NOW = json("{\"error\":\"server_error\",\"error_description\":\"not now\"}"); + private static final byte[] NOT_FOUND = json("{\"error\":\"not_found\"}"); + + @Test + void localModeFailsClosedThenDecidesInProcess() throws Exception { + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + ExecutorService executor = Executors.newCachedThreadPool(runnable -> { + Thread thread = new Thread(runnable, "saml-pdp"); + thread.setDaemon(true); + return thread; + }); + AtomicBoolean policiesUp = new AtomicBoolean(false); + AtomicInteger policies = new AtomicInteger(); + AtomicInteger evaluation = new AtomicInteger(); + byte[] held = readOnlyPolicy(); + server.createContext("/", exchange -> answer(exchange, policiesUp, policies, evaluation, held)); + server.setExecutor(executor); + server.start(); + Path key = null; + ServiceProvider provider = null; + try { + key = ecKey("local"); + Map config = base(); + Map section = new LinkedHashMap<>(); + section.put("name", "pep-local"); + section.put("mode", "local"); + section.put("pollIntervalMs", 1000); + section.put("heartbeatIntervalMs", 60000); + section.put("assertionKey", key.toString()); + section.put("pdpUrl", "http://127.0.0.1:" + server.getAddress().getPort()); + config.put("pep", section); + provider = ServiceProvider.create(config); + assertNotNull(provider.pep()); + assertFalse(provider.pep().config().signals, "no receiver: the PEP polls at pollIntervalMs"); + Decision closed = provider.decide(login(), Access.of("read", "order", "42")); + assertEquals(Decision.Kind.UNAVAILABLE, closed.kind()); + + policiesUp.set(true); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(8); + while (System.nanoTime() < deadline && !provider.pep().status().holdsPolicy) { + Thread.sleep(100); + } + assertTrue(provider.pep().status().holdsPolicy, "the poll pulled once the service answered: " + provider.pep().status().lastError); + assertTrue(provider.decide(login(), Access.of("read", "order", "42")).isPermit()); + assertEquals(Decision.Kind.DENY, provider.decide(login(), Access.of("write", "order", "42")).kind()); + assertEquals(0, evaluation.get(), "decided in process"); + assertTrue(policies.get() >= 2, "policies were requested " + policies.get() + " times"); + } finally { + if (provider != null && provider.pep() != null) { + try { + provider.pep().stop(); + } catch (RuntimeException ignored) { + // Still close the stub. + } + } + server.stop(0); + executor.shutdownNow(); + if (key != null) { + try { + Files.deleteIfExists(key); + } catch (java.io.IOException ignored) { + // The key file is in the temporary directory. + } + } + } + } + + private static void answer(HttpExchange exchange, AtomicBoolean policiesUp, AtomicInteger policies, AtomicInteger evaluation, byte[] held) { + try { + exchange.getRequestBody().readAllBytes(); + String path = exchange.getRequestURI().getPath(); + if (path == null) path = ""; + if ("/xacml/pep/policies".equals(path)) policies.incrementAndGet(); + if ("/access/v1/evaluation".equals(path)) evaluation.incrementAndGet(); + String authorization = exchange.getRequestHeaders().getFirst("Authorization"); + if (!"/oauth2/token".equals(path) && (authorization == null || !authorization.startsWith("DPoP "))) { + send(exchange, 401, "application/json", UNAUTHORIZED); + return; + } + if ("/oauth2/token".equals(path)) send(exchange, 200, "application/json", TOKEN); + else if ("/xacml/pep/register".equals(path)) send(exchange, 201, "application/json", REGISTERED); + else if ("/xacml/pep/heartbeat".equals(path)) send(exchange, 200, "application/json", HEARTBEAT); + else if ("/xacml/pep/authzen-catalogue".equals(path)) send(exchange, 200, "application/json", CATALOGUE); + else if ("/xacml/pep/policies".equals(path)) { + if (policiesUp.get()) send(exchange, 200, "application/json", held); + else send(exchange, 503, "application/json", NOT_NOW); + } else if ("/admin-api/pep-audit".equals(path)) send(exchange, 200, "application/json", AUDIT); + else if ("/access/v1/evaluation".equals(path)) send(exchange, 200, "application/json", PERMIT); + else send(exchange, 404, "application/json", NOT_FOUND); + } catch (Exception err) { + try { + byte[] body = String.valueOf(err).getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(500, body.length); + exchange.getResponseBody().write(body); + } catch (Exception ignored) { + // The exchange is already gone. + } + } finally { + exchange.close(); + } + } + + private static byte[] readOnlyPolicy() throws Exception { + ObjectNode body = JSON.createObjectNode(); + body.put("syncToken", "p1"); + ObjectNode row = body.putArray("policies").addObject(); + row.put("policyId", "orders"); + row.put("kind", "Policy"); + row.put("version", "1.0"); + row.put("isRoot", true); + row.put("document", READ_ONLY); + return JSON.writeValueAsBytes(body); + } + + private static void send(HttpExchange exchange, int status, String type, byte[] body) throws java.io.IOException { + exchange.getResponseHeaders().set("Content-Type", type); + exchange.sendResponseHeaders(status, body.length); + exchange.getResponseBody().write(body); + } + + private static byte[] json(String text) { + return text.getBytes(StandardCharsets.UTF_8); + } + + private static Path ecKey(String tag) throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("EC"); + generator.initialize(new ECGenParameterSpec("secp256r1")); + byte[] encoded = generator.generateKeyPair().getPrivate().getEncoded(); + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(encoded); + String pem = "-----BEGIN PRIVATE KEY-----\n" + body + "\n-----END PRIVATE KEY-----\n"; + Path path = Path.of(System.getProperty("java.io.tmpdir"), "saml2-sp-pep-" + tag + "-" + ProcessHandle.current().pid() + "-" + System.nanoTime() + ".pem"); + Files.writeString(path, pem); + return path.toAbsolutePath(); + } + + private static SamlLogin login() { + SamlLogin login = new SamlLogin(); + login.nameId = "alice"; + login.attributes.put("uid", List.of("alice")); + return login; + } + + private static Map base() { + Map out = new LinkedHashMap<>(); + out.put("entityId", StubIdp.SP_ENTITY); + out.put("acsUrl", StubIdp.ACS); + out.put("privateKey", StubIdp.SP_KEY); + out.put("certificate", StubIdp.SP_CERT); + out.put("idpMetadata", StubIdp.idpMetadata(null)); + return out; + } +} diff --git a/library/src/test/java/com/iyasec/saml/pep/PepTest.java b/library/src/test/java/com/iyasec/saml/pep/PepTest.java new file mode 100644 index 0000000..e74bbef --- /dev/null +++ b/library/src/test/java/com/iyasec/saml/pep/PepTest.java @@ -0,0 +1,143 @@ +// SPDX-FileCopyrightText: 2026 Iya CyberSecurity Solutions, LLC +// SPDX-License-Identifier: MIT +package com.iyasec.saml.pep; + +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.saml.Config; +import com.iyasec.saml.Keys; +import com.iyasec.saml.SamlError; +import com.iyasec.saml.SamlLogin; +import com.iyasec.saml.ServiceProvider; +import com.iyasec.saml.StubIdp; +import com.iyasec.saml.ssf.MemorySessionIndex; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** The embedded PEP's SAML wiring. Nothing here calls {@code Pep.start}. */ +class PepTest { + @Test + void usernamePrefersTheFirstAttributeThenFallsThrough() { + SamlLogin login = new SamlLogin(); + assertNull(login.username()); + login.attributes.put("uid", List.of("")); + login.attributes.put("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", List.of("adfs")); + assertEquals("adfs", login.username()); + login.attributes.put("preferred_username", List.of("preferred")); + assertEquals("preferred", login.username()); + login.attributes.put("username", List.of("real")); + assertEquals("real", login.username()); + login.attributes.put("urn:oid:0.9.2342.19200300.100.1.1", List.of("ldap")); + assertEquals("real", login.username()); + } + + @Test + void subjectIdIsTheUsernameElseTheNameId() { + SamlLogin login = new SamlLogin(); + login.nameId = "transient-handle"; + login.attributes.put("mail", List.of("a@b.test")); + login.attributeFriendlyNames.put("mail", "email"); + login.authnContextClassRef = "urn:example:acr"; + login.authnInstant = Instant.ofEpochSecond(1_700_000_000L); + login.attributes.put("amr", List.of("pwd")); + var subject = SamlPep.subjectOf(login); + assertEquals("transient-handle", subject.id); + assertEquals("a@b.test", subject.properties.get("mail").asText()); + assertEquals("a@b.test", subject.properties.get("email").asText()); + assertEquals("urn:example:acr", subject.properties.get("acr").asText()); + assertEquals(1_700_000_000L, subject.properties.get("auth_time").asLong()); + assertEquals("pwd", subject.properties.get("amr").get(0).asText()); + login.attributes.put("uid", List.of("alice")); + assertEquals("alice", SamlPep.subjectOf(login).id); + } + + @Test + void pepSectionDefaultsDoNotBuildAPep() throws Exception { + Path dir = Files.createTempDirectory("saml-pep"); + String ca = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n"; + Map config = base(); + config.put("idpCa", ca); + config.put("ssf", Map.of("transmitter", "https://idp.test")); + config.put("pep", Map.of("name", "pep-test", "assertionKey", "generated/pep-key.pem")); + Config.Resolved resolved = Config.resolveConfig(config, dir.toString()); + assertEquals(Boolean.TRUE, resolved.pep.get("signals")); + assertEquals(ca, resolved.pep.get("tlsCa")); + assertTrue(String.valueOf(resolved.pep.get("assertionKey")).endsWith("/generated/pep-key.pem")); + config.put("signals", false); + assertEquals(Boolean.FALSE, Config.resolveConfig(config, dir.toString()).pep.get("signals")); + config.remove("pep"); + assertNull(Config.resolveConfig(config, dir.toString()).pep); + config.put("pep", "no"); + SamlError bad = assertThrows(SamlError.class, () -> Config.resolveConfig(config, dir.toString())); + assertTrue(bad.getMessage().contains("pep must be an object")); + } + + @Test + void ssfClientCertificateAndKeyGoTogether() { + Map missing = base(); + missing.put("ssf", Map.of("transmitter", "https://idp.test", "clientKey", StubIdp.SP_KEY)); + SamlError alone = assertThrows(SamlError.class, () -> Config.resolveConfig(missing, null)); + assertTrue(alone.getMessage().contains("go together")); + Map both = base(); + both.put("ssf", Map.of("transmitter", "https://idp.test", "clientCertificate", StubIdp.SP_CERT, "clientKey", StubIdp.SP_KEY)); + Config.Resolved resolved = Config.resolveConfig(both, null); + assertTrue(resolved.ssfClientKey.contains("PRIVATE KEY")); + assertTrue(resolved.ssfClientCertificate.contains("CERTIFICATE")); + } + + @Test + void thePepKeyMustDifferFromTheSpKeyAndTheReceiverKey() throws Exception { + Path dir = Files.createTempDirectory("saml-pep-key"); + Path key = dir.resolve("pep-key.pem"); + Files.writeString(key, StubIdp.SP_KEY); + Map section = new LinkedHashMap<>(); + section.put("name", "pep-test"); + section.put("assertionKey", key.toString()); + SamlError sp = assertThrows(SamlError.class, () -> SamlPep.build(section, "https://idp.test/saml2", StubIdp.SP_ENTITY, StubIdp.SP_KEY, null)); + assertTrue(sp.getMessage().contains("privateKey"), sp.getMessage()); + String other = Keys.createSelfSigned("other.test", 1, 2048).privateKeyPem(); + SamlError receiver = assertThrows(SamlError.class, () -> SamlPep.build(section, "https://idp.test/saml2", StubIdp.SP_ENTITY, other, StubIdp.SP_KEY)); + assertTrue(receiver.getMessage().contains("ssf.clientKey"), receiver.getMessage()); + } + + @Test + void anUntrackedOrExpiredSessionIsDeniedWithoutAPep() { + ServiceProvider sp = ServiceProvider.create(base()); + assertNull(sp.pep()); + SamlLogin login = new SamlLogin(); + login.nameId = "alice"; + MemorySessionIndex sessions = new MemorySessionIndex(); + Decision missing = sp.decideSession(sessions, "sid", login, Access.of("read", "order", "42")); + assertEquals(403, missing.httpStatus()); + assertEquals("no signed-in session", missing.why()); + sessions.add(new MemorySessionIndex.Tracked("sid", "alice", null, null, Instant.now().minusSeconds(5))); + Decision expired = sp.decideSession(sessions, "sid", login, Access.of("read", "order", "42")); + assertEquals("no signed-in session", expired.why()); + sessions.add(new MemorySessionIndex.Tracked("live", "alice", null, null, null)); + Decision open = sp.decideSession(sessions, "live", login, Access.of("read", "order", "42")); + assertEquals(403, open.httpStatus()); + assertEquals("no pep section is configured", open.why()); + assertFalse(open.isPermit()); + } + + private static Map base() { + Map out = new LinkedHashMap<>(); + out.put("entityId", StubIdp.SP_ENTITY); + out.put("acsUrl", StubIdp.ACS); + out.put("privateKey", StubIdp.SP_KEY); + out.put("certificate", StubIdp.SP_CERT); + out.put("idpMetadata", StubIdp.idpMetadata(null)); + return out; + } +} diff --git a/library/src/test/resources/authzen/application.xml b/library/src/test/resources/authzen/application.xml new file mode 100644 index 0000000..d0d64ae --- /dev/null +++ b/library/src/test/resources/authzen/application.xml @@ -0,0 +1,49 @@ + + + + + + + + + invoice + + + + + + + + + + + view + + + + + + + + + + + + pay + + + + + + + + access + + + + + + + + urn:saml-sp:authzen:settlements + diff --git a/library/src/test/resources/authzen/cases.json b/library/src/test/resources/authzen/cases.json new file mode 100644 index 0000000..eeccef8 --- /dev/null +++ b/library/src/test/resources/authzen/cases.json @@ -0,0 +1,153 @@ +{ + "about": "saml2-sp's own AuthZEN cases for the embedded Remote PEP (#40). Each case is a SAML sign-in (a SamlLogin), an Access and the answer the host must see. src/authzen_test.rs runs them offline through a local-mode ServiceProvider against a stub PDP serving these rows and the *.xml policies; scripts/live_authzen.py runs every case through a central and a local ServiceProvider against a fresh iya-sts and requires central == local == expect. The *.alfa files are what iya-sts is given; the *.xml files are what iya-sts stored for them (fetched from a live run, see docs/remote-pep.md).", + "application": "the SP's entityId: the bound application", + "supportedObligations": ["step-up"], + "directory": { + "azn-carol": {"cn": "Carol Ledger", "givenName": "Carol", "sn": "Ledger", "displayName": "Carol Ledger", "mail": "carol@saml-sp.test"} + }, + "catalogue": [ + {"object": "subject", "property": "acr", "attributeId": "urn:saml-sp:acr"}, + {"object": "subject", "property": "clearance", "attributeId": "urn:saml-sp:clearance", "dataType": "integer"}, + {"object": "subject", "property": "team", "attributeId": "urn:saml-sp:team", "multiplicity": "bag"}, + {"object": "subject", "property": "contractor", "attributeId": "urn:saml-sp:contractor", "dataType": "boolean"}, + {"object": "resource", "property": "sensitivity", "attributeId": "urn:saml-sp:sensitivity", "category": "resource", "dataType": "double"}, + {"object": "resource", "property": "retainUntil", "attributeId": "urn:saml-sp:retain-until", "dataType": "dateTime"}, + {"object": "resource", "property": "owner.region", "attributeId": "urn:saml-sp:owner-region"}, + {"object": "resource", "property": "labels", "attributeId": "urn:saml-sp:label", "multiplicity": "bag"}, + {"object": "action", "property": "reason", "attributeId": "urn:saml-sp:reason", "category": "action"}, + {"object": "context", "property": "channel", "attributeId": "urn:saml-sp:channel", "category": "environment"}, + {"object": "context", "property": "device.managed", "attributeId": "urn:saml-sp:device-managed", "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:environment", "dataType": "http://www.w3.org/2001/XMLSchema#boolean"} + ], + "policies": { + "root": {"name": "saml-sp-authzen-root", "alfa": "root.alfa", "xacml": "root.xml", "kind": "PolicySet", "policyId": "urn:saml-sp:authzen:root"}, + "shared": {"name": "saml-sp-authzen-settlements", "alfa": "shared.alfa", "xacml": "shared.xml", "kind": "Policy", "policyId": "urn:saml-sp:authzen:settlements"}, + "application": {"alfa": "application.alfa", "xacml": "application.xml", "kind": "PolicySet", "policyId": "urn:saml-sp:authzen:application", "references": ["urn:saml-sp:authzen:settlements"]} + }, + "phases": { + "root": "the realm root decides: the application enforces no fine-grained authorization", + "application": "the application enforces fine-grained authorization; its own policy (a PolicySet referencing the shared settlements policy) decides, never the root" + }, + "logins": { + "carol": { + "nameId": "_azn-transient-1", + "acr": "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport", + "attributes": { + "urn:oid:0.9.2342.19200300.100.1.1": ["azn-carol"], + "uid": ["azn-carol"], + "urn:oid:0.9.2342.19200300.100.1.3": ["carol@saml-sp.test"], + "displayName": ["Carol Ledger"], + "clearance": ["4"], + "team": ["staff", "legal"], + "contractor": ["false"] + }, + "friendlyNames": {"urn:oid:0.9.2342.19200300.100.1.1": "uid", "urn:oid:0.9.2342.19200300.100.1.3": "mail"} + }, + "nobody": { + "nameId": "_azn-transient-2", + "acr": "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport", + "attributes": {"uid": ["azn-nobody"], "clearance": ["4"], "team": ["legal"], "contractor": ["false"]} + } + }, + "cases": [ + {"name": "permit: read with the acr the policy wants", "login": "carol", + "access": {"action": "read", "type": "dossier", "id": "d-1"}, "expect": {"decision": "Permit"}}, + {"name": "deny: the policy's own deny for another acr", "login": "carol", + "acr": "urn:oasis:names:tc:SAML:2.0:ac:classes:Password", + "access": {"action": "read", "type": "dossier", "id": "d-1"}, "expect": {"decision": "Deny"}}, + {"name": "missing claim: no AuthnContextClassRef, so no acr", "login": "carol", "acr": "", + "access": {"action": "read", "type": "dossier", "id": "d-1"}, "expect": {"decision": "Deny"}}, + {"name": "not applicable: a resource type no policy targets", "login": "carol", + "access": {"action": "read", "type": "parcel", "id": "p-1"}, "expect": {"decision": "Deny"}}, + {"name": "integer: a SAML string reaches an integer row", "login": "carol", + "access": {"action": "annotate", "type": "dossier", "id": "d-1"}, "expect": {"decision": "Permit"}}, + {"name": "integer: too low", "login": "carol", "attributes": {"clearance": ["2"]}, + "access": {"action": "annotate", "type": "dossier", "id": "d-1"}, "expect": {"decision": "Deny"}}, + {"name": "wrong type: a claim that is not an integer is refused", "login": "carol", "attributes": {"clearance": ["four"]}, + "access": {"action": "annotate", "type": "dossier", "id": "d-1"}, "expect": {"decision": "Deny"}}, + {"name": "friendly name: the claim under an OID Name, read by its FriendlyName", "login": "carol", + "attributes": {"clearance": null, "urn:oid:1.3.6.1.4.1.55555.7": ["5"]}, "friendlyNames": {"urn:oid:1.3.6.1.4.1.55555.7": "clearance"}, + "access": {"action": "annotate", "type": "dossier", "id": "d-1"}, "expect": {"decision": "Permit"}}, + {"name": "double and dateTime: typed resource properties", "login": "carol", + "access": {"action": "archive", "type": "dossier", "id": "d-2", "resource": {"sensitivity": 0.25, "retainUntil": "2027-03-01T00:00:00Z"}}, + "expect": {"decision": "Permit"}}, + {"name": "double: a string that parses at the row's type", "login": "carol", + "access": {"action": "archive", "type": "dossier", "id": "d-2", "resource": {"sensitivity": "0.25", "retainUntil": "2027-03-01T00:00:00Z"}}, + "expect": {"decision": "Permit"}}, + {"name": "double: above the limit", "login": "carol", + "access": {"action": "archive", "type": "dossier", "id": "d-2", "resource": {"sensitivity": 0.75, "retainUntil": "2027-03-01T00:00:00Z"}}, + "expect": {"decision": "Deny"}}, + {"name": "wrong type: a double that does not parse is refused", "login": "carol", + "access": {"action": "archive", "type": "dossier", "id": "d-2", "resource": {"sensitivity": "low", "retainUntil": "2027-03-01T00:00:00Z"}}, + "expect": {"decision": "Deny"}}, + {"name": "wrong type: a dateTime that does not parse is refused", "login": "carol", + "access": {"action": "archive", "type": "dossier", "id": "d-2", "resource": {"sensitivity": 0.25, "retainUntil": "next spring"}}, + "expect": {"decision": "Deny"}}, + {"name": "bag and nested path: the team bag and owner.region", "login": "carol", + "access": {"action": "share", "type": "dossier", "id": "d-3", "resource": {"owner": {"region": "emea"}}}, "expect": {"decision": "Permit"}}, + {"name": "bag: one SAML value reaches a bag row", "login": "carol", "attributes": {"team": ["legal"]}, + "access": {"action": "share", "type": "dossier", "id": "d-3", "resource": {"owner": {"region": "emea"}}}, "expect": {"decision": "Permit"}}, + {"name": "bag: not in the team", "login": "carol", "attributes": {"team": ["staff", "sales"]}, + "access": {"action": "share", "type": "dossier", "id": "d-3", "resource": {"owner": {"region": "emea"}}}, "expect": {"decision": "Deny"}}, + {"name": "nested path: another region", "login": "carol", + "access": {"action": "share", "type": "dossier", "id": "d-3", "resource": {"owner": {"region": "apac"}}}, "expect": {"decision": "Deny"}}, + {"name": "nested path: an undeclared sibling member is refused", "login": "carol", + "access": {"action": "share", "type": "dossier", "id": "d-3", "resource": {"owner": {"region": "emea", "city": "Paris"}}}, "expect": {"decision": "Deny"}}, + {"name": "resource bag and an action property", "login": "carol", + "access": {"action": "hold", "type": "dossier", "id": "d-4", "resource": {"labels": ["archive", "litigation"]}, "actionProperties": {"reason": "court-order"}}, + "expect": {"decision": "Permit"}}, + {"name": "null is refused", "login": "carol", + "access": {"action": "hold", "type": "dossier", "id": "d-4", "resource": {"labels": null}, "actionProperties": {"reason": "court-order"}}, + "expect": {"decision": "Deny"}}, + {"name": "context members: channel and the nested device.managed", "login": "carol", + "access": {"action": "export", "type": "dossier", "id": "d-5", "context": {"channel": "branch", "device": {"managed": true}}}, "expect": {"decision": "Permit"}}, + {"name": "boolean: the string true parses at a boolean row", "login": "carol", + "access": {"action": "export", "type": "dossier", "id": "d-5", "context": {"channel": "branch", "device": {"managed": "true"}}}, "expect": {"decision": "Permit"}}, + {"name": "wrong type: a number at a boolean row is refused", "login": "carol", + "access": {"action": "export", "type": "dossier", "id": "d-5", "context": {"channel": "branch", "device": {"managed": 1}}}, "expect": {"decision": "Deny"}}, + {"name": "wrong type: an array at a single row is refused", "login": "carol", + "access": {"action": "export", "type": "dossier", "id": "d-5", "context": {"channel": ["branch"], "device": {"managed": true}}}, "expect": {"decision": "Deny"}}, + {"name": "boolean claim: a contractor", "login": "carol", "attributes": {"contractor": ["true"]}, + "access": {"action": "export", "type": "dossier", "id": "d-5", "context": {"channel": "branch", "device": {"managed": true}}}, "expect": {"decision": "Deny"}}, + {"name": "wrong type: a boolean claim that does not parse is refused", "login": "carol", "attributes": {"contractor": ["yes"]}, + "access": {"action": "export", "type": "dossier", "id": "d-5", "context": {"channel": "branch", "device": {"managed": true}}}, "expect": {"decision": "Deny"}}, + {"name": "undeclared resource property: refused", "login": "carol", + "access": {"action": "read", "type": "dossier", "id": "d-1", "resource": {"colour": "red"}}, "expect": {"decision": "Deny"}}, + {"name": "undeclared context member: refused", "login": "carol", + "access": {"action": "read", "type": "dossier", "id": "d-1", "context": {"weather": "rain"}}, "expect": {"decision": "Deny"}}, + {"name": "undeclared claim: dropped, so the policy never sees it", "login": "carol", "attributes": {"department": ["finance"]}, + "access": {"action": "budget", "type": "dossier", "id": "d-6"}, "expect": {"decision": "Deny"}}, + {"name": "undeclared claim named as the XACML id: still dropped", "login": "carol", "attributes": {"urn:saml-sp:department": ["finance"]}, + "access": {"action": "budget", "type": "dossier", "id": "d-6"}, "expect": {"decision": "Deny"}}, + {"name": "context.application naming another application: the PEP keeps its own", "login": "carol", + "access": {"action": "read", "type": "dossier", "id": "d-1", "context": {"application": "https://elsewhere.saml-sp.test/app"}}, "expect": {"decision": "Permit"}}, + {"name": "directory attribute: sn from the PIP", "login": "carol", + "access": {"action": "audit", "type": "dossier", "id": "d-7"}, "expect": {"decision": "Permit"}}, + {"name": "directory attribute: a person the directory does not hold", "login": "nobody", + "access": {"action": "audit", "type": "dossier", "id": "d-7"}, "expect": {"decision": "Deny"}}, + {"name": "trusted fact: the protocol is authzen", "login": "carol", + "access": {"action": "inspect", "type": "dossier", "id": "d-8"}, "expect": {"decision": "Permit"}}, + {"name": "a processing error is no decision", "login": "carol", + "access": {"action": "tally", "type": "dossier", "id": "d-8"}, "expect": {"decision": "Unavailable"}}, + {"name": "obligation the host declared: handed under the Obligations Profile", "login": "carol", + "access": {"action": "approve", "type": "dossier", "id": "d-9"}, + "expect": {"decision": "Permit", "obligations": [{"type": "step-up", "properties": {"acr_value": "urn:saml-sp:acr:two-factor"}}]}}, + {"name": "obligation the host did not declare: a Deny", "login": "carol", + "access": {"action": "notify", "type": "dossier", "id": "d-9"}, "expect": {"decision": "Deny"}}, + {"name": "the log obligation is discharged by the PDP side", "login": "carol", + "access": {"action": "list", "type": "dossier", "id": "d-9"}, "expect": {"decision": "Permit"}}, + {"name": "decide_session: a tracked session is asked", "login": "carol", "session": "tracked", + "access": {"action": "read", "type": "dossier", "id": "d-1"}, "expect": {"decision": "Permit"}}, + {"name": "decide_session: an ended session is a Deny without asking", "login": "carol", "session": "ended", + "access": {"action": "read", "type": "dossier", "id": "d-1"}, "expect": {"decision": "Deny"}}, + {"name": "fga: the application's own rule", "phase": "application", "login": "carol", + "access": {"action": "view", "type": "invoice", "id": "i-1"}, "expect": {"decision": "Permit"}}, + {"name": "fga: a rule in the policy the application's policy references", "phase": "application", "login": "carol", + "access": {"action": "settle", "type": "invoice", "id": "i-1"}, "expect": {"decision": "Permit"}}, + {"name": "fga: a rule on the stage the service adds for an application's policy", "phase": "application", "login": "carol", + "access": {"action": "pay", "type": "invoice", "id": "i-1"}, "expect": {"decision": "Permit"}}, + {"name": "fga: nothing permits", "phase": "application", "login": "carol", + "access": {"action": "delete", "type": "invoice", "id": "i-1"}, "expect": {"decision": "Deny"}}, + {"name": "fga: the root is not consulted", "phase": "application", "login": "carol", + "access": {"action": "read", "type": "dossier", "id": "d-1"}, "expect": {"decision": "Deny"}} + ] +} diff --git a/library/src/test/resources/authzen/root.xml b/library/src/test/resources/authzen/root.xml new file mode 100644 index 0000000..d99adb4 --- /dev/null +++ b/library/src/test/resources/authzen/root.xml @@ -0,0 +1,319 @@ + + + + + + + + + dossier + + + + + + + + + + + read + + + + + + + + urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport + + + + + + + + + + + + annotate + + + + + + + + 3 + + + + + + + + + + + + archive + + + + + + + + 0.5 + + + + + + + + 2026-01-01T00:00:00Z + + + + + + + + + + + + share + + + + + + + + legal + + + + + + + + emea + + + + + + + + + + + + hold + + + + + + + + litigation + + + + + + + + court-order + + + + + + + + + + + + export + + + + + + + + branch + + + + + + + + true + + + + + + + + false + + + + + + + + + + + + audit + + + + + + + + Ledger + + + + + + + + + + + + budget + + + + + + + + finance + + + + + + + + + + + + inspect + + + + + + + + authzen + + + + + + + + + + + + tally + + + + + + + + + + + legal + + + + + + + + + approve + + + + + + + + + urn:saml-sp:acr:two-factor + + + + + + + + + + notify + + + + + + + + + records@saml-sp.test + + + a dossier was shared + + + + + + + + + + list + + + + + + + + + dossiers listed + + + + + + + + + diff --git a/library/src/test/resources/authzen/shared.xml b/library/src/test/resources/authzen/shared.xml new file mode 100644 index 0000000..6d34445 --- /dev/null +++ b/library/src/test/resources/authzen/shared.xml @@ -0,0 +1,25 @@ + + + + + + + invoice + + + + + + + + + + + settle + + + + + + + diff --git a/scripts/configure_iya_sts.py b/scripts/configure_iya_sts.py index e9b01d0..8721480 100644 --- a/scripts/configure_iya_sts.py +++ b/scripts/configure_iya_sts.py @@ -9,6 +9,15 @@ It writes iya-sts's listener CA trust chain (leaf, TLS Issuing CA, Intermediate, Root) to the file idpCa names, every run (scripts/trust_chain.py). The demo image build copies that file in, so rebuild the image after running this against a different iya-sts. + +--pep [local|central] (local when left out) also sets the demo up with its embedded PEP (docs/remote-pep.md, steps 2 to 6): +the PEP's service account in remote-peps; a P-256 key made here with openssl in generated/pep-key.pem +beside the configuration (0600, never printed, kept out of the image by .dockerignore), certified from +its own request with the PEP bound to the demo's application; the catalogue row the demo's policy reads; +and the demo application's OWN policy, which it then enforces, so the realm root is never touched. It +writes the `pep` section into the configuration. Run again against the same iya-sts, it keeps the +account, the key and the policy (an administrator's edits survive), binds the PEP again and switches +the mode. """ from __future__ import annotations @@ -17,6 +26,7 @@ import json import os import re +import secrets import ssl import subprocess import sys @@ -37,10 +47,61 @@ } MULTIPLE_ACCOUNTS = {"key": "authn.multipleAccounts", "value": True} +# The embedded PEP (--pep). PEP_KEY is relative to the configuration's directory. +SSF_CLIENT_KEY = "generated/ssf-client.key" +SSF_CLIENT_CERT = "generated/ssf-client.crt" +SSF_CLIENT_LABEL = "saml2-sp demo SSF" +RETIRED_SP_CERTS = "generated/retired-sp-certificates.txt" +PEP_MODES = ("central", "local") +PEP_NAME = "pep-saml-demo" +PEP_KEY = "generated/pep-key.pem" +PEP_GROUP = "remote-peps" +PEP_EVENT = "urn:iya:sts:secevent:event-type:pep-policies-changed" +ACR_ATTRIBUTE = "urn:example:acr" +TEST_ATTRIBUTE = "attr1" +TEST_ATTRIBUTE_VALUE = "abc123" +TEST_ATTRIBUTE_ID = "urn:sts:xacml:attribute:" + TEST_ATTRIBUTE +ATTRIBUTE_PROTECTED = "attribute-protected" +OWN_POLICY_IDS = ("urn:saml-sp-demo:samlspdemo:orders",) + + +def orders_policy(namespace: str = "samlspdemo", read_effect: str = "permit") -> str: + """The demo application's own policy, in ALFA.""" + needs_acr = " condition integerGreaterThan(stringBagSize(acr), 0)\n" if read_effect == "permit" else "" + return ( + f"namespace {namespace} {{\n" + ' attribute action { category = actionCat id = "urn:oasis:names:tc:xacml:1.0:action:action-id" type = string }\n' + ' attribute kind { 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:saml-sp-demo:{namespace}:orders"\n' + " apply firstApplicable\n" + " rule readAnOrder {\n" + f" {read_effect}\n" + ' target clause action == "read"\n' + ' target clause kind == "order"\n' + f"{needs_acr}" + " }\n" + " rule readAttributeProtected {\n" + " permit\n" + ' target clause action == "read"\n' + f' target clause kind == "{ATTRIBUTE_PROTECTED}"\n' + f' target clause {TEST_ATTRIBUTE} == "{TEST_ATTRIBUTE_VALUE}"\n' + " }\n" + " rule nothingElse {\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 [local|central]] [--pep-name name] + [--dry-run] --config The demo's SAML configuration (default: demo/saml.json) --idp iya-sts's base URL; the realm's, e.g. https://host/realm/acme, for a trust realm @@ -49,9 +110,25 @@ def usage() -> str: and keep their paths (default: unset; $PUBLIC_URL). Without it, a loopback entityID and ACS follow the running demo's PORT, then $PORT. A non-loopback URL is left as written. --test-user The test user to create (default: saml-demo-user). Its password is - $SAML_DEMO_USER_PASSWORD, or one is generated and printed once. With - $SAML_DEMO_USER_PASSWORD set, an existing user's password is replaced. + $SAML_DEMO_USER_PASSWORD, or one is generated and written to a file beside the + key pair (mode 0600); only the path is printed. With $SAML_DEMO_USER_PASSWORD set, + an existing user's password is replaced. --no-test-user Do not create a test user. + --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, a key of its own in generated/pep-key.pem (0600), its certificate and + binding, the catalogue row, the demo application's own policy (enforced), and the + `pep` section in the configuration. Safe to run again; the mode is switched. + --pep-name The PEP's service account (default: pep-saml-demo). + +With an ssf block (signals on), the Shared Signals receiver authenticates to iya-sts's /ssf/* +with a TLS client certificate the realm issues the application (issue-tls-client-certificate, +urn:sts:application:): generated/ssf-client.key (0600, never printed) and +generated/ssf-client.crt, named in the configuration's ssf.clientKey / ssf.clientCertificate. +A certificate the realm still lists for the application is kept on later runs. The SP's own +certificate is no longer added to iya-sts's client-certificate truststore; an anchor an +earlier run added (and the copy stored on the application) is removed once the new +certificate is in place. --dry-run Print what would be done, and send nothing. The management API secret is ADMIN_API_CLIENT_SECRET or STS_ADMIN_API_CLIENT_SECRET.""" @@ -133,6 +210,8 @@ def parse_args(argv: list[str], env: dict | None = None) -> Args: public_url=str(env.get("PUBLIC_URL") or "http://localhost:3000").rstrip("/"), public_url_given=bool(env.get("PUBLIC_URL")), test_user="saml-demo-user", + pep="", + pep_name=PEP_NAME, dry_run=False, help=False, ) @@ -160,6 +239,17 @@ def value() -> str: out.test_user = value().strip() elif arg == "--no-test-user": out.test_user = "" + elif arg == "--pep": + if index + 1 < len(argv) and not argv[index + 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") elif arg == "--dry-run": out.dry_run = True else: @@ -298,22 +388,71 @@ def plan_for(files: DemoFiles, base: str, test_user: str, sp_metadata_xml: str) calls.insert(2, {"method": "POST", "path": f"{base}/admin-api/applications/set", "why": f"encrypt the assertion: {attribute}", "body": {"application": files.entity_id, "attribute": attribute, "value": value}}) if files.ssf_transmitter: - calls[-1:-1] = ssf_calls(files, base, "") + calls[-1:-1] = ssf_calls(files, base) + ssf_client_plan(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}}) + calls.append({"method": "POST", "path": f"{base}/admin-api/policies/define-person-attribute", + "why": f"define the realm's custom attribute {TEST_ATTRIBUTE} (unless it is), with an admin:security token", + "body": define_attribute_body()}) + 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 -def ssf_calls(files: DemoFiles, base: str, certificate_pem: str) -> list[dict]: +def define_attribute_body() -> dict: + return {"name": TEST_ATTRIBUTE, "label": "Attribute 1", "syntax": "string", "multiValued": False, + "description": "The demo's attribute-protected resource is permitted when this is abc123."} + + +def set_test_attribute(call, user: str) -> bool: + """The realm's custom attribute attr1, and the test user's value of it. + `call(path, body, security)` answers {"status", "body"} and does not stop on a refusal.""" + defined = call("/policies/define-person-attribute", define_attribute_body(), True) + body = defined["body"] if isinstance(defined["body"], dict) else {} + words = (" ".join(_errors_of(body)) + " " + str(body.get("error_description") or body.get("error") or "")).lower() + not_allowed = defined["status"] in (401, 403) or "security administrator" in words or "insufficient_scope" in words + if not not_allowed and not (defined["status"] == 200 and body.get("ok") is not False): + if "already" not in words and "exists" not in words: + raise SystemExit(f"defining the custom attribute {TEST_ATTRIBUTE}: refused ({defined['status']}): {json.dumps(body)[:400]}") + answered = call("/users/set-attribute", {"user": user, "attribute": TEST_ATTRIBUTE, "value": TEST_ATTRIBUTE_VALUE}, False) + reply = answered["body"] if isinstance(answered["body"], dict) else {} + if answered["status"] == 200 and reply.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(reply))[:300]}") + return False + + +def ssf_calls(files: DemoFiles, base: str) -> list[dict]: + """The scope the application declares and SSF_MANAGE. Its TLS client certificate is the realm's.""" return [ {"method": "POST", "path": f"{base}/admin-api/applications/add", "why": "declare the Shared Signals write scope", "body": {"application": files.entity_id, "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.entity_id}}, - {"method": "POST", "path": f"{base}/admin-api/tls/trust/add", "why": "trust the SP certificate at the TLS handshake", - "body": {"certificates": certificate_pem}}, - {"method": "POST", "path": f"{base}/admin-api/applications/add-certificate", "why": "store the SP certificate on the application", - "body": {"application": files.entity_id, "certificate": certificate_pem}}, + ] + + +def ssf_client_plan(files: DemoFiles, base: str) -> list[dict]: + return [ + {"method": "GET", "path": f"{base}/admin-api/applications?application={urllib.parse.quote(files.entity_id, safe='')}", + "why": f"keep {SSF_CLIENT_CERT} when the realm still lists it for the application", "body": None}, + {"method": "POST", "path": f"{base}/admin-api/applications/issue-tls-client-certificate", + "why": f"(otherwise) the realm issues the receiver its TLS client certificate: {SSF_CLIENT_KEY} (0600), {SSF_CLIENT_CERT}", + "body": {"application": files.entity_id, "password": "", "keyAlg": "ec-p256", "label": SSF_CLIENT_LABEL}}, + {"method": "POST", "path": f"{base}/admin-api/tls/trust/remove", + "why": "take off the SP certificate's trust anchor an earlier run added (if held)", "body": {"fingerprint": ""}}, + {"method": "POST", "path": f"{base}/admin-api/applications/remove-certificate", + "why": "and its copy stored on the application (if stored)", "body": {"application": files.entity_id, "sha256": ""}}, ] @@ -357,7 +496,7 @@ def _request(url: str, method: str, headers: dict, body: bytes | None, ca: str | return err.code, err.read() -def _json(url: str, ca: str | None, method: str = "GET", headers: dict | None = None, body: str | None = None) -> dict: +def _json(url: str, ca: str | None, method: str = "GET", headers: dict | None = None, body: str | None = None, refuse_denied: bool = True) -> dict: raw_headers = dict(headers or {}) payload = None if body is None else body.encode() status, data = _request(url, method, raw_headers, payload, ca) @@ -366,7 +505,7 @@ def _json(url: str, ca: str | None, method: str = "GET", headers: dict | None = parsed = json.loads(text) if text else {} except json.JSONDecodeError as err: raise SystemExit(f"{method} {url} answered {status} with non-JSON: {text[:300]}") from err - if status in (401, 403): + if refuse_denied and status in (401, 403): raise SystemExit(f"{method} {url} answered {status}: {json.dumps(parsed)[:300]}") return {"status": status, "body": parsed} @@ -375,8 +514,8 @@ def _errors_of(body: dict) -> list[str]: return [str(item) for item in (body.get("errors") or [])] -def mint_admin_token(origin: str, base: str, ca: str | None, secret: str) -> str: - form = urllib.parse.urlencode({"grant_type": "client_credentials", "scope": "admin:read admin:write", "resource": f"{base}/admin-api"}) +def mint_admin_token(origin: str, base: str, ca: str | None, secret: str, scope: str = "admin:read admin:write") -> str: + 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) token = reply["body"].get("access_token") if isinstance(reply["body"], dict) else None @@ -422,6 +561,9 @@ def main(argv: list[str] | None = None) -> None: for call in plan_for(files, base, args.test_user, xml): body = f"\n{json.dumps(call['body'], indent=2)}" if call.get("body") is not None else "" print(f"{call['method']} {call['path']} # {call['why']}{body}") + 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.") @@ -453,6 +595,18 @@ def api(path: str, body) -> dict: "accept": "application/json", "content-type": "application/json", "authorization": f"Bearer {token}", }, json.dumps(body)) + security_token: list[str] = [] + + def call(path: str, body, security: bool = False) -> dict: + bearer = token + if security: + if not security_token: + security_token.append(mint_admin_token(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), refuse_denied=False) + create, upload = plan_for(files, base, args.test_user, sp_metadata_xml)[:2] created = api("/applications/create", create["body"]) if created["body"].get("ok"): @@ -477,16 +631,22 @@ def api(path: str, body) -> dict: raise SystemExit(f"setting authn.multipleAccounts was refused: {json.dumps(multiple['body'])[:300]}") print("authn.multipleAccounts is on: one browser may hold several signed-in people.") if files.ssf_transmitter: - certificate_pem = Path(files.cert).read_text(encoding="utf-8") - for call in ssf_calls(files, base, certificate_pem): - path = call["path"][len(f"{base}/admin-api"):] - reply = api(path, call["body"]) + for step in ssf_calls(files, base): + path = step["path"][len(f"{base}/admin-api"):] + reply = api(path, step["body"]) errors = " ".join(_errors_of(reply["body"])) if not reply["body"].get("ok") and not re.search(r"already", errors, re.I): - raise SystemExit(f"{call['why']}: refused: {json.dumps(reply['body'])[:400]}") + raise SystemExit(f"{step['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.entity_id} holds SSF_MANAGE and authenticates to /ssf/* with its own certificate (mutual TLS).") + print(f" {step['why']}: already so ({errors[:160]})") + + def get_page(path: str) -> dict: + return _json(f"{base}/admin-api{path}", ca, "GET", {"accept": "application/json", "authorization": f"Bearer {token}"}) + + issue_ssf_client_certificate(api, get_page, files, args.config) + retire_sp_trust(call, files, args.config) + print(f"Shared Signals: {files.entity_id} holds SSF_MANAGE and authenticates to /ssf/* by mutual TLS with the " + "TLS client certificate the realm issued it (ssf.clientCertificate), not the SAML key pair.") url = idp_metadata_url(base, files.entity_id) status, data = _request(url, "GET", {"accept": "application/samlmetadata+xml"}, None, ca) if status != 200: @@ -534,9 +694,271 @@ def api(path: str, body) -> dict: with os.fdopen(descriptor, "w", encoding="utf-8") as out: out.write(made["body"]["password"] + "\n") print(f"Generated a password for {args.test_user}; it is in {saved} (readable by you only).") + set_test_attribute(call, args.test_user) + if args.pep: + def get(path: str) -> dict: + return _json(f"{base}/admin-api{path}", ca, "GET", {"accept": "application/json", "authorization": f"Bearer {token}"}) + setup_pep(api, get, files, args.config, args.pep_name, args.pep) + print(f"pep: {args.pep_name}, {args.pep} (GET /orders/42 and GET /{ATTRIBUTE_PROTECTED} need a sign-in; any other method is denied)") print("Done. Start the demo with: docker compose up --build (the build copies idpCa's trust chain in)") +def _pem_blocks(text: str) -> list[str]: + return re.findall(r"-----BEGIN CERTIFICATE-----[A-Za-z0-9+/=\s]+?-----END CERTIFICATE-----", text or "") + + +def _same_pem(a: str, b: str) -> bool: + return re.sub(r"\s+", "", a or "") == re.sub(r"\s+", "", b or "") and bool(a) + + +def certificate_sha256(pem_text: str) -> str: + import hashlib + blocks = _pem_blocks(pem_text) + if not blocks: + return "" + return hashlib.sha256(ssl.PEM_cert_to_DER_cert(blocks[0])).hexdigest() + + +def ssf_client_paths(config_path: str) -> dict: + raw = json.loads(Path(config_path).read_text(encoding="utf-8")) + ssf = raw.get("ssf") if isinstance(raw.get("ssf"), dict) else {} + base = Path(config_path).resolve().parent + out = {} + for name, member, default in (("key", "clientKey", SSF_CLIENT_KEY), ("cert", "clientCertificate", SSF_CLIENT_CERT)): + value = ssf.get(member) if isinstance(ssf.get(member), str) and ssf.get(member) else default + if "-----BEGIN" in value or value.startswith("env:"): + raise SystemExit(f"{config_path}'s ssf.{member} must be a file path for this script to write") + path = Path(_expand_path(value)) + out[name] = str(path if path.is_absolute() else (base / path).resolve()) + out[name + "_value"] = value + return out + + +def held_tls_certificates(get, app: str) -> list[dict]: + page = get("/applications?application=" + urllib.parse.quote(app, safe=""))["body"] + found = [] + + def walk(value): + if isinstance(value, dict): + if value.get("serialHex") and value.get("certificatePem"): + found.append(value) + for inner in value.values(): + walk(inner) + elif isinstance(value, list): + for inner in value: + walk(inner) + + walk(page) + return found + + +def _decrypt_key(encrypted: str, password: str, key_path: str) -> None: + descriptor = os.open(key_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + os.close(descriptor) + env = dict(os.environ, SAML_SSF_CLIENT_KEY_PASSWORD=password) + done = subprocess.run(["openssl", "pkey", "-passin", "env:SAML_SSF_CLIENT_KEY_PASSWORD", "-out", key_path], + input=encrypted, capture_output=True, text=True, env=env, check=False) + if done.returncode != 0: + raise SystemExit(f"the issued key could not be opened: {done.stderr.strip()[:200]}") + os.chmod(key_path, 0o600) + + +def write_ssf_client_section(config_path: str, paths: dict) -> None: + path = Path(config_path) + raw = json.loads(path.read_text(encoding="utf-8")) + ssf = raw.get("ssf") if isinstance(raw.get("ssf"), dict) else {} + ssf["clientCertificate"] = paths["cert_value"] + ssf["clientKey"] = paths["key_value"] + raw["ssf"] = ssf + path.write_text(json.dumps(raw, indent=2) + "\n", encoding="utf-8") + + +def issue_ssf_client_certificate(api, get, files: DemoFiles, config_path: str, decrypt=_decrypt_key) -> bool: + paths = ssf_client_paths(config_path) + on_disk = Path(paths["cert"]).read_text(encoding="utf-8") if Path(paths["cert"]).exists() else "" + leaf = (_pem_blocks(on_disk) or [""])[0] + if leaf and Path(paths["key"]).exists(): + for held in held_tls_certificates(get, files.entity_id): + if str(held.get("state") or "valid") == "valid" and _same_pem(held.get("certificatePem") or "", leaf): + write_ssf_client_section(config_path, paths) + print(f"The receiver's TLS client certificate (serial {held.get('serialHex')}) is one the realm issued to " + f"{files.entity_id} and still lists; kept.") + return False + password = secrets.token_urlsafe(24) + answered = api("/applications/issue-tls-client-certificate", { + "application": files.entity_id, "password": password, "keyAlg": "ec-p256", "label": SSF_CLIENT_LABEL, + }) + body = answered["body"] if isinstance(answered["body"], dict) else {} + if not body.get("ok"): + shown = {k: v for k, v in body.items() if k != "files"} + raise SystemExit(f"issuing {files.entity_id} a TLS client certificate 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 SystemExit("the issued certificate's answer carried no key or certificate") + Path(paths["key"]).parent.mkdir(parents=True, exist_ok=True) + decrypt(encrypted, password, paths["key"]) + pems = [leaf] + [pem for pem in (chain if isinstance(chain, list) else [chain]) if pem and not _same_pem(pem, leaf)] + Path(paths["cert"]).write_text("".join(pem if pem.endswith("\n") else pem + "\n" for pem in pems), encoding="utf-8") + write_ssf_client_section(config_path, paths) + print(f"Issued {files.entity_id} a TLS client certificate from the realm's CA (serial {issued.get('serialHex')}, " + f"{issued.get('implicitName') or 'urn:sts:application:' + files.entity_id}) for Shared Signals mutual TLS;") + print(f" wrote {paths['key']} (0600) and {paths['cert']}, named in ssf.clientKey / ssf.clientCertificate.") + return True + + +def retire_sp_trust(call, files: DemoFiles, config_path: str) -> list[str]: + retired_file = Path(config_path).resolve().parent / RETIRED_SP_CERTS + prints = [line.strip() for line in (retired_file.read_text(encoding="utf-8").splitlines() if retired_file.exists() else []) if line.strip()] + current = certificate_sha256(Path(files.cert).read_text(encoding="utf-8")) if Path(files.cert).exists() else "" + if current and current not in prints: + prints.insert(0, current) + removed, keep = [], [] + for fingerprint in prints: + settled = True + for path, body, absent in (("/tls/trust/remove", {"fingerprint": fingerprint}, "holds no anchor"), + ("/applications/remove-certificate", {"application": files.entity_id, "sha256": fingerprint}, "stores no certificate")): + answer = call(path, body) + reply = answer["body"] if isinstance(answer["body"], dict) else {} + if answer["status"] == 200 and reply.get("ok") is not False: + removed.append(f"{path}:{fingerprint}") + continue + if absent in " ".join(_errors_of(reply)).lower(): + continue + settled = False + print(f" {path} for {fingerprint[:16]}…: refused ({answer['status']}): {' '.join(_errors_of(reply))[:200]}") + if not settled and fingerprint != current: + keep.append(fingerprint) + if retired_file.exists() or keep: + retired_file.write_text("".join(f"{line}\n" for line in keep), encoding="utf-8") + for item in removed: + what, fingerprint = item.split(":", 1) + print(f"Removed the SP certificate {fingerprint[:16]}… from iya-sts ({'trust anchor' if 'trust' in what else 'stored on the application'}).") + return removed + + +def pep_plan(files: DemoFiles, base: str, name: str, mode: str) -> list[str]: + app = files.entity_id + return [ + f"GET {base}/admin-api/users?user={name} # the PEP's service account: created only if unknown", + 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 at {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, bind {name} 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 (when {app} enforces none yet, or this script's own)", + f"POST {base}/admin-api/applications/fga-enable # {app} enforces its own policy (the realm root is untouched)", + 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}\"}} into the configuration", + ] + + +def make_pep_key(key_file: Path) -> None: + key_file.parent.mkdir(parents=True, exist_ok=True) + old = os.umask(0o077) + try: + 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 SystemExit("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: + made = subprocess.run(["openssl", "req", "-new", "-key", str(key_file), "-subj", f"/CN={name}"], + check=False, capture_output=True, text=True) + if made.returncode != 0 or "BEGIN CERTIFICATE REQUEST" not in made.stdout: + raise SystemExit("openssl could not make the PEP's certificate request from its key") + return made.stdout + + +def _ok(answer: dict, what: str, allow: str = "") -> bool: + body = answer["body"] if isinstance(answer["body"], dict) else {} + 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 SystemExit(f"{what}: refused ({answer['status']}): {json.dumps(body)[:400]}") + + +def write_pep_section(config_path: str, name: str, mode: str) -> None: + 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}) + raw["pep"] = section + path.write_text(json.dumps(raw, indent=2) + "\n", encoding="utf-8") + + +def own_policy(api, get, app: str) -> dict: + page_path = f"/applications?application={urllib.parse.quote(app, safe='')}" + page = get(page_path)["body"].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)["body"].get("page") or {} + fga = page.get("fga") or {} + policy = (fga.get("policy") or {}).get("name") or fga.get("reference") + if not policy: + raise SystemExit(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 AuthnContextClassRef; " + f"read on {ATTRIBUTE_PROTECTED} needs {TEST_ATTRIBUTE}={TEST_ATTRIBUTE_VALUE}; anything else is denied.") + return page + + +def setup_pep(api, get, files: DemoFiles, config_path: str, name: str, mode: str) -> None: + app = files.entity_id + made_account = get(f"/users?user={urllib.parse.quote(name)}")["body"].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}") + 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 = own_policy(api, get, app) + 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: try: from saml2_sp.cli import main as cli_main