Author SHA1 Message Date
arnaud.dartois c347d70ec9 fix(install): lire les secrets des services optionnels (#319)
Heimdall Gitea / Detect CI scope (pull_request) Successful in 9s
Heimdall Gitea / Build and tests (pull_request) Successful in 21m42s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Skipped
Heimdall Gitea / Publish versioned installer release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Successful in 3s
2026-11-12 06:06:24 +01:00
arnaud.dartois 78ff15799e [Auth] Couvrir le cookie navigateur après 2FA (#330)
Heimdall Gitea / Detect CI scope (push) Successful in 9s
Heimdall Gitea / Build and tests (push) Successful in 26m6s
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 8s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 05:00:00 +01:00
arnaud.dartois aef04552a8 [Auth] Couvrir la première connexion après création par rôle (#329)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Failing after 21m23s
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Failing after 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 04:18:55 +01:00
8 changed files with 623 additions and 12 deletions

No files matched your search

+24 -7
View File
@@ -3,6 +3,16 @@ services:
coturn:
image: coturn/coturn:4.6
pull_policy: always
# Local Compose secrets are read-only bind mounts and preserve the
# installer's 0600 owner-only permissions. Read the mounted file as a
# short-lived root initializer, write a private config into tmpfs, then
# run turnserver as nobody. The upstream binary does not exec with a
# reduced capability set; no-new-privileges still prevents elevation.
user: "0:0"
security_opt:
- no-new-privileges:true
tmpfs:
- /run/coturn:rw,noexec,nosuid,nodev,size=1m,mode=0700
ports:
- "${COTURN_PORT:-3478}:3478/tcp"
- "${COTURN_PORT:-3478}:3478/udp"
@@ -10,13 +20,20 @@ services:
entrypoint: ["/bin/sh", "-c"]
command:
- >-
exec turnserver -n --use-auth-secret
--static-auth-secret="$$(cat /run/secrets/coturn_secret)"
--realm=${COTURN_REALM:-heimdall.local}
--fingerprint --no-tlsv1 --no-tlsv1_1 --log-file=stdout
--no-cli --listening-port=3478
--min-port=${COTURN_RELAY_PORT_MIN:-49160}
--max-port=${COTURN_RELAY_PORT_MAX:-49200}
set -eu;
umask 077;
printf 'use-auth-secret\nstatic-auth-secret=%s\nrealm=%s\nfingerprint\nno-tlsv1\nno-tlsv1_1\nlog-file=stdout\nno-cli\nlistening-port=3478\nmin-port=%s\nmax-port=%s\n'
"$$(cat /run/secrets/coturn_secret)" "${COTURN_REALM:-heimdall.local}"
"${COTURN_RELAY_PORT_MIN:-49160}" "${COTURN_RELAY_PORT_MAX:-49200}"
> /run/coturn/turnserver.conf;
printf 'pidfile=/run/coturn/turnserver.pid\n' >> /run/coturn/turnserver.conf;
if [ -n "$$COTURN_EXTERNAL_IP" ]; then
printf 'external-ip=%s\n' "$$COTURN_EXTERNAL_IP" >> /run/coturn/turnserver.conf;
fi;
chown 65534:65534 /run/coturn /run/coturn/turnserver.conf;
exec su -s /bin/sh -c 'exec /usr/bin/turnserver -c /run/coturn/turnserver.conf' nobody
environment:
COTURN_EXTERNAL_IP: ${COTURN_EXTERNAL_IP:-}
secrets:
- coturn_secret
restart: unless-stopped
+30 -2
View File
@@ -5,6 +5,34 @@ services:
image: rustfs/rustfs:latest
pull_policy: always
restart: unless-stopped
# Compose file secrets are read-only bind mounts locally. The installer
# deliberately creates them mode 0600, owned by root; RustFS runs as UID
# 10001 and cannot read that source directly. A small root init copies the
# files into tmpfs, then drops privileges before starting the server.
user: "0:0"
read_only: true
cap_drop:
- ALL
cap_add:
- CHOWN
- DAC_OVERRIDE
- SETGID
- SETUID
security_opt:
- no-new-privileges:true
tmpfs:
- /run/rustfs-secrets:rw,noexec,nosuid,nodev,size=1m,mode=0700
- /logs:rw,noexec,nosuid,nodev,size=16m,mode=1777
- /tmp:rw,noexec,nosuid,nodev,size=16m,mode=1777
entrypoint: ["/bin/sh", "-c"]
command:
- >-
set -eu;
umask 077;
cp /run/secrets/rustfs_access_key /run/rustfs-secrets/access_key;
cp /run/secrets/rustfs_secret_key /run/rustfs-secrets/secret_key;
chown 10001:10001 /run/rustfs-secrets /run/rustfs-secrets/access_key /run/rustfs-secrets/secret_key;
exec su -s /bin/sh -c 'exec /etc/rustfs/entrypoint.sh rustfs' rustfs
ports:
- "${RUSTFS_API_PORT:-9000}:9000"
- "${RUSTFS_CONSOLE_PORT:-9001}:9001"
@@ -13,8 +41,8 @@ services:
RUSTFS_ADDRESS: 0.0.0.0:9000
RUSTFS_CONSOLE_ADDRESS: 0.0.0.0:9001
RUSTFS_CONSOLE_ENABLE: "true"
RUSTFS_ACCESS_KEY_FILE: /run/secrets/rustfs_access_key
RUSTFS_SECRET_KEY_FILE: /run/secrets/rustfs_secret_key
RUSTFS_ACCESS_KEY_FILE: /run/rustfs-secrets/access_key
RUSTFS_SECRET_KEY_FILE: /run/rustfs-secrets/secret_key
secrets:
- rustfs_access_key
- rustfs_secret_key
+3
View File
@@ -16,6 +16,7 @@ Read `AGENTS.md`, the focused Gitea issue and [the Gitea ticket workflow](../git
- Rotate `SecurityStamp` after password changes/resets, email or role changes, lock/unlock, and 2FA changes. Verify existing cookies, JWTs, and refresh tokens are rejected after the change.
- Cookie principal validation runs on every authenticated HTTP request. Keep it asynchronous and use `AccountSessionPolicy.IsValidLiveAsync` with `IIdentityAccountService.GetSessionRecordAsync` plus an `IApplicationDbContext` projection; this bypasses Identity's tracked-user cache and avoids repeated `UserManager` database round trips while preserving fresh security-stamp, lockout, and email-confirmation checks. Do not replace it with claims-only validation.
- The Blazor cookie bridge runs through `heimdallAuth.signIn` → `POST /_auth/signin`. Have JavaScript return only the HTTP status code (or `0` for a network failure); classify `JSDisconnectedException` separately from non-2xx responses. Log only the failure stage, HTTP status, or exception type—never exception messages, emails, user IDs, access tokens, cookies, or request bodies. Return generic public errors from the endpoint. Integration coverage should verify a successful 2FA response can create a usable cookie and that malformed tokens reveal no validation details.
- For cookie failures reported after 2FA, inspect only sanitized event breadcrumbs around the JS bridge; distinguish a circuit/WebSocket disconnect from a `/_auth/signin` HTTP rejection, and do not infer cookie serialization failure when the event has no exception. Keep a Playwright E2E path that submits an authenticator code through `/login`, observes the real HttpOnly auth cookie, and proves that cookie authorizes `/api/users/me`; remove the temporary Identity account in `finally`.
- Enroll an authenticator in two steps: create/show the setup key while 2FA remains disabled; renew the user's access token and cookie after Identity rotates the security stamp; verify a TOTP code before enabling 2FA and creating one-time recovery codes. Persist only hashes of recovery codes, redeem each atomically once, and clear them when 2FA is disabled.
- Check every `IdentityResult` before proceeding. Avoid partial account creation; clean up the created user if role assignment fails.
- Keep first-account provisioning on `/setup` → `/api/auth/bootstrap-admin`; later accounts and role assignment use `/users` → `/api/users`. Do not reintroduce a second Admin-registration endpoint.
@@ -28,6 +29,8 @@ Read `AGENTS.md`, the focused Gitea issue and [the Gitea ticket workflow](../git
- For cookie session validation changes, prove a freshly issued cookie succeeds before account mutation and fails afterward for lockout, role/security-stamp, email, and password changes. Treat GlitchTip blocking warnings as hypotheses: inspect the full async stack and do not claim a synchronous block solely from the warning title.
- For behavior changes, update FR/EN resources and UI/API contracts, add focused tests, update the Gitea issue, and run the disposable Compose acceptance recipe with unique credentials, ports, volumes, project name, and network.
- Acceptance must exercise bootstrap through the setup UI, user lifecycle and role editing through `/users`, permission editing through `/admin/claims`, and verify the resulting JWT/API allow and deny decisions. Check that stale sessions fail after a role/permission change and that the last usable Admin cannot be demoted, deleted, or locked.
- For account-creation password regressions, cover the real `/users` dialog for Viewer and Supervisor with the role selected both before and after password entry. Confirm the new account's email through the admin row action, then authenticate through `/api/auth/login` using the exact synthetic password entered in the form; assert only the status/token presence and never log the password. Keep this as a Playwright E2E test under the `E2E` collection.
- The disposable Compose recipe defaults to the account-creation path; `HEIMDALL_ACCEPTANCE_FLOW=2fa-cookie` runs the complete authenticator challenge → `/_auth/signin` → cookie-authorized `/api/users/me` path. Each invocation uses a unique project, generated PostgreSQL/JWT credentials, a free loopback port, and a project-specific Central image tag. Build from the checkout and wait for `/healthz`; the separate Playwright E2E test covers the real browser UI bridge. Teardown only that Compose project and verify its containers, volumes, and network are gone; remove and verify absence of the exact Central tag while retaining PostgreSQL and other shared base images.
- Record a project-unique tag for each source-built Central acceptance image and install an EXIT cleanup trap before build/start. After scoped Compose teardown, verify zero containers/volumes/networks and remove/verify absence of each exact local tag even on failure. Keep shared upstream base images, preserve test exit status, report cleanup failures, and avoid `--rmi all` or broad image-prune commands.
Useful official references: [ASP.NET Core Identity configuration](https://learn.microsoft.com/aspnet/core/security/authentication/identity-configuration), [Two-factor authentication](https://learn.microsoft.com/aspnet/core/security/authentication/identity-enable-qrcodes), and [Data Protection](https://learn.microsoft.com/aspnet/core/security/data-protection/introduction).
+182
View File
@@ -0,0 +1,182 @@
#!/usr/bin/env bash
set -Eeuo pipefail
repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
suffix="$(date -u +%Y%m%d%H%M%S)-$(od -An -N5 -tx1 /dev/urandom | tr -d ' \\n')"
flow="${HEIMDALL_ACCEPTANCE_FLOW:-create-login}"
if [[ "$flow" != "create-login" && "$flow" != "2fa-cookie" ]]; then
echo 'HEIMDALL_ACCEPTANCE_FLOW must be create-login or 2fa-cookie' >&2
exit 2
fi
project="heimdall-auth-${flow}-${suffix}"
central_image="heimdall:${project}-central"
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
env_file="$temp_dir/acceptance.env"
override_file="$temp_dir/compose.override.yml"
compose_file="$repo_root/docker/docker-compose.yml"
local_image_tags=("$central_image")
compose_port=$(python3 - <<'PY'
import socket
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
print(sock.getsockname()[1])
PY
)
web_port=$(python3 - <<'PY'
import socket
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
print(sock.getsockname()[1])
PY
)
cleanup() {
status=$?
trap - EXIT
cleanup_failed=0
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$override_file" \
down --volumes --remove-orphans || cleanup_failed=1
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
if [[ -n "$containers" || -n "$volumes" || -n "$networks" ]]; then
printf 'Project resources remain: containers=%s volumes=%s networks=%s\n' \
"${containers:-<none>}" "${volumes:-<none>}" "${networks:-<none>}" >&2
cleanup_failed=1
else
printf 'Verified no project containers, volumes, or networks remain: %s\n' "$project"
fi
for tag in "${local_image_tags[@]}"; do
docker image rm "$tag" >/dev/null 2>&1 || true
if docker image inspect "$tag" >/dev/null 2>&1; then
printf 'Recipe image remains: %s\n' "$tag" >&2
cleanup_failed=1
else
printf 'Verified recipe image absent: %s\n' "$tag"
fi
done
rm -f -- "$env_file" "$override_file" || cleanup_failed=1
rmdir -- "$temp_dir" || cleanup_failed=1
if (( cleanup_failed )); then status=1; fi
exit "$status"
}
trap cleanup EXIT
pg_password=$(python3 - <<'PY'
import secrets, string
alphabet=string.ascii_letters+string.digits
print(''.join(secrets.choice(alphabet) for _ in range(40)))
PY
)
jwt_key=$(od -An -N48 -tx1 /dev/urandom | tr -d ' \\n')
refresh_key=$(od -An -N48 -tx1 /dev/urandom | tr -d ' \\n')
admin_password=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \\n')
admin_password="${admin_password}Aa1!"
cat >"$env_file" <<EOF
ACCEPTANCE_PROJECT=$project
POSTGRES_DB=heimdall_acceptance
POSTGRES_USER=heimdall_acceptance
POSTGRES_PASSWORD=$pg_password
POSTGRES_PORT=$compose_port
WEB_PORT=$web_port
DATABASE_URL="Host=postgresql;Port=5432;Database=heimdall_acceptance;Username=heimdall_acceptance;Password=$pg_password;Timeout=60;Command Timeout=300"
JWT__KEY=$jwt_key
JWT__REFRESHKEY=$refresh_key
JWT__ISSUER=heimdall-acceptance
JWT__AUDIENCE=heimdall-acceptance
ASPNETCORE_ENVIRONMENT=Production
HEIMDALL_NETWORK_NAME=${project}-net
EOF
cat >"$override_file" <<EOF
services:
heimdall:
image: $central_image
environment:
Database__MigrateOnStartup: "true"
EOF
printf 'Disposable project: %s\nCentral image: %s\n' "$project" "$central_image"
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$override_file" up -d --build
base_url="http://127.0.0.1:$web_port"
deadline=$((SECONDS + 300))
until curl -fsS "$base_url/healthz" >/dev/null 2>&1; do
if (( SECONDS >= deadline )); then echo 'Central health check timed out' >&2; exit 1; fi
sleep 2
done
printf 'Central /healthz: HTTP 200\n'
BASE_URL="$base_url" ACCEPTANCE_ADMIN_PASSWORD="$admin_password" ACCEPTANCE_FLOW="$flow" python3 - <<'PY'
import base64, hashlib, hmac, json, os, secrets, time, urllib.error, urllib.request
base=os.environ['BASE_URL']
flow=os.environ['ACCEPTANCE_FLOW']
def request(method, path, body=None, token=None, cookie=None):
headers={'Content-Type':'application/json'}
if token: headers['Authorization']='Bearer '+token
if cookie: headers['Cookie']=cookie
data=json.dumps(body).encode() if body is not None else None
req=urllib.request.Request(base+path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=20) as response:
return response.status, response.read(), response.headers
except urllib.error.HTTPError as error:
return error.code, error.read(), error.headers
def post(path, body, token=None):
status, payload, _=request('POST', path, body, token)
return status, payload
def totp(key):
secret=base64.b32decode(key.upper()+'='*((8-len(key)%8)%8))
counter=int(time.time())//30
digest=hmac.new(secret, counter.to_bytes(8,'big'), hashlib.sha1).digest()
offset=digest[-1]&15
value=int.from_bytes(digest[offset:offset+4], 'big')&0x7fffffff
return f'{value%1000000:06d}'
status, bootstrap_payload, _=request('POST','/api/auth/bootstrap-admin', {'email':'acceptance-admin@heimdall.test','password':os.environ['ACCEPTANCE_ADMIN_PASSWORD'],'displayName':'Disposable Acceptance Admin'})
if status != 200: raise SystemExit(f'Admin bootstrap failed: HTTP {status}')
if flow == 'create-login':
status, payload=post('/api/auth/login', {'email':'acceptance-admin@heimdall.test','password':os.environ['ACCEPTANCE_ADMIN_PASSWORD']})
if status != 200: raise SystemExit(f'Admin login failed: HTTP {status}')
admin=json.loads(payload)['accessToken']
for role in ('Viewer','Supervisor'):
email=f'{role.lower()}-{secrets.token_hex(8)}@heimdall.test'
password='CreateLogin!'+secrets.token_urlsafe(18)+'A1'
status, payload=post('/api/users', {'email':email,'password':password,'displayName':f'Acceptance {role}','roles':[role]}, admin)
if status not in (200,201): raise SystemExit(f'{role} create failed: HTTP {status}')
user_id=json.loads(payload)['id']
status,_=post(f'/api/users/{user_id}/confirm-email', {}, admin)
if status != 200: raise SystemExit(f'{role} email confirmation failed: HTTP {status}')
status,payload=post('/api/auth/login', {'email':email,'password':password})
if status != 200: raise SystemExit(f'{role} first login failed: HTTP {status}')
if not json.loads(payload).get('accessToken'): raise SystemExit(f'{role} login returned no access token')
print(f'{role}: create, admin email confirmation, and first login passed (HTTP 200)')
else:
admin=json.loads(bootstrap_payload)['accessToken']
email='acceptance-admin@heimdall.test'
password=os.environ['ACCEPTANCE_ADMIN_PASSWORD']
status,payload=post('/api/auth/2fa/enable', {'currentPassword':password}, admin)
if status != 200: raise SystemExit(f'2FA enrollment initialization failed: HTTP {status}')
shared_key=json.loads(payload)['sharedKey']
# ResetAuthenticatorKey rotates the security stamp; renew the setup session
# before the authenticated confirmation call.
status,payload=post('/api/auth/login', {'email':email,'password':password})
if status != 200: raise SystemExit(f'2FA setup session renewal failed: HTTP {status}')
admin=json.loads(payload)['accessToken']
status,_=post('/api/auth/2fa/enable/confirm', {'code':totp(shared_key)}, admin)
if status != 200: raise SystemExit(f'2FA enrollment confirmation failed: HTTP {status}')
status,payload=post('/api/auth/login', {'email':email,'password':password})
if status != 200: raise SystemExit(f'2FA password challenge failed: HTTP {status}')
challenge=json.loads(payload)
if not challenge.get('requires2fa') or not challenge.get('challengeId'):
raise SystemExit('2FA login did not return an authenticator challenge')
status,payload=post('/api/auth/2fa/verify', {'challengeId':challenge['challengeId'],'code':totp(shared_key)})
if status != 200: raise SystemExit(f'2FA verification failed: HTTP {status}')
access_token=json.loads(payload)['accessToken']
status,_,headers=request('POST','/_auth/signin', {'accessToken':access_token})
if status != 200: raise SystemExit(f'2FA cookie sign-in failed: HTTP {status}')
set_cookie=headers.get('Set-Cookie','').split(';',1)[0]
if not set_cookie.startswith('.Heimdall.Auth='):
raise SystemExit('2FA cookie sign-in returned no auth cookie')
status,_,_=request('GET','/api/users/me',cookie=set_cookie)
if status != 200: raise SystemExit(f'2FA auth cookie did not authorize current-user endpoint: HTTP {status}')
print('2FA authenticator challenge, cookie issuance, and cookie-authenticated /api/users/me passed (HTTP 200)')
PY
+5 -3
View File
@@ -10,18 +10,20 @@ The Linux and Windows server installers run optional Compose files with the inst
## RustFS
- Keep `rustfs_access_key` and `rustfs_secret_key` file paths aligned with the generated files from both installers.
- Installers create these bind-mounted secret files as owner-only (`0600`), which the official RustFS process (`10001:10001`) cannot read directly. Keep a short root initializer, copy the files into the service's private tmpfs, `chown` the copies to UID/GID 10001, then drop to the `rustfs` account before executing the upstream entrypoint. Keep the root filesystem read-only and provide tmpfs only for runtime paths that RustFS writes (`/logs`, `/tmp`, and its secret copies).
- Verify Compose config from the install-root working directory and ensure Docker secrets are sourced from those files.
- Keep the named data volume and shared `heimdall-net` behavior intact.
## coturn
- Keep `coturn_secret` sourced from `./optional/secrets/coturn_secret`.
- coturn 4.6 does not support `--static-auth-secret-file`; read the mounted Docker secret in a shell entrypoint and pass it to `--static-auth-secret`. Do not print the value.
- coturn 4.6 does not support `--static-auth-secret-file`; read the mounted Docker secret in a short root initializer and write its configuration into private tmpfs. Do not print the value or pass it in the server process arguments.
- Local Compose secrets are owner-only bind mounts too. Start the initializer as root, make the temporary config readable by the image's `nobody` account, then `exec` `turnserver` as `nobody` with `no-new-privileges` enabled. Keep the root init transient; do not run the TURN daemon as root.
- Use a shell entrypoint that executes `turnserver`, bridge networking, and explicit TCP/UDP listener and UDP relay port publications; the upstream image has a `turnadmin` entrypoint, and host networking cannot be combined with useful Compose port mappings.
- Keep the published relay range identical to coturn's `--min-port`/`--max-port` options. Make listener and relay settings configurable with documented defaults.
- Set `COTURN_EXTERNAL_IP` only when NAT requires coturn to advertise an explicit public address. The operator must forward the listener and relay range through firewalls/NAT.
- Keep `COTURN_EXTERNAL_IP` optional; when set in the installer root `.env`, add Coturn's `external-ip` directive so it advertises the public address across NAT. The operator must forward the listener and relay range through firewalls/NAT. Do not set a guessed public address.
- Do not claim public TURN reachability from a local container startup. It requires an external ICE/TURN client on a real network.
## Acceptance
Run both services in one uniquely named disposable Compose project using generated secrets and unique loopback listener ports. Use `docker compose --project-directory <install-root> --env-file <generated-env> -f <source-compose> -p <project> config` to prove the installer root resolves `optional/secrets/` correctly. Start RustFS and coturn; verify RustFS `/health` and S3 authentication and coturn startup plus a TURN REST authenticated allocation from a test client if available. State separately whether the real TURN allocation succeeded. Tear down only that project, verify its containers/volumes/networks are absent, and keep upstream images. No local images should be built by this recipe.
Run `skills/optional-server-services/acceptance.sh`. It creates a uniquely named disposable Compose project, generated owner-only secrets, an isolated install root, unique listener and relay ports, then validates Compose using that root. It verifies RustFS `/health`, signs a real S3 bucket-creation request with the generated keys, and runs `turnutils_uclient` inside the Compose network with TURN REST credentials. This proves local container-network allocation only; it does not prove external firewall/NAT reachability. The trap tears down only that project and verifies its containers, volumes, and networks are absent. The recipe builds no local images and retains upstream images.
+226
View File
@@ -0,0 +1,226 @@
#!/usr/bin/env bash
set -Eeuo pipefail
repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
suffix="$(date -u +%Y%m%d%H%M%S)-$(od -An -N5 -tx1 /dev/urandom | tr -d ' \\n')"
project="heimdall-optional-services-${suffix}"
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
install_root="$temp_dir/install-root"
secret_dir="$install_root/optional/secrets"
env_file="$temp_dir/acceptance.env"
override_file="$temp_dir/compose.override.yml"
turn_log="$temp_dir/turn-client.log"
rustfs_compose="$repo_root/docker/docker-compose.rustfs.yml"
coturn_compose="$repo_root/docker/docker-compose.coturn.yml"
local_image_tags=()
mkdir -p "$secret_dir"
compose() {
docker compose --project-directory "$install_root" --env-file "$env_file" \
-f "$rustfs_compose" -f "$coturn_compose" -f "$override_file" \
-p "$project" "$@"
}
cleanup() {
status=$?
trap - EXIT
cleanup_failed=0
compose down --volumes --remove-orphans || cleanup_failed=1
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
if [[ -n "$containers" ]]; then
# `compose run --rm` may leave a one-off test container behind if the
# client exits during shutdown; remove only containers carrying this
# recipe's unique Compose project label.
while IFS= read -r container; do
[[ -z "$container" ]] || docker rm -f "$container" >/dev/null || cleanup_failed=1
done <<< "$containers"
fi
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
if [[ -n "$containers" || -n "$volumes" || -n "$networks" ]]; then
printf 'Project resources remain: containers=%s volumes=%s networks=%s\n' \
"${containers:-<none>}" "${volumes:-<none>}" "${networks:-<none>}" >&2
cleanup_failed=1
else
printf 'Verified no project containers, volumes, or networks remain: %s\n' "$project"
fi
if ((${#local_image_tags[@]} == 0)); then
printf 'No local images built; upstream service images retained.\n'
fi
for tag in "${local_image_tags[@]}"; do
docker image rm "$tag" >/dev/null 2>&1 || true
if docker image inspect "$tag" >/dev/null 2>&1; then
printf 'Recipe image remains: %s\n' "$tag" >&2
cleanup_failed=1
else
printf 'Verified recipe image absent: %s\n' "$tag"
fi
done
rm -f -- "$env_file" "$override_file" "$turn_log" \
"$secret_dir/rustfs_access_key" "$secret_dir/rustfs_secret_key" \
"$secret_dir/coturn_secret" || cleanup_failed=1
rmdir -- "$secret_dir" "$install_root/optional" "$install_root" || cleanup_failed=1
rmdir -- "$temp_dir" || cleanup_failed=1
if ((cleanup_failed)); then
printf 'Disposable optional-service cleanup failed for %s\n' "$project" >&2
status=1
fi
exit "$status"
}
trap cleanup EXIT
read -r rustfs_api_port rustfs_console_port coturn_port relay_min relay_max < <(python3 - <<'PY'
import random, socket
used=set()
def free_port(protocols):
for port in random.sample(range(20000, 60000), 2000):
if port in used: continue
sockets=[]
try:
for kind in protocols:
sock=socket.socket(socket.AF_INET,kind)
sock.bind(('127.0.0.1',port))
sockets.append(sock)
used.add(port)
return port
except OSError:
pass
finally:
for sock in sockets: sock.close()
raise SystemExit('No free loopback ports found')
def free_udp_range(width):
for start in random.sample(range(25000, 55000-width), 2000):
if any(port in used for port in range(start,start+width)): continue
sockets=[]
try:
for port in range(start,start+width):
sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind(('127.0.0.1',port))
sockets.append(sock)
used.update(range(start,start+width))
return start,start+width-1
except OSError:
pass
finally:
for sock in sockets: sock.close()
raise SystemExit('No free contiguous UDP relay ports found')
print(free_port((socket.SOCK_STREAM,)), free_port((socket.SOCK_STREAM,)),
free_port((socket.SOCK_STREAM,socket.SOCK_DGRAM)), *free_udp_range(20))
PY
)
rustfs_access_key="acceptance$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')"
rustfs_secret_key=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \\n')
coturn_secret=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \\n')
coturn_username=acceptance
printf '%s' "$rustfs_access_key" > "$secret_dir/rustfs_access_key"
printf '%s' "$rustfs_secret_key" > "$secret_dir/rustfs_secret_key"
printf '%s' "$coturn_secret" > "$secret_dir/coturn_secret"
chmod 600 "$secret_dir"/*
cat > "$env_file" <<EOF
RUSTFS_API_PORT=$rustfs_api_port
RUSTFS_CONSOLE_PORT=$rustfs_console_port
COTURN_PORT=$coturn_port
COTURN_RELAY_PORT_MIN=$relay_min
COTURN_RELAY_PORT_MAX=$relay_max
COTURN_REALM=heimdall.acceptance.test
COTURN_SECRET=$coturn_secret
COTURN_USERNAME=$coturn_username
RUSTFS_ACCESS_KEY=$rustfs_access_key
RUSTFS_SECRET_KEY=$rustfs_secret_key
ACCEPTANCE_NETWORK=${project}-heimdall-net
EOF
chmod 600 "$env_file"
cat > "$override_file" <<'EOF'
services:
turn-test:
image: coturn/coturn:4.6
pull_policy: always
profiles: [acceptance]
entrypoint: ["/bin/sh", "-c"]
command:
- >-
exec turnutils_uclient -v -y -X -m 1 -n 1 -p 3478
-W "$$COTURN_SECRET" -u "$$COTURN_USERNAME" coturn
environment:
COTURN_SECRET: ${COTURN_SECRET}
COTURN_USERNAME: ${COTURN_USERNAME}
depends_on:
- coturn
networks:
heimdall-net:
name: ${ACCEPTANCE_NETWORK}
external: false
EOF
printf 'Disposable project: %s\nLocal images built: none\n' "$project"
compose config --quiet
compose up -d rustfs coturn
base_url="http://127.0.0.1:$rustfs_api_port"
deadline=$((SECONDS + 180))
until curl -fsS "$base_url/health" >/dev/null 2>&1; do
if ((SECONDS >= deadline)); then echo 'RustFS health check timed out' >&2; exit 1; fi
sleep 2
done
printf 'RustFS /health: HTTP 200; API port %s and console port %s published.\n' \
"$rustfs_api_port" "$rustfs_console_port"
RUSTFS_ACCESS_KEY="$rustfs_access_key" RUSTFS_SECRET_KEY="$rustfs_secret_key" \
RUSTFS_API_PORT="$rustfs_api_port" python3 - <<'PY'
import datetime, hashlib, hmac, os, urllib.error, urllib.request
access = os.environ['RUSTFS_ACCESS_KEY']
secret = os.environ['RUSTFS_SECRET_KEY']
host = '127.0.0.1:' + os.environ['RUSTFS_API_PORT']
path = '/acceptance'
payload_hash = hashlib.sha256(b'').hexdigest()
now = datetime.datetime.now(datetime.timezone.utc)
amz_date = now.strftime('%Y%m%dT%H%M%SZ')
date = now.strftime('%Y%m%d')
canonical_headers = f'host:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{amz_date}\n'
signed_headers = 'host;x-amz-content-sha256;x-amz-date'
canonical_request = f'PUT\n{path}\n\n{canonical_headers}\n{signed_headers}\n{payload_hash}'
scope = f'{date}/us-east-1/s3/aws4_request'
to_sign = 'AWS4-HMAC-SHA256\n' + amz_date + '\n' + scope + '\n' + hashlib.sha256(canonical_request.encode()).hexdigest()
def sign(key, value): return hmac.new(key, value.encode(), hashlib.sha256).digest()
key = sign(('AWS4' + secret).encode(), date)
key = sign(key, 'us-east-1')
key = sign(key, 's3')
key = sign(key, 'aws4_request')
signature = hmac.new(key, to_sign.encode(), hashlib.sha256).hexdigest()
authorization = f'AWS4-HMAC-SHA256 Credential={access}/{scope}, SignedHeaders={signed_headers}, Signature={signature}'
request = urllib.request.Request(
f'http://{host}{path}', data=b'', method='PUT',
headers={'Host': host, 'x-amz-content-sha256': payload_hash,
'x-amz-date': amz_date, 'Authorization': authorization})
try:
with urllib.request.urlopen(request, timeout=15) as response:
if response.status not in (200, 204): raise SystemExit('RustFS S3 bucket creation returned an unexpected status')
except urllib.error.HTTPError as error:
from xml.etree import ElementTree
body = error.read()
try: code = ElementTree.fromstring(body).findtext('{*}Code')
except ElementTree.ParseError: code = None
raise SystemExit(f'RustFS S3 authenticated bucket creation failed with HTTP {error.code} ({code or "unknown"})')
PY
printf 'RustFS S3 authenticated bucket creation: passed.\n'
if ! compose --profile acceptance run --rm --no-deps turn-test > "$turn_log" 2>&1; then
echo 'coturn authenticated TURN REST allocation did not succeed; sanitized client output:' >&2
sed -E 's/(secret|password|token)[=: ]+[^ ]+/\1=<redacted>/Ig' "$turn_log" | tail -30 >&2 || true
echo 'sanitized coturn server diagnostics:' >&2
compose logs --no-color coturn 2>&1 | rg -i 'error|fail|allocate|success|resolve|connect|auth|port|socket' | \
sed -E 's/(secret|password|token)[=: ]+[^ ]+/\1=<redacted>/Ig' | tail -40 >&2 || true
exit 1
fi
printf 'coturn TURN REST authenticated allocation: passed via Compose network at listener port %s (relay UDP %s-%s).\n' \
"$coturn_port" "$relay_min" "$relay_max"
for secret_value in "$rustfs_access_key" "$rustfs_secret_key" "$coturn_secret"; do
if compose logs --no-color 2>/dev/null | grep -Fq -- "$secret_value"; then
echo 'A generated service secret appeared in container logs.' >&2
exit 1
fi
done
printf 'Verified generated service secrets are absent from container logs.\n'
@@ -1,4 +1,6 @@
using System.Buffers.Binary;
using System.Net.Http.Json;
using System.Security.Cryptography;
using Heimdall.Domain.Entities;
using Heimdall.TestCommon;
using Microsoft.AspNetCore.Identity;
@@ -83,6 +85,73 @@ public class AuthFlowTests : E2ETestBase
navCount.ShouldBeGreaterThanOrEqualTo(1);
}
[Fact]
public async Task Authenticator_2fa_login_creates_a_usable_browser_cookie()
{
const string password = "BrowserTwoFactorPass123!";
var email = $"e2e-2fa-{Guid.NewGuid():N}@heimdall.test";
IdentityAppUser? user = null;
try
{
using (var scope = App.Services.CreateScope())
{
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
user = new IdentityAppUser
{
Id = Guid.NewGuid(),
Email = email,
UserName = email,
EmailConfirmed = true
};
(await users.CreateAsync(user, password)).Succeeded.ShouldBeTrue();
(await users.AddToRoleAsync(user, "Viewer")).Succeeded.ShouldBeTrue();
(await users.ResetAuthenticatorKeyAsync(user)).Succeeded.ShouldBeTrue();
(await users.SetTwoFactorEnabledAsync(user, true)).Succeeded.ShouldBeTrue();
}
await GotoWithCircuitAsync("/login");
await Page.FillAsync("input[autocomplete='email']", email);
await Page.FillAsync("input[autocomplete='current-password']", password);
await Page.ClickAsync("button:has-text('Se connecter')");
var codeInput = Page.Locator("input[autocomplete='one-time-code']");
await codeInput.WaitForAsync(new() { Timeout = 15000 });
string authenticatorKey;
using (var scope = App.Services.CreateScope())
{
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
var storedUser = await users.FindByIdAsync(user!.Id.ToString());
authenticatorKey = (await users.GetAuthenticatorKeyAsync(storedUser!))!;
}
await codeInput.FillAsync(GenerateTotp(authenticatorKey));
await Page.ClickAsync("button:has-text('Vérifier')");
await Page.WaitForURLAsync("**/dashboard**", new() { Timeout = 20000 });
await Page.WaitForSelectorAsync("text=Bienvenue", new() { Timeout = 15000 });
var cookies = await Page.Context.CookiesAsync([BaseUrl]);
var authCookie = cookies.SingleOrDefault(cookie => cookie.Name == ".Heimdall.Auth");
authCookie.ShouldNotBeNull();
using var authenticated = new HttpClient();
authenticated.DefaultRequestHeaders.Add("Cookie", $".Heimdall.Auth={authCookie!.Value}");
var response = await authenticated.GetAsync($"{BaseUrl}/api/users/me");
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
}
finally
{
if (user is not null)
{
using var scope = App.Services.CreateScope();
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
var storedUser = await users.FindByIdAsync(user.Id.ToString());
if (storedUser is not null)
(await users.DeleteAsync(storedUser)).Succeeded.ShouldBeTrue();
}
}
}
[Fact]
public async Task Login_with_wrong_password_shows_error()
{
@@ -153,4 +222,30 @@ public class AuthFlowTests : E2ETestBase
}
private sealed record BootstrapStatus(bool SetupRequired);
#pragma warning disable CA5350
private static string GenerateTotp(string base32Key)
{
const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
var key = new List<byte>();
var buffer = 0;
var bits = 0;
foreach (var character in base32Key.TrimEnd('='))
{
buffer = (buffer << 5) | alphabet.IndexOf(character);
bits += 5;
if (bits < 8) continue;
bits -= 8;
key.Add((byte)(buffer >> bits));
}
Span<byte> message = stackalloc byte[8];
BinaryPrimitives.WriteInt64BigEndian(message, DateTimeOffset.UtcNow.ToUnixTimeSeconds() / 30);
var hash = HMACSHA1.HashData(key.ToArray(), message);
var offset = hash[^1] & 0x0f;
var binary = ((hash[offset] & 0x7f) << 24) | (hash[offset + 1] << 16)
| (hash[offset + 2] << 8) | hash[offset + 3];
return (binary % 1_000_000).ToString("D6", System.Globalization.CultureInfo.InvariantCulture);
}
#pragma warning restore CA5350
}
@@ -56,6 +56,64 @@ public class UserManagementTests : E2ETestBase
body.ShouldContain("E2E Viewer");
}
[Theory]
[InlineData("Supervisor", true)]
[InlineData("Supervisor", false)]
[InlineData("Viewer", true)]
[InlineData("Viewer", false)]
public async Task User_created_from_dialog_can_log_in_with_submitted_password_after_email_confirmation(
string role, bool selectRoleBeforePassword)
{
await LoginViaUiAsync();
await GotoWithCircuitAsync("/users");
await Page.WaitForSelectorAsync("text=Nouvel utilisateur", new() { Timeout = 20000 });
await Page.ClickAsync("text=Nouvel utilisateur");
var dialog = Page.Locator(".mud-dialog");
await dialog.WaitForAsync(new() { Timeout = 10000 });
var email = $"e2e-{role.ToLowerInvariant()}-{Guid.NewGuid():N}@heimdall.test";
var password = "FirstLoginPass123!";
await dialog.Locator("input[autocomplete='email']").FillAsync(email);
await dialog.Locator("input[autocomplete='name']").FillAsync($"E2E {role}");
if (selectRoleBeforePassword)
await SelectCreateRoleAsync(dialog, role);
await dialog.Locator("input[autocomplete='new-password']").FillAsync(password);
if (!selectRoleBeforePassword)
await SelectCreateRoleAsync(dialog, role);
await dialog.Locator("button:has-text('Créer')").ClickAsync();
await dialog.WaitForAsync(new() { State = WaitForSelectorState.Detached, Timeout = 15000 });
var token = await LoginViaApiAsync();
using var admin = new HttpClient { BaseAddress = new Uri(BaseUrl) };
admin.DefaultRequestHeaders.Authorization = new("Bearer", token);
var row = Page.Locator($"tr:has-text('{email}')");
await row.WaitForAsync(new() { Timeout = 15000 });
await row.GetByRole(AriaRole.Button, new() { Name = "Confirmer l’email", Exact = true }).ClickAsync();
using var login = new HttpClient { BaseAddress = new Uri(BaseUrl) };
var response = await login.PostAsJsonAsync("/api/auth/login", new { email, password });
response.StatusCode.ShouldBe(HttpStatusCode.OK,
$"A {role} account created with role selected {(selectRoleBeforePassword ? "before" : "after")} its password should authenticate after admin email confirmation.");
var body = await response.Content.ReadFromJsonAsync<System.Text.Json.JsonElement>();
body.GetProperty("accessToken").GetString().ShouldNotBeNullOrWhiteSpace();
using var cleanup = new HttpClient { BaseAddress = new Uri(BaseUrl) };
cleanup.DefaultRequestHeaders.Authorization = new("Bearer", token);
var deleteResponse = await cleanup.DeleteAsync($"/api/users/{body.GetProperty("user").GetProperty("id").GetString()}");
deleteResponse.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.NoContent);
}
private static async Task SelectCreateRoleAsync(ILocator dialog, string role)
{
await dialog.Locator(".mud-input-control.mud-select").ClickAsync();
await dialog.Page.Locator(".mud-popover-open .mud-list-item")
.Filter(new() { HasText = role }).ClickAsync();
}
[Fact]
public async Task New_user_can_log_in_with_viewer_role()
{