#123 was built before staticcheck came back in #125. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
201 lines
8.3 KiB
Go
201 lines
8.3 KiB
Go
package api_test
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/sso/ssotest"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
|
)
|
|
|
|
// fakeGitHub answers like GitHub's OAuth and REST API for one user.
|
|
func fakeGitHub(t *testing.T, id int64, email string, verified bool) *httptest.Server {
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
switch r.URL.Path {
|
|
case "/login/oauth/authorize":
|
|
back, _ := url.Parse(r.URL.Query().Get("redirect_uri"))
|
|
q := back.Query()
|
|
q.Set("code", "gh-code")
|
|
q.Set("state", r.URL.Query().Get("state"))
|
|
back.RawQuery = q.Encode()
|
|
http.Redirect(w, r, back.String(), http.StatusFound)
|
|
case "/login/oauth/access_token":
|
|
if r.FormValue("code") != "gh-code" || r.FormValue("code_verifier") == "" {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(`{"access_token":"gh-token","token_type":"bearer"}`))
|
|
case "/api/v3/user":
|
|
if r.Header.Get("Authorization") != "Bearer gh-token" {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"id": id, "login": "octo", "name": ""})
|
|
case "/api/v3/user/emails":
|
|
_ = json.NewEncoder(w).Encode([]map[string]any{
|
|
{"email": "other@" + uniq("x") + ".test", "primary": false, "verified": true},
|
|
{"email": email, "primary": true, "verified": verified},
|
|
})
|
|
default:
|
|
http.NotFound(w, r)
|
|
}
|
|
}))
|
|
t.Cleanup(srv.Close)
|
|
return srv
|
|
}
|
|
|
|
func TestPlatformSSO(t *testing.T) {
|
|
e := newEnv(t)
|
|
ctx := context.Background()
|
|
idp := ssotest.New(t)
|
|
admin := e.browser(t)
|
|
admin.signup("admin@"+uniq("psso")+".test", uniq("psso-"))
|
|
if err := tenant.New(e.dbPool).Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
|
return q.MakeAdmin(ctx, admin.userIDSelf())
|
|
}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
st, google := admin.do("POST", "/api/v1/admin/identity-providers", map[string]any{
|
|
"kind": "oidc", "name": "Google", "issuer": idp.Issuer(), "client_id": idp.ClientID, "client_secret": idp.Secret,
|
|
"allow_signup": true, "enabled": true,
|
|
})
|
|
if st != http.StatusCreated || google["client_secret_set"] != true || strings.Contains(mustJSON(google), idp.Secret) {
|
|
t.Fatalf("create provider = %d %v", st, google)
|
|
}
|
|
start := "/login/sso/" + google["id"].(string)
|
|
t.Cleanup(func() {
|
|
_ = e.asSystem(t, func(tx pgx.Tx) error {
|
|
_, err := tx.Exec(ctx, `DELETE FROM platform_identity_providers`)
|
|
return err
|
|
})
|
|
})
|
|
if _, _, html := e.browser(t).page("/login"); !strings.Contains(html, "Continue with Google") || !strings.Contains(html, start) {
|
|
t.Error("the login page lacks the provider")
|
|
}
|
|
|
|
// Sign up, then sign in again with the same identity.
|
|
newEmail := uniq("new") + "@example.test"
|
|
subject := uniq("sub")
|
|
idp.SetUser(ssotest.User{Subject: subject, Email: newEmail, EmailVerified: true, Name: "New Person"})
|
|
u := e.browser(t)
|
|
if got := u.visit(start); got.Path != "/orgs/new" {
|
|
t.Fatalf("sign-up landed on %s, want /orgs/new", got)
|
|
}
|
|
if _, me := u.do("GET", "/api/v1/me", nil); me["email"] != newEmail {
|
|
t.Errorf("me = %v", me)
|
|
}
|
|
if got := e.browser(t).visit(start); got.Path != "/orgs/new" || got.Query().Get("sso_error") != "" {
|
|
t.Errorf("second sign-in landed on %s", got)
|
|
}
|
|
|
|
// Existing accounts are never taken over, also not through an alias.
|
|
owner := e.browser(t)
|
|
ownerBox := uniq("owner")
|
|
owner.signup(ownerBox+"@example.test", uniq("psso-o-"))
|
|
for _, email := range []string{ownerBox + "@example.test", ownerBox + "+x@example.test"} {
|
|
idp.SetUser(ssotest.User{Subject: uniq("sub"), Email: email, EmailVerified: true})
|
|
if got := e.browser(t).visit(start); got.Query().Get("sso_error") != "sso_link_required" {
|
|
t.Errorf("%s: landed on %s, want sso_link_required", email, got)
|
|
}
|
|
}
|
|
idp.SetUser(ssotest.User{Subject: uniq("sub"), Email: uniq("u") + "@example.test", EmailVerified: false})
|
|
if got := e.browser(t).visit(start); got.Query().Get("sso_error") != "sso_email_unverified" {
|
|
t.Errorf("unverified email landed on %s", got)
|
|
}
|
|
|
|
// The owner links the provider while signed in and then signs in with it.
|
|
linked := uniq("sub")
|
|
idp.SetUser(ssotest.User{Subject: linked, Email: "whatever@" + uniq("x") + ".test", EmailVerified: true})
|
|
if got := owner.visit(start + "?link=1"); got.Path != "/settings/security" || got.Query().Get("sso") != "linked" {
|
|
t.Fatalf("linking landed on %s", got)
|
|
}
|
|
if _, _, html := owner.page("/settings/security"); !strings.Contains(html, "Disconnect") {
|
|
t.Error("the security page lacks the linked provider")
|
|
}
|
|
via := e.browser(t)
|
|
if got := via.visit(start); got.Path != "/" {
|
|
t.Errorf("sign-in through the linked identity landed on %s", got)
|
|
}
|
|
if _, me := via.do("GET", "/api/v1/me", nil); me["email"] != ownerBox+"@example.test" {
|
|
t.Errorf("signed in as %v", me["email"])
|
|
}
|
|
|
|
// The account's second factor still applies after the provider.
|
|
_, codes := owner.enableTOTP()
|
|
mfa := e.browser(t)
|
|
if got := mfa.visit(start); got.Path != "/login" || got.Query().Get("mfa") != "1" {
|
|
t.Fatalf("sign-in with TOTP landed on %s", got)
|
|
}
|
|
if st, _ := mfa.do("GET", "/api/v1/me", nil); st != http.StatusUnauthorized {
|
|
t.Error("signed in before the second factor")
|
|
}
|
|
if st, body := mfa.do("POST", "/api/v1/auth/login/totp", map[string]any{"code": codes[0]}); st != http.StatusOK {
|
|
t.Fatalf("second factor = %d %v", st, body)
|
|
}
|
|
|
|
// Unlinking: never the last way to sign in.
|
|
u.page("/orgs/new")
|
|
st, body := u.do("DELETE", "/api/v1/me/identities/"+google["id"].(string), nil)
|
|
expect(t, "unlink the only sign-in", st, body, http.StatusConflict, "last_sign_in")
|
|
if st, _ := owner.do("DELETE", "/api/v1/me/identities/"+google["id"].(string), nil); st != http.StatusNoContent {
|
|
t.Errorf("unlink = %d", st)
|
|
}
|
|
|
|
// Removing a provider some accounts depend on is refused.
|
|
st, body = admin.do("DELETE", "/api/v1/admin/identity-providers/"+google["id"].(string), nil)
|
|
expect(t, "delete a provider in use", st, body, http.StatusConflict, "idp_in_use")
|
|
|
|
// Sign-up closed for this provider.
|
|
google["allow_signup"], google["client_secret"] = false, ""
|
|
if st, body := admin.do("PUT", "/api/v1/admin/identity-providers/"+google["id"].(string), google); st != http.StatusOK || body["client_secret_set"] != true {
|
|
t.Fatalf("update = %d %v", st, body)
|
|
}
|
|
idp.SetUser(ssotest.User{Subject: uniq("sub"), Email: uniq("late") + "@example.test", EmailVerified: true})
|
|
if got := e.browser(t).visit(start); got.Query().Get("sso_error") != "sso_not_provisioned" {
|
|
t.Errorf("sign-up through a closed provider landed on %s", got)
|
|
}
|
|
|
|
// GitHub, here a GitHub Enterprise server.
|
|
ghEmail := uniq("octo") + "@example.test"
|
|
gh := fakeGitHub(t, 4242, ghEmail, true)
|
|
st, github := admin.do("POST", "/api/v1/admin/identity-providers", map[string]any{
|
|
"kind": "github", "name": "GitHub", "issuer": gh.URL, "client_id": "gh-client", "client_secret": "gh-secret",
|
|
"allow_signup": true, "enabled": true,
|
|
})
|
|
if st != http.StatusCreated {
|
|
t.Fatalf("create github = %d %v", st, github)
|
|
}
|
|
g := e.browser(t)
|
|
if got := g.visit("/login/sso/" + github["id"].(string)); got.Path != "/orgs/new" {
|
|
t.Fatalf("GitHub sign-up landed on %s", got)
|
|
}
|
|
if _, me := g.do("GET", "/api/v1/me", nil); me["email"] != ghEmail || me["display_name"] != "octo" {
|
|
t.Errorf("GitHub account = %v", me)
|
|
}
|
|
unverified := fakeGitHub(t, 777, uniq("u")+"@example.test", false)
|
|
_, gh2 := admin.do("POST", "/api/v1/admin/identity-providers", map[string]any{
|
|
"kind": "github", "name": "GHE", "issuer": unverified.URL, "client_id": "c", "client_secret": "s", "allow_signup": true, "enabled": true,
|
|
})
|
|
if got := e.browser(t).visit("/login/sso/" + gh2["id"].(string)); got.Query().Get("sso_error") != "sso_email_unverified" {
|
|
t.Errorf("GitHub with an unverified primary email landed on %s", got)
|
|
}
|
|
|
|
// Admins only, secrets never listed.
|
|
if st, _ := u.do("GET", "/api/v1/admin/identity-providers", nil); st != http.StatusForbidden {
|
|
t.Errorf("non-admin listing = %d", st)
|
|
}
|
|
_, list := admin.do("GET", "/api/v1/admin/identity-providers", nil)
|
|
if raw := mustJSON(list); strings.Contains(raw, "gh-secret") || strings.Contains(raw, idp.Secret) || !strings.Contains(raw, "/sso/callback") {
|
|
t.Errorf("provider list = %s", raw)
|
|
}
|
|
}
|