diff --git a/README.adoc b/README.adoc index 18922cb..df0130c 100644 --- a/README.adoc +++ b/README.adoc @@ -10,8 +10,9 @@ Gate Status]] image:https://sonarcloud.io/api/project_badges/measure?project=cuioss_TrailHand&metric=ncloc[Lines of Code,link=https://sonarcloud.io/summary/new_code?id=cuioss_TrailHand] image:https://sonarcloud.io/api/project_badges/measure?project=cuioss_TrailHand&metric=coverage[Coverage,link=https://sonarcloud.io/summary/new_code?id=cuioss_TrailHand] -*Bootstrap.* The concepts, specifications and decisions are written; the web app, its mock server and its end-to-end -suite are built, the application follows. +*Bootstrap.* The concepts, specifications and decisions are written; the web app, its mock server, its end-to-end +suite and the application with its login, configuration and repository handling are built; the document operations +follow. == What is it? @@ -36,12 +37,17 @@ The target is Java 25; CI builds on Java 25 and 27. ---- The modules of link:doc/specification/architecture-and-modules.adoc[Architecture and Modules] are added as they are -built: `web-app` (the Svelte web app), `web-mock` (the mock server of its requests, development and tests only) and -`web-e2e` (Playwright and axe-core). The end-to-end suite runs with the profile `e2e`: +built, each with its own README: link:web-app/README.adoc[`web-app`] (the Svelte web app), +link:web-mock/README.adoc[`web-mock`] (the mock server of its requests, development and tests only), +link:trailhand/README.adoc[`trailhand`] (the Quarkus application) and link:web-e2e/README.adoc[`web-e2e`] (Playwright +and axe-core). The end-to-end suite runs with the profile `e2e`, the native image with the profile `native` (Mandrel +in a container): [source,bash] ---- ./mvnw verify -Pe2e -pl web-e2e -am +./mvnw package -Pnative -pl trailhand -am +docker build -f trailhand/src/main/docker/Dockerfile.native -t trailhand:dev trailhand ---- == Working on the Web App diff --git a/doc/adr/0001-Authentication_is_delegated_to_Token_Sheriff_with_a_server-side_session_for_the_web_app.adoc b/doc/adr/0001-Authentication_is_delegated_to_Token_Sheriff_with_a_server-side_session_for_the_web_app.adoc index 09e0bc2..470c547 100644 --- a/doc/adr/0001-Authentication_is_delegated_to_Token_Sheriff_with_a_server-side_session_for_the_web_app.adoc +++ b/doc/adr/0001-Authentication_is_delegated_to_Token_Sheriff_with_a_server-side_session_for_the_web_app.adoc @@ -27,7 +27,9 @@ application; the identity provider is the external system. * The application is a confidential client through `token-sheriff-client-quarkus`. It holds the tokens server-side. * During the login the browser holds a short-lived `HttpOnly`, `Secure`, `SameSite=Lax` login-transaction cookie that binds `state` and `nonce` across the identity provider's callback. Afterwards it holds only an `HttpOnly`, - `Secure`, `SameSite=Strict` session cookie. + `Secure`, `SameSite=Strict` session cookie. The authorization request asks for `response_mode=query`, so the + callback is a top-level `GET` navigation that carries the `Lax` cookie + (xref:../specification/authentication.adoc#TRH-AUTH-1[TRH-AUTH-1]). * Step-up for releases uses RFC 9470 through the client. * Agents present bearer tokens that `token-sheriff-validation-quarkus` validates. * Rights come from identity-provider groups, mapped per repository. Directory roles grant nothing. @@ -57,12 +59,15 @@ option for organisations that run API Sheriff anyway. === Properties of the design -* No token reaches the browser. +* No token reaches the browser, except the ID token as `id_token_hint` in the address of the RP-initiated logout, + after the held tokens are revoked (TRH-AUTH-1). * One authentication component serves the web app and the MCP server. === Accepted costs * Sessions are lost on restart. Users log in again. +* The logout address shows the browser the ID token of the ended session, so the provider can end its own session + without a confirmation page. * The application runs as one instance; a second instance would need a shared session store. === When this is revisited diff --git a/doc/concepts/application-architecture.adoc b/doc/concepts/application-architecture.adoc index 76bcc19..36fc549 100644 --- a/doc/concepts/application-architecture.adoc +++ b/doc/concepts/application-architecture.adoc @@ -131,10 +131,15 @@ asks for it. The compare-and-swap of the library still keeps concurrent saves of == Native Image The native image follows API Sheriff: Mandrel builder on the JDK 25 line, distroless runtime image, a health probe -built into the binary. JGit in a native image is the open risk of this architecture: its reflection, resource and -service-loader use has to be registered, and the transport is restricted to HTTPS, which avoids the SSH stack. The -first integration test builds the native image and runs a fetch, a save and a push against a local Git server before -anything else depends on it. +built into the binary. JGit in a native image was the open risk of this architecture: its reflection, resource and +service-loader use has to be registered, and the transport is restricted to HTTPS, which avoids the SSH stack. + +The bootstrap settled the first half. Clone and fetch of `file:` remotes run in the native image, with no JVM fallback, +once JGit is initialised at run time (it holds random generators in static fields) and its message bundle and enums +are registered for reflection; Token Sheriff's flow package needs the same run-time initialisation. The registrations +and their reasons are listed in the README of the `trailhand` module. HTTPS transport, in-core writing and notes +follow with the Git round trip, whose integration test (TRH-NFR-5) runs a fetch, a save, a release and a push against +a local Git server. == Testing @@ -145,7 +150,8 @@ specified in xref:../specification/testing.adoc[Testing]. == Open Questions -. Verify that JGit (HTTPS transport, in-core writing, notes) runs in the native image without the JVM fallback. +. Verify that the rest of JGit (HTTPS transport, in-core writing, notes) runs in the native image without the JVM + fallback; clone and fetch are verified. . Whether the categories module ships inside the application or as an overridable directory mounted at run time. == Related diff --git a/doc/specification/architecture-and-modules.adoc b/doc/specification/architecture-and-modules.adoc index 137832c..ed6ded6 100644 --- a/doc/specification/architecture-and-modules.adoc +++ b/doc/specification/architecture-and-modules.adoc @@ -297,7 +297,8 @@ created with the code. Metrics: `quarkus-micrometer-registry-prometheus` at `/q/ |Condition |Behaviour |Fetch fails -|The index serves the last fetched state; the health check `git-remote` reports `DOWN` per repository; readiness +|The index serves the last fetched state; the health check `git-remote` (health group +`/q/health/group/git-remote`) reports `DOWN` with the fetch state per repository; readiness stays `UP` |Push fails during a save diff --git a/doc/specification/authentication.adoc b/doc/specification/authentication.adoc index ab62b44..1d8cd52 100644 --- a/doc/specification/authentication.adoc +++ b/doc/specification/authentication.adoc @@ -16,7 +16,8 @@ https://github.com/cuioss/git-document-repository/blob/main/doc/specification/gi == TRH-AUTH-1: Web Login * The web login must use the authorization code flow with PKCE `S256` as a confidential client through Token Sheriff. -* No access, refresh or ID token may be sent to the browser. +* No access, refresh or ID token may be sent to the browser, with one exception: the ID token as `id_token_hint` in + the address of the RP-initiated logout, after the held tokens are revoked and the session is ended. * During login the browser must hold only a short-lived login-transaction cookie, afterwards only the session cookie, both `HttpOnly` and `Secure`; the session must end after a configurable idle time (default 30 minutes) and absolute lifetime (default 8 hours). @@ -37,15 +38,19 @@ https://github.com/cuioss/git-document-repository/blob/main/doc/specification/gi |Endpoints |`GET /api/v1/auth/login?return=
`, `GET /api/v1/auth/callback`, `POST /api/v1/auth/logout` -|`return` -|Starts with a single `/` (not `//`, no `\`, no scheme, no authority) and matches one of the canonical addresses of -xref:web-app.adoc#TRH-WEB-3[Web App, Navigation]; kept in the server-side login transaction, not in the browser +|Response mode +|`response_mode=query`: the provider sends the browser back to the callback with `code`, `state` and `iss` in the +query, a top-level `GET` navigation that carries the transaction cookie. Token Sheriff's request builder sets +`form_post`, whose callback is a cross-site `POST` without `SameSite=Lax` cookies +(link:https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-22.html#section-5.6.7.1[draft-ietf-httpbis-rfc6265bis-22, §5.6.7.1]); +the application replaces only that parameter, as API Sheriff does. Accepted cost: the code appears in the callback +address; PKCE, the single use of the code, the transaction with `state` and `Referrer-Policy: no-referrer` bound it |Transaction cookie |`__Host-trailhand-login`; `HttpOnly`, `Secure`, `SameSite=Lax`, `Path=/`, `Max-Age=600`; carries only an opaque -reference to the server-side login transaction (`state`, `nonce`, PKCE verifier); deleted by the callback. `Lax`, -because the browser does not send a `SameSite=Strict` cookie on the cross-site redirect back from the identity -provider +reference to the server-side login transaction (`state`, `nonce`, PKCE verifier); taken once and deleted by the +callback. `Lax`, because the browser does not send a `SameSite=Strict` cookie on the cross-site redirect back from the +identity provider |Session cookie |`__Host-trailhand-session`; `HttpOnly`, `Secure`, `SameSite=Strict`, `Path=/`; set by the callback @@ -64,7 +69,20 @@ carries the session cookie. |`web.session.idle-timeout` (default `PT30M`), `web.session.max-lifetime` (default `PT8H`) |Logout -|RP-initiated at the provider's `end_session_endpoint`; held tokens revoked first +|RP-initiated at the provider's `end_session_endpoint`; held tokens revoked first. Revocation is best effort: a +provider without `revocation_endpoint` or a refused revocation (logged, `TRAILHAND-104`) does not stop the logout. The +session ends and the tokens are dropped from the application in every case, and the end-session request ends the +provider's session. The address carries the ID token as +`id_token_hint`, which OpenID Connect RP-Initiated Logout recommends +(link:https://openid.net/specs/openid-connect-rpinitiated-1_0.html#RPLogout[RP-Initiated Logout 1.0, §2]: the RP +redirects the user agent to the logout endpoint; `id_token_hint` RECOMMENDED); with it the provider ends its session +without asking again. The application accepts no token from the browser, only the session cookie + +|Pending logins +|At most 10,000 login transactions at once, each for 10 minutes; a start beyond that answers `503 TOO_MANY_LOGINS` +with `Retry-After: 60` (the login is reachable without a session). Every transaction has the same lifetime, so each +start drops the expired and taken transactions in the order of their expiry, without scanning the others. A start +whose authorization request cannot be sent (PAR refused) frees its place at once |`401` from `/api/v1` |Response body names the login address; the web app follows it with the current canonical address as `return` @@ -78,8 +96,9 @@ carries the session cookie. * Every request must be checked; a request without a mapped right must be refused (deny by default). * No right may be derived from a directory role. -Input: the `groups` claim (or the claim configured as group source) of the session or bearer token. Mapping: -`trailhand.yaml` → `rights`. +Input: the `groups` claim (or the claim configured as group source) of the session or bearer token, read from the +JSON payload of the validated token as the provider wrote it: an array yields its strings, a single string one group, +anything else none, so a group name that contains a comma stays one group. Mapping: `trailhand.yaml` → `rights`. [cols="1,3"] |=== diff --git a/doc/specification/configuration.adoc b/doc/specification/configuration.adoc index 2f2ca3e..391a8fe 100644 --- a/doc/specification/configuration.adoc +++ b/doc/specification/configuration.adoc @@ -48,8 +48,21 @@ The application sets these values; the column shows the application's value, not |`trailhand.config.dir` |`config` |Directory holding `trailhand.yaml` + +|`trailhand.oidc.jwks-url` +|not set +|The address of the provider's keys, set only when the application reaches the provider under another origin than +its issuer (split horizon, as in the compose stack); otherwise the keys are found through the issuer's well-known +document |=== +Token Sheriff reads its own keys (`sheriff.client.*`, `sheriff.token.issuers.*`); the application derives them from +`trailhand.yaml` → `oidc` and `web.origin` with an ordinal above `application.properties` and below the environment. +Settings of the deployment's network stay in the environment, among them `SHERIFF_CLIENT_BACK_CHANNEL_ORIGIN` (the +origin the client dials instead of the issuer's), `SHERIFF_CLIENT_ALLOWED_EGRESS_HOSTS` and +`SHERIFF_TOKEN_ISSUERS_TRAILHAND_JWKS_HTTP_ALLOWED_EGRESS_HOSTS` (hosts on private addresses that the egress guard +admits). + === trailhand.yaml Validated against `schema/trailhand.schema.json` (bundled). Top-level keys: @@ -125,7 +138,9 @@ https://github.com/cuioss/git-document-repository/blob/main/doc/specification/gi |`web` |yes -|`session.idle-timeout` (default `PT30M`), `session.max-lifetime` (default `PT8H`), `information-text-ref` +|`origin` (the application's own origin, an absolute `https` URI without path: the `Origin` check of +xref:web-app.adoc#TRH-WEB-8[TRH-WEB-8] compares with it, and the login callback is `/api/v1/auth/callback`), +`session.idle-timeout` (default `PT30M`), `session.max-lifetime` (default `PT8H`), `information-text-ref` |`directory` |no @@ -152,16 +167,26 @@ Every key ending in `-ref` accepts one of three reference forms; no key accepts `anchor.signed-key-ref`). * `vault:`: a secret of Vault's key-value engine; accepted by every key except the signing keys. -Placeholders: `${NAME}` and `${NAME:-default}` in any string value, resolved from the environment before validation; -an unresolved placeholder without default is a boot error. +Placeholders: `${NAME}` and `${NAME:-default}` in any string value, resolved from the environment before validation. +`NAME` is an environment variable name (letters, digits and underscores, not starting with a digit). An unresolved +placeholder without default is a boot error, and so is any other `${...}`, so it never passes as a literal value. === Boot Validation Before the application accepts requests, every rule runs; each violation produces one `ERROR` record, and any violation stops the boot. Besides the schema, the rules refuse what the schema cannot see: two repositories with one alias, a `rights` entry or `directory.persons.repository` naming an unknown alias, a `-ref` value in a form its key -does not accept, an `anchor.signed-key-ref` equal to `signing.key-ref`, and an `mcp.canonical-uri` that is not an -absolute HTTPS URI without fragment. `--validate-config ` runs the same rules offline. +does not accept, an `anchor.signed-key-ref` equal to `signing.key-ref`, an `mcp.canonical-uri` that is not an +absolute HTTPS URI without fragment, and a `web.origin` that is no HTTPS origin or a `web.session.idle-timeout` longer +than `web.session.max-lifetime`. `--validate-config ` runs the same rules offline. + +The bootstrap enforces the rules of the keys it reads: `repositories`, `rights`, `oidc`, `web` and `fetch`, the +placeholders, and `web.origin` and the session lifetimes. Until the Vault adapter is built, `file:` is the only +reference form it accepts for the references it reads, `repositories[].credential-ref` and +`oidc.client-credential-ref`; `vault:` and `kms:` are refused there at boot. Other `-ref` keys, such as +`web.information-text-ref`, are not read yet and not checked. The JSON Schema and the rules of `signing`, +`anchor`, `mcp` and `directory`, with the per-key reference forms, apply once their modules are built; until then a +value under those keys is not checked. [#TRH-CONF-2] == TRH-CONF-2: Repositories and Refresh diff --git a/doc/specification/deployment.adoc b/doc/specification/deployment.adoc index 07c7014..edd440c 100644 --- a/doc/specification/deployment.adoc +++ b/doc/specification/deployment.adoc @@ -31,7 +31,7 @@ xref:../concepts/deployment.adoc[Deployment]. |`quay.io/quarkus/quarkus-distroless-image:2.0@sha256:`; the digest is updated by a dependency bot |User and binary -|`nonroot`; `/app/application` +|`nonroot`, declared numerically as `65532:65532`, its id in the base image's `/etc/passwd`; `/app/application` |Health check |`HEALTHCHECK CMD ["/app/application","--health-probe"]`; the binary probes its own management port and exits `0` diff --git a/doc/specification/web-app.adoc b/doc/specification/web-app.adoc index 157bd1e..5ee18e4 100644 --- a/doc/specification/web-app.adoc +++ b/doc/specification/web-app.adoc @@ -243,12 +243,20 @@ Refusals: |`VALIDATION` |`errors`: a list of `{"pointer", "code"}`, `pointer` a JSON Pointer into the request body +|`502` +|`IDENTITY_PROVIDER_UNAVAILABLE` +|`GET /api/v1/auth/login` cannot start the login: the provider's metadata cannot be read + |`503` |`GIT_UNAVAILABLE` |The Git server is unreachable (xref:architecture-and-modules.adoc#TRH-GEN-6[TRH-GEN-6]) + +|`503` +|`TOO_MANY_LOGINS` +|`GET /api/v1/auth/login` cannot start the login: 10,000 logins are pending (TRH-AUTH-1); with `Retry-After: 60` |=== -The login callback (xref:authentication.adoc#TRH-AUTH-1[TRH-AUTH-1]) navigates with +The login callback (xref:authentication.adoc#TRH-AUTH-1[TRH-AUTH-1]) answers a page that navigates with ``, so the page needs no script and passes the policy of <> unchanged. `POST /api/v1/auth/logout` answers `{"redirect"}`, the address the web app navigates to (the provider's `end_session_endpoint`). diff --git a/pom.xml b/pom.xml index 03ace15..a6c7dfe 100644 --- a/pom.xml +++ b/pom.xml @@ -48,6 +48,7 @@ web-app web-mock + trailhand web-e2e diff --git a/trailhand/.dockerignore b/trailhand/.dockerignore new file mode 100644 index 0000000..3222868 --- /dev/null +++ b/trailhand/.dockerignore @@ -0,0 +1,4 @@ +# Only the native runner and the data directory placeholder enter the image (Dockerfile.native). +* +!target/*-runner +!src/main/docker/data/ diff --git a/trailhand/README.adoc b/trailhand/README.adoc new file mode 100644 index 0000000..d8e82d2 --- /dev/null +++ b/trailhand/README.adoc @@ -0,0 +1,140 @@ += TrailHand Application +:toc: left +:toclevels: 2 + +The Quarkus application: it serves the web app and its `/api/v1`, logs people in through Token Sheriff with the +session held on the server (ADR-0001), and keeps the configured repositories as local copies through +`git-document-repository`. It ships as a native image in a distroless container. Specifications: +`doc/specification/architecture-and-modules.adoc` (layers), `authentication.adoc`, `configuration.adoc`, +`deployment.adoc`, `web-app.adoc` (the requests of the web app); log messages: link:doc/LogMessages.adoc[]. + +== Packages + +[cols="1,3"] +|=== +|Package |Content + +|`de.cuioss.trailhand` +|`TrailhandApplication` (`@QuarkusMain`): `--health-probe` (`HealthProbe`, a connect to the own management port) and +`--validate-config ` (`ConfigValidation`) run before Quarkus boots; `TrailhandLogMessages` + +|`config` +|`trailhand.yaml`: `ConfigurationLoader` (with the `${NAME:-default}` placeholders of `Placeholders`) yields a +`ConfigurationResult` with every `Violation`; `ConfigurationProducer` stops the boot on one. +`TokenSheriffConfigSourceFactory` derives the Token Sheriff settings from the same file (see <>) + +|`security` +|The login (`LoginService`, `LoginFlowProducer`, `QueryResponseModeRequestBuilder`), the pending logins +(`LoginTransactions`), the session (`SessionStore`, `UserSession`, cleaned by `SessionJanitor`), the rights from the +groups claim (`RightsMapper`), the check of the `return` address against the canonical addresses (`ReturnAddresses`) + +|`service` +|The only package that uses the libraries (TRH-GEN-4): `RepositoryService` builds the registry and clones or fetches; +`RepositoryLifecycle` runs the fetch every `fetch.interval`; the health checks + +|`web` +|`RequestGate` in front of every request; the resources below `/api/v1`; `PagePolicy` (the Content Security Policy +taken from the built `index.html`); `MessageCatalogue` (the catalogue of `web-app`); `EventStream` +|=== + +`ArchitectureTest` (ArchUnit) keeps the layering: nothing uses JGit directly, only `service` uses the libraries, and +`web` and the later `mcp` are independent of each other. + +== Requests + +`RequestGate` registers three Vert.x routes in front of the resources: + +. every answer gets the security headers (Content Security Policy, `nosniff`, `no-referrer`); +. below `/api/v1` the session comes from its cookie. A request without one answers `401 UNAUTHENTICATED`, except the + public `GET` of `status`, `messages`, `auth/login` and `auth/callback`. A state-changing request needs the + `X-CSRF-Token` of the session and the configured `web.origin` as `Origin`, else `403 CSRF_REJECTED`; +. every other `GET` that names no file of the web app answers with its `index.html`, so a canonical address reloads. + +[cols="1,3"] +|=== +|Request |Answer + +|`GET /api/v1/status`, `GET /api/v1/messages?lang=` +|The application status (version, degraded state); the catalogue of `en` or `de`, `400` otherwise + +|`GET /api/v1/auth/login?return=` +|`302` to the identity provider (code flow with PKCE, `response_mode=query`, PAR when the provider offers it; the +reasoning is in `doc/specification/authentication.adoc`); `502 IDENTITY_PROVIDER_UNAVAILABLE` when its discovery +fails, `503 TOO_MANY_LOGINS` while 10,000 logins are pending + +|`GET /api/v1/auth/callback` +|Completes the login and sets the session cookie; a same-origin page leads on to the checked `return` address (the +Strict cookie is sent from there on). A failed login answers `400` with a page that offers a new one + +|`POST /api/v1/auth/logout` +|Ends the session, revokes the tokens and names the provider's logout address + +|`GET /api/v1/session`, `GET /api/v1/due`, `GET /api/v1/events` +|The user, rights and anti-CSRF token; the Due list (empty until the document index is built); the event stream +|=== + +[#configuration] +== Configuration + +Two files, as `doc/specification/configuration.adoc` specifies: `application.properties` (Quarkus: ports, TLS paths, +management interface, the native build) and the policy `trailhand.yaml` in `trailhand.config.dir`. +`TokenSheriffConfigSourceFactory` derives `sheriff.client.*` (issuer, client id, the secret from its `file:` +reference, redirect address, scopes) and the issuer `sheriff.token.issuers.trailhand.*` from `oidc` and `web.origin`, +with an ordinal above `application.properties` and below the environment. Settings that depend on the deployment +(egress hosts, a back-channel address of the provider, `TRAILHAND_OIDC_JWKS_URL`) come from the environment; the +compose file of `integration-tests` shows them. + +The tests read `src/test/resources/config/trailhand.yaml`, whose issuer is not reachable: they cover everything up to +the call to the provider. The full login runs in `integration-tests`. + +== Health + +On the management port 9000 (plain HTTP, fixed at build time): `/q/health/live`, `/q/health/ready` with the check +`repositories` (`UP` once every repository has a local copy; a later fetch failure does not take it down) and the group +`/q/health/group/git-remote` (`DOWN` while a fetch fails), and `/q/metrics`. + +== Native Image + +[source,bash] +---- +./mvnw package -Pnative -pl trailhand -am # Mandrel in a container; runs NativeRegistrationTest first +docker build -f trailhand/src/main/docker/Dockerfile.native -t trailhand:dev trailhand +docker run --rm -v "$PWD/my-config:/cfg:ro" trailhand:dev --validate-config /cfg # exit 0 or 1 +---- + +The image is distroless, runs as `65532:65532`, and its `HEALTHCHECK` is the binary's `--health-probe`. JGit and Token +Sheriff need registrations that the JVM does not; each one fixed a failure seen in the native image: + +[cols="1,3"] +|=== +|Registration |Why + +|`--initialize-at-run-time` for `org.eclipse.jgit`, `de.cuioss.sheriff.token.client.flow` and `SessionStore` +(`application.properties`) +|Their classes hold `Random` or `SecureRandom` in static fields; initialised during the build, every process would +share the same seed + +|`META-INF/native-image/de.cuioss/trailhand/reflect-config.json` +|JGit fills the fields of its message bundle `JGitText` by reflection, and `Config.getEnum` calls `values()` of every +enum it reads; without them a clone fails + +|`META-INF/native-image/de.cuioss/trailhand/resource-config.json` +|The `JGitText` properties + +|`security/TokenClientNativeRegistration` +|The generated DSL-JSON converters of Token Sheriff's response types, so the client can read discovery and token +answers +|=== + +`NativeRegistrationTest` compares both lists with the resolved JARs: every converter of the Token Sheriff client and +every enum of JGit must be registered, and nothing else. The profile `native` runs it before every native build, so a +dependency update that changes them fails before an image is packaged; this lists +every enum of the JGit JAR for `reflect-config.json`: + +[source,bash] +---- +JAR=~/.m2/repository/org/eclipse/jgit/org.eclipse.jgit//org.eclipse.jgit-.jar +javap -cp "$JAR" $(unzip -Z1 "$JAR" | sed -n 's#\.class$##p' | tr / .) | grep -E '^[^ ].* extends java\.lang\.Enum<' +---- + +A change of the registrations is checked only by the native image: run `integration-tests`. diff --git a/trailhand/doc/LogMessages.adoc b/trailhand/doc/LogMessages.adoc new file mode 100644 index 0000000..3bcf1ad --- /dev/null +++ b/trailhand/doc/LogMessages.adoc @@ -0,0 +1,85 @@ += TrailHand: Log Messages +:toc: left +:toclevels: 2 + +The log records of the application (doc/specification/architecture-and-modules.adoc, TRH-GEN-5), defined in +`de.cuioss.trailhand.TrailhandLogMessages`. Prefix `TRAILHAND`; CUI ranges: INFO 1-99, WARN 100-199, ERROR 200-299. +No record carries a token, a session id, an anti-CSRF token, a secret, a credential or a person's name; a +remote appears only without user information. + +[cols="1,1,3,2,3"] +|=== +|Identifier |Level |Template |Parameters |Trigger + +|`TRAILHAND-1` +|INFO +|Configuration loaded from %s with %s repositories +|directory, count +|`trailhand.yaml` passed the boot rules + +|`TRAILHAND-2` +|INFO +|Repository %s is present locally +|alias +|A clone was made or an existing one opened + +|`TRAILHAND-3` +|INFO +|Login completed for a user of issuer %s +|issuer +|The login callback opened a session + +|`TRAILHAND-4` +|INFO +|Logout completed +|— +|A session ended with RP-initiated logout at the provider + +|`TRAILHAND-100` +|WARN +|Fetch of repository %s failed: %s (%s) +|alias, library outcome, library detail (the remote without user information, GDR-NFR-3) +|A periodic fetch failed (TRH-GEN-6); the last fetched state is served + +|`TRAILHAND-101` +|WARN +|Clone of repository %s failed: %s (%s) +|alias, library outcome, library detail (the remote without user information, GDR-NFR-3) +|The first clone failed; readiness stays `DOWN` until it succeeds + +|`TRAILHAND-102` +|WARN +|Refused %s %s: anti-CSRF token or Origin not valid +|method, path +|A state-changing request without valid `X-CSRF-Token` or from a foreign `Origin` (TRH-WEB-8) + +|`TRAILHAND-103` +|WARN +|Login could not be completed: %s +|reason (no value of the request) +|A callback without or with an unknown transaction, or a refused code exchange + +|`TRAILHAND-104` +|WARN +|Token revocation at logout failed: %s +|exception type +|The provider refused or could not be reached for the revocation + +|`TRAILHAND-105` +|WARN +|Refresh of the repositories failed: %s +|exception type and message +|A refresh ended with an unexpected failure; the next refresh runs as planned + +|`TRAILHAND-200` +|ERROR +|Invalid configuration at %s: %s +|key, rule +|One violation of `trailhand.yaml` (TRH-CONF-1), at boot and with `--validate-config` + +|`TRAILHAND-201` +|ERROR +|Boot stopped: the configuration has %s violation(s) +|count +|The boot stops on an invalid configuration +|=== diff --git a/trailhand/pom.xml b/trailhand/pom.xml new file mode 100644 index 0000000..4c1f08e --- /dev/null +++ b/trailhand/pom.xml @@ -0,0 +1,223 @@ + + + 4.0.0 + + de.cuioss + trailhand-parent + 0.1.0-SNAPSHOT + ../pom.xml + + trailhand + jar + TrailHand Application + The TrailHand application: Quarkus, native image, web app, REST API and the Git persistence of + git-document-repository; authentication through Token Sheriff (doc/specification/architecture-and-modules.adoc). + + + + de.cuioss.trailhand + + **/TrailhandApplication.java + + + + + + de.cuioss + trailhand-web-app + + + de.cuioss + git-core + + + de.cuioss + git-store + + + de.cuioss.sheriff.token + token-sheriff-client + + + de.cuioss.sheriff.token + token-sheriff-client-quarkus + + + io.quarkus + quarkus-rest + + + io.quarkus + quarkus-rest-jackson + + + io.quarkus + quarkus-smallrye-health + + + io.quarkus + quarkus-micrometer-registry-prometheus + + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + + + de.cuioss + cui-java-tools + + + org.jspecify + jspecify + + + org.projectlombok + lombok + provided + + + + io.quarkus + quarkus-junit + test + + + + io.quarkus + quarkus-jacoco + test + + + io.rest-assured + rest-assured + test + + + org.junit.jupiter + junit-jupiter + test + + + de.cuioss.test + cui-test-generator + test + + + de.cuioss.test + cui-test-juli-logger + test + + + de.cuioss.test + cui-test-value-objects + test + + + org.easymock + easymock + test + + + org.hamcrest + hamcrest + test + + + com.tngtech.archunit + archunit + test + + + de.cuioss + git-testing + test + + + + + + + io.quarkus + quarkus-maven-plugin + + + org.apache.maven.plugins + maven-enforcer-plugin + + + + ban-persistence + + enforce + + + + + + io.quarkus:quarkus-datasource* + io.quarkus:quarkus-hibernate-orm* + io.quarkus:quarkus-hibernate-reactive* + io.quarkus:quarkus-jdbc-* + io.quarkus:quarkus-reactive-*-client + + TRH-GEN-3: TrailHand persists only in Git; no datasource or Hibernate. + + + + + + + + org.jacoco + jacoco-maven-plugin + + + **/TrailhandApplication.class + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.projectlombok + lombok + + + + + + + + + + + native + + true + true + true + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/NativeRegistrationTest.java + + + + + + + + diff --git a/trailhand/src/main/docker/Dockerfile.native b/trailhand/src/main/docker/Dockerfile.native new file mode 100644 index 0000000..f816db8 --- /dev/null +++ b/trailhand/src/main/docker/Dockerfile.native @@ -0,0 +1,37 @@ +# TrailHand native image (doc/specification/deployment.adoc, TRH-OPS-1). +# +# Build the native executable first: ./mvnw package -Pnative -pl trailhand -am +# then, from the trailhand module: docker build -f src/main/docker/Dockerfile.native -t trailhand:dev . +# +# Single stage: the runner is built by Maven (Mandrel builder image, quarkus.native.builder-image) and copied +# into the distroless base. The base image digest is pinned and updated by the dependency bot. +FROM quay.io/quarkus/quarkus-distroless-image:2.0@sha256:f8cbe79d903703e741b84eca9d321e286e7537da87cb414832d7c71cd0c5063a + +ARG APP_VERSION=dev +ARG APP_REVISION=dev + +LABEL org.opencontainers.image.title="TrailHand" \ + org.opencontainers.image.description="Security documents as versioned Git documents on the Git server you already run - the CISO's friend" \ + org.opencontainers.image.version="${APP_VERSION}" \ + org.opencontainers.image.revision="${APP_REVISION}" \ + org.opencontainers.image.vendor="CUIoss" \ + org.opencontainers.image.licenses="Apache-2.0" \ + org.opencontainers.image.source="https://github.com/cuioss/TrailHand" \ + org.opencontainers.image.base.name="quay.io/quarkus/quarkus-distroless-image:2.0" + +WORKDIR /app +COPY --chmod=0755 target/*-runner /app/application +# /app/data (TRH-OPS-2): owned by nonroot, so a new named volume mounted there is writable; the image declares no +# volume. The distroless base has no shell to create it, so a placeholder directory is copied. +COPY --chown=65532:65532 --chmod=0750 src/main/docker/data/ /app/data/ + +# 8443 HTTPS (web app, /api/v1, /mcp), 8080 redirect to HTTPS, 9000 management (health, metrics) - TRH-OPS-2. +EXPOSE 8080 8443 9000 + +# The distroless image has no shell: the binary probes its own management port (TrailhandApplication). +HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=3 \ + CMD ["/app/application", "--health-probe"] + +# nonroot of the distroless base (65532:65532 in its /etc/passwd), numeric so the host can resolve it. +USER 65532:65532 +ENTRYPOINT ["/app/application", "-Dquarkus.http.host=0.0.0.0"] diff --git a/trailhand/src/main/docker/data/README b/trailhand/src/main/docker/data/README new file mode 100644 index 0000000..80f40ae --- /dev/null +++ b/trailhand/src/main/docker/data/README @@ -0,0 +1,2 @@ +The data directory of TrailHand (/app/data): the local repositories and the drafts. Mount a persistent volume +here; the image creates the directory owned by nonroot (65532) so a new named volume takes over that owner. diff --git a/trailhand/src/main/java/de/cuioss/trailhand/ConfigValidation.java b/trailhand/src/main/java/de/cuioss/trailhand/ConfigValidation.java new file mode 100644 index 0000000..de8d9b1 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/ConfigValidation.java @@ -0,0 +1,70 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand; + +import de.cuioss.trailhand.config.ConfigurationLoader; + +import java.nio.file.Path; +import java.util.Arrays; +import java.util.function.UnaryOperator; +import java.util.logging.ConsoleHandler; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * {@code --validate-config } (TRH-CONF-1): validates {@code trailhand.yaml} offline with the boot rules; every + * violation is logged as one ERROR record. Exit code {@code 0} for a valid, {@code 1} for an invalid configuration, + * {@code 2} for a missing directory argument. + */ +final class ConfigValidation { + + /** The flag that selects the validation. */ + static final String FLAG = "--validate-config"; + + private ConfigValidation() { + // utility + } + + /** + * @param args the command line, starting with the flag + * @param environment the environment of the placeholders + * @return the exit code + */ + static int run(String[] args, UnaryOperator environment) { + int index = Arrays.asList(args).indexOf(FLAG); + if (index < 0 || index + 1 >= args.length) { + return 2; + } + ensureConsoleLogging(); + var result = new ConfigurationLoader(environment).load(Path.of(args[index + 1])); + return result.isValid() ? 0 : 1; + } + + /** + * The validation runs without booting Quarkus, so no handler writes the records yet, in the native image in + * particular; the records of the violations go to the console. + */ + static void ensureConsoleLogging() { + var root = Logger.getLogger(""); + // The native image carries Quarkus' delayed handler, which holds records until the boot that never comes. + if (Arrays.stream(root.getHandlers()).noneMatch(ConsoleHandler.class::isInstance)) { + var handler = new ConsoleHandler(); + handler.setLevel(Level.INFO); + root.addHandler(handler); + root.setLevel(Level.INFO); + } + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/HealthProbe.java b/trailhand/src/main/java/de/cuioss/trailhand/HealthProbe.java new file mode 100644 index 0000000..c428953 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/HealthProbe.java @@ -0,0 +1,53 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; + +/** + * The health check of the distroless image (TRH-OPS-1): {@code /app/application --health-probe} connects to the own + * management port on the loopback interface and exits {@code 0} or {@code 1} before Quarkus boots. The image has no + * shell or other program to check with. + */ +final class HealthProbe { + + /** The flag that selects the probe. */ + static final String FLAG = "--health-probe"; + + /** The management port (TRH-OPS-2). */ + static final int PORT = 9000; + + private static final int CONNECT_TIMEOUT_MILLIS = 2000; + + private HealthProbe() { + // utility + } + + /** + * @param port the port + * @return {@code 0} when the port accepts a connection, {@code 1} otherwise + */ + static int probe(int port) { + try (Socket socket = new Socket()) { + socket.connect(new InetSocketAddress("127.0.0.1", port), CONNECT_TIMEOUT_MILLIS); + return 0; + } catch (IOException e) { + return 1; + } + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/TrailhandApplication.java b/trailhand/src/main/java/de/cuioss/trailhand/TrailhandApplication.java new file mode 100644 index 0000000..ca68b63 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/TrailhandApplication.java @@ -0,0 +1,48 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand; + +import io.quarkus.runtime.Quarkus; +import io.quarkus.runtime.annotations.QuarkusMain; + +import java.util.Arrays; + +/** + * The entry point: {@code --health-probe} and {@code --validate-config } run without booting Quarkus; anything + * else starts the application. This class only routes; the logic is in {@link HealthProbe} and + * {@link ConfigValidation}. + */ +@QuarkusMain +public class TrailhandApplication { + + private TrailhandApplication() { + // entry point only + } + + /** + * @param args the command line + */ + public static void main(String... args) { + var arguments = Arrays.asList(args); + if (arguments.contains(HealthProbe.FLAG)) { + System.exit(HealthProbe.probe(HealthProbe.PORT)); + } + if (arguments.contains(ConfigValidation.FLAG)) { + System.exit(ConfigValidation.run(args, System::getenv)); + } + Quarkus.run(args); + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/TrailhandLogMessages.java b/trailhand/src/main/java/de/cuioss/trailhand/TrailhandLogMessages.java new file mode 100644 index 0000000..a61d674 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/TrailhandLogMessages.java @@ -0,0 +1,131 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand; + +import de.cuioss.tools.logging.LogRecord; +import de.cuioss.tools.logging.LogRecordModel; +import lombok.experimental.UtilityClass; + +/** + * The {@link LogRecord}s of the application (TRH-GEN-5). Identifiers carry the prefix {@value #PREFIX} and follow the + * CUI ranges: INFO 1-99, WARN 100-199, ERROR 200-299. The catalogue is {@code trailhand/doc/LogMessages.adoc}. No + * record carries a token, a session id, a secret, a credential or a person's name. + */ +@UtilityClass +public final class TrailhandLogMessages { + + /** The prefix of every identifier. */ + public static final String PREFIX = "TRAILHAND"; + + /** Messages at level INFO. */ + @UtilityClass + public static final class INFO { + + /** The configuration is valid: the directory and the number of repositories. */ + public static final LogRecord CONFIGURATION_LOADED = LogRecordModel.builder() + .template("Configuration loaded from %s with %s repositories") + .prefix(PREFIX) + .identifier(1) + .build(); + + /** A repository has a valid local copy: the alias. */ + public static final LogRecord REPOSITORY_READY = LogRecordModel.builder() + .template("Repository %s is present locally") + .prefix(PREFIX) + .identifier(2) + .build(); + + /** A user signed in: the issuer. */ + public static final LogRecord LOGIN_COMPLETED = LogRecordModel.builder() + .template("Login completed for a user of issuer %s") + .prefix(PREFIX) + .identifier(3) + .build(); + + /** A user signed out. */ + public static final LogRecord LOGOUT_COMPLETED = LogRecordModel.builder() + .template("Logout completed") + .prefix(PREFIX) + .identifier(4) + .build(); + } + + /** Messages at level WARN. */ + @UtilityClass + public static final class WARN { + + /** The fetch of a repository failed: the alias, the library's outcome and its detail (the remote without credentials). */ + public static final LogRecord FETCH_FAILED = LogRecordModel.builder() + .template("Fetch of repository %s failed: %s (%s)") + .prefix(PREFIX) + .identifier(100) + .build(); + + /** The first clone of a repository failed: the alias, the library's outcome and its detail (the remote without credentials). */ + public static final LogRecord CLONE_FAILED = LogRecordModel.builder() + .template("Clone of repository %s failed: %s (%s)") + .prefix(PREFIX) + .identifier(101) + .build(); + + /** A state-changing request was refused by the anti-CSRF or Origin check: the method and the path. */ + public static final LogRecord CSRF_REJECTED = LogRecordModel.builder() + .template("Refused %s %s: anti-CSRF token or Origin not valid") + .prefix(PREFIX) + .identifier(102) + .build(); + + /** A login callback could not be completed: the reason. */ + public static final LogRecord LOGIN_FAILED = LogRecordModel.builder() + .template("Login could not be completed: %s") + .prefix(PREFIX) + .identifier(103) + .build(); + + /** The revocation of a token at logout failed: the reason. */ + public static final LogRecord REVOCATION_FAILED = LogRecordModel.builder() + .template("Token revocation at logout failed: %s") + .prefix(PREFIX) + .identifier(104) + .build(); + + /** A refresh of the repositories ended with an unexpected failure: the exception type and its message. */ + public static final LogRecord REFRESH_FAILED = LogRecordModel.builder() + .template("Refresh of the repositories failed: %s: %s") + .prefix(PREFIX) + .identifier(105) + .build(); + } + + /** Messages at level ERROR. */ + @UtilityClass + public static final class ERROR { + + /** One violation of the configuration: the key and the rule. */ + public static final LogRecord CONFIGURATION_VIOLATION = LogRecordModel.builder() + .template("Invalid configuration at %s: %s") + .prefix(PREFIX) + .identifier(200) + .build(); + + /** The boot stops because the configuration is invalid: the number of violations. */ + public static final LogRecord BOOT_STOPPED = LogRecordModel.builder() + .template("Boot stopped: the configuration has %s violation(s)") + .prefix(PREFIX) + .identifier(201) + .build(); + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/Action.java b/trailhand/src/main/java/de/cuioss/trailhand/config/Action.java new file mode 100644 index 0000000..0e90957 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/config/Action.java @@ -0,0 +1,53 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.config; + +import java.util.Arrays; +import java.util.Locale; +import java.util.Optional; + +/** + * The actions a right permits (TRH-AUTH-2). + */ +public enum Action { + + /** Reading documents, index views and diffs. */ + READ, + + /** Drafts, saves and transitions that are no release. */ + EDIT, + + /** Releases, with step-up. */ + APPROVE, + + /** Changes of the catalogs, erasure of persons, deletion of expired repositories. */ + ADMINISTER_CATALOGS; + + /** + * @return the name used in {@code trailhand.yaml} and on the wire, e.g. {@code administer-catalogs} + */ + public String wireName() { + return name().toLowerCase(Locale.ROOT).replace('_', '-'); + } + + /** + * @param wireName the name of {@code trailhand.yaml} + * @return the action, or empty for an unknown name + */ + public static Optional fromWireName(String wireName) { + return Arrays.stream(values()).filter(action -> action.wireName().equals(wireName)).findFirst(); + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/ConfigurationLoader.java b/trailhand/src/main/java/de/cuioss/trailhand/config/ConfigurationLoader.java new file mode 100644 index 0000000..8f100ff --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/config/ConfigurationLoader.java @@ -0,0 +1,393 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import de.cuioss.tools.logging.CuiLogger; +import org.jspecify.annotations.Nullable; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.time.Period; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.UnaryOperator; +import java.util.regex.Pattern; + +import static de.cuioss.trailhand.TrailhandLogMessages.ERROR; +import static de.cuioss.trailhand.TrailhandLogMessages.INFO; + +/** + * Loads and validates {@code trailhand.yaml} (TRH-CONF-1, TRH-CONF-2). + *

