Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Skipped
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 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
183 lines
8.7 KiB
Bash
Executable File
183 lines
8.7 KiB
Bash
Executable File
#!/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
|