package api_test import ( "bytes" "context" "crypto/rand" "encoding/base64" "encoding/json" "io" "log/slog" "net/http" "net/http/cookiejar" "net/http/httptest" "net/url" "os" "regexp" "strings" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5/pgxpool" "github.com/redis/go-redis/v9" "git.zb-server.de/ZB-Server/uptimesebi/internal/api" "git.zb-server.de/ZB-Server/uptimesebi/internal/config" "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" "git.zb-server.de/ZB-Server/uptimesebi/internal/migrations" "git.zb-server.de/ZB-Server/uptimesebi/internal/platform" "git.zb-server.de/ZB-Server/uptimesebi/internal/sealed" "git.zb-server.de/ZB-Server/uptimesebi/internal/sso/ssotest" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" ) type env struct { srv *httptest.Server dbPool *pgxpool.Pool rdb *redis.Client api *api.Server } func newEnv(t *testing.T) *env { t.Helper() return newEnvWith(t, nil) } // newEnvWith lets a test adjust the API configuration before start. func newEnvWith(t *testing.T, adjust func(*config.API)) *env { t.Helper() dsn, redisURL := os.Getenv("UPTIME_TEST_DATABASE_URL"), os.Getenv("UPTIME_TEST_REDIS_URL") if dsn == "" || redisURL == "" { t.Skip("UPTIME_TEST_DATABASE_URL and UPTIME_TEST_REDIS_URL must be set") } ctx := context.Background() if _, err := migrations.Up(ctx, dsn); err != nil { t.Fatalf("migrations.Up() failed: %v", err) } pool, err := pgxpool.New(ctx, dsn) if err != nil { t.Fatal(err) } t.Cleanup(pool.Close) opts, err := redis.ParseURL(redisURL) if err != nil { t.Fatal(err) } rdb := redis.NewClient(opts) t.Cleanup(func() { _ = rdb.Close() }) // UPTIME_TEST_REDIS_URL must name a database reserved for tests; clearing // it resets rate limits left over from earlier runs. if err := rdb.FlushDB(ctx).Err(); err != nil { t.Fatalf("FLUSHDB failed: %v", err) } key := make([]byte, 32) _, _ = rand.Read(key) keys, err := sealed.Parse("t:" + base64.StdEncoding.EncodeToString(key)) if err != nil { t.Fatal(err) } catalog, err := i18n.Load() if err != nil { t.Fatal(err) } log := slog.New(slog.DiscardHandler) if os.Getenv("UPTIME_TEST_LOG") != "" { log = slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug})) } e := &env{dbPool: pool, rdb: rdb} r := platform.NewRouter(log) e.srv = httptest.NewUnstartedServer(r) e.srv.StartTLS() t.Cleanup(e.srv.Close) cfg := config.API{ Common: config.Common{Edition: config.EditionSelfHosted}, Signup: config.SignupOpen, SessionIdle: time.Hour, SessionAbsolute: 24 * time.Hour, PublicURL: e.srv.URL, SSOPrivateNetworks: "true", } if adjust != nil { adjust(&cfg) } e.api = api.New(cfg, api.Deps{Log: log, DB: tenant.New(pool), Redis: rdb, Keys: keys, Catalog: catalog}) e.api.Mount(r) return e } // browser is a cookie-keeping client that follows redirects like a browser. type browser struct { t *testing.T base string hc *http.Client csrf string // bearer, if set, is sent as an API token instead of relying on cookies. bearer string } func (e *env) browser(t *testing.T) *browser { jar, _ := cookiejar.New(nil) // Client() returns a shared instance; copy it so each browser has its own jar. hc := *e.srv.Client() hc.Jar = jar return &browser{t: t, base: e.srv.URL, hc: &hc} } func (b *browser) do(method, path string, body any) (int, map[string]any) { b.t.Helper() var rd io.Reader if body != nil { raw, _ := json.Marshal(body) rd = bytes.NewReader(raw) } req, _ := http.NewRequest(method, b.base+path, rd) req.Header.Set("Content-Type", "application/json") if b.csrf != "" { req.Header.Set("X-CSRF-Token", b.csrf) } if b.bearer != "" { req.Header.Set("Authorization", "Bearer "+b.bearer) } resp, err := b.hc.Do(req) if err != nil { b.t.Fatalf("%s %s failed: %v", method, path, err) } defer func() { _ = resp.Body.Close() }() var out map[string]any _ = json.NewDecoder(resp.Body).Decode(&out) if tok, ok := out["csrf_token"].(string); ok { b.csrf = tok } return resp.StatusCode, out } // visit follows redirects and returns the final URL. func (b *browser) visit(path string) *url.URL { b.t.Helper() resp, err := b.hc.Get(b.base + path) if err != nil { b.t.Fatalf("GET %s failed: %v", path, err) } _ = resp.Body.Close() if resp.StatusCode != http.StatusOK { b.t.Errorf("GET %s ended with status %d at %s", path, resp.StatusCode, resp.Request.URL) } return resp.Request.URL } func uniq(prefix string) string { return prefix + strings.ReplaceAll(uuid.NewString()[:8], "-", "") } var consentVersionsField = regexp.MustCompile(`name="(?:consent_versions|versions)" value="([^"]*)"`) // consentShown returns the document versions a page asks to accept, empty // when it asks for none. func consentShown(html string) string { if m := consentVersionsField.FindStringSubmatch(html); m != nil { return m[1] } return "" } // acceptConsent accepts the documents the console asks for, as someone // ticking the box on /consent would. func (b *browser) acceptConsent() { b.t.Helper() _, _, html := b.page("/consent") if v := consentShown(html); v != "" { if st, body := b.do("POST", "/api/v1/consent", map[string]any{"versions": v, "accept": true}); st != http.StatusOK { b.t.Fatalf("accept consent = %d %v", st, body) } } } func (b *browser) signup(email, slug string) { b.t.Helper() // Tick the consent box the sign-up page shows, if any. _, _, form := b.page("/signup") versions := consentShown(form) st, body := b.do("POST", "/api/v1/auth/signup", map[string]any{ "email": email, "password": "correct horse battery", "org_name": slug, "org_slug": slug, "consent": versions != "", "consent_versions": versions, }) if st != http.StatusOK { b.t.Fatalf("signup(%s) = %d %v, want 200", email, st, body) } } func TestSSO(t *testing.T) { e := newEnv(t) idp := ssotest.New(t) slug := uniq("sso-") domain := uniq("d") + ".test" owner := e.browser(t) owner.signup("owner@"+domain, slug) st, body := owner.do("POST", "/api/v1/org/sso", map[string]any{ "name": "Corp IdP", "issuer": idp.Issuer(), "client_id": idp.ClientID, "client_secret": idp.Secret, "allowed_domains": []string{domain}, "auto_provision": true, }) if st != http.StatusCreated { t.Fatalf("create provider = %d %v, want 201", st, body) } if body["has_client_secret"] != true || body["client_secret"] != nil { t.Errorf("create provider response = %v, want has_client_secret and no secret", body) } t.Run("other org cannot see provider", func(t *testing.T) { other := e.browser(t) other.signup("x@"+uniq("o")+".test", uniq("other-")) st, body := other.do("GET", "/api/v1/org/sso", nil) if st != http.StatusOK || len(body["providers"].([]any)) != 0 { t.Errorf("GET /api/v1/org/sso as other org = %d %v, want 200 with no providers", st, body) } }) t.Run("auto provisioning", func(t *testing.T) { idp.SetUser(ssotest.User{Subject: uniq("s"), Email: "new@" + domain, EmailVerified: true, Name: "New"}) u := e.browser(t) if got := u.visit("/sso/" + slug); got.Path != "/" || got.Query().Get("sso_error") != "" { t.Fatalf("SSO login landed on %s, want /", got) } st, me := u.do("GET", "/api/v1/me", nil) if st != http.StatusOK || me["email"] != "new@"+domain { t.Errorf("GET /api/v1/me = %d %v, want new@%s", st, me, domain) } st, _ = u.do("GET", "/api/v1/org/sso", nil) if st != http.StatusForbidden { t.Errorf("GET /api/v1/org/sso as member = %d, want 403", st) } }) t.Run("unverified email is not provisioned", func(t *testing.T) { idp.SetUser(ssotest.User{Subject: uniq("s"), Email: "unverified@" + domain, EmailVerified: false}) if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_not_provisioned" { t.Errorf("SSO login landed on %s, want sso_error=sso_not_provisioned", got) } }) t.Run("foreign domain is not provisioned", func(t *testing.T) { idp.SetUser(ssotest.User{Subject: uniq("s"), Email: "x@elsewhere.test", EmailVerified: true}) if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_not_provisioned" { t.Errorf("SSO login landed on %s, want sso_error=sso_not_provisioned", got) } }) t.Run("existing email requires explicit linking", func(t *testing.T) { subject := uniq("s") idp.SetUser(ssotest.User{Subject: subject, Email: "owner@" + domain, EmailVerified: true}) if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_link_required" { t.Fatalf("SSO login landed on %s, want sso_error=sso_link_required", got) } if got := owner.visit("/sso/" + slug + "?link=1"); got.Path != "/settings/security" || got.Query().Get("sso") != "linked" { t.Fatalf("link flow landed on %s, want /settings/security?sso=linked", got) } fresh := e.browser(t) if got := fresh.visit("/sso/" + slug); got.Path != "/" { t.Fatalf("SSO login after linking landed on %s, want /", got) } if _, me := fresh.do("GET", "/api/v1/me", nil); me["email"] != "owner@"+domain { t.Errorf("GET /api/v1/me after linked login = %v, want owner", me) } }) t.Run("callback without browser binding is rejected", func(t *testing.T) { attacker := e.browser(t) attacker.hc.CheckRedirect = func(req *http.Request, _ []*http.Request) error { if strings.HasPrefix(req.URL.Path, "/sso/callback") { return http.ErrUseLastResponse } return nil } resp, err := attacker.hc.Get(attacker.base + "/sso/" + slug) if err != nil { t.Fatal(err) } _ = resp.Body.Close() callback := resp.Header.Get("Location") if got := e.browser(t).visit(strings.TrimPrefix(callback, attacker.base)); got.Query().Get("sso_error") != "sso_expired" { t.Errorf("replaying callback in another browser landed on %s, want sso_error=sso_expired", got) } }) t.Run("disabled provider", func(t *testing.T) { _, list := owner.do("GET", "/api/v1/org/sso", nil) p := list["providers"].([]any)[0].(map[string]any) st, body := owner.do("PUT", "/api/v1/org/sso/"+p["id"].(string), map[string]any{ "name": p["name"], "issuer": p["issuer"], "client_id": p["client_id"], "enabled": false, }) if st != http.StatusOK || body["has_client_secret"] != true { t.Fatalf("PUT provider = %d %v, want 200 keeping the secret", st, body) } if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_unavailable" { t.Errorf("SSO login with disabled provider landed on %s, want sso_error=sso_unavailable", got) } }) } func TestSSOProviderValidation(t *testing.T) { e := newEnv(t) owner := e.browser(t) owner.signup("o@"+uniq("v")+".test", uniq("val-")) tests := []struct { name string body map[string]any want string }{ {"bad scheme", map[string]any{"name": "x", "issuer": "ftp://idp.test", "client_id": "c"}, "sso_invalid_issuer"}, {"unreachable", map[string]any{"name": "x", "issuer": "http://127.0.0.1:1", "client_id": "c"}, "sso_discovery_failed"}, {"bad domain", map[string]any{"name": "x", "issuer": "https://idp.test", "client_id": "c", "allowed_domains": []string{"not a domain"}}, "invalid_domain"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { st, body := owner.do("POST", "/api/v1/org/sso", tt.body) if st != http.StatusUnprocessableEntity || body["error"] != tt.want { t.Errorf("POST /api/v1/org/sso = %d %v, want 422 %s", st, body["error"], tt.want) } }) } }