Files

488 lines
18 KiB
Go
Raw Permalink Normal View History

package yaiam
// Signing the users of a web application in (authorization code flow
// with PKCE, OpenID Connect Core 3.1). SignIn sends the browser to the
// provider with a fresh state, nonce and code verifier, kept in a short
// cookie of this browser; Callback checks the state against the cookie,
// trades the code for tokens and checks the ID token.
//
// The ID token comes straight from the token endpoint over TLS, so its
// signature is not checked here: OpenID Connect Core 3.1.3.7 lets a
// client rely on the TLS server check instead -- no crypto in this
// package. Its claims are: iss the issuer, aud this client (azp too when
// there are several), not expired, the nonce of this sign-in. The
// profile, groups and roles come from UserInfo, which must name the same
// subject.
import (
"context"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"slices"
"strings"
"time"
)
// WebScopes are asked for when Web.Scopes is nil: who the user is, their
// address, their groups and roles at yaiam (the client must be allowed
// "groups" and "roles") and the user attributes released to the client
// (yaiam allows "attributes" once some are). A scope the client is not
// allowed is left out, not refused.
var WebScopes = []string{"openid", "profile", "email", "groups", "roles", "attributes"}
// signInLifetime is how long a started sign-in may take.
const signInLifetime = 10 * time.Minute
// clockSkew is the leeway for an ID token's exp and iat.
const clockSkew = time.Minute
// Errors of a sign-in.
var (
// ErrSignInState: the callback does not belong to a sign-in this
// browser started (no cookie, another state, too late). Start again.
ErrSignInState = errors.New("yaiam: the sign-in does not belong to this browser or took too long")
// ErrSignInRefused: the provider answered the callback with an error
// (the user cancelled, may not use the application, ...); see the
// wrapped *Error for its code.
ErrSignInRefused = errors.New("yaiam: the provider refused the sign-in")
)
// Web signs the users of a web application in at one issuer as one
// client. Its fields must not change once it is in use; use it by
// pointer; it is safe for concurrent use.
type Web struct {
// Client holds the issuer, the client ID, the scopes (nil:
// WebScopes) and the HTTP client. Its Scopes and token store are not
// used.
Client
// ClientSecret authenticates a confidential client at the token
// endpoint (client_secret_basic); "" for a public client.
ClientSecret string
// RedirectURL is this application's callback, registered at the
// client, e.g. "https://app.example.org/callback".
RedirectURL string
// PostLogoutRedirectURL is where the provider sends the browser
// after a sign-out (registered at the client); "" for none.
PostLogoutRedirectURL string
// PublicIssuer is the issuer URL as the browser reaches it, when this
// application reaches the provider under another name (a container
// network: Issuer "http://oidc:8080/default", PublicIssuer
// "http://localhost:8180/default"): the same path on another origin.
// The endpoints the browser is sent to (authorization, end session)
// that are on Issuer's origin go to PublicIssuer's instead, and the
// callback's iss may name either. "" means Issuer.
PublicIssuer string
// CookieName names the short cookie of a running sign-in; "" means
// "yaiam_signin". On https it always gets the prefix "__Host-". One
// sign-in per browser at a time: a second one started in another tab
// replaces the first, whose callback then is ErrSignInState.
CookieName string
}
// SignedIn is who signed in, with the tokens.
type SignedIn struct {
// Subject is the user's ID at yaiam: it stays the same when the user
// is renamed -- the key to keep an application's own data under.
Subject string
// Username, Name and Email (EmailVerified: confirmed) with the
// scopes profile and email.
Username, Name, Email string
EmailVerified bool
// Groups and Roles with the scopes groups and roles: the names of the
// user's groups (subgroups' members included) and roles in the tenant.
Groups, Roles []string
// Attributes with the scope attributes: the user's attributes yaiam
// releases to the client (department, cost_center, ...), by name.
Attributes map[string]string
// ACR is how strongly the user signed in ("pwd", "mfa", "phr"), AMR
// with what; AuthTime when.
ACR string
AMR []string
AuthTime time.Time
// IDToken is for LogoutURL; Token for the APIs (it holds no refresh
// token unless the scopes asked for offline_access).
IDToken string
Token *Token
// ReturnTo is the path SignIn was given.
ReturnTo string
}
// String keeps the tokens out of anything printed or logged.
func (s *SignedIn) String() string {
if s == nil {
return "<nil>"
}
return fmt.Sprintf("yaiam.SignedIn{Subject: %q, Username: %q, Groups: %q, ACR: %q, tokens redacted}", s.Subject, s.Username, s.Groups, s.ACR)
}
// GoString is String, for %#v.
func (s *SignedIn) GoString() string { return s.String() }
// signInCookie is what the cookie of a running sign-in holds.
type signInCookie struct {
State string `json:"s"`
Nonce string `json:"n"`
Verifier string `json:"v"`
ReturnTo string `json:"r"`
Expires int64 `json:"e"`
}
func (w *Web) secure() bool { return strings.HasPrefix(w.RedirectURL, "https://") }
func (w *Web) cookieName() string {
name := w.CookieName
if name == "" {
name = "yaiam_signin"
}
// On https always __Host-: no other host can plant it.
if w.secure() && !strings.HasPrefix(name, "__Host-") {
return "__Host-" + name
}
return name
}
func (w *Web) scope() string {
if w.Scopes == nil {
return strings.Join(WebScopes, " ")
}
return strings.Join(w.Scopes, " ")
}
// check refuses a Web that cannot sign anyone in safely.
func (w *Web) check() error {
if err := checkURL("redirect URL", w.RedirectURL, w.AllowInsecure); err != nil {
return err
}
if w.PostLogoutRedirectURL != "" {
if err := checkURL("post-logout redirect URL", w.PostLogoutRedirectURL, w.AllowInsecure); err != nil {
return err
}
}
scopes := WebScopes
if w.Scopes != nil {
scopes = w.Scopes
}
if w.PublicIssuer != "" {
if err := checkURL("public issuer", w.PublicIssuer, w.AllowInsecure); err != nil {
return err
}
pub, _ := url.Parse(w.PublicIssuer)
if iss, err := url.Parse(w.Issuer); err != nil || iss.Path != pub.Path {
return errors.New("yaiam: the public issuer must have the issuer's path")
}
}
if !slices.Contains(scopes, "openid") {
return errors.New("yaiam: a sign-in needs the scope openid")
}
return nil
}
// SignIn starts a sign-in: it remembers a fresh state, nonce and PKCE
// verifier in a cookie of this browser (HttpOnly, SameSite=Lax, Secure on
// https, ten minutes) and redirects the browser to the provider.
// returnTo is the path of this application to go to afterwards
// (Callback returns it); anything but a local path becomes "/".
func (w *Web) SignIn(ctx context.Context, rw http.ResponseWriter, r *http.Request, returnTo string) error {
if err := w.check(); err != nil {
return err
}
m, err := w.discover(ctx)
if err != nil {
return err
}
if m.AuthorizationEndpoint == "" {
return errors.New("yaiam: the provider names no authorization endpoint")
}
c := signInCookie{State: random(), Nonce: random(), Verifier: random() + random(), ReturnTo: localPath(returnTo),
Expires: time.Now().Add(signInLifetime).Unix()}
raw, err := json.Marshal(c)
if err != nil {
return err
}
http.SetCookie(rw, &http.Cookie{Name: w.cookieName(), Value: base64.RawURLEncoding.EncodeToString(raw), Path: "/",
MaxAge: int(signInLifetime.Seconds()), HttpOnly: true, Secure: w.secure(), SameSite: http.SameSiteLaxMode})
challenge := sha256.Sum256([]byte(c.Verifier))
q := url.Values{"response_type": {"code"}, "client_id": {w.ClientID}, "redirect_uri": {w.RedirectURL},
"scope": {w.scope()}, "state": {c.State}, "nonce": {c.Nonce},
"code_challenge": {base64.RawURLEncoding.EncodeToString(challenge[:])}, "code_challenge_method": {"S256"}}
target := w.browser(m.AuthorizationEndpoint)
if strings.Contains(target, "?") {
target += "&" + q.Encode()
} else {
target += "?" + q.Encode()
}
http.Redirect(rw, r, target, http.StatusFound)
return nil
}
// localPath is p when it is a path of this application, else "/": no
// redirect to another site after the sign-in. A browser drops tabs and
// line breaks from a URL and reads a backslash as a slash, so none of
// them, no control character, and no "//" at the start.
func localPath(p string) string {
if !strings.HasPrefix(p, "/") || strings.HasPrefix(p, "//") ||
strings.ContainsFunc(p, func(r rune) bool { return r < 0x20 || r == 0x7f || r == '\\' }) {
return "/"
}
return p
}
// random is 32 random bytes, base64url.
func random() string {
b := make([]byte, 32)
rand.Read(b) // never fails (crypto/rand)
return base64.RawURLEncoding.EncodeToString(b)
}
// Callback finishes the sign-in the request r (the provider's redirect
// to RedirectURL) belongs to: the state must be the one of this
// browser's cookie (which it removes), the code is traded for tokens with
// the verifier, the ID token checked, UserInfo asked. A refusal of the
// provider is ErrSignInRefused, a callback of another or an old sign-in
// ErrSignInState.
func (w *Web) Callback(ctx context.Context, rw http.ResponseWriter, r *http.Request) (*SignedIn, error) {
if err := w.check(); err != nil {
return nil, err
}
// The browser's cookie and the state first: a callback of no sign-in
// of this browser never reaches the provider.
var c signInCookie
cookie, cerr := r.Cookie(w.cookieName())
http.SetCookie(rw, &http.Cookie{Name: w.cookieName(), Value: "", Path: "/", MaxAge: -1, HttpOnly: true, Secure: w.secure(),
SameSite: http.SameSiteLaxMode})
if cerr != nil {
return nil, ErrSignInState
}
raw, err := base64.RawURLEncoding.DecodeString(cookie.Value)
if err != nil || json.Unmarshal(raw, &c) != nil || c.State == "" || time.Now().Unix() > c.Expires {
return nil, ErrSignInState
}
q := r.URL.Query()
if subtle.ConstantTimeCompare([]byte(q.Get("state")), []byte(c.State)) != 1 {
return nil, ErrSignInState
}
// RFC 9207: an iss parameter must name this issuer.
if iss := q.Get("iss"); iss != "" && iss != w.Issuer && (w.PublicIssuer == "" || iss != w.PublicIssuer) {
return nil, fmt.Errorf("yaiam: the callback comes from issuer %q, not %q", iss, w.Issuer)
}
if code := q.Get("error"); code != "" {
return nil, fmt.Errorf("%w: %w", ErrSignInRefused, &Error{Endpoint: "authorization", Status: http.StatusFound, Code: code,
Description: q.Get("error_description")})
}
code := q.Get("code")
if code == "" {
return nil, errors.New("yaiam: the callback has no code")
}
m, err := w.discover(ctx)
if err != nil {
return nil, err
}
tok, idToken, err := w.exchange(ctx, m, code, c.Verifier)
if err != nil {
return nil, err
}
claims, err := w.checkIDToken(idToken, c.Nonce)
if err != nil {
return nil, err
}
out := &SignedIn{Subject: claims.Subject, ACR: claims.ACR, AMR: claims.AMR, IDToken: idToken, Token: tok,
ReturnTo: localPath(c.ReturnTo)} // the cookie is the browser's: check again
if claims.AuthTime > 0 {
out.AuthTime = time.Unix(claims.AuthTime, 0)
}
if m.UserinfoEndpoint != "" {
u, err := w.userInfo(ctx, m, tok)
if err != nil {
return nil, err
}
if u.Subject != claims.Subject {
return nil, errors.New("yaiam: UserInfo names another user than the ID token")
}
// Only the JSON boolean true confirms the address: some providers
// send the string "true", which a sign-in must not take for it
// (nor fail on).
out.Username, out.Name, out.Email, out.Groups, out.Roles = u.Username, u.Name, u.Email, u.Groups, u.Roles
out.EmailVerified = string(u.EmailVerified) == "true"
out.Attributes = u.Attributes
}
return out, nil
}
// exchange trades code for tokens at the token endpoint.
func (w *Web) exchange(ctx context.Context, m *metadata, code, verifier string) (*Token, string, error) {
form := url.Values{"grant_type": {"authorization_code"}, "code": {code}, "redirect_uri": {w.RedirectURL},
"code_verifier": {verifier}}
if w.ClientSecret == "" {
form.Set("client_id", w.ClientID)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, m.TokenEndpoint, strings.NewReader(form.Encode()))
if err != nil {
return nil, "", err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
if w.ClientSecret != "" {
req.SetBasicAuth(url.QueryEscape(w.ClientID), url.QueryEscape(w.ClientSecret)) // RFC 6749 2.3.1
}
status, body, err := w.do(req)
if err != nil {
return nil, "", fmt.Errorf("yaiam: token: %w", err)
}
if status != http.StatusOK {
return nil, "", oauthError("token", status, body)
}
var out struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
Scope string `json:"scope"`
IDToken string `json:"id_token"`
}
if err := json.Unmarshal(body, &out); err != nil {
return nil, "", fmt.Errorf("yaiam: token: %w", err)
}
// No ID token: checkIDToken refuses it.
if out.AccessToken == "" || !strings.EqualFold(out.TokenType, "Bearer") || out.ExpiresIn <= 0 {
return nil, "", errors.New("yaiam: token: no bearer token with a lifetime in the answer")
}
return &Token{Issuer: w.Issuer, ClientID: w.ClientID, AccessToken: out.AccessToken, RefreshToken: out.RefreshToken,
Expiry: time.Now().Add(time.Duration(out.ExpiresIn) * time.Second), Scope: out.Scope}, out.IDToken, nil
}
// idClaims are the ID token's claims a sign-in looks at.
type idClaims struct {
Issuer string `json:"iss"`
Subject string `json:"sub"`
Audience json.RawMessage `json:"aud"`
AZP string `json:"azp"`
Expiry int64 `json:"exp"`
IssuedAt int64 `json:"iat"`
Nonce string `json:"nonce"`
ACR string `json:"acr"`
AMR []string `json:"amr"`
AuthTime int64 `json:"auth_time"`
}
// checkIDToken reads the claims of idToken, which came from the token
// endpoint over TLS (OpenID Connect Core 3.1.3.7: no signature check),
// and checks them: issuer, audience, expiry, issue time, nonce.
func (w *Web) checkIDToken(idToken, nonce string) (*idClaims, error) {
parts := strings.Split(idToken, ".")
if len(parts) != 3 {
return nil, errors.New("yaiam: the ID token is not a JWT")
}
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return nil, errors.New("yaiam: the ID token's claims are not base64url")
}
var c idClaims
if err := json.Unmarshal(raw, &c); err != nil {
return nil, fmt.Errorf("yaiam: the ID token's claims: %w", err)
}
var aud []string
if err := json.Unmarshal(c.Audience, &aud); err != nil {
var one string
if json.Unmarshal(c.Audience, &one) != nil {
return nil, errors.New("yaiam: the ID token has no audience")
}
aud = []string{one}
}
now := time.Now()
switch {
case c.Issuer != w.Issuer:
return nil, fmt.Errorf("yaiam: the ID token is from issuer %q, not %q", c.Issuer, w.Issuer)
case !slices.Contains(aud, w.ClientID):
return nil, errors.New("yaiam: the ID token is not for this client")
case len(aud) > 1 && c.AZP != w.ClientID:
return nil, errors.New("yaiam: the ID token was issued to another client (azp)")
case c.Subject == "":
return nil, errors.New("yaiam: the ID token names no subject")
case c.Expiry == 0 || now.After(time.Unix(c.Expiry, 0).Add(clockSkew)):
return nil, errors.New("yaiam: the ID token has expired")
case c.IssuedAt == 0 || time.Unix(c.IssuedAt, 0).After(now.Add(clockSkew)):
return nil, errors.New("yaiam: the ID token is issued in the future")
case subtle.ConstantTimeCompare([]byte(c.Nonce), []byte(nonce)) != 1:
return nil, errors.New("yaiam: the ID token is not for this sign-in (nonce)")
}
return &c, nil
}
// webUserInfo is UserInfo's answer with what a web sign-in also takes.
type webUserInfo struct {
UserInfo
EmailVerified json.RawMessage `json:"email_verified"`
Groups []string `json:"groups"`
Roles []string `json:"roles"`
Attributes map[string]string `json:"attributes"`
}
func (w *Web) userInfo(ctx context.Context, m *metadata, t *Token) (*webUserInfo, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, m.UserinfoEndpoint, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+t.AccessToken)
req.Header.Set("Accept", "application/json")
status, body, err := w.do(req)
if err != nil {
return nil, fmt.Errorf("yaiam: userinfo: %w", err)
}
if status != http.StatusOK {
return nil, &Error{Endpoint: "userinfo", Status: status}
}
var u webUserInfo
if err := json.Unmarshal(body, &u); err != nil {
return nil, fmt.Errorf("yaiam: userinfo: %w", err)
}
return &u, nil
}
// LogoutURL is where to send the browser to sign out at the provider too
// (RP-initiated logout): with the ID token of the sign-in as hint and,
// when set, PostLogoutRedirectURL. "" when the provider offers none --
// then the application ends only its own session.
func (w *Web) LogoutURL(ctx context.Context, idToken string) (string, error) {
m, err := w.discover(ctx)
if err != nil {
return "", err
}
if m.EndSessionEndpoint == "" {
return "", nil
}
q := url.Values{"client_id": {w.ClientID}}
if idToken != "" {
q.Set("id_token_hint", idToken)
}
if w.PostLogoutRedirectURL != "" {
q.Set("post_logout_redirect_uri", w.PostLogoutRedirectURL)
}
sep := "?"
if strings.Contains(m.EndSessionEndpoint, "?") {
sep = "&"
}
return w.browser(m.EndSessionEndpoint) + sep + q.Encode(), nil
}
// browser is endpoint as the browser reaches it: on PublicIssuer's
// origin when it is on Issuer's.
func (w *Web) browser(endpoint string) string {
if w.PublicIssuer == "" {
return endpoint
}
e, err := url.Parse(endpoint)
iss, err2 := url.Parse(w.Issuer)
pub, err3 := url.Parse(w.PublicIssuer)
if err != nil || err2 != nil || err3 != nil || e.Scheme != iss.Scheme || e.Host != iss.Host {
return endpoint
}
e.Scheme, e.Host = pub.Scheme, pub.Host
return e.String()
}