ci: expand shared package validation and test coverage
Lint / Lint (push) Successful in 32s
Docker / Docker Build & Push (push) Failing after 2m22s
Tests / Go backend (push) Failing after 1m2s
Tests / Dashboard checks (push) Failing after 35s

- Add lint, formatting, vet, and publish workflow checks
- Run Go database tests with PostgreSQL and add Java tests
- Make consumer sync opt-in; update docs and Go dependency
This commit is contained in:
Gabriel20xx committed 2026-10-19 21:46:52 +00:00
1 parent 937f51b4fb
commit 0ff94f9b10
107 files changed
+10124 -410

No files matched your search

+155 -52
View File
@@ -165,9 +165,12 @@ package auth
import (
"context"
"crypto/subtle"
"encoding/json"
"errors"
"io"
"mime"
"net"
"net/http"
"os"
"strconv"
@@ -178,7 +181,6 @@ import (
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"golang.org/x/crypto/bcrypt"
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
"repos.gfranz.ch/Gabriel20xx/shared/backend/authproxy"
)
@@ -222,6 +224,11 @@ var (
// indistinguishable from any other server bug.
errAuthGuardUnavailable = errors.New("Unable to reach the authentication service. Please try again shortly.")
errSecretNotSet = errors.New("SECRET environment variable is not set.")
errTooManyAttempts = errors.New("Too many attempts. Try again later.")
errSetupRequiresLogin = errors.New("Account setup is only available while login is required.")
errNoLoginRequiredStore = errors.New("the login-required setting has no store to save to")
errCrossSiteRequest = errors.New("cross-site request refused")
errJSONContentType = errors.New("request body must be application/json")
errSelfServiceProfile = errors.New("Self-service profile editing is only available to administrator accounts; ask an administrator to update this account.")
)
@@ -230,6 +237,8 @@ const (
setupClaimedSettingKey = "setup_claimed"
proxyMinPasswordLength = 8
// maxBcryptPasswordBytes is the longest password bcrypt hashes in full.
maxBcryptPasswordBytes = 72
proxyMaxUsernameLength = 64
proxyMaxEmailLength = 254
)
@@ -277,12 +286,17 @@ type Service struct {
// real base URL.
authGuard *authclient.Client
configurationError error
// loginRequiredOverride is populated by the internal ProjectConfigurator
// endpoint. Some legacy consumers intentionally use a no-op ProxyStore for
// this setting because they historically had no local toggle; the live
// override lets those services still honor the central setting immediately.
loginRequiredMu sync.RWMutex
loginRequiredOverride *bool
loginCacheMu sync.Mutex
loginCacheValue bool
loginCacheSet bool
loginCacheExpires time.Time
// Attempt counters for the credential endpoints; see ratelimit.go.
loginAccountAttempts *attemptLimiter
loginClientAttempts *attemptLimiter
totpAttempts *attemptLimiter
// trustedProxies are the peers whose X-Forwarded-For header is honoured;
// see clientAddress in clientip.go.
trustedProxies []*net.IPNet
}
// ServiceOption configures optional New/NewWithStore construction behavior.
@@ -291,8 +305,9 @@ type Service struct {
type ServiceOption func(*serviceOptions)
type serviceOptions struct {
disabled bool
requireSecret bool
disabled bool
requireSecret bool
trustedProxies []*net.IPNet
}
// Disabled explicitly builds a Service in auth-disabled mode (see the
@@ -314,6 +329,14 @@ func RequireSecret() ServiceOption {
return func(o *serviceOptions) { o.requireSecret = true }
}
// WithTrustedProxies sets the reverse proxies whose X-Forwarded-For header is
// honoured when a login's client address is taken. Build the list from the
// TRUSTED_PROXIES setting with ParseTrustedProxies. Without it, the TCP peer
// is always the client address.
func WithTrustedProxies(networks []*net.IPNet) ServiceOption {
return func(o *serviceOptions) { o.trustedProxies = networks }
}
// New constructs a Service backed by the media family's shared `settings`
// table (pgSettingsStore) for the login-required toggle and setup-claim
// flag, and by db directly for the unrelated "moderatable platform users"
@@ -359,7 +382,17 @@ func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authG
if options.requireSecret && !options.disabled && strings.TrimSpace(os.Getenv("SECRET")) == "" {
configurationError = errSecretNotSet
}
return &Service{store: store, cookieName: cookieName, secureCookies: secureCookies, authGuard: client, configurationError: configurationError}
return &Service{
store: store,
cookieName: cookieName,
secureCookies: secureCookies,
authGuard: client,
configurationError: configurationError,
loginAccountAttempts: newAttemptLimiter(attemptWindow, loginAccountLimit),
loginClientAttempts: newAttemptLimiter(attemptWindow, loginClientLimit),
totpAttempts: newAttemptLimiter(attemptWindow, totpAttemptLimit),
trustedProxies: options.trustedProxies,
}
}
// pgSettingsStore is the default ProxyStore New builds over the media
@@ -562,16 +595,8 @@ func (s *Service) RequireIfLoginRequired(next http.Handler) http.Handler {
next.ServeHTTP(w, r)
return
}
loginRequired, err := s.LoginRequired(r.Context())
if err != nil {
writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
if !loginRequired {
next.ServeHTTP(w, r)
return
}
// CurrentUser returns no user only when login is required (it returns the
// synthetic admin for every other case), so no second settings read is needed.
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
}))
}
@@ -595,15 +620,7 @@ func (s *Service) RequireAdminIfLoginRequired(next http.Handler) http.Handler {
return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context())
if user == nil {
loginRequired, err := s.LoginRequired(r.Context())
if err != nil {
writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
if !loginRequired {
next.ServeHTTP(w, r)
return
}
// As in RequireIfLoginRequired, a nil user means login is required.
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return
}
@@ -756,17 +773,37 @@ func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) {
writeProxyJSON(w, http.StatusOK, map[string]bool{"adminNeeded": setupRequired})
}
// LoginRequired caches the store's value briefly to avoid a database read for
// every authenticated route. Updates through this Service clear the cache
// immediately; changes made by another replica become visible within two seconds.
func (s *Service) LoginRequired(ctx context.Context) (bool, error) {
s.loginRequiredMu.RLock()
override := s.loginRequiredOverride
s.loginRequiredMu.RUnlock()
if override != nil {
return *override, nil
}
if s.store == nil {
return true, nil
}
return s.store.LoginRequired(ctx)
now := time.Now()
s.loginCacheMu.Lock()
if s.loginCacheSet && now.Before(s.loginCacheExpires) {
value := s.loginCacheValue
s.loginCacheMu.Unlock()
return value, nil
}
s.loginCacheMu.Unlock()
value, err := s.store.LoginRequired(ctx)
if err != nil {
return false, err
}
s.loginCacheMu.Lock()
if s.loginCacheSet && time.Now().Before(s.loginCacheExpires) {
cached := s.loginCacheValue
s.loginCacheMu.Unlock()
return cached, nil
}
s.loginCacheValue = value
s.loginCacheSet = true
s.loginCacheExpires = time.Now().Add(2 * time.Second)
s.loginCacheMu.Unlock()
return value, nil
}
func (s *Service) AccessSettings(w http.ResponseWriter, r *http.Request) {
@@ -799,14 +836,17 @@ func (s *Service) UpdateAccessSettings(w http.ResponseWriter, r *http.Request) {
// central "Require Login" toggle (ConfigWorkspace.svelte's loginControls) apply here without an
// admin session of its own.
func (s *Service) SetLoginRequired(ctx context.Context, required bool) error {
if s.store != nil {
if err := s.store.SetLoginRequired(ctx, required); err != nil {
return err
}
if s.store == nil {
return errNoLoginRequiredStore
}
s.loginRequiredMu.Lock()
s.loginRequiredOverride = &required
s.loginRequiredMu.Unlock()
if err := s.store.SetLoginRequired(ctx, required); err != nil {
return err
}
// Drop the cached value rather than setting it, so the next read comes from the store and a
// store that discards writes cannot leave this process with its own login setting.
s.loginCacheMu.Lock()
s.loginCacheSet = false
s.loginCacheMu.Unlock()
return nil
}
@@ -816,7 +856,7 @@ func (s *Service) SetLoginRequired(ctx context.Context, required bool) error {
// expose the same propagation endpoint without duplicating its JSON handling.
func (s *Service) SetLoginRequiredInternal(secret string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.TrimSpace(secret) == "" || r.Header.Get("X-Internal-Auth") != secret {
if strings.TrimSpace(secret) == "" || subtle.ConstantTimeCompare([]byte(r.Header.Get("X-Internal-Auth")), []byte(secret)) != 1 {
writeProxyError(w, http.StatusUnauthorized, "internal service authentication required")
return
}
@@ -992,6 +1032,9 @@ func (s *Service) ManagedUpdateUser(w http.ResponseWriter, r *http.Request) {
// enforces authorization (including "this user cannot be deleted" rules)
// itself.
func (s *Service) ManagedDeleteUser(w http.ResponseWriter, r *http.Request) {
if refuseCrossSite(w, r) {
return
}
id, err := strconv.ParseInt(idURLParam(r), 10, 64)
if err != nil {
writeProxyError(w, http.StatusBadRequest, "invalid user id")
@@ -1017,6 +1060,18 @@ func (s *Service) Signup(w http.ResponseWriter, r *http.Request) {
writeProxyJSON(w, http.StatusCreated, map[string]any{"user": &user})
return
}
// First-run setup only applies while login is required. With login off, every
// caller already gets the local admin identity, and a fresh AuthGuard would make
// an anonymous signup its superadmin.
loginRequired, err := s.LoginRequired(r.Context())
if err != nil {
writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
if !loginRequired {
writeProxyError(w, http.StatusConflict, errSetupRequiresLogin.Error())
return
}
var input struct {
Email string `json:"email"`
@@ -1074,7 +1129,7 @@ func (s *Service) Signup(w http.ResponseWriter, r *http.Request) {
return
}
result, err := s.authGuard.Register(r.Context(), username, email, input.Password)
result, err := s.authGuard.Register(s.withClientIP(r), username, email, input.Password)
if err != nil {
// The claim slot is only valid once actually backed by a real
// AuthGuard account; reopen it so a corrected retry can proceed.
@@ -1115,8 +1170,13 @@ func (s *Service) Login(w http.ResponseWriter, r *http.Request) {
writeProxyError(w, http.StatusUnauthorized, ErrInvalidLogin.Error())
return
}
now := time.Now()
if !s.loginAccountAttempts.allow(strings.ToLower(identifier), now) || !s.loginClientAttempts.allow(s.clientAddress(r), now) {
writeProxyError(w, http.StatusTooManyRequests, errTooManyAttempts.Error())
return
}
result, err := s.authGuard.Login(r.Context(), identifier, input.Password, input.TOTPToken)
result, err := s.authGuard.Login(s.withClientIP(r), identifier, input.Password, input.TOTPToken)
if err != nil {
var apiErr *authclient.APIError
if errors.As(err, &apiErr) {
@@ -1142,6 +1202,9 @@ func (s *Service) Login(w http.ResponseWriter, r *http.Request) {
}
func (s *Service) Logout(w http.ResponseWriter, r *http.Request) {
if refuseCrossSite(w, r) {
return
}
if !s.enabled() {
writeProxyJSON(w, http.StatusOK, map[string]bool{"ok": true})
return
@@ -1181,6 +1244,9 @@ func (s *Service) TOTPStatus(w http.ResponseWriter, r *http.Request) {
// /api/totp/enable (AuthGuard's "enable" is this service's "initiate" step -
// naming differs, the two-step provision-then-confirm flow is identical).
func (s *Service) TOTPInitiate(w http.ResponseWriter, r *http.Request) {
if refuseCrossSite(w, r) {
return
}
if !s.enabled() {
writeProxyError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error())
return
@@ -1217,6 +1283,10 @@ func (s *Service) TOTPVerify(w http.ResponseWriter, r *http.Request) {
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return
}
if !s.totpAttempts.allow(strconv.FormatInt(user.ID, 10), time.Now()) {
writeProxyError(w, http.StatusTooManyRequests, errTooManyAttempts.Error())
return
}
var input struct {
Token string `json:"token"`
TOTPToken string `json:"totpToken"`
@@ -1229,7 +1299,7 @@ func (s *Service) TOTPVerify(w http.ResponseWriter, r *http.Request) {
if token == "" {
token = strings.TrimSpace(input.Token)
}
if err := s.authGuard.TOTPVerify(r.Context(), s.sessionToken(r), token); err != nil {
if err := s.authGuard.TOTPVerify(s.withClientIP(r), s.sessionToken(r), token); err != nil {
writeProxyError(w, http.StatusUnauthorized, "Invalid authenticator code.")
return
}
@@ -1246,6 +1316,10 @@ func (s *Service) TOTPDisable(w http.ResponseWriter, r *http.Request) {
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return
}
if !s.totpAttempts.allow(strconv.FormatInt(user.ID, 10), time.Now()) {
writeProxyError(w, http.StatusTooManyRequests, errTooManyAttempts.Error())
return
}
var input struct {
Token string `json:"token"`
TOTPToken string `json:"totpToken"`
@@ -1258,7 +1332,7 @@ func (s *Service) TOTPDisable(w http.ResponseWriter, r *http.Request) {
if token == "" {
token = strings.TrimSpace(input.Token)
}
if err := s.authGuard.TOTPDisable(r.Context(), s.sessionToken(r), token); err != nil {
if err := s.authGuard.TOTPDisable(s.withClientIP(r), s.sessionToken(r), token); err != nil {
writeProxyError(w, http.StatusUnauthorized, "Invalid authenticator code.")
return
}
@@ -1341,7 +1415,7 @@ func (s *Service) CreateUser(ctx context.Context, email, username, password, rol
return nil, err
}
role = normalizePlatformRole(role)
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
hash, err := HashPassword(password)
if err != nil {
return nil, err
}
@@ -1350,7 +1424,7 @@ func (s *Service) CreateUser(ctx context.Context, email, username, password, rol
INSERT INTO users (email, username, password_hash, role)
VALUES ($1, $2, $3, $4)
RETURNING id, email, COALESCE(username, ''), COALESCE(role, 'user')
`, email, username, string(hash), role).Scan(&user.ID, &user.Email, &user.Username, &user.Role)
`, email, username, hash, role).Scan(&user.ID, &user.Email, &user.Username, &user.Role)
if err != nil {
return nil, err
}
@@ -1414,11 +1488,11 @@ func (s *Service) SetPassword(ctx context.Context, id int64, password string) er
if err := validateProxyPassword(password); err != nil {
return err
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
hash, err := HashPassword(password)
if err != nil {
return err
}
_, err = s.db.Exec(ctx, `UPDATE users SET password_hash=$2 WHERE id=$1`, id, string(hash))
_, err = s.db.Exec(ctx, `UPDATE users SET password_hash=$2 WHERE id=$1`, id, hash)
return err
}
@@ -1445,6 +1519,10 @@ func normalizeProxyUsername(value string) (string, error) {
if len([]rune(value)) > proxyMaxUsernameLength {
return "", errors.New("username is too long")
}
// An identifier containing "@" could be read as another account's email at login.
if strings.Contains(value, "@") {
return "", errors.New("username cannot contain @")
}
return value, nil
}
@@ -1460,6 +1538,10 @@ func validateProxyPassword(password string) error {
if len([]rune(password)) < proxyMinPasswordLength || len([]rune(password)) > 1024 {
return errors.New("Password must be at least 8 characters.")
}
// bcrypt uses only the first 72 bytes, so a longer password would be refused at hashing time.
if len(password) > maxBcryptPasswordBytes {
return errors.New("Password must be at most 72 bytes.")
}
return nil
}
@@ -1506,8 +1588,29 @@ func idURLParam(r *http.Request) string {
return r.PathValue("id")
}
// decodeProxyJSON reads a JSON request body. It refuses a body that is not sent as
// application/json, which a cross-site HTML form cannot produce, and any request the browser
// marks as cross-site.
// refuseCrossSite answers a state-changing request that carries no JSON body (logout, TOTP
// initiate, user delete) when the browser says it came from another site. Simple cross-site
// forms cannot send a JSON body, so decodeProxyJSON already refuses them; this covers the rest.
func refuseCrossSite(w http.ResponseWriter, r *http.Request) bool {
if r.Header.Get("Sec-Fetch-Site") == "cross-site" {
writeProxyError(w, http.StatusForbidden, errCrossSiteRequest.Error())
return true
}
return false
}
func decodeProxyJSON(r *http.Request, target any) error {
defer r.Body.Close()
if r.Header.Get("Sec-Fetch-Site") == "cross-site" {
return errCrossSiteRequest
}
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mediaType != "application/json" {
return errJSONContentType
}
decoder := json.NewDecoder(io.LimitReader(r.Body, 128*1024))
return decoder.Decode(target)
}