diff --git a/README.adoc b/README.adoc index df0130c..e1811a1 100644 --- a/README.adoc +++ b/README.adoc @@ -39,13 +39,14 @@ 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, 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): +link:trailhand/README.adoc[`trailhand`] (the Quarkus application), link:web-e2e/README.adoc[`web-e2e`] (Playwright +and axe-core) and link:integration-tests/README.adoc[`integration-tests`] (the native image with Keycloak). 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 verify -Pintegration-tests -pl integration-tests -am # native image + Keycloak, Docker required ./mvnw package -Pnative -pl trailhand -am docker build -f trailhand/src/main/docker/Dockerfile.native -t trailhand:dev trailhand ---- diff --git a/doc/specification/architecture-and-modules.adoc b/doc/specification/architecture-and-modules.adoc index ed6ded6..639d2b0 100644 --- a/doc/specification/architecture-and-modules.adoc +++ b/doc/specification/architecture-and-modules.adoc @@ -72,7 +72,7 @@ Root: `de.cuioss:trailhand-parent` (working coordinates). Parent `de.cuioss:cui- |Playwright and axe-core suite; profile `e2e` |`integration-tests` -|pom +|jar (not deployed) |Native image, distroless container, compose stack, failsafe `*IT`; profile `integration-tests`; the measurements of xref:testing.adoc#TRH-NFR-1[TRH-NFR-1] and xref:testing.adoc#TRH-NFR-2[TRH-NFR-2] in the profile `benchmarks` diff --git a/doc/specification/testing.adoc b/doc/specification/testing.adoc index 1ef5ec0..4a82a05 100644 --- a/doc/specification/testing.adoc +++ b/doc/specification/testing.adoc @@ -34,7 +34,9 @@ xref:../concepts/application-architecture.adoc#_testing[Application Architecture |Integration |Profile `integration-tests` (failsafe `*IT`) -|Native image, distroless container, compose stack with Keycloak and Gitea +|Native image, distroless container, compose stack with Keycloak and Gitea; until the Git round trip +(<>) is built, the repositories are local bare repositories mounted as `file:` remotes (TRH-CONF-2) and +Gitea is not started |Benchmarks |Profile `benchmarks` of the `integration-tests` module, in a CI job of its own diff --git a/integration-tests/README.adoc b/integration-tests/README.adoc new file mode 100644 index 0000000..de7f3a7 --- /dev/null +++ b/integration-tests/README.adoc @@ -0,0 +1,127 @@ += TrailHand Integration Tests +:toc: left +:toclevels: 2 + +The integration lane of `doc/specification/testing.adoc`: the native image of `trailhand` in its distroless container, +with a Keycloak, in one compose stack. The tests talk to it over HTTPS as a browser would, including the login form of +Keycloak. Gitea joins with the Git round trip (TRH-NFR-5); until then the repositories are local bare repositories +mounted as `file:` remotes (TRH-CONF-2). The module deploys nothing, and CI does not run the profile yet. + +== Running + +Docker with compose is required. + +[source,bash] +---- +./mvnw verify -Pintegration-tests -pl integration-tests -am +---- + +Without the profile the module only compiles. With it, Maven: + +. before the tests: stops a leftover stack, generates the certificates, seeds the remotes, builds the native runner + and the image `trailhand:it` when they are missing or built from other inputs, and starts the stack + (`scripts/start-integration-stack.sh` waits until Keycloak is ready and the TrailHand container is ready and + reported healthy; a start that fails stops the stack again); +. runs every `*IT` with failsafe; +. afterwards: writes the container logs to `target/compose.log` and removes the stack with its volume, then checks + that an invalid configuration fails `--validate-config` and stops the boot with exactly the `TRAILHAND-200` records + `--validate-config` reports, one per violation (`scripts/verify-invalid-config-fails.sh`, TRH-NFR-5). + +The native build runs Mandrel in a container and takes minutes. A later run reuses the runner while its inputs are +unchanged: `scripts/build-native-if-needed.sh` fingerprints the reactor's build files, the sources of `trailhand` and +`web-app` and the web app's package lock by path and content (`trailhand/target/native-inputs.sha256`), so a changed +dependency version or a deleted file rebuilds it. + +=== Against a Running Stack + +To look at the stack in a browser or to repeat the tests without restarting it, run the scripts by hand. `-pl +integration-tests` without `-am` takes `trailhand` from the local repository, so install it once +(`./mvnw install -DskipTests -pl trailhand -am`). + +From the repository root: + +[source,bash] +---- +S=integration-tests/scripts +$S/generate-certificates.sh && $S/seed-remotes.sh && $S/build-native-if-needed.sh && $S/start-integration-stack.sh +./mvnw test-compile failsafe:integration-test failsafe:verify -Pintegration-tests -pl integration-tests +$S/stop-integration-stack.sh --clean # logs to target/compose.log; without --clean the data volume stays +---- + +While it runs, the application is at https://localhost:10443 (the certificate is self-signed) and signs in with a user +of the realm below. + +== The Stack + +[cols="1,1,3"] +|=== +|Service |Host ports |Notes + +|`keycloak` +|1443 (HTTPS), 1090 (management) +|Keycloak 26.8.1, pinned by digest; realm `trailhand` imported from `src/main/docker/keycloak/trailhand-realm.json`; +admin `admin`/`admin` + +|`trailhand` +|10443 (HTTPS), 19000 (management) +|The image `trailhand:it`, read-only root file system, all capabilities dropped, `no-new-privileges`; configuration +`src/main/docker/trailhand-config/`, client secret `src/main/docker/secrets/`, data in the volume `trailhand-data` +|=== + +Every port is published on `127.0.0.1` only. The browser reaches Keycloak as `https://localhost:1443`, the application as `https://keycloak:8443` on the compose +network. Keycloak mints every issuer and redirect address from the browser-facing name (`KC_HOSTNAME`); the +application reaches it through `SHERIFF_CLIENT_BACK_CHANNEL_ORIGIN` and `TRAILHAND_OIDC_JWKS_URL`. + +The scripts generate into `target/` (never committed): `certificates/`, one self-signed PEM pair for `localhost`, +`keycloak` and `trailhand` plus the PKCS#12 trust store with which the application trusts Keycloak, and `remotes/`, the +bare repositories `samm-assessments.git` and `directory.git`. + +=== Realm + +[cols="1,1,2"] +|=== +|User |Group |Rights in `trailhand.yaml` + +|`alex-assessor` |`assessors` |`samm-assessments`: read, edit +|`ana-approver` |`approvers` |`samm-assessments`: read, approve +|`cara-catalog` |`catalog-admins` |`directory`: read, administer catalogs +|`rudi-reader` |`readers` |`samm-assessments`: read +|`otto-outsider` |`auditors` |none: the group has no mapping (deny by default) +|=== + +Each password is `-password`. The confidential client `trailhand-web` (secret `trailhand-it-client-secret`) +admits only `https://localhost:10443/api/v1/auth/callback`; the client `trailhand-mcp-agent` is registered for the MCP +server and not used yet. All of it is test data of this stack only. + +== Tests + +[cols="1,3"] +|=== +|Class |What it checks + +|`HealthIT` +|Liveness and readiness are `UP` once the repositories are cloned; the `git-remote` group and the metrics are on the +management port, not on 8443; the status answers without login and is not degraded + +|`WebAppServingIT` +|Every canonical address answers the start page with the page security headers; the files of the web app come from +the application; the catalogue answers both languages + +|`WebLoginIT` +|The login through Keycloak sets `HttpOnly` `Secure` cookies, ends at the return address and gives no token to the +browser; the session carries the rights mapped from the groups; a group without mapping grants nothing; a callback +without the login transaction opens no session + +|`ReturnAddressIT` +|Only a canonical address is returned to; anything else becomes `/` + +|`CsrfIT` +|Without a session `401` with the login address; a state-changing request without the anti-CSRF header, with a wrong +one or from a foreign origin is refused + +|`LogoutIT` +|The logout ends the session, revokes the tokens and leads to Keycloak's end-session address +|=== + +`Stack` holds the addresses (system properties `trailhand.it.base`, `trailhand.it.management`, `trailhand.it.keycloak`) +and the browser-like login: no automatic redirects, cookies per site, the Keycloak form filled in. diff --git a/integration-tests/pom.xml b/integration-tests/pom.xml new file mode 100644 index 0000000..f5924fa --- /dev/null +++ b/integration-tests/pom.xml @@ -0,0 +1,129 @@ + + + 4.0.0 + + de.cuioss + trailhand-parent + 0.1.0-SNAPSHOT + ../pom.xml + + trailhand-integration-tests + jar + TrailHand Integration Tests + The integration lane (doc/specification/testing.adoc): the native image in its distroless container with + Keycloak, driven over HTTPS by failsafe *IT classes. Runs with the profile integration-tests. + + + + de.cuioss.trailhand.integration + true + true + true + true + + + + + + de.cuioss + trailhand + ${project.version} + provided + + + io.rest-assured + rest-assured + test + + + org.junit.jupiter + junit-jupiter + test + + + + + + integration-tests + + false + + + + + org.codehaus.mojo + exec-maven-plugin + + + prepare-stack + pre-integration-test + + exec + + + bash + + -c + scripts/stop-integration-stack.sh --clean; scripts/generate-certificates.sh && scripts/seed-remotes.sh && scripts/build-native-if-needed.sh && scripts/start-integration-stack.sh + + ${project.basedir} + + + + + stop-stack + post-integration-test + + exec + + + ${project.basedir}/scripts/stop-integration-stack.sh + + --clean + + ${project.basedir} + + + + invalid-config + post-integration-test + + exec + + + ${project.basedir}/scripts/verify-invalid-config-fails.sh + ${project.basedir} + + + + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + **/*IT.java + + + https://localhost:10443 + http://localhost:19000 + https://localhost:1443 + + + + + + integration-test + verify + + + + + + + + + diff --git a/integration-tests/scripts/build-native-if-needed.sh b/integration-tests/scripts/build-native-if-needed.sh new file mode 100755 index 0000000..d4a1945 --- /dev/null +++ b/integration-tests/scripts/build-native-if-needed.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# +# 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. +# +# Builds the native runner of the trailhand module unless the one in target/ was built from the same inputs, then the +# image trailhand:it. The native build runs in a container (Mandrel, profile native). The inputs are fingerprinted by +# path and content: the build files of the reactor (dependency versions included), the sources and resources of +# trailhand and web-app, and the web app's package lock. An added, changed or deleted file rebuilds. +set -euo pipefail +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +APP_DIR="$REPO_ROOT/trailhand" +STAMP="$APP_DIR/target/native-inputs.sha256" +fingerprint() { + (cd "$REPO_ROOT" && find pom.xml .mvn trailhand/pom.xml trailhand/src/main web-app/pom.xml web-app/package.json \ + web-app/package-lock.json web-app/vite.config.ts web-app/tsconfig.json web-app/src web-app/static \ + -type f -not -path '*/node_modules/*' -print0 2>/dev/null \ + | LC_ALL=C sort -z | xargs -0 shasum -a 256 | shasum -a 256 | cut -d' ' -f1) +} +RUNNER="$(ls "$APP_DIR"/target/*-runner 2>/dev/null | head -n1 || true)" +INPUTS="$(fingerprint)" +if [ -z "$RUNNER" ] || [ ! -f "$STAMP" ] || [ "$(cat "$STAMP")" != "$INPUTS" ]; then + echo "building the native runner" + (cd "$REPO_ROOT" && ./mvnw -q package -Pnative -pl trailhand -am) + echo "$INPUTS" > "$STAMP" +else + echo "native runner is current: $RUNNER" +fi +docker build -q -f "$APP_DIR/src/main/docker/Dockerfile.native" \ + --build-arg APP_VERSION=it --build-arg APP_REVISION="$(git -C "$REPO_ROOT" rev-parse --short HEAD)" \ + -t trailhand:it "$APP_DIR" >/dev/null +echo "image trailhand:it built" diff --git a/integration-tests/scripts/generate-certificates.sh b/integration-tests/scripts/generate-certificates.sh new file mode 100755 index 0000000..1205f4e --- /dev/null +++ b/integration-tests/scripts/generate-certificates.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# +# 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. +# +# Generates the TLS material of the stack into target/certificates (never committed): one self-signed key pair +# (PEM) for Keycloak and TrailHand with the names they are reached under, and a PKCS#12 trust store holding the +# certificate, with which TrailHand trusts Keycloak. +set -euo pipefail +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +CERT_DIR="$TARGET_DIR/certificates" +# A complete set is reused; a missing file regenerates all of them, so key, certificate and trust store match. +if [ -f "$CERT_DIR/tls.key" ] && [ -f "$CERT_DIR/tls.crt" ] && [ -f "$CERT_DIR/truststore.p12" ]; then + echo "certificates present in $CERT_DIR" + exit 0 +fi +mkdir -p "$CERT_DIR" +openssl req -x509 -newkey rsa:2048 -nodes -days 30 -sha256 \ + -subj "/CN=localhost" \ + -addext "subjectAltName=DNS:localhost,DNS:keycloak,DNS:trailhand,IP:127.0.0.1" \ + -keyout "$CERT_DIR/tls.key" -out "$CERT_DIR/tls.crt" 2>/dev/null +# Read by the containers' non-root users; the material is test-only and lives in target/. +chmod 644 "$CERT_DIR/tls.key" "$CERT_DIR/tls.crt" +rm -f "$CERT_DIR/truststore.p12" +keytool -importcert -noprompt -alias trailhand-it -file "$CERT_DIR/tls.crt" \ + -keystore "$CERT_DIR/truststore.p12" -storetype PKCS12 -storepass trailhand-it >/dev/null +chmod 644 "$CERT_DIR/truststore.p12" +echo "certificates written to $CERT_DIR" diff --git a/integration-tests/scripts/lib.sh b/integration-tests/scripts/lib.sh new file mode 100755 index 0000000..e536b45 --- /dev/null +++ b/integration-tests/scripts/lib.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# +# 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. +# +# Shared settings of the integration scripts; sourced, not run. + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +MODULE_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" +REPO_ROOT="$(cd "$MODULE_DIR/.." && pwd)" +TARGET_DIR="$MODULE_DIR/target" +COMPOSE_FILE="$MODULE_DIR/src/main/docker/docker-compose.yml" +export TRAILHAND_IT_TARGET="$TARGET_DIR" + +# docker compose v2, or the legacy docker-compose. +compose() { + if docker compose version >/dev/null 2>&1; then + docker compose -f "$COMPOSE_FILE" -p trailhand-it "$@" + else + docker-compose -f "$COMPOSE_FILE" -p trailhand-it "$@" + fi +} diff --git a/integration-tests/scripts/seed-remotes.sh b/integration-tests/scripts/seed-remotes.sh new file mode 100755 index 0000000..f4f20b1 --- /dev/null +++ b/integration-tests/scripts/seed-remotes.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# +# 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. +# +# Creates the bare repositories the stack uses as file: remotes (TRH-CONF-2, a single-server setup) in +# target/remotes, each with one initial commit on main. The aliases are the file:/srv/remotes/.git remotes of the +# stack's trailhand.yaml. A repository is built in a temporary directory and moved into place only once its main +# branch is pushed, so a run that stops halfway leaves nothing that a later run would take as complete. +set -euo pipefail +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +REMOTES="$TARGET_DIR/remotes" +CONFIG="$MODULE_DIR/src/main/docker/trailhand-config/trailhand.yaml" +ALIASES="$(sed -n 's#^[[:space:]]*remote:[[:space:]]*file:/srv/remotes/\([a-z0-9-]*\)\.git[[:space:]]*$#\1#p' "$CONFIG")" +[ -n "$ALIASES" ] || { echo "no file:/srv/remotes/ remote in $CONFIG" >&2; exit 1; } +mkdir -p "$REMOTES" +for alias in $ALIASES; do + bare="$REMOTES/$alias.git" + if git --git-dir="$bare" rev-parse -q --verify refs/heads/main >/dev/null 2>&1; then + continue + fi + rm -rf "$bare" "$bare.partial" + git init -q --bare -b main "$bare.partial" + work="$(mktemp -d)" + git -C "$work" init -q -b main + printf 'Repository %s of the TrailHand integration tests.\n' "$alias" > "$work/README.adoc" + git -C "$work" add README.adoc + git -C "$work" -c user.name=trailhand-it -c user.email=it@trailhand.invalid commit -q -m "Initial commit" + git -C "$work" push -q "$bare.partial" main + rm -rf "$work" + mv "$bare.partial" "$bare" +done +chmod -R a+rX "$REMOTES" +echo "remotes in $REMOTES" diff --git a/integration-tests/scripts/start-integration-stack.sh b/integration-tests/scripts/start-integration-stack.sh new file mode 100755 index 0000000..f770a2a --- /dev/null +++ b/integration-tests/scripts/start-integration-stack.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# +# 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. +# +# Starts Keycloak and TrailHand (docker-compose.yml) and waits until Keycloak is ready and the TrailHand container +# is ready on its management port and reported healthy by the image's binary health check. A start that fails stops +# the stack again (logs in target/compose.log); a successful one leaves it running for the tests. +set -euo pipefail +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +# Every request is bounded: an endpoint that accepts the connection and never answers cannot stall a loop. +probe() { curl -sf --max-time 5 "$@" >/dev/null 2>&1; } + +started=false +cleanup() { + if [ "$started" != true ]; then + echo "the stack did not start; stopping it" >&2 + "$SCRIPT_DIR/stop-integration-stack.sh" --clean >&2 || true + fi +} +trap cleanup EXIT + +compose up -d keycloak +for _ in $(seq 1 120); do + if probe -k https://localhost:1090/health/ready; then break; fi + sleep 1 +done +probe -k https://localhost:1090/health/ready || { echo "Keycloak did not become ready" >&2; exit 1; } +echo "Keycloak is ready" + +compose up -d trailhand +container="$(compose ps -q trailhand)" +for _ in $(seq 1 120); do + health="$(docker inspect --format '{{.State.Health.Status}}' "$container" 2>/dev/null || true)" + if [ "$health" = healthy ] && probe http://localhost:19000/q/health/ready; then + started=true + echo "TrailHand is ready and healthy" + exit 0 + fi + sleep 1 +done +echo "TrailHand did not become ready and healthy (health: ${health:-unknown}):" >&2 +curl -s --max-time 5 http://localhost:19000/q/health/ready >&2 || true +exit 1 diff --git a/integration-tests/scripts/stop-integration-stack.sh b/integration-tests/scripts/stop-integration-stack.sh new file mode 100755 index 0000000..bfe9e00 --- /dev/null +++ b/integration-tests/scripts/stop-integration-stack.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# +# 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. +# +# Writes the container logs to target/ and stops the stack; --clean also removes the volumes. +set -euo pipefail +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +mkdir -p "$TARGET_DIR" +compose logs --no-color > "$TARGET_DIR/compose.log" 2>&1 || true +if [ "${1:-}" = "--clean" ]; then + compose down --remove-orphans --volumes +else + compose down --remove-orphans +fi diff --git a/integration-tests/scripts/verify-invalid-config-fails.sh b/integration-tests/scripts/verify-invalid-config-fails.sh new file mode 100755 index 0000000..e0fefa1 --- /dev/null +++ b/integration-tests/scripts/verify-invalid-config-fails.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +# +# 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. +# +# TRH-NFR-5, second half: the native image must refuse to boot with an invalid configuration, and +# --validate-config must report it with exit code 1. +set -euo pipefail +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +INVALID="$MODULE_DIR/src/main/docker/trailhand-config-invalid" +set +e +docker run --rm -v "$INVALID:/cfg:ro" trailhand:it --validate-config /cfg > "$TARGET_DIR/invalid-config-validate.log" 2>&1 +validate=$? +container="$(docker run -d -v "$INVALID:/app/config:ro" trailhand:it)" +status="" +for _ in $(seq 1 30); do + status="$(docker inspect --format '{{.State.Status}} {{.State.ExitCode}}' "$container")" + case "$status" in exited*) break ;; esac + sleep 1 +done +docker logs "$container" > "$TARGET_DIR/invalid-config-boot.log" 2>&1 +docker rm -f "$container" >/dev/null +set -e +if [ "$validate" -ne 1 ]; then + echo "--validate-config answered $validate for an invalid configuration, expected 1" >&2 + exit 1 +fi +case "$status" in + "exited 0" | running* | "") echo "the boot with an invalid configuration did not fail: $status" >&2; exit 1 ;; +esac +# One record per violation: the boot must log exactly the violations --validate-config reports for the fixture, as a +# multiset of "key: rule" records, so an added violation of the fixture is expected without a list here. +records() { grep -o 'TRAILHAND-200: Invalid configuration at .*' "$1" | LC_ALL=C sort; } +expected="$(records "$TARGET_DIR/invalid-config-validate.log")" +actual="$(records "$TARGET_DIR/invalid-config-boot.log")" +[ -n "$expected" ] || { echo "--validate-config reported no TRAILHAND-200 record" >&2; exit 1; } +if [ "$expected" != "$actual" ]; then + echo "the boot logged other violations than --validate-config reports:" >&2 + diff <(echo "$expected") <(echo "$actual") >&2 || true + exit 1 +fi +# The fixture covers every rule group of the bootstrap; each of these keys must be among the records. +for key in 'repositories[0].alias' 'repositories[0].remote' 'repositories[0].confidentiality' \ + 'repositories[0].retention' 'rights.assessors[0].repository' 'rights.assessors[0].actions' 'oidc.issuer' \ + 'oidc.client-credential-ref' 'web.origin'; do + grep -qF "Invalid configuration at $key: " <<< "$expected" \ + || { echo "the fixture no longer produces a violation of $key" >&2; exit 1; } +done +echo "an invalid configuration stops the boot ($status) and fails --validate-config" diff --git a/integration-tests/src/main/docker/docker-compose.yml b/integration-tests/src/main/docker/docker-compose.yml new file mode 100644 index 0000000..f0d07b6 --- /dev/null +++ b/integration-tests/src/main/docker/docker-compose.yml @@ -0,0 +1,74 @@ +# The integration stack (doc/specification/testing.adoc, Integration lane): the native TrailHand image with +# Keycloak. Gitea joins with the Git round trip (TRH-NFR-5); until then the repositories are local bare +# repositories mounted as file: remotes (TRH-CONF-2). Certificates and remotes are generated into target/ by the +# scripts of the module (TRAILHAND_IT_TARGET). +name: trailhand-it + +services: + keycloak: + image: quay.io/keycloak/keycloak:26.8.1@sha256:79c623a22abacf3fe6c00a5fb30f5b7843d717b234033b80995891c06116d244 + command: + - start-dev + - --import-realm + - --https-certificate-file=/opt/keycloak/certificates/tls.crt + - --https-certificate-key-file=/opt/keycloak/certificates/tls.key + - --https-port=8443 + environment: + KC_BOOTSTRAP_ADMIN_USERNAME: admin + KC_BOOTSTRAP_ADMIN_PASSWORD: admin + KC_HEALTH_ENABLED: "true" + KC_HTTP_ENABLED: "false" + # One identity, the browser-facing one: every issuer and redirect is minted from it. TrailHand reaches the + # same server as https://keycloak:8443 (SHERIFF_CLIENT_BACK_CHANNEL_ORIGIN below). + KC_HOSTNAME: https://localhost:1443 + # Published on loopback only: the stack is for this host, and Keycloak's admin account is admin/admin. + ports: + - "127.0.0.1:1443:8443" + - "127.0.0.1:1090:9000" + volumes: + - ./keycloak:/opt/keycloak/data/import:ro + - ${TRAILHAND_IT_TARGET:-../../../target}/certificates:/opt/keycloak/certificates:ro + healthcheck: + test: ["CMD-SHELL", "exec 3<>/dev/tcp/localhost/9000 && exec 3<&-"] + interval: 5s + timeout: 3s + retries: 30 + networks: [trailhand-it] + + trailhand: + image: trailhand:it + # The trust store makes Token Sheriff's calls to Keycloak trust its self-signed certificate. + command: + - -Djavax.net.ssl.trustStore=/run/secrets/tls/truststore.p12 + - -Djavax.net.ssl.trustStorePassword=trailhand-it + - -Djavax.net.ssl.trustStoreType=PKCS12 + environment: + SHERIFF_CLIENT_BACK_CHANNEL_ORIGIN: https://keycloak:8443 + SHERIFF_CLIENT_ALLOWED_EGRESS_HOSTS: keycloak + SHERIFF_TOKEN_ISSUERS_TRAILHAND_JWKS_HTTP_ALLOWED_EGRESS_HOSTS: keycloak + TRAILHAND_OIDC_JWKS_URL: https://keycloak:8443/realms/trailhand/protocol/openid-connect/certs + ports: + - "127.0.0.1:10443:8443" + - "127.0.0.1:19000:9000" + volumes: + - ./trailhand-config:/app/config:ro + - ./secrets:/app/secrets:ro + - ${TRAILHAND_IT_TARGET:-../../../target}/certificates:/run/secrets/tls:ro + - ${TRAILHAND_IT_TARGET:-../../../target}/remotes:/srv/remotes:ro + - trailhand-data:/app/data + depends_on: + keycloak: + condition: service_healthy + security_opt: ["no-new-privileges:true"] + cap_drop: [ALL] + read_only: true + tmpfs: + - /tmp:rw,noexec,nosuid,size=64m + # No healthcheck key: the image's HEALTHCHECK (the binary's --health-probe) applies. + networks: [trailhand-it] + +volumes: + trailhand-data: + +networks: + trailhand-it: diff --git a/integration-tests/src/main/docker/keycloak/trailhand-realm.json b/integration-tests/src/main/docker/keycloak/trailhand-realm.json new file mode 100644 index 0000000..b8e1a2e --- /dev/null +++ b/integration-tests/src/main/docker/keycloak/trailhand-realm.json @@ -0,0 +1,196 @@ +{ + "realm": "trailhand", + "enabled": true, + "sslRequired": "external", + "registrationAllowed": false, + "accessTokenLifespan": 300, + "ssoSessionIdleTimeout": 1800, + "ssoSessionMaxLifespan": 28800, + "groups": [ + { + "name": "assessors", + "path": "/assessors" + }, + { + "name": "approvers", + "path": "/approvers" + }, + { + "name": "catalog-admins", + "path": "/catalog-admins" + }, + { + "name": "readers", + "path": "/readers" + }, + { + "name": "auditors", + "path": "/auditors" + } + ], + "users": [ + { + "username": "alex-assessor", + "enabled": true, + "emailVerified": true, + "firstName": "Alex", + "lastName": "Assessor", + "email": "alex-assessor@trailhand.invalid", + "credentials": [ + { + "type": "password", + "value": "alex-assessor-password", + "temporary": false + } + ], + "groups": [ + "/assessors" + ], + "requiredActions": [] + }, + { + "username": "ana-approver", + "enabled": true, + "emailVerified": true, + "firstName": "Ana", + "lastName": "Approver", + "email": "ana-approver@trailhand.invalid", + "credentials": [ + { + "type": "password", + "value": "ana-approver-password", + "temporary": false + } + ], + "groups": [ + "/approvers" + ], + "requiredActions": [] + }, + { + "username": "cara-catalog", + "enabled": true, + "emailVerified": true, + "firstName": "Cara", + "lastName": "Catalog", + "email": "cara-catalog@trailhand.invalid", + "credentials": [ + { + "type": "password", + "value": "cara-catalog-password", + "temporary": false + } + ], + "groups": [ + "/catalog-admins" + ], + "requiredActions": [] + }, + { + "username": "rudi-reader", + "enabled": true, + "emailVerified": true, + "firstName": "Rudi", + "lastName": "Reader", + "email": "rudi-reader@trailhand.invalid", + "credentials": [ + { + "type": "password", + "value": "rudi-reader-password", + "temporary": false + } + ], + "groups": [ + "/readers" + ], + "requiredActions": [] + }, + { + "username": "otto-outsider", + "enabled": true, + "emailVerified": true, + "firstName": "Otto", + "lastName": "Outsider", + "email": "otto-outsider@trailhand.invalid", + "credentials": [ + { + "type": "password", + "value": "otto-outsider-password", + "temporary": false + } + ], + "groups": [ + "/auditors" + ], + "requiredActions": [] + } + ], + "clients": [ + { + "clientId": "trailhand-web", + "name": "TrailHand web login", + "enabled": true, + "publicClient": false, + "clientAuthenticatorType": "client-secret", + "secret": "trailhand-it-client-secret", + "standardFlowEnabled": true, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, + "serviceAccountsEnabled": false, + "redirectUris": [ + "https://localhost:10443/api/v1/auth/callback" + ], + "webOrigins": [ + "https://localhost:10443" + ], + "attributes": { + "pkce.code.challenge.method": "S256", + "post.logout.redirect.uris": "https://localhost:10443/" + }, + "protocolMappers": [ + { + "name": "groups", + "protocol": "openid-connect", + "protocolMapper": "oidc-group-membership-mapper", + "consentRequired": false, + "config": { + "full.path": "false", + "id.token.claim": "true", + "access.token.claim": "true", + "userinfo.token.claim": "true", + "claim.name": "groups" + } + } + ] + }, + { + "clientId": "trailhand-mcp-agent", + "name": "TrailHand MCP agent (registered for the MCP server, not used yet)", + "enabled": true, + "publicClient": true, + "standardFlowEnabled": true, + "directAccessGrantsEnabled": false, + "redirectUris": [ + "http://127.0.0.1/*" + ], + "attributes": { + "pkce.code.challenge.method": "S256" + }, + "protocolMappers": [ + { + "name": "groups", + "protocol": "openid-connect", + "protocolMapper": "oidc-group-membership-mapper", + "consentRequired": false, + "config": { + "full.path": "false", + "id.token.claim": "true", + "access.token.claim": "true", + "userinfo.token.claim": "true", + "claim.name": "groups" + } + } + ] + } + ] +} \ No newline at end of file diff --git a/integration-tests/src/main/docker/secrets/README b/integration-tests/src/main/docker/secrets/README new file mode 100644 index 0000000..006219b --- /dev/null +++ b/integration-tests/src/main/docker/secrets/README @@ -0,0 +1,2 @@ +The client secret of the Keycloak client trailhand-web of the integration realm (keycloak/trailhand-realm.json). +A test value of the integration stack only; it grants nothing outside it. diff --git a/integration-tests/src/main/docker/secrets/client-secret b/integration-tests/src/main/docker/secrets/client-secret new file mode 100644 index 0000000..9f2ab6c --- /dev/null +++ b/integration-tests/src/main/docker/secrets/client-secret @@ -0,0 +1 @@ +trailhand-it-client-secret diff --git a/integration-tests/src/main/docker/trailhand-config-invalid/trailhand.yaml b/integration-tests/src/main/docker/trailhand-config-invalid/trailhand.yaml new file mode 100644 index 0000000..084db3d --- /dev/null +++ b/integration-tests/src/main/docker/trailhand-config-invalid/trailhand.yaml @@ -0,0 +1,16 @@ +# An invalid trailhand.yaml: the boot must stop with one TRAILHAND-200 record per violation (TRH-CONF-1, TRH-NFR-5). +repositories: + - alias: Not_An_Alias + remote: ssh://git@example.org/x.git + confidentiality: secret + retention: forever +rights: + assessors: + - repository: nowhere + actions: [delete] +oidc: + issuer: http://insecure.example.org + client-id: trailhand-web + client-credential-ref: hunter2 +web: + origin: https://trailhand.example.org/path diff --git a/integration-tests/src/main/docker/trailhand-config/trailhand.yaml b/integration-tests/src/main/docker/trailhand-config/trailhand.yaml new file mode 100644 index 0000000..96a956c --- /dev/null +++ b/integration-tests/src/main/docker/trailhand-config/trailhand.yaml @@ -0,0 +1,31 @@ +# trailhand.yaml of the integration stack. +repositories: + - alias: samm-assessments + remote: file:/srv/remotes/samm-assessments.git + confidentiality: restricted + retention: unlimited + - alias: directory + remote: file:/srv/remotes/directory.git + confidentiality: strongly-restricted + retention: unlimited +rights: + assessors: + - repository: samm-assessments + actions: [read, edit] + approvers: + - repository: samm-assessments + actions: [read, approve] + catalog-admins: + - repository: directory + actions: [read, administer-catalogs] + readers: + - repository: samm-assessments + actions: [read] +oidc: + issuer: ${TRAILHAND_OIDC_ISSUER:-https://localhost:1443/realms/trailhand} + client-id: trailhand-web + client-credential-ref: file:/app/secrets/client-secret +web: + origin: https://localhost:10443 +fetch: + interval: PT1M diff --git a/integration-tests/src/test/java/de/cuioss/trailhand/integration/CsrfIT.java b/integration-tests/src/test/java/de/cuioss/trailhand/integration/CsrfIT.java new file mode 100644 index 0000000..1e76bf8 --- /dev/null +++ b/integration-tests/src/test/java/de/cuioss/trailhand/integration/CsrfIT.java @@ -0,0 +1,66 @@ +/* + * 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.integration; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@DisplayName("Anti-CSRF header and Origin check (TRH-WEB-8)") +class CsrfIT { + + private static Stack.Login login; + + @BeforeAll + static void signIn() { + login = Stack.login("alex-assessor", "/"); + } + + @Test + @DisplayName("a request without session is refused with 401 and the login address") + void unauthenticated() { + var answer = Stack.request().get(Stack.BASE + "/api/v1/session"); + assertEquals(401, answer.statusCode()); + assertEquals("/api/v1/auth/login", answer.jsonPath().getString("login")); + } + + @Test + @DisplayName("a state-changing request without the anti-CSRF header is refused") + void missingToken() { + var answer = Stack.request().cookie(Stack.SESSION_COOKIE, login.sessionId()).post(Stack.BASE + "/api/v1/auth/logout"); + assertEquals(403, answer.statusCode()); + assertEquals("CSRF_REJECTED", answer.jsonPath().getString("outcome")); + } + + @Test + @DisplayName("a state-changing request from a foreign origin is refused even with the token") + void foreignOrigin() { + var answer = Stack.request().cookie(Stack.SESSION_COOKIE, login.sessionId()) + .header("X-CSRF-Token", login.csrfToken()).header("Origin", "https://evil.example") + .post(Stack.BASE + "/api/v1/auth/logout"); + assertEquals(403, answer.statusCode()); + } + + @Test + @DisplayName("a wrong token is refused") + void wrongToken() { + var answer = Stack.request().cookie(Stack.SESSION_COOKIE, login.sessionId()).header("X-CSRF-Token", "wrong") + .post(Stack.BASE + "/api/v1/auth/logout"); + assertEquals(403, answer.statusCode()); + } +} diff --git a/integration-tests/src/test/java/de/cuioss/trailhand/integration/HealthIT.java b/integration-tests/src/test/java/de/cuioss/trailhand/integration/HealthIT.java new file mode 100644 index 0000000..19a30e8 --- /dev/null +++ b/integration-tests/src/test/java/de/cuioss/trailhand/integration/HealthIT.java @@ -0,0 +1,57 @@ +/* + * 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.integration; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@DisplayName("Management interface of the native image (TRH-OPS-2, TRH-GEN-5, TRH-GEN-6)") +class HealthIT { + + @Test + @DisplayName("liveness and readiness are UP once the repositories are cloned") + void ready() { + assertEquals(200, Stack.request().get(Stack.MANAGEMENT + "/q/health/live").statusCode()); + var ready = Stack.request().get(Stack.MANAGEMENT + "/q/health/ready"); + assertEquals(200, ready.statusCode(), ready.asString()); + assertEquals("UP", ready.jsonPath().getString("checks.find { it.name == 'repositories' }.status")); + assertEquals("UP", ready.jsonPath().getString("checks.find { it.name == 'repositories' }.data.directory")); + } + + @Test + @DisplayName("the fetch state is UP and the metrics are on the management port, not on 8443") + void gitRemoteAndMetrics() { + assertEquals("UP", Stack.request().get(Stack.MANAGEMENT + "/q/health/group/git-remote").jsonPath() + .getString("status")); + var metrics = Stack.request().get(Stack.MANAGEMENT + "/q/metrics"); + assertEquals(200, metrics.statusCode()); + assertTrue(metrics.asString().contains("jvm_") || metrics.asString().contains("process_")); + assertTrue(Stack.request().get(Stack.BASE + "/q/metrics").statusCode() >= 300); + } + + @Test + @DisplayName("the status answers without login and is not degraded") + void status() { + var status = Stack.request().get(Stack.BASE + "/api/v1/status"); + assertEquals(200, status.statusCode()); + assertFalse(status.jsonPath().getBoolean("degraded")); + assertEquals(2, status.jsonPath().getList("repositories").size()); + } +} diff --git a/integration-tests/src/test/java/de/cuioss/trailhand/integration/LogoutIT.java b/integration-tests/src/test/java/de/cuioss/trailhand/integration/LogoutIT.java new file mode 100644 index 0000000..14ad29d --- /dev/null +++ b/integration-tests/src/test/java/de/cuioss/trailhand/integration/LogoutIT.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.integration; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@DisplayName("RP-initiated logout (TRH-AUTH-1)") +class LogoutIT { + + @Test + @DisplayName("logout ends the session, revokes the tokens and leads to Keycloak's end-session address") + void logout() { + var login = Stack.login("ana-approver", "/"); + + var answer = Stack.request().cookie(Stack.SESSION_COOKIE, login.sessionId()) + .header("X-CSRF-Token", login.csrfToken()).header("Origin", Stack.BASE) + .post(Stack.BASE + "/api/v1/auth/logout"); + + assertEquals(200, answer.statusCode(), answer.asString()); + var redirect = answer.jsonPath().getString("redirect"); + assertTrue(redirect.startsWith(Stack.KEYCLOAK + "/realms/trailhand/protocol/openid-connect/logout?"), + redirect); + assertTrue(redirect.contains("id_token_hint="), redirect); + assertTrue(redirect.contains("post_logout_redirect_uri=" + URLEncoder.encode(Stack.BASE + "/", + StandardCharsets.UTF_8)), redirect); + assertEquals(401, Stack.request().cookie(Stack.SESSION_COOKIE, login.sessionId()) + .get(Stack.BASE + "/api/v1/session").statusCode()); + + var endSession = Stack.request().get(redirect); + assertEquals(302, endSession.statusCode(), endSession.asString()); + assertTrue(endSession.header("Location").startsWith(Stack.BASE + "/"), endSession.header("Location")); + } +} diff --git a/integration-tests/src/test/java/de/cuioss/trailhand/integration/ReturnAddressIT.java b/integration-tests/src/test/java/de/cuioss/trailhand/integration/ReturnAddressIT.java new file mode 100644 index 0000000..ad770ae --- /dev/null +++ b/integration-tests/src/test/java/de/cuioss/trailhand/integration/ReturnAddressIT.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.integration; + +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.assertTrue; + +@DisplayName("The return address of the login (TRH-AUTH-1)") +class ReturnAddressIT { + + @ParameterizedTest + @CsvSource({"/incidents/2026/inc-0007,/incidents/2026/inc-0007", "%2F%2Fevil.example%2Fx,/", + "https%3A%2F%2Fevil.example,/", "/not/a/view/at/all,/"}) + @DisplayName("only a canonical address is returned to; anything else becomes /") + void returnAddress(String requested, String expected) { + var login = Stack.login("alex-assessor", requested); + + assertTrue(login.callback().asString().contains("content=\"0;url=" + expected + "\""), + login.callback().asString()); + } +} diff --git a/integration-tests/src/test/java/de/cuioss/trailhand/integration/Stack.java b/integration-tests/src/test/java/de/cuioss/trailhand/integration/Stack.java new file mode 100644 index 0000000..c913202 --- /dev/null +++ b/integration-tests/src/test/java/de/cuioss/trailhand/integration/Stack.java @@ -0,0 +1,130 @@ +/* + * 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.integration; + +import io.restassured.RestAssured; +import io.restassured.config.RedirectConfig; +import io.restassured.config.RestAssuredConfig; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; + +import java.net.URI; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Pattern; + +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; + +/** + * The addresses of the integration stack and a browser-like login through Keycloak (TRH-AUTH-1): no automatic + * redirects, cookies kept per site, the provider's login form filled in. + */ +final class Stack { + + /** The application's own origin. */ + static final String BASE = System.getProperty("trailhand.it.base", "https://localhost:10443"); + + /** The management interface. */ + static final String MANAGEMENT = System.getProperty("trailhand.it.management", "http://localhost:19000"); + + /** Keycloak as the browser reaches it. */ + static final String KEYCLOAK = System.getProperty("trailhand.it.keycloak", "https://localhost:1443"); + + /** The session cookie. */ + static final String SESSION_COOKIE = "__Host-trailhand-session"; + + /** The login-transaction cookie. */ + static final String LOGIN_COOKIE = "__Host-trailhand-login"; + + private static final Pattern FORM_ACTION = Pattern.compile("]*id=\"kc-form-login\"[^>]*action=\"([^\"]+)\""); + + private Stack() { + } + + /** + * @return a request against the stack: self-signed certificates accepted, redirects not followed + */ + static RequestSpecification request() { + // The configuration first: config(...) replaces the whole configuration, the SSL settings included. + return RestAssured.given() + .config(RestAssuredConfig.config().redirect(RedirectConfig.redirectConfig().followRedirects(false))) + .relaxedHTTPSValidation().urlEncodingEnabled(false); + } + + /** + * The result of a login. + * + * @param sessionId the value of the session cookie + * @param csrfToken the anti-CSRF token of the session + * @param returnAddress the address the callback page navigates to + * @param callback the callback answer + */ + record Login(String sessionId, String csrfToken, String returnAddress, Response callback) { + } + + /** + * Logs a user in, from {@code GET /api/v1/auth/login} to the session. + * + * @param user the Keycloak user; its password is {@code -password} + * @param returnAddress the requested return address + * @return the session + */ + static Login login(String user, String returnAddress) { + var start = request().get(BASE + "/api/v1/auth/login?return=" + returnAddress); + assertEquals(302, start.statusCode(), start.asString()); + var transaction = start.getCookie(LOGIN_COOKIE); + assertNotNull(transaction, "login-transaction cookie"); + var authorization = start.header("Location"); + // Keycloak offers PAR: the parameters (PKCE, state, nonce, response_mode=query) went over the back channel, + // and the browser carries only client_id and request_uri. + assertTrue(authorization.contains("?client_id=trailhand-web&request_uri=urn"), authorization); + assertFalse(authorization.contains("code_challenge") || authorization.contains("state="), authorization); + + // With PAR, Keycloak answers the authorization request with a redirect to its login action; follow it within + // Keycloak, keeping its cookies, as a browser does. + Map keycloakCookies = new HashMap<>(); + var page = request().get(authorization); + for (int hop = 0; page.statusCode() == 302 && hop < 3; hop++) { + keycloakCookies.putAll(page.getCookies()); + var next = page.header("Location"); + assertTrue(next.startsWith(KEYCLOAK + "/"), next); + page = request().cookies(keycloakCookies).get(next); + } + assertEquals(200, page.statusCode()); + keycloakCookies.putAll(page.getCookies()); + var matcher = FORM_ACTION.matcher(page.asString()); + assertTrue(matcher.find(), "Keycloak login form"); + var action = matcher.group(1).replace("&", "&"); + + var answer = request().cookies(keycloakCookies).contentType("application/x-www-form-urlencoded") + .formParam("username", user).formParam("password", user + "-password").post(action); + assertEquals(302, answer.statusCode(), answer.asString()); + var callbackAddress = answer.header("Location"); + assertTrue(callbackAddress.startsWith(BASE + "/api/v1/auth/callback?"), callbackAddress); + + var callback = request().cookie(LOGIN_COOKIE, transaction).get(callbackAddress); + assertEquals(200, callback.statusCode(), callback.asString()); + var sessionId = callback.getCookie(SESSION_COOKIE); + assertNotNull(sessionId, "session cookie"); + var session = request().cookie(SESSION_COOKIE, sessionId).get(BASE + "/api/v1/session"); + assertEquals(200, session.statusCode()); + var target = URI.create(BASE).resolve(returnAddress).getPath(); + return new Login(sessionId, session.jsonPath().getString("csrfToken"), target, callback); + } +} diff --git a/integration-tests/src/test/java/de/cuioss/trailhand/integration/WebAppServingIT.java b/integration-tests/src/test/java/de/cuioss/trailhand/integration/WebAppServingIT.java new file mode 100644 index 0000000..245ebdd --- /dev/null +++ b/integration-tests/src/test/java/de/cuioss/trailhand/integration/WebAppServingIT.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.integration; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.charset.StandardCharsets; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@DisplayName("The web app served by the native image (TRH-WEB-1, TRH-WEB-3, TRH-WEB-8)") +class WebAppServingIT { + + @ParameterizedTest + @ValueSource(strings = {"/", "/samm/payments/2026-q4/sm", "/incidents/2026/inc-0007/release", "/no/such/view/x"}) + @DisplayName("every address answers the start page with the page security headers") + void appPage(String address) { + var page = Stack.request().accept("text/html").get(Stack.BASE + address); + + assertEquals(200, page.statusCode()); + assertTrue(page.asString().contains("/theme-init.js")); + var policy = page.header("Content-Security-Policy"); + assertTrue(policy.contains("script-src 'self' 'sha256-"), policy); + assertTrue(policy.contains("frame-ancestors 'none'"), policy); + assertFalse(policy.contains("unsafe-inline"), policy); + assertEquals("nosniff", page.header("X-Content-Type-Options")); + assertEquals("no-referrer", page.header("Referrer-Policy")); + } + + @ParameterizedTest + @CsvSource({"/theme-init.js,javascript,trailhand_theme", "/brand-mark.svg,image/svg+xml, value.startsWith(Stack.SESSION_COOKIE + "=")).findFirst() + .orElseThrow(); + assertTrue(session.contains("HttpOnly") && session.contains("Secure") && session.contains("SameSite=Strict") + && session.contains("Path=/"), session); + assertTrue(cookies.stream().anyMatch(value -> value.startsWith(Stack.LOGIN_COOKIE + "=;") + && value.contains("Max-Age=0")), cookies.toString()); + var page = callback.asString(); + assertTrue(page.contains("http-equiv=\"refresh\" content=\"0;url=/samm/payments\""), page); + assertFalse(page.contains(" value.startsWith(Stack.SESSION_COOKIE + "=") && !value.contains("Max-Age=0"))); + } +} diff --git a/pom.xml b/pom.xml index a6c7dfe..1480a19 100644 --- a/pom.xml +++ b/pom.xml @@ -50,6 +50,7 @@ web-mock trailhand web-e2e + integration-tests diff --git a/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryService.java b/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryService.java index 676c500..3579f5a 100644 --- a/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryService.java +++ b/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryService.java @@ -182,7 +182,8 @@ private void cloneOrOpen(StoreRepository repository, Path gitDir) { } private void fetch(StoreRepository repository, Path gitDir) { - var result = operations.fetch(new RepositoryOperations.FetchInput(gitDir, "origin", FETCH_SPECS, null)); + // prune false: a reference the remote no longer advertises stays in the local copy, as before. + var result = operations.fetch(new RepositoryOperations.FetchInput(gitDir, "origin", FETCH_SPECS, null, false)); boolean up = result.outcome() == GitOutcome.OK; if (!up) { LOGGER.warn(WARN.FETCH_FAILED, repository.alias(), result.outcome(), result.detail());