From ba4ea588c2aaffef4d3346d852f79a992c053f76 Mon Sep 17 00:00:00 2001 From: Khaliq Date: Mon, 30 Nov 2026 19:02:27 -0800 Subject: [PATCH 1/9] test(okta-e2e): kind e2e for the self-hosted Okta SSO path ci/agent-relay/okta-e2e/kind.sh runs the published okta-setup.sh (or OKTA_SETUP) on kind: - mock: against mock_okta.py, a stateful stand-in for the Okta API. Refuses before any Okta call with no Secret or read-only kubectl; writes one key with a merge patch and keeps cluster-only keys; never prints the token or secret; refuses a second run. Runs the guide's console merge patch and JSON-patch remove verbatim. - chart: helm template relay-control with the exact values the script prints, with them removed (turn it off), and with oidcClientSecret left behind (refused). - live (OKTA_LIVE_ORG + OKTA_TOKEN_CMD): a throwaway group, the real script against a real org, verifies app settings, group, that the stored secret equals the app's active secret, discovery and redirect enforcement, then deactivates/deletes the app and group, also on failure. Co-Authored-By: Claude Opus 5.5 --- ci/agent-relay/okta-e2e/kind.sh | 311 +++++++++++++++++++++++++++ ci/agent-relay/okta-e2e/mock_okta.py | 107 +++++++++ 2 files changed, 418 insertions(+) create mode 100755 ci/agent-relay/okta-e2e/kind.sh create mode 100755 ci/agent-relay/okta-e2e/mock_okta.py diff --git a/ci/agent-relay/okta-e2e/kind.sh b/ci/agent-relay/okta-e2e/kind.sh new file mode 100755 index 00000000..8f6bf566 --- /dev/null +++ b/ci/agent-relay/okta-e2e/kind.sh @@ -0,0 +1,311 @@ +#!/usr/bin/env bash +# End-to-end test of the customer Okta SSO path (agentrelay.com/docs/self-hosting/okta-sso) +# on kind: the published okta-setup.sh, the guide's console and "turn it off" +# commands, and the values the script prints, rendered through the chart. +# +# ci/agent-relay/okta-e2e/kind.sh # mock + chart phases +# OKTA_SETUP=path/to/okta-setup.sh ci/agent-relay/okta-e2e/kind.sh +# OKTA_LIVE_ORG=https://.okta.com \ +# OKTA_TOKEN_CMD='op read --account "op:////password"' \ +# ci/agent-relay/okta-e2e/kind.sh # adds the live-Okta phase +# +# Phases: +# mock okta-setup.sh against mock_okta.py (a stateful stand-in for the Okta +# API). Proves that it writes ONE key, oidc-client-secret, with a merge +# patch, and keeps every other key, including keys that exist only in +# the cluster (never in ~/.agent-relay-install). Proves that it refuses before any +# Okta call when the Secret is missing or kubectl can't patch it, and +# that it refuses a second run. Also runs the guide's console merge patch +# and its JSON-patch remove. +# chart helm template relay-control with the exact lines okta-setup.sh +# prints, and with them removed again (turn it off). +# live (only with OKTA_LIVE_ORG and OKTA_TOKEN_CMD) okta-setup.sh against a +# real Okta org with a throwaway group and app label check; verifies the +# app, its redirect URI and group assignment through the API, then +# deactivates and deletes everything it created (also on failure). +# +# The token is read by OKTA_TOKEN_CMD into a 0600 curl config in a 0700 work +# dir. It is never printed or put on a command line. +# +# Without OKTA_SETUP, the script fetches okta-setup.sh from agentrelay.com and +# checks it against the published SHA256SUMS (OKTA_SETUP_CLOUD=eks|gke). +# Needs docker, kind, kubectl, helm, jq, curl, python3, shasum or sha256sum. +set -euo pipefail +cd "$(dirname "$0")/../../.." +ROOT="$PWD" +HERE="$ROOT/ci/agent-relay/okta-e2e" +CLUSTER="${CLUSTER:-ar-okta-e2e}" +CTX="kind-$CLUSTER" +NS=agent-relay +SECRET=agent-relay-secrets +WORK="$(mktemp -d "${TMPDIR:-/tmp}/ar-okta-e2e.XXXXXX")"; chmod 700 "$WORK" +export KUBECONFIG="$WORK/kubeconfig" +pass=0 +ok() { pass=$((pass + 1)); printf 'ok %d - %s\n' "$pass" "$*"; } +fail() { printf 'not ok - %s\n' "$*" >&2; exit 1; } +k() { kubectl --context "$CTX" -n "$NS" "$@"; } +MOCK_PID= +LIVE_CLEANUP=() +cleanup() { + local rc=$? + for c in "${LIVE_CLEANUP[@]}"; do eval "$c" || echo "cleanup step failed: ${c%% *}" >&2; done + [ -z "$MOCK_PID" ] || kill "$MOCK_PID" 2>/dev/null || true + [[ "${KEEP_CLUSTER:-0}" == 1 ]] || kind delete cluster --name "$CLUSTER" >/dev/null 2>&1 || true + rm -rf "$WORK" + exit "$rc" +} +trap cleanup EXIT +sha256() { if command -v sha256sum >/dev/null; then sha256sum "$@"; else shasum -a 256 "$@"; fi; } + +# --- the script under test ------------------------------------------------- +if [ -n "${OKTA_SETUP:-}" ]; then + cp "$OKTA_SETUP" "$WORK/okta-setup.sh" + echo "# okta-setup.sh from $OKTA_SETUP ($(sha256 "$WORK/okta-setup.sh" | cut -c1-12))" +else + base="https://agentrelay.com/self-hosting/files/${OKTA_SETUP_CLOUD:-eks}" + curl -fsSL "$base/okta-setup.sh" -o "$WORK/okta-setup.sh" + curl -fsSL "$base/SHA256SUMS" | grep ' okta-setup.sh$' > "$WORK/okta.sum" + (cd "$WORK" && sha256 -c okta.sum >/dev/null) || fail "published okta-setup.sh does not match SHA256SUMS" + echo "# okta-setup.sh from $base (checksum verified)" +fi +grep -q -- '--type merge' "$WORK/okta-setup.sh" || + fail "okta-setup.sh does not use a merge patch (published copy predates agentrelay.com#356?)" + +# --- cluster --------------------------------------------------------------- +kind get clusters 2>/dev/null | grep -qx "$CLUSTER" || kind create cluster --name "$CLUSTER" --wait 120s >/dev/null 2>&1 +kind get kubeconfig --name "$CLUSTER" > "$KUBECONFIG" +kubectl --context "$CTX" delete namespace "$NS" --ignore-not-found --wait=true >/dev/null +kubectl --context "$CTX" create namespace "$NS" >/dev/null +ok "kind cluster $CLUSTER ready" + +# An install's Secret. selfhost-encryption-key and SUMMARY_MASTER_KEYS exist +# ONLY in the cluster here: the local secret-files folder is absent, as on a +# second admin's machine. +seed_secret() { + k delete secret "$SECRET" --ignore-not-found >/dev/null + k create secret generic "$SECRET" \ + --from-literal=selfhost-encryption-key="$(openssl rand -hex 32)" \ + --from-literal=SUMMARY_MASTER_KEYS="k1:$(openssl rand -hex 32)" \ + --from-literal=selfhost-bootstrap-token="$(openssl rand -hex 32)" \ + --from-literal=database-url='postgres://x:y@db/relaycontrol?sslmode=verify-full' >/dev/null + k get secret "$SECRET" -o json | jq -S '.data' > "$WORK/seed.json" +} +others() { k get secret "$SECRET" -o json | jq -S '.data | del(.["oidc-client-secret"])'; } +key_value() { k get secret "$SECRET" -o json | jq -r --arg k "$1" '.data[$k] // empty | @base64d'; } + +# --- mock Okta --------------------------------------------------------------- +REAL_HOME="$HOME" +export HOME="$WORK/home"; mkdir -p "$HOME" # okta-setup.sh writes ~/.agent-relay-install +MOCK_TOKEN="mock-$(openssl rand -hex 8)" +MOCK_SECRET="mock-client-$(openssl rand -hex 16)" +MOCK_GROUP="Agent Relay Users" +MOCK_TOKEN="$MOCK_TOKEN" MOCK_CLIENT_SECRET="$MOCK_SECRET" MOCK_GROUP="$MOCK_GROUP" \ + python3 -I "$HERE/mock_okta.py" "$WORK/mock.port" "$WORK/mock.log" & MOCK_PID=$! +for _ in $(seq 50); do [ -s "$WORK/mock.port" ] && break; sleep 0.1; done +MOCK="http://127.0.0.1:$(cat "$WORK/mock.port")" +mock_calls() { [ -f "$WORK/mock.log" ] && wc -l < "$WORK/mock.log" | tr -d ' ' || echo 0; } + +run_setup() { # token kubeconfig-context -> output in $WORK/setup.out, exit status returned + local token="$1"; shift + printf '%s\n' "$token" | env OKTA_ORG="$MOCK" APP_DOMAIN=relay.okta-e2e.example \ + OKTA_GROUP="$MOCK_GROUP" ALLOWED_DOMAIN=okta-e2e.example "$@" \ + bash "$WORK/okta-setup.sh" > "$WORK/setup.out" 2>&1 +} + +# 1. Missing Secret: refuses before reading the token, nothing reaches Okta. +k delete secret "$SECRET" --ignore-not-found >/dev/null +if run_setup "$MOCK_TOKEN"; then fail "okta-setup.sh ran without the Secret"; fi +grep -q "no Secret $SECRET" "$WORK/setup.out" || fail "missing-Secret message: $(tail -2 "$WORK/setup.out")" +[ "$(mock_calls)" = 0 ] || fail "okta-setup.sh called Okta although the Secret is missing" +ok "missing Secret: refused before any Okta call" + +# 2. kubectl can read but not patch the Secret: the server dry run refuses, +# still before any Okta call. +seed_secret +k create serviceaccount okta-e2e-reader >/dev/null +k create role secret-reader --verb=get,list --resource=secrets >/dev/null +k create rolebinding okta-e2e-reader --role=secret-reader --serviceaccount="$NS:okta-e2e-reader" >/dev/null +RO_TOKEN="$(k create token okta-e2e-reader)" +kubectl config set-credentials okta-e2e-reader --token="$RO_TOKEN" >/dev/null +kubectl config set-context okta-e2e-ro --cluster="kind-$CLUSTER" --user=okta-e2e-reader >/dev/null +kubectl config use-context okta-e2e-ro >/dev/null +if run_setup "$MOCK_TOKEN"; then fail "okta-setup.sh ran without patch rights"; fi +grep -q "dry run failed" "$WORK/setup.out" || fail "read-only message: $(tail -2 "$WORK/setup.out")" +[ "$(mock_calls)" = 0 ] || fail "okta-setup.sh called Okta without patch rights" +kubectl config use-context "$CTX" >/dev/null +ok "read-only kubectl: server dry run refused before any Okta call" + +# 3. The real run: one key added, every other key byte-for-byte unchanged. +run_setup "$MOCK_TOKEN" || fail "okta-setup.sh failed: $(tail -5 "$WORK/setup.out")" +grep -q "client secret stored in Secret $SECRET" "$WORK/setup.out" || fail "no success line: $(tail -3 "$WORK/setup.out")" +grep -q 'Then run the helm upgrade' "$WORK/setup.out" || fail "the values for step 2 were not printed" +cp "$WORK/setup.out" "$WORK/setup.first.out" +[ "$(others)" = "$(cat "$WORK/seed.json")" ] || fail "other keys changed" +[ "$(key_value oidc-client-secret)" = "$MOCK_SECRET" ] || fail "oidc-client-secret is not the app's secret" +ok "merge patch set oidc-client-secret; the 4 cluster-only keys are unchanged" +if grep -q -e "$MOCK_SECRET" -e "$MOCK_TOKEN" "$WORK/setup.out"; then fail "token or client secret printed"; fi +ok "neither the token nor the client secret was printed" +[ "$(stat -c %a "$HOME/.agent-relay-install/secret-files/$SECRET/oidc-client-secret" 2>/dev/null || + stat -f %Lp "$HOME/.agent-relay-install/secret-files/$SECRET/oidc-client-secret")" = 600 ] || fail "backup copy is not 0600" +ok "backup copy written 0600" +curl -fsS -H "Authorization: SSWS $MOCK_TOKEN" "$MOCK/state" > "$WORK/state.json" # mock-only token +jq -e '.apps | length == 1' "$WORK/state.json" >/dev/null || fail "expected one app" +jq -e '.apps[0].settings.oauthClient.redirect_uris == ["https://relay.okta-e2e.example/login/oidc/callback"]' \ + "$WORK/state.json" >/dev/null || fail "wrong redirect URI" +jq -e '.assigned == [{"app": .apps[0].id, "group": "00gmockgroup"}]' "$WORK/state.json" >/dev/null || fail "group not assigned" +jq -e 'map(select(.path != "/.well-known/openid-configuration")) | all(.auth)' -s "$WORK/mock.log" >/dev/null || fail "an Okta call went without the token" +ok "app created with the callback redirect and the group assigned" + +# 4. A second run refuses (active "Agent Relay" app exists), and changes nothing. +before_calls=$(mock_calls) +if run_setup "$MOCK_TOKEN"; then fail "second run succeeded"; fi +grep -q 'already exists' "$WORK/setup.out" || fail "second-run message: $(tail -2 "$WORK/setup.out")" +[ "$(jq -s "[.[$before_calls:][] | select(.method != \"GET\")] | length" "$WORK/mock.log")" = 0 ] || fail "second run wrote to Okta" +[ "$(key_value oidc-client-secret)" = "$MOCK_SECRET" ] || fail "second run changed the stored secret" +ok "second run refused; nothing written" + +# 5. The guide's console steps (okta-sso.md step 1, "Prefer the Okta console?"). +seed_secret +mkdir -p "$HOME/.agent-relay-install/secret-files/$SECRET" +CONSOLE_SECRET="console-$(openssl rand -hex 16)" +printf '%s\n' "$CONSOLE_SECRET" | bash -c ' +set -euo pipefail +read -rs -p "Okta client secret: " X; echo +( umask 077; printf "%s" "$X" > ~/.agent-relay-install/secret-files/agent-relay-secrets/oidc-client-secret ) +P="$(mktemp)"; chmod 600 "$P" +jq -n --arg s "$X" "{data: {\"oidc-client-secret\": (\$s | @base64)}}" > "$P"; unset X +kubectl -n agent-relay patch secret agent-relay-secrets --type merge --patch-file "$P" +rm -f "$P" +kubectl -n agent-relay get secret agent-relay-secrets -o json | jq ".data | keys"' > "$WORK/console.out" 2>&1 || + fail "console steps failed: $(tail -3 "$WORK/console.out")" +[ "$(others)" = "$(cat "$WORK/seed.json")" ] || fail "console steps changed other keys" +[ "$(key_value oidc-client-secret)" = "$CONSOLE_SECRET" ] || fail "console steps stored the wrong value" +if grep -q "$CONSOLE_SECRET" "$WORK/console.out"; then fail "console steps printed the secret"; fi +ok "guide console steps: one-key merge patch, other keys unchanged, nothing printed" + +# 6. The guide's "turn it off": JSON-patch remove of just that key. +kubectl -n agent-relay patch secret agent-relay-secrets --type json \ + -p '[{"op":"remove","path":"/data/oidc-client-secret"}]' >/dev/null +[ -z "$(key_value oidc-client-secret)" ] || fail "key still present" +[ "$(k get secret "$SECRET" -o json | jq -S .data)" = "$(cat "$WORK/seed.json")" ] || fail "remove changed other keys" +ok "guide turn-off: JSON-patch remove dropped only oidc-client-secret" + +# --- chart ------------------------------------------------------------------- +# The exact lines okta-setup.sh printed, applied as the guide's step 2 says, on +# top of the chart's minimal CI values (password sign-in on). +values_from_output() { # setup output -> JSON values overlay + python3 -I - "$1" <<'EOF' +import json, re, sys +out = open(sys.argv[1]).read() +get = lambda k: re.search(r"^\s+" + k + r": (.+?)\s*(#.*)?$", out, re.M).group(1) +lst = lambda v: [x.strip() for x in v.strip("[]").split(",") if x.strip()] +print(json.dumps({ + "dashboardUrl": "https://relay.okta-e2e.example/", + "secretKeys": {"oidcClientSecret": get("oidcClientSecret")}, + "auth": {"password": {"enabled": True}, + "oidc": {"issuer": get("issuer"), "clientId": get("clientId"), + "allowedDomains": lst(get("allowedDomains")), "displayName": get("displayName"), + # Only the mock's issuer is http; the chart allows that for tests only. + **({"allowHttpIssuer": True} if get("issuer").startswith("http://") else {})}, + "autoJoinDomains": lst(get("autoJoinDomains"))}})) +EOF +} +values_from_output "$WORK/setup.first.out" > "$WORK/okta-values.json" +printf '%s\n' '{"dashboardUrl": "https://relay.okta-e2e.example/", "auth": {"password": {"enabled": true}}}' > "$WORK/off-values.json" +CHART=charts/relay-control +helm dependency build "$CHART" >/dev/null 2>&1 || true +helm template t "$CHART" -f "$CHART/ci/default-values.yaml" -f "$WORK/okta-values.json" > "$WORK/on.yaml" 2> "$WORK/on.err" || + fail "chart refused the printed values: $(tail -3 "$WORK/on.err")" +for want in "SELFHOST_OIDC_ISSUER" "SELFHOST_OIDC_CLIENT_ID" "SELFHOST_OIDC_DISPLAY_NAME" "SELFHOST_OIDC_CLIENT_SECRET_FILE"; do + grep -q "$want" "$WORK/on.yaml" || fail "rendered chart lacks $want" +done +grep -q "\"$MOCK\"" "$WORK/on.yaml" || fail "rendered issuer is not the one okta-setup.sh printed" +grep -q 'okta-e2e.example' "$WORK/on.yaml" || fail "allowed/auto-join domain not rendered" +grep -q 'key: "oidc-client-secret"' "$WORK/on.yaml" || fail "client secret not mounted from key oidc-client-secret" +ok "chart: the printed values render OIDC env and mount oidc-client-secret" +helm template t "$CHART" -f "$CHART/ci/default-values.yaml" -f "$WORK/off-values.json" > "$WORK/off.yaml" 2> "$WORK/off.err" || + fail "chart refused the turn-off values: $(tail -3 "$WORK/off.err")" +if grep -q -e SELFHOST_OIDC -e oidc-client-secret "$WORK/off.yaml"; then fail "turn-off values still render OIDC"; fi +ok "chart: with oidc, autoJoinDomains and oidcClientSecret removed, nothing OIDC renders" +jq '.secretKeys = {"oidcClientSecret": "oidc-client-secret"} | del(.auth.oidc)' "$WORK/okta-values.json" > "$WORK/half.json" +if helm template t "$CHART" -f "$CHART/ci/default-values.yaml" -f "$WORK/half.json" >/dev/null 2>&1; then + fail "chart accepted oidcClientSecret without auth.oidc (the guide says to remove both)" +fi +ok "chart: oidcClientSecret left behind without oidc: is refused, as the guide warns" + +# --- live Okta ----------------------------------------------------------------- +if [ -z "${OKTA_LIVE_ORG:-}" ] || [ -z "${OKTA_TOKEN_CMD:-}" ]; then + echo "# live phase skipped (set OKTA_LIVE_ORG and OKTA_TOKEN_CMD)" + echo "1..$pass"; exit 0 +fi +ORG="${OKTA_LIVE_ORG%/}" +RUN_ID="okta-e2e-$(date +%Y%m%d%H%M%S)-$(openssl rand -hex 3)" +LCFG="$WORK/live-curl.cfg" +( umask 077 + { printf 'header = "Authorization: SSWS '; HOME="$REAL_HOME" eval "$OKTA_TOKEN_CMD" | tr -d '\r\n'; printf '"\n'; } > "$LCFG" ) +[ "$(wc -c < "$LCFG")" -gt 40 ] || fail "OKTA_TOKEN_CMD returned nothing" +live() { curl -fsS -K "$LCFG" -H 'Accept: application/json' -H 'Content-Type: application/json' "$@"; } +live "$ORG/api/v1/users/me" >/dev/null || fail "the Okta token was refused by $ORG" +ok "live: token accepted by $ORG" + +# okta-setup.sh refuses while ANY active "Agent Relay" app exists; never touch one we did not create. +pre="$(live -G "$ORG/api/v1/apps" --data-urlencode 'q=Agent Relay' --data-urlencode limit=200 | + jq -r '[.[] | select(.label == "Agent Relay" and .status == "ACTIVE")] | map(.id) | join(" ")')" +[ -z "$pre" ] || fail "an active Okta app labelled \"Agent Relay\" already exists in $ORG ($pre); okta-setup.sh would refuse. Not touching it." + +GROUP_JSON="$(jq -n --arg n "$RUN_ID" '{profile: {name: $n, description: "agent-relay okta-e2e; safe to delete"}}' | + live -X POST "$ORG/api/v1/groups" --data-binary @-)" +LGROUP_ID="$(jq -r .id <<<"$GROUP_JSON")" +LIVE_CLEANUP+=("live -X DELETE '$ORG/api/v1/groups/$LGROUP_ID' >/dev/null && echo '# live cleanup: deleted group $RUN_ID'") +ok "live: created throwaway group $RUN_ID" + +seed_secret +rm -rf "$HOME/.agent-relay-install" +LIVE_DOMAIN="$RUN_ID.okta-e2e.invalid" +set +e +sed -n 's/^header = "Authorization: SSWS \(.*\)"$/\1/p' "$LCFG" | env OKTA_ORG="$ORG" APP_DOMAIN="$LIVE_DOMAIN" \ + OKTA_GROUP="$RUN_ID" ALLOWED_DOMAIN=okta-e2e.invalid bash "$WORK/okta-setup.sh" > "$WORK/live.out" 2>&1 +rc=$? +set -e +LAPP_ID="$(sed -n 's/^app created: \([^ ]*\) .*/\1/p' "$WORK/live.out")" +if [ -n "$LAPP_ID" ]; then + LIVE_CLEANUP=("live -X POST '$ORG/api/v1/apps/$LAPP_ID/lifecycle/deactivate' >/dev/null && live -X DELETE '$ORG/api/v1/apps/$LAPP_ID' >/dev/null && echo '# live cleanup: deactivated and deleted app $LAPP_ID'" "${LIVE_CLEANUP[@]}") +fi +[ "$rc" = 0 ] || fail "okta-setup.sh failed against $ORG: $(tail -4 "$WORK/live.out")" +[ -n "$LAPP_ID" ] || fail "no app id in the output" +if grep -q -F -f <(sed -n 's/^header = "Authorization: SSWS \(.*\)"$/\1/p' "$LCFG") "$WORK/live.out"; then fail "token printed"; fi +ok "live: okta-setup.sh created app $LAPP_ID and stored the secret" + +[ "$(others)" = "$(cat "$WORK/seed.json")" ] || fail "live run changed other keys" +ok "live: the 4 cluster-only keys are unchanged" +app="$(live "$ORG/api/v1/apps/$LAPP_ID")" +jq -e --arg r "https://$LIVE_DOMAIN/login/oidc/callback" '.settings.oauthClient.redirect_uris == [$r] + and .settings.oauthClient.grant_types == ["authorization_code"] and .signOnMode == "OPENID_CONNECT" + and .status == "ACTIVE"' <<<"$app" >/dev/null || fail "app settings differ from the guide" +ok "live: app is an active OIDC web app with only the callback redirect" +live "$ORG/api/v1/apps/$LAPP_ID/groups" | jq -e --arg g "$LGROUP_ID" 'map(.id) == [$g]' >/dev/null || + fail "group not (only) assigned" +ok "live: exactly the throwaway group is assigned" +live "$ORG/api/v1/apps/$LAPP_ID/credentials/secrets" | + jq -jr '[.[] | select(.status == "ACTIVE")][0].client_secret' > "$WORK/okta-secret" +cmp -s <(key_value oidc-client-secret | tr -d '\n') <(tr -d '\n' < "$WORK/okta-secret") || + fail "the Secret does not hold the app's active client secret" +rm -f "$WORK/okta-secret" +ok "live: Secret oidc-client-secret equals the app's active client secret (compared, not printed)" +cid="$(jq -r .credentials.oauthClient.client_id <<<"$app")" +issuer="$(sed -n 's/^ issuer: //p' "$WORK/live.out")" +[ "$issuer" = "$ORG" ] || fail "printed issuer $issuer is not the org issuer" +curl -fsS "$issuer/.well-known/openid-configuration" | jq -e --arg i "$issuer" '.issuer == $i' >/dev/null || + fail "issuer discovery mismatch" +auth_code() { curl -s -o /dev/null -w '%{http_code}' -G "$issuer/oauth2/v1/authorize" --data-urlencode "client_id=$cid" \ + --data-urlencode "redirect_uri=$1" --data-urlencode response_type=code --data-urlencode 'scope=openid email profile' \ + --data-urlencode state=s --data-urlencode nonce=n; } +good="$(auth_code "https://$LIVE_DOMAIN/login/oidc/callback")"; bad="$(auth_code "https://evil.invalid/login/oidc/callback")" +[ "$good" = 200 ] && [ "$bad" = 400 ] || fail "authorize: registered redirect $good (want 200), other redirect $bad (want 400)" +ok "live: issuer discovery matches; authorize accepts only the registered redirect" +values_from_output "$WORK/live.out" | sed "s#relay.okta-e2e.example#$LIVE_DOMAIN#" > "$WORK/live-values.json" +helm template t "$CHART" -f "$CHART/ci/default-values.yaml" -f "$WORK/live-values.json" > "$WORK/live.yaml" || + fail "chart refused the live values" +grep -q "\"$cid\"" "$WORK/live.yaml" || fail "live client id not rendered" +ok "live: chart renders the printed live values" +echo "1..$pass" diff --git a/ci/agent-relay/okta-e2e/mock_okta.py b/ci/agent-relay/okta-e2e/mock_okta.py new file mode 100755 index 00000000..b2a12304 --- /dev/null +++ b/ci/agent-relay/okta-e2e/mock_okta.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""A stateful stand-in for the parts of the Okta API that okta-setup.sh calls. + + python3 -I mock_okta.py + +Binds 127.0.0.1 on a free port and writes the port to . Every +request is appended to as one JSON line (method, path, and +whether the SSWS token matched), so the test can assert exactly what reached +"Okta", including that nothing did when the script refuses early. + +State: one group named by MOCK_GROUP (default "Agent Relay Users"); apps +created with POST /api/v1/apps are kept, so a second run sees the active +"Agent Relay" app. The client secret is MOCK_CLIENT_SECRET. +""" +import json +import os +import sys +import uuid +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlsplit + +PORT_FILE, LOG = sys.argv[1], sys.argv[2] +TOKEN = os.environ.get("MOCK_TOKEN", "mock-okta-token") +GROUP = {"id": "00gmockgroup", "profile": {"name": os.environ.get("MOCK_GROUP", "Agent Relay Users")}} +SECRET = os.environ.get("MOCK_CLIENT_SECRET", "mock-client-secret") +APPS = [] +ASSIGNED = [] + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *_): + pass + + def reply(self, code, body): + data = json.dumps(body).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def record(self, body=None): + url = urlsplit(self.path) + entry = {"method": self.command, "path": url.path, "query": parse_qs(url.query), + "auth": self.headers.get("Authorization") == "SSWS " + TOKEN} + if body is not None: + entry["body"] = body + with open(LOG, "a") as f: + f.write(json.dumps(entry) + "\n") + return url + + def authed(self): + if self.headers.get("Authorization") != "SSWS " + TOKEN: + self.reply(401, {"errorCode": "E0000011", "errorSummary": "Invalid token provided"}) + return False + return True + + def do_GET(self): + url = self.record() + base = "http://" + self.headers.get("Host", "127.0.0.1") + if url.path == "/.well-known/openid-configuration": + return self.reply(200, {"issuer": base, "authorization_endpoint": base + "/oauth2/v1/authorize"}) + if not self.authed(): + return + q = parse_qs(url.query) + if url.path == "/api/v1/apps": + term = q.get("q", [""])[0] + return self.reply(200, [a for a in APPS if a["label"].startswith(term)]) + if url.path == "/api/v1/groups": + term = q.get("q", [""])[0] + return self.reply(200, [GROUP] if GROUP["profile"]["name"].startswith(term) else []) + if url.path == "/state": + return self.reply(200, {"apps": APPS, "assigned": ASSIGNED}) + self.reply(404, {"errorCode": "E0000007"}) + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}") + url = self.record(body) + if not self.authed(): + return + if url.path == "/api/v1/apps": + app = dict(body, id="0oa" + uuid.uuid4().hex[:17], status="ACTIVE") + app["credentials"] = {"oauthClient": dict(body.get("credentials", {}).get("oauthClient", {}), + client_id="0oaclient" + uuid.uuid4().hex[:11], + client_secret=SECRET)} + APPS.append(app) + return self.reply(200, app) + self.reply(404, {"errorCode": "E0000007"}) + + def do_PUT(self): + length = int(self.headers.get("Content-Length", 0)) + body = json.loads(self.rfile.read(length) or b"{}") + url = self.record(body) + if not self.authed(): + return + parts = url.path.strip("/").split("/") + if parts[:3] == ["api", "v1", "apps"] and len(parts) == 6 and parts[4] == "groups": + ASSIGNED.append({"app": parts[3], "group": parts[5]}) + return self.reply(200, {"id": parts[5]}) + self.reply(404, {"errorCode": "E0000007"}) + + +server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) +with open(PORT_FILE + ".tmp", "w") as f: + f.write(str(server.server_address[1])) +os.replace(PORT_FILE + ".tmp", PORT_FILE) +server.serve_forever() From 43b6940b1a0a8404ba1ec916bc427ced46ba8019 Mon Sep 17 00:00:00 2001 From: Khaliq Date: Mon, 30 Nov 2026 19:12:20 -0800 Subject: [PATCH 2/9] feat(kind): local OIDC sign-in for any issuer; okta-e2e browser phase - local_stack.py: the stored OIDC client may name an https "issuer" and a "display_name" (Google stays the default and keeps its client-id check); make local-oidc is an alias of local-google-oidc. - ci/agent-relay/okta-e2e/browser.sh + browser_signin.py: throwaway Okta group, users, app (shaped like okta-setup.sh's) and a password-only authentication policy; points the local stack at it and drives "Continue with Okta" in Chromium: a group member joins as a member, a non-member is refused by Okta, an other-domain user is refused by Control. Deletes every Okta object it created and restores the stack's OIDC setting. Co-Authored-By: Claude Opus 5.5 --- Makefile | 4 +- ci/agent-relay/kind/local_stack.py | 31 ++-- ci/agent-relay/kind/test_local_stack.py | 10 ++ ci/agent-relay/okta-e2e/browser.sh | 164 ++++++++++++++++++++++ ci/agent-relay/okta-e2e/browser_signin.py | 125 +++++++++++++++++ docs/local-development.md | 5 + 6 files changed, 327 insertions(+), 12 deletions(-) create mode 100755 ci/agent-relay/okta-e2e/browser.sh create mode 100755 ci/agent-relay/okta-e2e/browser_signin.py diff --git a/Makefile b/Makefile index b8e89dea..31b567cd 100644 --- a/Makefile +++ b/Makefile @@ -60,14 +60,14 @@ local-up: local-tools local-down: local-tools PATH=$(call sh_quote,$(CURDIR)/.kind/tools):"$$PATH" $(call sh_quote,$(CURDIR)/.kind/tools/venv/bin/python3) ci/agent-relay/kind/local_stack.py down -.PHONY: local-trust local-login local-llm-key local-google-oidc +.PHONY: local-trust local-login local-llm-key local-google-oidc local-oidc local-trust: sudo $(call sh_quote,$(PYTHON)) ci/agent-relay/kind/local_host_setup.py up local-login: local-tools PATH=$(call sh_quote,$(CURDIR)/.kind/tools):"$$PATH" $(call sh_quote,$(CURDIR)/.kind/tools/venv/bin/python3) ci/agent-relay/kind/local_stack.py login local-llm-key: local-tools @PATH=$(call sh_quote,$(CURDIR)/.kind/tools):"$$PATH" $(call sh_quote,$(CURDIR)/.kind/tools/venv/bin/python3) ci/agent-relay/kind/local_stack.py llm-key -local-google-oidc: local-tools +local-google-oidc local-oidc: local-tools @PATH=$(call sh_quote,$(CURDIR)/.kind/tools):"$$PATH" $(call sh_quote,$(CURDIR)/.kind/tools/venv/bin/python3) ci/agent-relay/kind/local_stack.py google-oidc .PHONY: local-postgres-cast-proof diff --git a/ci/agent-relay/kind/local_stack.py b/ci/agent-relay/kind/local_stack.py index f4961118..8b583c47 100644 --- a/ci/agent-relay/kind/local_stack.py +++ b/ci/agent-relay/kind/local_stack.py @@ -394,8 +394,8 @@ def values(self, phase, tenant=None): if oidc: # Real Google sign-in through Control's OIDC (the same code path as # Okta or Entra ID); the email link stays as the operator fallback. - result["relay-control"]["auth"]["oidc"] = {"issuer": GOOGLE_ISSUER, "clientId": oidc["client_id"], - "allowedDomains": oidc["allowed_domains"], "displayName": "Google"} + result["relay-control"]["auth"]["oidc"] = {"issuer": oidc["issuer"], "clientId": oidc["client_id"], + "allowedDomains": oidc["allowed_domains"], "displayName": oidc["display_name"]} # allowedDomains only gates who may authenticate; joining the single # organization without an invite is auth.autoJoinDomains. result["relay-control"]["auth"]["autoJoinDomains"] = oidc["allowed_domains"] @@ -464,15 +464,25 @@ def github_releases_egress(self): "app.kubernetes.io/component": "api"})) def google_oidc(self): - """The Google OAuth client for local sign-in, or None (email link only).""" + """The OIDC client for local sign-in, or None (email link only). + + Google by default; an optional "issuer" (https) and "display_name" + select another provider, such as an Okta org, through the same file.""" state = getattr(self, "state", None) path = state / "google-oidc.json" if state else None if path is None or not path.exists(): return None value = json.loads(path.read_text()) - if not (isinstance(value.get("client_id"), str) and value["client_id"].endswith(".apps.googleusercontent.com") + issuer = value.get("issuer") or GOOGLE_ISSUER + if not (isinstance(issuer, str) and re.fullmatch(r"https://[^?#@\s]+", issuer)): + raise StackError(str(path) + " issuer must be an https URL") + google = issuer == GOOGLE_ISSUER + if not (isinstance(value.get("client_id"), str) and value["client_id"] + and (not google or value["client_id"].endswith(".apps.googleusercontent.com")) and isinstance(value.get("client_secret"), str) and value["client_secret"]): - raise StackError(str(path) + " must hold a Google web client_id and client_secret") + raise StackError(str(path) + " must hold a " + ("Google web " if google else "") + "client_id and client_secret") + value["issuer"] = issuer.rstrip("/") + value.setdefault("display_name", "Google" if google else "single sign-on") value.setdefault("allowed_domains", ["agentrelay.com"]) return value @@ -485,7 +495,7 @@ def google_oidc_egress(self): self.k("delete", "networkpolicy", "local-control-oidc-egress", "--ignore-not-found=true") def install_google_oidc(self): - """Store a Google OAuth client (JSON on stdin) for this owned stack, then reconcile it.""" + """Store an OIDC client (JSON on stdin; Google unless it has "issuer") for this owned stack, then reconcile it.""" self.docker(require_space=False) self.owned() if sys.stdin.isatty(): @@ -493,12 +503,13 @@ def install_google_oidc(self): raw = json.loads(sys.stdin.read()) domains = [d.strip() for d in os.environ.get("LOCAL_OIDC_ALLOWED_DOMAINS", "agentrelay.com").split(",") if d.strip()] value = {"client_id": raw.get("client_id", ""), "client_secret": raw.get("client_secret", ""), "allowed_domains": domains} + value.update({k: raw[k] for k in ("issuer", "display_name") if raw.get(k)}) private_json(self.state / "google-oidc.json", value) - self.google_oidc() # validate before spending a reconcile - print("Google sign-in stored (0600; allowed domains: " + ", ".join(domains) + "). Reconciling the local stack...", flush=True) + label = self.google_oidc()["display_name"] # validate before spending a reconcile + print(label + " sign-in stored (0600; allowed domains: " + ", ".join(domains) + "). Reconciling the local stack...", flush=True) self.up_local() - print("Register " + SITE + "/login/oidc/callback as an authorized redirect URI on that Google client, " - "then use 'Continue with Google' at " + SITE + "/login.") + print("Register " + SITE + "/login/oidc/callback as an authorized redirect URI on that client, " + "then use 'Continue with " + label + "' at " + SITE + "/login.") def configure_model(self, key=None): # Repeating local-up without an environment override preserves a key diff --git a/ci/agent-relay/kind/test_local_stack.py b/ci/agent-relay/kind/test_local_stack.py index f3136973..63f3fe1f 100644 --- a/ci/agent-relay/kind/test_local_stack.py +++ b/ci/agent-relay/kind/test_local_stack.py @@ -566,6 +566,16 @@ def test_google_oidc_renders_control_sign_in_and_egress_only_when_stored(self): (stack.state / "google-oidc.json").write_text(json.dumps({"client_id": "not-google", "client_secret": "x"})) with self.assertRaises(local_stack.StackError): stack.google_oidc() + # Any https issuer (an Okta org here) through the same file. + (stack.state / "google-oidc.json").write_text(json.dumps({"issuer": "https://example.okta.com/", + "client_id": "0oaexample", "client_secret": "not-a-real-secret", "display_name": "Okta", + "allowed_domains": ["example.com"]})) + oidc = stack.values("serve", tenant)["relay-control"]["auth"]["oidc"] + self.assertEqual((oidc["issuer"], oidc["clientId"], oidc["displayName"]), ("https://example.okta.com", "0oaexample", "Okta")) + (stack.state / "google-oidc.json").write_text(json.dumps({"issuer": "http://example.okta.com", + "client_id": "0oaexample", "client_secret": "x"})) + with self.assertRaises(local_stack.StackError): + stack.google_oidc() def test_google_oidc_secret_reconciles_when_control_bootstrap_is_cached(self): with tempfile.TemporaryDirectory() as tmp: diff --git a/ci/agent-relay/okta-e2e/browser.sh b/ci/agent-relay/okta-e2e/browser.sh new file mode 100755 index 00000000..4b6029ca --- /dev/null +++ b/ci/agent-relay/okta-e2e/browser.sh @@ -0,0 +1,164 @@ +#!/usr/bin/env bash +# Real browser sign-in through Okta on the local Kind stack (make local-up). +# +# OKTA_LIVE_ORG=https://.okta.com \ +# OKTA_TOKEN_CMD='op read --account "op:////password"' \ +# PLAYWRIGHT_PYTHON=/path/to/venv/bin/python \ +# ci/agent-relay/okta-e2e/browser.sh +# +# Creates, in the Okta org, only throwaway objects named okta-e2e-: +# - a group, and three users with passwords (no email is sent): +# member in the group, allowed email domain -> joins as a member +# outsider NOT in the group, allowed domain -> Okta refuses +# otherdom in the group, other email domain -> Control refuses +# - an OIDC web app shaped exactly like okta-setup.sh's (label +# "Agent Relay e2e ", so it never collides with a real "Agent Relay" +# app), redirect https://relay.kind.agentrelay.com/login/oidc/callback; +# - an authentication policy for that app: password only. New apps +# otherwise get the org default, which requires two factors and can't run +# unattended. The guide's note on this is unchanged. +# It points the local stack at that app (make local-oidc), checks login-config, +# and drives "Continue with Okta" in Chromium (browser_signin.py) for each user. +# On exit, also on failure, it deletes the app, policy, users and group, and +# restores the stack's previous OIDC setting (KEEP_OIDC=1 leaves it). +# +# make local-oidc and the restore re-run the stack's "up": export the same +# LOCAL_RELAYCAST_BACKEND the stack was created with (it is not remembered). +# +# The token goes from OKTA_TOKEN_CMD into a 0600 curl config; the client secret +# and user passwords go to 0600 files or stdin. None is printed or put on argv. +set -euo pipefail +cd "$(dirname "$0")/../../.." +ROOT="$PWD" +HERE="$ROOT/ci/agent-relay/okta-e2e" +: "${OKTA_LIVE_ORG:?set OKTA_LIVE_ORG}" "${OKTA_TOKEN_CMD:?set OKTA_TOKEN_CMD}" +PY="${PLAYWRIGHT_PYTHON:-python3}" +ORG="${OKTA_LIVE_ORG%/}" +SITE=https://relay.kind.agentrelay.com +DOMAIN="${OKTA_E2E_DOMAIN:-example.com}" +STATE="$ROOT/.kind/local" +[ -f "$STATE/kubeconfig" ] || { echo "no local stack in this checkout: run make local-up first" >&2; exit 1; } +"$PY" -c 'import playwright' 2>/dev/null || { echo "$PY has no playwright (set PLAYWRIGHT_PYTHON)" >&2; exit 1; } +RUN_ID="okta-e2e-$(date +%Y%m%d%H%M%S)-$(openssl rand -hex 3)" +WORK="$(mktemp -d "${TMPDIR:-/tmp}/ar-okta-browser.XXXXXX")"; chmod 700 "$WORK" +EVIDENCE="${EVIDENCE_DIR:-$WORK/evidence}"; mkdir -p "$EVIDENCE" +pass=0 +ok() { pass=$((pass + 1)); printf 'ok %d - %s\n' "$pass" "$*"; } +fail() { printf 'not ok - %s\n' "$*" >&2; exit 1; } +CLEANUP=() +OIDC_FILE="$STATE/google-oidc.json" +cleanup() { + local rc=$? i + for ((i = ${#CLEANUP[@]} - 1; i >= 0; i--)); do eval "${CLEANUP[$i]}" || echo "# cleanup step failed: ${CLEANUP[$i]%% *}" >&2; done + rm -rf "$WORK" + exit "$rc" +} +trap cleanup EXIT + +CFG="$WORK/curl.cfg" +( umask 077; { printf 'header = "Authorization: SSWS '; eval "$OKTA_TOKEN_CMD" | tr -d '\r\n'; printf '"\n'; } > "$CFG" ) +[ "$(wc -c < "$CFG")" -gt 40 ] || fail "OKTA_TOKEN_CMD returned nothing" +okta() { curl -fsS -K "$CFG" -H 'Accept: application/json' -H 'Content-Type: application/json' "$@"; } +okta "$ORG/api/v1/users/me" >/dev/null || fail "the Okta token was refused by $ORG" +ok "token accepted by $ORG (run $RUN_ID)" + +# --- Okta objects --------------------------------------------------------------- +GROUP_ID="$(jq -n --arg n "$RUN_ID" '{profile: {name: $n, description: "agent-relay okta-e2e; safe to delete"}}' | + okta -X POST "$ORG/api/v1/groups" --data-binary @- | jq -r .id)" +CLEANUP+=("okta -X DELETE '$ORG/api/v1/groups/$GROUP_ID' >/dev/null && echo '# cleanup: deleted group $RUN_ID'") + +new_user() { # name domain in-group -> user id; password in $WORK/.pw + local name="$1" email="$RUN_ID-$1@$2" groups=() + ( umask 077; printf 'Ae2e!%s' "$(openssl rand -hex 16)" > "$WORK/$name.pw" ) + [ "$3" = yes ] && groups=("$GROUP_ID") + local id + id="$(jq -n --arg e "$email" --arg n "$name" --rawfile p "$WORK/$name.pw" --args '{ + profile: {firstName: "okta-e2e", lastName: $n, email: $e, login: $e}, + credentials: {password: {value: $p}}, groupIds: $ARGS.positional}' "${groups[@]}" | + okta -X POST "$ORG/api/v1/users?activate=true" --data-binary @- | jq -r .id)" + [ -n "$id" ] && [ "$id" != null ] || return 1 + CLEANUP+=("okta -X POST '$ORG/api/v1/users/$id/lifecycle/deactivate' >/dev/null; okta -X DELETE '$ORG/api/v1/users/$id' >/dev/null && echo '# cleanup: deleted user $email'") + printf '%s %s\n' "$id" "$email" > "$WORK/$name.user" +} +new_user member "$DOMAIN" yes || fail "could not create the member user" +new_user outsider "$DOMAIN" no || fail "could not create the outsider user" +new_user otherdom "other-$DOMAIN" yes || fail "could not create the other-domain user" +ok "created group and 3 users (member, outsider, otherdom)" + +# The app, exactly as okta-setup.sh creates it, under a unique label. +APP="$(jq -n --arg d "${SITE#https://}" --arg l "Agent Relay e2e $RUN_ID" '{ + name: "oidc_client", label: $l, signOnMode: "OPENID_CONNECT", + credentials: {oauthClient: {token_endpoint_auth_method: "client_secret_basic"}}, + settings: {oauthClient: { + client_uri: ("https://" + $d), + redirect_uris: [("https://" + $d + "/login/oidc/callback")], + response_types: ["code"], grant_types: ["authorization_code"], + application_type: "web", consent_method: "TRUSTED"}}}' | + okta -X POST "$ORG/api/v1/apps" --data-binary @-)" +APP_ID="$(jq -r .id <<<"$APP")" +CLIENT_ID="$(jq -r .credentials.oauthClient.client_id <<<"$APP")" +( umask 077; jq -jr .credentials.oauthClient.client_secret <<<"$APP" > "$WORK/client-secret" ); unset APP +POLICY_ID= +delete_app_and_policy() { # the policy can only go once no app uses it + okta -X POST "$ORG/api/v1/apps/$APP_ID/lifecycle/deactivate" >/dev/null || true + okta -X DELETE "$ORG/api/v1/apps/$APP_ID" >/dev/null && echo "# cleanup: deleted app $APP_ID" + [ -z "$POLICY_ID" ] || { okta -X DELETE "$ORG/api/v1/policies/$POLICY_ID" >/dev/null && echo "# cleanup: deleted policy $RUN_ID"; } +} +CLEANUP+=("delete_app_and_policy") +okta -X PUT "$ORG/api/v1/apps/$APP_ID/groups/$GROUP_ID" --data-binary '{}' >/dev/null +ok "created app $APP_ID (as okta-setup.sh does) and assigned the group" + +POLICY_ID="$(jq -n --arg n "$RUN_ID" '{type: "ACCESS_POLICY", name: $n, description: "agent-relay okta-e2e; safe to delete", status: "ACTIVE"}' | + okta -X POST "$ORG/api/v1/policies" --data-binary @- | jq -r .id)" +jq -n '{name: "password only", type: "ACCESS_POLICY", priority: 1, actions: {appSignOn: {access: "ALLOW", + verificationMethod: {type: "ASSURANCE", factorMode: "1FA", reauthenticateIn: "PT0S", + constraints: [{knowledge: {types: ["password"]}}]}}}}' | + okta -X POST "$ORG/api/v1/policies/$POLICY_ID/rules" --data-binary @- >/dev/null +okta -X PUT "$ORG/api/v1/apps/$APP_ID/policies/$POLICY_ID" >/dev/null +ok "app uses a password-only authentication policy (test users have no second factor)" + +# --- the local stack --------------------------------------------------------------- +if [ -f "$OIDC_FILE" ]; then cp -p "$OIDC_FILE" "$WORK/oidc.prev"; fi +restore_oidc() { + [ "${KEEP_OIDC:-0}" = 1 ] && { echo "# KEEP_OIDC=1: the stack still points at the deleted app"; return 0; } + if [ -f "$WORK/oidc.prev" ]; then cp -p "$WORK/oidc.prev" "$OIDC_FILE"; else rm -f "$OIDC_FILE"; fi + make -s local-up > "$WORK/restore.log" 2>&1 && echo "# cleanup: local stack OIDC setting restored" || + { echo "# cleanup: make local-up failed restoring OIDC; see below" >&2; tail -5 "$WORK/restore.log" >&2; } +} +CLEANUP+=("restore_oidc") +jq -n --arg i "$ORG" --arg c "$CLIENT_ID" --rawfile s "$WORK/client-secret" \ + '{issuer: $i, client_id: $c, client_secret: $s, display_name: "Okta"}' | + LOCAL_OIDC_ALLOWED_DOMAINS="$DOMAIN" make -s local-oidc > "$WORK/oidc.log" 2>&1 || + fail "make local-oidc failed: $(tail -5 "$WORK/oidc.log")" +rm -f "$WORK/client-secret" +if grep -q -F -f <(jq -r .client_secret "$OIDC_FILE") "$WORK/oidc.log"; then fail "client secret printed by local-oidc"; fi +ok "local stack reconciled with the Okta app (allowed domain $DOMAIN)" + +EDGE="${LOCAL_EDGE:-127.0.0.1}" +cfg="$(curl -fsS -k --resolve "relay.kind.agentrelay.com:443:$EDGE" "$SITE/cloud/api/v1/auth/login-config")" +jq -e '.oidc.displayName == "Okta"' <<<"$cfg" >/dev/null || fail "login-config: $(jq -c '{methods, oidc}' <<<"$cfg")" +ok "login-config offers Okta ($(jq -c '{methods, oidc}' <<<"$cfg"))" + +# --- browser ------------------------------------------------------------------------- +( umask 077 + jq -n --arg site "$SITE" --arg edge "$EDGE" \ + --arg me "$(cut -d' ' -f2 "$WORK/member.user")" --rawfile mp "$WORK/member.pw" \ + --arg oe "$(cut -d' ' -f2 "$WORK/outsider.user")" --rawfile op "$WORK/outsider.pw" \ + --arg de "$(cut -d' ' -f2 "$WORK/otherdom.user")" --rawfile dp "$WORK/otherdom.pw" \ + '{site: $site, edge: $edge, cases: [ + {name: "member", email: $me, password: $mp, expect: "member"}, + {name: "outsider", email: $oe, password: $op, expect: "okta_refused"}, + {name: "otherdom", email: $de, password: $dp, expect: "control_refused"}]}' > "$WORK/cases.json" ) +set +e +"$PY" -I "$HERE/browser_signin.py" "$WORK/cases.json" "$EVIDENCE" > "$WORK/browser.out" 2> "$WORK/browser.err" +brc=$? +set -e +rm -f "$WORK/cases.json" "$WORK"/*.pw +while read -r line; do + name="$(jq -r .case <<<"$line")" + if jq -e .pass <<<"$line" >/dev/null; then ok "browser: $name -> $(jq -c 'del(.case, .pass)' <<<"$line")" + else echo "not ok - browser: $name -> $(jq -c 'del(.case, .pass)' <<<"$line")" >&2; fi +done < "$WORK/browser.out" +[ "$brc" = 0 ] || fail "browser cases failed (screenshots: $EVIDENCE) $(tail -3 "$WORK/browser.err")" +[ -n "${EVIDENCE_DIR:-}" ] && echo "# screenshots: $EVIDENCE" +echo "1..$pass" diff --git a/ci/agent-relay/okta-e2e/browser_signin.py b/ci/agent-relay/okta-e2e/browser_signin.py new file mode 100755 index 00000000..1ba8a544 --- /dev/null +++ b/ci/agent-relay/okta-e2e/browser_signin.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Drive "Continue with Okta" on the local stack's /login with Playwright. + + python3 browser_signin.py + +cases.json (0600, written by browser.sh) is + {"site": "https://relay.kind.agentrelay.com", "edge": "127.0.0.1", + "cases": [{"name": ..., "email": ..., "password": ..., "expect": "member" | "okta_refused" | "control_refused"}]} +Passwords are filled into the page and never printed. Prints one JSON result +per case and exits 1 if any case does not match its expectation. Screenshots of +each case's final page go to . +""" +import json +import re +import sys +from urllib.parse import urlsplit + +from playwright.sync_api import TimeoutError as PlaywrightTimeout +from playwright.sync_api import sync_playwright + +CASES, EVIDENCE = sys.argv[1], sys.argv[2] +config = json.load(open(CASES)) +SITE = config["site"].rstrip("/") +HOST = urlsplit(SITE).hostname + + +def okta_sign_in(page, email, password): + """Okta Identity Engine (identifier first) or the classic widget.""" + page.wait_for_selector('input[name="identifier"], input[name="username"], #okta-signin-username', timeout=30000) + if page.locator('input[name="identifier"]').count(): + page.fill('input[name="identifier"]', email) + page.locator('input[type="submit"], button[type="submit"]').first.click() + page.wait_for_selector('input[name="credentials.passcode"], input[type="password"]', timeout=30000) + page.fill('input[name="credentials.passcode"], input[type="password"]', password) + else: + page.fill('input[name="username"], #okta-signin-username', email) + page.fill('input[name="password"], #okta-signin-password', password) + page.locator('input[type="submit"], button[type="submit"]').first.click() + + +def session(page): + response = page.request.get(SITE + "/cloud/api/auth/session") + try: + body = response.json() + except Exception: + body = {} + return response.status, body + + +def run_case(browser, case): + context = browser.new_context(ignore_https_errors=True) + page = context.new_page() + result = {"case": case["name"], "expect": case["expect"]} + callbacks = [] # query keys (never values) of each OIDC callback the browser reached + page.on("framenavigated", lambda f: f == page.main_frame and urlsplit(f.url).path == "/login/oidc/callback" + and callbacks.append(sorted(re.findall(r"(?:^|&)([^=&]+)=", urlsplit(f.url).query)) + + (["error=access_denied"] if "error=access_denied" in f.url else []))) + try: + page.goto(SITE + "/login", wait_until="networkidle") + button = page.get_by_role("button", name=re.compile("Continue with Okta")).or_( + page.get_by_role("link", name=re.compile("Continue with Okta"))) + button.first.click(timeout=30000) + page.wait_for_url(re.compile(r"^https://[^/]*okta\.com/"), timeout=30000) + result["oktaHost"] = urlsplit(page.url).hostname + okta_sign_in(page, case["email"], case["password"]) + # Back on the site (signed in or refused by Control), or stopped at Okta. + try: + page.wait_for_url(lambda u: urlsplit(u).hostname == HOST, timeout=45000) + page.wait_for_load_state("networkidle") + except PlaywrightTimeout: + pass + final = urlsplit(page.url) + result["finalHost"], result["finalPath"] = final.hostname, final.path + status, body = session(page) + result["sessionStatus"] = status + if status == 200: + result["email"] = body.get("user", {}).get("email") + result["role"] = body.get("currentOrganization", {}).get("role") + result["organization"] = body.get("currentOrganization", {}).get("name") + result["organizationId"] = body.get("currentOrganization", {}).get("id") + org = result["organizationId"] + if org: + usage = page.request.get(SITE + "/cloud/api/v1/organizations/" + org + "/usage?days=7") + result["usageStatus"] = usage.status # owner-only: a member gets 403 + text = page.inner_text("body")[:4000] + if final.hostname != HOST: + m = re.search(r"(not allowed to access this app|not assigned to the client application|" + r"access to this application|not allowed)", text, re.I) + result["oktaMessage"] = m.group(0) if m else None + else: + m = re.search(r"(not allowed|isn't allowed|not permitted|domain|couldn't sign you in|sign-in failed|error)[^\n]{0,120}", text, re.I) + result["siteMessage"] = m.group(0) if m else None + except Exception as error: # noqa: BLE001 - report every case + result["error"] = type(error).__name__ + ": " + str(error).splitlines()[0][:300] + finally: + page.screenshot(path=EVIDENCE + "/" + case["name"] + ".png", full_page=True) + context.close() + result["callbacks"] = callbacks + denied_at_okta = (result.get("finalHost") != HOST and bool(result.get("oktaMessage"))) or any( + "error=access_denied" in c for c in callbacks) + code_returned = any("code" in c for c in callbacks) + e = case["expect"] + if e == "member": + result["pass"] = (result.get("sessionStatus") == 200 and result.get("email", "").lower() == case["email"].lower() + and result.get("role") == "member" and result.get("usageStatus") == 403 + and result.get("finalHost") == HOST) + elif e == "okta_refused": + result["pass"] = result.get("sessionStatus") == 401 and "error" not in result and denied_at_okta and not code_returned + elif e == "control_refused": + # Okta authenticated the person (a code came back); Control refused the session. + result["pass"] = (result.get("sessionStatus") == 401 and result.get("finalHost") == HOST + and "error" not in result and code_returned) + else: + result["pass"] = False + return result + + +with sync_playwright() as p: + edge = config.get("edge", "127.0.0.1") + browser = p.chromium.launch(args=["--host-resolver-rules=MAP " + HOST + " " + edge]) + results = [run_case(browser, c) for c in config["cases"]] + browser.close() +for r in results: + print(json.dumps(r, sort_keys=True)) +sys.exit(0 if all(r["pass"] for r in results) else 1) diff --git a/docs/local-development.md b/docs/local-development.md index 57681ae6..f7fb23ff 100644 --- a/docs/local-development.md +++ b/docs/local-development.md @@ -162,6 +162,11 @@ op item get "Local Kind Google OAuth client" --vault "AI Agents" --reveal --form | jq '{client_id: (.fields[]|select(.label=="client_id").value), client_secret: (.fields[]|select(.label=="client_secret").value)}' \ | ssh -T agentrelay@100.104.148.105 'cd /infra && make -s local-google-oidc' ``` +**Another OIDC provider (for example Okta).** Pipe `{"issuer": "https://.okta.com", +"client_id": ..., "client_secret": ..., "display_name": "Okta"}` to `make local-oidc` +(the same command; it stores the same file). `ci/agent-relay/okta-e2e/browser.sh` +does this with a throwaway Okta app and users, and signs in with Playwright. + All generated database/service credentials stay in `.kind/local/credentials.json` (0600); never commit `.kind`. From 56a25e50d5f3ceb3cc91bdd0ece20bfc330f4d8b Mon Sep 17 00:00:00 2001 From: Khaliq Date: Mon, 30 Nov 2026 19:22:44 -0800 Subject: [PATCH 3/9] fix(kind): local stack names its own HoopDb owner Secret for databaseGuard make local-up failed at the first agent-relay helm upgrade since the render-time databaseGuard (#552): the worker's migrations.hoopdb still came from values-kind-core (Secret kind-pipeline), which this recipe never creates. Point it at local-pipeline-owner/url, the HoopDb owner login the recipe already uses for its migrations. Verified with a fresh make local-up on amd64 Linux (LOCAL_RELAYCAST_BACKEND=postgres); test_local_stack 40/40. Co-Authored-By: Claude Opus 5.5 --- ci/agent-relay/kind/local_stack.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ci/agent-relay/kind/local_stack.py b/ci/agent-relay/kind/local_stack.py index 8b583c47..027ae625 100644 --- a/ci/agent-relay/kind/local_stack.py +++ b/ci/agent-relay/kind/local_stack.py @@ -424,6 +424,10 @@ def values(self, phase, tenant=None): for slot, producer in (("ingestEdge", "ingest"), ("nativeConsumer", "consumer"), ("sessionReadApi", "reader")): result["sessions-pipeline"][slot]["analytics"] = analytics(producer) worker = result["sessions-pipeline"]["worker"] + # The HoopDb owner login is local-pipeline-owner (this recipe runs the + # migrations); the kind-core profile's kind-pipeline Secret never + # exists here, and the chart's databaseGuard refuses a missing one. + worker.setdefault("migrations", {})["hoopdb"] = {"existingSecret": "local-pipeline-owner", "key": "url"} worker.update(image=image(PIPELINE), existingSecret="local-brief", hoopdb={"existingSecret": "local-brief", "key": "HOOPDB_URL"}, postgresCa={"enabled": True, "configMap": "local-ca", "key": "ca.crt", "sha256": self.ca_sha}, locker={"endpoint": "http://locker.agent-relay.svc.cluster.local:9000", "bucket": "locker", "region": "us-east-1"}, From 1471021a531f516616ee72647aaa8ef05927d54e Mon Sep 17 00:00:00 2001 From: Khaliq Date: Mon, 30 Nov 2026 19:29:06 -0800 Subject: [PATCH 4/9] fix(okta-e2e): browser phase waits for Control, reads the session in-page, handles early Okta refusal - browser.sh: retry login-config for up to 3 minutes after the reconcile, with pod status and the last log lines on timeout. - browser_signin.py: query the session with fetch() inside the page (the APIRequestContext bypasses Chromium's host mapping); a person not assigned to the app is refused after the identifier step, before any password field; screenshot and read the final page before any check navigates away; Control's refusal must show its message. Co-Authored-By: Claude Opus 5.5 --- ci/agent-relay/okta-e2e/browser.sh | 13 +++++- ci/agent-relay/okta-e2e/browser_signin.py | 56 ++++++++++++++--------- 2 files changed, 47 insertions(+), 22 deletions(-) diff --git a/ci/agent-relay/okta-e2e/browser.sh b/ci/agent-relay/okta-e2e/browser.sh index 4b6029ca..fdfe09de 100755 --- a/ci/agent-relay/okta-e2e/browser.sh +++ b/ci/agent-relay/okta-e2e/browser.sh @@ -135,7 +135,18 @@ if grep -q -F -f <(jq -r .client_secret "$OIDC_FILE") "$WORK/oidc.log"; then fai ok "local stack reconciled with the Okta app (allowed domain $DOMAIN)" EDGE="${LOCAL_EDGE:-127.0.0.1}" -cfg="$(curl -fsS -k --resolve "relay.kind.agentrelay.com:443:$EDGE" "$SITE/cloud/api/v1/auth/login-config")" +KCTL=(kubectl --kubeconfig "$STATE/kubeconfig" -n agent-relay) +cfg= +for _ in $(seq 36); do # Control may still be rolling out after the reconcile + cfg="$(curl -fsS -k --resolve "relay.kind.agentrelay.com:443:$EDGE" "$SITE/cloud/api/v1/auth/login-config" 2>/dev/null)" && + jq -e '.oidc.displayName' <<<"$cfg" >/dev/null && break + sleep 5 +done +if ! jq -e '.oidc.displayName' <<<"${cfg:-null}" >/dev/null 2>&1; then + "${KCTL[@]}" get pods -l app.kubernetes.io/name=relay-control -o wide >&2 || true + "${KCTL[@]}" logs deployment/relay-control --tail=25 2>&1 | grep -v -i -e secret -e token >&2 || true + fail "login-config never offered OIDC: ${cfg:-no response}" +fi jq -e '.oidc.displayName == "Okta"' <<<"$cfg" >/dev/null || fail "login-config: $(jq -c '{methods, oidc}' <<<"$cfg")" ok "login-config offers Okta ($(jq -c '{methods, oidc}' <<<"$cfg"))" diff --git a/ci/agent-relay/okta-e2e/browser_signin.py b/ci/agent-relay/okta-e2e/browser_signin.py index 1ba8a544..9ba61a2e 100755 --- a/ci/agent-relay/okta-e2e/browser_signin.py +++ b/ci/agent-relay/okta-e2e/browser_signin.py @@ -30,7 +30,12 @@ def okta_sign_in(page, email, password): if page.locator('input[name="identifier"]').count(): page.fill('input[name="identifier"]', email) page.locator('input[type="submit"], button[type="submit"]').first.click() - page.wait_for_selector('input[name="credentials.passcode"], input[type="password"]', timeout=30000) + # A person not assigned to the app is refused right after the identifier. + secret_box = page.locator('input[name="credentials.passcode"], input[type="password"]') + refused = page.get_by_text(re.compile("not assigned to the client application|not allowed to access this app", re.I)) + secret_box.or_(refused).first.wait_for(timeout=30000) + if not secret_box.count(): + return page.fill('input[name="credentials.passcode"], input[type="password"]', password) else: page.fill('input[name="username"], #okta-signin-username', email) @@ -38,19 +43,27 @@ def okta_sign_in(page, email, password): page.locator('input[type="submit"], button[type="submit"]').first.click() +def fetch_status(page, path): + """GET from inside the page: the browser's host mapping and cookies apply + (page.request would bypass the --host-resolver-rules mapping).""" + if urlsplit(page.url).hostname != HOST: + page.goto(SITE + "/login", wait_until="domcontentloaded") + return page.evaluate("""async (path) => { + const r = await fetch(path, {credentials: "include", headers: {accept: "application/json"}}); + let body = {}; try { body = await r.json(); } catch (e) {} + return [r.status, body]; + }""", path) + + def session(page): - response = page.request.get(SITE + "/cloud/api/auth/session") - try: - body = response.json() - except Exception: - body = {} - return response.status, body + return fetch_status(page, "/cloud/api/auth/session") def run_case(browser, case): context = browser.new_context(ignore_https_errors=True) page = context.new_page() result = {"case": case["name"], "expect": case["expect"]} + shot = False callbacks = [] # query keys (never values) of each OIDC callback the browser reached page.on("framenavigated", lambda f: f == page.main_frame and urlsplit(f.url).path == "/login/oidc/callback" and callbacks.append(sorted(re.findall(r"(?:^|&)([^=&]+)=", urlsplit(f.url).query)) @@ -71,29 +84,30 @@ def run_case(browser, case): pass final = urlsplit(page.url) result["finalHost"], result["finalPath"] = final.hostname, final.path + # Evidence of where the person ended up, before any check navigates away. + page.screenshot(path=EVIDENCE + "/" + case["name"] + ".png", full_page=True) + shot = True + text = page.inner_text("body")[:4000] + if final.hostname != HOST: + m = re.search(r"(not allowed to access this app|not assigned to the client application)", text, re.I) + result["oktaMessage"] = m.group(0) if m else None + else: + m = re.search(r"[^\n]{0,80}(can't sign in|cannot sign in|not allowed|not permitted)[^\n]{0,80}", text, re.I) + result["siteMessage"] = m.group(0).strip() if m else None status, body = session(page) result["sessionStatus"] = status if status == 200: result["email"] = body.get("user", {}).get("email") result["role"] = body.get("currentOrganization", {}).get("role") result["organization"] = body.get("currentOrganization", {}).get("name") - result["organizationId"] = body.get("currentOrganization", {}).get("id") - org = result["organizationId"] + org = body.get("currentOrganization", {}).get("id") if org: - usage = page.request.get(SITE + "/cloud/api/v1/organizations/" + org + "/usage?days=7") - result["usageStatus"] = usage.status # owner-only: a member gets 403 - text = page.inner_text("body")[:4000] - if final.hostname != HOST: - m = re.search(r"(not allowed to access this app|not assigned to the client application|" - r"access to this application|not allowed)", text, re.I) - result["oktaMessage"] = m.group(0) if m else None - else: - m = re.search(r"(not allowed|isn't allowed|not permitted|domain|couldn't sign you in|sign-in failed|error)[^\n]{0,120}", text, re.I) - result["siteMessage"] = m.group(0) if m else None + result["usageStatus"] = fetch_status(page, "/cloud/api/v1/organizations/" + org + "/usage?days=7")[0] # owner-only except Exception as error: # noqa: BLE001 - report every case result["error"] = type(error).__name__ + ": " + str(error).splitlines()[0][:300] finally: - page.screenshot(path=EVIDENCE + "/" + case["name"] + ".png", full_page=True) + if not shot: + page.screenshot(path=EVIDENCE + "/" + case["name"] + ".png", full_page=True) context.close() result["callbacks"] = callbacks denied_at_okta = (result.get("finalHost") != HOST and bool(result.get("oktaMessage"))) or any( @@ -109,7 +123,7 @@ def run_case(browser, case): elif e == "control_refused": # Okta authenticated the person (a code came back); Control refused the session. result["pass"] = (result.get("sessionStatus") == 401 and result.get("finalHost") == HOST - and "error" not in result and code_returned) + and "error" not in result and code_returned and bool(result.get("siteMessage"))) else: result["pass"] = False return result From 7c87f69391d37e354b41685856c49ee66f247445 Mon Sep 17 00:00:00 2001 From: Khaliq Date: Mon, 30 Nov 2026 19:45:16 -0800 Subject: [PATCH 5/9] fix(okta-e2e): address review: cluster ownership, honest cleanup, TLS pinning, exact refusals kind.sh - Reuse or delete only a cluster this harness created (owner ConfigMap in kube-system); refuse any other existing cluster before changing anything. - Live cleanup failures fail the run and name what to remove by hand; bash 3.2-safe empty-array expansion. - Console and turn-off commands are extracted from the published guide (OKTA_GUIDE) and run as published, so the fixture can't drift; also checks the patch file is gone and the backup is deleted. - The oidcClientSecret-without-oidc render must fail for that reason. - OKTA_LIVE_ORG must be https before the token is used. browser.sh / browser_signin.py - No blanket ignore_https_errors: Chromium skips certificate checks only for the local Kind CA and leaf keys (SPKI pins); Okta keeps full TLS checks. - Restore failure (and any cleanup failure) fails the run; the restore log is kept in .kind/local; screenshots persist under .kind/local/okta-e2e-evidence. - login-config waits until it offers Okta, not any provider. - verdict() is a pure function; the other-domain case requires Control's exact message naming the rejected and allowed domains. test_browser_signin covers generic refusals, wrong domains, no code from Okta, null email. - A failed screenshot no longer aborts the remaining cases. mock_okta.py: malformed bodies are logged and answered 400. local_stack.py: validate a new OIDC client before replacing the stored one; keep the issuer exactly as given; only port 443 (what the egress opens); Google's client-id check applies to either issuer spelling; display_name must be a string. The Okta unit case renders the chart. docs: the local-oidc example is valid JSON. Co-Authored-By: Claude Opus 5.5 --- ci/agent-relay/kind/local_stack.py | 39 +++++--- ci/agent-relay/kind/test_local_stack.py | 45 ++++++++- ci/agent-relay/okta-e2e/browser.sh | 39 +++++--- ci/agent-relay/okta-e2e/browser_signin.py | 94 ++++++++++++------- ci/agent-relay/okta-e2e/kind.sh | 83 +++++++++++----- ci/agent-relay/okta-e2e/mock_okta.py | 19 +++- .../okta-e2e/test_browser_signin.py | 55 +++++++++++ docs/local-development.md | 2 +- 8 files changed, 282 insertions(+), 94 deletions(-) create mode 100644 ci/agent-relay/okta-e2e/test_browser_signin.py diff --git a/ci/agent-relay/kind/local_stack.py b/ci/agent-relay/kind/local_stack.py index 027ae625..273c7259 100644 --- a/ci/agent-relay/kind/local_stack.py +++ b/ci/agent-relay/kind/local_stack.py @@ -476,19 +476,7 @@ def google_oidc(self): path = state / "google-oidc.json" if state else None if path is None or not path.exists(): return None - value = json.loads(path.read_text()) - issuer = value.get("issuer") or GOOGLE_ISSUER - if not (isinstance(issuer, str) and re.fullmatch(r"https://[^?#@\s]+", issuer)): - raise StackError(str(path) + " issuer must be an https URL") - google = issuer == GOOGLE_ISSUER - if not (isinstance(value.get("client_id"), str) and value["client_id"] - and (not google or value["client_id"].endswith(".apps.googleusercontent.com")) - and isinstance(value.get("client_secret"), str) and value["client_secret"]): - raise StackError(str(path) + " must hold a " + ("Google web " if google else "") + "client_id and client_secret") - value["issuer"] = issuer.rstrip("/") - value.setdefault("display_name", "Google" if google else "single sign-on") - value.setdefault("allowed_domains", ["agentrelay.com"]) - return value + return oidc_client(json.loads(path.read_text()), str(path)) def google_oidc_egress(self): selector = {"app.kubernetes.io/name": "relay-control", "app.kubernetes.io/instance": "agent-relay", @@ -508,8 +496,9 @@ def install_google_oidc(self): domains = [d.strip() for d in os.environ.get("LOCAL_OIDC_ALLOWED_DOMAINS", "agentrelay.com").split(",") if d.strip()] value = {"client_id": raw.get("client_id", ""), "client_secret": raw.get("client_secret", ""), "allowed_domains": domains} value.update({k: raw[k] for k in ("issuer", "display_name") if raw.get(k)}) + # Validate before replacing a working stored client. + label = oidc_client(dict(value), "the client JSON")["display_name"] private_json(self.state / "google-oidc.json", value) - label = self.google_oidc()["display_name"] # validate before spending a reconcile print(label + " sign-in stored (0600; allowed domains: " + ", ".join(domains) + "). Reconciling the local stack...", flush=True) self.up_local() print("Register " + SITE + "/login/oidc/callback as an authorized redirect URI on that client, " @@ -892,6 +881,28 @@ def pgurl(role, credentials, ca, database="hoopdb"): + "?sslmode=verify-full" + ("&sslrootcert=" + ca if ca else "")) +def oidc_client(value, where): + """Validate a stored OIDC client; Google unless it names an https issuer. + + The issuer is kept exactly as given: Control compares it with the + provider's published issuer, which may end in "/". It must use the default + https port, the only one the local OIDC egress policy opens.""" + issuer = value.get("issuer") or GOOGLE_ISSUER + if not (isinstance(issuer, str) and re.fullmatch(r"https://[^/:?#@\s]+(:443)?(/[^?#@\s]*)?", issuer)): + raise StackError(where + ": issuer must be an https URL on port 443, without query, fragment or credentials") + google = issuer.rstrip("/") == GOOGLE_ISSUER # either spelling gets Google's client-id check + if not (isinstance(value.get("client_id"), str) and value["client_id"] + and (not google or value["client_id"].endswith(".apps.googleusercontent.com")) + and isinstance(value.get("client_secret"), str) and value["client_secret"]): + raise StackError(where + " must hold a " + ("Google web " if google else "") + "client_id and client_secret") + if "display_name" in value and not (isinstance(value["display_name"], str) and value["display_name"].strip()): + raise StackError(where + ": display_name must be a non-empty string") + value["issuer"] = issuer + value.setdefault("display_name", "Google" if google else "single sign-on") + value.setdefault("allowed_domains", ["agentrelay.com"]) + return value + + def locker_env(): return [env("LOCKER_BUCKET", "locker"), env("LOCKER_ENDPOINT", "http://locker.agent-relay.svc.cluster.local:9000"), env("LOCKER_REGION", "us-east-1"), env("ALLOW_IN_CLUSTER_HTTP", "true"), diff --git a/ci/agent-relay/kind/test_local_stack.py b/ci/agent-relay/kind/test_local_stack.py index 63f3fe1f..3abe8d07 100644 --- a/ci/agent-relay/kind/test_local_stack.py +++ b/ci/agent-relay/kind/test_local_stack.py @@ -532,7 +532,7 @@ def test_real_final_render_has_exact_core_roles_without_inline_credentials(self) with patch.multiple(local_stack, DESKTOP_RELEASES=False, CONTROL=control, WEBAPP=webapp): self.assert_final_render(experimental=False) - def test_google_oidc_renders_control_sign_in_and_egress_only_when_stored(self): + def test_oidc_renders_control_sign_in_and_egress_only_when_stored(self): control, webapp = local_stack.profile_images(False) with tempfile.TemporaryDirectory() as tmp, patch.multiple(local_stack, DESKTOP_RELEASES=False, CONTROL=control, WEBAPP=webapp): stack = LocalStack.__new__(LocalStack) @@ -570,12 +570,47 @@ def test_google_oidc_renders_control_sign_in_and_egress_only_when_stored(self): (stack.state / "google-oidc.json").write_text(json.dumps({"issuer": "https://example.okta.com/", "client_id": "0oaexample", "client_secret": "not-a-real-secret", "display_name": "Okta", "allowed_domains": ["example.com"]})) - oidc = stack.values("serve", tenant)["relay-control"]["auth"]["oidc"] - self.assertEqual((oidc["issuer"], oidc["clientId"], oidc["displayName"]), ("https://example.okta.com", "0oaexample", "Okta")) - (stack.state / "google-oidc.json").write_text(json.dumps({"issuer": "http://example.okta.com", - "client_id": "0oaexample", "client_secret": "x"})) + okta_values = stack.values("serve", tenant) + oidc = okta_values["relay-control"]["auth"]["oidc"] + # Kept exactly: Control compares it with the provider's published issuer. + self.assertEqual((oidc["issuer"], oidc["clientId"], oidc["displayName"]), ("https://example.okta.com/", "0oaexample", "Okta")) + result = subprocess.run(["helm", "template", "agent-relay", "charts/agent-relay", "-n", "agent-relay", "-f", "-", "--is-upgrade"], + cwd=ROOT, input=json.dumps(okta_values), capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertNotIn("not-a-real-secret", result.stdout) + api = next(d for d in yaml.safe_load_all(result.stdout) if d and d["kind"] == "Deployment" and d["metadata"]["name"] == "relay-control") + names = {e["name"]: e.get("value") for c in api["spec"]["template"]["spec"]["containers"] for e in c.get("env", [])} + self.assertEqual((names["SELFHOST_OIDC_ISSUER"], names["SELFHOST_OIDC_CLIENT_ID"], names["SELFHOST_OIDC_DISPLAY_NAME"]), + ("https://example.okta.com/", "0oaexample", "Okta")) + self.assertEqual(names["SELFHOST_OIDC_ALLOWED_DOMAINS"], "example.com") + self.assertIn("SELFHOST_OIDC_CLIENT_SECRET_FILE", names) + (stack.state / "google-oidc.json").write_text(json.dumps({"issuer": "https://accounts.google.com/", + "client_id": "not-google", "client_secret": "x"})) + with self.assertRaises(local_stack.StackError): + stack.google_oidc() # Google's client-id check applies with a trailing slash too + (stack.state / "google-oidc.json").write_text(json.dumps({"issuer": "https://example.okta.com", + "client_id": "0oa", "client_secret": "x", "display_name": 7})) with self.assertRaises(local_stack.StackError): stack.google_oidc() + for bad in ("http://example.okta.com", "https://example.okta.com:8443", "https://u:p@example.okta.com"): + (stack.state / "google-oidc.json").write_text(json.dumps({"issuer": bad, "client_id": "0oaexample", "client_secret": "x"})) + with self.assertRaises(local_stack.StackError): + stack.google_oidc() + + def test_oidc_install_rejects_bad_client_without_replacing_the_stored_one(self): + with tempfile.TemporaryDirectory() as tmp: + stack = LocalStack.__new__(LocalStack) + stack.state = Path(tmp) + stored = stack.state / "google-oidc.json" + good = {"client_id": "1-x.apps.googleusercontent.com", "client_secret": "kept", "allowed_domains": ["agentrelay.com"]} + stored.write_text(json.dumps(good)) + bad = json.dumps({"issuer": "http://example.okta.com", "client_id": "0oa", "client_secret": "x"}) + with patch.object(stack, "docker"), patch.object(stack, "owned"), patch.object(stack, "up_local") as up, \ + patch.object(local_stack.sys, "stdin", io.StringIO(bad)): + with self.assertRaises(local_stack.StackError): + stack.install_google_oidc() + up.assert_not_called() + self.assertEqual(json.loads(stored.read_text()), good) def test_google_oidc_secret_reconciles_when_control_bootstrap_is_cached(self): with tempfile.TemporaryDirectory() as tmp: diff --git a/ci/agent-relay/okta-e2e/browser.sh b/ci/agent-relay/okta-e2e/browser.sh index fdfe09de..54b02ccf 100755 --- a/ci/agent-relay/okta-e2e/browser.sh +++ b/ci/agent-relay/okta-e2e/browser.sh @@ -34,6 +34,7 @@ HERE="$ROOT/ci/agent-relay/okta-e2e" : "${OKTA_LIVE_ORG:?set OKTA_LIVE_ORG}" "${OKTA_TOKEN_CMD:?set OKTA_TOKEN_CMD}" PY="${PLAYWRIGHT_PYTHON:-python3}" ORG="${OKTA_LIVE_ORG%/}" +[[ "$ORG" =~ ^https://[^/?#@]+$ ]] || { echo "OKTA_LIVE_ORG must be https:// (the API token is never sent over plain http)" >&2; exit 1; } SITE=https://relay.kind.agentrelay.com DOMAIN="${OKTA_E2E_DOMAIN:-example.com}" STATE="$ROOT/.kind/local" @@ -41,7 +42,8 @@ STATE="$ROOT/.kind/local" "$PY" -c 'import playwright' 2>/dev/null || { echo "$PY has no playwright (set PLAYWRIGHT_PYTHON)" >&2; exit 1; } RUN_ID="okta-e2e-$(date +%Y%m%d%H%M%S)-$(openssl rand -hex 3)" WORK="$(mktemp -d "${TMPDIR:-/tmp}/ar-okta-browser.XXXXXX")"; chmod 700 "$WORK" -EVIDENCE="${EVIDENCE_DIR:-$WORK/evidence}"; mkdir -p "$EVIDENCE" +# Screenshots outlive the run (they hold no credentials); $WORK is removed on exit. +EVIDENCE="${EVIDENCE_DIR:-$STATE/okta-e2e-evidence/$RUN_ID}"; mkdir -p "$EVIDENCE" pass=0 ok() { pass=$((pass + 1)); printf 'ok %d - %s\n' "$pass" "$*"; } fail() { printf 'not ok - %s\n' "$*" >&2; exit 1; } @@ -49,7 +51,9 @@ CLEANUP=() OIDC_FILE="$STATE/google-oidc.json" cleanup() { local rc=$? i - for ((i = ${#CLEANUP[@]} - 1; i >= 0; i--)); do eval "${CLEANUP[$i]}" || echo "# cleanup step failed: ${CLEANUP[$i]%% *}" >&2; done + for ((i = ${#CLEANUP[@]} - 1; i >= 0; i--)); do + eval "${CLEANUP[$i]}" || { echo "not ok - cleanup step failed: ${CLEANUP[$i]%% *}" >&2; [ "$rc" != 0 ] || rc=1; } + done rm -rf "$WORK" exit "$rc" } @@ -122,8 +126,16 @@ if [ -f "$OIDC_FILE" ]; then cp -p "$OIDC_FILE" "$WORK/oidc.prev"; fi restore_oidc() { [ "${KEEP_OIDC:-0}" = 1 ] && { echo "# KEEP_OIDC=1: the stack still points at the deleted app"; return 0; } if [ -f "$WORK/oidc.prev" ]; then cp -p "$WORK/oidc.prev" "$OIDC_FILE"; else rm -f "$OIDC_FILE"; fi - make -s local-up > "$WORK/restore.log" 2>&1 && echo "# cleanup: local stack OIDC setting restored" || - { echo "# cleanup: make local-up failed restoring OIDC; see below" >&2; tail -5 "$WORK/restore.log" >&2; } + local log="$STATE/okta-e2e-restore.log" + if make -s local-up > "$log" 2>&1; then + echo "# cleanup: local stack OIDC setting restored"; rm -f "$log" + else + # The stack may still point at the test app, which is deleted next: fail + # the run and keep the log (outside $WORK, which is removed). + echo "not ok - restoring the stack's OIDC setting failed; log kept at $log; rerun make local-up" >&2 + tail -5 "$log" >&2 + return 1 + fi } CLEANUP+=("restore_oidc") jq -n --arg i "$ORG" --arg c "$CLIENT_ID" --rawfile s "$WORK/client-secret" \ @@ -137,26 +149,29 @@ ok "local stack reconciled with the Okta app (allowed domain $DOMAIN)" EDGE="${LOCAL_EDGE:-127.0.0.1}" KCTL=(kubectl --kubeconfig "$STATE/kubeconfig" -n agent-relay) cfg= -for _ in $(seq 36); do # Control may still be rolling out after the reconcile +for _ in $(seq 36); do # Control may still be rolling out (or serving the previous provider) cfg="$(curl -fsS -k --resolve "relay.kind.agentrelay.com:443:$EDGE" "$SITE/cloud/api/v1/auth/login-config" 2>/dev/null)" && - jq -e '.oidc.displayName' <<<"$cfg" >/dev/null && break + jq -e '.oidc.displayName == "Okta"' <<<"$cfg" >/dev/null && break sleep 5 done -if ! jq -e '.oidc.displayName' <<<"${cfg:-null}" >/dev/null 2>&1; then +if ! jq -e '.oidc.displayName == "Okta"' <<<"${cfg:-null}" >/dev/null 2>&1; then "${KCTL[@]}" get pods -l app.kubernetes.io/name=relay-control -o wide >&2 || true "${KCTL[@]}" logs deployment/relay-control --tail=25 2>&1 | grep -v -i -e secret -e token >&2 || true - fail "login-config never offered OIDC: ${cfg:-no response}" + fail "login-config never offered Okta: ${cfg:-no response}" fi -jq -e '.oidc.displayName == "Okta"' <<<"$cfg" >/dev/null || fail "login-config: $(jq -c '{methods, oidc}' <<<"$cfg")" ok "login-config offers Okta ($(jq -c '{methods, oidc}' <<<"$cfg"))" # --- browser ------------------------------------------------------------------------- +# Chromium skips certificate checks only for the local edge's own keys (the +# Kind CA and its leaf); Okta and every other host keep full TLS checks. +spki() { openssl x509 -in "$1" -noout -pubkey | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | base64; } +PINS="$(spki "$STATE/ca.crt"),$(spki "$STATE/tls.crt")" ( umask 077 - jq -n --arg site "$SITE" --arg edge "$EDGE" \ + jq -n --arg site "$SITE" --arg edge "$EDGE" --arg pins "$PINS" --arg allowed "$DOMAIN" \ --arg me "$(cut -d' ' -f2 "$WORK/member.user")" --rawfile mp "$WORK/member.pw" \ --arg oe "$(cut -d' ' -f2 "$WORK/outsider.user")" --rawfile op "$WORK/outsider.pw" \ --arg de "$(cut -d' ' -f2 "$WORK/otherdom.user")" --rawfile dp "$WORK/otherdom.pw" \ - '{site: $site, edge: $edge, cases: [ + '{site: $site, edge: $edge, spki: $pins, allowedDomain: $allowed, cases: [ {name: "member", email: $me, password: $mp, expect: "member"}, {name: "outsider", email: $oe, password: $op, expect: "okta_refused"}, {name: "otherdom", email: $de, password: $dp, expect: "control_refused"}]}' > "$WORK/cases.json" ) @@ -171,5 +186,5 @@ while read -r line; do else echo "not ok - browser: $name -> $(jq -c 'del(.case, .pass)' <<<"$line")" >&2; fi done < "$WORK/browser.out" [ "$brc" = 0 ] || fail "browser cases failed (screenshots: $EVIDENCE) $(tail -3 "$WORK/browser.err")" -[ -n "${EVIDENCE_DIR:-}" ] && echo "# screenshots: $EVIDENCE" +echo "# screenshots: $EVIDENCE" echo "1..$pass" diff --git a/ci/agent-relay/okta-e2e/browser_signin.py b/ci/agent-relay/okta-e2e/browser_signin.py index 9ba61a2e..c460b361 100755 --- a/ci/agent-relay/okta-e2e/browser_signin.py +++ b/ci/agent-relay/okta-e2e/browser_signin.py @@ -15,13 +15,10 @@ import sys from urllib.parse import urlsplit -from playwright.sync_api import TimeoutError as PlaywrightTimeout -from playwright.sync_api import sync_playwright - -CASES, EVIDENCE = sys.argv[1], sys.argv[2] -config = json.load(open(CASES)) -SITE = config["site"].rstrip("/") -HOST = urlsplit(SITE).hostname +# Set by main(); verdict() is pure so test_browser_signin.py can run it +# without Playwright or a browser. +SITE = HOST = EVIDENCE = None +config = {} def okta_sign_in(page, email, password): @@ -59,8 +56,32 @@ def session(page): return fetch_status(page, "/cloud/api/auth/session") +def verdict(case, result, host, allowed_domain): + """Does this case's observed result match its expectation?""" + denied_at_okta = (result.get("finalHost") != host and bool(result.get("oktaMessage"))) or any( + "error=access_denied" in c for c in result.get("callbacks", [])) + code_returned = any("code" in c for c in result.get("callbacks", [])) + e = case["expect"] + if e == "member": + ok = (result.get("sessionStatus") == 200 and (result.get("email") or "").lower() == case["email"].lower() + and result.get("role") == "member" and result.get("usageStatus") == 403 + and result.get("finalHost") == host) + elif e == "okta_refused": + ok = result.get("sessionStatus") == 401 and "error" not in result and denied_at_okta and not code_returned + elif e == "control_refused": + # Okta authenticated the person (a code came back); Control refused the session. + # Control's domain refusal, naming this person's domain and the allowed one. + rejected = case["email"].rsplit("@", 1)[1] + want = "Accounts from " + rejected + " can't sign in here. Use your " + allowed_domain + " account." + ok = (result.get("sessionStatus") == 401 and result.get("finalHost") == host + and "error" not in result and code_returned and want in (result.get("siteMessage") or "")) + else: + ok = False + return ok + + def run_case(browser, case): - context = browser.new_context(ignore_https_errors=True) + context = browser.new_context() # TLS errors are ignored only for the pinned local keys page = context.new_page() result = {"case": case["name"], "expect": case["expect"]} shot = False @@ -80,8 +101,9 @@ def run_case(browser, case): try: page.wait_for_url(lambda u: urlsplit(u).hostname == HOST, timeout=45000) page.wait_for_load_state("networkidle") - except PlaywrightTimeout: - pass + except Exception as wait_error: # Playwright's TimeoutError: stopped at Okta + if type(wait_error).__name__ != "TimeoutError": + raise final = urlsplit(page.url) result["finalHost"], result["finalPath"] = final.hostname, final.path # Evidence of where the person ended up, before any check navigates away. @@ -92,7 +114,8 @@ def run_case(browser, case): m = re.search(r"(not allowed to access this app|not assigned to the client application)", text, re.I) result["oktaMessage"] = m.group(0) if m else None else: - m = re.search(r"[^\n]{0,80}(can't sign in|cannot sign in|not allowed|not permitted)[^\n]{0,80}", text, re.I) + # The visible refusal text (verdict() requires Control's exact domain message). + m = re.search(r"[^\n]{0,160}(can't sign in|cannot sign in|not allowed|not permitted)[^\n]{0,160}", text, re.I) result["siteMessage"] = m.group(0).strip() if m else None status, body = session(page) result["sessionStatus"] = status @@ -107,33 +130,32 @@ def run_case(browser, case): result["error"] = type(error).__name__ + ": " + str(error).splitlines()[0][:300] finally: if not shot: - page.screenshot(path=EVIDENCE + "/" + case["name"] + ".png", full_page=True) + try: + page.screenshot(path=EVIDENCE + "/" + case["name"] + ".png", full_page=True) + except Exception: # noqa: BLE001 - evidence must not replace the case result + pass context.close() result["callbacks"] = callbacks - denied_at_okta = (result.get("finalHost") != HOST and bool(result.get("oktaMessage"))) or any( - "error=access_denied" in c for c in callbacks) - code_returned = any("code" in c for c in callbacks) - e = case["expect"] - if e == "member": - result["pass"] = (result.get("sessionStatus") == 200 and result.get("email", "").lower() == case["email"].lower() - and result.get("role") == "member" and result.get("usageStatus") == 403 - and result.get("finalHost") == HOST) - elif e == "okta_refused": - result["pass"] = result.get("sessionStatus") == 401 and "error" not in result and denied_at_okta and not code_returned - elif e == "control_refused": - # Okta authenticated the person (a code came back); Control refused the session. - result["pass"] = (result.get("sessionStatus") == 401 and result.get("finalHost") == HOST - and "error" not in result and code_returned and bool(result.get("siteMessage"))) - else: - result["pass"] = False + result["pass"] = verdict(case, result, HOST, config["allowedDomain"]) return result -with sync_playwright() as p: - edge = config.get("edge", "127.0.0.1") - browser = p.chromium.launch(args=["--host-resolver-rules=MAP " + HOST + " " + edge]) - results = [run_case(browser, c) for c in config["cases"]] - browser.close() -for r in results: - print(json.dumps(r, sort_keys=True)) -sys.exit(0 if all(r["pass"] for r in results) else 1) +def main(): + global SITE, HOST, EVIDENCE, config + from playwright.sync_api import sync_playwright + config = json.load(open(sys.argv[1])) + EVIDENCE = sys.argv[2] + SITE = config["site"].rstrip("/") + HOST = urlsplit(SITE).hostname + with sync_playwright() as p: + browser = p.chromium.launch(args=["--host-resolver-rules=MAP " + HOST + " " + config.get("edge", "127.0.0.1"), + "--ignore-certificate-errors-spki-list=" + config["spki"]]) + results = [run_case(browser, c) for c in config["cases"]] + browser.close() + for r in results: + print(json.dumps(r, sort_keys=True)) + sys.exit(0 if all(r["pass"] for r in results) else 1) + + +if __name__ == "__main__": + main() diff --git a/ci/agent-relay/okta-e2e/kind.sh b/ci/agent-relay/okta-e2e/kind.sh index 8f6bf566..df827e40 100755 --- a/ci/agent-relay/okta-e2e/kind.sh +++ b/ci/agent-relay/okta-e2e/kind.sh @@ -10,6 +10,9 @@ # ci/agent-relay/okta-e2e/kind.sh # adds the live-Okta phase # # Phases: +# OKTA_GUIDE (default: the published okta-sso.md) supplies the console and +# "turn it off" commands, which run exactly as published. +# # mock okta-setup.sh against mock_okta.py (a stateful stand-in for the Okta # API). Proves that it writes ONE key, oidc-client-secret, with a merge # patch, and keeps every other key, including keys that exist only in @@ -46,11 +49,16 @@ fail() { printf 'not ok - %s\n' "$*" >&2; exit 1; } k() { kubectl --context "$CTX" -n "$NS" "$@"; } MOCK_PID= LIVE_CLEANUP=() +CREATED=0 # delete only a cluster this run created +OWNER_MARK=okta-e2e-owner # ConfigMap in kube-system on clusters this harness created cleanup() { - local rc=$? - for c in "${LIVE_CLEANUP[@]}"; do eval "$c" || echo "cleanup step failed: ${c%% *}" >&2; done + local rc=$? c + # Every step runs; any failure fails the run (bash 3.2-safe empty expansion). + for c in ${LIVE_CLEANUP[@]+"${LIVE_CLEANUP[@]}"}; do + eval "$c" || { echo "not ok - live cleanup failed, remove by hand in Okta: $c" | sed 's/live -X [A-Z]* //g' >&2; [ "$rc" != 0 ] || rc=1; } + done [ -z "$MOCK_PID" ] || kill "$MOCK_PID" 2>/dev/null || true - [[ "${KEEP_CLUSTER:-0}" == 1 ]] || kind delete cluster --name "$CLUSTER" >/dev/null 2>&1 || true + if [[ "$CREATED" == 1 && "${KEEP_CLUSTER:-0}" != 1 ]]; then kind delete cluster --name "$CLUSTER" >/dev/null 2>&1 || true; fi rm -rf "$WORK" exit "$rc" } @@ -71,9 +79,36 @@ fi grep -q -- '--type merge' "$WORK/okta-setup.sh" || fail "okta-setup.sh does not use a merge patch (published copy predates agentrelay.com#356?)" +# --- the guide's own commands ---------------------------------------------------- +# The console and "turn it off" blocks of okta-sso.md, run as published so this +# test can't drift from the docs. OKTA_GUIDE: a URL or a local path. +GUIDE="${OKTA_GUIDE:-https://agentrelay.com/docs/self-hosting/okta-sso.md}" +if [ -f "$GUIDE" ]; then cp "$GUIDE" "$WORK/guide.md"; else curl -fsSL "$GUIDE" -o "$WORK/guide.md"; fi +python3 -I - "$WORK/guide.md" "$WORK" <<'EOF' || fail "could not find the console and turn-off blocks in $GUIDE" +import re, sys +text, out = open(sys.argv[1]).read(), sys.argv[2] +def block_after(marker): + at = text.index(marker) + return re.search(r"```sh\n(.*?)```", text[at:], re.S).group(1) +open(out + "/guide-console.sh", "w").write(block_after("Prefer the Okta console?")) +open(out + "/guide-off.sh", "w").write(block_after("To remove the stored secret")) +EOF +grep -q -- '--rawfile' "$WORK/guide-console.sh" || fail "guide console block has no --rawfile (stale guide?)" +echo "# guide commands from $GUIDE" + # --- cluster --------------------------------------------------------------- -kind get clusters 2>/dev/null | grep -qx "$CLUSTER" || kind create cluster --name "$CLUSTER" --wait 120s >/dev/null 2>&1 -kind get kubeconfig --name "$CLUSTER" > "$KUBECONFIG" +# Reuse only a cluster this harness created (and kept with KEEP_CLUSTER=1): +# the run deletes its agent-relay namespace, and may delete the cluster. +if kind get clusters 2>/dev/null | grep -qx "$CLUSTER"; then + kind get kubeconfig --name "$CLUSTER" > "$KUBECONFIG" + kubectl --context "$CTX" -n kube-system get configmap "$OWNER_MARK" >/dev/null 2>&1 || + fail "kind cluster $CLUSTER exists and was not created by this harness; set CLUSTER to another name (nothing was changed)" +else + kind create cluster --name "$CLUSTER" --wait 120s >/dev/null 2>&1 + CREATED=1 + kind get kubeconfig --name "$CLUSTER" > "$KUBECONFIG" + kubectl --context "$CTX" -n kube-system create configmap "$OWNER_MARK" --from-literal=by=ci/agent-relay/okta-e2e/kind.sh >/dev/null +fi kubectl --context "$CTX" delete namespace "$NS" --ignore-not-found --wait=true >/dev/null kubectl --context "$CTX" create namespace "$NS" >/dev/null ok "kind cluster $CLUSTER ready" @@ -164,31 +199,30 @@ grep -q 'already exists' "$WORK/setup.out" || fail "second-run message: $(tail - [ "$(key_value oidc-client-secret)" = "$MOCK_SECRET" ] || fail "second run changed the stored secret" ok "second run refused; nothing written" -# 5. The guide's console steps (okta-sso.md step 1, "Prefer the Okta console?"). +# 5. The guide's console steps (okta-sso.md step 1, "Prefer the Okta console?"), +# run exactly as published (extracted above), from a folder with a settings.sh. seed_secret -mkdir -p "$HOME/.agent-relay-install/secret-files/$SECRET" +mkdir -p "$HOME/.agent-relay-install/secret-files/$SECRET" "$WORK/install" +: > "$WORK/install/settings.sh" CONSOLE_SECRET="console-$(openssl rand -hex 16)" -printf '%s\n' "$CONSOLE_SECRET" | bash -c ' -set -euo pipefail -read -rs -p "Okta client secret: " X; echo -( umask 077; printf "%s" "$X" > ~/.agent-relay-install/secret-files/agent-relay-secrets/oidc-client-secret ) -P="$(mktemp)"; chmod 600 "$P" -jq -n --arg s "$X" "{data: {\"oidc-client-secret\": (\$s | @base64)}}" > "$P"; unset X -kubectl -n agent-relay patch secret agent-relay-secrets --type merge --patch-file "$P" -rm -f "$P" -kubectl -n agent-relay get secret agent-relay-secrets -o json | jq ".data | keys"' > "$WORK/console.out" 2>&1 || +( cd "$WORK/install" && printf '%s\n' "$CONSOLE_SECRET" | env -u NAMESPACE bash "$WORK/guide-console.sh" ) > "$WORK/console.out" 2>&1 || fail "console steps failed: $(tail -3 "$WORK/console.out")" [ "$(others)" = "$(cat "$WORK/seed.json")" ] || fail "console steps changed other keys" [ "$(key_value oidc-client-secret)" = "$CONSOLE_SECRET" ] || fail "console steps stored the wrong value" if grep -q "$CONSOLE_SECRET" "$WORK/console.out"; then fail "console steps printed the secret"; fi -ok "guide console steps: one-key merge patch, other keys unchanged, nothing printed" +grep -q '"oidc-client-secret"' "$WORK/console.out" || fail "console steps did not list the new key" +[ -z "$(find "${TMPDIR:-/tmp}" -maxdepth 1 -newer "$WORK/guide-console.sh" -name 'tmp.*' -user "$(id -u)" -exec grep -l "$(printf '%s' "$CONSOLE_SECRET" | base64)" {} + 2>/dev/null)" ] || + fail "console steps left the patch file behind" +ok "guide console steps (as published): one-key merge patch, other keys unchanged, nothing printed or left behind" -# 6. The guide's "turn it off": JSON-patch remove of just that key. -kubectl -n agent-relay patch secret agent-relay-secrets --type json \ - -p '[{"op":"remove","path":"/data/oidc-client-secret"}]' >/dev/null +# 6. The guide's "turn it off", as published: JSON-patch remove of just that +# key, then the backup copy. +( cd "$WORK/install" && env -u NAMESPACE bash "$WORK/guide-off.sh" ) > "$WORK/off.out" 2>&1 || + fail "turn-off steps failed: $(tail -3 "$WORK/off.out")" [ -z "$(key_value oidc-client-secret)" ] || fail "key still present" [ "$(k get secret "$SECRET" -o json | jq -S .data)" = "$(cat "$WORK/seed.json")" ] || fail "remove changed other keys" -ok "guide turn-off: JSON-patch remove dropped only oidc-client-secret" +[ ! -e "$HOME/.agent-relay-install/secret-files/$SECRET/oidc-client-secret" ] || fail "backup copy not deleted" +ok "guide turn-off (as published): JSON-patch remove dropped only oidc-client-secret, then the backup" # --- chart ------------------------------------------------------------------- # The exact lines okta-setup.sh printed, applied as the guide's step 2 says, on @@ -228,9 +262,11 @@ helm template t "$CHART" -f "$CHART/ci/default-values.yaml" -f "$WORK/off-values if grep -q -e SELFHOST_OIDC -e oidc-client-secret "$WORK/off.yaml"; then fail "turn-off values still render OIDC"; fi ok "chart: with oidc, autoJoinDomains and oidcClientSecret removed, nothing OIDC renders" jq '.secretKeys = {"oidcClientSecret": "oidc-client-secret"} | del(.auth.oidc)' "$WORK/okta-values.json" > "$WORK/half.json" -if helm template t "$CHART" -f "$CHART/ci/default-values.yaml" -f "$WORK/half.json" >/dev/null 2>&1; then +if half_out="$(helm template t "$CHART" -f "$CHART/ci/default-values.yaml" -f "$WORK/half.json" 2>&1)"; then fail "chart accepted oidcClientSecret without auth.oidc (the guide says to remove both)" fi +grep -q 'secretKeys.oidcClientSecret is set but auth.oidc.issuer is empty' <<<"$half_out" || + fail "chart refused for another reason: $(tail -2 <<<"$half_out")" ok "chart: oidcClientSecret left behind without oidc: is refused, as the guide warns" # --- live Okta ----------------------------------------------------------------- @@ -239,6 +275,7 @@ if [ -z "${OKTA_LIVE_ORG:-}" ] || [ -z "${OKTA_TOKEN_CMD:-}" ]; then echo "1..$pass"; exit 0 fi ORG="${OKTA_LIVE_ORG%/}" +[[ "$ORG" =~ ^https://[^/?#@]+$ ]] || fail "OKTA_LIVE_ORG must be https:// (the API token is never sent over plain http)" RUN_ID="okta-e2e-$(date +%Y%m%d%H%M%S)-$(openssl rand -hex 3)" LCFG="$WORK/live-curl.cfg" ( umask 077 @@ -269,7 +306,7 @@ rc=$? set -e LAPP_ID="$(sed -n 's/^app created: \([^ ]*\) .*/\1/p' "$WORK/live.out")" if [ -n "$LAPP_ID" ]; then - LIVE_CLEANUP=("live -X POST '$ORG/api/v1/apps/$LAPP_ID/lifecycle/deactivate' >/dev/null && live -X DELETE '$ORG/api/v1/apps/$LAPP_ID' >/dev/null && echo '# live cleanup: deactivated and deleted app $LAPP_ID'" "${LIVE_CLEANUP[@]}") + LIVE_CLEANUP=("live -X POST '$ORG/api/v1/apps/$LAPP_ID/lifecycle/deactivate' >/dev/null && live -X DELETE '$ORG/api/v1/apps/$LAPP_ID' >/dev/null && echo '# live cleanup: deactivated and deleted app $LAPP_ID'" ${LIVE_CLEANUP[@]+"${LIVE_CLEANUP[@]}"}) fi [ "$rc" = 0 ] || fail "okta-setup.sh failed against $ORG: $(tail -4 "$WORK/live.out")" [ -n "$LAPP_ID" ] || fail "no app id in the output" diff --git a/ci/agent-relay/okta-e2e/mock_okta.py b/ci/agent-relay/okta-e2e/mock_okta.py index b2a12304..448feb43 100755 --- a/ci/agent-relay/okta-e2e/mock_okta.py +++ b/ci/agent-relay/okta-e2e/mock_okta.py @@ -73,8 +73,20 @@ def do_GET(self): return self.reply(200, {"apps": APPS, "assigned": ASSIGNED}) self.reply(404, {"errorCode": "E0000007"}) + def body(self): + """The JSON body, or None after logging the raw body and replying 400.""" + raw = self.rfile.read(int(self.headers.get("Content-Length", 0))) + try: + return json.loads(raw or b"{}") + except ValueError: + self.record(raw.decode("utf-8", "replace")) + self.reply(400, {"errorCode": "E0000003", "errorSummary": "Malformed JSON"}) + return None + def do_POST(self): - body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}") + body = self.body() + if body is None: + return url = self.record(body) if not self.authed(): return @@ -88,8 +100,9 @@ def do_POST(self): self.reply(404, {"errorCode": "E0000007"}) def do_PUT(self): - length = int(self.headers.get("Content-Length", 0)) - body = json.loads(self.rfile.read(length) or b"{}") + body = self.body() + if body is None: + return url = self.record(body) if not self.authed(): return diff --git a/ci/agent-relay/okta-e2e/test_browser_signin.py b/ci/agent-relay/okta-e2e/test_browser_signin.py new file mode 100644 index 00000000..4635ca5b --- /dev/null +++ b/ci/agent-relay/okta-e2e/test_browser_signin.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""Unit cases for browser_signin.verdict (no browser, no Playwright). + + python3 -m unittest ci/agent-relay/okta-e2e/test_browser_signin.py +""" +import os +import sys +import unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from browser_signin import verdict # noqa: E402 + +HOST = "relay.kind.agentrelay.com" +OTHER = {"name": "otherdom", "email": "x-otherdom@other-example.com", "expect": "control_refused"} +REFUSED = {"sessionStatus": 401, "finalHost": HOST, "callbacks": [["code", "state"]]} + + +class ControlRefusal(unittest.TestCase): + def check(self, message): + return verdict(OTHER, dict(REFUSED, siteMessage=message), HOST, "example.com") + + def test_exact_domain_refusal_passes(self): + self.assertTrue(self.check("Accounts from other-example.com can't sign in here. Use your example.com account.")) + + def test_generic_refusals_fail(self): + for message in ("This account cannot sign in because the email is not verified.", + "You can't sign in here right now.", "Sign-in is not allowed.", None): + self.assertFalse(self.check(message), message) + + def test_wrong_domains_fail(self): + self.assertFalse(self.check("Accounts from evil.example can't sign in here. Use your example.com account.")) + self.assertFalse(self.check("Accounts from other-example.com can't sign in here. Use your other.example account.")) + + def test_no_code_from_okta_fails(self): + result = dict(REFUSED, callbacks=[], siteMessage="Accounts from other-example.com can't sign in here. Use your example.com account.") + self.assertFalse(verdict(OTHER, result, HOST, "example.com")) + + +class MemberAndOkta(unittest.TestCase): + def test_member_needs_member_role_and_owner_only_denied(self): + case = {"email": "m@example.com", "expect": "member"} + good = {"sessionStatus": 200, "email": "M@example.com", "role": "member", "usageStatus": 403, "finalHost": HOST} + self.assertTrue(verdict(case, good, HOST, "example.com")) + self.assertFalse(verdict(case, dict(good, role="owner"), HOST, "example.com")) + self.assertFalse(verdict(case, dict(good, email=None), HOST, "example.com")) + + def test_okta_refusal_must_not_return_a_code(self): + case = {"email": "o@example.com", "expect": "okta_refused"} + stopped = {"sessionStatus": 401, "finalHost": "org.okta.com", "oktaMessage": "not assigned to the client application", "callbacks": []} + self.assertTrue(verdict(case, stopped, HOST, "example.com")) + self.assertFalse(verdict(case, dict(stopped, callbacks=[["code", "state"]]), HOST, "example.com")) + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/local-development.md b/docs/local-development.md index f7fb23ff..fd9b9b3a 100644 --- a/docs/local-development.md +++ b/docs/local-development.md @@ -163,7 +163,7 @@ op item get "Local Kind Google OAuth client" --vault "AI Agents" --reveal --form | ssh -T agentrelay@100.104.148.105 'cd /infra && make -s local-google-oidc' ``` **Another OIDC provider (for example Okta).** Pipe `{"issuer": "https://.okta.com", -"client_id": ..., "client_secret": ..., "display_name": "Okta"}` to `make local-oidc` +"client_id": "", "client_secret": "", "display_name": "Okta"}` to `make local-oidc` (the same command; it stores the same file). `ci/agent-relay/okta-e2e/browser.sh` does this with a throwaway Okta app and users, and signs in with Playwright. From d7c59cc02227674d4e3b3698351dc3deeed1d0b8 Mon Sep 17 00:00:00 2001 From: Khaliq Date: Mon, 30 Nov 2026 19:50:13 -0800 Subject: [PATCH 6/9] fix(okta-e2e): cleanup warnings name the run ID for manual recovery Co-Authored-By: Claude Opus 5.5 --- ci/agent-relay/okta-e2e/browser.sh | 4 +++- ci/agent-relay/okta-e2e/kind.sh | 5 ++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/ci/agent-relay/okta-e2e/browser.sh b/ci/agent-relay/okta-e2e/browser.sh index 54b02ccf..b8b910da 100755 --- a/ci/agent-relay/okta-e2e/browser.sh +++ b/ci/agent-relay/okta-e2e/browser.sh @@ -52,7 +52,9 @@ OIDC_FILE="$STATE/google-oidc.json" cleanup() { local rc=$? i for ((i = ${#CLEANUP[@]} - 1; i >= 0; i--)); do - eval "${CLEANUP[$i]}" || { echo "not ok - cleanup step failed: ${CLEANUP[$i]%% *}" >&2; [ "$rc" != 0 ] || rc=1; } + eval "${CLEANUP[$i]}" || { + echo "not ok - cleanup step failed: ${CLEANUP[$i]%% *} (run $RUN_ID: in $ORG remove any app labelled \"Agent Relay e2e $RUN_ID\", and the group, users and authentication policy named $RUN_ID*)" >&2 + [ "$rc" != 0 ] || rc=1; } done rm -rf "$WORK" exit "$rc" diff --git a/ci/agent-relay/okta-e2e/kind.sh b/ci/agent-relay/okta-e2e/kind.sh index df827e40..bdd950fc 100755 --- a/ci/agent-relay/okta-e2e/kind.sh +++ b/ci/agent-relay/okta-e2e/kind.sh @@ -49,13 +49,16 @@ fail() { printf 'not ok - %s\n' "$*" >&2; exit 1; } k() { kubectl --context "$CTX" -n "$NS" "$@"; } MOCK_PID= LIVE_CLEANUP=() +RUN_ID= CREATED=0 # delete only a cluster this run created OWNER_MARK=okta-e2e-owner # ConfigMap in kube-system on clusters this harness created cleanup() { local rc=$? c # Every step runs; any failure fails the run (bash 3.2-safe empty expansion). for c in ${LIVE_CLEANUP[@]+"${LIVE_CLEANUP[@]}"}; do - eval "$c" || { echo "not ok - live cleanup failed, remove by hand in Okta: $c" | sed 's/live -X [A-Z]* //g' >&2; [ "$rc" != 0 ] || rc=1; } + eval "$c" || { + echo "not ok - live cleanup failed (run ${RUN_ID:-unknown}); remove by hand in Okta: $c" | sed 's/live -X [A-Z]* //g' >&2 + [ "$rc" != 0 ] || rc=1; } done [ -z "$MOCK_PID" ] || kill "$MOCK_PID" 2>/dev/null || true if [[ "$CREATED" == 1 && "${KEEP_CLUSTER:-0}" != 1 ]]; then kind delete cluster --name "$CLUSTER" >/dev/null 2>&1 || true; fi From 392102ed6a7fa659a6e57873837b205393cb1f0e Mon Sep 17 00:00:00 2001 From: Khaliq Date: Mon, 30 Nov 2026 19:53:13 -0800 Subject: [PATCH 7/9] fix(okta-e2e): wait for the dashboard rollout and the Okta button before browser cases The first case could load /login while relay-webapp was still rolling out after the OIDC reconcile (blank page, 30s timeout), although Control's login-config already answered. Co-Authored-By: Claude Opus 5.5 --- ci/agent-relay/okta-e2e/browser.sh | 4 ++++ ci/agent-relay/okta-e2e/browser_signin.py | 10 +++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/ci/agent-relay/okta-e2e/browser.sh b/ci/agent-relay/okta-e2e/browser.sh index b8b910da..5137314c 100755 --- a/ci/agent-relay/okta-e2e/browser.sh +++ b/ci/agent-relay/okta-e2e/browser.sh @@ -161,6 +161,10 @@ if ! jq -e '.oidc.displayName == "Okta"' <<<"${cfg:-null}" >/dev/null 2>&1; then "${KCTL[@]}" logs deployment/relay-control --tail=25 2>&1 | grep -v -i -e secret -e token >&2 || true fail "login-config never offered Okta: ${cfg:-no response}" fi +# Control answering is not the whole site: the dashboard may still be rolling +# out after the reconcile. +"${KCTL[@]}" rollout status deployment --timeout=300s >/dev/null || + fail "deployments in agent-relay did not finish rolling out" ok "login-config offers Okta ($(jq -c '{methods, oidc}' <<<"$cfg"))" # --- browser ------------------------------------------------------------------------- diff --git a/ci/agent-relay/okta-e2e/browser_signin.py b/ci/agent-relay/okta-e2e/browser_signin.py index c460b361..34033706 100755 --- a/ci/agent-relay/okta-e2e/browser_signin.py +++ b/ci/agent-relay/okta-e2e/browser_signin.py @@ -90,9 +90,17 @@ def run_case(browser, case): and callbacks.append(sorted(re.findall(r"(?:^|&)([^=&]+)=", urlsplit(f.url).query)) + (["error=access_denied"] if "error=access_denied" in f.url else []))) try: - page.goto(SITE + "/login", wait_until="networkidle") button = page.get_by_role("button", name=re.compile("Continue with Okta")).or_( page.get_by_role("link", name=re.compile("Continue with Okta"))) + for attempt in range(6): # the dashboard may still be settling after a reconcile + page.goto(SITE + "/login", wait_until="networkidle") + try: + button.first.wait_for(timeout=20000) + break + except Exception as wait_error: # Playwright's TimeoutError + if type(wait_error).__name__ != "TimeoutError" or attempt == 5: + raise + result["loginAttempts"] = attempt + 1 button.first.click(timeout=30000) page.wait_for_url(re.compile(r"^https://[^/]*okta\.com/"), timeout=30000) result["oktaHost"] = urlsplit(page.url).hostname From ed2aa3594474094230ba8da0f77759412d486884 Mon Sep 17 00:00:00 2001 From: Khaliq Date: Mon, 30 Nov 2026 19:59:34 -0800 Subject: [PATCH 8/9] fix(okta-e2e): address second review round - kind.sh: run the guide's console/turn-off commands only when they match the reviewed guide-blocks.sha256; a changed guide fails with a diff. - browser.sh: cleanup failures print the whole step (URLs and IDs only); delete_app_and_policy fails, naming the app or policy, if either remains; wait for each Deployment by name (older kubectl needs one) and dump deployments/pods on timeout. - browser_signin.py: pick Control's exact domain message anywhere on the page; compare it without case; document spki/allowedDomain. - test_browser_signin.py: usage 200 fails the member case; domain case. - mock_okta.py: a JSON null body is a body (dedicated MALFORMED sentinel). - local_stack.py: issuer hosts must be valid DNS names with a dot. Co-Authored-By: Claude Opus 5.5 --- ci/agent-relay/kind/local_stack.py | 4 +++- ci/agent-relay/kind/test_local_stack.py | 3 ++- ci/agent-relay/okta-e2e/browser.sh | 22 ++++++++++++++----- ci/agent-relay/okta-e2e/browser_signin.py | 13 +++++++---- ci/agent-relay/okta-e2e/guide-blocks.sha256 | 2 ++ ci/agent-relay/okta-e2e/kind.sh | 7 ++++++ ci/agent-relay/okta-e2e/mock_okta.py | 9 ++++---- .../okta-e2e/test_browser_signin.py | 5 +++++ 8 files changed, 49 insertions(+), 16 deletions(-) create mode 100644 ci/agent-relay/okta-e2e/guide-blocks.sha256 diff --git a/ci/agent-relay/kind/local_stack.py b/ci/agent-relay/kind/local_stack.py index 273c7259..dbfe98b6 100644 --- a/ci/agent-relay/kind/local_stack.py +++ b/ci/agent-relay/kind/local_stack.py @@ -888,7 +888,9 @@ def oidc_client(value, where): provider's published issuer, which may end in "/". It must use the default https port, the only one the local OIDC egress policy opens.""" issuer = value.get("issuer") or GOOGLE_ISSUER - if not (isinstance(issuer, str) and re.fullmatch(r"https://[^/:?#@\s]+(:443)?(/[^?#@\s]*)?", issuer)): + label = r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?" + if not (isinstance(issuer, str) + and re.fullmatch(r"https://" + label + r"(?:\." + label + r")+(:443)?(/[^?#@\s]*)?", issuer)): raise StackError(where + ": issuer must be an https URL on port 443, without query, fragment or credentials") google = issuer.rstrip("/") == GOOGLE_ISSUER # either spelling gets Google's client-id check if not (isinstance(value.get("client_id"), str) and value["client_id"] diff --git a/ci/agent-relay/kind/test_local_stack.py b/ci/agent-relay/kind/test_local_stack.py index 3abe8d07..a26c00de 100644 --- a/ci/agent-relay/kind/test_local_stack.py +++ b/ci/agent-relay/kind/test_local_stack.py @@ -592,7 +592,8 @@ def test_oidc_renders_control_sign_in_and_egress_only_when_stored(self): "client_id": "0oa", "client_secret": "x", "display_name": 7})) with self.assertRaises(local_stack.StackError): stack.google_oidc() - for bad in ("http://example.okta.com", "https://example.okta.com:8443", "https://u:p@example.okta.com"): + for bad in ("http://example.okta.com", "https://example.okta.com:8443", "https://u:p@example.okta.com", + "https://.okta.com", "https://example..okta.com", "https://-x.okta.com", "https://localhost"): (stack.state / "google-oidc.json").write_text(json.dumps({"issuer": bad, "client_id": "0oaexample", "client_secret": "x"})) with self.assertRaises(local_stack.StackError): stack.google_oidc() diff --git a/ci/agent-relay/okta-e2e/browser.sh b/ci/agent-relay/okta-e2e/browser.sh index 5137314c..41bca83f 100755 --- a/ci/agent-relay/okta-e2e/browser.sh +++ b/ci/agent-relay/okta-e2e/browser.sh @@ -53,7 +53,8 @@ cleanup() { local rc=$? i for ((i = ${#CLEANUP[@]} - 1; i >= 0; i--)); do eval "${CLEANUP[$i]}" || { - echo "not ok - cleanup step failed: ${CLEANUP[$i]%% *} (run $RUN_ID: in $ORG remove any app labelled \"Agent Relay e2e $RUN_ID\", and the group, users and authentication policy named $RUN_ID*)" >&2 + # The step text holds only URLs and object IDs, never the token. + echo "not ok - cleanup step failed: ${CLEANUP[$i]} (run $RUN_ID: in $ORG remove any app labelled \"Agent Relay e2e $RUN_ID\", and the group, users and authentication policy named $RUN_ID*)" >&2 [ "$rc" != 0 ] || rc=1; } done rm -rf "$WORK" @@ -105,10 +106,15 @@ APP_ID="$(jq -r .id <<<"$APP")" CLIENT_ID="$(jq -r .credentials.oauthClient.client_id <<<"$APP")" ( umask 077; jq -jr .credentials.oauthClient.client_secret <<<"$APP" > "$WORK/client-secret" ); unset APP POLICY_ID= -delete_app_and_policy() { # the policy can only go once no app uses it +delete_app_and_policy() { # the policy can only go once no app uses it; fails if either remains okta -X POST "$ORG/api/v1/apps/$APP_ID/lifecycle/deactivate" >/dev/null || true - okta -X DELETE "$ORG/api/v1/apps/$APP_ID" >/dev/null && echo "# cleanup: deleted app $APP_ID" - [ -z "$POLICY_ID" ] || { okta -X DELETE "$ORG/api/v1/policies/$POLICY_ID" >/dev/null && echo "# cleanup: deleted policy $RUN_ID"; } + okta -X DELETE "$ORG/api/v1/apps/$APP_ID" >/dev/null || + { echo "not ok - could not delete Okta app $APP_ID (policy ${POLICY_ID:-none} left with it)" >&2; return 1; } + echo "# cleanup: deleted app $APP_ID" + [ -n "$POLICY_ID" ] || return 0 + okta -X DELETE "$ORG/api/v1/policies/$POLICY_ID" >/dev/null || + { echo "not ok - could not delete Okta policy $POLICY_ID" >&2; return 1; } + echo "# cleanup: deleted policy $RUN_ID" } CLEANUP+=("delete_app_and_policy") okta -X PUT "$ORG/api/v1/apps/$APP_ID/groups/$GROUP_ID" --data-binary '{}' >/dev/null @@ -163,8 +169,12 @@ if ! jq -e '.oidc.displayName == "Okta"' <<<"${cfg:-null}" >/dev/null 2>&1; then fi # Control answering is not the whole site: the dashboard may still be rolling # out after the reconcile. -"${KCTL[@]}" rollout status deployment --timeout=300s >/dev/null || - fail "deployments in agent-relay did not finish rolling out" +# One name at a time: older kubectl clients need a resource name. +for d in $("${KCTL[@]}" get deployments -o name); do + "${KCTL[@]}" rollout status "$d" --timeout=300s >/dev/null || { + "${KCTL[@]}" get deployments,pods -o wide >&2 || true + fail "$d in agent-relay did not finish rolling out"; } +done ok "login-config offers Okta ($(jq -c '{methods, oidc}' <<<"$cfg"))" # --- browser ------------------------------------------------------------------------- diff --git a/ci/agent-relay/okta-e2e/browser_signin.py b/ci/agent-relay/okta-e2e/browser_signin.py index 34033706..7f1483c9 100755 --- a/ci/agent-relay/okta-e2e/browser_signin.py +++ b/ci/agent-relay/okta-e2e/browser_signin.py @@ -5,6 +5,8 @@ cases.json (0600, written by browser.sh) is {"site": "https://relay.kind.agentrelay.com", "edge": "127.0.0.1", + "spki": ",..." (local edge keys whose TLS errors are ignored), + "allowedDomain": "example.com" (the stack's allowed email domain), "cases": [{"name": ..., "email": ..., "password": ..., "expect": "member" | "okta_refused" | "control_refused"}]} Passwords are filled into the page and never printed. Prints one JSON result per case and exits 1 if any case does not match its expectation. Screenshots of @@ -72,9 +74,10 @@ def verdict(case, result, host, allowed_domain): # Okta authenticated the person (a code came back); Control refused the session. # Control's domain refusal, naming this person's domain and the allowed one. rejected = case["email"].rsplit("@", 1)[1] - want = "Accounts from " + rejected + " can't sign in here. Use your " + allowed_domain + " account." + # Control lowercases domains; compare without case. + want = ("Accounts from " + rejected + " can't sign in here. Use your " + allowed_domain + " account.").casefold() ok = (result.get("sessionStatus") == 401 and result.get("finalHost") == host - and "error" not in result and code_returned and want in (result.get("siteMessage") or "")) + and "error" not in result and code_returned and want in (result.get("siteMessage") or "").casefold()) else: ok = False return ok @@ -122,8 +125,10 @@ def run_case(browser, case): m = re.search(r"(not allowed to access this app|not assigned to the client application)", text, re.I) result["oktaMessage"] = m.group(0) if m else None else: - # The visible refusal text (verdict() requires Control's exact domain message). - m = re.search(r"[^\n]{0,160}(can't sign in|cannot sign in|not allowed|not permitted)[^\n]{0,160}", text, re.I) + # Control's domain refusal if shown anywhere on the page, else the first + # refusal-like line (verdict() requires the exact domain message). + m = (re.search(r"Accounts from \S+ can't sign in here\. Use your \S+ account\.", text, re.I) + or re.search(r"[^\n]{0,160}(can't sign in|cannot sign in|not allowed|not permitted)[^\n]{0,160}", text, re.I)) result["siteMessage"] = m.group(0).strip() if m else None status, body = session(page) result["sessionStatus"] = status diff --git a/ci/agent-relay/okta-e2e/guide-blocks.sha256 b/ci/agent-relay/okta-e2e/guide-blocks.sha256 new file mode 100644 index 00000000..c625cbc9 --- /dev/null +++ b/ci/agent-relay/okta-e2e/guide-blocks.sha256 @@ -0,0 +1,2 @@ +]7;file://Khaliqs-MacBook-Pro.local/private/tmp/claude-501/-Users-khaliqgant-Projects-AgentWorkforce-infra/6a49dea7-49ef-40be-9759-be44d6b5f622/scratchpad/guide.M6Dca0ba3c7173718947d01bc39e19097f8d7994bf0945545afdc352188d709f0313 guide-console.sh +7e63d78f91ad72f3d5ede1db3faafedb3735a74e013dca2ec26420f6c6481467 guide-off.sh diff --git a/ci/agent-relay/okta-e2e/kind.sh b/ci/agent-relay/okta-e2e/kind.sh index bdd950fc..7475fca1 100755 --- a/ci/agent-relay/okta-e2e/kind.sh +++ b/ci/agent-relay/okta-e2e/kind.sh @@ -97,6 +97,13 @@ open(out + "/guide-console.sh", "w").write(block_after("Prefer the Okta console? open(out + "/guide-off.sh", "w").write(block_after("To remove the stored secret")) EOF grep -q -- '--rawfile' "$WORK/guide-console.sh" || fail "guide console block has no --rawfile (stale guide?)" +# Run only reviewed commands: the blocks must match guide-blocks.sha256. When +# the guide changes, read the new blocks, then update that file +# (cd "$WORK" && sha256sum guide-console.sh guide-off.sh). +(cd "$WORK" && sha256 -c "$HERE/guide-blocks.sha256" >/dev/null 2>&1) || { + diff <(cd "$WORK" && sha256 guide-console.sh guide-off.sh) "$HERE/guide-blocks.sha256" >&2 || true + fail "the guide's console/turn-off commands differ from the reviewed ones in guide-blocks.sha256; review them in $GUIDE and update that file" +} echo "# guide commands from $GUIDE" # --- cluster --------------------------------------------------------------- diff --git a/ci/agent-relay/okta-e2e/mock_okta.py b/ci/agent-relay/okta-e2e/mock_okta.py index 448feb43..55db7f99 100755 --- a/ci/agent-relay/okta-e2e/mock_okta.py +++ b/ci/agent-relay/okta-e2e/mock_okta.py @@ -24,6 +24,7 @@ GROUP = {"id": "00gmockgroup", "profile": {"name": os.environ.get("MOCK_GROUP", "Agent Relay Users")}} SECRET = os.environ.get("MOCK_CLIENT_SECRET", "mock-client-secret") APPS = [] +MALFORMED = object() # body() result for an unparseable body (JSON null is a valid body) ASSIGNED = [] @@ -74,18 +75,18 @@ def do_GET(self): self.reply(404, {"errorCode": "E0000007"}) def body(self): - """The JSON body, or None after logging the raw body and replying 400.""" + """The JSON body, or MALFORMED after logging the raw body and replying 400.""" raw = self.rfile.read(int(self.headers.get("Content-Length", 0))) try: return json.loads(raw or b"{}") except ValueError: self.record(raw.decode("utf-8", "replace")) self.reply(400, {"errorCode": "E0000003", "errorSummary": "Malformed JSON"}) - return None + return MALFORMED def do_POST(self): body = self.body() - if body is None: + if body is MALFORMED: return url = self.record(body) if not self.authed(): @@ -101,7 +102,7 @@ def do_POST(self): def do_PUT(self): body = self.body() - if body is None: + if body is MALFORMED: return url = self.record(body) if not self.authed(): diff --git a/ci/agent-relay/okta-e2e/test_browser_signin.py b/ci/agent-relay/okta-e2e/test_browser_signin.py index 4635ca5b..c0ec67d8 100644 --- a/ci/agent-relay/okta-e2e/test_browser_signin.py +++ b/ci/agent-relay/okta-e2e/test_browser_signin.py @@ -31,6 +31,10 @@ def test_wrong_domains_fail(self): self.assertFalse(self.check("Accounts from evil.example can't sign in here. Use your example.com account.")) self.assertFalse(self.check("Accounts from other-example.com can't sign in here. Use your other.example account.")) + def test_domain_case_is_ignored(self): + message = "Accounts from other-example.com can't sign in here. Use your example.com account." + self.assertTrue(verdict(OTHER, dict(REFUSED, siteMessage=message), HOST, "Example.com")) + def test_no_code_from_okta_fails(self): result = dict(REFUSED, callbacks=[], siteMessage="Accounts from other-example.com can't sign in here. Use your example.com account.") self.assertFalse(verdict(OTHER, result, HOST, "example.com")) @@ -43,6 +47,7 @@ def test_member_needs_member_role_and_owner_only_denied(self): self.assertTrue(verdict(case, good, HOST, "example.com")) self.assertFalse(verdict(case, dict(good, role="owner"), HOST, "example.com")) self.assertFalse(verdict(case, dict(good, email=None), HOST, "example.com")) + self.assertFalse(verdict(case, dict(good, usageStatus=200), HOST, "example.com")) # owner-only must be denied def test_okta_refusal_must_not_return_a_code(self): case = {"email": "o@example.com", "expect": "okta_refused"} From 93d89008f0e12ff410152ac1058d94ee41a3dd25 Mon Sep 17 00:00:00 2001 From: Khaliq Date: Mon, 30 Nov 2026 20:08:47 -0800 Subject: [PATCH 9/9] fix(okta-e2e): clean guide-blocks.sha256 and verify it strictly; mock refuses non-object JSON guide-blocks.sha256 had a terminal escape sequence before the first hash. sha256sum -c only warns about a malformed line and still passes on the rest, so the console block was not actually pinned. The file is now two plain lines, kind.sh requires exactly that format, and it compares the computed hashes byte for byte instead of using -c. mock_okta.py: a JSON body that is not an object is recorded and answered 400 instead of raising in the handler. Co-Authored-By: Claude Opus 5.5 --- ci/agent-relay/okta-e2e/guide-blocks.sha256 | 2 +- ci/agent-relay/okta-e2e/kind.sh | 8 +++++++- ci/agent-relay/okta-e2e/mock_okta.py | 6 ++++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/ci/agent-relay/okta-e2e/guide-blocks.sha256 b/ci/agent-relay/okta-e2e/guide-blocks.sha256 index c625cbc9..ef636ad5 100644 --- a/ci/agent-relay/okta-e2e/guide-blocks.sha256 +++ b/ci/agent-relay/okta-e2e/guide-blocks.sha256 @@ -1,2 +1,2 @@ -]7;file://Khaliqs-MacBook-Pro.local/private/tmp/claude-501/-Users-khaliqgant-Projects-AgentWorkforce-infra/6a49dea7-49ef-40be-9759-be44d6b5f622/scratchpad/guide.M6Dca0ba3c7173718947d01bc39e19097f8d7994bf0945545afdc352188d709f0313 guide-console.sh +a0ba3c7173718947d01bc39e19097f8d7994bf0945545afdc352188d709f0313 guide-console.sh 7e63d78f91ad72f3d5ede1db3faafedb3735a74e013dca2ec26420f6c6481467 guide-off.sh diff --git a/ci/agent-relay/okta-e2e/kind.sh b/ci/agent-relay/okta-e2e/kind.sh index 7475fca1..dc309407 100755 --- a/ci/agent-relay/okta-e2e/kind.sh +++ b/ci/agent-relay/okta-e2e/kind.sh @@ -100,7 +100,13 @@ grep -q -- '--rawfile' "$WORK/guide-console.sh" || fail "guide console block has # Run only reviewed commands: the blocks must match guide-blocks.sha256. When # the guide changes, read the new blocks, then update that file # (cd "$WORK" && sha256sum guide-console.sh guide-off.sh). -(cd "$WORK" && sha256 -c "$HERE/guide-blocks.sha256" >/dev/null 2>&1) || { +# Strict: exactly these two well-formed lines (sha256sum -c only warns about a +# malformed line and still passes on the others). +grep -Eqx '[0-9a-f]{64} guide-console\.sh' <(sed -n 1p "$HERE/guide-blocks.sha256") && + grep -Eqx '[0-9a-f]{64} guide-off\.sh' <(sed -n 2p "$HERE/guide-blocks.sha256") && + [ "$(wc -l < "$HERE/guide-blocks.sha256" | tr -d ' ')" = 2 ] || + fail "guide-blocks.sha256 must be exactly two lines: guide-console.sh / guide-off.sh" +[ "$(cd "$WORK" && sha256 guide-console.sh guide-off.sh)" = "$(cat "$HERE/guide-blocks.sha256")" ] || { diff <(cd "$WORK" && sha256 guide-console.sh guide-off.sh) "$HERE/guide-blocks.sha256" >&2 || true fail "the guide's console/turn-off commands differ from the reviewed ones in guide-blocks.sha256; review them in $GUIDE and update that file" } diff --git a/ci/agent-relay/okta-e2e/mock_okta.py b/ci/agent-relay/okta-e2e/mock_okta.py index 55db7f99..0ab11c28 100755 --- a/ci/agent-relay/okta-e2e/mock_okta.py +++ b/ci/agent-relay/okta-e2e/mock_okta.py @@ -88,6 +88,9 @@ def do_POST(self): body = self.body() if body is MALFORMED: return + if not isinstance(body, dict): # recorded, then refused like Okta does + self.record(body) + return self.reply(400, {"errorCode": "E0000003", "errorSummary": "Expected a JSON object"}) url = self.record(body) if not self.authed(): return @@ -104,6 +107,9 @@ def do_PUT(self): body = self.body() if body is MALFORMED: return + if not isinstance(body, dict): + self.record(body) + return self.reply(400, {"errorCode": "E0000003", "errorSummary": "Expected a JSON object"}) url = self.record(body) if not self.authed(): return