Files
superbrain/internal/auth/oidc_provision.go
T
Andrew S Erwin f372936894
release gate / check (push) Failing after 7m28s
Add deployment tiers, self-service password reset, and Authelia SSO fixes
Product tiers (decided 2026-10-26): TIER=core|multi is the deployment knob.
core (federated install, paying customers) derives AUTH_MODE=oidc with
signup/bootstrap off - Authelia is the only way in and accounts are
provisioned upstream (Superpanel -> LDAP -> Authelia). multi (hosted
self-service) derives AUTH_MODE=password: signup, password login and
SMTP-backed self-reset, with the OIDC bridge refused even when variables
are set. Explicit AUTH_MODE/SIGNUP_ENABLED/ALLOW_BOOTSTRAP_SIGNUP always
override the tier; invalid values fail startup instead of falling back.
Go enforces every gate at the API; the web UI mirrors it (conditional
credentials provider, SSO-only login page, signup/reset redirects).

Authelia-only bootstrap: ProvisionExternal grants ADMIN to ADMIN_EMAILS
addresses at first SSO login, and --seed accepts SEED_SUBJECT to link a
pre-existing password account offline - the only path when 409 'account
link required' meets a deployment where nobody can password-login to call
oidc-link.

Self-service password reset (multi tier): POST /api/password/forgot and
/api/password/reset with hashed single-use 30-minute tokens
(PasswordResetToken, migration 011 + schema.sql), enumeration-safe
identical 200s, per-IP rate limits, tokenVersion bump on success (all
prior sessions revoked), OIDC-only accounts excluded by design. New
internal/mailer sends via netguard+outbound budget; NETGUARD_TRUSTED_HOSTS
pins operator-chosen relays that resolve privately (split-horizon DNS)
without the blanket INTEGRATIONS_ALLOW_PRIVATE switch. Web gains
/forgot-password and /reset-password pages and a login-page link.

Federated install fixes: the Authelia client now registers a
claims_policy putting email in the ID token (production AccessDenied -
Auth.js builds OIDC profiles exclusively from ID-token claims), config is
validated before restarting the shared Authelia, uninstall removes the
claims block marker-safely, and generated .env switches to TIER=core with
a password-less admin seed.

Tests: tier derivation/override unit tests, mode and tier integration
tests (403 gates, bridge refusal, ADMIN_EMAILS promotion, offline link),
reset-flow integration tests against a loopback SMTP fake, netguard
trusted-host tests. Docs: RUNNING.md, web/docs/AUTHELIA.md section 7,
.env.example, STRATEGY.md.
2026-10-26 12:28:43 -05:00

148 lines
5.3 KiB
Go

