diff --git a/go.mod b/go.mod index 6efc2e3..7c78cd5 100644 --- a/go.mod +++ b/go.mod @@ -5,11 +5,19 @@ go 1.27.1 require ( github.com/a-h/templ v0.3.1118 github.com/caarlos0/env/v11 v11.4.2 + github.com/coreos/go-oidc/v3 v3.21.0 github.com/gin-gonic/gin v1.12.0 + github.com/go-jose/go-jose/v4 v4.1.4 + github.com/go-playground/validator/v10 v10.30.6 github.com/google/uuid v1.6.0 github.com/jackc/pgx/v5 v5.13.0 + github.com/nicksnyder/go-i18n/v2 v2.7.0 + github.com/pquerna/otp v1.5.0 github.com/pressly/goose/v3 v3.30.1 github.com/redis/go-redis/v9 v9.23.0 + golang.org/x/crypto v0.59.0 + golang.org/x/oauth2 v0.38.0 + golang.org/x/text v0.44.0 ) require ( @@ -29,7 +37,6 @@ require ( github.com/gin-contrib/sse v1.1.0 // indirect github.com/go-playground/locales v0.14.2 // indirect github.com/go-playground/universal-translator v0.18.2 // indirect - github.com/go-playground/validator/v10 v10.30.6 // indirect github.com/goccy/go-json v0.10.5 // indirect github.com/goccy/go-yaml v1.19.2 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect @@ -44,9 +51,7 @@ require ( github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/natefinch/atomic v1.0.1 // indirect - github.com/nicksnyder/go-i18n/v2 v2.7.0 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect - github.com/pquerna/otp v1.5.0 // indirect github.com/quic-go/qpack v0.6.0 // indirect github.com/quic-go/quic-go v0.59.0 // indirect github.com/sethvargo/go-retry v0.5.0 // indirect @@ -56,12 +61,10 @@ require ( go.uber.org/atomic v1.12.0 // indirect go.uber.org/multierr v1.11.0 // indirect golang.org/x/arch v0.22.0 // indirect - golang.org/x/crypto v0.59.0 // indirect golang.org/x/mod v0.43.0 // indirect golang.org/x/net v0.62.0 // indirect golang.org/x/sync v0.25.0 // indirect golang.org/x/sys v0.50.0 // indirect - golang.org/x/text v0.44.0 // indirect golang.org/x/tools v0.52.0 // indirect google.golang.org/protobuf v1.36.12 // indirect ) diff --git a/go.sum b/go.sum index dc44847..ea1bd41 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= +github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/a-h/parse v0.0.42 h1:OUb8soeTG5+mRWieRyS/OyNU7Xl0+4wr4kPKKPa/WUQ= github.com/a-h/parse v0.0.42/go.mod h1:X9OHJ1IjgakwZoDSoHYhdtKKD0zXZ2agpoIztPAA95w= github.com/a-h/templ v0.3.1118 h1:rZv90g1xVb7ieNz4j5WK6yQePZfsg7j7fVvP8qVmeJI= @@ -26,6 +28,8 @@ github.com/cli/browser v1.3.0 h1:LejqCrpWr+1pRqmEPDGnTZOjsMe7sehifLynZJuqJpo= github.com/cli/browser v1.3.0/go.mod h1:HH8s+fOAxjhQoBUAsKuPCbqUuxZDhQ2/aD+SzsEfBTk= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= +github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM= +github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -35,26 +39,20 @@ github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w= github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE= github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho= github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= -github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw= -github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E= github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4= github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w= github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8= github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc= +github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= +github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= -github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= -github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY= github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= -github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= -github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU= github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk= -github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w= -github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM= github.com/go-playground/validator/v10 v10.30.6 h1:E+mymlPNRzAMNz1FShrRvLeGWcprF5w305eLLgWieuo= github.com/go-playground/validator/v10 v10.30.6/go.mod h1:jPLL8SKCXGe/g87QmEyNw3NO28nmGt5GCnZnufm7rj4= github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= @@ -78,8 +76,6 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= -github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= -github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0= github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE= github.com/mattn/go-colorable v0.1.16 h1:+2YjeAe7xP1OQbZW1jERPWWCDLlNqFNCvjiqGiAt84A= @@ -116,8 +112,6 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY= github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= -github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0= -github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -150,14 +144,14 @@ go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM= go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI= golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= -golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= -golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg= golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY= golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/oauth2 v0.38.0 h1:uW7XQbcu1eoiQS7uMJvLOjPMl04bTbmY1VeRPxvbspI= +golang.org/x/oauth2 v0.38.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= diff --git a/internal/sso/httpclient.go b/internal/sso/httpclient.go new file mode 100644 index 0000000..c132918 --- /dev/null +++ b/internal/sso/httpclient.go @@ -0,0 +1,45 @@ +package sso + +import ( + "context" + "errors" + "net" + "net/http" + "net/netip" + "syscall" + "time" +) + +// ErrForbiddenAddress is returned when an IdP resolves to an address the +// client may not contact. +var ErrForbiddenAddress = errors.New("sso: issuer resolves to a non-public address") + +var cgnat = netip.MustParsePrefix("100.64.0.0/10") + +// SafeHTTPClient returns a client for talking to customer-configured IdPs. +// Unless allowPrivate is set it refuses to connect to loopback, private, +// link-local and similar ranges. The check runs on the resolved address at +// dial time, so DNS rebinding and redirects cannot bypass it. +func SafeHTTPClient(allowPrivate bool) *http.Client { + d := &net.Dialer{Timeout: 5 * time.Second} + if !allowPrivate { + d.Control = func(_, address string, _ syscall.RawConn) error { + ap, err := netip.ParseAddrPort(address) + if err != nil || !isPublic(ap.Addr()) { + return ErrForbiddenAddress + } + return nil + } + } + tr := http.DefaultTransport.(*http.Transport).Clone() + tr.Proxy = nil + tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { + return d.DialContext(ctx, network, addr) + } + return &http.Client{Transport: tr, Timeout: 10 * time.Second} +} + +func isPublic(a netip.Addr) bool { + a = a.Unmap() + return a.IsGlobalUnicast() && !a.IsPrivate() && !cgnat.Contains(a) +} diff --git a/internal/sso/httpclient_test.go b/internal/sso/httpclient_test.go new file mode 100644 index 0000000..226344d --- /dev/null +++ b/internal/sso/httpclient_test.go @@ -0,0 +1,46 @@ +package sso + +import ( + "errors" + "net/http" + "net/http/httptest" + "net/netip" + "testing" +) + +func TestIsPublic(t *testing.T) { + tests := map[string]bool{ + "8.8.8.8": true, + "2606:4700::1111": true, + "127.0.0.1": false, + "10.1.2.3": false, + "172.16.0.1": false, + "192.168.1.1": false, + "169.254.169.254": false, + "100.64.0.1": false, + "0.0.0.0": false, + "::1": false, + "fd00::1": false, + "fe80::1": false, + "::ffff:127.0.0.1": false, + } + for addr, want := range tests { + if got := isPublic(netip.MustParseAddr(addr)); got != want { + t.Errorf("isPublic(%s) = %t, want %t", addr, got, want) + } + } +} + +func TestSafeHTTPClientBlocksLoopback(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + defer srv.Close() + + if _, err := SafeHTTPClient(false).Get(srv.URL); !errors.Is(err, ErrForbiddenAddress) { + t.Errorf("Get(%s) with private networks denied: error = %v, want %v", srv.URL, err, ErrForbiddenAddress) + } + resp, err := SafeHTTPClient(true).Get(srv.URL) + if err != nil { + t.Fatalf("Get(%s) with private networks allowed failed: %v", srv.URL, err) + } + _ = resp.Body.Close() +} diff --git a/internal/sso/sso.go b/internal/sso/sso.go new file mode 100644 index 0000000..c46bb03 --- /dev/null +++ b/internal/sso/sso.go @@ -0,0 +1,188 @@ +// Package sso implements OpenID Connect sign-in against identity providers +// that each organization configures for itself. +package sso + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "sync" + "time" + + "github.com/coreos/go-oidc/v3/oidc" + "golang.org/x/oauth2" +) + +// Provider is one organization's IdP registration. +type Provider struct { + Issuer string + ClientID string + ClientSecret string + Scopes []string +} + +// Claims are the ID token fields used to identify and provision a user. +type Claims struct { + Subject string `json:"sub"` + Email string `json:"email"` + EmailVerified bool `json:"email_verified"` + Name string `json:"name"` +} + +// Flow holds the per-attempt secrets that must survive the redirect to the +// IdP. Callers store it server side, keyed by State. +type Flow struct { + State string + Nonce string + Verifier string +} + +// ErrInvalidIssuer is returned for issuer URLs that are malformed or use a +// scheme the client does not allow. +var ErrInvalidIssuer = errors.New("sso: invalid issuer url") + +const discoveryTTL = time.Hour + +// Client performs discovery, builds authorization URLs and verifies +// callbacks. Discovery documents are cached per issuer. +type Client struct { + http *http.Client + redirectURL string + allowHTTP bool + now func() time.Time + + mu sync.Mutex + cache map[string]cached +} + +type cached struct { + provider *oidc.Provider + expires time.Time +} + +// New returns a Client whose callbacks land on redirectURL. httpClient is +// used for every request to an IdP; pass one from SafeHTTPClient. allowHTTP +// permits plain-http issuers, which only makes sense for IdPs on a private +// network. +func New(httpClient *http.Client, redirectURL string, allowHTTP bool) *Client { + return &Client{ + http: httpClient, + redirectURL: redirectURL, + allowHTTP: allowHTTP, + now: time.Now, + cache: map[string]cached{}, + } +} + +// RedirectURL is the callback URL to register at the IdP. +func (c *Client) RedirectURL() string { return c.redirectURL } + +// ValidateIssuer checks the URL syntactically and runs discovery, so that +// misconfiguration surfaces when an admin saves the provider rather than +// when users try to sign in. +func (c *Client) ValidateIssuer(ctx context.Context, issuer string) error { + if err := c.checkIssuer(issuer); err != nil { + return err + } + _, err := c.discover(ctx, issuer) + return err +} + +func (c *Client) checkIssuer(issuer string) error { + u, err := url.Parse(issuer) + if err != nil || u.Host == "" || u.RawQuery != "" || u.Fragment != "" || u.User != nil { + return ErrInvalidIssuer + } + if u.Scheme != "https" && !(c.allowHTTP && u.Scheme == "http") { + return ErrInvalidIssuer + } + return nil +} + +func (c *Client) discover(ctx context.Context, issuer string) (*oidc.Provider, error) { + c.mu.Lock() + if e, ok := c.cache[issuer]; ok && c.now().Before(e.expires) { + c.mu.Unlock() + return e.provider, nil + } + c.mu.Unlock() + + p, err := oidc.NewProvider(oidc.ClientContext(ctx, c.http), issuer) + if err != nil { + return nil, fmt.Errorf("sso: discovery for %s: %w", issuer, err) + } + c.mu.Lock() + c.cache[issuer] = cached{provider: p, expires: c.now().Add(discoveryTTL)} + c.mu.Unlock() + return p, nil +} + +func (c *Client) oauth(p Provider, op *oidc.Provider) *oauth2.Config { + scopes := p.Scopes + if !slices.Contains(scopes, oidc.ScopeOpenID) { + scopes = append([]string{oidc.ScopeOpenID}, scopes...) + } + return &oauth2.Config{ + ClientID: p.ClientID, + ClientSecret: p.ClientSecret, + Endpoint: op.Endpoint(), + RedirectURL: c.redirectURL, + Scopes: scopes, + } +} + +// NewFlow returns fresh state, nonce and PKCE verifier. +func NewFlow(random func() string) Flow { + return Flow{State: random(), Nonce: random(), Verifier: oauth2.GenerateVerifier()} +} + +// AuthURL returns the IdP URL to redirect the browser to. +func (c *Client) AuthURL(ctx context.Context, p Provider, f Flow) (string, error) { + if err := c.checkIssuer(p.Issuer); err != nil { + return "", err + } + op, err := c.discover(ctx, p.Issuer) + if err != nil { + return "", err + } + return c.oauth(p, op).AuthCodeURL(f.State, + oidc.Nonce(f.Nonce), + oauth2.S256ChallengeOption(f.Verifier), + ), nil +} + +// Exchange redeems the authorization code and verifies the ID token's +// signature, issuer, audience, expiry and nonce. +func (c *Client) Exchange(ctx context.Context, p Provider, f Flow, code string) (Claims, error) { + op, err := c.discover(ctx, p.Issuer) + if err != nil { + return Claims{}, err + } + ctx = oidc.ClientContext(ctx, c.http) + tok, err := c.oauth(p, op).Exchange(ctx, code, oauth2.VerifierOption(f.Verifier)) + if err != nil { + return Claims{}, fmt.Errorf("sso: code exchange: %w", err) + } + raw, ok := tok.Extra("id_token").(string) + if !ok { + return Claims{}, errors.New("sso: token response without id_token") + } + idt, err := op.VerifierContext(ctx, &oidc.Config{ClientID: p.ClientID, Now: c.now}).Verify(ctx, raw) + if err != nil { + return Claims{}, fmt.Errorf("sso: id token: %w", err) + } + if idt.Nonce != f.Nonce { + return Claims{}, errors.New("sso: id token nonce mismatch") + } + var cl Claims + if err := idt.Claims(&cl); err != nil { + return Claims{}, fmt.Errorf("sso: id token claims: %w", err) + } + if cl.Subject == "" { + return Claims{}, errors.New("sso: id token without subject") + } + return cl, nil +} diff --git a/internal/sso/sso_test.go b/internal/sso/sso_test.go new file mode 100644 index 0000000..d79cda0 --- /dev/null +++ b/internal/sso/sso_test.go @@ -0,0 +1,115 @@ +package sso_test + +import ( + "context" + "crypto/rand" + "errors" + "net/http" + "net/url" + "testing" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/sso" + "git.zb-server.de/ZB-Server/uptimesebi/internal/sso/ssotest" +) + +const callback = "https://uptime.example/sso/callback" + +// authorize follows the IdP redirect and returns the code and state it +// would deliver to the callback. +func authorize(t *testing.T, authURL string) (code, state string) { + t.Helper() + noFollow := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + resp, err := noFollow.Get(authURL) + if err != nil { + t.Fatalf("GET %s failed: %v", authURL, err) + } + _ = resp.Body.Close() + loc, err := url.Parse(resp.Header.Get("Location")) + if err != nil || resp.StatusCode != http.StatusFound { + t.Fatalf("authorize = %d %q, want 302 to callback", resp.StatusCode, resp.Header.Get("Location")) + } + return loc.Query().Get("code"), loc.Query().Get("state") +} + +func setup(t *testing.T) (*ssotest.IDP, *sso.Client, sso.Provider) { + t.Helper() + idp := ssotest.New(t) + c := sso.New(sso.SafeHTTPClient(true), callback, true) + p := sso.Provider{Issuer: idp.Issuer(), ClientID: idp.ClientID, ClientSecret: idp.Secret, Scopes: []string{"email"}} + return idp, c, p +} + +func TestFlow(t *testing.T) { + idp, c, p := setup(t) + idp.SetUser(ssotest.User{Subject: "u-1", Email: "a@corp.test", EmailVerified: true, Name: "A"}) + ctx := context.Background() + + flow := sso.NewFlow(rand.Text) + authURL, err := c.AuthURL(ctx, p, flow) + if err != nil { + t.Fatalf("AuthURL() failed: %v", err) + } + code, state := authorize(t, authURL) + if state != flow.State { + t.Fatalf("state = %q, want %q", state, flow.State) + } + got, err := c.Exchange(ctx, p, flow, code) + if err != nil { + t.Fatalf("Exchange() failed: %v", err) + } + want := sso.Claims{Subject: "u-1", Email: "a@corp.test", EmailVerified: true, Name: "A"} + if got != want { + t.Errorf("Exchange() = %+v, want %+v", got, want) + } +} + +func TestExchangeRejects(t *testing.T) { + tests := []struct { + name string + tamper func(*ssotest.IDP, *sso.Flow) + }{ + {"wrong nonce", func(i *ssotest.IDP, _ *sso.Flow) { i.NonceOverride = "other" }}, + {"wrong audience", func(i *ssotest.IDP, _ *sso.Flow) { i.AudienceOverride = "someone-else" }}, + {"wrong pkce verifier", func(_ *ssotest.IDP, f *sso.Flow) { f.Verifier = "x" + f.Verifier[1:] }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + idp, c, p := setup(t) + idp.SetUser(ssotest.User{Subject: "u-1"}) + ctx := context.Background() + flow := sso.NewFlow(rand.Text) + authURL, err := c.AuthURL(ctx, p, flow) + if err != nil { + t.Fatalf("AuthURL() failed: %v", err) + } + code, _ := authorize(t, authURL) + tt.tamper(idp, &flow) + if _, err := c.Exchange(ctx, p, flow, code); err == nil { + t.Error("Exchange() error = nil, want rejection") + } + }) + } +} + +func TestValidateIssuer(t *testing.T) { + idp, _, _ := setup(t) + strict := sso.New(sso.SafeHTTPClient(false), callback, false) + tests := []struct { + issuer string + client *sso.Client + want error + }{ + {"ftp://idp.test", strict, sso.ErrInvalidIssuer}, + {"https://idp.test/?q=1", strict, sso.ErrInvalidIssuer}, + {"https://user@idp.test", strict, sso.ErrInvalidIssuer}, + {idp.Issuer(), strict, sso.ErrInvalidIssuer}, + {"https://127.0.0.1:1", strict, sso.ErrForbiddenAddress}, + {idp.Issuer(), sso.New(sso.SafeHTTPClient(true), callback, true), nil}, + } + for _, tt := range tests { + err := tt.client.ValidateIssuer(context.Background(), tt.issuer) + if !errors.Is(err, tt.want) { + t.Errorf("ValidateIssuer(%q) = %v, want %v", tt.issuer, err, tt.want) + } + } +} diff --git a/internal/sso/ssotest/idp.go b/internal/sso/ssotest/idp.go new file mode 100644 index 0000000..062a66a --- /dev/null +++ b/internal/sso/ssotest/idp.go @@ -0,0 +1,166 @@ +// Package ssotest provides a minimal OpenID Connect provider for tests. +package ssotest + +import ( + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "sync" + "testing" + "time" + + "github.com/go-jose/go-jose/v4" + "github.com/go-jose/go-jose/v4/jwt" +) + +// User is the identity the IDP asserts for the next login. +type User struct { + Subject string + Email string + EmailVerified bool + Name string +} + +// IDP is an in-memory authorization server. It signs ID tokens with a fresh +// RSA key and enforces PKCE. +type IDP struct { + Server *httptest.Server + ClientID string + Secret string + + key *rsa.PrivateKey + signer jose.Signer + + mu sync.Mutex + user User + codes map[string]grant + // NonceOverride, when set, replaces the nonce in issued tokens. + NonceOverride string + // AudienceOverride, when set, replaces the audience in issued tokens. + AudienceOverride string +} + +type grant struct { + nonce, challenge, redirect string + user User +} + +// New starts an IDP that is shut down when t ends. +func New(t *testing.T) *IDP { + t.Helper() + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: jose.JSONWebKey{Key: key, KeyID: "k1"}}, nil) + if err != nil { + t.Fatal(err) + } + idp := &IDP{ClientID: "client-1", Secret: "secret-1", key: key, signer: signer, codes: map[string]grant{}} + mux := http.NewServeMux() + mux.HandleFunc("GET /.well-known/openid-configuration", idp.discovery) + mux.HandleFunc("GET /keys", idp.keys) + mux.HandleFunc("GET /authorize", idp.authorize) + mux.HandleFunc("POST /token", idp.token) + idp.Server = httptest.NewServer(mux) + t.Cleanup(idp.Server.Close) + return idp +} + +// Issuer is the issuer URL to configure. +func (i *IDP) Issuer() string { return i.Server.URL } + +// SetUser selects who the next authorization asserts. +func (i *IDP) SetUser(u User) { + i.mu.Lock() + defer i.mu.Unlock() + i.user = u +} + +func (i *IDP) discovery(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, map[string]any{ + "issuer": i.Issuer(), + "authorization_endpoint": i.Issuer() + "/authorize", + "token_endpoint": i.Issuer() + "/token", + "jwks_uri": i.Issuer() + "/keys", + "response_types_supported": []string{"code"}, + "subject_types_supported": []string{"public"}, + "id_token_signing_alg_values_supported": []string{"RS256"}, + }) +} + +func (i *IDP) keys(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{Key: &i.key.PublicKey, KeyID: "k1", Algorithm: "RS256", Use: "sig"}}}) +} + +// authorize skips the login screen and immediately redirects back with a code. +func (i *IDP) authorize(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + if q.Get("client_id") != i.ClientID || q.Get("code_challenge_method") != "S256" { + http.Error(w, "bad request", http.StatusBadRequest) + return + } + code := rand.Text() + i.mu.Lock() + i.codes[code] = grant{nonce: q.Get("nonce"), challenge: q.Get("code_challenge"), redirect: q.Get("redirect_uri"), user: i.user} + i.mu.Unlock() + back, _ := url.Parse(q.Get("redirect_uri")) + v := back.Query() + v.Set("code", code) + v.Set("state", q.Get("state")) + back.RawQuery = v.Encode() + http.Redirect(w, r, back.String(), http.StatusFound) +} + +func (i *IDP) token(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, "bad form", http.StatusBadRequest) + return + } + id, secret, ok := r.BasicAuth() + if !ok { + id, secret = r.PostForm.Get("client_id"), r.PostForm.Get("client_secret") + } + if id != i.ClientID || secret != i.Secret { + http.Error(w, `{"error":"invalid_client"}`, http.StatusUnauthorized) + return + } + i.mu.Lock() + g, ok := i.codes[r.PostForm.Get("code")] + delete(i.codes, r.PostForm.Get("code")) + i.mu.Unlock() + sum := sha256.Sum256([]byte(r.PostForm.Get("code_verifier"))) + if !ok || base64.RawURLEncoding.EncodeToString(sum[:]) != g.challenge || r.PostForm.Get("redirect_uri") != g.redirect { + http.Error(w, `{"error":"invalid_grant"}`, http.StatusBadRequest) + return + } + nonce, aud := g.nonce, i.ClientID + if i.NonceOverride != "" { + nonce = i.NonceOverride + } + if i.AudienceOverride != "" { + aud = i.AudienceOverride + } + now := time.Now() + claims := map[string]any{ + "iss": i.Issuer(), "sub": g.user.Subject, "aud": aud, "nonce": nonce, + "iat": now.Unix(), "exp": now.Add(5 * time.Minute).Unix(), + "email": g.user.Email, "email_verified": g.user.EmailVerified, "name": g.user.Name, + } + raw, err := jwt.Signed(i.signer).Claims(claims).Serialize() + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + writeJSON(w, map[string]any{"access_token": "at", "token_type": "Bearer", "expires_in": 300, "id_token": raw}) +} + +func writeJSON(w http.ResponseWriter, v any) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(v) +}