Files
pages/internal/server/auth_external.go
T
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

302 lines
12 KiB
Go

package server
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type oidcChallenge struct{ Verifier, Nonce, Return, Issuer, ClientID, BrowserHash string }
func logOIDCFailure(stage, domainUUID, issuer string, err error) {
host := "invalid"
if parsed, parseErr := url.Parse(issuer); parseErr == nil && parsed.Hostname() != "" {
host = parsed.Hostname()
}
cause := err
for errors.Unwrap(cause) != nil {
cause = errors.Unwrap(cause)
}
log.Printf("OIDC %s failed domain=%s issuer_host=%s cause=%T: %v", stage, domainUUID, host, cause, cause)
}
func randomURLToken(size int) string {
raw := make([]byte, size)
_, _ = rand.Read(raw)
return base64.RawURLEncoding.EncodeToString(raw)
}
func externalURL(r *http.Request, path string) string {
scheme := "http"
if requestIsHTTPS(r) {
scheme = "https"
}
return scheme + "://" + r.Host + path
}
func (s *Server) beginOIDC(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.Header().Set("Allow", http.MethodGet)
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
domainUUID := s.domainUUIDForRequest(r)
config, err := s.store.AuthProviderConfig(domainUUID, "oidc")
if err != nil || !config.Enabled {
http.NotFound(w, r)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
defer cancel()
metadata, err := fetchOIDCMetadata(ctx, config.Issuer)
if err != nil {
logOIDCFailure("discovery", domainUUID, config.Issuer, err)
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
verifier, nonce, browser := randomURLToken(32), randomURLToken(24), randomURLToken(32)
browserDigest := sha256.Sum256([]byte(browser))
state, err := s.store.CreateAuthChallenge(domainUUID, "", "oidc", oidcChallenge{Verifier: verifier, Nonce: nonce, Return: safeReturnPath(r.URL.Query().Get("return")), Issuer: config.Issuer, ClientID: config.ClientID, BrowserHash: base64.RawURLEncoding.EncodeToString(browserDigest[:])}, 5*time.Minute)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
digest := sha256.Sum256([]byte(verifier))
query := url.Values{"response_type": {"code"}, "client_id": {config.ClientID}, "redirect_uri": {externalURL(r, "/_/auth/callback/oidc")}, "scope": {"openid email profile"}, "state": {state}, "nonce": {nonce}, "code_challenge_method": {"S256"}, "code_challenge": {base64.RawURLEncoding.EncodeToString(digest[:])}}
authorizationURL, _ := url.Parse(metadata.AuthorizationEndpoint)
parameters := authorizationURL.Query()
for key, value := range query {
parameters[key] = value
}
authorizationURL.RawQuery = parameters.Encode()
setOIDCBrowserCookie(w, r, browser, 300)
w.Header().Set("Cache-Control", "no-store")
http.Redirect(w, r, authorizationURL.String(), http.StatusFound)
}
func (s *Server) completeOIDC(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.Header().Set("Allow", http.MethodGet)
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Cache-Control", "no-store")
domainUUID := s.domainUUIDForRequest(r)
var challenge oidcChallenge
if _, err := s.store.ConsumeAuthChallenge(domainUUID, "oidc", r.URL.Query().Get("state"), &challenge); err != nil {
http.Error(w, "invalid OIDC state", http.StatusBadRequest)
return
}
if !validOIDCBrowserChallenge(oidcBrowserCookie(r), challenge.BrowserHash) {
http.Error(w, "OIDC state belongs to a different browser", http.StatusBadRequest)
return
}
setOIDCBrowserCookie(w, r, "", -1)
config, err := s.store.AuthProviderConfig(domainUUID, "oidc")
if err != nil || !config.Enabled {
http.Error(w, "OIDC is disabled", http.StatusBadRequest)
return
}
if config.Issuer != challenge.Issuer || config.ClientID != challenge.ClientID || r.URL.Query().Get("code") == "" || r.URL.Query().Get("error") != "" {
http.Error(w, "OIDC login must be restarted", http.StatusBadRequest)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
metadata, err := fetchOIDCMetadata(ctx, config.Issuer)
if err != nil {
logOIDCFailure("callback discovery", domainUUID, config.Issuer, err)
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
form := url.Values{"grant_type": {"authorization_code"}, "code": {r.URL.Query().Get("code")}, "redirect_uri": {externalURL(r, "/_/auth/callback/oidc")}, "client_id": {config.ClientID}, "client_secret": {config.ClientSecret}, "code_verifier": {challenge.Verifier}}
var tokens struct {
AccessToken string `json:"access_token"`
IDToken string `json:"id_token"`
TokenType string `json:"token_type"`
}
if tokenErr := oidcVerifier.requestJSON(ctx, http.MethodPost, metadata.TokenEndpoint, form, "", &tokens); tokenErr != nil {
logOIDCFailure("token exchange", domainUUID, config.Issuer, tokenErr)
http.Error(w, "OIDC token exchange failed", http.StatusBadGateway)
return
}
if tokens.AccessToken == "" || len(tokens.AccessToken) > 16<<10 || !strings.EqualFold(tokens.TokenType, "Bearer") {
http.Error(w, "OIDC token exchange failed", http.StatusBadGateway)
return
}
idClaims, err := oidcVerifier.verify(ctx, metadata, tokens.IDToken, config.ClientID, challenge.Nonce, tokens.AccessToken)
if err != nil {
logOIDCFailure("ID-token verification", domainUUID, config.Issuer, err)
http.Error(w, "OIDC ID-token verification failed", http.StatusBadRequest)
return
}
var claims struct {
Sub, Email string
Name string `json:"name"`
DisplayName string `json:"display_name"`
PreferredName string `json:"preferred_username"`
EmailVerified bool `json:"email_verified"`
}
if userinfoErr := oidcVerifier.requestJSON(ctx, http.MethodGet, metadata.UserinfoEndpoint, nil, tokens.AccessToken, &claims); userinfoErr != nil {
logOIDCFailure("UserInfo", domainUUID, config.Issuer, userinfoErr)
http.Error(w, "OIDC identity is not a verified account", http.StatusForbidden)
return
}
if claims.Sub == "" {
http.Error(w, "OIDC identity is not a verified account", http.StatusForbidden)
return
}
if claims.Sub != idClaims.Sub {
http.Error(w, "OIDC subject mismatch", http.StatusForbidden)
return
}
principal, err := s.store.PrincipalByExternalIdentity(domainUUID, "oidc", "oidc", config.Issuer, claims.Sub)
if err != nil {
switch config.OIDCMatchBy {
case "preferred_username":
principal, err = s.store.PrincipalByExternalUsername(domainUUID, claims.PreferredName)
if err != nil {
log.Printf("OIDC local account match failed domain=%s mode=preferred_username present=%t", domainUUID, strings.TrimSpace(claims.PreferredName) != "")
}
case "display_name":
displayName := strings.TrimSpace(claims.Name)
claimSource := "name"
if displayName == "" {
displayName = strings.TrimSpace(claims.DisplayName)
claimSource = "display_name"
}
principal, err = s.store.PrincipalByDisplayName(domainUUID, displayName)
if err != nil {
log.Printf("OIDC local account match failed domain=%s mode=display_name claim=%s present=%t", domainUUID, claimSource, displayName != "")
}
default:
if claims.Email == "" || !claims.EmailVerified {
http.Error(w, "OIDC identity is not a verified account", http.StatusForbidden)
return
}
principal, err = s.store.PrincipalByVerifiedEmail(domainUUID, claims.Email)
}
if err == nil {
err = s.store.BindExternalIdentity(principal.UUID, "oidc", "oidc", config.Issuer, claims.Sub, claims)
}
}
if err != nil {
http.Error(w, "No local account matches the configured OIDC identity field", http.StatusForbidden)
return
}
token, err := s.store.CreateBrowserAuthSession(domainUUID, principal.UUID, 0)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
s.setAuthCookie(w, r, token)
http.Redirect(w, r, challenge.Return, http.StatusSeeOther)
}
func (s *Server) requestMagicLink(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.Header().Set("Allow", "POST")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Cache-Control", "no-store")
domainUUID := s.domainUUIDForRequest(r)
r.Body = http.MaxBytesReader(w, r.Body, 64<<10)
if err := r.ParseForm(); err != nil {
http.Error(w, "invalid sign-in request", http.StatusBadRequest)
return
}
config, configErr := s.store.AuthProviderConfig(domainUUID, "smtp")
requested, mailboxErr := smtpMailbox(r.FormValue("email"))
if configErr == nil && config.Enabled && mailboxErr == nil {
principal, principalErr := s.store.PrincipalByVerifiedEmail(domainUUID, requested.Address)
if principalErr == nil {
_, _, _, _, principalErr = smtpMessage(config, principal.Email, externalURL(r, "/_/auth/magic-link/verify"))
}
if principalErr == nil {
select {
case s.smtpSlots <- struct{}{}:
token, err := s.store.CreateAuthChallenge(domainUUID, principal.UUID, "magic-link", magicLinkChallenge{Return: safeReturnPath(r.FormValue("return")), Email: principal.Email}, 15*time.Minute)
if err != nil {
<-s.smtpSlots
break
}
link := externalURL(r, "/_/auth/magic-link/verify?token="+url.QueryEscape(token))
go func() {
defer func() { <-s.smtpSlots }()
_ = sendMagicLinkSMTP(context.Background(), config, principal.Email, link)
}()
default:
}
}
}
s.renderAuthPage(w, r, map[string]any{"MagicSent": true, "Return": safeReturnPath(r.FormValue("return"))})
}
func (s *Server) verifyMagicLink(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.Header().Set("Allow", "GET")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Cache-Control", "no-store")
domainUUID := s.domainUUIDForRequest(r)
var payload magicLinkChallenge
principalUUID, err := s.store.ConsumeAuthChallenge(domainUUID, "magic-link", r.URL.Query().Get("token"), &payload)
if err != nil {
http.Error(w, "This sign-in link is invalid or expired", http.StatusBadRequest)
return
}
config, configErr := s.store.AuthProviderConfig(domainUUID, "smtp")
var valid bool
stateErr := s.store.DB.QueryRow(`SELECT EXISTS(SELECT 1 FROM principals p JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=? WHERE p.uuid=? AND p.state IN ('active','readonly') AND m.state='active' AND p.email=?)`, domainUUID, principalUUID, payload.Email).Scan(&valid)
if configErr != nil || !config.Enabled || stateErr != nil || !valid || payload.Email == "" {
http.Error(w, "This sign-in link is invalid or expired", http.StatusBadRequest)
return
}
token, err := s.store.CreateBrowserAuthSession(domainUUID, principalUUID, 0)
if err != nil {
http.Error(w, "This sign-in link is invalid or expired", http.StatusBadRequest)
return
}
s.setAuthCookie(w, r, token)
http.Redirect(w, r, safeReturnPath(payload.Return), http.StatusSeeOther)
}
func (s *Server) renderAuthPage(w http.ResponseWriter, r *http.Request, data map[string]any) {
domainUUID := s.domainUUIDForRequest(r)
if data == nil {
data = map[string]any{}
}
if config, err := s.store.AuthProviderConfig(domainUUID, "oidc"); err == nil {
data["OIDCEnabled"] = config.Enabled
}
if config, err := s.store.AuthProviderConfig(domainUUID, "smtp"); err == nil {
data["MagicEnabled"] = config.Enabled
}
if config, err := s.store.AuthProviderConfig(domainUUID, "ldap"); err == nil {
data["LDAPEnabled"] = config.Enabled
}
data["Locale"] = s.getLocale(domainUUID)
transparency := s.homeGlassTransparency(domainUUID)
data["HomeGlassTransparency"] = transparency
data["HomeGlassOpacity"] = 100 - transparency
configured, opacity := s.homeWallpaperConfig(domainUUID)
data["HomeWallpaperOpacity"] = strconv.FormatFloat(float64(opacity)/100, 'f', 2, 64)
if configured != "" {
// Only the administrator-selected login wallpaper is exposed; the
// request cannot choose an arbitrary document address.
data["HomeWallpaperURL"] = "/_/auth/wallpaper"
w.Header().Set("Cache-Control", "private, no-store")
}
s.renderWithContext(w, r, "auth.gohtml", data)
}