// 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 }