+ * Placeholders are resolved from the environment first; then every rule runs and every violation is collected, so + * one run names them all. The bootstrap validates the keys the application uses so far ({@code repositories}, + * {@code rights}, {@code oidc}, {@code web}, {@code fetch}); the validation against the bundled JSON Schema follows + * with the remaining keys. + */ +public class ConfigurationLoader { + + private static final CuiLogger LOGGER = new CuiLogger(ConfigurationLoader.class); + + /** The name of the policy file in the configuration directory. */ + public static final String FILE_NAME = "trailhand.yaml"; + + private static final Pattern ALIAS = Pattern.compile("[a-z0-9-]+"); + private static final Set CONFIDENTIALITY = Set.of("public-internal", "restricted", "strongly-restricted"); + /** The reference forms that can be resolved; {@code vault:} joins with the Vault adapter. */ + private static final List REFERENCE_FORMS = List.of("file:"); + private static final String MUST_BE_MAPPING = "must be a mapping"; + private static final String ALIAS_KEY = ".alias"; + private static final String CREDENTIAL_KEY = ".credential-ref"; + + private final UnaryOperator environment; + + /** + * @param environment the environment the placeholders are resolved from + */ + public ConfigurationLoader(UnaryOperator environment) { + this.environment = environment; + } + + /** + * @return a loader reading the process environment + */ + public static ConfigurationLoader fromProcessEnvironment() { + return new ConfigurationLoader(System::getenv); + } + + /** + * Loads {@code trailhand.yaml} from a directory and logs one ERROR record per violation. + * + * @param directory the configuration directory + * @return the configuration or the violations + */ + public ConfigurationResult load(Path directory) { + var file = directory.resolve(FILE_NAME); + Object tree; + try { + if (!Files.isRegularFile(file)) { + return report(List.of(new Violation(FILE_NAME, "the file is missing"))); + } + tree = new ObjectMapper(new YAMLFactory()).readValue(file.toFile(), Object.class); + } catch (IOException e) { + return report(List.of(new Violation(FILE_NAME, "the file is no valid YAML"))); + } + return report(directory, validate(tree)); + } + + /** + * Validates a parsed tree, without logging. + * + * @param tree the YAML content as maps, lists and scalars + * @return the configuration or the violations + */ + @SuppressWarnings("unchecked") + public ConfigurationResult validate(@Nullable Object tree) { + var violations = new ArrayList(); + if (!(tree instanceof Map)) { + return new ConfigurationResult(null, List.of(new Violation(FILE_NAME, "the document is no mapping"))); + } + var unresolved = new ArrayList(); + var root = (Map) Placeholders.resolveTree(tree, environment, unresolved); + for (String name : unresolved) { + violations.add(new Violation("${" + name + "}", "the placeholder has no value and no default")); + } + var reader = new Reader(root, violations); + var repositories = reader.repositories(); + var aliases = new HashSet(); + repositories.forEach(repository -> aliases.add(repository.alias())); + var rights = reader.rights(aliases); + var oidc = reader.oidc(); + var web = reader.web(); + var fetch = reader.duration(reader.map(root, "fetch", false), "fetch.interval", "interval", + TrailhandConfiguration.DEFAULT_FETCH_INTERVAL); + if (!violations.isEmpty() || oidc == null || web == null) { + return new ConfigurationResult(null, violations); + } + return new ConfigurationResult(new TrailhandConfiguration(repositories, rights, oidc, web, fetch), List.of()); + } + + private static ConfigurationResult report(List violations) { + for (Violation violation : violations) { + LOGGER.error(ERROR.CONFIGURATION_VIOLATION, violation.key(), violation.rule()); + } + return new ConfigurationResult(null, violations); + } + + private ConfigurationResult report(Path directory, ConfigurationResult result) { + var configuration = result.configuration(); + if (result.isValid() && configuration != null) { + LOGGER.info(INFO.CONFIGURATION_LOADED, directory, configuration.repositories().size()); + return result; + } + return report(result.violations()); + } + + /** Reads typed values from the tree and records a violation for every problem. */ + private static final class Reader { + + private final Map root; + private final List violations; + + Reader(Map root, List violations) { + this.root = root; + this.violations = violations; + } + + @SuppressWarnings("unchecked") + @Nullable + Map map(@Nullable Map parent, String key, boolean required) { + var value = parent == null ? null : parent.get(key); + if (value instanceof Map map) { + return (Map) map; + } + if (value != null || required) { + violations.add(new Violation(key, value == null ? "is required" : MUST_BE_MAPPING)); + } + return null; + } + + @Nullable + String text(@Nullable Map parent, String path, String key, boolean required) { + var value = parent == null ? null : parent.get(key); + if (value instanceof String text && !text.isBlank()) { + return text.trim(); + } + if (value != null || required) { + violations.add(new Violation(path, value == null ? "is required" : "must be a non-empty string")); + } + return null; + } + + Duration duration(@Nullable Map parent, String path, String key, Duration fallback) { + var text = text(parent, path, key, false); + if (text == null) { + return fallback; + } + try { + var duration = Duration.parse(text); + if (duration.isNegative() || duration.isZero()) { + violations.add(new Violation(path, "must be a positive ISO 8601 duration")); + return fallback; + } + return duration; + } catch (DateTimeParseException e) { + violations.add(new Violation(path, "must be an ISO 8601 duration such as PT5M")); + return fallback; + } + } + + @SuppressWarnings("unchecked") + List repositories() { + var value = root.get("repositories"); + if (!(value instanceof List list) || list.isEmpty()) { + violations.add(new Violation("repositories", "must be a non-empty list")); + return List.of(); + } + var result = new ArrayList(); + var seen = new HashSet(); + for (int index = 0; index < list.size(); index++) { + var path = "repositories[" + index + "]"; + if (!(list.get(index) instanceof Map entry)) { + violations.add(new Violation(path, MUST_BE_MAPPING)); + continue; + } + var repository = repository((Map) entry, path, seen); + if (repository != null) { + result.add(repository); + } + } + return result; + } + + @Nullable + private RepositorySettings repository(Map entry, String path, Set seen) { + int before = violations.size(); + var alias = text(entry, path + ALIAS_KEY, "alias", true); + if (alias != null && !ALIAS.matcher(alias).matches()) { + violations.add(new Violation(path + ALIAS_KEY, "must match [a-z0-9-]+")); + } else if (alias != null && !seen.add(alias)) { + violations.add(new Violation(path + ALIAS_KEY, "is used by another repository")); + } + var remote = text(entry, path + ".remote", "remote", true); + if (remote != null && !remote.startsWith("https://") && !remote.startsWith("file:")) { + violations.add(new Violation(path + ".remote", "must be an https or a file: URL")); + } + var confidentiality = text(entry, path + ".confidentiality", "confidentiality", true); + if (confidentiality != null && !CONFIDENTIALITY.contains(confidentiality)) { + violations.add(new Violation(path + ".confidentiality", + "must be public-internal, restricted or strongly-restricted")); + } + var retention = retention(text(entry, path + ".retention", "retention", true), path + ".retention"); + var credentialRef = text(entry, path + CREDENTIAL_KEY, "credential-ref", false); + if (remote != null && remote.startsWith("https://") && credentialRef == null) { + violations.add(new Violation(path + CREDENTIAL_KEY, "is required for an https remote")); + } + reference(credentialRef, path + CREDENTIAL_KEY); + if (violations.size() > before || alias == null || remote == null || confidentiality == null) { + return null; + } + return new RepositorySettings(alias, remote, confidentiality, retention, credentialRef); + } + + @Nullable + private Period retention(@Nullable String text, String path) { + if (text == null || "unlimited".equals(text)) { + return null; + } + try { + return Period.parse(text); + } catch (DateTimeParseException e) { + violations.add(new Violation(path, "must be unlimited or an ISO 8601 period such as P10Y")); + return null; + } + } + + private void reference(@Nullable String reference, String path) { + if (reference != null && REFERENCE_FORMS.stream().noneMatch(reference::startsWith)) { + violations.add(new Violation(path, reference.startsWith("vault:") + ? "vault: references are not supported yet (the Vault adapter is not built); use file:" + : "must be a reference: file:")); + } + } + + @SuppressWarnings("unchecked") + Map> rights(Set aliases) { + var rights = map(root, "rights", true); + var result = new LinkedHashMap>(); + if (rights == null) { + return result; + } + rights.forEach((group, value) -> { + var path = "rights." + group; + if (!(value instanceof List list)) { + violations.add(new Violation(path, "must be a list")); + return; + } + var entries = new ArrayList(); + for (int index = 0; index < list.size(); index++) { + var entryPath = path + "[" + index + "]"; + if (!(list.get(index) instanceof Map entry)) { + violations.add(new Violation(entryPath, MUST_BE_MAPPING)); + continue; + } + var right = right((Map) entry, entryPath, aliases); + if (right != null) { + entries.add(right); + } + } + result.put(group, entries); + }); + return result; + } + + @Nullable + private RightSettings right(Map entry, String path, Set aliases) { + var repository = text(entry, path + ".repository", "repository", true); + if (repository != null && !aliases.contains(repository)) { + violations.add(new Violation(path + ".repository", "names no configured repository")); + } + var actions = EnumSet.noneOf(Action.class); + if (!(entry.get("actions") instanceof List list) || list.isEmpty()) { + violations.add(new Violation(path + ".actions", "must be a non-empty list")); + return null; + } + for (Object action : list) { + var parsed = action instanceof String name ? Action.fromWireName(name) : Optional.empty(); + if (parsed.isEmpty()) { + violations.add(new Violation(path + ".actions", + "must hold read, edit, approve or administer-catalogs")); + } else { + actions.add(parsed.get()); + } + } + return repository == null ? null : new RightSettings(repository, actions); + } + + @Nullable + OidcSettings oidc() { + var oidc = map(root, "oidc", true); + if (oidc == null) { + return null; + } + var issuer = text(oidc, "oidc.issuer", "issuer", true); + if (issuer != null && httpsUri(issuer, false) == null) { + violations.add(new Violation("oidc.issuer", "must be an absolute https URI")); + } + var clientId = text(oidc, "oidc.client-id", "client-id", true); + var credential = text(oidc, "oidc.client-credential-ref", "client-credential-ref", true); + reference(credential, "oidc.client-credential-ref"); + var groups = text(oidc, "oidc.groups-claim", "groups-claim", false); + if (issuer == null || clientId == null || credential == null) { + return null; + } + return new OidcSettings(issuer, clientId, credential, + groups == null ? OidcSettings.DEFAULT_GROUPS_CLAIM : groups); + } + + @Nullable + WebSettings web() { + var web = map(root, "web", true); + if (web == null) { + return null; + } + var originText = text(web, "web.origin", "origin", true); + var origin = originText == null ? null : httpsUri(originText, true); + if (originText != null && origin == null) { + violations.add(new Violation("web.origin", "must be an https origin without path, query or fragment")); + } + var session = map(web, "session", false); + var idle = duration(session, "web.session.idle-timeout", "idle-timeout", WebSettings.DEFAULT_IDLE_TIMEOUT); + var max = duration(session, "web.session.max-lifetime", "max-lifetime", WebSettings.DEFAULT_MAX_LIFETIME); + if (idle.compareTo(max) > 0) { + violations.add(new Violation("web.session.idle-timeout", "must not exceed web.session.max-lifetime")); + } + return origin == null ? null : new WebSettings(origin, idle, max); + } + + @Nullable + private static URI httpsUri(String text, boolean originOnly) { + try { + var uri = new URI(text); + // The scheme is case-insensitive (RFC 3986, section 3.1); WebSettings writes the origin in lower case. + if (!"https".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null || uri.getFragment() != null + || uri.getUserInfo() != null) { + return null; + } + if (originOnly && ((uri.getRawPath() != null && !uri.getRawPath().isEmpty() + && !"/".equals(uri.getRawPath())) || uri.getQuery() != null)) { + return null; + } + return uri; + } catch (URISyntaxException e) { + return null; + } + } + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/ConfigurationProducer.java b/trailhand/src/main/java/de/cuioss/trailhand/config/ConfigurationProducer.java new file mode 100644 index 0000000..09b4908 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/config/ConfigurationProducer.java @@ -0,0 +1,62 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.config; + +import de.cuioss.tools.logging.CuiLogger; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Produces; +import jakarta.inject.Singleton; +import org.eclipse.microprofile.config.inject.ConfigProperty; + +import java.nio.file.Path; + +import static de.cuioss.trailhand.TrailhandLogMessages.ERROR; + +/** + * Loads {@code trailhand.yaml} from {@code trailhand.config.dir} once and provides it (TRH-CONF-1). An invalid + * configuration stops the boot: every violation was logged as one ERROR record, and the producer fails. + */ +@ApplicationScoped +public class ConfigurationProducer { + + private static final CuiLogger LOGGER = new CuiLogger(ConfigurationProducer.class); + + private final Path directory; + + /** + * @param directory the configuration directory, {@code trailhand.config.dir} + */ + public ConfigurationProducer(@ConfigProperty(name = "trailhand.config.dir", defaultValue = "config") String directory) { + this.directory = Path.of(directory); + } + + /** + * @return the validated configuration + * @throws InvalidConfigurationException if the configuration has a violation + */ + @Produces + // @Singleton, not @ApplicationScoped: a record is final and cannot stand behind the client proxy of a normal scope. + @Singleton + public TrailhandConfiguration configuration() { + var result = ConfigurationLoader.fromProcessEnvironment().load(directory); + var configuration = result.configuration(); + if (!result.isValid() || configuration == null) { + LOGGER.error(ERROR.BOOT_STOPPED, result.violations().size()); + throw new InvalidConfigurationException(result.violations().size()); + } + return configuration; + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/ConfigurationResult.java b/trailhand/src/main/java/de/cuioss/trailhand/config/ConfigurationResult.java new file mode 100644 index 0000000..d22f3c7 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/config/ConfigurationResult.java @@ -0,0 +1,46 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.config; + +import org.jspecify.annotations.Nullable; + +import java.util.List; + +/** + * The result of loading {@code trailhand.yaml}: the configuration, or every violation. + * + * @param configuration the configuration; {@code null} when there is a violation + * @param violations the violations, empty for a valid configuration + */ +public record ConfigurationResult(@Nullable TrailhandConfiguration configuration, List violations) { + + /** + * Copies the violations. + * + * @param configuration the configuration + * @param violations the violations + */ + public ConfigurationResult { + violations = List.copyOf(violations); + } + + /** + * @return whether the configuration is valid + */ + public boolean isValid() { + return configuration != null && violations.isEmpty(); + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/InvalidConfigurationException.java b/trailhand/src/main/java/de/cuioss/trailhand/config/InvalidConfigurationException.java new file mode 100644 index 0000000..86bbbbd --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/config/InvalidConfigurationException.java @@ -0,0 +1,34 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.config; + +import java.io.Serial; + +/** + * Stops the boot on an invalid configuration (TRH-CONF-1). The violations themselves were logged one by one. + */ +public class InvalidConfigurationException extends IllegalStateException { + + @Serial + private static final long serialVersionUID = 1L; + + /** + * @param violations the number of violations + */ + public InvalidConfigurationException(int violations) { + super("Invalid configuration: " + violations + " violation(s), see the log records TRAILHAND-200"); + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/OidcSettings.java b/trailhand/src/main/java/de/cuioss/trailhand/config/OidcSettings.java new file mode 100644 index 0000000..6bc9d5f --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/config/OidcSettings.java @@ -0,0 +1,30 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.config; + +/** + * The web login through Token Sheriff (TRH-AUTH-1): {@code trailhand.yaml} → {@code oidc}. + * + * @param issuer the issuer of the identity provider, an absolute {@code https} URI + * @param clientId the client id of the confidential client + * @param clientCredentialRef the reference to the client secret + * @param groupsClaim the claim the groups are read from, default {@code groups} + */ +public record OidcSettings(String issuer, String clientId, String clientCredentialRef, String groupsClaim) { + + /** The default of {@code groups-claim}. */ + public static final String DEFAULT_GROUPS_CLAIM = "groups"; +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/Placeholders.java b/trailhand/src/main/java/de/cuioss/trailhand/config/Placeholders.java new file mode 100644 index 0000000..886ed11 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/config/Placeholders.java @@ -0,0 +1,96 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.config; + +import lombok.experimental.UtilityClass; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.UnaryOperator; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Resolves {@code ${NAME}} and {@code ${NAME:-default}} in string values from the environment, before validation + * (TRH-CONF-1). {@code NAME} is an environment variable name (letters, digits and underscores, not starting with a + * digit). Any other {@code ${...}}, a nested one in a default included, is reported like an unresolved placeholder, so + * it can never pass as a literal value. + */ +@UtilityClass +public class Placeholders { + + private static final Pattern PLACEHOLDER = Pattern.compile("\\$\\{([^}]*)}"); + private static final Pattern NAME = Pattern.compile("[A-Za-z_]\\w*"); + private static final String DEFAULT_SEPARATOR = ":-"; + + /** + * Resolves every placeholder of a string. + * + * @param value the string + * @param environment the environment + * @param unresolved receives the name of every placeholder without value and without default + * @return the resolved string + */ + public static String resolve(String value, UnaryOperator environment, List unresolved) { + Matcher matcher = PLACEHOLDER.matcher(value); + var result = new StringBuilder(); + while (matcher.find()) { + String body = matcher.group(1); + int separator = body.indexOf(DEFAULT_SEPARATOR); + String name = separator < 0 ? body : body.substring(0, separator); + String replacement = null; + // A nested ${...} in a default is not resolved; it is refused like an unresolved placeholder. + if (NAME.matcher(name).matches() && !body.contains("${")) { + replacement = environment.apply(name); + if (replacement == null && separator >= 0) { + replacement = body.substring(separator + DEFAULT_SEPARATOR.length()); + } + } + if (replacement == null) { + unresolved.add(name); + replacement = ""; + } + matcher.appendReplacement(result, Matcher.quoteReplacement(replacement)); + } + matcher.appendTail(result); + return result.toString(); + } + + /** + * Resolves the placeholders of every string in a tree of maps and lists, as Jackson reads YAML. + * + * @param node a node of the tree + * @param environment the environment + * @param unresolved receives the names of placeholders without value and default + * @return the resolved node + */ + @SuppressWarnings("unchecked") + public static Object resolveTree(Object node, UnaryOperator environment, List unresolved) { + return switch (node) { + case String text -> resolve(text, environment, unresolved); + case Map map -> { + var copy = new LinkedHashMap(); + ((Map) map).forEach((key, value) -> copy.put(key, + value == null ? null : resolveTree(value, environment, unresolved))); + yield copy; + } + case List list -> list.stream() + .map(entry -> entry == null ? null : resolveTree(entry, environment, unresolved)).toList(); + default -> node; + }; + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/RepositorySettings.java b/trailhand/src/main/java/de/cuioss/trailhand/config/RepositorySettings.java new file mode 100644 index 0000000..7e98783 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/config/RepositorySettings.java @@ -0,0 +1,42 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.config; + +import org.jspecify.annotations.Nullable; + +import java.time.Period; + +/** + * One repository of {@code trailhand.yaml} (TRH-CONF-2). + * + * @param alias the stable alias, {@code [a-z0-9-]+} + * @param remote the remote: an {@code https} URL or a {@code file:} URL of a local bare repository + * @param confidentiality the confidentiality class: {@code public-internal}, {@code restricted} or + * {@code strongly-restricted} + * @param retention the retention period; {@code null} for {@code unlimited} + * @param credentialRef the reference to the credential of the technical user; {@code null} for a {@code file:} + * remote + */ +public record RepositorySettings(String alias, String remote, String confidentiality, @Nullable Period retention, +@Nullable String credentialRef) { + + /** + * @return whether the remote is a local bare repository + */ + public boolean isLocal() { + return remote.startsWith("file:"); + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/RightSettings.java b/trailhand/src/main/java/de/cuioss/trailhand/config/RightSettings.java new file mode 100644 index 0000000..9df6148 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/config/RightSettings.java @@ -0,0 +1,37 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.config; + +import java.util.Set; + +/** + * One entry of {@code trailhand.yaml} → {@code rights}: what a group may do on a repository (TRH-AUTH-2). + * + * @param repository the alias of the repository + * @param actions the actions + */ +public record RightSettings(String repository, Set actions) { + + /** + * Copies the actions. + * + * @param repository the alias + * @param actions the actions + */ + public RightSettings { + actions = Set.copyOf(actions); + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/TokenSheriffConfigSourceFactory.java b/trailhand/src/main/java/de/cuioss/trailhand/config/TokenSheriffConfigSourceFactory.java new file mode 100644 index 0000000..053de4b --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/config/TokenSheriffConfigSourceFactory.java @@ -0,0 +1,166 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import io.smallrye.config.ConfigSourceContext; +import io.smallrye.config.ConfigSourceFactory; +import io.smallrye.config.common.MapBackedConfigSource; +import org.eclipse.microprofile.config.spi.ConfigSource; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.OptionalInt; +import java.util.function.UnaryOperator; + +/** + * Derives the configuration of Token Sheriff's client and validation extensions from {@code trailhand.yaml} → + * {@code oidc} and {@code web.origin}, so the operator maintains one policy file (TRH-CONF-1): + * {@code sheriff.client.*} (issuer, client id, client secret from its {@code file:} reference, redirect address, scopes) + * and the issuer {@code sheriff.token.issuers.trailhand.*} that validates the tokens of the login. + *

+ * The source has the ordinal {@value #ORDINAL}: above {@code application.properties}, below the environment. An + * invalid {@code trailhand.yaml} yields no values; the boot then stops in {@link ConfigurationProducer} with every + * violation logged. Transport settings that depend on the deployment (egress hosts, loopback) stay in the + * environment. + */ +public class TokenSheriffConfigSourceFactory implements ConfigSourceFactory { + + /** The ordinal of the derived source. */ + public static final int ORDINAL = 260; + + /** + * The optional key of the JWKS address, for a deployment that reaches the provider under another origin than the + * issuer's (split horizon): it replaces the discovery of the keys through the issuer's well-known document. + */ + public static final String JWKS_URL = "trailhand.oidc.jwks-url"; + + /** The name of the issuer configuration that validates the login's tokens. */ + public static final String ISSUER_NAME = "trailhand"; + + @Override + public Iterable getConfigSources(ConfigSourceContext context) { + var dirValue = context.getValue("trailhand.config.dir"); + var directory = Path.of(dirValue == null || dirValue.getValue() == null ? "config" : dirValue.getValue()); + var keys = new LinkedHashMap<>(derive(directory, System::getenv)); + var jwksUrl = context.getValue(JWKS_URL); + if (!keys.isEmpty() && jwksUrl != null && jwksUrl.getValue() != null && !jwksUrl.getValue().isBlank()) { + useJwksUrl(keys, jwksUrl.getValue().trim()); + } + return List.of(new MapBackedConfigSource("trailhand.yaml (oidc)", keys, ORDINAL) { + }); + } + + @Override + public OptionalInt getPriority() { + return OptionalInt.of(ORDINAL); + } + + /** + * @param directory the configuration directory + * @param environment the environment of the placeholders + * @return the derived keys; empty when {@code trailhand.yaml} is missing or invalid + */ + static Map derive(Path directory, UnaryOperator environment) { + var file = directory.resolve(ConfigurationLoader.FILE_NAME); + if (!Files.isRegularFile(file)) { + return Map.of(); + } + try { + var tree = new ObjectMapper(new YAMLFactory()).readValue(file.toFile(), Object.class); + var result = new ConfigurationLoader(environment).validate(tree); + var configuration = result.configuration(); + if (!result.isValid() || configuration == null) { + return Map.of(); + } + return derive(configuration); + } catch (IOException e) { + return Map.of(); + } + } + + /** + * @param configuration a valid configuration + * @return the derived keys + */ + static Map derive(TrailhandConfiguration configuration) { + var oidc = configuration.oidc(); + var keys = new LinkedHashMap(); + keys.put("sheriff.client.issuer", oidc.issuer()); + keys.put("sheriff.client.client-id", oidc.clientId()); + readSecret(oidc.clientCredentialRef()).ifPresent(secret -> keys.put("sheriff.client.client-secret", secret)); + keys.put("sheriff.client.redirect-uri", + configuration.web().originHeaderValue() + "/api/v1/auth/callback"); + keys.put("sheriff.client.scopes", "openid,profile,email"); + var issuer = "sheriff.token.issuers." + ISSUER_NAME + "."; + keys.put(issuer + "enabled", "true"); + keys.put(issuer + "issuer-identifier", oidc.issuer()); + keys.put(issuer + "jwks.http.well-known-url", stripSlash(oidc.issuer()) + "/.well-known/openid-configuration"); + keys.put(issuer + "expected-client-id", oidc.clientId()); + // Access and ID token are validated by this one issuer configuration: the ID token's audience is the client, + // an access token's audience is the resource the provider names; the client id (azp) is checked for both. + keys.put(issuer + "audience-validation-disabled", "true"); + return keys; + } + + /** + * @param keys the derived keys + * @param jwksUrl the JWKS address + */ + static void useJwksUrl(Map keys, String jwksUrl) { + var issuer = "sheriff.token.issuers." + ISSUER_NAME + "."; + keys.remove(issuer + "jwks.http.well-known-url"); + keys.put(issuer + "jwks.http.url", jwksUrl); + } + + static String withoutTrailingLineBreak(String content) { + if (content.endsWith("\r\n")) { + return content.substring(0, content.length() - 2); + } + if (content.endsWith("\n") || content.endsWith("\r")) { + return content.substring(0, content.length() - 1); + } + return content; + } + + private static String stripSlash(String issuer) { + return issuer.endsWith("/") ? issuer.substring(0, issuer.length() - 1) : issuer; + } + + /** + * Resolves a {@code file:} reference, the only form the loader accepts until the Vault adapter is built. + * + * @param reference the reference + * @return the secret: the file's content without one trailing line break; every other character is kept + */ + static Optional readSecret(String reference) { + if (!reference.startsWith("file:")) { + return Optional.empty(); + } + try { + var content = Files.readString(Path.of(reference.substring("file:".length()))); + return Optional.of(withoutTrailingLineBreak(content)); + } catch (IOException e) { + return Optional.empty(); + } + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/TrailhandConfiguration.java b/trailhand/src/main/java/de/cuioss/trailhand/config/TrailhandConfiguration.java new file mode 100644 index 0000000..7ccf653 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/config/TrailhandConfiguration.java @@ -0,0 +1,50 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.config; + +import java.time.Duration; +import java.util.List; +import java.util.Map; + +/** + * The validated policy configuration of {@code trailhand.yaml} (TRH-CONF-1), as far as the application uses it. + * + * @param repositories the repositories in file order + * @param rights the rights per identity-provider group + * @param oidc the web login + * @param web the web app + * @param fetchInterval the interval of the periodic fetch, default 5 minutes + */ +public record TrailhandConfiguration(List repositories, Map> rights, +OidcSettings oidc, WebSettings web, Duration fetchInterval) { + + /** The default of {@code fetch.interval}. */ + public static final Duration DEFAULT_FETCH_INTERVAL = Duration.ofMinutes(5); + + /** + * Copies the collections. + * + * @param repositories the repositories + * @param rights the rights + * @param oidc the web login + * @param web the web app + * @param fetchInterval the fetch interval + */ + public TrailhandConfiguration { + repositories = List.copyOf(repositories); + rights = Map.copyOf(rights); + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/Violation.java b/trailhand/src/main/java/de/cuioss/trailhand/config/Violation.java new file mode 100644 index 0000000..b8c0474 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/config/Violation.java @@ -0,0 +1,25 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.config; + +/** + * One violation of the configuration: where and which rule (TRH-CONF-1). + * + * @param key the key, e.g. {@code repositories[1].alias} + * @param rule what is wrong, without the value (a value may be a secret's reference or a URL with user information) + */ +public record Violation(String key, String rule) { +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/WebSettings.java b/trailhand/src/main/java/de/cuioss/trailhand/config/WebSettings.java new file mode 100644 index 0000000..c60689c --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/config/WebSettings.java @@ -0,0 +1,149 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.config; + +import java.net.InetAddress; +import java.net.URI; +import java.net.UnknownHostException; +import java.time.Duration; +import java.util.Locale; +import java.util.Optional; + +/** + * The web app: {@code trailhand.yaml} → {@code web} (TRH-AUTH-1, TRH-WEB-8). + * + * @param origin the application's own origin, an absolute {@code https} URI without path; the Origin check and + * the login callback address use it + * @param idleTimeout the idle time after which a session ends, default 30 minutes + * @param maxLifetime the absolute lifetime of a session, default 8 hours + */ +public record WebSettings(URI origin, Duration idleTimeout, Duration maxLifetime) { + + private static final int HTTPS_PORT = 443; + private static final int HTTP_PORT = 80; + private static final int IPV4_BYTES = 4; + private static final int IPV6_BYTES = 16; + private static final int IPV6_PIECES = 8; + + /** The default of {@code session.idle-timeout}. */ + public static final Duration DEFAULT_IDLE_TIMEOUT = Duration.ofMinutes(30); + + /** The default of {@code session.max-lifetime}. */ + public static final Duration DEFAULT_MAX_LIFETIME = Duration.ofHours(8); + + /** + * @return the origin as the browser sends it in the {@code Origin} header: scheme and host in lower case and the + * port only when it is not the default of the scheme (RFC 6454, section 6.1) + */ + public String originHeaderValue() { + var scheme = origin.getScheme().toLowerCase(Locale.ROOT); + var defaultPort = "https".equals(scheme) ? HTTPS_PORT : HTTP_PORT; + var port = origin.getPort() == -1 || origin.getPort() == defaultPort ? "" : ":" + origin.getPort(); + return scheme + "://" + browserHost(origin.getHost()) + port; + } + + /** + * @param host the host of a URI: a name, an IPv4 address or a bracketed IPv6 literal + * @return the host as the browser serializes it: a name in lower case, an IPv6 literal in the form of the URL + * Standard's IPv6 serializer (section 3.6: lower-case hexadecimal without leading zeros, the first longest + * run of two or more zero pieces as {@code ::}, no embedded IPv4) + */ + static String browserHost(String host) { + var lower = host.toLowerCase(Locale.ROOT); + if (!lower.startsWith("[") || !lower.endsWith("]")) { + return lower; + } + return ipv6Pieces(lower.substring(1, lower.length() - 1)).map(pieces -> "[" + ipv6Text(pieces) + "]") + .orElse(lower); + } + + /** + * @param literal an IPv6 literal without brackets + * @return its eight pieces, or empty when it is no IPv6 literal + */ + private static Optional ipv6Pieces(String literal) { + byte[] bytes; + try { + // A literal is only parsed, never looked up. + bytes = InetAddress.getByName(literal).getAddress(); + } catch (UnknownHostException e) { + return Optional.empty(); + } + if (bytes.length == IPV4_BYTES) { + // Java answers an IPv4-mapped literal (::ffff:a.b.c.d) with the IPv4 address; the browser keeps it IPv6. + var mapped = new byte[IPV6_BYTES]; + mapped[10] = (byte) 0xff; + mapped[11] = (byte) 0xff; + System.arraycopy(bytes, 0, mapped, 12, IPV4_BYTES); + bytes = mapped; + } + var pieces = new int[IPV6_PIECES]; + for (int index = 0; index < IPV6_PIECES; index++) { + pieces[index] = ((bytes[2 * index] & 0xff) << 8) | (bytes[2 * index + 1] & 0xff); + } + return Optional.of(pieces); + } + + /** + * @param pieces the eight pieces of an IPv6 address + * @return the address as the URL Standard's IPv6 serializer writes it + */ + private static String ipv6Text(int[] pieces) { + var compress = compressedPiece(pieces); + var text = new StringBuilder(); + var index = 0; + while (index < IPV6_PIECES) { + if (index == compress) { + text.append(index == 0 ? "::" : ":"); + index += zeroRun(pieces, index); + } else { + text.append(Integer.toHexString(pieces[index])); + if (index < IPV6_PIECES - 1) { + text.append(':'); + } + index++; + } + } + return text.toString(); + } + + /** + * @param pieces the eight pieces of an IPv6 address + * @return the index of the first longest run of two or more zero pieces, or {@code -1} + */ + private static int compressedPiece(int[] pieces) { + var longestIndex = -1; + var longestSize = 1; + var index = 0; + while (index < pieces.length) { + var size = zeroRun(pieces, index); + if (size > longestSize) { + longestIndex = index; + longestSize = size; + } + index += Math.max(size, 1); + } + return longestIndex; + } + + private static int zeroRun(int[] pieces, int start) { + var size = 0; + while (start + size < pieces.length && pieces[start + size] == 0) { + size++; + } + return size; + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/package-info.java b/trailhand/src/main/java/de/cuioss/trailhand/config/package-info.java new file mode 100644 index 0000000..b7de4ad --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/config/package-info.java @@ -0,0 +1,22 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Configuration model and boot validation rules (TRH-CONF-1, TRH-CONF-2); depends on nothing else of the application. + */ +@NullMarked +package de.cuioss.trailhand.config; + +import org.jspecify.annotations.NullMarked; diff --git a/trailhand/src/main/java/de/cuioss/trailhand/package-info.java b/trailhand/src/main/java/de/cuioss/trailhand/package-info.java new file mode 100644 index 0000000..26d67b3 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/package-info.java @@ -0,0 +1,22 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * TrailHand: security documents as versioned Git documents (doc/specification/architecture-and-modules.adoc). + */ +@NullMarked +package de.cuioss.trailhand; + +import org.jspecify.annotations.NullMarked; diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/LoginFlowProducer.java b/trailhand/src/main/java/de/cuioss/trailhand/security/LoginFlowProducer.java new file mode 100644 index 0000000..b31cdad --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/security/LoginFlowProducer.java @@ -0,0 +1,56 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.security; + +import de.cuioss.sheriff.token.client.config.ClientConfiguration; +import de.cuioss.sheriff.token.client.flow.AuthorizationCodeFlow; +import de.cuioss.sheriff.token.client.flow.CallbackHandler; +import de.cuioss.sheriff.token.client.flow.IssValidator; +import de.cuioss.sheriff.token.client.flow.TokenEndpointClient; +import de.cuioss.sheriff.token.client.token.IdTokenValidationBridge; +import de.cuioss.sheriff.token.client.token.TokenValidationBridge; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Produces; +import jakarta.inject.Named; + +/** + * Builds the authorization code flow of the web login from Token Sheriff's beans, with the + * {@link QueryResponseModeRequestBuilder} in place of the built-in request builder (TRH-AUTH-1). Without sender + * constraint: the tokens stay on the server. + */ +@ApplicationScoped +public class LoginFlowProducer { + + /** The qualifier of the web login's flow. */ + public static final String WEB_LOGIN = "trailhand-web-login"; + + /** + * @param configuration the client configuration + * @param tokenEndpoint the token endpoint client + * @param accessTokenBridge the access-token validation + * @param idTokenBridge the ID-token validation + * @param issValidator the issuer check of the authorization response (RFC 9207) + * @return the flow + */ + @Produces + @ApplicationScoped + @Named(WEB_LOGIN) + AuthorizationCodeFlow webLoginFlow(ClientConfiguration configuration, TokenEndpointClient tokenEndpoint, + TokenValidationBridge accessTokenBridge, IdTokenValidationBridge idTokenBridge, IssValidator issValidator) { + return new AuthorizationCodeFlow(configuration, tokenEndpoint, accessTokenBridge, idTokenBridge, issValidator, + new QueryResponseModeRequestBuilder(), new CallbackHandler(), null); + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/LoginIdentity.java b/trailhand/src/main/java/de/cuioss/trailhand/security/LoginIdentity.java new file mode 100644 index 0000000..6988b63 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/security/LoginIdentity.java @@ -0,0 +1,49 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.security; + +import org.jspecify.annotations.Nullable; + +import java.time.Instant; +import java.util.List; + +/** + * The identity values a completed login yields (TRH-AUTH-3: issuer, subject, authentication time and context). + * + * @param issuer {@code iss} + * @param subject {@code sub} + * @param name the display name + * @param groups the groups of the configured claim + * @param authTime {@code auth_time}, or {@code null} + * @param acr {@code acr}, or {@code null} + */ +public record LoginIdentity(String issuer, String subject, String name, List groups, +@Nullable Instant authTime, @Nullable String acr) { + + /** + * Copies the groups. + * + * @param issuer the issuer + * @param subject the subject + * @param name the name + * @param groups the groups + * @param authTime the authentication time + * @param acr the authentication context class + */ + public LoginIdentity { + groups = List.copyOf(groups); + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/LoginService.java b/trailhand/src/main/java/de/cuioss/trailhand/security/LoginService.java new file mode 100644 index 0000000..391ef70 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/security/LoginService.java @@ -0,0 +1,350 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.security; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import de.cuioss.sheriff.token.client.auth.ClientAuthentication; +import de.cuioss.sheriff.token.client.discovery.DiscoveryResolver; +import de.cuioss.sheriff.token.client.discovery.ProviderMetadata; +import de.cuioss.sheriff.token.client.flow.AuthorizationCodeFlow; +import de.cuioss.sheriff.token.client.flow.CallbackParameters; +import de.cuioss.sheriff.token.client.flow.ParClient; +import de.cuioss.sheriff.token.client.lifecycle.RevocationClient; +import de.cuioss.sheriff.token.client.lifecycle.StoredToken; +import de.cuioss.sheriff.token.client.lifecycle.TokenLifecycleManager; +import de.cuioss.sheriff.token.client.logout.EndSessionFlow; +import de.cuioss.sheriff.token.client.logout.PostLogoutRedirectValidator; +import de.cuioss.sheriff.token.commons.error.TokenSheriffException; +import de.cuioss.sheriff.token.validation.domain.claim.ClaimValue; +import de.cuioss.sheriff.token.validation.domain.token.IdTokenContent; +import de.cuioss.tools.logging.CuiLogger; +import de.cuioss.trailhand.config.TrailhandConfiguration; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Named; +import org.jspecify.annotations.Nullable; + +import java.io.IOException; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; + +import static de.cuioss.trailhand.TrailhandLogMessages.INFO; +import static de.cuioss.trailhand.TrailhandLogMessages.WARN; + +/** + * The web login of TRH-AUTH-1 on Token Sheriff's confidential client (ADR-0001): authorization code with PKCE + * {@code S256}, session-bound {@code state} and {@code nonce}, issuer check, and PAR (RFC 9126) when the provider + * offers it; tokens stay in Token Sheriff's token + * store under the session id, the browser gets only the session cookie. Logout revokes the held tokens and ends the + * session at the provider (RP-initiated). + */ +@ApplicationScoped +public class LoginService { + + private static final CuiLogger LOGGER = new CuiLogger(LoginService.class); + private static final ObjectMapper JSON = new ObjectMapper(); + + private final DiscoveryResolver discovery; + private final AuthorizationCodeFlow flow; + private final ParClient par; + private final ClientAuthentication clientAuthentication; + private final TokenLifecycleManager tokens; + private final RevocationClient revocation; + private final SessionStore sessions; + private final LoginTransactions transactions; + private final ReturnAddresses returnAddresses; + private final TrailhandConfiguration configuration; + private final AtomicReference<@Nullable ProviderMetadata> metadata = new AtomicReference<>(); + + /** + * @param discovery Token Sheriff's discovery + * @param flow the authorization code flow + * @param par the client of the pushed-authorization-request endpoint + * @param clientAuthentication the client authentication + * @param tokens the token store of the sessions + * @param revocation the revocation client + * @param sessions the sessions + * @param transactions the login transactions + * @param returnAddresses the return check + * @param configuration the configuration + */ + @SuppressWarnings("java:S107") // the collaborators of the flow; grouping them would only hide them + public LoginService(DiscoveryResolver discovery, @Named(LoginFlowProducer.WEB_LOGIN) AuthorizationCodeFlow flow, + ParClient par, ClientAuthentication clientAuthentication, TokenLifecycleManager tokens, RevocationClient revocation, + SessionStore sessions, LoginTransactions transactions, ReturnAddresses returnAddresses, + TrailhandConfiguration configuration) { + this.discovery = discovery; + this.flow = flow; + this.par = par; + this.clientAuthentication = clientAuthentication; + this.tokens = tokens; + this.revocation = revocation; + this.sessions = sessions; + this.transactions = transactions; + this.returnAddresses = returnAddresses; + this.configuration = configuration; + } + + /** + * The provider's metadata, read once: the resolver of Token Sheriff fetches on every call. + * + * @return the metadata + */ + ProviderMetadata metadata() { + var current = metadata.get(); + if (current == null) { + current = discovery.resolve(); + metadata.set(current); + } + return current; + } + + /** + * Starts a login. When the provider offers PAR, the authorization parameters are pushed to it and the browser + * goes to the provider with {@code client_id} and {@code request_uri} only. + * + * @param requestedReturn the {@code return} of the request + * @return the authorization address and the transaction reference for the cookie + * @throws TokenSheriffException if the provider cannot be reached or refuses the flow + * @throws TooManyLoginsException if {@value LoginTransactions#MAX_PENDING} logins are pending + */ + public LoginStart start(@Nullable String requestedReturn) { + var metadataNow = metadata(); + var redirect = flow.authorize(metadataNow); + var reference = transactions.begin(redirect.context(), returnAddresses.check(requestedReturn)) + .orElseThrow(TooManyLoginsException::new); + var started = false; + try { + var start = new LoginStart(authorizationAddress(metadataNow, redirect.authorizationUrl()), reference); + started = true; + return start; + } finally { + if (!started) { + // The reference never reaches the browser: free its place at once instead of waiting for its expiry. + transactions.take(reference); + } + } + } + + /** + * @param metadataNow the provider's metadata + * @param direct the authorization address with every parameter in its query + * @return the direct address, or with PAR the authorization endpoint with {@code client_id} and + * {@code request_uri} + */ + String authorizationAddress(ProviderMetadata metadataNow, String direct) { + var endpoint = metadataNow.getPushedAuthorizationRequestEndpoint(); + var queryStart = direct.indexOf('?'); + if (endpoint.isEmpty() || queryStart < 0) { + return direct; + } + var parameters = queryParameters(direct.substring(queryStart + 1)); + var clientId = parameters.get("client_id"); + var requestUri = par.pushAuthorizationRequest(endpoint.get(), parameters, clientAuthentication).getRequestUri() + .orElseThrow(() -> new IllegalStateException("PAR answer without request_uri")); + return direct.substring(0, queryStart) + "?client_id=" + encode(clientId == null ? "" : clientId) + + "&request_uri=" + encode(requestUri); + } + + static Map queryParameters(String query) { + var parameters = new LinkedHashMap(); + for (String pair : query.split("&")) { + if (pair.isEmpty()) { + continue; + } + var separator = pair.indexOf('='); + var name = separator < 0 ? pair : pair.substring(0, separator); + var value = separator < 0 ? "" : pair.substring(separator + 1); + parameters.put(URLDecoder.decode(name, StandardCharsets.UTF_8), + URLDecoder.decode(value, StandardCharsets.UTF_8)); + } + return parameters; + } + + private static String encode(String value) { + return URLEncoder.encode(value, StandardCharsets.UTF_8); + } + + /** + * Completes a login from the provider's answer. + * + * @param transactionReference the reference from the transaction cookie, or {@code null} when it is missing + * @param callbackQuery the raw query of the callback ({@code code}, {@code state}, {@code iss}) + * @return the new session and the return address, or empty when the login cannot be completed + */ + public Optional complete(@Nullable String transactionReference, String callbackQuery) { + if (transactionReference == null) { + LOGGER.warn(WARN.LOGIN_FAILED, "no login transaction cookie"); + return Optional.empty(); + } + var transaction = transactions.take(transactionReference); + if (transaction.isEmpty()) { + LOGGER.warn(WARN.LOGIN_FAILED, "unknown or expired login transaction"); + return Optional.empty(); + } + try { + var callback = CallbackParameters.parse(callbackQuery); + var result = flow.exchange(metadata(), transaction.get().context(), callback, clientAuthentication); + var identity = identity(result.idToken()); + var session = sessions.open(identity); + tokens.store(session.id(), new StoredToken(result.accessToken().getRawToken(), result.refreshToken(), + result.idToken().getRawToken(), null, result.accessToken().getExpirationDateTime().toInstant(), + identity.subject())); + LOGGER.info(INFO.LOGIN_COMPLETED, identity.issuer()); + return Optional.of(new LoginCompletion(session, transaction.get().returnAddress())); + } catch (TokenSheriffException | IllegalArgumentException | IllegalStateException e) { + LOGGER.warn(WARN.LOGIN_FAILED, e.getClass().getSimpleName()); + return Optional.empty(); + } + } + + private LoginIdentity identity(IdTokenContent idToken) { + var subject = idToken.getSubject().orElseThrow(() -> new IllegalStateException("ID token without sub")); + var claims = idToken.getClaims(); + var groups = groups(idToken.getRawToken(), configuration.oidc().groupsClaim()); + var authTime = Optional.ofNullable(claims.get("auth_time")).map(ClaimValue::getOriginalString) + .flatMap(LoginService::epochSeconds).orElse(null); + var acr = Optional.ofNullable(claims.get("acr")).map(ClaimValue::getOriginalString).orElse(null); + var name = idToken.getDisplayName().orElse(subject); + return new LoginIdentity(idToken.getIssuer(), subject, name, groups, authTime, acr); + } + + /** + * Reads the groups from the JSON payload of the validated ID token: an array yields its strings, a single string + * one group, anything else none. The claim is read as the provider wrote it, so a group name that contains a comma + * stays one group. + * + * @param rawToken the validated ID token (a JWS) + * @param claim the name of the group claim + * @return the groups, empty when the claim is missing or the token cannot be read + */ + static List groups(String rawToken, String claim) { + var parts = rawToken.split("\\."); + if (parts.length != 3) { + return List.of(); + } + try { + var value = JSON.readTree(Base64.getUrlDecoder().decode(parts[1])).get(claim); + return groups(value); + } catch (IOException | IllegalArgumentException e) { + LOGGER.warn(WARN.LOGIN_FAILED, "unreadable group claim"); + return List.of(); + } + } + + private static List groups(@Nullable JsonNode value) { + if (value == null) { + return List.of(); + } + if (value.isTextual()) { + return value.asText().isBlank() ? List.of() : List.of(value.asText()); + } + var groups = new ArrayList(); + if (value.isArray()) { + value.forEach(entry -> { + if (entry.isTextual() && !entry.asText().isBlank()) { + groups.add(entry.asText()); + } + }); + } + return List.copyOf(groups); + } + + static Optional epochSeconds(@Nullable String text) { + try { + return text == null ? Optional.empty() : Optional.of(Instant.ofEpochSecond(Long.parseLong(text.trim()))); + } catch (NumberFormatException e) { + return Optional.empty(); + } + } + + /** + * Ends a session: revokes the held tokens, then builds the RP-initiated logout address of the provider. + * + * @param sessionId the session id + * @return the address the browser navigates to: the provider's end-session address, or the own origin when the + * provider has none + */ + public String logout(String sessionId) { + sessions.close(sessionId); + var held = tokens.revokeAndClear(sessionId); + var home = configuration.web().originHeaderValue() + "/"; + if (held.isEmpty()) { + return home; + } + var metadataNow = metadata(); + revoke(metadataNow, held.get().refreshToken(), "refresh_token"); + revoke(metadataNow, held.get().accessToken(), "access_token"); + var endSession = metadataNow.getEndSessionEndpoint(); + var idToken = held.get().idToken(); + if (endSession.isEmpty() || idToken == null) { + return home; + } + LOGGER.info(INFO.LOGOUT_COMPLETED); + return new EndSessionFlow(new PostLogoutRedirectValidator(Set.of(home))) + .buildLogoutRedirect(endSession.get(), idToken, home, SessionStore.randomToken()); + } + + private void revoke(ProviderMetadata metadataNow, @Nullable String token, String hint) { + var endpoint = metadataNow.getRevocationEndpoint(); + if (token == null || endpoint.isEmpty()) { + return; + } + try { + revocation.revoke(endpoint.get(), token, hint, clientAuthentication); + } catch (TokenSheriffException e) { + LOGGER.warn(WARN.REVOCATION_FAILED, e.getClass().getSimpleName()); + } + } + + /** + * The start of a login. + * + * @param authorizationUrl where the browser goes + * @param transactionReference the value of the transaction cookie + */ + public record LoginStart(String authorizationUrl, String transactionReference) { + } + + /** + * A completed login. + * + * @param session the new session + * @param returnAddress the checked return address + */ + public record LoginCompletion(UserSession session, String returnAddress) { + } + + /** Thrown when the login cannot start because {@value LoginTransactions#MAX_PENDING} logins are pending. */ + public static final class TooManyLoginsException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + TooManyLoginsException() { + super("too many pending logins"); + } + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/LoginTransactions.java b/trailhand/src/main/java/de/cuioss/trailhand/security/LoginTransactions.java new file mode 100644 index 0000000..ec01d3a --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/security/LoginTransactions.java @@ -0,0 +1,159 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.security; + +import de.cuioss.sheriff.token.client.flow.FlowContext; +import jakarta.enterprise.context.ApplicationScoped; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Map; +import java.util.Optional; +import java.util.Queue; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * The server-side login transactions (TRH-AUTH-1): {@code state}, {@code nonce} and PKCE verifier (Token Sheriff's + * {@link FlowContext}) and the checked {@code return}, under an opaque reference the transaction cookie carries. + * A transaction lives ten minutes and is taken once. + *

+ * The login is reachable without a session, so the store is bounded: at most {@value #MAX_PENDING} transactions are + * pending. Every transaction lives {@link #LIFETIME}, so the order of the starts is the order of expiry: a queue in + * that order lets each start drop the expired and the taken transactions at its head, without scanning the store. + */ +@ApplicationScoped +public class LoginTransactions { + + /** The lifetime of a transaction, also the {@code Max-Age} of its cookie. */ + public static final Duration LIFETIME = Duration.ofMinutes(10); + + /** The most transactions pending at once; a start beyond it is refused. */ + public static final int MAX_PENDING = 10_000; + + private final Map transactions = new ConcurrentHashMap<>(); + /** The references in the order of their start, which is the order of their expiry. */ + private final Queue byExpiry = new ConcurrentLinkedQueue<>(); + private final AtomicInteger queued = new AtomicInteger(); + private final AtomicBoolean compacting = new AtomicBoolean(); + private final AtomicInteger pending = new AtomicInteger(); + private final Clock clock; + private final int maxPending; + + /** Creates the store with the system clock. */ + public LoginTransactions() { + this(Clock.systemUTC(), MAX_PENDING); + } + + /** + * @param clock the clock + * @param maxPending the most transactions pending at once + */ + LoginTransactions(Clock clock, int maxPending) { + this.clock = clock; + this.maxPending = maxPending; + } + + /** + * @param context the flow context of the authorization request + * @param returnAddress the checked return address + * @return the opaque reference for the transaction cookie, or empty when {@value #MAX_PENDING} logins are pending + */ + public Optional begin(FlowContext context, String returnAddress) { + var now = clock.instant(); + dropExpired(now); + if (pending.incrementAndGet() > maxPending) { + pending.decrementAndGet(); + return Optional.empty(); + } + var reference = SessionStore.randomToken(); + // The expiry is taken and queued in one step, so the queue order is the expiry order across threads. + synchronized (byExpiry) { + transactions.put(reference, new Transaction(context, returnAddress, clock.instant().plus(LIFETIME))); + byExpiry.add(reference); + } + if (queued.incrementAndGet() > 2 * Math.max(maxPending, 1)) { + compact(); + } + return Optional.of(reference); + } + + /** + * Takes a transaction: it can be completed once. + * + * @param reference the reference from the cookie + * @return the live transaction, or empty + */ + public Optional take(String reference) { + var transaction = transactions.remove(reference); + if (transaction == null) { + return Optional.empty(); + } + pending.decrementAndGet(); + return transaction.expires().isBefore(clock.instant()) ? Optional.empty() : Optional.of(transaction); + } + + /** + * Drops the transactions at the head of the queue that are taken or expired; it stops at the first live one, so + * its cost is the number of transactions it drops. + * + * @param now the current time + */ + private void dropExpired(Instant now) { + for (String head = byExpiry.peek(); head != null; head = byExpiry.peek()) { + var transaction = transactions.get(head); + if (transaction != null && !transaction.expires().isBefore(now)) { + return; + } + if (byExpiry.remove(head)) { + queued.decrementAndGet(); + if (transaction != null && transactions.remove(head, transaction)) { + pending.decrementAndGet(); + } + } + } + } + + /** + * Drops the references of taken transactions from the queue. It runs when the queue holds twice the limit, which + * only starts that are taken again soon can cause; after it the queue holds at most the pending transactions, so + * its cost is spread over the starts that filled it. + */ + private void compact() { + if (!compacting.compareAndSet(false, true)) { + return; + } + try { + byExpiry.removeIf(reference -> !transactions.containsKey(reference)); + queued.set(byExpiry.size()); + } finally { + compacting.set(false); + } + } + + /** + * A pending login. + * + * @param context the flow context + * @param returnAddress the checked return address + * @param expires when the transaction ends + */ + public record Transaction(FlowContext context, String returnAddress, Instant expires) { + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/QueryResponseModeRequestBuilder.java b/trailhand/src/main/java/de/cuioss/trailhand/security/QueryResponseModeRequestBuilder.java new file mode 100644 index 0000000..057e16f --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/security/QueryResponseModeRequestBuilder.java @@ -0,0 +1,84 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.security; + +import de.cuioss.sheriff.token.client.config.ClientConfiguration; +import de.cuioss.sheriff.token.client.discovery.ProviderMetadata; +import de.cuioss.sheriff.token.client.flow.AuthorizationRequestBuilder; +import de.cuioss.sheriff.token.client.flow.FlowContext; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * Drives the authorization request with {@code response_mode=query} instead of Token Sheriff's built-in + * {@code response_mode=form_post} (TRH-AUTH-1). + *

+ * With {@code form_post} the provider answers with a cross-site {@code POST} to the callback, with which a browser + * sends no {@code SameSite=Lax} cookie, so the login-transaction cookie would not arrive. With {@code query} the + * callback is a top-level {@code GET} navigation, which carries it. The cookie keeps {@code SameSite=Lax}; the + * alternative {@code SameSite=None} would weaken the binding the cookie exists for. The same decision and reasoning as + * API Sheriff's {@code QueryResponseModeAuthorizationRequestBuilder}. + *

+ * Accepted trade-off: the code travels in the callback's query string. It is bounded by PKCE (the code cannot be + * redeemed without the verifier, which stays on the server), by the single use of the code, by the login transaction + * with {@code state}, and by {@code Referrer-Policy: no-referrer} on every answer. The rewrite touches only + * {@code response_mode} and keeps every other parameter in its order and encoding. + */ +public class QueryResponseModeRequestBuilder extends AuthorizationRequestBuilder { + + private static final String RESPONSE_MODE = "response_mode"; + private static final String QUERY_PAIR = RESPONSE_MODE + "=query"; + + @Override + public String build(ClientConfiguration configuration, ProviderMetadata metadata, FlowContext context) { + return withQueryResponseMode(super.build(configuration, metadata, context)); + } + + /** + * @param authorizationUrl an authorization address + * @return the address with {@code response_mode=query}, added or replacing the existing value + */ + static String withQueryResponseMode(String authorizationUrl) { + Objects.requireNonNull(authorizationUrl, "authorizationUrl"); + int queryStart = authorizationUrl.indexOf('?'); + if (queryStart < 0) { + return authorizationUrl + '?' + QUERY_PAIR; + } + var prefix = authorizationUrl.substring(0, queryStart + 1); + var query = authorizationUrl.substring(queryStart + 1); + if (query.isEmpty()) { + return prefix + QUERY_PAIR; + } + List pairs = new ArrayList<>(); + boolean rewritten = false; + for (String pair : query.split("&", -1)) { + int separator = pair.indexOf('='); + var name = separator < 0 ? pair : pair.substring(0, separator); + if (RESPONSE_MODE.equals(name)) { + pairs.add(QUERY_PAIR); + rewritten = true; + } else { + pairs.add(pair); + } + } + if (!rewritten) { + pairs.add(QUERY_PAIR); + } + return prefix + String.join("&", pairs); + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/ReturnAddresses.java b/trailhand/src/main/java/de/cuioss/trailhand/security/ReturnAddresses.java new file mode 100644 index 0000000..54443f5 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/security/ReturnAddresses.java @@ -0,0 +1,113 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.security; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.enterprise.context.ApplicationScoped; +import org.jspecify.annotations.Nullable; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * The check of the login's {@code return} (TRH-AUTH-1): a same-origin relative path that matches a canonical address + * of the web app (TRH-WEB-3); anything else becomes {@code /}. The addresses are the ones the web app routes with, + * {@code META-INF/trailhand/canonical-addresses.json} of the {@code web-app} JAR. + */ +@ApplicationScoped +public class ReturnAddresses { + + /** The resource holding the canonical addresses. */ + public static final String RESOURCE = "META-INF/trailhand/canonical-addresses.json"; + + /** The address used for every refused value. */ + public static final String DEFAULT = "/"; + + private static final Pattern PLACEHOLDER = Pattern.compile("\\{([a-z][a-z0-9]*)}"); + private static final int MAX_LENGTH = 512; + + private final List patterns; + + /** + * Reads the canonical addresses from the class path. + */ + public ReturnAddresses() { + this(readResource()); + } + + /** + * @param definition the content of {@code canonical-addresses.json} + */ + ReturnAddresses(JsonNode definition) { + var segment = definition.path("segment").asText(); + var params = definition.path("params"); + var compiled = new ArrayList(); + for (JsonNode address : definition.path("addresses")) { + Matcher matcher = PLACEHOLDER.matcher(address.path("pattern").asText()); + var regex = new StringBuilder(); + int last = 0; + var pattern = address.path("pattern").asText(); + while (matcher.find()) { + regex.append(Pattern.quote(pattern.substring(last, matcher.start()))); + var own = params.path(matcher.group(1)); + regex.append('(').append(own.isMissingNode() ? segment : own.asText()).append(')'); + last = matcher.end(); + } + regex.append(Pattern.quote(pattern.substring(last))); + compiled.add(Pattern.compile(regex.toString())); + } + this.patterns = List.copyOf(compiled); + } + + private static JsonNode readResource() { + try (InputStream in = ReturnAddresses.class.getClassLoader().getResourceAsStream(RESOURCE)) { + if (in == null) { + throw new IllegalStateException(RESOURCE + " is missing from the class path"); + } + return new ObjectMapper().readTree(in); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** + * @param value the {@code return} of the login request, possibly {@code null} + * @return the value when it is a canonical address, otherwise {@code /} + */ + public String check(@Nullable String value) { + if (value == null || value.isEmpty() || value.length() > MAX_LENGTH || !value.startsWith("/") + || value.startsWith("//") || value.contains("\\")) { + return DEFAULT; + } + int query = value.indexOf('?'); + var path = query < 0 ? value : value.substring(0, query); + if (path.length() > 1 && path.endsWith("/")) { + path = path.substring(0, path.length() - 1); + } + for (Pattern pattern : patterns) { + if (pattern.matcher(path).matches()) { + return path; + } + } + return DEFAULT; + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/RightsMapper.java b/trailhand/src/main/java/de/cuioss/trailhand/security/RightsMapper.java new file mode 100644 index 0000000..f0cb920 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/security/RightsMapper.java @@ -0,0 +1,79 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.security; + +import de.cuioss.trailhand.config.Action; +import de.cuioss.trailhand.config.RightSettings; +import de.cuioss.trailhand.config.TrailhandConfiguration; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.Collection; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +/** + * Derives the rights of a user from the identity-provider groups through {@code trailhand.yaml} → {@code rights} + * (TRH-AUTH-2). Deny by default: a group without mapping grants nothing, and nothing else grants a right. + */ +@ApplicationScoped +public class RightsMapper { + + private final Map> rights; + + /** + * @param configuration the configuration + */ + @Inject + public RightsMapper(TrailhandConfiguration configuration) { + this(configuration.rights()); + } + + /** + * @param rights the mapping group → rights + */ + RightsMapper(Map> rights) { + this.rights = Map.copyOf(rights); + } + + /** + * @param groups the user's groups + * @return the actions per repository alias, in alias order; repositories without a right are absent + */ + public Map> rightsOf(Collection groups) { + var result = new TreeMap>(); + for (String group : groups) { + for (RightSettings right : rights.getOrDefault(group, List.of())) { + result.computeIfAbsent(right.repository(), alias -> EnumSet.noneOf(Action.class)) + .addAll(right.actions()); + } + } + return result; + } + + /** + * @param groups the user's groups + * @param repository the repository alias + * @param action the action + * @return whether one of the groups maps the action on the repository + */ + public boolean permits(Collection groups, String repository, Action action) { + return rightsOf(groups).getOrDefault(repository, Set.of()).contains(action); + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/SessionJanitor.java b/trailhand/src/main/java/de/cuioss/trailhand/security/SessionJanitor.java new file mode 100644 index 0000000..d34af50 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/security/SessionJanitor.java @@ -0,0 +1,62 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.security; + +import de.cuioss.sheriff.token.client.lifecycle.TokenLifecycleManager; +import io.quarkus.runtime.ShutdownEvent; +import io.quarkus.runtime.StartupEvent; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import org.jspecify.annotations.Nullable; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * Removes expired sessions every minute and drops their tokens (TRH-AUTH-1: idle timeout and absolute lifetime). + */ +@ApplicationScoped +public class SessionJanitor { + + private final SessionStore sessions; + private final TokenLifecycleManager tokens; + private @Nullable ScheduledExecutorService scheduler; + + /** + * @param sessions the sessions + * @param tokens the tokens of the sessions + */ + public SessionJanitor(SessionStore sessions, TokenLifecycleManager tokens) { + this.sessions = sessions; + this.tokens = tokens; + } + + void onStart(@Observes StartupEvent event) { + scheduler = Executors.newSingleThreadScheduledExecutor(Thread.ofVirtual().name("trailhand-sessions").factory()); + scheduler.scheduleWithFixedDelay(this::evict, 1, 1, TimeUnit.MINUTES); + } + + void onStop(@Observes ShutdownEvent event) { + if (scheduler != null) { + scheduler.shutdownNow(); + } + } + + void evict() { + sessions.evictExpired().forEach(tokens::revokeAndClear); + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/SessionStore.java b/trailhand/src/main/java/de/cuioss/trailhand/security/SessionStore.java new file mode 100644 index 0000000..572236e --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/security/SessionStore.java @@ -0,0 +1,147 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.security; + +import de.cuioss.trailhand.config.TrailhandConfiguration; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Queue; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * The web sessions, held in memory (TRH-AUTH-1, TRH-GEN-3: sessions are lost on restart; ADR-0001: one instance). + * A session ends after the idle timeout or the absolute lifetime of {@code web.session}. + */ +@ApplicationScoped +public class SessionStore { + + private static final SecureRandom RANDOM = new SecureRandom(); + + private final Map sessions = new ConcurrentHashMap<>(); + /** The ids of sessions {@link #use(String)} found expired, until {@link #evictExpired()} hands them on. */ + private final Queue ended = new ConcurrentLinkedQueue<>(); + private final Duration idleTimeout; + private final Duration maxLifetime; + private final Clock clock; + + /** + * @param configuration the configuration with the session lifetimes + */ + @Inject + public SessionStore(TrailhandConfiguration configuration) { + this(configuration.web().idleTimeout(), configuration.web().maxLifetime(), Clock.systemUTC()); + } + + /** + * @param idleTimeout the idle timeout + * @param maxLifetime the absolute lifetime + * @param clock the clock + */ + SessionStore(Duration idleTimeout, Duration maxLifetime, Clock clock) { + this.idleTimeout = idleTimeout; + this.maxLifetime = maxLifetime; + this.clock = clock; + } + + /** + * @return a random, URL-safe token of 256 bits + */ + public static String randomToken() { + byte[] bytes = new byte[32]; + RANDOM.nextBytes(bytes); + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + /** + * Opens a session for a completed login. + * + * @param identity the identity values of the login + * @return the new session + */ + public UserSession open(LoginIdentity identity) { + var now = clock.instant(); + var session = new UserSession(randomToken(), identity.issuer(), identity.subject(), identity.name(), + identity.groups(), identity.authTime(), identity.acr(), randomToken(), now, now); + sessions.put(session.id(), session); + return session; + } + + /** + * Finds a live session and records the access; an expired one is removed, and its id is kept for + * {@link #evictExpired()}, which hands it on so its tokens are dropped. Check and renewal are one atomic step: a + * session closed meanwhile is not brought back. + * + * @param id the session id from the cookie + * @return the session, or empty when unknown or expired + */ + public Optional use(String id) { + var found = new AtomicBoolean(); + var touched = sessions.computeIfPresent(id, (key, session) -> { + found.set(true); + // The clock is read inside the atomic step: an older request cannot undo a newer renewal. + var now = clock.instant(); + return expired(session, now) ? null : session.touched(now); + }); + if (touched == null && found.get()) { + ended.add(id); + } + return Optional.ofNullable(touched); + } + + /** + * @param id the session id + * @return the removed session, if it existed + */ + public Optional close(String id) { + return Optional.ofNullable(sessions.remove(id)); + } + + /** + * Removes every expired session. A session is removed only as it was found expired: one renewed meanwhile stays. + * + * @return the ids of the sessions removed here or found expired by {@link #use(String)} since the last call, so + * their tokens can be dropped + */ + public List evictExpired() { + var now = clock.instant(); + var removed = new ArrayList(); + for (UserSession session : sessions.values()) { + if (expired(session, now) && sessions.remove(session.id(), session)) { + removed.add(session.id()); + } + } + for (String id = ended.poll(); id != null; id = ended.poll()) { + removed.add(id); + } + return removed; + } + + private boolean expired(UserSession session, Instant now) { + return session.lastAccess().plus(idleTimeout).isBefore(now) || session.created().plus(maxLifetime).isBefore(now); + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/TokenClientNativeRegistration.java b/trailhand/src/main/java/de/cuioss/trailhand/security/TokenClientNativeRegistration.java new file mode 100644 index 0000000..92b46f5 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/security/TokenClientNativeRegistration.java @@ -0,0 +1,64 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.security; + +import de.cuioss.sheriff.token.client.discovery.ProviderMetadata; +import de.cuioss.sheriff.token.client.discovery._ProviderMetadata_DslJsonConverter; +import de.cuioss.sheriff.token.client.flow.ParResponse; +import de.cuioss.sheriff.token.client.flow._ParResponse_DslJsonConverter; +import de.cuioss.sheriff.token.client.internal.AccessTokenConfirmation; +import de.cuioss.sheriff.token.client.internal._AccessTokenConfirmation$Confirmation_DslJsonConverter; +import de.cuioss.sheriff.token.client.internal._AccessTokenConfirmation$JsonObjectProbe_DslJsonConverter; +import de.cuioss.sheriff.token.client.internal._AccessTokenConfirmation_DslJsonConverter; +import de.cuioss.sheriff.token.client.token.TokenErrorResponse; +import de.cuioss.sheriff.token.client.token.TokenResponse; +import de.cuioss.sheriff.token.client.token.UserInfoResponse; +import de.cuioss.sheriff.token.client.token._TokenErrorResponse_DslJsonConverter; +import de.cuioss.sheriff.token.client.token._TokenResponse_DslJsonConverter; +import de.cuioss.sheriff.token.client.token._UserInfoResponse_DslJsonConverter; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * Registers the response types of Token Sheriff's client and their generated DSL-JSON converters for reflection, so + * the client can read the provider's answers (discovery, token, error, PAR, user info, confirmation) in the native + * image (TRH-OPS-1). DSL-JSON finds a converter by name and instantiates it reflectively; without the registration the + * native image answers "Unable to find reader for provided type". The same registration as API Sheriff's + * {@code TokenClientDslJsonReflection}; naming the classes by symbol makes a rename in the client fail the build. + */ +@RegisterForReflection(targets = { + _ProviderMetadata_DslJsonConverter.class, + _ParResponse_DslJsonConverter.class, + _TokenResponse_DslJsonConverter.class, + _TokenErrorResponse_DslJsonConverter.class, + _UserInfoResponse_DslJsonConverter.class, + _AccessTokenConfirmation_DslJsonConverter.class, + _AccessTokenConfirmation$Confirmation_DslJsonConverter.class, + _AccessTokenConfirmation$JsonObjectProbe_DslJsonConverter.class, + ProviderMetadata.class, + ParResponse.class, + TokenResponse.class, + TokenErrorResponse.class, + UserInfoResponse.class, + AccessTokenConfirmation.class, + AccessTokenConfirmation.Confirmation.class, + AccessTokenConfirmation.JsonObjectProbe.class +}) +public final class TokenClientNativeRegistration { + + private TokenClientNativeRegistration() { + // registration holder + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/UserSession.java b/trailhand/src/main/java/de/cuioss/trailhand/security/UserSession.java new file mode 100644 index 0000000..6407f33 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/security/UserSession.java @@ -0,0 +1,72 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.security; + +import org.jspecify.annotations.Nullable; + +import java.time.Instant; +import java.util.List; + +/** + * A server-side web session (TRH-AUTH-1): the identity values of the login, the anti-CSRF token and the lifetimes. + * The browser holds only the opaque session id in a cookie; tokens stay in Token Sheriff's token store under the + * same id. + * + * @param id the opaque session id, the cookie value + * @param issuer {@code iss} + * @param subject {@code sub} + * @param name the display name from the token + * @param groups the groups the rights are mapped from + * @param authTime {@code auth_time}, or {@code null} when the token carries none + * @param acr {@code acr}, or {@code null} + * @param csrfToken the anti-CSRF token of TRH-WEB-8 + * @param created when the session began + * @param lastAccess when the session was last used + */ +public record UserSession(String id, String issuer, String subject, String name, List groups, +@Nullable Instant authTime, @Nullable String acr, String csrfToken, Instant created, Instant lastAccess) { + + /** + * Copies the groups. + * + * @param id the id + * @param issuer the issuer + * @param subject the subject + * @param name the name + * @param groups the groups + * @param authTime the authentication time + * @param acr the authentication context class + * @param csrfToken the anti-CSRF token + * @param created the start + * @param lastAccess the last use + */ + public UserSession { + groups = List.copyOf(groups); + } + + /** + * @param now the time of the access + * @return this session, used at {@code now} + */ + public UserSession touched(Instant now) { + return new UserSession(id, issuer, subject, name, groups, authTime, acr, csrfToken, created, now); + } + + @Override + public String toString() { + return "UserSession[issuer=" + issuer + ", created=" + created + "]"; + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/package-info.java b/trailhand/src/main/java/de/cuioss/trailhand/security/package-info.java new file mode 100644 index 0000000..2cc8987 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/security/package-info.java @@ -0,0 +1,22 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Rights mapping, the server-side session and the login through Token Sheriff (TRH-AUTH-1, TRH-AUTH-2). + */ +@NullMarked +package de.cuioss.trailhand.security; + +import org.jspecify.annotations.NullMarked; diff --git a/trailhand/src/main/java/de/cuioss/trailhand/service/GitRemoteHealthCheck.java b/trailhand/src/main/java/de/cuioss/trailhand/service/GitRemoteHealthCheck.java new file mode 100644 index 0000000..2905d6e --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/service/GitRemoteHealthCheck.java @@ -0,0 +1,50 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.service; + +import io.smallrye.health.api.HealthGroup; +import jakarta.enterprise.context.ApplicationScoped; +import org.eclipse.microprofile.health.HealthCheck; +import org.eclipse.microprofile.health.HealthCheckResponse; + +/** + * The check {@code git-remote} (TRH-GEN-6): {@code DOWN} while the fetch of a repository fails, with the fetch state + * per alias. It is a health group of its own ({@code /q/health/group/git-remote}), so an unreachable Git server + * neither drops readiness nor restarts the container. + */ +@HealthGroup("git-remote") +@ApplicationScoped +public class GitRemoteHealthCheck implements HealthCheck { + + private final RepositoryService repositories; + + /** + * @param repositories the repository service + */ + public GitRemoteHealthCheck(RepositoryService repositories) { + this.repositories = repositories; + } + + @Override + public HealthCheckResponse call() { + var snapshot = repositories.states(); + var builder = HealthCheckResponse.named("git-remote").status(!RepositoryService.degraded(snapshot)); + for (RepositoryState state : snapshot) { + builder.withData(state.alias(), state.fetchUp() ? "UP" : "DOWN"); + } + return builder.build(); + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoriesHealthCheck.java b/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoriesHealthCheck.java new file mode 100644 index 0000000..15d7f40 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoriesHealthCheck.java @@ -0,0 +1,60 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.service; + +import jakarta.enterprise.context.ApplicationScoped; +import org.eclipse.microprofile.health.HealthCheck; +import org.eclipse.microprofile.health.HealthCheckResponse; +import org.eclipse.microprofile.health.Readiness; + +/** + * The readiness check {@code repositories} (TRH-OPS-2): {@code UP} once every repository has a local copy; a later + * fetch failure does not drop it. The data name the fetch state per alias. + */ +@Readiness +@ApplicationScoped +public class RepositoriesHealthCheck implements HealthCheck { + + private final RepositoryService repositories; + + /** + * @param repositories the repository service + */ + public RepositoriesHealthCheck(RepositoryService repositories) { + this.repositories = repositories; + } + + @Override + public HealthCheckResponse call() { + var snapshot = repositories.states(); + var builder = HealthCheckResponse.named("repositories").status(RepositoryService.allPresent(snapshot)); + for (RepositoryState state : snapshot) { + builder.withData(state.alias(), describe(state)); + } + return builder.build(); + } + + /** + * @param state the state of one repository + * @return {@code ABSENT}, {@code UP} or {@code FETCH_DOWN} + */ + static String describe(RepositoryState state) { + if (!state.present()) { + return "ABSENT"; + } + return state.fetchUp() ? "UP" : "FETCH_DOWN"; + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryLifecycle.java b/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryLifecycle.java new file mode 100644 index 0000000..a35f091 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryLifecycle.java @@ -0,0 +1,109 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.service; + +import de.cuioss.tools.logging.CuiLogger; +import de.cuioss.trailhand.config.TrailhandConfiguration; +import io.quarkus.runtime.ShutdownEvent; +import io.quarkus.runtime.StartupEvent; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import jakarta.enterprise.inject.Produces; +import jakarta.inject.Singleton; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import org.jspecify.annotations.Nullable; + +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import static de.cuioss.trailhand.TrailhandLogMessages.WARN; + +/** + * Creates the {@link RepositoryService} at boot, clones or opens every repository in the background and fetches at + * {@code fetch.interval} (TRH-CONF-2). The boot does not wait for the Git server: readiness reports the state + * (TRH-OPS-2). + */ +@ApplicationScoped +public class RepositoryLifecycle { + + private static final CuiLogger LOGGER = new CuiLogger(RepositoryLifecycle.class); + + private final TrailhandConfiguration configuration; + private final Path dataDirectory; + private @Nullable ScheduledExecutorService scheduler; + private @Nullable RepositoryService service; + + /** + * @param configuration the configuration + * @param dataDirectory the data directory, {@code trailhand.data.dir} + */ + public RepositoryLifecycle(TrailhandConfiguration configuration, + @ConfigProperty(name = "trailhand.data.dir", defaultValue = "data") String dataDirectory) { + this.configuration = configuration; + this.dataDirectory = Path.of(dataDirectory); + } + + /** + * @return the repository service + * @throws IllegalStateException if the library refuses the repositories + */ + @Produces + // @Singleton, not @ApplicationScoped: the service is used directly, without a client proxy, by the health checks + // and the web resources. + @Singleton + public synchronized RepositoryService repositoryService() { + if (service == null) { + var created = RepositoryService.create(configuration.repositories(), dataDirectory); + if (created.value() == null) { + throw new IllegalStateException("repositories refused: " + created.detail()); + } + service = created.value(); + } + return Objects.requireNonNull(service); + } + + void onStart(@Observes StartupEvent event) { + var repositories = repositoryService(); + scheduler = Executors.newSingleThreadScheduledExecutor(Thread.ofVirtual().name("trailhand-fetch").factory()); + long interval = configuration.fetchInterval().toMillis(); + scheduler.scheduleWithFixedDelay(() -> refreshSafely(repositories), 0, interval, TimeUnit.MILLISECONDS); + } + + /** + * Runs one refresh; a failure is logged and the next refresh runs as planned. A scheduled task that throws would + * otherwise end the periodic fetch silently. + * + * @param repositories the repository service + */ + static void refreshSafely(RepositoryService repositories) { + try { + repositories.refresh(); + // Deliberately broad: whatever a refresh throws must not end the periodic fetch. + // cui-rewrite:disable InvalidExceptionUsageRecipe + } catch (RuntimeException | LinkageError e) { + LOGGER.warn(e, WARN.REFRESH_FAILED, e.getClass().getName(), e.getMessage()); + } + } + + void onStop(@Observes ShutdownEvent event) { + if (scheduler != null) { + scheduler.shutdownNow(); + } + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryService.java b/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryService.java new file mode 100644 index 0000000..676c500 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryService.java @@ -0,0 +1,255 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.service; + +import de.cuioss.git.document.core.GitOutcome; +import de.cuioss.git.document.core.JGitRepositoryOperations; +import de.cuioss.git.document.core.RemotePolicy; +import de.cuioss.git.document.core.RepositoryOperations; +import de.cuioss.git.document.store.RepositoryRegistry; +import de.cuioss.git.document.store.StoreRepository; +import de.cuioss.tools.logging.CuiLogger; +import de.cuioss.trailhand.config.RepositorySettings; +import org.jspecify.annotations.Nullable; + +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.locks.ReentrantLock; + +import static de.cuioss.trailhand.TrailhandLogMessages.INFO; +import static de.cuioss.trailhand.TrailhandLogMessages.WARN; + +/** + * Keeps a local bare copy of every configured repository below the data directory and fetches it (TRH-CONF-2, + * TRH-OPS-2, TRH-GEN-6), through the {@code git-document-repository} libraries only (TRH-GEN-4). + *

+ * A repository is present once a clone exists, whether made now or kept on the volume; a failed fetch later + * keeps it present and marks only its fetch {@code DOWN}, so readiness stays {@code UP} while reads are served from + * the last fetched state. Signing, anchoring and saving join with the save operation. + */ +public class RepositoryService { + + private static final CuiLogger LOGGER = new CuiLogger(RepositoryService.class); + + /** The directory below the data directory that holds the bare repositories. */ + public static final String REPOSITORIES_DIR = "repositories"; + + private static final List FETCH_SPECS = List.of("+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*", + "+refs/notes/*:refs/notes/*"); + private static final List PUSH_SPECS = List.of("refs/heads/main:refs/heads/main"); + + private final RepositoryRegistry registry; + private final RepositoryOperations operations; + private final Path repositoriesDir; + /** The fetch state per alias; guarded by the monitor of this service, which is never held during Git transport. */ + private final Map states = new LinkedHashMap<>(); + /** Keeps refreshes one at a time without blocking the readers of the state. */ + private final ReentrantLock refreshLock = new ReentrantLock(); + + /** + * @param registry the validated repositories + * @param operations the Git operations of the library + * @param dataDirectory the data directory, {@code /app/data} in the container + */ + public RepositoryService(RepositoryRegistry registry, RepositoryOperations operations, Path dataDirectory) { + this.registry = registry; + this.operations = operations; + this.repositoriesDir = dataDirectory.resolve(REPOSITORIES_DIR); + registry.repositories().forEach(repository -> states.put(repository.alias(), + new RepositoryState(repository.alias(), false, false))); + } + + /** + * Builds the registry and the operations for configured repositories. + * + * @param settings the repositories of {@code trailhand.yaml} + * @param dataDirectory the data directory + * @return the service, or the library's refusal of the repositories as detail + */ + public static ServiceResult create(List settings, Path dataDirectory) { + var policy = remotePolicy(settings); + if (policy.isEmpty()) { + return ServiceResult.refused("the https remotes must share one origin"); + } + var repositories = settings.stream() + .map(entry -> new StoreRepository(entry.alias(), libraryRemote(entry), entry.confidentiality(), + entry.retention())) + .toList(); + var registry = RepositoryRegistry.of(repositories, policy.get()); + var value = registry.value(); + if (!registry.isOk() || value == null) { + return ServiceResult.refused(String.valueOf(registry.detail())); + } + return ServiceResult.ok(new RepositoryService(value, new JGitRepositoryOperations(policy.get()), dataDirectory)); + } + + /** + * The remote as the library takes it: an {@code https} URL unchanged, a {@code file:} URL as the absolute path of the + * local bare repository (relative to the working directory). + * + * @param settings the repository + * @return the remote for the library + */ + static String libraryRemote(RepositorySettings settings) { + if (!settings.isLocal()) { + return settings.remote(); + } + var path = settings.remote().substring("file:".length()); + while (path.startsWith("//")) { + path = path.substring(1); + } + return Path.of(path).toAbsolutePath().normalize().toString(); + } + + /** + * The policy of the library admits local repositories and at most one HTTPS origin. + * + * @param settings the repositories + * @return the policy, or empty when the HTTPS remotes name more than one origin + */ + static Optional remotePolicy(List settings) { + var origins = settings.stream().filter(entry -> !entry.isLocal()).map(entry -> URI.create(entry.remote())) + .map(uri -> URI.create("https://" + uri.getRawAuthority())).distinct().toList(); + if (origins.isEmpty()) { + return Optional.of(RemotePolicy.localOnly()); + } + return origins.size() == 1 ? Optional.of(RemotePolicy.httpsOrigin(origins.getFirst())) : Optional.empty(); + } + + /** + * Makes sure every repository has a local copy: an existing one is opened, a missing one is cloned. A repository + * whose clone fails stays absent; the next refresh tries again. Refreshes run one at a time; the state stays + * readable while a clone or fetch waits for the remote. + */ + public void refresh() { + refreshLock.lock(); + try { + for (StoreRepository repository : registry.repositories()) { + var gitDir = repositoriesDir.resolve(repository.alias() + ".git"); + if (isPresent(repository.alias())) { + fetch(repository, gitDir); + } else { + cloneOrOpen(repository, gitDir); + } + } + } finally { + refreshLock.unlock(); + } + } + + private synchronized boolean isPresent(String alias) { + var known = states.get(alias); + return known != null && known.present(); + } + + private synchronized void recordState(RepositoryState state) { + states.put(state.alias(), state); + } + + private void cloneOrOpen(StoreRepository repository, Path gitDir) { + var existed = Files.isDirectory(gitDir); + var result = operations.cloneIfMissing( + new RepositoryOperations.CloneInput(gitDir, repository.remote(), PUSH_SPECS, null)); + if (result.outcome() == GitOutcome.OK) { + LOGGER.info(INFO.REPOSITORY_READY, repository.alias()); + // A fresh clone has reached the remote; an existing one is opened without it, so its fetch state stays + // DOWN until the fetch below succeeds. + recordState(new RepositoryState(repository.alias(), true, !existed)); + fetch(repository, gitDir); + } else { + LOGGER.warn(WARN.CLONE_FAILED, repository.alias(), result.outcome(), result.detail()); + recordState(new RepositoryState(repository.alias(), false, false)); + } + } + + private void fetch(StoreRepository repository, Path gitDir) { + var result = operations.fetch(new RepositoryOperations.FetchInput(gitDir, "origin", FETCH_SPECS, null)); + boolean up = result.outcome() == GitOutcome.OK; + if (!up) { + LOGGER.warn(WARN.FETCH_FAILED, repository.alias(), result.outcome(), result.detail()); + } + recordState(new RepositoryState(repository.alias(), true, up)); + } + + /** + * @return the state of every repository, in configuration order + */ + public synchronized List states() { + return new ArrayList<>(states.values()); + } + + /** + * @return whether every repository has a local copy (the readiness check {@code repositories}) + */ + public boolean allPresent() { + return allPresent(states()); + } + + /** + * @return whether a repository's last fetch failed (the degraded state of TRH-GEN-6) + */ + public boolean degraded() { + return degraded(states()); + } + + /** + * @param snapshot the states from one call of {@link #states()} + * @return whether every repository of the snapshot has a local copy + */ + public static boolean allPresent(List snapshot) { + return snapshot.stream().allMatch(RepositoryState::present); + } + + /** + * @param snapshot the states from one call of {@link #states()} + * @return whether a repository of the snapshot failed its last fetch + */ + public static boolean degraded(List snapshot) { + return snapshot.stream().anyMatch(state -> !state.fetchUp()); + } + + /** + * @param alias an alias + * @return the local git directory of a configured repository + */ + public Optional gitDirectory(String alias) { + return registry.find(alias).map(repository -> repositoriesDir.resolve(repository.alias() + ".git")); + } + + /** + * The result of {@link #create(List, Path)}. + * + * @param value the service, or {@code null} when refused + * @param detail the reason of a refusal + * @param the value type + */ + public record ServiceResult(@Nullable V value, @Nullable String detail) { + + static ServiceResult ok(V value) { + return new ServiceResult<>(value, null); + } + + static ServiceResult refused(String detail) { + return new ServiceResult<>(null, detail); + } + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryState.java b/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryState.java new file mode 100644 index 0000000..4f961ab --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryState.java @@ -0,0 +1,26 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.service; + +/** + * The fetch state of one repository as the status request and the health checks report it (TRH-OPS-2, TRH-GEN-6). + * + * @param alias the alias + * @param present whether a valid local repository exists (fetched now or kept from an earlier fetch) + * @param fetchUp whether the last fetch succeeded + */ +public record RepositoryState(String alias, boolean present, boolean fetchUp) { +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/service/package-info.java b/trailhand/src/main/java/de/cuioss/trailhand/service/package-info.java new file mode 100644 index 0000000..84389ff --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/service/package-info.java @@ -0,0 +1,22 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Application services over the git-document-repository libraries; the only package that uses them (TRH-GEN-4). + */ +@NullMarked +package de.cuioss.trailhand.service; + +import org.jspecify.annotations.NullMarked; diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/ApiAnswers.java b/trailhand/src/main/java/de/cuioss/trailhand/web/ApiAnswers.java new file mode 100644 index 0000000..1828958 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/web/ApiAnswers.java @@ -0,0 +1,34 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.web; + +import lombok.experimental.UtilityClass; + +/** + * The JSON bodies of the refusals of TRH-WEB-9, written by the request gate before any resource runs. + */ +@UtilityClass +public class ApiAnswers { + + /** The login address a {@code 401} names. */ + public static final String LOGIN_ADDRESS = "/api/v1/auth/login"; + + /** {@code 401 UNAUTHENTICATED}. */ + public static final String UNAUTHENTICATED = "{\"outcome\":\"UNAUTHENTICATED\",\"login\":\"" + LOGIN_ADDRESS + "\"}"; + + /** {@code 403 CSRF_REJECTED}. */ + public static final String CSRF_REJECTED = "{\"outcome\":\"CSRF_REJECTED\"}"; +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/AuthResource.java b/trailhand/src/main/java/de/cuioss/trailhand/web/AuthResource.java new file mode 100644 index 0000000..6b79d95 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/web/AuthResource.java @@ -0,0 +1,155 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.web; + +import de.cuioss.sheriff.token.commons.error.TokenSheriffException; +import de.cuioss.trailhand.security.LoginService; +import de.cuioss.trailhand.security.LoginTransactions; +import de.cuioss.trailhand.security.UserSession; +import io.vertx.ext.web.RoutingContext; +import jakarta.ws.rs.CookieParam; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriInfo; +import org.jspecify.annotations.Nullable; + +import java.net.URI; +import java.util.Map; + +/** + * The login endpoints of TRH-AUTH-1: {@code GET /api/v1/auth/login?return=}, the provider's redirect back to + * {@code GET /api/v1/auth/callback} ({@code response_mode=query}), and {@code POST /api/v1/auth/logout}. + *

+ * The callback answers a small same-origin page that navigates to the checked {@code return} by + * {@code }, not a redirect: the navigation it starts is same-site and carries the + * {@code SameSite=Strict} session cookie (TRH-AUTH-1, TRH-WEB-9). + */ +@Path(AuthResource.PATH) +public class AuthResource { + + /** The root of the login requests. */ + public static final String PATH = "/api/v1/auth"; + + /** The start of the login, below {@link #PATH}; public. */ + public static final String LOGIN_PATH = "/login"; + + /** The provider's return, below {@link #PATH}; public. */ + public static final String CALLBACK_PATH = "/callback"; + + private static final String SET_COOKIE = "Set-Cookie"; + private static final String CACHE_CONTROL = "Cache-Control"; + private static final String NO_STORE = "no-store"; + + private final LoginService login; + private final MessageCatalogue messages; + + /** + * @param login the login service + * @param messages the catalogue for the callback page + */ + public AuthResource(LoginService login, MessageCatalogue messages) { + this.login = login; + this.messages = messages; + } + + /** + * Starts the login. + * + * @param returnAddress the address to return to + * @return a redirect to the provider with the login-transaction cookie, {@code 502} when the provider cannot be + * used, or {@code 503} when too many logins are pending + */ + @GET + @Path(LOGIN_PATH) + public Response start(@QueryParam("return") @Nullable String returnAddress) { + try { + var started = login.start(returnAddress); + return Response.status(302).location(URI.create(started.authorizationUrl())) + .header(SET_COOKIE, Cookies.loginCookie(started.transactionReference(), LoginTransactions.LIFETIME)) + .header(CACHE_CONTROL, NO_STORE).build(); + } catch (LoginService.TooManyLoginsException e) { + return Response.status(503).type(MediaType.APPLICATION_JSON).header("Retry-After", "60") + .header(CACHE_CONTROL, NO_STORE).entity(Map.of("outcome", "TOO_MANY_LOGINS")).build(); + } catch (TokenSheriffException | IllegalArgumentException | IllegalStateException e) { + return Response.status(502).type(MediaType.APPLICATION_JSON) + .entity(Map.of("outcome", "IDENTITY_PROVIDER_UNAVAILABLE")).build(); + } + } + + /** + * Completes the login from the provider's redirect. + * + * @param transaction the login-transaction cookie + * @param uriInfo the request address with {@code code}, {@code state} and {@code iss} + * @return the page that navigates to the return address with the session cookie, or a page that offers a new + * login + */ + @GET + @Path(CALLBACK_PATH) + @Produces(MediaType.TEXT_HTML) + public Response callback(@CookieParam(Cookies.LOGIN) @Nullable String transaction, @Context UriInfo uriInfo) { + var query = uriInfo.getRequestUri().getRawQuery(); + var completed = login.complete(transaction, query == null ? "" : query); + var clearLogin = Cookies.expired(Cookies.LOGIN, "Lax"); + if (completed.isEmpty()) { + var page = page(null, messages.english("auth.callback.failed"), "/api/v1/auth/login?return=/", + messages.english("auth.callback.retry")); + return Response.status(400).entity(page).header(SET_COOKIE, clearLogin) + .header(CACHE_CONTROL, NO_STORE).build(); + } + var target = completed.get().returnAddress(); + var page = page(target, null, target, messages.english("auth.callback.continue")); + return Response.ok(page).header(SET_COOKIE, clearLogin) + .header(SET_COOKIE, Cookies.sessionCookie(completed.get().session().id())) + .header(CACHE_CONTROL, NO_STORE).build(); + } + + /** + * Ends the session (RP-initiated logout); the gate has checked the anti-CSRF header. + * + * @param context the routing context with the session + * @return the address the web app navigates to + */ + @POST + @Path("/logout") + @Produces(MediaType.APPLICATION_JSON) + public Response logout(@Context RoutingContext context) { + UserSession session = context.get(RequestGate.SESSION_KEY); + var redirect = login.logout(session.id()); + return Response.ok(Map.of("redirect", redirect)).header(SET_COOKIE, Cookies.expired(Cookies.SESSION, "Strict")) + .header(CACHE_CONTROL, NO_STORE).build(); + } + + private String page(@Nullable String refreshTo, @Nullable String text, String link, String linkText) { + var refresh = refreshTo == null ? "" + : ""; + var paragraph = text == null ? "" : "

" + escape(text) + "

"; + return "" + refresh + "" + + escape(messages.english("auth.callback.title")) + "" + paragraph + + "

" + escape(linkText) + "

"; + } + + static String escape(String text) { + return text.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """) + .replace("'", "'"); + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/Cookies.java b/trailhand/src/main/java/de/cuioss/trailhand/web/Cookies.java new file mode 100644 index 0000000..ec894a9 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/web/Cookies.java @@ -0,0 +1,65 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.web; + +import lombok.experimental.UtilityClass; + +import java.time.Duration; + +/** + * The two cookies of TRH-AUTH-1. Both carry the {@code __Host-} prefix: {@code Secure}, {@code Path=/}, no + * {@code Domain}. + */ +@UtilityClass +public class Cookies { + + /** The session cookie. */ + public static final String SESSION = "__Host-trailhand-session"; + + /** The login-transaction cookie. */ + public static final String LOGIN = "__Host-trailhand-login"; + + /** + * @param sessionId the session id + * @return the {@code Set-Cookie} value of the session: {@code SameSite=Strict} + */ + public static String sessionCookie(String sessionId) { + return SESSION + "=" + sessionId + "; Path=/; Secure; HttpOnly; SameSite=Strict"; + } + + /** + * The login-transaction cookie: {@code SameSite=Lax}, because the browser sends no {@code Strict} cookie with the + * cross-site navigation back from the identity provider, and the callback is such a navigation by {@code GET} + * ({@code response_mode=query}). It carries only an opaque reference, lives ten minutes and is deleted by the + * callback. + * + * @param reference the transaction reference + * @param maxAge the lifetime + * @return the {@code Set-Cookie} value + */ + public static String loginCookie(String reference, Duration maxAge) { + return LOGIN + "=" + reference + "; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=" + maxAge.toSeconds(); + } + + /** + * @param name a cookie name of this class + * @param sameSite the {@code SameSite} value it was set with + * @return the {@code Set-Cookie} value that deletes it + */ + public static String expired(String name, String sameSite) { + return name + "=; Path=/; Secure; HttpOnly; SameSite=" + sameSite + "; Max-Age=0"; + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/DueResource.java b/trailhand/src/main/java/de/cuioss/trailhand/web/DueResource.java new file mode 100644 index 0000000..b9fea82 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/web/DueResource.java @@ -0,0 +1,41 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.web; + +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; + +import java.util.List; +import java.util.Map; + +/** + * {@code GET /api/v1/due} (TRH-WEB-9): the launcher of the Due lens. Empty until the index and the reminders are built + * (TRH-GEN-3). + */ +@Path("/api/v1/due") +public class DueResource { + + /** + * @return the due entries + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + public Map> due() { + return Map.of("items", List.of()); + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/EventStream.java b/trailhand/src/main/java/de/cuioss/trailhand/web/EventStream.java new file mode 100644 index 0000000..b9c5dc4 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/web/EventStream.java @@ -0,0 +1,137 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.web; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import de.cuioss.trailhand.service.RepositoryService; +import io.quarkus.runtime.ShutdownEvent; +import io.quarkus.runtime.StartupEvent; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import jakarta.ws.rs.sse.Sse; +import jakarta.ws.rs.sse.SseBroadcaster; +import jakarta.ws.rs.sse.SseEventSink; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import org.jspecify.annotations.Nullable; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +/** + * The one event stream of all browsers (TRH-WEB-9): the event {@code status} when the degraded state changes, and a + * comment every 15 seconds so idle connections stay open. {@code document-saved} joins with the save operation. + */ +@ApplicationScoped +public class EventStream { + + private static final String STATUS_EVENT = "status"; + + private final RepositoryService repositories; + private final String version; + private final ObjectMapper mapper = new ObjectMapper(); + /** The SSE factory and the broadcaster, created with the first connection. */ + private final AtomicReference<@Nullable Channel> channel = new AtomicReference<>(); + private final AtomicReference lastStatus = new AtomicReference<>(""); + /** Orders the initial status of a connection with the status broadcasts. */ + private final Object statusLock = new Object(); + private @Nullable ScheduledExecutorService scheduler; + + /** + * The SSE factory of the first request and the broadcaster it created. + * + * @param sse the factory of events + * @param broadcaster the broadcaster of all connections + */ + private record Channel(Sse sse, SseBroadcaster broadcaster) { + } + + /** + * @param repositories the repository service + * @param version the application version + */ + public EventStream(RepositoryService repositories, + @ConfigProperty(name = "quarkus.application.version", defaultValue = "dev") String version) { + this.repositories = repositories; + this.version = version; + } + + void onStart(@Observes StartupEvent event) { + scheduler = Executors.newSingleThreadScheduledExecutor(Thread.ofVirtual().name("trailhand-events").factory()); + scheduler.scheduleWithFixedDelay(this::tick, 5, 5, TimeUnit.SECONDS); + scheduler.scheduleWithFixedDelay(this::keepAlive, 15, 15, TimeUnit.SECONDS); + } + + void onStop(@Observes ShutdownEvent event) { + if (scheduler != null) { + scheduler.shutdownNow(); + } + var current = channel.get(); + if (current != null) { + current.broadcaster().close(); + } + } + + /** + * Adds a connection and sends it the current status. + * + * @param sink the connection + * @param sseFactory the SSE factory of the request + */ + void register(SseEventSink sink, Sse sseFactory) { + var current = channel.updateAndGet( + existing -> existing != null ? existing : new Channel(sseFactory, sseFactory.newBroadcaster())); + // One lock with tick(): a status broadcast cannot overtake the initial status of a new connection. A status + // that changed since the last tick goes to every connection, so no connection keeps a status the others missed. + synchronized (statusLock) { + current.broadcaster().register(sink); + var status = statusJson(); + if (status.equals(lastStatus.getAndSet(status))) { + sink.send(sseFactory.newEventBuilder().name(STATUS_EVENT).data(status).build()); + } else { + current.broadcaster().broadcast(current.sse().newEventBuilder().name(STATUS_EVENT).data(status).build()); + } + } + } + + void tick() { + synchronized (statusLock) { + var status = statusJson(); + var previous = lastStatus.getAndSet(status); + var current = channel.get(); + if (!status.equals(previous) && current != null) { + current.broadcaster().broadcast(current.sse().newEventBuilder().name(STATUS_EVENT).data(status).build()); + } + } + } + + void keepAlive() { + var current = channel.get(); + if (current != null) { + current.broadcaster().broadcast(current.sse().newEventBuilder().comment("keepalive").build()); + } + } + + private String statusJson() { + try { + return mapper.writeValueAsString(StatusResource.current(repositories, version)); + } catch (JsonProcessingException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/EventsResource.java b/trailhand/src/main/java/de/cuioss/trailhand/web/EventsResource.java new file mode 100644 index 0000000..c03e6c4 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/web/EventsResource.java @@ -0,0 +1,51 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.web; + +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.sse.Sse; +import jakarta.ws.rs.sse.SseEventSink; + +/** + * {@code GET /api/v1/events} (TRH-WEB-5, TRH-WEB-9): the event stream of the web app. On connect it sends the event + * {@code status}; later events come from {@link EventStream}. + */ +@Path("/api/v1/events") +public class EventsResource { + + private final EventStream stream; + + /** + * @param stream the shared stream + */ + public EventsResource(EventStream stream) { + this.stream = stream; + } + + /** + * @param sink the sink of this connection + * @param sse the SSE factory + */ + @GET + @Produces(MediaType.SERVER_SENT_EVENTS) + public void events(@Context SseEventSink sink, @Context Sse sse) { + stream.register(sink, sse); + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/MessageCatalogue.java b/trailhand/src/main/java/de/cuioss/trailhand/web/MessageCatalogue.java new file mode 100644 index 0000000..dd960da --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/web/MessageCatalogue.java @@ -0,0 +1,81 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.web; + +import jakarta.enterprise.context.ApplicationScoped; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.Optional; +import java.util.Properties; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; + +/** + * The message catalogue of TRH-WEB-7, read from {@code META-INF/trailhand/messages/messages_.properties} of the + * {@code web-app} JAR (UTF-8). The languages are the catalogue files: a language is served when its file exists, so a + * new language needs no list here. Each file is read once. + */ +@ApplicationScoped +public class MessageCatalogue { + + private static final String LOCATION = "META-INF/trailhand/messages/messages_%s.properties"; + /** A language code as the catalogue files name it; anything else is never looked up. */ + private static final Pattern LANGUAGE = Pattern.compile("[a-z]{2}"); + private static final String ENGLISH = "en"; + + private final Map>> catalogues = new ConcurrentHashMap<>(); + + /** + * @param language a language code, such as {@code en} or {@code de} + * @return the catalogue, or empty when no catalogue file exists for the language + */ + public Optional> catalogue(String language) { + if (!LANGUAGE.matcher(language).matches()) { + return Optional.empty(); + } + return catalogues.computeIfAbsent(language, MessageCatalogue::read); + } + + /** + * @param key a message key + * @return the English text, or the key when the catalogue lacks it + */ + public String english(String key) { + return catalogue(ENGLISH).map(messages -> messages.getOrDefault(key, key)).orElse(key); + } + + private static Optional> read(String language) { + var resource = LOCATION.formatted(language); + try (InputStream in = MessageCatalogue.class.getClassLoader().getResourceAsStream(resource)) { + if (in == null) { + return Optional.empty(); + } + var properties = new Properties(); + properties.load(new InputStreamReader(in, StandardCharsets.UTF_8)); + var result = new TreeMap(); + properties.stringPropertyNames().forEach(key -> result.put(key, properties.getProperty(key))); + return Optional.of(Map.copyOf(result)); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/MessagesResource.java b/trailhand/src/main/java/de/cuioss/trailhand/web/MessagesResource.java new file mode 100644 index 0000000..27569d1 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/web/MessagesResource.java @@ -0,0 +1,60 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.web; + +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import org.jspecify.annotations.Nullable; + +import java.util.List; +import java.util.Map; + +/** + * {@code GET /api/v1/messages?lang=en|de} (TRH-WEB-7): the catalogue as one JSON object; a missing {@code lang} answers + * English, any other value {@code 400}. + */ +@Path(MessagesResource.PATH) +public class MessagesResource { + + /** The address of the request; public. */ + public static final String PATH = "/api/v1/messages"; + + private final MessageCatalogue catalogue; + + /** + * @param catalogue the catalogue + */ + public MessagesResource(MessageCatalogue catalogue) { + this.catalogue = catalogue; + } + + /** + * @param lang the language + * @return the catalogue or the refusal + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + public Response messages(@QueryParam("lang") @Nullable String lang) { + var language = lang == null ? "en" : lang; + return catalogue.catalogue(language).map(messages -> Response.ok(messages).build()) + .orElseGet(() -> Response.status(400).entity(Map.of("outcome", "VALIDATION", "errors", + List.of(Map.of("pointer", "/lang", "code", "UNSUPPORTED")))).build()); + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/PagePolicy.java b/trailhand/src/main/java/de/cuioss/trailhand/web/PagePolicy.java new file mode 100644 index 0000000..1217e6d --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/web/PagePolicy.java @@ -0,0 +1,100 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.web; + +import jakarta.enterprise.context.ApplicationScoped; +import lombok.Getter; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.util.regex.Pattern; + +/** + * The page security of TRH-WEB-8: the Content Security Policy as a header, and the built {@code index.html} of the web + * app, which every address of the app answers. + *

+ * SvelteKit writes the policy with the hash of its bootstrap script into {@code index.html} as a {@code } tag; + * the header repeats that policy and adds {@code frame-ancestors 'none'}, which a {@code } policy cannot carry. + */ +@ApplicationScoped +public class PagePolicy { + + /** The web app's start page in the {@code web-app} JAR. */ + public static final String INDEX_RESOURCE = "META-INF/resources/index.html"; + + /** The policy when the page carries none (no built web app on the class path). */ + static final String FALLBACK_POLICY = "default-src 'self'; script-src 'self'; style-src 'self'; " + + "img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'self'"; + + private static final Pattern META_POLICY = Pattern + .compile("} tag with {@code frame-ancestors 'none'} + */ + static String headerPolicy(String html) { + var matcher = META_POLICY.matcher(html); + var base = matcher.find() ? matcher.group(1) : FALLBACK_POLICY; + return base + "; frame-ancestors 'none'"; + } + + /** + * @return a copy of {@code index.html} + */ + public byte[] index() { + return index.clone(); + } + + /** + * @return whether the web app is on the class path + */ + public boolean hasIndex() { + return index.length > 0; + } + + private static byte[] readIndex() { + try (InputStream in = PagePolicy.class.getClassLoader().getResourceAsStream(INDEX_RESOURCE)) { + return in == null ? new byte[0] : in.readAllBytes(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/RequestGate.java b/trailhand/src/main/java/de/cuioss/trailhand/web/RequestGate.java new file mode 100644 index 0000000..637d8cc --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/web/RequestGate.java @@ -0,0 +1,154 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.web; + +import de.cuioss.tools.logging.CuiLogger; +import de.cuioss.trailhand.config.TrailhandConfiguration; +import de.cuioss.trailhand.security.SessionStore; +import de.cuioss.trailhand.security.UserSession; +import io.vertx.core.buffer.Buffer; +import io.vertx.core.http.HttpMethod; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import org.jspecify.annotations.Nullable; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Set; + +import static de.cuioss.trailhand.TrailhandLogMessages.WARN; + +/** + * The gate in front of every request (TRH-AUTH-1, TRH-WEB-1, TRH-WEB-8): + *

    + *
  • the security headers on every answer: the Content Security Policy, {@code nosniff}, {@code no-referrer};
  • + *
  • for {@code /api/v1}: the session from its cookie, {@code 401 UNAUTHENTICATED} without one except for the public + * requests, and for every state-changing request the anti-CSRF header and the {@code Origin} check, else + * {@code 403 CSRF_REJECTED};
  • + *
  • for every other {@code GET} that names no file of the web app: the web app's {@code index.html}, so a canonical + * address can be reloaded (TRH-WEB-3).
  • + *
+ */ +@ApplicationScoped +public class RequestGate { + + private static final CuiLogger LOGGER = new CuiLogger(RequestGate.class); + + /** The key of the session in the routing context. */ + public static final String SESSION_KEY = "trailhand.session"; + + /** The anti-CSRF header. */ + public static final String CSRF_HEADER = "X-CSRF-Token"; + + /** The requests answered without a session; each path is the constant its resource declares itself under. */ + private static final Set PUBLIC_GET = Set.of(StatusResource.PATH, MessagesResource.PATH, + AuthResource.PATH + AuthResource.LOGIN_PATH, AuthResource.PATH + AuthResource.CALLBACK_PATH); + private static final String STATIC_ROOT = "META-INF/resources"; + + private final SessionStore sessions; + private final PagePolicy pagePolicy; + private final String ownOrigin; + + /** + * @param sessions the sessions + * @param pagePolicy the policy and the start page + * @param configuration the configuration with the own origin + */ + public RequestGate(SessionStore sessions, PagePolicy pagePolicy, TrailhandConfiguration configuration) { + this.sessions = sessions; + this.pagePolicy = pagePolicy; + this.ownOrigin = configuration.web().originHeaderValue(); + } + + void register(@Observes Router router) { + router.route().order(-200).handler(this::headers); + router.route("/api/v1/*").order(-150).handler(this::api); + router.get().order(-100).handler(this::appPage); + } + + void headers(RoutingContext context) { + context.addHeadersEndHandler(handler -> { + var headers = context.response().headers(); + headers.set("Content-Security-Policy", pagePolicy.getPolicy()); + headers.set("X-Content-Type-Options", "nosniff"); + headers.set("Referrer-Policy", "no-referrer"); + }); + context.next(); + } + + void api(RoutingContext context) { + var path = context.normalizedPath(); + var method = context.request().method(); + var session = session(context); + if (session != null) { + context.put(SESSION_KEY, session); + } + if (method == HttpMethod.GET && PUBLIC_GET.contains(path)) { + context.next(); + return; + } + if (session == null) { + refuse(context, 401, ApiAnswers.UNAUTHENTICATED); + return; + } + if (method != HttpMethod.GET && method != HttpMethod.HEAD && !csrfValid(context, session)) { + LOGGER.warn(WARN.CSRF_REJECTED, method, path); + refuse(context, 403, ApiAnswers.CSRF_REJECTED); + return; + } + context.next(); + } + + private boolean csrfValid(RoutingContext context, UserSession session) { + var origin = context.request().getHeader("Origin"); + if (origin != null && !ownOrigin.equals(origin)) { + return false; + } + var token = context.request().getHeader(CSRF_HEADER); + return token != null && MessageDigest.isEqual(token.getBytes(StandardCharsets.UTF_8), + session.csrfToken().getBytes(StandardCharsets.UTF_8)); + } + + @Nullable + private UserSession session(RoutingContext context) { + var cookie = context.request().getCookie(Cookies.SESSION); + return cookie == null ? null : sessions.use(cookie.getValue()).orElse(null); + } + + private static void refuse(RoutingContext context, int status, String body) { + context.response().setStatusCode(status).putHeader("Content-Type", "application/json") + .putHeader("Cache-Control", "no-store").end(body); + } + + void appPage(RoutingContext context) { + var path = context.normalizedPath(); + if (!pagePolicy.hasIndex() || path.startsWith("/api/") || path.startsWith("/q/") || isWebAppFile(path)) { + context.next(); + return; + } + context.response().putHeader("Content-Type", "text/html; charset=utf-8").putHeader("Cache-Control", "no-cache") + .end(Buffer.buffer(pagePolicy.index())); + } + + private static boolean isWebAppFile(String path) { + if ("/".equals(path) || path.endsWith("/") || path.contains("..")) { + return false; + } + return RequestGate.class.getClassLoader().getResource(STATIC_ROOT + path) != null; + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/SessionResource.java b/trailhand/src/main/java/de/cuioss/trailhand/web/SessionResource.java new file mode 100644 index 0000000..2fed494 --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/web/SessionResource.java @@ -0,0 +1,89 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.web; + +import de.cuioss.trailhand.config.Action; +import de.cuioss.trailhand.security.RightsMapper; +import de.cuioss.trailhand.security.UserSession; +import io.vertx.ext.web.RoutingContext; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.MediaType; +import org.jspecify.annotations.Nullable; + +import java.util.List; + +/** + * {@code GET /api/v1/session} (TRH-WEB-9): the user, the rights and the anti-CSRF token. The pseudonym comes with the + * person directory (TRH-DIR-2); until it is built the first login is not required and the pseudonym is {@code null}. + */ +@Path("/api/v1/session") +public class SessionResource { + + private final RightsMapper rights; + + /** + * @param rights the rights mapping + */ + public SessionResource(RightsMapper rights) { + this.rights = rights; + } + + /** + * @param context the routing context holding the session the gate found + * @return the session + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + public SessionBody session(@Context RoutingContext context) { + UserSession session = context.get(RequestGate.SESSION_KEY); + var mapped = rights.rightsOf(session.groups()).entrySet().stream() + .map(entry -> new RightBody(entry.getKey(), entry.getValue().stream().map(Action::wireName).toList())) + .toList(); + return new SessionBody(new UserBody(null, session.name()), mapped, session.csrfToken(), false); + } + + /** + * The body of the session. + * + * @param user the user + * @param rights the rights per repository + * @param csrfToken the anti-CSRF token + * @param firstLoginRequired whether the own directory entry must be saved first + */ + public record SessionBody(UserBody user, List rights, String csrfToken, boolean firstLoginRequired) { + } + + /** + * The user. + * + * @param pseudonym the pseudonym, {@code null} until the directory entry exists + * @param name the display name + */ + public record UserBody(@Nullable String pseudonym, String name) { + } + + /** + * The actions on one repository. + * + * @param repository the alias + * @param actions the actions + */ + public record RightBody(String repository, List actions) { + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/StatusResource.java b/trailhand/src/main/java/de/cuioss/trailhand/web/StatusResource.java new file mode 100644 index 0000000..5b850cb --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/web/StatusResource.java @@ -0,0 +1,89 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.web; + +import de.cuioss.trailhand.service.RepositoryService; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import org.eclipse.microprofile.config.inject.ConfigProperty; + +import java.util.List; + +/** + * {@code GET /api/v1/status} (TRH-WEB-9): the application version and the degraded state; no login needed and no + * personal data. + */ +@Path(StatusResource.PATH) +public class StatusResource { + + /** The address of the request; public. */ + public static final String PATH = "/api/v1/status"; + + private final RepositoryService repositories; + private final String version; + + /** + * @param repositories the repository service + * @param version the application version + */ + public StatusResource(RepositoryService repositories, + @ConfigProperty(name = "quarkus.application.version", defaultValue = "dev") String version) { + this.repositories = repositories; + this.version = version; + } + + /** + * @return the status + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + public Status status() { + return current(repositories, version); + } + + /** + * @param repositories the repository service + * @param version the version + * @return the status as the request and the event {@code status} carry it + */ + static Status current(RepositoryService repositories, String version) { + var snapshot = repositories.states(); + var states = snapshot.stream() + .map(state -> new RepositoryStatus(state.alias(), state.fetchUp() ? "UP" : "DOWN")).toList(); + return new Status(version, RepositoryService.degraded(snapshot), states); + } + + /** + * The body of the status. + * + * @param version the version + * @param degraded whether a fetch fails + * @param repositories the fetch state per repository + */ + public record Status(String version, boolean degraded, List repositories) { + } + + /** + * The fetch state of one repository. + * + * @param alias the alias + * @param fetch {@code UP} or {@code DOWN} + */ + public record RepositoryStatus(String alias, String fetch) { + } +} diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/package-info.java b/trailhand/src/main/java/de/cuioss/trailhand/web/package-info.java new file mode 100644 index 0000000..aaad52e --- /dev/null +++ b/trailhand/src/main/java/de/cuioss/trailhand/web/package-info.java @@ -0,0 +1,22 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * REST resources below /api/v1, the event stream, page security and the serving of the web app (TRH-WEB-*). + */ +@NullMarked +package de.cuioss.trailhand.web; + +import org.jspecify.annotations.NullMarked; diff --git a/trailhand/src/main/resources/META-INF/native-image/de.cuioss/trailhand/reflect-config.json b/trailhand/src/main/resources/META-INF/native-image/de.cuioss/trailhand/reflect-config.json new file mode 100644 index 0000000..154bc8d --- /dev/null +++ b/trailhand/src/main/resources/META-INF/native-image/de.cuioss/trailhand/reflect-config.json @@ -0,0 +1,1607 @@ +[ + { + "name": "org.eclipse.jgit.internal.JGitText", + "allPublicFields": true, + "allPublicConstructors": true + }, + { + "name": "org.eclipse.jgit.api.CheckoutCommand$Stage", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.api.CheckoutResult$Status", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.api.CherryPickResult$CherryPickStatus", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.api.CloneCommand$FETCH_TYPE", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.api.CreateBranchCommand$SetupUpstreamMode", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.api.ListBranchCommand$ListMode", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.api.MergeCommand$ConflictStyle", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.api.MergeCommand$FastForwardMode", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.api.MergeCommand$FastForwardMode$Merge", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.api.MergeResult$MergeStatus", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.api.RebaseCommand$Operation", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.api.RebaseResult$Status", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.api.RemoteSetUrlCommand$UriType", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.api.ResetCommand$ResetType", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.api.SubmoduleDeinitCommand$SubmoduleDeinitStatus", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.api.VerifySignatureCommand$VerifyMode", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.attributes.Attribute$State", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.diff.DiffAlgorithm$SupportedAlgorithm", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.diff.DiffConfig$RenameDetectionType", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.diff.DiffDriver", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.diff.DiffEntry$ChangeType", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.diff.DiffEntry$Side", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.diff.Edit$Type", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.dircache.DirCache$DirCacheVersion", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.errors.CorruptPackIndexException$ErrorType", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.errors.NoMergeBaseException$MergeBaseFailureReason", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.ignore.IgnoreNode$MatchResult", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.ignore.internal.Strings$PatternState", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.internal.diffmergetool.CommandLineDiffTool", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.internal.diffmergetool.CommandLineMergeTool", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.internal.diffmergetool.FileElement$Type", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.internal.storage.dfs.DfsObjDatabase$PackSource", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.internal.storage.file.FileObjectDatabase$InsertLooseObjectResult", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.internal.storage.pack.PackExt", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.internal.storage.pack.PackWriter$PackingPhase", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.internal.util.ShutdownHook", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.BranchConfig$BranchRebaseMode", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.CommitConfig$CleanupMode", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.CoreConfig$AutoCRLF", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.CoreConfig$CheckStat", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.CoreConfig$EOL", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.CoreConfig$EolStreamType", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.CoreConfig$HideDotFiles", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.CoreConfig$LogRefUpdates", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.CoreConfig$SymLinks", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.CoreConfig$TrustLooseRefStat", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.CoreConfig$TrustPackedRefsStat", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.CoreConfig$TrustStat", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.GcConfig$PackRefsMode", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.GpgConfig$GpgFormat", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.IndexDiff$StageState", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.internal.BooleanTriState", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.ObjectChecker$ErrorType", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.PackedRefsTrait", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.RebaseTodoLine$Action", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.Ref$Storage", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.RefUpdate$Result", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.RepositoryState", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.SignatureVerifier$TrustLevel", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.lib.SubmoduleConfig$FetchRecurseSubmodulesMode", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.merge.ContentMergeStrategy", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.merge.MergeChunk$ConflictState", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.merge.ResolveMerger$MergeFailureReason", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.patch.BinaryHunk$Type", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.patch.FileHeader$PatchType", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.patch.FormatError$Severity", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.revwalk.RevSort", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.revwalk.RevWalk$GetMergedIntoStrategy", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.submodule.SubmoduleStatusType", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.submodule.SubmoduleWalk$IgnoreSubmoduleMode", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.GitProtocolConstants$MultiAck", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.HttpAuthMethod$Type", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.HttpConfig$HttpRedirectMode", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.NetRC$State", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.PacketLineIn$AckNackResult", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.PackParser$Source", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.PushCertificate$NonceStatus", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.PushConfig$PushDefault", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.PushConfig$PushRecurseSubmodulesMode", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.ReceiveCommand$Result", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.ReceiveCommand$Type", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.RefSpec$WildcardMode", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.RemoteRefUpdate$Status", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.TagOpt", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.TransferConfig$FsckMode", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.TransferConfig$ProtocolVersion", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.Transport$Operation", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.TransportHttp$AcceptEncoding", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.TransportProtocol$URIishField", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.UploadPack$Option", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.transport.UploadPack$RequestPolicy", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.treewalk.TreeWalk$OperationType", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.treewalk.WorkingTreeIterator$MetadataDiff", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.util.FS_POSIX$AtomicFileCreation", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.util.GitDateFormatter$Format", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.util.GitDateParser$ParseableSimpleDateFormat", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.util.GitTimeParser$ParseableSimpleDateFormat", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.util.io.AutoLFInputStream$StreamFlag", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.util.ProcessResult$Status", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "name": "org.eclipse.jgit.util.sha1.SHA1$Sha1Implementation", + "allPublicFields": true, + "methods": [ + { + "name": "values", + "parameterTypes": [] + }, + { + "name": "valueOf", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + } +] \ No newline at end of file diff --git a/trailhand/src/main/resources/META-INF/native-image/de.cuioss/trailhand/resource-config.json b/trailhand/src/main/resources/META-INF/native-image/de.cuioss/trailhand/resource-config.json new file mode 100644 index 0000000..20603f0 --- /dev/null +++ b/trailhand/src/main/resources/META-INF/native-image/de.cuioss/trailhand/resource-config.json @@ -0,0 +1,14 @@ +{ + "bundles": [ + { + "name": "org.eclipse.jgit.internal.JGitText" + } + ], + "resources": { + "includes": [ + { + "pattern": "org/eclipse/jgit/internal/JGitText.*\\.properties" + } + ] + } +} \ No newline at end of file diff --git a/trailhand/src/main/resources/META-INF/services/io.smallrye.config.ConfigSourceFactory b/trailhand/src/main/resources/META-INF/services/io.smallrye.config.ConfigSourceFactory new file mode 100644 index 0000000..bf64058 --- /dev/null +++ b/trailhand/src/main/resources/META-INF/services/io.smallrye.config.ConfigSourceFactory @@ -0,0 +1 @@ +de.cuioss.trailhand.config.TokenSheriffConfigSourceFactory diff --git a/trailhand/src/main/resources/application.properties b/trailhand/src/main/resources/application.properties new file mode 100644 index 0000000..a9b3af1 --- /dev/null +++ b/trailhand/src/main/resources/application.properties @@ -0,0 +1,47 @@ +# TrailHand: Quarkus runtime settings (doc/specification/configuration.adoc, application.properties). The policy of +# the application is trailhand.yaml in trailhand.config.dir. +quarkus.application.name=trailhand + +# TRH-OPS-2: HTTPS on 8443, plain HTTP only redirects; management (health, metrics) on 9000. +quarkus.http.port=8080 +quarkus.http.ssl-port=8443 +quarkus.http.insecure-requests=redirect +quarkus.http.ssl.certificate.files=/run/secrets/tls/tls.crt +quarkus.http.ssl.certificate.key-files=/run/secrets/tls/tls.key +# Fixed at build time (the native image needs it there): health and metrics on their own port. +quarkus.management.enabled=true +quarkus.management.port=9000 +quarkus.management.host=0.0.0.0 + +trailhand.config.dir=config +trailhand.data.dir=/app/data + + +# TRH-OPS-1: native image, built with Mandrel in a container. +quarkus.native.builder-image=quay.io/quarkus/ubi9-quarkus-mandrel-builder-image:jdk-25 +# Classes with Random or SecureRandom instances in static fields are initialised at run time: a value created during +# the image build would be the same in every process. JGit (HttpAuthMethod$Digest, FileUtils, ...), Token Sheriff's +# flow package (PkceChallenge, FlowContext; as in API Sheriff) and the session ids of SessionStore. A package name is a +# prefix over its classes; every entry needs its own flag. +quarkus.native.additional-build-args=--enable-url-protocols=https\\,http,\ + --initialize-at-run-time=org.eclipse.jgit,\ + --initialize-at-run-time=de.cuioss.sheriff.token.client.flow,\ + --initialize-at-run-time=de.cuioss.trailhand.security.SessionStore +quarkus.native.resources.includes=META-INF/trailhand/** +# JGit in the native image (TRH-NFR-5): META-INF/native-image/de.cuioss/trailhand registers the message bundle +# JGitText (its public fields are filled by reflection) and every enum of the JGit JAR, whose values Config.getEnum +# reads by reflection; the enum list is the one of org.eclipse.jgit 7.8.0 and is regenerated with a JGit update. + +# Development and tests run without TLS material and without the container paths. +%dev.quarkus.http.ssl.certificate.files= +%dev.quarkus.http.ssl.certificate.key-files= +%dev.quarkus.http.insecure-requests=enabled +%dev.trailhand.data.dir=target/data +%test.quarkus.http.ssl.certificate.files= +%test.quarkus.http.ssl.certificate.key-files= +%test.quarkus.http.insecure-requests=enabled +%test.trailhand.data.dir=target/test-data +%test.trailhand.config.dir=src/test/resources/config +# quarkus-jacoco: the agent of jacoco:prepare-agent writes target/jacoco.exec and jacoco:report builds the report +# Sonar reads; the extension's second report is off (as in API Sheriff). +%test.quarkus.jacoco.report=false diff --git a/trailhand/src/test/java/de/cuioss/trailhand/ArchitectureTest.java b/trailhand/src/test/java/de/cuioss/trailhand/ArchitectureTest.java new file mode 100644 index 0000000..74710fb --- /dev/null +++ b/trailhand/src/test/java/de/cuioss/trailhand/ArchitectureTest.java @@ -0,0 +1,76 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand; + +import com.tngtech.archunit.core.domain.JavaClasses; +import com.tngtech.archunit.core.importer.ClassFileImporter; +import com.tngtech.archunit.core.importer.ImportOption; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; + +@DisplayName("The layering of doc/specification/architecture-and-modules.adoc (TRH-GEN-2, TRH-GEN-4)") +class ArchitectureTest { + + private static JavaClasses classes; + + @BeforeAll + static void importClasses() { + classes = new ClassFileImporter().withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS) + .importPackages("de.cuioss.trailhand"); + } + + @Test + @DisplayName("no application package imports JGit") + void noJgit() { + noClasses().should().dependOnClassesThat().resideInAPackage("org.eclipse.jgit..").check(classes); + } + + @Test + @DisplayName("only the service package uses the git-document-repository libraries") + void onlyServiceUsesLibraries() { + noClasses().that().resideOutsideOfPackage("de.cuioss.trailhand.service..").should().dependOnClassesThat() + .resideInAPackage("de.cuioss.git.document..").check(classes); + } + + @Test + @DisplayName("web and mcp do not depend on each other") + void webAndMcpIndependent() { + noClasses().that().resideInAPackage("de.cuioss.trailhand.web..").should().dependOnClassesThat() + .resideInAPackage("de.cuioss.trailhand.mcp..").allowEmptyShould(true).check(classes); + noClasses().that().resideInAPackage("de.cuioss.trailhand.mcp..").should().dependOnClassesThat() + .resideInAPackage("de.cuioss.trailhand.web..").allowEmptyShould(true).check(classes); + } + + @Test + @DisplayName("security depends on config only; service on config only; config on no other package") + void layers() { + noClasses().that().resideInAPackage("de.cuioss.trailhand.security..").should().dependOnClassesThat() + .resideInAnyPackage("de.cuioss.trailhand.web..", "de.cuioss.trailhand.service..", + "de.cuioss.trailhand.mcp..") + .check(classes); + noClasses().that().resideInAPackage("de.cuioss.trailhand.service..").should().dependOnClassesThat() + .resideInAnyPackage("de.cuioss.trailhand.web..", "de.cuioss.trailhand.security..", + "de.cuioss.trailhand.mcp..") + .check(classes); + noClasses().that().resideInAPackage("de.cuioss.trailhand.config..").should().dependOnClassesThat() + .resideInAnyPackage("de.cuioss.trailhand.web..", "de.cuioss.trailhand.service..", + "de.cuioss.trailhand.security..", "de.cuioss.trailhand.mcp..") + .check(classes); + } +} diff --git a/trailhand/src/test/java/de/cuioss/trailhand/EntryPointTest.java b/trailhand/src/test/java/de/cuioss/trailhand/EntryPointTest.java new file mode 100644 index 0000000..e28af03 --- /dev/null +++ b/trailhand/src/test/java/de/cuioss/trailhand/EntryPointTest.java @@ -0,0 +1,50 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.net.ServerSocket; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@DisplayName("The command-line modes of the binary (TRH-OPS-1, TRH-CONF-1)") +class EntryPointTest { + + @Test + @DisplayName("--health-probe answers 0 for a listening port and 1 for a closed one") + void healthProbe() throws Exception { + int port; + try (var server = new ServerSocket(0)) { + port = server.getLocalPort(); + assertEquals(0, HealthProbe.probe(port)); + } + assertEquals(1, HealthProbe.probe(port)); + } + + @Test + @DisplayName("--validate-config answers 0, 1, or 2 without a directory") + void validateConfig(@TempDir Path directory) throws Exception { + assertEquals(2, ConfigValidation.run(new String[]{ConfigValidation.FLAG}, name -> null)); + assertEquals(1, ConfigValidation.run(new String[]{ConfigValidation.FLAG, directory.toString()}, name -> null)); + Files.copy(Path.of("src/test/resources/config/trailhand.yaml"), directory.resolve("trailhand.yaml")); + assertEquals(0, ConfigValidation.run(new String[]{ConfigValidation.FLAG, directory.toString()}, name -> null)); + } +} diff --git a/trailhand/src/test/java/de/cuioss/trailhand/NativeRegistrationTest.java b/trailhand/src/test/java/de/cuioss/trailhand/NativeRegistrationTest.java new file mode 100644 index 0000000..e544b31 --- /dev/null +++ b/trailhand/src/test/java/de/cuioss/trailhand/NativeRegistrationTest.java @@ -0,0 +1,128 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand; + +import com.fasterxml.jackson.databind.ObjectMapper; +import de.cuioss.sheriff.token.client.discovery.ProviderMetadata; +import de.cuioss.trailhand.security.TokenClientNativeRegistration; +import io.quarkus.runtime.annotations.RegisterForReflection; +import io.smallrye.config.PropertiesConfigSource; +import io.smallrye.config.SmallRyeConfigBuilder; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Set; +import java.util.TreeSet; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The native-image registrations name exactly the classes of the resolved dependencies that need them (TRH-OPS-1), + * so a dependency update that adds or removes one fails here and not only in the native image. + */ +@DisplayName("Native-image registrations follow the resolved dependencies") +class NativeRegistrationTest { + + private static final Pattern CONVERTER = Pattern.compile("(.*/)_([^/]+)_DslJsonConverter\\.class"); + private static final String JGIT_TEXT = "org.eclipse.jgit.internal.JGitText"; + + @Test + @DisplayName("every DSL-JSON converter of Token Sheriff's client and its response type is registered") + void tokenClientConverters() throws Exception { + var expected = new TreeSet(); + try (var jar = jarOf(ProviderMetadata.class)) { + jar.stream().map(JarEntry::getName).map(CONVERTER::matcher).filter(Matcher::matches) + .forEach(match -> { + var packageName = match.group(1).replace('/', '.'); + expected.add(packageName + "_" + match.group(2) + "_DslJsonConverter"); + expected.add(packageName + match.group(2)); + }); + } + var registration = TokenClientNativeRegistration.class.getAnnotation(RegisterForReflection.class); + var registered = Arrays.stream(registration.targets()).map(Class::getName).collect(Collectors.toCollection(TreeSet::new)); + + assertTrue(expected.size() > 1, "the client JAR holds converters"); + assertEquals(expected, registered); + } + + @Test + @DisplayName("every enum of the JGit JAR and its message bundle are registered for reflection") + void jgitEnums() throws Exception { + var expected = new TreeSet(); + var loader = getClass().getClassLoader(); + try (var jar = jarOf(Class.forName(JGIT_TEXT, false, loader))) { + for (String name : jar.stream().map(JarEntry::getName).filter(entry -> entry.endsWith(".class")) + .map(entry -> entry.substring(0, entry.length() - ".class".length()).replace('/', '.')).toList()) { + if (isEnum(name, loader)) { + expected.add(name); + } + } + } + expected.add(JGIT_TEXT); + + assertTrue(expected.size() > 1, "the JGit JAR holds enums"); + assertEquals(expected, reflectConfigNames()); + } + + @Test + @DisplayName("the native build arguments keep the comma inside --enable-url-protocols") + void buildArguments() throws Exception { + var properties = NativeRegistrationTest.class.getClassLoader().getResource("application.properties"); + assertNotNull(properties, "application.properties is on the class path"); + var config = new SmallRyeConfigBuilder().withSources(new PropertiesConfigSource(properties)).build(); + + var arguments = config.getValues("quarkus.native.additional-build-args", String.class); + + assertTrue(arguments.contains("--enable-url-protocols=https,http"), arguments.toString()); + assertTrue(arguments.contains("--initialize-at-run-time=org.eclipse.jgit"), arguments.toString()); + assertTrue(arguments.stream().noneMatch("http"::equals), arguments.toString()); + } + + private static boolean isEnum(String name, ClassLoader loader) { + try { + return Class.forName(name, false, loader).isEnum(); + } catch (ClassNotFoundException | LinkageError e) { + // A class whose optional dependency is absent cannot be an enum JGit reads at run time here. + return false; + } + } + + private static Set reflectConfigNames() throws IOException { + try (InputStream in = NativeRegistrationTest.class.getClassLoader() + .getResourceAsStream("META-INF/native-image/de.cuioss/trailhand/reflect-config.json")) { + assertNotNull(in, "reflect-config.json is on the class path"); + var names = new TreeSet(); + new ObjectMapper().readTree(in).forEach(entry -> names.add(entry.get("name").asText())); + return names; + } + } + + private static JarFile jarOf(Class type) throws IOException, URISyntaxException { + return new JarFile(Path.of(type.getProtectionDomain().getCodeSource().getLocation().toURI()).toFile()); + } +} diff --git a/trailhand/src/test/java/de/cuioss/trailhand/config/ConfigurationLoaderTest.java b/trailhand/src/test/java/de/cuioss/trailhand/config/ConfigurationLoaderTest.java new file mode 100644 index 0000000..6ded36f --- /dev/null +++ b/trailhand/src/test/java/de/cuioss/trailhand/config/ConfigurationLoaderTest.java @@ -0,0 +1,232 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import de.cuioss.test.juli.LogAsserts; +import de.cuioss.test.juli.TestLogLevel; +import de.cuioss.test.juli.junit5.EnableTestLogger; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.time.Period; +import java.util.Map; +import java.util.Set; + +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.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@EnableTestLogger +@DisplayName("ConfigurationLoader: trailhand.yaml and the boot rules (TRH-CONF-1, TRH-CONF-2)") +class ConfigurationLoaderTest { + + private static final String VALID = """ + repositories: + - alias: samm-assessments + remote: https://git.example.org/security/samm.git + confidentiality: restricted + retention: P10Y + credential-ref: file:/run/secrets/git/token + - alias: directory + remote: file:/srv/git/directory.git + confidentiality: strongly-restricted + retention: unlimited + rights: + assessors: + - repository: samm-assessments + actions: [read, edit] + catalog-admins: + - repository: directory + actions: [administer-catalogs] + oidc: + issuer: ${IDP_ISSUER:-https://idp.example.org/realms/trailhand} + client-id: ${CLIENT_ID} + client-credential-ref: file:/run/secrets/oidc/client-secret + web: + origin: https://trailhand.example.org + """; + + private final ConfigurationLoader loader = new ConfigurationLoader(Map.of("CLIENT_ID", "trailhand-web")::get); + + private static Object yaml(String text) throws IOException { + return new ObjectMapper(new YAMLFactory()).readValue(text, Object.class); + } + + private ConfigurationResult validate(String text) throws IOException { + return loader.validate(yaml(text)); + } + + private static boolean hasViolation(ConfigurationResult result, String key) { + return result.violations().stream().anyMatch(violation -> violation.key().equals(key)); + } + + @Test + @DisplayName("reads a valid configuration with placeholders and defaults") + void valid() throws Exception { + var result = validate(VALID); + + assertTrue(result.isValid(), result.violations().toString()); + var configuration = result.configuration(); + assertNotNull(configuration); + assertEquals(2, configuration.repositories().size()); + assertEquals(Period.ofYears(10), configuration.repositories().getFirst().retention()); + assertNull(configuration.repositories().get(1).retention()); + assertTrue(configuration.repositories().get(1).isLocal()); + assertEquals("https://idp.example.org/realms/trailhand", configuration.oidc().issuer()); + assertEquals("trailhand-web", configuration.oidc().clientId()); + assertEquals("groups", configuration.oidc().groupsClaim()); + assertEquals(Duration.ofMinutes(30), configuration.web().idleTimeout()); + assertEquals(Duration.ofHours(8), configuration.web().maxLifetime()); + assertEquals("https://trailhand.example.org", configuration.web().originHeaderValue()); + assertEquals(Duration.ofMinutes(5), configuration.fetchInterval()); + assertEquals(Set.of(Action.ADMINISTER_CATALOGS), + configuration.rights().get("catalog-admins").getFirst().actions()); + } + + @Test + @DisplayName("writes the own origin as the browser sends it: lower case, without the default port") + void originForm() throws Exception { + var result = validate(VALID.replace("origin: https://trailhand.example.org", + "origin: HTTPS://TrailHand.Example.org:443")); + + assertTrue(result.isValid(), result.violations().toString()); + assertEquals("https://trailhand.example.org", result.configuration().web().originHeaderValue()); + var custom = validate(VALID.replace("origin: https://trailhand.example.org", "origin: https://Example.org:8443")); + assertEquals("https://example.org:8443", custom.configuration().web().originHeaderValue()); + var ipv6 = validate(VALID.replace("origin: https://trailhand.example.org", + "origin: 'https://[0:0:0:0:0:0:0:1]:443'")); + assertEquals("https://[::1]", ipv6.configuration().web().originHeaderValue()); + } + + @ParameterizedTest(name = "{0} -> {1}") + @CsvSource({"[0:0:0:0:0:0:0:1],[::1]", "[2001:DB8:0:0:1:0:0:1],[2001:db8::1:0:0:1]", + "[2001:db8:0:1:1:1:1:1],[2001:db8:0:1:1:1:1:1]", "[::],[::]", "[1:0:0:0:0:0:0:0],[1::]", + "[0:0:1:0:0:0:2:3],[0:0:1::2:3]", "[::ffff:192.0.2.1],[::ffff:c000:201]", "Example.ORG,example.org", + "192.0.2.1,192.0.2.1"}) + @DisplayName("writes a host as the browser serializes it (URL Standard, IPv6 serializer)") + void browserHost(String host, String expected) { + assertEquals(expected, WebSettings.browserHost(host)); + } + + @Test + @DisplayName("an unresolved placeholder without default is a violation") + void unresolvedPlaceholder() throws Exception { + var result = new ConfigurationLoader(name -> null).validate(yaml(VALID)); + + assertFalse(result.isValid()); + assertTrue(hasViolation(result, "${CLIENT_ID}")); + } + + @Nested + @DisplayName("refuses") + class Refusals { + + @ParameterizedTest(name = "{0}") + @CsvSource(delimiter = '|', value = { + "an alias outside [a-z0-9-]|alias: samm-assessments|alias: Samm_Assessments|repositories[0].alias", + "a second repository with one alias|alias: directory|alias: samm-assessments|repositories[1].alias", + "an ssh remote|remote: https://git.example.org/security/samm.git|remote: ssh://git@x/y.git|repositories[0].remote", + "an unknown confidentiality|confidentiality: restricted|confidentiality: secret|repositories[0].confidentiality", + "a retention that is no period|retention: P10Y|retention: ten years|repositories[0].retention", + "an https remote without credential|credential-ref: file:/run/secrets/git/token|credential-ref:|repositories[0].credential-ref", + "a secret value instead of a reference|credential-ref: file:/run/secrets/git/token|credential-ref: hunter2|repositories[0].credential-ref", + "a right on an unknown repository|- repository: samm-assessments|- repository: nowhere|rights.assessors[0].repository", + "an unknown action|actions: [read, edit]|actions: [read, delete]|rights.assessors[0].actions", + "an issuer that is no https URI|issuer: ${IDP_ISSUER:-https://idp.example.org/realms/trailhand}|issuer: http://idp|oidc.issuer", + "an origin with a path|origin: https://trailhand.example.org|origin: https://trailhand.example.org/app|web.origin", + "a vault reference before the Vault adapter|client-credential-ref: file:/run/secrets/oidc/client-secret|client-credential-ref: vault:secret/trailhand/oidc|oidc.client-credential-ref", + "a placeholder that names no environment variable|client-id: ${CLIENT_ID}|client-id: ${client.id}|${client.id}"}) + void rule(String name, String original, String replacement, String key) throws Exception { + assertTrue(VALID.contains(original), name); + + var result = validate(VALID.replace(original, replacement)); + + assertFalse(result.isValid(), name); + assertTrue(hasViolation(result, key), name + ": " + result.violations()); + } + + @Test + @DisplayName("a document without the required sections, naming each") + void missingSections() throws Exception { + var result = validate("fetch:\n interval: nonsense\n"); + + assertFalse(result.isValid()); + for (String key : new String[]{"repositories", "rights", "oidc", "web", "fetch.interval"}) { + assertTrue(hasViolation(result, key), key + ": " + result.violations()); + } + } + + @Test + @DisplayName("an idle timeout longer than the session lifetime") + void idleLongerThanLifetime() throws Exception { + var result = validate(VALID + " session:\n idle-timeout: PT9H\n max-lifetime: PT8H\n"); + + assertTrue(hasViolation(result, "web.session.idle-timeout")); + } + + @Test + @DisplayName("a document that is no mapping") + void noMapping() throws Exception { + assertFalse(validate("- just\n- a list\n").isValid()); + assertFalse(loader.validate(null).isValid()); + } + } + + @Nested + @DisplayName("loads from a directory") + class Loading { + + @Test + @DisplayName("and logs one ERROR record per violation") + void logsViolations(@TempDir Path directory) throws Exception { + Files.writeString(directory.resolve(ConfigurationLoader.FILE_NAME), "repositories: []\n"); + + var result = loader.load(directory); + + assertFalse(result.isValid()); + LogAsserts.assertLogMessagePresentContaining(TestLogLevel.ERROR, "TRAILHAND-200"); + } + + @Test + @DisplayName("reports a missing file and invalid YAML") + void missingAndBroken(@TempDir Path directory) throws Exception { + assertTrue(hasViolation(loader.load(directory), ConfigurationLoader.FILE_NAME)); + Files.writeString(directory.resolve(ConfigurationLoader.FILE_NAME), "a: [unclosed\n"); + assertTrue(hasViolation(loader.load(directory), ConfigurationLoader.FILE_NAME)); + } + + @Test + @DisplayName("and logs the loaded configuration") + void logsSuccess(@TempDir Path directory) throws Exception { + Files.writeString(directory.resolve(ConfigurationLoader.FILE_NAME), VALID); + + assertTrue(loader.load(directory).isValid()); + LogAsserts.assertLogMessagePresentContaining(TestLogLevel.INFO, "TRAILHAND-1"); + } + } +} diff --git a/trailhand/src/test/java/de/cuioss/trailhand/config/PlaceholdersTest.java b/trailhand/src/test/java/de/cuioss/trailhand/config/PlaceholdersTest.java new file mode 100644 index 0000000..1aab9c0 --- /dev/null +++ b/trailhand/src/test/java/de/cuioss/trailhand/config/PlaceholdersTest.java @@ -0,0 +1,81 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.config; + +import de.cuioss.test.generator.Generators; +import de.cuioss.test.generator.junit.EnableGeneratorController; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@EnableGeneratorController +@DisplayName("Placeholders: ${NAME} and ${NAME:-default} from the environment (TRH-CONF-1)") +class PlaceholdersTest { + + @Test + @DisplayName("resolves a value, a default and leaves text without placeholder alone") + void resolves() { + var value = Generators.letterStrings(5, 12).next(); + var unresolved = new ArrayList(); + + assertEquals("a-" + value + "-b", Placeholders.resolve("a-${NAME}-b", Map.of("NAME", value)::get, unresolved)); + assertEquals("fallback", Placeholders.resolve("${MISSING:-fallback}", name -> null, unresolved)); + assertEquals("", Placeholders.resolve("${EMPTY:-}", name -> null, unresolved)); + assertEquals("plain $ {text}", Placeholders.resolve("plain $ {text}", name -> null, unresolved)); + assertTrue(unresolved.isEmpty()); + } + + @Test + @DisplayName("collects every placeholder without value and default") + void collectsUnresolved() { + var unresolved = new ArrayList(); + + Placeholders.resolve("${A}/${B:-b}/${C}", name -> null, unresolved); + + assertEquals(List.of("A", "C"), unresolved); + } + + @Test + @DisplayName("resolves a lowercase environment name and reports a placeholder that names no environment variable") + void names() { + var unresolved = new ArrayList(); + + assertEquals("id", Placeholders.resolve("${client_id}", Map.of("client_id", "id")::get, unresolved)); + assertEquals("", Placeholders.resolve("${client.id:-x}", name -> "never", unresolved)); + assertEquals("", Placeholders.resolve("${1A}", name -> "never", unresolved)); + assertEquals("", Placeholders.resolve("${}", name -> "never", unresolved)); + + Placeholders.resolve("${MISSING:-${OTHER}}", name -> null, unresolved); + + assertEquals(List.of("client.id", "1A", "", "MISSING"), unresolved); + } + + @Test + @DisplayName("resolves every string of a tree and keeps the other values") + void resolvesTree() { + var tree = Map.of("list", List.of("${X}", 3), "nested", Map.of("flag", true, "text", "${X}")); + + var resolved = Placeholders.resolveTree(tree, Map.of("X", "x")::get, new ArrayList<>()); + + assertEquals(Map.of("list", List.of("x", 3), "nested", Map.of("flag", true, "text", "x")), resolved); + } +} diff --git a/trailhand/src/test/java/de/cuioss/trailhand/config/TokenSheriffConfigSourceFactoryTest.java b/trailhand/src/test/java/de/cuioss/trailhand/config/TokenSheriffConfigSourceFactoryTest.java new file mode 100644 index 0000000..dbc9c71 --- /dev/null +++ b/trailhand/src/test/java/de/cuioss/trailhand/config/TokenSheriffConfigSourceFactoryTest.java @@ -0,0 +1,94 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.config; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@DisplayName("TokenSheriffConfigSourceFactory: Token Sheriff's keys from trailhand.yaml") +class TokenSheriffConfigSourceFactoryTest { + + @Test + @DisplayName("derives client and issuer keys and reads the client secret from its file") + void derives(@TempDir Path directory) throws Exception { + var secret = directory.resolve("client-secret"); + Files.writeString(secret, "s3cret\n"); + Files.writeString(directory.resolve(ConfigurationLoader.FILE_NAME), """ + repositories: + - {alias: directory, remote: "file:/srv/directory.git", confidentiality: restricted, retention: unlimited} + rights: {} + oidc: + issuer: https://idp.example.org/realms/trailhand/ + client-id: trailhand-web + client-credential-ref: file:%s + web: + origin: https://trailhand.example.org:8443 + """.formatted(secret)); + + var keys = TokenSheriffConfigSourceFactory.derive(directory, name -> null); + + assertEquals("https://idp.example.org/realms/trailhand/", keys.get("sheriff.client.issuer")); + assertEquals("trailhand-web", keys.get("sheriff.client.client-id")); + assertEquals("s3cret", keys.get("sheriff.client.client-secret")); + assertEquals("https://trailhand.example.org:8443/api/v1/auth/callback", keys.get("sheriff.client.redirect-uri")); + assertEquals("https://idp.example.org/realms/trailhand/.well-known/openid-configuration", + keys.get("sheriff.token.issuers.trailhand.jwks.http.well-known-url")); + assertEquals("trailhand-web", keys.get("sheriff.token.issuers.trailhand.expected-client-id")); + assertEquals("true", keys.get("sheriff.token.issuers.trailhand.enabled")); + } + + @Test + @DisplayName("an explicit JWKS address replaces the well-known discovery") + void jwksUrl() { + var keys = new LinkedHashMap(); + keys.put("sheriff.token.issuers.trailhand.jwks.http.well-known-url", "https://idp/.well-known"); + + TokenSheriffConfigSourceFactory.useJwksUrl(keys, "https://keycloak:8443/certs"); + + assertEquals(Map.of("sheriff.token.issuers.trailhand.jwks.http.url", "https://keycloak:8443/certs"), + keys); + } + + @Test + @DisplayName("reads a secret file without one trailing line break and keeps every other character") + void secretFile(@TempDir Path directory) throws Exception { + var file = directory.resolve("secret"); + Files.writeString(file, " s3cret \n"); + assertEquals(" s3cret ", TokenSheriffConfigSourceFactory.readSecret("file:" + file).orElseThrow()); + assertEquals("s\n", TokenSheriffConfigSourceFactory.withoutTrailingLineBreak("s\n\r\n")); + assertEquals("s", TokenSheriffConfigSourceFactory.withoutTrailingLineBreak("s\r")); + assertEquals("s", TokenSheriffConfigSourceFactory.withoutTrailingLineBreak("s")); + } + + @Test + @DisplayName("derives nothing from a missing or invalid file, and no secret from a vault reference") + void nothing(@TempDir Path directory) throws Exception { + assertTrue(TokenSheriffConfigSourceFactory.derive(directory, name -> null).isEmpty()); + Files.writeString(directory.resolve(ConfigurationLoader.FILE_NAME), "rights: {}\n"); + assertTrue(TokenSheriffConfigSourceFactory.derive(directory, name -> null).isEmpty()); + assertTrue(TokenSheriffConfigSourceFactory.readSecret("vault:secret/x").isEmpty()); + assertTrue(TokenSheriffConfigSourceFactory.readSecret("file:" + directory.resolve("absent")).isEmpty()); + } +} diff --git a/trailhand/src/test/java/de/cuioss/trailhand/security/LoginServiceTest.java b/trailhand/src/test/java/de/cuioss/trailhand/security/LoginServiceTest.java new file mode 100644 index 0000000..f6024ae --- /dev/null +++ b/trailhand/src/test/java/de/cuioss/trailhand/security/LoginServiceTest.java @@ -0,0 +1,309 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.security; + +import de.cuioss.sheriff.token.client.auth.ClientAuthentication; +import de.cuioss.sheriff.token.client.discovery.DiscoveryResolver; +import de.cuioss.sheriff.token.client.discovery.ProviderMetadata; +import de.cuioss.sheriff.token.client.flow.AuthorizationCodeFlow; +import de.cuioss.sheriff.token.client.flow.CallbackParameters; +import de.cuioss.sheriff.token.client.flow.FlowContext; +import de.cuioss.sheriff.token.client.flow.ParClient; +import de.cuioss.sheriff.token.client.flow.ParResponse; +import de.cuioss.sheriff.token.client.lifecycle.InMemoryTokenStore; +import de.cuioss.sheriff.token.client.lifecycle.RefreshScheduler; +import de.cuioss.sheriff.token.client.lifecycle.RevocationClient; +import de.cuioss.sheriff.token.client.lifecycle.StoredToken; +import de.cuioss.sheriff.token.client.lifecycle.TokenLifecycleManager; +import de.cuioss.sheriff.token.commons.error.ClientProtocolException; +import de.cuioss.sheriff.token.validation.domain.claim.ClaimValue; +import de.cuioss.sheriff.token.validation.domain.token.AccessTokenContent; +import de.cuioss.sheriff.token.validation.domain.token.IdTokenContent; +import de.cuioss.test.juli.LogAsserts; +import de.cuioss.test.juli.TestLogLevel; +import de.cuioss.test.juli.junit5.EnableTestLogger; +import de.cuioss.trailhand.config.OidcSettings; +import de.cuioss.trailhand.config.TrailhandConfiguration; +import de.cuioss.trailhand.config.WebSettings; +import org.easymock.EasyMock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.easymock.EasyMock.anyObject; +import static org.easymock.EasyMock.eq; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@EnableTestLogger +@DisplayName("LoginService: the web login on Token Sheriff (TRH-AUTH-1)") +class LoginServiceTest { + + private static final String ORIGIN = "https://trailhand.example.org"; + private static final String CALLBACK = ORIGIN + "/api/v1/auth/callback"; + private static final String ISSUER = "https://idp.example.org/realms/trailhand"; + + private DiscoveryResolver discovery; + private AuthorizationCodeFlow flow; + private ParClient par; + private RevocationClient revocation; + private ProviderMetadata metadata; + private ClientAuthentication clientAuthentication; + private TokenLifecycleManager tokens; + private SessionStore sessions; + private LoginTransactions transactions; + private LoginService service; + + @BeforeEach + void setUp() { + discovery = EasyMock.createMock(DiscoveryResolver.class); + flow = EasyMock.createMock(AuthorizationCodeFlow.class); + par = EasyMock.createMock(ParClient.class); + revocation = EasyMock.createMock(RevocationClient.class); + metadata = EasyMock.createNiceMock(ProviderMetadata.class); + clientAuthentication = EasyMock.createNiceMock(ClientAuthentication.class); + tokens = new TokenLifecycleManager(new InMemoryTokenStore(), new RefreshScheduler()); + sessions = new SessionStore(Duration.ofMinutes(30), Duration.ofHours(8), Clock.systemUTC()); + transactions = new LoginTransactions(); + service = service(transactions); + } + + private LoginService service(LoginTransactions pending) { + var configuration = new TrailhandConfiguration(List.of(), Map.of(), + new OidcSettings(ISSUER, "trailhand-web", "file:/x", "groups"), + new WebSettings(URI.create(ORIGIN), Duration.ofMinutes(30), Duration.ofHours(8)), Duration.ofMinutes(5)); + return new LoginService(discovery, flow, par, clientAuthentication, tokens, revocation, sessions, pending, + new ReturnAddresses(), configuration); + } + + /** A JWS-shaped token with the given payload; the signature is irrelevant, Token Sheriff validated it. */ + private static String jws(String payloadJson) { + var encoder = Base64.getUrlEncoder().withoutPadding(); + return encoder.encodeToString("{\"alg\":\"RS256\"}".getBytes(StandardCharsets.UTF_8)) + "." + + encoder.encodeToString(payloadJson.getBytes(StandardCharsets.UTF_8)) + ".c2ln"; + } + + private static IdTokenContent idToken() { + return new IdTokenContent(Map.of("iss", ClaimValue.forPlainString(ISSUER), "sub", ClaimValue.forPlainString("sub-7"), + "name", ClaimValue.forPlainString("Alex Example"), + "groups", ClaimValue.forList("[\"assessors\",\"approvers\"]", List.of("assessors", "approvers")), + "auth_time", ClaimValue.forPlainString("1795161600"), "acr", ClaimValue.forPlainString("1")), + jws("{\"sub\":\"sub-7\",\"groups\":[\"assessors\",\"approvers\"]}")); + } + + private static AccessTokenContent accessToken() { + var exp = OffsetDateTime.now().plusMinutes(5); + return new AccessTokenContent(Map.of("iss", ClaimValue.forPlainString(ISSUER), + "exp", ClaimValue.forDateTime(String.valueOf(exp.toEpochSecond()), exp)), "access-token"); + } + + @Test + @DisplayName("starts with the provider's authorization address and a transaction for the checked return") + void start() { + var context = FlowContext.create(CALLBACK); + expect(discovery.resolve()).andReturn(metadata).once(); + expect(metadata.getPushedAuthorizationRequestEndpoint()).andReturn(Optional.empty()).anyTimes(); + expect(flow.authorize(metadata)) + .andReturn(new AuthorizationCodeFlow.AuthorizationRedirect("https://idp/auth?x", context)).times(2); + replay(discovery, flow, metadata); + + var first = service.start("/samm/payments"); + service.start("//evil.example"); + + assertEquals("https://idp/auth?x", first.authorizationUrl()); + assertEquals("/samm/payments", transactions.take(first.transactionReference()).orElseThrow().returnAddress()); + verify(discovery, flow); + } + + @Test + @DisplayName("pushes the authorization parameters when the provider offers PAR and sends only the request_uri") + void startWithPar() { + var context = FlowContext.create(CALLBACK); + expect(discovery.resolve()).andReturn(metadata); + expect(metadata.getPushedAuthorizationRequestEndpoint()).andReturn(Optional.of("https://idp/par")).anyTimes(); + expect(flow.authorize(metadata)).andReturn(new AuthorizationCodeFlow.AuthorizationRedirect( + "https://idp/auth?client_id=trailhand-web&state=s%201&response_mode=query&flag", context)); + var pushed = new LinkedHashMap(); + pushed.put("client_id", "trailhand-web"); + pushed.put("state", "s 1"); + pushed.put("response_mode", "query"); + pushed.put("flag", ""); + var answer = new ParResponse(); + answer.requestUri = "urn:ietf:params:oauth:request_uri:abc"; + expect(par.pushAuthorizationRequest("https://idp/par", pushed, clientAuthentication)).andReturn(answer); + replay(discovery, flow, metadata, par); + + var started = service.start("/"); + + assertEquals("https://idp/auth?client_id=trailhand-web&request_uri=urn%3Aietf%3Aparams%3Aoauth%3Arequest_uri%3Aabc", + started.authorizationUrl()); + verify(par); + } + + @Test + @DisplayName("refuses a PAR answer without request_uri and a start while too many logins are pending") + void startRefusals() { + var context = FlowContext.create(CALLBACK); + expect(discovery.resolve()).andReturn(metadata).times(2); + expect(metadata.getPushedAuthorizationRequestEndpoint()).andReturn(Optional.of("https://idp/par")).anyTimes(); + expect(flow.authorize(metadata)).andReturn( + new AuthorizationCodeFlow.AuthorizationRedirect("https://idp/auth?client_id=c", context)).times(2); + expect(par.pushAuthorizationRequest(anyObject(), anyObject(), anyObject())).andReturn(new ParResponse()); + replay(discovery, flow, metadata, par); + + assertThrows(IllegalStateException.class, () -> service.start("/")); + var full = service(new LoginTransactions(Clock.systemUTC(), 0)); + assertThrows(LoginService.TooManyLoginsException.class, () -> full.start("/")); + } + + @Test + @DisplayName("frees the place of a login whose PAR request fails, so the next login can start") + void parFailureFreesCapacity() { + var context = FlowContext.create(CALLBACK); + var single = service(new LoginTransactions(Clock.systemUTC(), 1)); + expect(discovery.resolve()).andReturn(metadata); + expect(metadata.getPushedAuthorizationRequestEndpoint()).andReturn(Optional.of("https://idp/par")).anyTimes(); + expect(flow.authorize(metadata)).andReturn( + new AuthorizationCodeFlow.AuthorizationRedirect("https://idp/auth?client_id=c", context)).times(2); + var answer = new ParResponse(); + answer.requestUri = "urn:x"; + expect(par.pushAuthorizationRequest(anyObject(), anyObject(), anyObject())) + .andThrow(new ClientProtocolException("PAR refused")).andReturn(answer); + replay(discovery, flow, metadata, par); + + assertThrows(ClientProtocolException.class, () -> single.start("/")); + + assertEquals("https://idp/auth?client_id=c&request_uri=urn%3Ax", single.start("/").authorizationUrl()); + } + + @Test + @DisplayName("completes a login into a session with the identity values and keeps the tokens server-side") + void complete() { + var context = FlowContext.create(CALLBACK); + var reference = transactions.begin(context, "/incidents").orElseThrow(); + expect(discovery.resolve()).andReturn(metadata); + expect(flow.exchange(eq(metadata), eq(context), anyObject(CallbackParameters.class), eq(clientAuthentication))) + .andReturn(new AuthorizationCodeFlow.AuthenticationResult(accessToken(), idToken(), "refresh-token")); + replay(discovery, flow); + + var completed = service.complete(reference, "code=abc&state=" + context.state()).orElseThrow(); + + var session = completed.session(); + assertEquals("/incidents", completed.returnAddress()); + assertEquals(ISSUER, session.issuer()); + assertEquals("sub-7", session.subject()); + assertEquals("Alex Example", session.name()); + assertEquals(List.of("assessors", "approvers"), session.groups()); + assertEquals(Instant.ofEpochSecond(1795161600L), session.authTime()); + assertEquals("1", session.acr()); + assertEquals("refresh-token", tokens.get(session.id()).orElseThrow().refreshToken()); + LogAsserts.assertLogMessagePresentContaining(TestLogLevel.INFO, "TRAILHAND-3"); + assertTrue(transactions.take(reference).isEmpty(), "a transaction completes once"); + } + + @Test + @DisplayName("refuses a callback without cookie, with an unknown transaction or with a refused exchange") + void refusals() { + var context = FlowContext.create(CALLBACK); + var reference = transactions.begin(context, "/").orElseThrow(); + expect(discovery.resolve()).andReturn(metadata); + expect(flow.exchange(anyObject(), anyObject(), anyObject(), anyObject())) + .andThrow(new ClientProtocolException("state mismatch")); + replay(discovery, flow); + + assertTrue(service.complete(null, "code=a").isEmpty()); + assertTrue(service.complete("unknown", "code=a").isEmpty()); + assertTrue(service.complete(reference, "code=a&state=wrong").isEmpty()); + LogAsserts.assertLogMessagePresentContaining(TestLogLevel.WARN, "TRAILHAND-103"); + } + + @Test + @DisplayName("logs out: revokes both tokens and leads to the provider's end-session address") + void logout() { + var session = sessions.open(new LoginIdentity(ISSUER, "sub-7", "Alex", List.of(), null, null)); + tokens.store(session.id(), new StoredToken("access-token", + "refresh-token", "id-token", null, Instant.now().plusSeconds(300), "sub-7")); + ProviderMetadata endpoints = EasyMock.createMock(ProviderMetadata.class); + expect(endpoints.getRevocationEndpoint()).andReturn(Optional.of("https://idp/revoke")).anyTimes(); + expect(endpoints.getEndSessionEndpoint()).andReturn(Optional.of("https://idp/logout")).anyTimes(); + expect(discovery.resolve()).andReturn(endpoints); + revocation.revoke("https://idp/revoke", "refresh-token", "refresh_token", clientAuthentication); + revocation.revoke("https://idp/revoke", "access-token", "access_token", clientAuthentication); + expectLastCall().andThrow(new ClientProtocolException("revocation refused")); + replay(discovery, endpoints, revocation); + + var redirect = service.logout(session.id()); + + assertTrue(redirect.startsWith("https://idp/logout?"), redirect); + assertTrue(redirect.contains("id_token_hint=id-token"), redirect); + assertTrue(sessions.use(session.id()).isEmpty()); + assertTrue(tokens.get(session.id()).isEmpty()); + LogAsserts.assertLogMessagePresentContaining(TestLogLevel.WARN, "TRAILHAND-104"); + verify(revocation); + } + + @Test + @DisplayName("logs out a session without tokens to the own origin") + void logoutWithoutTokens() { + assertEquals(ORIGIN + "/", service.logout("unknown")); + } + + @Test + @DisplayName("reads the groups as the provider wrote them: a comma inside a group name keeps it one group") + void groups() { + assertEquals(List.of("auditors,admins", "readers"), + LoginService.groups(jws("{\"memberOf\":[\"auditors,admins\",\"readers\",7,\" \"]}"), "memberOf")); + assertEquals(List.of("auditors,admins"), LoginService.groups(jws("{\"memberOf\":\"auditors,admins\"}"), "memberOf")); + assertEquals(List.of(), LoginService.groups(jws("{\"memberOf\":{\"a\":1}}"), "memberOf")); + assertEquals(List.of(), LoginService.groups(jws("{\"memberOf\":\" \"}"), "memberOf")); + assertEquals(List.of(), LoginService.groups(jws("{}"), "memberOf")); + } + + @Test + @DisplayName("grants no group from a token it cannot read") + void unreadableGroups() { + assertEquals(List.of(), LoginService.groups("not-a-jws", "groups")); + assertEquals(List.of(), LoginService.groups("a.%%%.c", "groups")); + assertEquals(List.of(), LoginService.groups("a." + Base64.getUrlEncoder().encodeToString("[".getBytes( + StandardCharsets.UTF_8)) + ".c", "groups")); + LogAsserts.assertLogMessagePresentContaining(TestLogLevel.WARN, "TRAILHAND-103"); + } + + @Test + @DisplayName("reads auth_time as epoch seconds and splits a query into its decoded parameters") + void parsing() { + assertEquals(Optional.empty(), LoginService.epochSeconds("not a number")); + assertEquals(Optional.empty(), LoginService.epochSeconds(null)); + assertEquals(Map.of("a", "1 2", "b", ""), LoginService.queryParameters("a=1+2&&b")); + } +} diff --git a/trailhand/src/test/java/de/cuioss/trailhand/security/QueryResponseModeRequestBuilderTest.java b/trailhand/src/test/java/de/cuioss/trailhand/security/QueryResponseModeRequestBuilderTest.java new file mode 100644 index 0000000..101a07e --- /dev/null +++ b/trailhand/src/test/java/de/cuioss/trailhand/security/QueryResponseModeRequestBuilderTest.java @@ -0,0 +1,38 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.security; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@DisplayName("QueryResponseModeRequestBuilder: response_mode=query (TRH-AUTH-1)") +class QueryResponseModeRequestBuilderTest { + + @ParameterizedTest(name = "{0}") + @CsvSource(delimiter = '|', value = { + "replaces form_post in place|https://idp/auth?client_id=a&response_mode=form_post&state=s|https://idp/auth?client_id=a&response_mode=query&state=s", + "adds the parameter|https://idp/auth?client_id=a&state=s|https://idp/auth?client_id=a&state=s&response_mode=query", + "adds a query|https://idp/auth|https://idp/auth?response_mode=query", + "fills an empty query|https://idp/auth?|https://idp/auth?response_mode=query", + "is idempotent|https://idp/auth?response_mode=query|https://idp/auth?response_mode=query", + "keeps a similar name|https://idp/auth?response_modes=x|https://idp/auth?response_modes=x&response_mode=query"}) + void rewrites(String name, String url, String expected) { + assertEquals(expected, QueryResponseModeRequestBuilder.withQueryResponseMode(url), name); + } +} diff --git a/trailhand/src/test/java/de/cuioss/trailhand/security/SecurityTest.java b/trailhand/src/test/java/de/cuioss/trailhand/security/SecurityTest.java new file mode 100644 index 0000000..3fd2556 --- /dev/null +++ b/trailhand/src/test/java/de/cuioss/trailhand/security/SecurityTest.java @@ -0,0 +1,276 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.security; + +import de.cuioss.sheriff.token.client.flow.FlowContext; +import de.cuioss.test.generator.Generators; +import de.cuioss.test.generator.junit.EnableGeneratorController; +import de.cuioss.trailhand.config.Action; +import de.cuioss.trailhand.config.RightSettings; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@EnableGeneratorController +@DisplayName("The security package (TRH-AUTH-1, TRH-AUTH-2)") +class SecurityTest { + + private static final Instant START = Instant.parse("2026-11-20T08:00:00Z"); + private static final String CALLBACK = "https://trailhand.example.org/api/v1/auth/callback"; + + /** A clock the test moves. */ + private static final class MovableClock extends Clock { + private Instant now = START; + + @Override + public ZoneOffset getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now; + } + + void advance(Duration duration) { + now = now.plus(duration); + } + } + + private static LoginIdentity identity() { + return new LoginIdentity("https://idp.example.org", "sub", "Alex", List.of("assessors"), START, "1"); + } + + @Nested + @DisplayName("SessionStore") + class Sessions { + + @Test + @DisplayName("opens sessions with random ids and tokens and ends them after the idle timeout") + void idle() { + var clock = new MovableClock(); + var store = new SessionStore(Duration.ofMinutes(30), Duration.ofHours(8), clock); + var first = store.open(identity()); + var second = store.open(identity()); + assertNotEquals(first.id(), second.id()); + assertNotEquals(first.csrfToken(), first.id()); + + clock.advance(Duration.ofMinutes(29)); + assertTrue(store.use(first.id()).isPresent()); + clock.advance(Duration.ofMinutes(29)); + assertTrue(store.use(first.id()).isPresent(), "use renews the idle time"); + clock.advance(Duration.ofMinutes(31)); + assertTrue(store.use(first.id()).isEmpty()); + assertEquals(Set.of(first.id(), second.id()), Set.copyOf(store.evictExpired()), + "the session found expired by the request is handed on as well"); + assertFalse(second.toString().contains(second.csrfToken())); + } + + @Test + @DisplayName("ends a session after its absolute lifetime however active it is") + void lifetime() { + var clock = new MovableClock(); + var store = new SessionStore(Duration.ofMinutes(30), Duration.ofHours(1), clock); + var session = store.open(identity()); + for (int step = 0; step < 3; step++) { + clock.advance(Duration.ofMinutes(20)); + assertTrue(store.use(session.id()).isPresent()); + } + clock.advance(Duration.ofMinutes(1)); + assertTrue(store.use(session.id()).isEmpty()); + assertTrue(store.close(session.id()).isEmpty()); + assertTrue(store.use("unknown").isEmpty()); + } + + @Test + @DisplayName("hands a session that a request found expired to the next eviction, so its tokens are dropped") + void expiredOnUse() { + var clock = new MovableClock(); + var store = new SessionStore(Duration.ofMinutes(30), Duration.ofHours(8), clock); + var seen = store.open(identity()); + var idle = store.open(identity()); + clock.advance(Duration.ofMinutes(31)); + + assertTrue(store.use(seen.id()).isEmpty()); + + assertEquals(Set.of(seen.id(), idle.id()), Set.copyOf(store.evictExpired())); + assertTrue(store.evictExpired().isEmpty(), "each id is handed on once"); + } + + @Test + @DisplayName("does not bring a closed session back and keeps a session renewed before the eviction") + void closedStaysClosed() { + var clock = new MovableClock(); + var store = new SessionStore(Duration.ofMinutes(30), Duration.ofHours(8), clock); + var session = store.open(identity()); + store.close(session.id()); + assertTrue(store.use(session.id()).isEmpty()); + + var renewed = store.open(identity()); + clock.advance(Duration.ofMinutes(29)); + assertTrue(store.use(renewed.id()).isPresent()); + clock.advance(Duration.ofMinutes(2)); + assertTrue(store.evictExpired().isEmpty(), "the renewed session is not expired"); + assertTrue(store.use(renewed.id()).isPresent()); + } + } + + @Nested + @DisplayName("RightsMapper") + class Rights { + + private final RightsMapper mapper = new RightsMapper(Map.of( + "assessors", List.of(new RightSettings("samm", Set.of(Action.READ, Action.EDIT))), + "approvers", List.of(new RightSettings("samm", Set.of(Action.APPROVE)), + new RightSettings("isms", Set.of(Action.READ))))); + + @Test + @DisplayName("unites the rights of all groups per repository") + void unites() { + assertEquals(Map.of("samm", Set.of(Action.READ, Action.EDIT, Action.APPROVE), "isms", Set.of(Action.READ)), + mapper.rightsOf(List.of("assessors", "approvers"))); + assertTrue(mapper.permits(List.of("approvers"), "samm", Action.APPROVE)); + } + + @Test + @DisplayName("denies by default") + void deniesByDefault() { + var group = Generators.letterStrings(4, 12).next(); + assertTrue(mapper.rightsOf(List.of(group)).isEmpty()); + assertFalse(mapper.permits(List.of("assessors"), "samm", Action.APPROVE)); + assertFalse(mapper.permits(List.of(), "samm", Action.READ)); + } + } + + @Nested + @DisplayName("ReturnAddresses") + class Returns { + + private final ReturnAddresses addresses = new ReturnAddresses(); + + @ParameterizedTest + @ValueSource(strings = {"/", "/samm", "/samm/payments/2026-q4/sm", "/samm/payments/2026-q4/release", + "/incidents/2026/inc-0007", "/settings/appearance", "/welcome"}) + @DisplayName("accepts a canonical address") + void accepts(String address) { + assertEquals(address, addresses.check(address)); + } + + @ParameterizedTest + @ValueSource(strings = {"//evil.example/x", "https://evil.example", "/\\evil", "samm", "/unknown", + "/incidents/26/x", "/samm/A", "", "/%2F%2Fevil"}) + @DisplayName("replaces anything else by /") + void replaces(String address) { + assertEquals("/", addresses.check(address)); + } + + @Test + @DisplayName("drops a query, a trailing slash and refuses null and overlong values") + void normalises() { + assertEquals("/samm", addresses.check("/samm/?x=1")); + assertEquals("/", addresses.check(null)); + assertEquals("/", addresses.check("/samm/" + "a".repeat(600))); + var segment = Generators.letterStrings(3, 20).next().toLowerCase(Locale.ROOT); + assertEquals("/catalogs/" + segment, addresses.check("/catalogs/" + segment)); + } + } + + @Nested + @DisplayName("LoginTransactions") + class Transactions { + + @Test + @DisplayName("hand a transaction out once and only within ten minutes") + void once() { + var clock = new MovableClock(); + var transactions = new LoginTransactions(clock, LoginTransactions.MAX_PENDING); + var context = FlowContext.create(CALLBACK); + var reference = transactions.begin(context, "/samm").orElseThrow(); + + var taken = transactions.take(reference); + assertTrue(taken.isPresent()); + assertEquals("/samm", taken.get().returnAddress()); + assertTrue(transactions.take(reference).isEmpty()); + + var late = transactions.begin(context, "/").orElseThrow(); + clock.advance(LoginTransactions.LIFETIME.plusSeconds(1)); + assertTrue(transactions.take(late).isEmpty()); + } + + @Test + @DisplayName("refuse a start beyond the limit until a pending login is taken or expires") + void bounded() { + var clock = new MovableClock(); + var transactions = new LoginTransactions(clock, 2); + var context = FlowContext.create(CALLBACK); + var first = transactions.begin(context, "/").orElseThrow(); + assertTrue(transactions.begin(context, "/").isPresent()); + + assertTrue(transactions.begin(context, "/").isEmpty(), "the third pending login is refused"); + transactions.take(first); + assertTrue(transactions.begin(context, "/").isPresent(), "a taken login frees its place"); + assertTrue(transactions.begin(context, "/").isEmpty()); + + clock.advance(LoginTransactions.LIFETIME.plusSeconds(1)); + assertTrue(transactions.begin(context, "/").isPresent(), "a start drops the expired logins"); + } + + @Test + @DisplayName("stay bounded when starts at the limit repeat and when started logins are taken at once") + void repeatedStarts() { + var clock = new MovableClock(); + var transactions = new LoginTransactions(clock, 3); + var context = FlowContext.create(CALLBACK); + for (int start = 0; start < 3; start++) { + assertTrue(transactions.begin(context, "/").isPresent()); + } + for (int start = 0; start < 1_000; start++) { + assertTrue(transactions.begin(context, "/").isEmpty(), "every start at the limit is refused"); + } + clock.advance(LoginTransactions.LIFETIME.plusSeconds(1)); + for (int cycle = 0; cycle < 1_000; cycle++) { + var reference = transactions.begin(context, "/").orElseThrow(); + assertTrue(transactions.take(reference).isPresent()); + } + for (int start = 0; start < 3; start++) { + assertTrue(transactions.begin(context, "/").isPresent(), "taken logins left their places free"); + } + assertTrue(transactions.begin(context, "/").isEmpty()); + } + } +} diff --git a/trailhand/src/test/java/de/cuioss/trailhand/service/RepositoryServiceTest.java b/trailhand/src/test/java/de/cuioss/trailhand/service/RepositoryServiceTest.java new file mode 100644 index 0000000..95d516e --- /dev/null +++ b/trailhand/src/test/java/de/cuioss/trailhand/service/RepositoryServiceTest.java @@ -0,0 +1,143 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.service; + +import de.cuioss.git.document.testing.LocalRemote; +import de.cuioss.git.document.testing.Remote; +import de.cuioss.test.juli.LogAsserts; +import de.cuioss.test.juli.TestLogLevel; +import de.cuioss.test.juli.junit5.EnableTestLogger; +import de.cuioss.trailhand.config.RepositorySettings; +import org.easymock.EasyMock; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Stream; + +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; + +@EnableTestLogger +@DisplayName("RepositoryService: local copies, fetch and readiness (TRH-CONF-2, TRH-OPS-2, TRH-GEN-6)") +class RepositoryServiceTest { + + private static RepositorySettings local(String alias, String remote) { + return new RepositorySettings(alias, remote, "restricted", null, null); + } + + private static RepositorySettings https(String alias, String remote) { + return new RepositorySettings(alias, remote, "restricted", null, "file:/run/secrets/git"); + } + + @Test + @DisplayName("clones a local remote, stays present when the remote vanishes and reports the failed fetch") + void cloneFetchDegrade(@Remote LocalRemote remote, @TempDir Path data) throws Exception { + var remoteDir = Path.of(remote.uri().getPath()); + var created = RepositoryService.create(List.of(local("samm", "file:" + remoteDir)), data); + var service = created.value(); + assertNotNull(service, created.detail()); + assertFalse(service.allPresent()); + + service.refresh(); + + assertTrue(service.allPresent()); + assertFalse(service.degraded()); + assertTrue(Files.isDirectory(service.gitDirectory("samm").orElseThrow())); + LogAsserts.assertLogMessagePresentContaining(TestLogLevel.INFO, "TRAILHAND-2"); + + deleteTree(remoteDir); + service.refresh(); + + assertTrue(service.allPresent(), "a failed fetch keeps the local copy"); + assertTrue(service.degraded()); + assertEquals(List.of(new RepositoryState("samm", true, false)), service.states()); + LogAsserts.assertLogMessagePresentContaining(TestLogLevel.WARN, "TRAILHAND-100"); + + var restarted = RepositoryService.create(List.of(local("samm", "file:" + remoteDir)), data).value(); + assertNotNull(restarted); + restarted.refresh(); + assertEquals(List.of(new RepositoryState("samm", true, false)), restarted.states(), + "a copy kept on the volume is present at once but fetch-UP only after a fetch succeeds"); + } + + @Test + @DisplayName("keeps an unreachable repository absent and tries again") + void unreachable(@TempDir Path data) { + var service = RepositoryService.create(List.of(local("gone", "file:" + data.resolve("nowhere.git"))), data) + .value(); + assertNotNull(service); + + service.refresh(); + + assertFalse(service.allPresent()); + LogAsserts.assertLogMessagePresentContaining(TestLogLevel.WARN, "TRAILHAND-101"); + } + + @Test + @DisplayName("admits local remotes and one https origin, and refuses a second origin") + void policy() { + assertTrue(RepositoryService.remotePolicy(List.of(local("a", "file:/x"))).isPresent()); + assertTrue(RepositoryService.remotePolicy( + List.of(https("a", "https://git.example.org/a.git"), https("b", "https://git.example.org/b.git"))) + .isPresent()); + assertTrue(RepositoryService.remotePolicy( + List.of(https("a", "https://git.example.org/a.git"), https("b", "https://other.example.org/b.git"))) + .isEmpty()); + assertNotNull(RepositoryService.create(List.of(https("a", "https://git.example.org/a.git"), + https("b", "https://other.example.org/b.git")), Path.of("target")).detail()); + } + + @Test + @DisplayName("hands file: remotes to the library as absolute paths") + void libraryRemote() { + assertEquals(Path.of("/srv/x.git").toString(), + RepositoryService.libraryRemote(local("x", "file:///srv/x.git"))); + assertEquals(Path.of("rel.git").toAbsolutePath().toString(), + RepositoryService.libraryRemote(local("x", "file:rel.git"))); + assertEquals("https://git.example.org/a.git", + RepositoryService.libraryRemote(https("a", "https://git.example.org/a.git"))); + } + + @Test + @DisplayName("a failing refresh is logged and does not end the periodic fetch") + void refreshSafely() { + RepositoryService service = EasyMock.createMock(RepositoryService.class); + service.refresh(); + EasyMock.expectLastCall().andThrow(new IllegalStateException("broken")); + EasyMock.replay(service); + + RepositoryLifecycle.refreshSafely(service); + + LogAsserts.assertLogMessagePresentContaining(TestLogLevel.WARN, "TRAILHAND-105"); + EasyMock.verify(service); + } + + private static void deleteTree(Path root) throws IOException { + try (Stream paths = Files.walk(root)) { + for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) { + Files.delete(path); + } + } + } +} diff --git a/trailhand/src/test/java/de/cuioss/trailhand/web/PagePolicyTest.java b/trailhand/src/test/java/de/cuioss/trailhand/web/PagePolicyTest.java new file mode 100644 index 0000000..d9566e9 --- /dev/null +++ b/trailhand/src/test/java/de/cuioss/trailhand/web/PagePolicyTest.java @@ -0,0 +1,48 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.web; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +@DisplayName("PagePolicy: the policy header from the page's (TRH-WEB-8)") +class PagePolicyTest { + + @Test + @DisplayName("repeats the page's policy and adds frame-ancestors") + void fromMeta() { + var html = ""; + + var policy = new PagePolicy(html.getBytes(StandardCharsets.UTF_8)); + + assertEquals("default-src 'self'; script-src 'self' 'sha256-abc'; frame-ancestors 'none'", policy.getPolicy()); + } + + @Test + @DisplayName("falls back to the strict policy without a page") + void fallback() { + var policy = new PagePolicy(new byte[0]); + + assertFalse(policy.hasIndex()); + assertEquals(PagePolicy.FALLBACK_POLICY + "; frame-ancestors 'none'", policy.getPolicy()); + assertEquals("<a href="x">&'", AuthResource.escape("&'")); + } +} diff --git a/trailhand/src/test/java/de/cuioss/trailhand/web/RuntimeEndpointsTest.java b/trailhand/src/test/java/de/cuioss/trailhand/web/RuntimeEndpointsTest.java new file mode 100644 index 0000000..5c634e1 --- /dev/null +++ b/trailhand/src/test/java/de/cuioss/trailhand/web/RuntimeEndpointsTest.java @@ -0,0 +1,80 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.web; + +import de.cuioss.trailhand.security.LoginIdentity; +import de.cuioss.trailhand.security.SessionStore; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.URI; +import java.net.URL; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +@DisplayName("Event stream, health and metrics (TRH-WEB-9, TRH-OPS-2, TRH-GEN-5)") +class RuntimeEndpointsTest { + + @Inject + SessionStore sessions; + + @TestHTTPResource("/api/v1/events") + URL events; + + @Test + @DisplayName("the event stream opens with the status event") + void eventStream() throws Exception { + var session = sessions.open(new LoginIdentity("https://idp.example.org", "s", "Alex", List.of(), null, null)); + var request = HttpRequest.newBuilder(URI.create(events.toString())).timeout(Duration.ofSeconds(10)) + .header("Cookie", Cookies.SESSION + "=" + session.id()).header("Accept", "text/event-stream").build(); + + var response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofInputStream()); + + assertEquals(200, response.statusCode()); + assertTrue(response.headers().firstValue("Content-Type").orElse("").startsWith("text/event-stream")); + try (var reader = new BufferedReader(new InputStreamReader(response.body(), StandardCharsets.UTF_8))) { + var first = reader.readLine(); + var second = reader.readLine(); + // A field may be followed by a space or not (WHATWG HTML, server-sent events, field parsing). + assertEquals("event:status", first.replace(": ", ":")); + assertTrue(second.replace(": ", ":").startsWith("data:{\"version\""), second); + } + } + + @Test + @DisplayName("readiness names the repositories, metrics are on the management port") + void management() { + var managementPort = Integer.parseInt(System.getProperty("quarkus.management.test-port", "9001")); + var health = given().port(managementPort).get("/q/health/ready").then().extract(); + assertTrue(health.asString().contains("\"repositories\""), health.asString()); + given().port(managementPort).get("/q/health/group/git-remote").then().extract(); + given().port(managementPort).get("/q/metrics").then().statusCode(200); + } +} diff --git a/trailhand/src/test/java/de/cuioss/trailhand/web/WebApiTest.java b/trailhand/src/test/java/de/cuioss/trailhand/web/WebApiTest.java new file mode 100644 index 0000000..197efee --- /dev/null +++ b/trailhand/src/test/java/de/cuioss/trailhand/web/WebApiTest.java @@ -0,0 +1,184 @@ +/* + * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.cuioss.trailhand.web; + +import de.cuioss.trailhand.security.LoginIdentity; +import de.cuioss.trailhand.security.SessionStore; +import de.cuioss.trailhand.security.UserSession; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.List; + +import static io.restassured.RestAssured.given; +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; + +@QuarkusTest +@DisplayName("The web API: gate, page security and shell requests (TRH-WEB-1, TRH-WEB-8, TRH-WEB-9, TRH-AUTH-1)") +class WebApiTest { + + private static final String OWN_ORIGIN = "https://trailhand.example.org"; + + @Inject + SessionStore sessions; + + private UserSession session; + + @BeforeEach + void openSession() { + session = sessions.open(new LoginIdentity("https://idp.example.org/realms/trailhand", "sub-1", "Alex Example", + List.of("assessors"), Instant.now(), "1")); + } + + @Nested + @DisplayName("Public requests") + class PublicRequests { + + @Test + @DisplayName("status answers without login and names the repositories") + void status() { + var body = given().when().get("/api/v1/status").then().statusCode(200).extract().jsonPath(); + assertNotNull(body.getString("version")); + assertEquals("samm-assessments", body.getString("repositories[0].alias")); + } + + @Test + @DisplayName("messages answer English by default, German on request, and refuse another language") + void messages() { + assertEquals("Due", given().get("/api/v1/messages").then().statusCode(200).extract().path("'lens.due'")); + assertEquals("Fällig", + given().get("/api/v1/messages?lang=de").then().statusCode(200).extract().path("'lens.due'")); + assertEquals("VALIDATION", + given().get("/api/v1/messages?lang=fr").then().statusCode(400).extract().path("outcome")); + } + } + + @Nested + @DisplayName("The session gate") + class Gate { + + @Test + @DisplayName("refuses a request without session with 401 and the login address") + void unauthenticated() { + var body = given().get("/api/v1/session").then().statusCode(401).extract().jsonPath(); + assertEquals("UNAUTHENTICATED", body.getString("outcome")); + assertEquals("/api/v1/auth/login", body.getString("login")); + given().cookie(Cookies.SESSION, "unknown").get("/api/v1/due").then().statusCode(401); + } + + @Test + @DisplayName("answers the session with the mapped rights and the anti-CSRF token") + void sessionBody() { + var body = given().cookie(Cookies.SESSION, session.id()).get("/api/v1/session").then().statusCode(200) + .extract().jsonPath(); + assertEquals("Alex Example", body.getString("user.name")); + assertEquals(session.csrfToken(), body.getString("csrfToken")); + assertEquals("samm-assessments", body.getString("rights[0].repository")); + assertEquals(List.of("read", "edit"), body.getList("rights[0].actions")); + assertFalse(body.getBoolean("firstLoginRequired")); + } + + @Test + @DisplayName("answers the due list for a session") + void due() { + given().cookie(Cookies.SESSION, session.id()).get("/api/v1/due").then().statusCode(200); + } + + @Test + @DisplayName("refuses a state-changing request without the anti-CSRF header") + void csrfMissing() { + assertEquals("CSRF_REJECTED", given().cookie(Cookies.SESSION, session.id()).post("/api/v1/auth/logout") + .then().statusCode(403).extract().path("outcome")); + } + + @Test + @DisplayName("refuses a state-changing request from a foreign origin even with the token") + void foreignOrigin() { + given().cookie(Cookies.SESSION, session.id()).header(RequestGate.CSRF_HEADER, session.csrfToken()) + .header("Origin", "https://evil.example").post("/api/v1/auth/logout").then().statusCode(403); + } + + @Test + @DisplayName("logs out with the token from the own origin and deletes the session cookie") + void logout() { + var response = given().cookie(Cookies.SESSION, session.id()) + .header(RequestGate.CSRF_HEADER, session.csrfToken()).header("Origin", OWN_ORIGIN) + .post("/api/v1/auth/logout").then().statusCode(200).extract(); + assertEquals(OWN_ORIGIN + "/", response.path("redirect")); + assertTrue(response.header("Set-Cookie").contains("Max-Age=0")); + given().cookie(Cookies.SESSION, session.id()).get("/api/v1/session").then().statusCode(401); + } + } + + @Nested + @DisplayName("The login callback") + class Callback { + + @Test + @DisplayName("refuses a callback without login transaction and offers a new login") + void withoutTransaction() { + var response = given().get("/api/v1/auth/callback?code=x&state=y").then().statusCode(400).extract(); + assertTrue(response.asString().contains("/api/v1/auth/login?return=/")); + assertTrue(response.header("Set-Cookie").startsWith(Cookies.LOGIN + "=;")); + } + + @Test + @DisplayName("refuses a callback with an unknown login transaction") + void unknownTransaction() { + given().cookie(Cookies.LOGIN, "unknown").get("/api/v1/auth/callback?code=x&state=y").then() + .statusCode(400); + } + } + + @Nested + @DisplayName("Page security and the web app") + class Pages { + + @Test + @DisplayName("every canonical address answers the web app's index.html with the policy header") + void appPage() { + var response = given().accept("text/html").get("/samm/payments/2026-q4").then().statusCode(200).extract(); + assertTrue(response.asString().contains("theme-init.js")); + var policy = response.header("Content-Security-Policy"); + assertTrue(policy.contains("script-src 'self' 'sha256-"), policy); + assertTrue(policy.endsWith("frame-ancestors 'none'"), policy); + assertFalse(policy.contains("unsafe-inline"), policy); + assertEquals("nosniff", response.header("X-Content-Type-Options")); + assertEquals("no-referrer", response.header("Referrer-Policy")); + } + + @Test + @DisplayName("files of the web app are served as files") + void staticFile() { + given().get("/theme-init.js").then().statusCode(200).contentType(Matchers.containsString("javascript")); + } + + @Test + @DisplayName("an unknown API path is no page") + void unknownApi() { + given().cookie(Cookies.SESSION, session.id()).get("/api/v1/nothing").then().statusCode(404); + } + } +} diff --git a/trailhand/src/test/resources/config/client-secret b/trailhand/src/test/resources/config/client-secret new file mode 100644 index 0000000..c301d47 --- /dev/null +++ b/trailhand/src/test/resources/config/client-secret @@ -0,0 +1 @@ +test-secret diff --git a/trailhand/src/test/resources/config/trailhand.yaml b/trailhand/src/test/resources/config/trailhand.yaml new file mode 100644 index 0000000..8221f0b --- /dev/null +++ b/trailhand/src/test/resources/config/trailhand.yaml @@ -0,0 +1,24 @@ +# trailhand.yaml of the unit tests: a local bare repository and an issuer that is never contacted. +repositories: + - alias: samm-assessments + remote: file:target/test-remotes/samm-assessments.git + confidentiality: restricted + retention: unlimited +rights: + assessors: + - repository: samm-assessments + actions: [read, edit] + approvers: + - repository: samm-assessments + actions: [read, approve] +oidc: + issuer: https://idp.example.org/realms/trailhand + client-id: trailhand-web + client-credential-ref: file:src/test/resources/config/client-secret +web: + origin: https://trailhand.example.org + session: + idle-timeout: PT30M + max-lifetime: PT8H +fetch: + interval: PT1H diff --git a/web-app/pom.xml b/web-app/pom.xml index c4c5981..3946d5a 100644 --- a/web-app/pom.xml +++ b/web-app/pom.xml @@ -123,8 +123,11 @@ maven-resources-plugin + copy-spa-resources - prepare-package + process-classes copy-resources diff --git a/web-app/src/lib/i18n/catalogue.test.ts b/web-app/src/lib/i18n/catalogue.test.ts index 49cd0c8..3f8ff83 100644 --- a/web-app/src/lib/i18n/catalogue.test.ts +++ b/web-app/src/lib/i18n/catalogue.test.ts @@ -2,10 +2,11 @@ import fs from 'node:fs'; import path from 'node:path'; import { describe, expect, it } from 'vitest'; import { loadMessages } from '../../test/catalogue-fixture'; +import { LOCALES } from './index'; /** - * The catalogue (TRH-WEB-7): both languages hold the same keys, no text is empty, and every key the - * sources name exists. + * The catalogue (TRH-WEB-7): the languages are its files, both languages hold the same keys, no text + * is empty, and every key the sources name exists. */ const en = loadMessages('en'); const de = loadMessages('de'); @@ -20,7 +21,17 @@ function sources(dir: string): string[] { }); } +const MESSAGES_DIR = path.resolve(__dirname, '../../main/resources/META-INF/trailhand/messages'); + describe('the message catalogue', () => { + it('offers exactly the languages that have a catalogue file', () => { + // The server serves every language with a file; the app's language list must name the same ones. + const files = fs + .readdirSync(MESSAGES_DIR) + .flatMap((name) => /^messages_([a-z]{2})\.properties$/.exec(name)?.[1] ?? []); + expect([...LOCALES].sort()).toEqual(files.sort()); + }); + it('holds the same keys in English and German', () => { expect(Object.keys(de).sort()).toEqual(Object.keys(en).sort()); }); diff --git a/web-app/src/main/resources/META-INF/trailhand/messages/messages_de.properties b/web-app/src/main/resources/META-INF/trailhand/messages/messages_de.properties index 03c5290..cb73293 100644 --- a/web-app/src/main/resources/META-INF/trailhand/messages/messages_de.properties +++ b/web-app/src/main/resources/META-INF/trailhand/messages/messages_de.properties @@ -88,3 +88,8 @@ error.validation.REFERENCE_NOT_FOUND=Wählen Sie einen Eintrag aus der Liste. error.not-found.title=Adresse nicht gefunden error.not-found.body=Unter dieser Adresse gibt es keine Ansicht. error.not-found.home=Zu „Fällig“ + +auth.callback.title=Anmeldung +auth.callback.continue=Weiter zu TrailHand +auth.callback.failed=Die Anmeldung konnte nicht abgeschlossen werden. +auth.callback.retry=Erneut anmelden diff --git a/web-app/src/main/resources/META-INF/trailhand/messages/messages_en.properties b/web-app/src/main/resources/META-INF/trailhand/messages/messages_en.properties index 50d9931..213f7fe 100644 --- a/web-app/src/main/resources/META-INF/trailhand/messages/messages_en.properties +++ b/web-app/src/main/resources/META-INF/trailhand/messages/messages_en.properties @@ -89,3 +89,8 @@ error.validation.REFERENCE_NOT_FOUND=Pick an entry from the list. error.not-found.title=Address not found error.not-found.body=There is no view at this address. error.not-found.home=Go to Due + +auth.callback.title=Signing in +auth.callback.continue=Continue to TrailHand +auth.callback.failed=The login could not be completed. +auth.callback.retry=Sign in again