#!/usr/bin/env bash # ============================================================================ # SSO 统一认证 —— OAuth2.0 / OIDC 端到端验证脚本 # # 覆盖:discovery / 登录建会话 / 授权码+PKCE / 授权码(机密) / token / # userinfo / introspect / client_credentials / password / refresh_token / # IAP 身份注入(无身份拦截、Bearer、Cookie、伪造头覆盖) # # 前置: # - 网关以 source/conf/nginx.test.conf(或等价生产配置)运行 # - 种子:source/data/users.json(alice/alice123)、source/data/oauth_clients.json # (grafana / spa-demo / machine) # - 依赖:curl、python3 # # 客户端密钥**不在本脚本内硬编码**,运行时从 $DATA_DIR/oauth_clients.json 读取, # 避免密钥散落在测试代码里。 # # 用法: # bash tests/oauth2-e2e.sh [IDP_BASE] [IAP_BASE] [DATA_DIR] # ============================================================================ set -u # 口令等敏感值从项目根 .env 读(不进 git);已存在的环境变量优先。 _ENV_HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" . "$_ENV_HERE/../scripts/load-env.sh" unset _ENV_HERE BASE="${1:-http://127.0.0.1:18098}" IAP="${2:-http://127.0.0.1:18099}" ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" DATA_DIR="${3:-$ROOT/source/data}" JAR="$(mktemp -t sso_e2e_cookies.XXXXXX.txt)" HDR="$(mktemp -t sso_e2e_hdr.XXXXXX.txt)" PASS=0; FAIL=0 ok() { echo " ✅ $1"; PASS=$((PASS+1)); } bad() { echo " ❌ $1"; FAIL=$((FAIL+1)); } need() { command -v "$1" >/dev/null 2>&1 || { echo "缺少依赖: $1"; exit 2; }; } need curl; need python3 echo "==> IdP: $BASE" echo "==> IAP: $IAP" echo "==> data: $DATA_DIR" # ---------- JSON 取值:支持信封 {code,msg,data:{...}} ---------- # dj 取 .data. # tj 取顶层 dj() { printf '%s' "$1" | python3 -c " import sys,json k=sys.argv[1] try: d=json.loads(sys.stdin.read()) except Exception: print(''); raise SystemExit v=(d.get('data') or {}) if isinstance(d,dict) else {} v=v.get(k) if isinstance(v,dict) else None print(v if isinstance(v,str) else (json.dumps(v) if v is not None else '')) " "$2"; } tj() { printf '%s' "$1" | python3 -c " import sys,json k=sys.argv[1] try: d=json.loads(sys.stdin.read()) except Exception: print(''); raise SystemExit v=d.get(k) if isinstance(d,dict) else None print(v if isinstance(v,str) else (json.dumps(v) if v is not None else '')) " "$2"; } # 从响应头文件取 Set-Cookie 的某个 cookie 值(curl 对 HttpOnly cookie 会写成 # `#HttpOnly_ ...`,故不能简单按 `^[^#]` 过滤) hdr_cookie() { local name="$1" file="$2" awk -F'\t' -v n="$name" '!/^#(?!HttpOnly)/ { } { if ($6==n) v=$7 } END { print v }' "$file" } # 从 -D 头文件里取 Set-Cookie 行(更直接) setcookie_val() { local name="$1" file="$2" python3 - "$name" "$file" <<'PY' import sys name, path = sys.argv[1], sys.argv[2] out = '' for ln in open(path, errors='replace'): if ln.lower().startswith('set-cookie'): first = ln.split(':', 1)[1].strip().split(';')[0] k, _, v = first.partition('=') if k.strip() == name: out = v print(out) PY } # 取 Location 头的值 hdr_location() { python3 - "$1" <<'PY' import sys for ln in open(sys.argv[1], errors='replace'): if ln.lower().startswith('location'): print(ln.split(':', 1)[1].strip()); break PY } # 从 URL 里取查询参数 url_param() { python3 - "$1" "$2" <<'PY' import sys, urllib.parse as u url, key = sys.argv[1], sys.argv[2] q = u.urlparse(url).query print(u.parse_qs(q).get(key, [''])[0]) PY } # JWT 段数 jwt_parts() { printf '%s' "$1" | python3 -c "import sys;t=sys.stdin.read().strip();print(len(t.split('.')) if t else 0)" } # client_secret client_secret() { python3 -c " import json,sys d=json.load(open('$DATA_DIR/oauth_clients.json')) for c in d: if c['client_id']==sys.argv[1]: print(c['client_secret']); break " "$1" } # PKCE pkce_verifier="$(python3 -c "import secrets;print(secrets.token_urlsafe(48))")" pkce_challenge="$(python3 -c " import hashlib,base64,sys v=sys.argv[1].encode() print(base64.urlsafe_b64encode(hashlib.sha256(v).digest()).rstrip(b'=').decode()) " "$pkce_verifier")" SPA_REDIRECT="https://app.yourdomain.com/callback" GRAFANA_REDIRECT="https://grafana.yourdomain.com/login/generic_oauth" # =========================================================================== echo "## 1. discovery(OIDC 元数据)" DISC="$(curl -s "$BASE/.well-known/openid-configuration")" if [ "$(dj "$DISC" issuer)" = "$BASE" ] \ && [ "$(dj "$DISC" token_endpoint)" = "$BASE/oauth/token" ] \ && [ "$(dj "$DISC" authorization_endpoint)" = "$BASE/oauth/authorize" ] \ && [ "$(dj "$DISC" userinfo_endpoint)" = "$BASE/oauth/userinfo" ] \ && [ "$(dj "$DISC" introspection_endpoint)" = "$BASE/oauth/introspect" ] \ && [[ "$(dj "$DISC" code_challenge_methods_supported)" == *S256* ]]; then ok "discovery 字段齐全(issuer/token/authorize/userinfo/introspect + S256)" else bad "discovery 异常: $DISC" fi # =========================================================================== echo "## 2. 登录建 SSO 会话(alice)" curl -s -D "$HDR" -o /dev/null -c "$JAR" -X POST "$BASE/login" \ --data-urlencode 'username=alice' \ --data-urlencode "password=${ALICE_PASSWORD:-alice123}" \ --data-urlencode 'redirect=/' SSO="$(setcookie_val sso_sid "$HDR")" COOKIE_CT="$(python3 -c " for ln in open('$HDR',errors='replace'): if ln.lower().startswith('content-type'): print(ln.split(':',1)[1].strip()) ")" if [ -n "$SSO" ]; then ok "登录成功并下发会话 Cookie(sso_sid, ${#SSO} 字符)" else bad "登录未拿到会话 Cookie(headers: $(grep -ci set-cookie "$HDR" 2>/dev/null) 个 set-cookie)" fi CK="sso_sid=$SSO" # =========================================================================== echo "## 3. 授权码 + PKCE(公开客户端 spa-demo)" curl -s -D "$HDR" -o /dev/null -b "$CK" \ "$BASE/oauth/authorize?response_type=code&client_id=spa-demo&redirect_uri=$(python3 -c "import urllib.parse,sys;print(urllib.parse.quote(sys.argv[1],safe=''))" "$SPA_REDIRECT")&scope=openid%20profile%20email&state=xyz&code_challenge=$pkce_challenge&code_challenge_method=S256" LOC="$(hdr_location "$HDR")" CODE="$(url_param "$LOC" code)" STATE="$(url_param "$LOC" state)" if [ -n "$CODE" ] && [ "$STATE" = "xyz" ] && [[ "$LOC" == "$SPA_REDIRECT"* ]]; then ok "拿到授权码并回跳(state 原样带回)" else bad "未拿到授权码 (Location=$LOC)" fi TOK="$(curl -s -X POST "$BASE/oauth/token" \ -d "grant_type=authorization_code&code=$CODE&redirect_uri=$SPA_REDIRECT&client_id=spa-demo&code_verifier=$pkce_verifier")" AT="$(dj "$TOK" access_token)" IT="$(dj "$TOK" id_token)" RT="$(dj "$TOK" refresh_token)" if [ "$(jwt_parts "$AT")" = "3" ] && [ "$(jwt_parts "$IT")" = "3" ] && [ -n "$RT" ]; then ok "授权码换发成功(access/id/refresh 三件套,access 为 HS256 JWT)" else bad "授权码换发失败: $TOK" fi # =========================================================================== echo "## 4. userinfo(Bearer access_token)" UI="$(curl -s -H "Authorization: Bearer $AT" "$BASE/oauth/userinfo")" if [ "$(dj "$UI" sub)" = "alice" ] && [ "$(dj "$UI" email)" = "alice@yourdomain.com" ]; then ok "userinfo 返回 sub=alice / email 正确" else bad "userinfo 异常: $UI" fi # =========================================================================== echo "## 5. introspect(RFC 7662,需客户端鉴权)" IS="$(curl -s -X POST "$BASE/oauth/introspect" -d "client_id=spa-demo&token=$AT")" if [ "$(dj "$IS" active)" = "true" ] && [ "$(dj "$IS" sub)" = "alice" ]; then ok "introspect: active=true, sub=alice" else bad "introspect 异常: $IS" fi # =========================================================================== echo "## 6. 授权码(机密客户端 grafana,Basic 鉴权、无 PKCE)" curl -s -D "$HDR" -o /dev/null -b "$CK" \ "$BASE/oauth/authorize?response_type=code&client_id=grafana&redirect_uri=$(python3 -c "import urllib.parse,sys;print(urllib.parse.quote(sys.argv[1],safe=''))" "$GRAFANA_REDIRECT")&scope=openid%20profile%20email&state=abc" LOC2="$(hdr_location "$HDR")" CODE2="$(url_param "$LOC2" code)" GSEC="$(client_secret grafana)" TOK2="$(curl -s -X POST "$BASE/oauth/token" -u "grafana:$GSEC" \ -d "grant_type=authorization_code&code=$CODE2&redirect_uri=$GRAFANA_REDIRECT")" AT2="$(dj "$TOK2" access_token)" if [ -n "$CODE2" ] && [ "$(jwt_parts "$AT2")" = "3" ]; then ok "机密客户端授权码换取成功(Basic 鉴权)" else bad "机密客户端流程失败 (code=${CODE2:0:8}…, body=$TOK2)" fi # =========================================================================== echo "## 7. client_credentials(machine 客户端)" MSEC="$(client_secret machine)" CC="$(curl -s -X POST "$BASE/oauth/token" -u "machine:$MSEC" \ -d 'grant_type=client_credentials&scope=openid')" CC_AT="$(dj "$CC" access_token)" CC_IS="$(curl -s -X POST "$BASE/oauth/introspect" -u "machine:$MSEC" -d "token=$CC_AT")" if [ "$(jwt_parts "$CC_AT")" = "3" ] && [ "$(dj "$CC_IS" active)" = "true" ] && [ "$(dj "$CC_IS" sub)" = "machine" ]; then ok "client_credentials 签发 + 自省 active=true(sub=machine)" else bad "client_credentials 异常: $CC / $CC_IS" fi # =========================================================================== echo "## 8. password grant(machine 客户端代资源所有者)" PW="$(curl -s -X POST "$BASE/oauth/token" -u "machine:$MSEC" \ -d "grant_type=password&username=alice&password=${ALICE_PASSWORD:-alice123}&scope=openid profile email")" PW_AT="$(dj "$PW" access_token)" PW_ID="$(dj "$PW" id_token)" PW_UI="$(curl -s -H "Authorization: Bearer $PW_AT" "$BASE/oauth/userinfo")" if [ "$(jwt_parts "$PW_AT")" = "3" ] && [ "$(jwt_parts "$PW_ID")" = "3" ] && [ "$(dj "$PW_UI" sub)" = "alice" ]; then ok "password grant 签发 access+id_token,且 token 可用于 userinfo" else bad "password grant 异常: $PW / $PW_UI" fi # =========================================================================== echo "## 9. refresh_token(spa-demo 刷新)" RF="$(curl -s -X POST "$BASE/oauth/token" \ -d "grant_type=refresh_token&refresh_token=$RT&client_id=spa-demo")" RF_AT="$(dj "$RF" access_token)" if [ "$(jwt_parts "$RF_AT")" = "3" ] && [ "$RF_AT" != "$AT" ]; then ok "refresh_token 换发成功(新 access_token)" else bad "refresh_token 失败: $RF" fi # =========================================================================== echo "## 10. IAP:无身份 → 门禁拦截(302 跳登录,绝不直达后端)" curl -s -D "$HDR" -o /dev/null "$IAP/" ST="$(head -1 "$HDR" | awk '{print $2}')" LI="$(hdr_location "$HDR")" if [ "$ST" = "302" ] && [[ "$LI" == *"/login"* ]]; then ok "无身份被拦截并跳登录(302 → ${LI})" else bad "无身份行为异常 (http=$ST, location=$LI)" fi # =========================================================================== echo "## 11. IAP:Bearer access_token → 注入 X-Auth-* 到后端" R11="$(curl -s -H "Authorization: Bearer $AT" "$IAP/")" if [[ "$R11" == *'"x_auth_user":"alice"'* ]] && [[ "$R11" == *'"x_auth_email":"alice@yourdomain.com"'* ]]; then ok "Bearer 注入成功(x_auth_user=alice)" else bad "IAP Bearer 注入异常: $R11" fi # =========================================================================== echo "## 12. IAP:SSO 会话 Cookie → 注入 X-Auth-* 到后端" R12="$(curl -s -b "$CK" "$IAP/")" if [[ "$R12" == *'"x_auth_user":"alice"'* ]]; then ok "Cookie 注入成功(x_auth_user=alice)" else bad "IAP Cookie 注入异常: $R12" fi # =========================================================================== echo "## 13. IAP:客户端伪造同名头被网关覆盖" R13="$(curl -s -H "Authorization: Bearer $AT" -H "X-Auth-User: evil" -H "X-Auth-Groups: root" "$IAP/")" if [[ "$R13" == *'"x_auth_user":"alice"'* ]] && [[ "$R13" != *'"x_auth_user":"evil"'* ]] && [[ "$R13" != *'"x_auth_groups":"root"'* ]]; then ok "伪造的 X-Auth-User / X-Auth-Groups 被网关断言覆盖" else bad "IAP 未覆盖伪造头: $R13" fi # =========================================================================== echo echo "======================== 结果 ========================" echo " 通过: $PASS 失败: $FAIL" rm -f "$JAR" "$HDR" [ "$FAIL" = "0" ]