feat(sync): paginate Android sync with change tokens
Lint / Lint (push) Successful in 1m8s
Tests / Go backend (push) Failing after 1m23s
Tests / Dashboard checks (push) Failing after 38s
Docker / Docker Build & Push (push) Failing after 6m29s

This commit is contained in:
Gabriel20xx committed 2026-10-20 15:27:53 +00:00
1 parent 0ff94f9b10
commit 97c237be80
76 files changed
+3401 -851

No files matched your search

+63 -12
View File
@@ -165,9 +165,9 @@ package auth
import (
"context"
"crypto/subtle"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net"
@@ -183,6 +183,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool"
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
"repos.gfranz.ch/Gabriel20xx/shared/backend/authproxy"
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
)
// ProxyUser is this service's own /auth/... response shape - UNCHANGED from
@@ -223,7 +224,7 @@ var (
// message rather than a generic "internal error" that would be
// 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.")
errSecretNotUsable = fmt.Errorf("SECRET environment variable is unset, shorter than %d characters, or an example placeholder.", coreconfig.MinInternalSecretLength)
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")
@@ -286,6 +287,10 @@ type Service struct {
// real base URL.
authGuard *authclient.Client
configurationError error
// reauthenticateEmailChanges is opt-in because older consumers historically
// allowed email-only edits without the current password. Password changes
// always require current credentials in UpdateMe.
reauthenticateEmailChanges bool
loginCacheMu sync.Mutex
loginCacheValue bool
loginCacheSet bool
@@ -305,9 +310,10 @@ type Service struct {
type ServiceOption func(*serviceOptions)
type serviceOptions struct {
disabled bool
requireSecret bool
trustedProxies []*net.IPNet
disabled bool
requireSecret bool
reauthenticateEmailChanges bool
trustedProxies []*net.IPNet
}
// Disabled explicitly builds a Service in auth-disabled mode (see the
@@ -329,6 +335,14 @@ func RequireSecret() ServiceOption {
return func(o *serviceOptions) { o.requireSecret = true }
}
// ReauthenticateEmailChanges requires current-password proof, and TOTP when
// enabled, for email changes through UpdateMe. Password changes already
// require the same proof. This is opt-in to preserve existing consumers that
// have not adopted the matching profile-dialog flow.
func ReauthenticateEmailChanges() ServiceOption {
return func(o *serviceOptions) { o.reauthenticateEmailChanges = 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
@@ -379,8 +393,8 @@ func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authG
client = authclient.New(strings.TrimSpace(authGuardURL), authclient.WithProjectKey(projectKey))
}
var configurationError error
if options.requireSecret && !options.disabled && strings.TrimSpace(os.Getenv("SECRET")) == "" {
configurationError = errSecretNotSet
if options.requireSecret && !options.disabled && !coreconfig.InternalSecretUsable(strings.TrimSpace(os.Getenv("SECRET"))) {
configurationError = errSecretNotUsable
}
return &Service{
store: store,
@@ -388,6 +402,7 @@ func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authG
secureCookies: secureCookies,
authGuard: client,
configurationError: configurationError,
reauthenticateEmailChanges: options.reauthenticateEmailChanges,
loginAccountAttempts: newAttemptLimiter(attemptWindow, loginAccountLimit),
loginClientAttempts: newAttemptLimiter(attemptWindow, loginClientLimit),
totpAttempts: newAttemptLimiter(attemptWindow, totpAttemptLimit),
@@ -694,9 +709,11 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
}
var input struct {
Email string `json:"email"`
Username string `json:"username"`
Password string `json:"password"`
Email string `json:"email"`
Username string `json:"username"`
Password string `json:"password"`
CurrentPassword string `json:"currentPassword"`
TOTPToken string `json:"totpToken"`
}
if err := decodeProxyJSON(r, &input); err != nil {
writeProxyError(w, http.StatusBadRequest, "invalid JSON body")
@@ -719,7 +736,29 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
writeProxyError(w, http.StatusBadRequest, err.Error())
return
}
managedInput.Password = input.Password
}
if input.Password != "" || (s.reauthenticateEmailChanges && email != current.Email) {
if input.CurrentPassword == "" {
writeProxyError(w, http.StatusBadRequest, "currentPassword is required to change email or password")
return
}
if current.MFAEnabled && strings.TrimSpace(input.TOTPToken) == "" {
writeProxyError(w, http.StatusBadRequest, "totpToken is required to change email or password")
return
}
reauthenticated, err := s.authGuard.Login(r.Context(), current.Username, input.CurrentPassword, input.TOTPToken)
if err != nil {
writeAuthGuardError(w, err, "current credentials could not be verified")
return
}
if token := temporarySessionToken(reauthenticated); token != "" {
defer func() {
_, _ = s.authGuard.Logout(context.WithoutCancel(r.Context()), token)
}()
}
if input.Password != "" {
managedInput.Password = input.Password
}
}
token := s.sessionToken(r)
@@ -736,6 +775,18 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
writeProxyJSON(w, http.StatusOK, map[string]any{"user": updated})
}
func temporarySessionToken(session *authclient.SessionResult) string {
if session == nil {
return ""
}
for _, cookie := range session.Cookies {
if cookie != nil && cookie.Name == authclient.DefaultCookieName {
return cookie.Value
}
}
return ""
}
// AdminNeeded answers GET /auth/bootstrap/admin-needed. See the package doc
// comment's "Setup flow" section.
func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) {
@@ -856,7 +907,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) == "" || subtle.ConstantTimeCompare([]byte(r.Header.Get("X-Internal-Auth")), []byte(secret)) != 1 {
if !coreconfig.InternalSecretMatches(r.Header.Get("X-Internal-Auth"), secret) {
writeProxyError(w, http.StatusUnauthorized, "internal service authentication required")
return
}