Files
archie/internal/webui/accounts.go
T

416 lines
14 KiB
Go

package webui
import (
"context"
"encoding/json"
"errors"
"net"
"net/http"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/ratelimit"
)
func (s *Server) registerAccountRoutes(public, protected *http.ServeMux) {
if s.Accounts == nil {
return
}
s.accountRateLimit = ratelimit.New(time.Minute, 20)
public.HandleFunc("GET /api/auth/status", s.handleAccountStatus)
public.HandleFunc("POST /api/auth/setup", s.handleAccountSetup)
public.HandleFunc("POST /api/auth/login", s.handleAccountLogin)
public.HandleFunc("POST /api/auth/logout", s.handleAccountLogout)
public.HandleFunc("POST /api/auth/recover", s.handleAccountRecover)
protected.HandleFunc("POST /api/accounts", s.handleAccountCreate)
personal := http.NewServeMux()
personal.HandleFunc("POST /api/account/password", s.handleAccountPassword)
personal.HandleFunc("POST /api/account/recovery", s.handleAccountRecovery)
public.Handle("/api/account/", s.requireAccount(s.authorizeAccountSelf(personal)))
protected.HandleFunc("GET /api/authentication", s.handleAuthenticationSettings)
protected.HandleFunc("PUT /api/authentication", s.handleAuthenticationSettings)
s.registerPasskeyRoutes(public, personal)
}
func (s *Server) accountIdentity(r *http.Request) (identity.Identity, error) {
if c, err := r.Cookie(s.cookies().account); err == nil {
value, err := s.Accounts.ResolveAccountSession(r.Context(), c.Value)
if err != nil {
return identity.Identity{}, err
}
if err := s.verifyAccountProvider(r, value); err != nil {
return identity.Identity{}, err
}
return value, nil
}
if s.Authenticate != nil && strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") {
return s.Authenticate(r.Context(), strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))
}
if cookie, err := r.Cookie(s.cookies().providerToken); err == nil {
return s.authenticateBrowser(r.Context(), cookie.Value)
}
return identity.Identity{}, identity.ErrNoCredential
}
func (s *Server) requireAccount(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
value, err := s.accountIdentity(r)
if err != nil || value.Kind != identity.KindUser || !value.CanAct() {
if err == nil {
err = identity.ErrCredentialRejected
}
s.writeAccountError(w, err)
return
}
h.ServeHTTP(w, r.WithContext(WithActingIdentity(r.Context(), value)))
})
}
func (s *Server) handleAccountStatus(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
required, err := s.Accounts.AccountSetupRequired(r.Context())
if err != nil {
s.writeAccountError(w, err)
return
}
var user *identity.Identity
value, err := s.accountIdentity(r)
if err == nil && value.Kind == identity.KindUser && value.CanAct() {
user = &value
} else if err != nil && !errors.Is(err, identity.ErrNoCredential) && !errors.Is(err, identity.ErrCredentialRejected) && !errors.Is(err, identity.ErrIdentityInactive) && !errors.Is(err, identity.ErrSubjectUnbound) {
s.writeAccountError(w, err)
return
}
oidcEnabled := s.Login != nil
publicURL := ""
if store, ok := s.authenticationSettings(); ok {
settings, settingsErr := store.AuthenticationSettings(r.Context())
if settingsErr != nil {
s.writeAccountError(w, settingsErr)
return
}
publicURL = settings.PublicURL
if settings.PublicURL != "" {
oidcEnabled = settings.OIDCIssuer != ""
}
}
writeJSON(w, map[string]any{"setup_required": required, "user": user, "oidc": oidcEnabled, "public_url": publicURL, "instance": s.Instance})
}
func decodeAccountRequest(w http.ResponseWriter, r *http.Request, value any) bool {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10)).Decode(value); err != nil {
http.Error(w, "invalid account request", http.StatusBadRequest)
return false
}
return true
}
func (s *Server) handleAccountSetup(w http.ResponseWriter, r *http.Request) {
if !s.authorizeAuthenticationMutation(w, r) {
return
}
var request identity.AccountRegistration
if !decodeAccountRequest(w, r, &request) {
return
}
if _, err := s.Accounts.RegisterAccount(r.Context(), request, true); err != nil {
s.writeAccountError(w, err)
return
}
s.signInAccount(w, r, request.Email, request.Password)
}
func (s *Server) handleAccountLogin(w http.ResponseWriter, r *http.Request) {
if !s.authorizeAuthenticationMutation(w, r) {
return
}
var request struct {
Email string `json:"email"`
Password string `json:"password"`
}
if !decodeAccountRequest(w, r, &request) {
return
}
s.signInAccount(w, r, request.Email, request.Password)
}
func (s *Server) signInAccount(w http.ResponseWriter, r *http.Request, email, password string) {
value, err := s.Accounts.SignInAccount(r.Context(), email, password)
if err != nil {
s.logf("account sign-in refused", "peer", r.RemoteAddr)
s.writeAccountError(w, err)
return
}
if s.Log != nil {
s.Log.InfoContext(r.Context(), "account signed in", "identity", value.Identity.ID)
}
s.clearProviderCookie(w)
s.setAccountCookie(w, r, value)
writeJSON(w, map[string]any{"user": value.Identity})
}
func (s *Server) setAccountCookie(w http.ResponseWriter, r *http.Request, value identity.AccountSession) {
scheme, _ := s.expectedOrigin(r)
http.SetCookie(w, &http.Cookie{Name: s.cookies().account, Value: value.Token, Path: "/", HttpOnly: true, Secure: scheme == "https", SameSite: http.SameSiteStrictMode, Expires: value.Expires, MaxAge: int(time.Until(value.Expires).Seconds())})
w.Header().Set("Cache-Control", "no-store")
}
func (s *Server) handleAccountLogout(w http.ResponseWriter, r *http.Request) {
if !s.authorizeAuthenticationMutation(w, r) {
return
}
if c, err := r.Cookie(s.cookies().account); err == nil {
if err = s.Accounts.SignOutAccount(r.Context(), c.Value); err != nil {
s.writeAccountError(w, err)
return
}
}
for _, name := range []string{s.cookies().account, s.cookies().providerToken} {
http.SetCookie(w, &http.Cookie{Name: name, Path: "/", HttpOnly: true, MaxAge: -1, SameSite: http.SameSiteStrictMode})
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) handleAccountCreate(w http.ResponseWriter, r *http.Request) {
if !s.authorizeAuthenticationMutation(w, r) {
return
}
if !s.requireFreshAccount(w, r) {
return
}
var request identity.AccountRegistration
if !decodeAccountRequest(w, r, &request) {
return
}
value, err := s.Accounts.RegisterAccount(r.Context(), request, false)
if err != nil {
s.writeAccountError(w, err)
return
}
w.WriteHeader(http.StatusCreated)
writeJSON(w, map[string]any{"user": value})
}
func (s *Server) handleAccountPassword(w http.ResponseWriter, r *http.Request) {
if !s.authorizeAuthenticationMutation(w, r) {
return
}
var request struct {
Current string `json:"current_password"`
New string `json:"new_password"`
}
if !decodeAccountRequest(w, r, &request) {
return
}
if err := s.Accounts.ChangeAccountPassword(r.Context(), request.Current, request.New); err != nil {
s.writeAccountError(w, err)
return
}
http.SetCookie(w, &http.Cookie{Name: s.cookies().account, Path: "/", MaxAge: -1, HttpOnly: true, SameSite: http.SameSiteStrictMode})
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) writeAccountError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, identity.ErrNoCredential), errors.Is(err, identity.ErrCredentialRejected), errors.Is(err, identity.ErrIdentityInactive), errors.Is(err, identity.ErrSubjectUnbound):
http.Error(w, "Sign-in required or credentials not accepted.", http.StatusUnauthorized)
case errors.Is(err, identity.ErrSetupComplete):
http.Error(w, identity.ErrSetupComplete.Error(), http.StatusConflict)
case errors.Is(err, identity.ErrNotFound):
http.Error(w, "Record not found.", http.StatusNotFound)
case errors.Is(err, identity.ErrConflict):
http.Error(w, "An account already uses that email.", http.StatusConflict)
case errors.Is(err, identity.ErrInvalid):
http.Error(w, "Enter a name, valid email, organisation name for setup, and an uncommon password of at least 15 characters (at most 1024 bytes).", http.StatusBadRequest)
default:
s.logf("account operation failed", "err", err)
http.Error(w, "Account service unavailable.", http.StatusServiceUnavailable)
}
}
func (s *Server) authenticationSettings() (identity.AuthenticationSettingsStore, bool) {
value, ok := s.Accounts.(identity.AuthenticationSettingsStore)
return value, ok
}
func (s *Server) handleAuthenticationSettings(w http.ResponseWriter, r *http.Request) {
if !instanceOwner(r) {
http.Error(w, "instance administrator required", http.StatusForbidden)
return
}
store, ok := s.authenticationSettings()
if !ok {
http.Error(w, "authentication settings unavailable", http.StatusServiceUnavailable)
return
}
if r.Method == http.MethodGet {
value, err := store.AuthenticationSettings(r.Context())
if err != nil {
s.writeAccountError(w, err)
return
}
writeJSON(w, value)
return
}
if !s.requireFreshAccount(w, r) {
return
}
if !s.authorizeAuthenticationMutation(w, r) {
return
}
var value identity.AuthenticationSettings
if !decodeAccountRequest(w, r, &value) {
return
}
if err := store.SaveAuthenticationSettings(r.Context(), value); err != nil {
if errors.Is(err, identity.ErrInvalid) {
http.Error(w, "Use a valid instance origin and complete OIDC settings. Remove enrolled passkeys before changing the instance URL.", http.StatusBadRequest)
return
}
s.writeAccountError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) authorizeAccountSelf(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
acting, ok := ActingIdentity(r.Context())
if !ok || acting.Kind != identity.KindUser || !acting.CanAct() {
http.Error(w, "sign-in required", http.StatusUnauthorized)
return
}
principal, err := s.requestPrincipal(r.Context())
if err != nil {
s.writeAccountError(w, err)
return
}
h.ServeHTTP(w, r.WithContext(org.WithOrg(access.WithPrincipal(r.Context(), principal), principal.Org)))
})
}
func (s *Server) requireFreshAccount(w http.ResponseWriter, r *http.Request) bool {
store, ok := s.Accounts.(identity.AccountSecurity)
if !ok {
http.Error(w, "account security unavailable", http.StatusServiceUnavailable)
return false
}
cookie, err := r.Cookie(s.cookies().account)
if err == nil {
err = store.RequireFreshAccountSession(r.Context(), cookie.Value)
}
if err != nil {
http.Error(w, "Sign in again before changing account security.", http.StatusForbidden)
return false
}
return true
}
func (s *Server) handleAccountRecovery(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) || !s.requireFreshAccount(w, r) {
return
}
store, ok := s.Accounts.(identity.AccountSecurity)
if !ok {
http.Error(w, "account security unavailable", http.StatusServiceUnavailable)
return
}
code, err := store.CreateAccountRecovery(r.Context())
if err != nil {
s.writeAccountError(w, err)
return
}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, map[string]string{"code": code})
}
func (s *Server) handleAccountRecover(w http.ResponseWriter, r *http.Request) {
if !s.authorizeAuthenticationMutation(w, r) {
return
}
store, ok := s.Accounts.(identity.AccountSecurity)
if !ok {
http.Error(w, "account security unavailable", http.StatusServiceUnavailable)
return
}
var request struct {
Email string `json:"email"`
Code string `json:"code"`
Password string `json:"password"`
}
if !decodeAccountRequest(w, r, &request) {
return
}
if err := store.RecoverAccount(r.Context(), request.Email, request.Code, request.Password); err != nil {
s.writeAccountError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) clearProviderCookie(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{Name: s.cookies().providerToken, Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1})
}
func (s *Server) authorizeAuthenticationMutation(w http.ResponseWriter, r *http.Request) bool {
if !s.authorizeTaskMutation(w, r) {
return false
}
scheme, host := s.expectedOrigin(r)
hostname := host
if name, _, err := net.SplitHostPort(host); err == nil {
hostname = name
}
local := strings.EqualFold(hostname, "localhost") || (net.ParseIP(hostname) != nil && net.ParseIP(hostname).IsLoopback())
if scheme != "https" && !local {
http.Error(w, "Account credentials require HTTPS. Use a TLS proxy, or localhost for development.", http.StatusForbidden)
return false
}
if strings.HasPrefix(r.URL.Path, "/api/auth/") && s.accountRateLimit != nil {
peer, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
peer = r.RemoteAddr
}
s.accountRateLimit.EvictStale()
if !s.accountRateLimit.Allow("authentication", peer) {
w.Header().Set("Retry-After", "60")
http.Error(w, "Too many sign-in attempts. Try again shortly.", http.StatusTooManyRequests)
return false
}
}
return true
}
func (s *Server) verifyAccountProvider(r *http.Request, value identity.Identity) error {
cookie, err := r.Cookie(s.cookies().providerToken)
if errors.Is(err, http.ErrNoCookie) {
return nil
}
if err != nil {
return err
}
providerValue, err := s.authenticateBrowser(r.Context(), cookie.Value)
if err != nil {
return err
}
if providerValue.ID != value.ID {
return identity.ErrCredentialRejected
}
return nil
}
func (s *Server) authenticateBrowser(ctx context.Context, credential string) (identity.Identity, error) {
verify := s.AuthenticateBrowser
if verify == nil {
verify = s.Authenticate
}
if verify == nil {
return identity.Identity{}, identity.ErrCredentialRejected
}
return verify(ctx, credential)
}