Files
Andrew S Erwin 4b6a58118e Rename Go module to gitea.federated.computer/Federated_Computer/superbrain
The Gitea repository was renamed brain -> superbrain (server-side redirect
already in place; local origin updated at 0.3.5). Carry the rename through
for accurate identity, the 0.3.2 precedent: go.mod + every internal import,
the agent's outbound User-Agent contact URL, README/RUNNING clone URLs and
local notes. CHANGELOG history entries stay as written. Pure identifier
rename, no runtime behavior change; verified with build + vet + unit tests
and the full database integration suite under -race.
2026-11-24 16:02:01 -06:00

148 lines
5.3 KiB
Go

package auth
import (
"encoding/json"
"errors"
"net/http"
"strings"
"time"
"gitea.federated.computer/Federated_Computer/superbrain/internal/config"
"gitea.federated.computer/Federated_Computer/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})
}