package auth
import (
"encoding/json"
"errors"
"net/http"
"strings"
"time"
"github.com/andrew/superbrain/internal/config"
"github.com/andrew/superbrain/internal/db"
"github.com/golang-jwt/jwt/v5"
)
// TokenTypeOIDCProvision identifies the short-lived service credential the
// Next server presents when exchanging a verified Authelia identity for a
// local user. It is deliberately distinct from "assertion": ReadSession only
// accepts "assertion" on the Bearer channel and "session" on the cookie
// channel, so a provisioning token can never be replayed as a user session.
const (
TokenTypeOIDCProvision = "oidc-provision"
oidcProvisionAudience = "superbrain-api"
maxOIDCProvisionLifetime = 120 * time.Second
maxOIDCProvisionSubject = 255
maxOIDCProvisionImageLen = 2048
maxOIDCProvisionBodyBytes = 16 << 10
)
// ServiceClaims is the payload of the Next-to-Go OIDC provisioning token.
type ServiceClaims struct {
Type string `json:"typ,omitempty"`
jwt.RegisteredClaims
}
// VerifyServiceToken validates the provisioning token's signature, issuer,
// audience, expiry and type. The Next server signs with AUTH_SECRET (the same
// secret Go uses for sessions) and a 60-second lifetime; this caps it at two
// minutes to bound replay if a token leaks.
func VerifyServiceToken(token, secret string) error {
if secret == "" {
return errors.New("auth: empty service secret")
}
claims := &ServiceClaims{}
tok, err := jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (interface{}, error) {
return []byte(secret), nil
},
jwt.WithValidMethods([]string{"HS256"}),
jwt.WithIssuer("superbrain"),
jwt.WithAudience(oidcProvisionAudience),
jwt.WithExpirationRequired(),
jwt.WithLeeway(5*time.Second),
)
if err != nil {
return err
}
if !tok.Valid || claims.Type != TokenTypeOIDCProvision {
return errors.New("auth: invalid service token")
}
if claims.IssuedAt == nil || claims.ExpiresAt == nil {
return errors.New("auth: service token missing timestamps")
}
if claims.ExpiresAt.Sub(claims.IssuedAt.Time) > maxOIDCProvisionLifetime {
return errors.New("auth: service token lifetime too long")
}
return nil
}
type oidcIdentityRequest struct {
Issuer string `json:"issuer"`
Subject string `json:"subject"`
Email string `json:"email"`
EmailVerified bool `json:"emailVerified"`
Name string `json:"name"`
Image string `json:"image"`
}
// HandleOIDCIdentity resolves a verified Authelia identity to a local Go user.
// It is server-to-server only: the caller must present the short-lived
// oidc-provision service token. The response contains the LOCAL user id and
// tokenVersion; the OIDC subject is never used as a User.id.
//
// POST /api/auth/oidc/identity
func HandleOIDCIdentity(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
if r.Method != http.MethodPost {
failure(w, http.StatusMethodNotAllowed, "Use POST")
return
}
// AUTH_MODE=password deployments (multi-tenant shape) have no Authelia:
// the bridge is refused even with valid OIDC_* variables and a valid
// service token, so a stray config can never provision identities.
if config.AuthMode() == "password" {
failure(w, http.StatusForbidden, "OIDC provisioning is disabled on this server")
return
}
header := r.Header.Get("Authorization")
if !strings.HasPrefix(header, "Bearer ") || VerifyServiceToken(strings.TrimPrefix(header, "Bearer "), config.Load().Secret()) != nil {
failure(w, http.StatusUnauthorized, "Unauthorized")
return
}
r.Body = http.MaxBytesReader(w, r.Body, maxOIDCProvisionBodyBytes)
var req oidcIdentityRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
failure(w, http.StatusRequestEntityTooLarge, "Request body too large")
return
}
failure(w, http.StatusBadRequest, "Invalid JSON")
return
}
req.Issuer = strings.TrimSpace(req.Issuer)
req.Subject = strings.TrimSpace(req.Subject)
req.Email = strings.ToLower(strings.TrimSpace(req.Email))
req.Name = strings.TrimSpace(req.Name)
req.Image = strings.TrimSpace(req.Image)
if req.Subject == "" || req.Email == "" {
failure(w, http.StatusBadRequest, "Subject and email are required")
return
}
if len(req.Subject) > maxOIDCProvisionSubject || len(req.Email) > maxSignupEmailLen || len([]rune(req.Name)) > maxSignupNameLen || len(req.Image) > maxOIDCProvisionImageLen {
failure(w, http.StatusBadRequest, "Invalid identity")
return
}
configured := strings.TrimRight(strings.TrimSpace(config.Load().OIDCIssuer), "/")
if configured == "" || strings.TrimRight(req.Issuer, "/") != configured {
failure(w, http.StatusBadRequest, "Unknown issuer")
return
}
u, err := db.NewUserRepo(db.FromContext(r.Context())).ProvisionExternal(r.Context(), db.ExternalUserInput{
Provider: "authelia",
ProviderAccountID: req.Subject,
Email: req.Email,
EmailVerified: req.EmailVerified,
Name: req.Name,
Image: req.Image,
})
if errors.Is(err, db.ErrLinkRequired) {
failure(w, http.StatusConflict, "Account link required")
return
}
if err != nil {
failure(w, http.StatusInternalServerError, "Unable to resolve identity")
return
}
writeJSON(w, http.StatusOK, map[string]any{"user": identity(u), "tokenVersion": u.TokenVersion})
}