Phase 12: signing in with the Core's Authelia

Admins make the client's secret under Settings → Sign-in, which shows the
entry for the Core's idproviders.yml (the secret's PBKDF2-SHA512 hash, the
redirect address, PKCE). People sign in with their Core account: invited
ones are matched by verified email, then by subject; optionally anyone at
the Core's domain joins. Passwords can be turned off but for the owner's,
and signing out ends the Core's session where it can. On multi-tenant, the
team is found by its proved domain.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 13:00:36 -07:00
co-authored by Claude Opus 5.5
parent 637ef1cc25
commit 962dbe3286
19 changed files with 1458 additions and 15 deletions
+365
View File
@@ -0,0 +1,365 @@
// Package oidc signs people in with an OpenID Connect provider: the
// Federated Core's Authelia. The authorization code flow, with PKCE (S256)
// and a nonce; the client authenticates to the token endpoint with its
// secret in the form (client_secret_post).
//
// The ID token comes straight from the provider's token endpoint over TLS,
// so (as OpenID Connect Core 1.0, 3.1.3.7, allows) its issuer is trusted
// from TLS rather than by checking its signature; its claims are checked:
// the issuer, the audience, the expiry and the nonce.
package oidc
import (
"context"
"crypto/rand"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"golang.org/x/crypto/pbkdf2"
)
// Provider is what an issuer's discovery document says.
type Provider struct {
Issuer string `json:"issuer"`
Authorization string `json:"authorization_endpoint"`
Token string `json:"token_endpoint"`
UserInfo string `json:"userinfo_endpoint"`
EndSession string `json:"end_session_endpoint"` // empty if the provider has no sign-out
Scopes []string `json:"scopes_supported"`
PKCEMethods []string `json:"code_challenge_methods_supported"`
}
// Client is how Supermarket is registered with the provider.
type Client struct {
ID, Secret string
RedirectURI string
}
// Scopes are what Supermarket asks for.
const Scopes = "openid profile email groups"
// HTTP is the client used to reach providers; tests replace it.
var HTTP = &http.Client{Timeout: 20 * time.Second}
// Discover reads an issuer's discovery document, and checks it names the
// same issuer and the endpoints the code flow needs.
func Discover(ctx context.Context, issuer string) (*Provider, error) {
issuer = strings.TrimRight(issuer, "/")
req, err := http.NewRequestWithContext(ctx, http.MethodGet, issuer+"/.well-known/openid-configuration", nil)
if err != nil {
return nil, err
}
resp, err := HTTP.Do(req)
if err != nil {
return nil, fmt.Errorf("reaching %s: %w", issuer, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s has no OpenID Connect discovery document (%s)", issuer, resp.Status)
}
var p Provider
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&p); err != nil {
return nil, fmt.Errorf("%s's discovery document can't be read: %w", issuer, err)
}
if strings.TrimRight(p.Issuer, "/") != issuer {
return nil, fmt.Errorf("the discovery document names another issuer (%s)", p.Issuer)
}
if p.Authorization == "" || p.Token == "" {
return nil, errors.New("the discovery document lacks the authorization or token endpoint")
}
return &p, nil
}
// Flow is a sign-in under way: kept until the provider sends the browser
// back.
type Flow struct {
State string `json:"state"`
Nonce string `json:"nonce"`
Verifier string `json:"verifier"`
Started time.Time `json:"started"`
Next string `json:"next,omitempty"`
}
func random() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// Start begins a sign-in: the address to send the browser to, and the
// flow to keep. statePrefix goes before the random state (the team, on
// the multi-tenant edition).
func Start(p *Provider, c Client, statePrefix string) (string, *Flow, error) {
f := &Flow{Started: time.Now()}
var err error
if f.State, err = random(); err != nil {
return "", nil, err
}
f.State = statePrefix + f.State
if f.Nonce, err = random(); err != nil {
return "", nil, err
}
if f.Verifier, err = random(); err != nil {
return "", nil, err
}
sum := sha256.Sum256([]byte(f.Verifier))
q := url.Values{
"response_type": {"code"},
"client_id": {c.ID},
"redirect_uri": {c.RedirectURI},
"scope": {Scopes},
"state": {f.State},
"nonce": {f.Nonce},
"code_challenge": {base64.RawURLEncoding.EncodeToString(sum[:])},
"code_challenge_method": {"S256"},
}
sep := "?"
if strings.Contains(p.Authorization, "?") {
sep = "&"
}
return p.Authorization + sep + q.Encode(), f, nil
}
// Identity is who signed in.
type Identity struct {
Subject string // the provider's ID for them: stable, unlike the email
Email string
Verified bool // the provider vouches for the email
Name string
Groups []string
IDToken string // for signing out of the provider
}
// Finish trades the code for tokens, checks the ID token's claims, and
// reads who it is (the ID token, completed by the userinfo endpoint).
func Finish(ctx context.Context, p *Provider, c Client, f *Flow, code string, now time.Time) (*Identity, error) {
form := url.Values{
"grant_type": {"authorization_code"},
"code": {code},
"redirect_uri": {c.RedirectURI},
"client_id": {c.ID},
"client_secret": {c.Secret},
"code_verifier": {f.Verifier},
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.Token, 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")
resp, err := HTTP.Do(req)
if err != nil {
return nil, fmt.Errorf("reaching the token endpoint: %w", err)
}
defer resp.Body.Close()
var tok struct {
AccessToken string `json:"access_token"`
IDToken string `json:"id_token"`
Error string `json:"error"`
Description string `json:"error_description"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&tok); err != nil {
return nil, fmt.Errorf("the token endpoint's answer can't be read (%s)", resp.Status)
}
if resp.StatusCode != http.StatusOK || tok.Error != "" {
return nil, fmt.Errorf("the provider refused the code: %s %s", tok.Error, tok.Description)
}
claims, err := parseIDToken(tok.IDToken)
if err != nil {
return nil, err
}
if err := claims.check(p.Issuer, c.ID, f.Nonce, now); err != nil {
return nil, err
}
id := &Identity{Subject: claims.Subject, Email: claims.Email, Verified: claims.EmailVerified, Name: claims.Name, Groups: claims.Groups, IDToken: tok.IDToken}
if p.UserInfo != "" && tok.AccessToken != "" {
if ui, err := userInfo(ctx, p.UserInfo, tok.AccessToken); err == nil && ui.Subject == claims.Subject {
if ui.Email != "" {
id.Email, id.Verified = ui.Email, ui.EmailVerified
}
if ui.Name != "" {
id.Name = ui.Name
}
if len(ui.Groups) > 0 {
id.Groups = ui.Groups
}
}
}
if id.Subject == "" {
return nil, errors.New("the provider sent no subject")
}
id.Email = strings.ToLower(strings.TrimSpace(id.Email))
return id, nil
}
// claims are the ID token's (and userinfo's).
type claims struct {
Issuer string `json:"iss"`
Subject string `json:"sub"`
Audience audience `json:"aud"`
Expiry int64 `json:"exp"`
IssuedAt int64 `json:"iat"`
Nonce string `json:"nonce"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Name string `json:"name"`
Groups []string `json:"groups"`
}
// audience is a string or a list of them.
type audience []string
func (a *audience) UnmarshalJSON(b []byte) error {
var one string
if json.Unmarshal(b, &one) == nil {
*a = []string{one}
return nil
}
var many []string
if err := json.Unmarshal(b, &many); err != nil {
return err
}
*a = many
return nil
}
func parseIDToken(tok string) (*claims, error) {
parts := strings.Split(tok, ".")
if len(parts) != 3 {
return nil, errors.New("the provider sent no ID token")
}
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return nil, errors.New("the ID token can't be read")
}
var c claims
if err := json.Unmarshal(raw, &c); err != nil {
return nil, errors.New("the ID token can't be read")
}
return &c, nil
}
// leeway allows for clocks that differ a little.
const leeway = 2 * time.Minute
func (c *claims) check(issuer, clientID, nonce string, now time.Time) error {
switch {
case strings.TrimRight(c.Issuer, "/") != strings.TrimRight(issuer, "/"):
return errors.New("the ID token is from another issuer")
case !c.has(clientID):
return errors.New("the ID token is for another client")
case c.Expiry == 0 || now.After(time.Unix(c.Expiry, 0).Add(leeway)):
return errors.New("the ID token has expired: check the server's clock")
case c.IssuedAt != 0 && time.Unix(c.IssuedAt, 0).After(now.Add(leeway)):
return errors.New("the ID token is from the future: check the server's clock")
case nonce == "" || c.Nonce != nonce:
return errors.New("the ID token doesn't match this sign-in")
}
return nil
}
func (c *claims) has(clientID string) bool {
for _, a := range c.Audience {
if a == clientID {
return true
}
}
return false
}
func userInfo(ctx context.Context, endpoint, access string) (*claims, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+access)
resp, err := HTTP.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("userinfo: %s", resp.Status)
}
var c claims
return &c, json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&c)
}
// SignOutURL is where to send the browser to sign out of the provider too,
// or "" if it has no end-session endpoint.
func SignOutURL(p *Provider, idToken, back string) string {
if p == nil || p.EndSession == "" {
return ""
}
q := url.Values{"post_logout_redirect_uri": {back}}
if idToken != "" {
q.Set("id_token_hint", idToken)
}
sep := "?"
if strings.Contains(p.EndSession, "?") {
sep = "&"
}
return p.EndSession + sep + q.Encode()
}
// Secrets, as Authelia's configuration takes them.
// NewSecret is a client secret: 48 random characters.
func NewSecret() (string, error) {
b := make([]byte, 36)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// HashRounds is how many PBKDF2 rounds the Core's own clients use.
const HashRounds = 310000
// ab64 is passlib's base64: the standard alphabet with . for +, no padding.
func ab64(b []byte) string {
return strings.ReplaceAll(base64.RawStdEncoding.EncodeToString(b), "+", ".")
}
// HashSecret is a secret as Authelia's client_secret takes it:
// $pbkdf2-sha512$310000$<salt>$<key>, like the Core's other clients.
func HashSecret(secret string) (string, error) {
salt := make([]byte, 16)
if _, err := rand.Read(salt); err != nil {
return "", err
}
return hashWith(secret, salt, HashRounds), nil
}
func hashWith(secret string, salt []byte, rounds int) string {
key := pbkdf2.Key([]byte(secret), salt, rounds, sha512.Size, sha512.New)
return fmt.Sprintf("$pbkdf2-sha512$%d$%s$%s", rounds, ab64(salt), ab64(key))
}
// CheckHash says whether a secret matches a hash from HashSecret.
func CheckHash(secret, hash string) bool {
parts := strings.Split(hash, "$")
if len(parts) != 5 || parts[1] != "pbkdf2-sha512" {
return false
}
var rounds int
if _, err := fmt.Sscanf(parts[2], "%d", &rounds); err != nil || rounds < 1 || rounds > 10_000_000 {
return false
}
salt, err := base64.RawStdEncoding.DecodeString(strings.ReplaceAll(parts[3], ".", "+"))
if err != nil {
return false
}
return hashWith(secret, salt, rounds) == hash
}
+131
View File
@@ -0,0 +1,131 @@
package oidc
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"strings"
"testing"
"time"
)
func TestHashSecret(t *testing.T) {
// The same as Python's hashlib.pbkdf2_hmac, in passlib's base64.
if got := hashWith("correct horse", []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, 1000); got != "$pbkdf2-sha512$1000$AAECAwQFBgcICQoLDA0ODw$Xpx07WjVx4vCIvrmBRj8uOoVVtGqJqtUv2J5bhizSQs7osCteF7W4A61dZDqSIqQjO.dxO6p5FT/Uy7QRBXSXA" {
t.Errorf("hash %s", got)
}
h, err := HashSecret("s3cret")
if err != nil {
t.Fatal(err)
}
// Shaped like the Core's own clients' secrets.
if !regexp.MustCompile(`^\$pbkdf2-sha512\$310000\$[A-Za-z0-9./]{22}\$[A-Za-z0-9./]{86}$`).MatchString(h) {
t.Errorf("shape %s", h)
}
if !CheckHash("s3cret", h) || CheckHash("s3creT", h) || CheckHash("s3cret", "$pbkdf2-sha256$1$a$b") {
t.Error("check")
}
if s, _ := NewSecret(); len(s) != 48 {
t.Errorf("secret %q", s)
}
}
// fakeAuthelia is a provider for tests.
func fakeAuthelia(t *testing.T, claims map[string]any) (*httptest.Server, *string) {
t.Helper()
var challenge string
var srv *httptest.Server
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/.well-known/openid-configuration":
json.NewEncoder(w).Encode(map[string]any{"issuer": srv.URL, "authorization_endpoint": srv.URL + "/api/oidc/authorization",
"token_endpoint": srv.URL + "/api/oidc/token", "userinfo_endpoint": srv.URL + "/api/oidc/userinfo"})
case "/api/oidc/token":
r.ParseForm()
sum := sha256.Sum256([]byte(r.PostForm.Get("code_verifier")))
if r.PostForm.Get("client_secret") != "s3cret" || r.PostForm.Get("code") != "c0de" ||
base64.RawURLEncoding.EncodeToString(sum[:]) != challenge {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "invalid_grant"})
return
}
c := map[string]any{"iss": srv.URL, "aud": []string{"supermarket"}, "exp": time.Now().Add(time.Minute).Unix(), "iat": time.Now().Unix()}
for k, v := range claims {
c[k] = v
}
payload, _ := json.Marshal(c)
json.NewEncoder(w).Encode(map[string]string{"access_token": "at", "id_token": "e30." + base64.RawURLEncoding.EncodeToString(payload) + ".sig"})
case "/api/oidc/userinfo":
if r.Header.Get("Authorization") != "Bearer at" {
w.WriteHeader(http.StatusUnauthorized)
return
}
json.NewEncoder(w).Encode(map[string]any{"sub": claims["sub"], "email": "Pat@Example.com", "email_verified": true, "groups": []string{"admins"}})
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
return srv, &challenge
}
func TestCodeFlow(t *testing.T) {
ctx := context.Background()
claims := map[string]any{"sub": "abc-123", "name": "Pat"}
srv, challenge := fakeAuthelia(t, claims)
if _, err := Discover(ctx, srv.URL+"/other"); err == nil {
t.Error("discovered a wrong issuer")
}
p, err := Discover(ctx, srv.URL+"/")
if err != nil {
t.Fatal(err)
}
c := Client{ID: "supermarket", Secret: "s3cret", RedirectURI: "https://sm.example.com/auth/core/callback"}
addr, f, err := Start(p, c, "7.")
if err != nil {
t.Fatal(err)
}
u, _ := url.Parse(addr)
q := u.Query()
if q.Get("code_challenge_method") != "S256" || q.Get("scope") != Scopes || q.Get("nonce") != f.Nonce || !strings.HasPrefix(f.State, "7.") || q.Get("state") != f.State {
t.Errorf("authorization address %s", addr)
}
*challenge = q.Get("code_challenge")
claims["nonce"] = f.Nonce
id, err := Finish(ctx, p, c, f, "c0de", time.Now())
if err != nil {
t.Fatal(err)
}
if id.Subject != "abc-123" || id.Email != "pat@example.com" || !id.Verified || id.Name != "Pat" || len(id.Groups) != 1 {
t.Errorf("identity %+v", id)
}
// What must fail.
if _, err := Finish(ctx, p, Client{ID: "supermarket", Secret: "wrong", RedirectURI: c.RedirectURI}, f, "c0de", time.Now()); err == nil {
t.Error("a wrong secret")
}
bad := *f
bad.Verifier = "other"
if _, err := Finish(ctx, p, c, &bad, "c0de", time.Now()); err == nil {
t.Error("a wrong verifier")
}
claims["nonce"] = "replayed"
if _, err := Finish(ctx, p, c, f, "c0de", time.Now()); err == nil || !strings.Contains(err.Error(), "match") {
t.Errorf("a wrong nonce: %v", err)
}
claims["nonce"] = f.Nonce
if _, err := Finish(ctx, p, Client{ID: "other", Secret: "s3cret", RedirectURI: c.RedirectURI}, f, "c0de", time.Now()); err == nil {
t.Error("another client's token")
}
if _, err := Finish(ctx, p, c, f, "c0de", time.Now().Add(10*time.Minute)); err == nil || !strings.Contains(err.Error(), "expired") {
t.Errorf("expired: %v", err)
}
if SignOutURL(p, "x", "https://sm.example.com/signin") != "" {
t.Error("sign-out without an endpoint")
}
}