package httpapi import ( "bytes" "context" "crypto" "crypto/rand" "crypto/rsa" "crypto/sha256" "database/sql" "encoding/base64" "encoding/json" "fmt" "github.com/coreos/go-oidc/v3/oidc" "github.com/go-sql-driver/mysql" "net/http" "net/http/httptest" "net/url" "os" "sea-vhost/internal/auth" "sea-vhost/internal/config" "sea-vhost/internal/isolation" "sea-vhost/internal/panel" "sea-vhost/internal/service" "sea-vhost/internal/store" "strings" "testing" "time" ) func TestSSOLoginMySQL(t *testing.T) { dsn := os.Getenv("SEA_TEST_MYSQL_DSN") if dsn == "" { t.Skip("disposable MySQL schema not supplied") } parsed, e := mysql.ParseDSN(dsn) if e != nil || !strings.HasPrefix(parsed.DBName, "svh_cluster_test_") { t.Fatal("refusing non-test schema") } db, e := store.Open(dsn) if e != nil { t.Fatal(e) } defer db.Close() ctx := context.Background() must := func(e error) { t.Helper() if e != nil { t.Fatal(e) } } must(db.Migrate(ctx)) must(db.Migrate(ctx)) raw, e := sql.Open("mysql", dsn) must(e) defer raw.Close() must(db.BootstrapAdmin(ctx, "sso-admin@example.invalid", "SSO 管理员", "sso-admin-password-123")) admin, e := db.UserByLogin(ctx, "sso-admin@example.invalid") must(e) root := t.TempDir() must(db.InitializeLocalNode(ctx, "hosts.example.invalid", root, "control.example.invalid")) secret := "sso-test-session-key-at-least-thirty-two-characters" projects := service.NewProjects(db, panel.NewMock(), isolation.Mock{Root: root}, "hosts.example.invalid", root, true, secret, "control.example.invalid") app := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour}, db, projects) key, e := rsa.GenerateKey(rand.Reader, 2048) must(e) var issuer, nonce, subject, email string verified := true idp := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch r.URL.Path { case "/.well-known/openid-configuration": json.NewEncoder(w).Encode(map[string]any{"issuer": issuer, "authorization_endpoint": issuer + "/authorize", "token_endpoint": issuer + "/token", "jwks_uri": issuer + "/keys", "id_token_signing_alg_values_supported": []string{"RS256"}}) case "/keys": json.NewEncoder(w).Encode(map[string]any{"keys": []any{map[string]any{"kty": "RSA", "use": "sig", "alg": "RS256", "kid": "test", "n": base64.RawURLEncoding.EncodeToString(key.N.Bytes()), "e": "AQAB"}}}) case "/token": _ = r.ParseForm() if r.Form.Get("code_verifier") == "" { t.Error("PKCE verifier missing") } encode := func(v any) string { b, _ := json.Marshal(v); return base64.RawURLEncoding.EncodeToString(b) } message := encode(map[string]any{"alg": "RS256", "kid": "test"}) + "." + encode(map[string]any{"iss": issuer, "sub": subject, "aud": "sso-client", "exp": time.Now().Add(time.Hour).Unix(), "iat": time.Now().Unix(), "nonce": nonce, "email": email, "email_verified": verified, "name": "SSO 测试用户"}) sum := sha256.Sum256([]byte(message)) signature, e := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, sum[:]) if e != nil { t.Error(e) } json.NewEncoder(w).Encode(map[string]any{"access_token": "test-access", "token_type": "Bearer", "expires_in": 3600, "id_token": message + "." + base64.RawURLEncoding.EncodeToString(signature)}) default: w.WriteHeader(404) } })) defer idp.Close() issuer = idp.URL cfg := secretServiceConfig{Enabled: true, Issuer: issuer, ClientID: "sso-client", Secret: "test-client-secret", RedirectURI: "https://control.example.invalid/api/v1/auth/oidc/callback", AutoCreate: true} must(app.writeServiceConfig(httptest.NewRequest("PUT", "https://control.example.invalid", nil), "oidc_config", cfg)) type jar map[string]string count := 0 call := func(method, path string, body any, cookies jar) *httptest.ResponseRecorder { t.Helper() var b bytes.Buffer if body != nil { must(json.NewEncoder(&b).Encode(body)) } r := httptest.NewRequest(method, "https://control.example.invalid"+path, &b) r.Header.Set("Content-Type", "application/json") r.Header.Set("Origin", "https://control.example.invalid") count++ r.RemoteAddr = fmt.Sprintf("192.0.2.%d:1234", 1+count%200) r = r.WithContext(oidc.ClientContext(r.Context(), idp.Client())) for name, value := range cookies { r.AddCookie(&http.Cookie{Name: name, Value: value}) } w := httptest.NewRecorder() app.Handler().ServeHTTP(w, r) for _, c := range w.Result().Cookies() { if c.MaxAge < 0 { delete(cookies, c.Name) } else { cookies[c.Name] = c.Value } } return w } expect := func(w *httptest.ResponseRecorder, status int) { t.Helper() if w.Code != status { t.Fatalf("HTTP %d want %d: %s", w.Code, status, w.Body.String()) } } session := func(u store.User) jar { token, e := auth.NewSessionToken(secret) must(e) must(db.CreateSession(ctx, u.ID, token, time.Now().Add(time.Hour))) return jar{"sea_session": token} } startMode := func(c jar, mode string) string { w := call("GET", "/api/v1/auth/oidc/start?mode="+mode, nil, c) expect(w, 200) var out map[string]string must(json.Unmarshal(w.Body.Bytes(), &out)) u, e := url.Parse(out["url"]) must(e) nonce = u.Query().Get("nonce") if u.Query().Get("code_challenge_method") != "S256" { t.Fatal("PKCE not enabled") } return u.Query().Get("state") } start := func(c jar) string { return startMode(c, "login") } callback := func(c jar, state string) *httptest.ResponseRecorder { return call("GET", "/api/v1/auth/oidc/callback?state="+url.QueryEscape(state)+"&code=test-code", nil, c) } off := false localID, e := db.CreateTenant(ctx, store.NewTenant{Slug: "sso-existing", Name: "已有用户", DisplayName: "已有用户", Email: "existing@example.invalid", Password: "existing-password-123", PlanID: 1}) must(e) _ = localID local, e := db.UserByLogin(ctx, "existing@example.invalid") must(e) t.Run("authenticated frontend binding does not merge by email", func(t *testing.T) { c := jar{} subject = "external-local" email = "existing@example.invalid" state := start(c) absent := jar{} w := callback(absent, state) expect(w, 303) if strings.Contains(w.Header().Get("Location"), "complete") { t.Fatal("callback accepted without browser state") } w = callback(c, state) expect(w, 303) if !strings.Contains(w.Header().Get("Location"), "complete") { t.Fatal(w.Header().Get("Location")) } if _, e := db.UserByOIDC(ctx, oidcProviderKey(cfg), subject); e == nil { t.Fatal("email silently linked") } expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "create"}, c), 409) expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "bind", "identifier": local.Email, "password": "wrong"}, c), 401) expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "bind", "identifier": local.Email, "password": "existing-password-123"}, c), 200) linked, e := db.UserByOIDC(ctx, oidcProviderKey(cfg), subject) must(e) if linked.ID != local.ID { t.Fatal("wrong account binding") } expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "create"}, c), 401) c = jar{} w = callback(c, start(c)) expect(w, 303) if !strings.Contains(w.Header().Get("Location"), "login") { t.Fatal("bound identity could not login") } }) t.Run("ordinary account creation has no host and is single use", func(t *testing.T) { c := jar{} subject = "fresh-subject" email = "new-sso@example.invalid" expect(callback(c, start(c)), 303) oldTicket := c["sea_oidc_pending"] expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "create"}, c), 200) u, e := db.UserByOIDC(ctx, oidcProviderKey(cfg), subject) must(e) if u.Role != "tenant" || u.ProjectID != nil { t.Fatal("SSO granted unexpected privileges") } n, e := db.CountProjects(ctx, *u.TenantID) must(e) if n != 0 { t.Fatal("SSO created a host") } replay := jar{"sea_oidc_pending": oldTicket} expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "create"}, replay), 401) if _, e = db.UserByOIDC(ctx, oidcProviderKey(cfg), "FRESH-SUBJECT"); e == nil { t.Fatal("subject lookup is case insensitive") } }) t.Run("new users need verified email and enabled creation", func(t *testing.T) { c := jar{} subject = "unverified" email = "notverified@example.invalid" verified = false expect(callback(c, start(c)), 303) expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "create"}, c), 403) verified = true cfg.AutoCreate = false must(app.writeServiceConfig(httptest.NewRequest("PUT", "https://control.example.invalid", nil), "oidc_config", cfg)) c = jar{} subject = "registration-off" email = "off@example.invalid" expect(callback(c, start(c)), 303) expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "create"}, c), 403) }) t.Run("host SSO is rejected and password policy is enforced by API", func(t *testing.T) { hash, e := auth.HashPassword("host-test-password-123") must(e) result, e := raw.Exec(`INSERT INTO users(email,login_name,display_name,password_hash,role) VALUES('host-sso@example.invalid','host-sso','主机账号',?,'host')`, hash) must(e) id, e := result.LastInsertId() must(e) host, e := db.UserByID(ctx, uint64(id)) must(e) expect(call("GET", "/api/v1/auth/oidc/start?mode=bind", nil, session(host)), 403) cfg.UserPasswordLogin = &off cfg.AdminPasswordLogin = &off must(app.writeServiceConfig(httptest.NewRequest("PUT", "https://control.example.invalid", nil), "oidc_config", cfg)) expect(call("POST", "/api/v1/auth/login", map[string]any{"identifier": local.Email, "password": "existing-password-123"}, jar{}), 403) expect(call("POST", "/api/v1/auth/login", map[string]any{"identifier": admin.Email, "password": "sso-admin-password-123"}, jar{}), 403) expect(call("POST", "/api/v1/auth/login", map[string]any{"identifier": "host-sso", "password": "host-test-password-123"}, jar{}), 200) expect(call("DELETE", "/api/v1/account/oidc", map[string]any{"currentPassword": "existing-password-123"}, session(local)), 409) c := jar{} subject = "external-local" email = local.Email expect(callback(c, start(c)), 303) if c["sea_session"] == "" { t.Fatal("password restriction blocked SSO") } }) t.Run("nonce mismatch and consumed state are rejected", func(t *testing.T) { c := jar{} state := start(c) nonce = "wrong-nonce" w := callback(c, state) expect(w, 303) if !strings.Contains(w.Header().Get("Location"), "claims") { t.Fatal("wrong nonce accepted") } if c["sea_oidc_pending"] != "" { t.Fatal("invalid token created continuation") } expect(callback(c, state), 303) }) t.Run("issuer changes invalidate pending login", func(t *testing.T) { c := jar{} state := start(c) changed := cfg changed.Issuer = "https://other.example.invalid" must(app.writeServiceConfig(httptest.NewRequest("PUT", "https://control.example.invalid", nil), "oidc_config", changed)) w := callback(c, state) expect(w, 303) if !strings.Contains(w.Header().Get("Location"), "provider_changed") { t.Fatal(w.Header().Get("Location")) } must(app.writeServiceConfig(httptest.NewRequest("PUT", "https://control.example.invalid", nil), "oidc_config", cfg)) }) t.Run("settings reject disabling SSO while passwords closed", func(t *testing.T) { body := map[string]any{"graceDays": 3, "recycleDays": 7, "backupRetentionDays": 14, "smtp": secretServiceConfig{}, "oidc": secretServiceConfig{Enabled: false, UserPasswordLogin: &off, AdminPasswordLogin: &off}} expect(call("PUT", "/api/v1/admin/settings", body, session(admin)), 422) body["oidc"] = cfg expect(call("PUT", "/api/v1/admin/settings", body, session(admin)), 422) }) t.Run("bind callback tolerates Strict session cookie but requires live parent", func(t *testing.T) { c := session(admin) subject = "admin-binding" email = admin.Email state := startMode(c, "bind") delete(c, "sea_session") w := callback(c, state) expect(w, 303) if !strings.Contains(w.Header().Get("Location"), "bound") { t.Fatal(w.Header().Get("Location")) } bound, e := db.UserByOIDC(ctx, oidcProviderKey(cfg), subject) must(e) if bound.ID != admin.ID { t.Fatal("wrong administrator identity") } body := map[string]any{"graceDays": 3, "recycleDays": 7, "backupRetentionDays": 14, "smtp": secretServiceConfig{}, "oidc": cfg} expect(call("PUT", "/api/v1/admin/settings", body, session(admin)), 204) c = session(admin) subject = "revoked-parent" state = startMode(c, "bind") hash := sha256.Sum256([]byte(c["sea_session"])) _, e = raw.Exec(`DELETE FROM sessions WHERE token_hash=?`, hash[:]) must(e) delete(c, "sea_session") w = callback(c, state) expect(w, 303) if !strings.Contains(w.Header().Get("Location"), "expired") { t.Fatal("revoked initiating session accepted") } }) }