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

+26 -5
View File
@@ -21,6 +21,8 @@ type authContract struct {
Hashes []struct {
Name string `json:"name"`
Hash string `json:"hash"`
Password string `json:"password"`
WrongPassword string `json:"wrongPassword"`
Verifies map[string]bool `json:"verifies"`
NeedsUpgrade map[string]bool `json:"needsUpgrade"`
} `json:"hashes"`
@@ -36,6 +38,7 @@ type authContract struct {
Unix int64 `json:"unix"`
Code string `json:"code"`
Secret *string `json:"secret"`
MatchedStep *int64 `json:"matchedStep"`
Valid bool `json:"valid"`
} `json:"cases"`
} `json:"totp"`
@@ -71,21 +74,29 @@ func TestContractPasswordHashes(t *testing.T) {
contract := loadContract(t)
for _, entry := range contract.Password.Hashes {
t.Run(entry.Name, func(t *testing.T) {
if got := VerifyPassword(entry.Hash, contract.Password.Plaintext); got != entry.Verifies["go"] {
password := entry.Password
if password == "" {
password = contract.Password.Plaintext
}
wrongPassword := entry.WrongPassword
if wrongPassword == "" {
wrongPassword = contract.Password.WrongPassword
}
if got := VerifyPassword(entry.Hash, password); got != entry.Verifies["go"] {
t.Errorf("VerifyPassword = %v, want %v", got, entry.Verifies["go"])
}
if VerifyPassword(entry.Hash, contract.Password.WrongPassword) {
if VerifyPassword(entry.Hash, wrongPassword) {
t.Error("VerifyPassword accepted the wrong password")
}
if want, ok := entry.NeedsUpgrade["go"]; ok {
if got := PasswordHashNeedsUpgrade(entry.Hash); got != want {
t.Errorf("PasswordHashNeedsUpgrade = %v, want %v", got, want)
}
valid, upgraded, err := VerifyAndUpgradePassword(entry.Hash, contract.Password.Plaintext)
valid, upgraded, err := VerifyAndUpgradePassword(entry.Hash, password)
if err != nil || !valid || (upgraded != "") != want {
t.Errorf("VerifyAndUpgradePassword = %v, upgraded %v, %v; want valid with an upgrade = %v", valid, upgraded != "", err, want)
}
if upgraded != "" && (!strings.HasPrefix(upgraded, bcryptScheme) || !VerifyPassword(upgraded, contract.Password.Plaintext)) {
if upgraded != "" && (!strings.HasPrefix(upgraded, bcryptScheme) && !strings.HasPrefix(upgraded, bcryptSHA256Scheme) || !VerifyPassword(upgraded, password)) {
t.Errorf("the upgraded hash %q is not a verifiable current-scheme hash", upgraded)
}
}
@@ -109,9 +120,19 @@ func TestContractTOTP(t *testing.T) {
if entry.Secret != nil {
secret = *entry.Secret
}
if got := VerifyTOTP(secret, entry.Code, time.Unix(entry.Unix, 0)); got != entry.Valid {
step, got := VerifyTOTP(secret, entry.Code, time.Unix(entry.Unix, 0))
if got != entry.Valid {
t.Errorf("VerifyTOTP = %v, want %v", got, entry.Valid)
}
if got {
want := entry.Unix / 30
if entry.MatchedStep != nil {
want = *entry.MatchedStep
}
if step != want {
t.Errorf("VerifyTOTP matched step %d, want %d", step, want)
}
}
})
}
}
+75 -3
View File
@@ -1,9 +1,15 @@
package auth
import (
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"errors"
"strconv"
"strings"
"golang.org/x/crypto/bcrypt"
"golang.org/x/crypto/pbkdf2"
)
// BcryptCost is kept in one place so all services use the same password
@@ -17,9 +23,19 @@ const BcryptCost = 12
// with "$"). Unprefixed bcrypt hashes from before the prefix still verify and
// are upgraded on login.
const bcryptScheme = "bcrypt$"
const bcryptSHA256Scheme = "bcrypt-sha256$"
const (
maxPasswordBytes = 72
legacyPBKDF2Iterations = 100000
maxPBKDF2Iterations = 10000000
)
// HashPassword returns a versioned password hash suitable for storage.
func HashPassword(password string) (string, error) {
if len([]byte(password)) > maxPasswordBytes {
return "", errors.New("password must be at most 72 bytes")
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), BcryptCost)
if err != nil {
return "", err
@@ -27,20 +43,38 @@ func HashPassword(password string) (string, error) {
return bcryptScheme + string(hash), nil
}
// VerifyPassword checks a plaintext password against a stored hash. It accepts
// hashes from HashPassword and unprefixed bcrypt hashes; any other format
// fails closed.
// VerifyPassword checks a plaintext password against bcrypt and legacy Node
// PBKDF2 hashes. A valid legacy hash is rewritten by VerifyAndUpgradePassword.
func VerifyPassword(hash, password string) bool {
if bcryptHash, ok := strings.CutPrefix(hash, bcryptSHA256Scheme); ok {
digest := sha256.Sum256([]byte(password))
return bcrypt.CompareHashAndPassword([]byte(bcryptHash), []byte(hex.EncodeToString(digest[:]))) == nil
}
if iterations, salt, expected, ok := parsePBKDF2Hash(hash); ok {
actual := pbkdf2.Key([]byte(password), []byte(salt), iterations, 32, sha256.New)
expectedBytes, err := hex.DecodeString(expected)
return err == nil && subtle.ConstantTimeCompare(expectedBytes, actual) == 1
}
bcryptHash, ok := bcryptHashOf(hash)
if !ok {
return false
}
if len([]byte(password)) > maxPasswordBytes {
return false
}
return bcrypt.CompareHashAndPassword([]byte(bcryptHash), []byte(password)) == nil
}
// PasswordHashNeedsUpgrade reports whether a stored hash is not in the current
// scheme: an unprefixed legacy hash, or a bcrypt cost below BcryptCost.
func PasswordHashNeedsUpgrade(hash string) bool {
if bcryptHash, prefixed := strings.CutPrefix(hash, bcryptSHA256Scheme); prefixed {
cost, err := bcrypt.Cost([]byte(bcryptHash))
return err != nil || cost < BcryptCost
}
if _, _, _, ok := parsePBKDF2Hash(hash); ok {
return true
}
bcryptHash, prefixed := strings.CutPrefix(hash, bcryptScheme)
if !prefixed {
return true
@@ -61,6 +95,15 @@ func VerifyAndUpgradePassword(hash, password string) (valid bool, upgraded strin
if !PasswordHashNeedsUpgrade(hash) {
return true, "", nil
}
if len([]byte(password)) > maxPasswordBytes {
digest := sha256.Sum256([]byte(password))
var hashBytes []byte
hashBytes, err = bcrypt.GenerateFromPassword([]byte(hex.EncodeToString(digest[:])), BcryptCost)
if err == nil {
upgraded = bcryptSHA256Scheme + string(hashBytes)
}
return true, upgraded, err
}
upgraded, err = HashPassword(password)
if err != nil {
return true, "", err
@@ -78,3 +121,32 @@ func bcryptHashOf(stored string) (string, bool) {
}
return "", false
}
func parsePBKDF2Hash(stored string) (iterations int, salt, expected string, ok bool) {
if strings.HasPrefix(stored, "pbkdf2-sha256$") {
parts := strings.Split(stored, "$")
if len(parts) != 4 {
return 0, "", "", false
}
parsedIterations, err := strconv.Atoi(parts[1])
if err != nil {
return 0, "", "", false
}
iterations, salt, expected = parsedIterations, parts[2], parts[3]
} else if strings.Count(stored, ":") == 1 {
parts := strings.SplitN(stored, ":", 2)
iterations, salt, expected = legacyPBKDF2Iterations, parts[0], parts[1]
} else {
return 0, "", "", false
}
if iterations < 1 || iterations > maxPBKDF2Iterations || len(salt) != 32 || len(expected) != 64 {
return 0, "", "", false
}
if _, err := hex.DecodeString(salt); err != nil {
return 0, "", "", false
}
if _, err := hex.DecodeString(expected); err != nil {
return 0, "", "", false
}
return iterations, salt, expected, true
}
+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
}
+32 -1
View File
@@ -406,6 +406,12 @@ func TestTOTPInitiateAndStatus(t *testing.T) {
func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.handle("POST /api/login", func(w http.ResponseWriter, _ map[string]any) {
w.Header().Add("Set-Cookie", authclient.DefaultCookieName+"=reauth-token; Path=/; HttpOnly")
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"user": map[string]any{"id": 7, "username": "boss", "email": "boss@example.com", "role": "admin"}})
})
guard.reply("POST /api/logout", http.StatusOK, map[string]any{"ok": true})
guard.reply("PUT /api/admin/users/7", http.StatusOK, map[string]any{})
guard.reply("GET /api/me", http.StatusOK, map[string]any{"user": map[string]any{"id": 7, "username": "boss", "email": "boss@example.com", "role": "admin"}})
service, _ := guard.service(t)
@@ -418,7 +424,7 @@ func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
service.UpdateMe(rec, req)
return rec
}
manager := &ProxyUser{ID: 7, Role: "admin"}
manager := &ProxyUser{ID: 7, Username: "boss", Role: "admin", MFAEnabled: true}
if rec := update(nil, `{}`); rec.Code != http.StatusUnauthorized {
t.Fatalf("no session user: status = %d, want 401", rec.Code)
@@ -431,6 +437,8 @@ func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
"at in username": `{"email":"a@b.com","username":"a@b.com"}`,
"short password": `{"email":"a@b.com","username":"boss","password":"short"}`,
"long password": `{"email":"a@b.com","username":"boss","password":"` + strings.Repeat("a", 73) + `"}`,
"missing current password": `{"email":"a@b.com","username":"boss","password":"new-password"}`,
"missing current totp": `{"email":"a@b.com","username":"boss","password":"new-password","currentPassword":"current-password"}`,
"not JSON": `nope`,
} {
if rec := update(manager, body); rec.Code != http.StatusBadRequest {
@@ -452,6 +460,29 @@ func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
if _, sent := calls[0].Body["password"]; sent {
t.Fatal("an update without a password sent one to AuthGuard")
}
rec = update(manager, `{"email":"boss@example.com","username":"boss","password":"new-password","currentPassword":"current-password","totpToken":"123456"}`)
if rec.Code != http.StatusOK {
t.Fatalf("password update status = %d, body %s", rec.Code, rec.Body.String())
}
loginCalls := guard.callsTo("POST /api/login")
if len(loginCalls) != 1 || loginCalls[0].Body["username_or_email"] != "boss" || loginCalls[0].Body["password"] != "current-password" || loginCalls[0].Body["totp_token"] != "123456" {
t.Fatalf("reauthentication request = %+v", loginCalls)
}
calls = guard.callsTo("PUT /api/admin/users/7")
if len(calls) != 2 || calls[1].Body["password"] != "new-password" {
t.Fatalf("password update request = %+v", calls)
}
if _, sent := calls[1].Body["currentPassword"]; sent {
t.Fatal("current password was forwarded to the managed-user API")
}
if _, sent := calls[1].Body["totpToken"]; sent {
t.Fatal("TOTP code was forwarded to the managed-user API")
}
logoutCalls := guard.callsTo("POST /api/logout")
if len(logoutCalls) != 1 || logoutCalls[0].Authorization != "Bearer reauth-token" {
t.Fatalf("temporary login session was not removed: %+v", logoutCalls)
}
if user := decodeBody(t, rec)["user"].(map[string]any); user["username"] != "boss" {
t.Fatalf("response user = %v", user)
}
+53 -11
View File
@@ -87,6 +87,7 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
role TEXT NOT NULL DEFAULT 'user',
totp_secret TEXT NOT NULL DEFAULT '',
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
last_used_step BIGINT NOT NULL DEFAULT -1,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
last_login_at TIMESTAMPTZ
@@ -95,6 +96,7 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1;
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
-- last_login_at is nullable (NULL means "never logged in" - registration
@@ -220,8 +222,9 @@ func ensureUsernameCaseIndex(ctx context.Context, pool *pgxpool.Pool) error {
// TOTPState is the private provisioning state for one account. Secret must
// never be included in an API response.
type TOTPState struct {
Secret string
Enabled bool
Secret string
Enabled bool
LastUsedStep int64
}
// GetTOTPState reads the stored TOTP provisioning state for an account.
@@ -230,7 +233,7 @@ func (s *Store) GetTOTPState(ctx context.Context, userID int64) (TOTPState, erro
return TOTPState{}, err
}
var state TOTPState
err := s.pool.QueryRow(ctx, `SELECT COALESCE(totp_secret, ''), COALESCE(totp_enabled, false) FROM auth_users WHERE id = $1`, userID).Scan(&state.Secret, &state.Enabled)
err := s.pool.QueryRow(ctx, `SELECT COALESCE(totp_secret, ''), COALESCE(totp_enabled, false), COALESCE(last_used_step, -1) FROM auth_users WHERE id = $1`, userID).Scan(&state.Secret, &state.Enabled, &state.LastUsedStep)
if errors.Is(err, pgx.ErrNoRows) {
return TOTPState{}, nil
}
@@ -246,7 +249,7 @@ func (s *Store) SetTOTPSecret(ctx context.Context, userID int64, secret string)
if err := s.validate(); err != nil {
return err
}
tag, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2 AND NOT totp_enabled`, secret, userID)
tag, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $2 AND NOT totp_enabled`, secret, userID)
if err != nil {
return fmt.Errorf("set TOTP secret: %w", err)
}
@@ -262,16 +265,39 @@ func (s *Store) SetTOTPSecret(ctx context.Context, userID int64, secret string)
return nil
}
// EnableTOTP marks a previously provisioned secret as active.
func (s *Store) EnableTOTP(ctx context.Context, userID int64) error {
// EnableTOTP marks a previously provisioned secret as active and records the
// step used to confirm it, preventing that code from being reused at login.
func (s *Store) EnableTOTP(ctx context.Context, userID int64, secret string, step int64) (bool, error) {
if err := s.validate(); err != nil {
return err
return false, err
}
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''`, userID)
tag, err := s.pool.Exec(ctx, `
UPDATE auth_users
SET totp_enabled = true, last_used_step = $1, updated_at = now()
WHERE id = $2 AND totp_secret = $3 AND NOT totp_enabled AND last_used_step < $1
`, step, userID, secret)
if err != nil {
return fmt.Errorf("enable TOTP: %w", err)
return false, fmt.Errorf("enable TOTP: %w", err)
}
return nil
return tag.RowsAffected() == 1, nil
}
// ConsumeTOTPStep advances an account's accepted TOTP step only once. The
// expected secret and enabled flag are part of the update so a concurrent
// disable or re-enrollment cannot consume a code against stale state.
func (s *Store) ConsumeTOTPStep(ctx context.Context, userID int64, secret string, step int64) (bool, error) {
if err := s.validate(); err != nil {
return false, err
}
tag, err := s.pool.Exec(ctx, `
UPDATE auth_users
SET last_used_step = $1, updated_at = now()
WHERE id = $2 AND totp_enabled AND totp_secret = $3 AND last_used_step < $1
`, step, userID, secret)
if err != nil {
return false, fmt.Errorf("consume TOTP step: %w", err)
}
return tag.RowsAffected() == 1, nil
}
// DisableTOTP clears both the active and pending TOTP secret.
@@ -279,7 +305,7 @@ func (s *Store) DisableTOTP(ctx context.Context, userID int64) error {
if err := s.validate(); err != nil {
return err
}
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1`, userID)
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = '', totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $1`, userID)
if err != nil {
return fmt.Errorf("disable TOTP: %w", err)
}
@@ -382,6 +408,22 @@ func (s *Store) UpdateCredentials(ctx context.Context, id int64, username, email
return nil
}
// UpgradePasswordHash replaces an old verifier only if it is still current,
// so a concurrent password change cannot be overwritten by a login rehash.
func (s *Store) UpgradePasswordHash(ctx context.Context, id int64, oldHash, newHash string) (bool, error) {
if err := s.validate(); err != nil {
return false, err
}
tag, err := s.pool.Exec(ctx, `
UPDATE auth_users SET password_hash = $1, updated_at = now()
WHERE id = $2 AND password_hash = $3
`, newHash, id, oldHash)
if err != nil {
return false, fmt.Errorf("upgrade password hash: %w", err)
}
return tag.RowsAffected() == 1, nil
}
// ListUsers returns the non-secret account fields used by the shared user
// management screen.
func (s *Store) ListUsers(ctx context.Context) ([]User, error) {
@@ -230,8 +230,8 @@ func TestStoreTOTPAndIdentifierPrimitives(t *testing.T) {
if err := store.SetTOTPSecret(ctx, owner.ID, "JBSWY3DPEHPK3PXP"); err != nil {
t.Fatalf("SetTOTPSecret() while disabled error = %v", err)
}
if err := store.EnableTOTP(ctx, owner.ID); err != nil {
t.Fatal(err)
if enabled, err := store.EnableTOTP(ctx, owner.ID, "JBSWY3DPEHPK3PXP", 123); err != nil || !enabled {
t.Fatalf("EnableTOTP() = %v, %v; want enabled", enabled, err)
}
if err := store.SetTOTPSecret(ctx, owner.ID, "OTHERSECRET"); !errors.Is(err, ErrTOTPAlreadyEnabled) {
t.Fatalf("SetTOTPSecret() while enabled error = %v, want ErrTOTPAlreadyEnabled", err)
+10 -7
View File
@@ -52,19 +52,22 @@ func TOTPProvisioningURI(issuer, account, secret string) string {
return "otpauth://totp/" + url.PathEscape(label) + "?" + query.Encode()
}
// VerifyTOTP checks a six-digit token with a one-period clock-skew window.
func VerifyTOTP(secret, token string, now time.Time) bool {
// VerifyTOTP checks a six-digit token with a one-period clock-skew window and
// returns the matching time step. A caller must atomically record that step
// before accepting the code so it cannot be used twice.
func VerifyTOTP(secret, token string, now time.Time) (int64, bool) {
secret = normalizeTOTPSecret(secret)
token = normalizeTOTPToken(token)
if secret == "" || len(token) != TOTPDigits {
return false
return -1, false
}
key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(secret)
if err != nil || len(key) == 0 {
return false
return -1, false
}
period := now.Unix() / int64(TOTPPeriod/time.Second)
for offset := int64(-TOTPWindow); offset <= TOTPWindow; offset++ {
// Prefer the current step if a six-digit collision occurs in the window.
for _, offset := range [...]int64{0, -1, 1} {
if period+offset < 0 {
continue
}
@@ -80,10 +83,10 @@ func VerifyTOTP(secret, token string, now time.Time) bool {
uint32(digest[index+3])
candidate := fmt.Sprintf("%06d", value%1000000)
if subtle.ConstantTimeCompare([]byte(candidate), []byte(token)) == 1 {
return true
return period + offset, true
}
}
return false
return -1, false
}
func normalizeTOTPSecret(value string) string {
+4 -1
View File
@@ -18,8 +18,11 @@ func TestVerifyTOTPRFC6238SHA1Vectors(t *testing.T) {
{unix: 2000000000, code: "279037"},
}
for _, testCase := range cases {
if !VerifyTOTP(secret, testCase.code, time.Unix(testCase.unix, 0)) {
step, valid := VerifyTOTP(secret, testCase.code, time.Unix(testCase.unix, 0))
if !valid {
t.Errorf("VerifyTOTP(%d, %q) = false", testCase.unix, testCase.code)
} else if want := testCase.unix / int64(TOTPPeriod/time.Second); step != want {
t.Errorf("VerifyTOTP(%d, %q) matched step %d, want %d", testCase.unix, testCase.code, step, want)
}
}
}
+20
View File
@@ -71,6 +71,7 @@ type Client struct {
projectKey string
validationMu sync.Mutex
validationCache map[[32]byte]validationCacheEntry
profileCache map[[32]byte]profileCacheEntry
}
// ProjectKeyHeader is the header Client attaches to every request identifying
@@ -118,6 +119,7 @@ func New(baseURL string, opts ...Option) *Client {
httpClient: &http.Client{Timeout: 5 * time.Second},
cookieName: DefaultCookieName,
validationCache: make(map[[32]byte]validationCacheEntry),
profileCache: make(map[[32]byte]profileCacheEntry),
}
for _, opt := range opts {
opt(c)
@@ -583,12 +585,24 @@ func (c *Client) Logout(ctx context.Context, token string) ([]*http.Cookie, erro
// Me calls GET /api/me, resolving token to its account.
func (c *Client) Me(ctx context.Context, token string) (*PublicUser, error) {
token = strings.TrimSpace(token)
if token == "" {
return nil, ErrInvalidSession
}
if profile, ok := c.cachedProfile(token); ok {
return profile, nil
}
var out struct {
User PublicUser `json:"user"`
}
if _, err := c.call(ctx, http.MethodGet, "/api/me", token, nil, &out); err != nil {
var apiErr *APIError
if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusUnauthorized {
c.invalidateValidation(token)
}
return nil, err
}
c.cacheProfile(token, &out.User)
return &out.User, nil
}
@@ -607,6 +621,9 @@ func (c *Client) TOTPEnable(ctx context.Context, token string) (*TOTPEnableResul
// pending secret TOTPEnable provisioned and activating two-factor auth.
func (c *Client) TOTPVerify(ctx context.Context, token, code string) error {
_, err := c.call(ctx, http.MethodPost, "/api/totp/verify", token, map[string]string{"token": code}, nil)
if err == nil {
c.invalidateValidation(token)
}
return err
}
@@ -615,6 +632,9 @@ func (c *Client) TOTPVerify(ctx context.Context, token, code string) error {
// as proof of possession.
func (c *Client) TOTPDisable(ctx context.Context, token, code string) error {
_, err := c.call(ctx, http.MethodPost, "/api/totp/disable", token, map[string]string{"token": code}, nil)
if err == nil {
c.invalidateValidation(token)
}
return err
}
@@ -10,12 +10,20 @@ const (
maxValidationCacheSize = 10000
)
// A session revoked directly in AuthGuard may remain accepted by this client
// for up to two seconds. Logout through this Client clears the cached result.
type validationCacheEntry struct {
user User
valid bool
expires time.Time
}
type profileCacheEntry struct {
profile PublicUser
expires time.Time
}
func (c *Client) cachedValidation(token string) (*User, error, bool) {
key := sha256.Sum256([]byte(token))
now := time.Now()
@@ -64,15 +72,61 @@ func (c *Client) cacheValidation(token string, user *User, valid bool) {
c.validationCache[key] = entry
}
func (c *Client) cachedProfile(token string) (*PublicUser, bool) {
key := sha256.Sum256([]byte(token))
now := time.Now()
c.validationMu.Lock()
defer c.validationMu.Unlock()
entry, ok := c.profileCache[key]
if !ok {
return nil, false
}
if !now.Before(entry.expires) {
delete(c.profileCache, key)
return nil, false
}
profile := entry.profile
return &profile, true
}
func (c *Client) cacheProfile(token string, profile *PublicUser) {
if profile == nil {
return
}
key := sha256.Sum256([]byte(token))
now := time.Now()
c.validationMu.Lock()
defer c.validationMu.Unlock()
if c.profileCache == nil {
c.profileCache = make(map[[32]byte]profileCacheEntry)
}
if len(c.profileCache) >= maxValidationCacheSize {
for existing, entry := range c.profileCache {
if !now.Before(entry.expires) {
delete(c.profileCache, existing)
}
}
if len(c.profileCache) >= maxValidationCacheSize {
for existing := range c.profileCache {
delete(c.profileCache, existing)
break
}
}
}
c.profileCache[key] = profileCacheEntry{profile: *profile, expires: now.Add(validationCacheTTL)}
}
func (c *Client) invalidateValidation(token string) {
key := sha256.Sum256([]byte(token))
c.validationMu.Lock()
delete(c.validationCache, key)
delete(c.profileCache, key)
c.validationMu.Unlock()
}
func (c *Client) clearValidationCache() {
c.validationMu.Lock()
c.validationCache = make(map[[32]byte]validationCacheEntry)
c.profileCache = make(map[[32]byte]profileCacheEntry)
c.validationMu.Unlock()
}
@@ -22,12 +22,25 @@ import (
"os"
"strconv"
"strings"
"sync"
"time"
)
// httpClient has no blanket timeout since it streams large media files;
// callers bound individual calls with a context deadline instead.
var httpClient = &http.Client{}
// httpClient has no total timeout since it streams large media files. The
// transport still bounds how long a request may wait for response headers;
// callers that need a shorter bound add a context deadline as well.
var httpClient = newHTTPClient()
func newHTTPClient() *http.Client {
var transport *http.Transport
if defaultTransport, ok := http.DefaultTransport.(*http.Transport); ok {
transport = defaultTransport.Clone()
} else {
transport = &http.Transport{Proxy: http.ProxyFromEnvironment}
}
transport.ResponseHeaderTimeout = 10 * time.Second
return &http.Client{Transport: transport}
}
var forwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"}
var forwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"}
@@ -69,6 +82,17 @@ type Client struct {
// multiple candidates are actually used (union for discovery, first-match
// for reads, primary-only for writes).
BaseURLs func(ctx context.Context) []string
thumbnailMu sync.Mutex
thumbnailPaths map[string]thumbnailPathEntry
}
const thumbnailPathCacheTTL = 5 * time.Minute
const thumbnailPathCacheLimit = 2048
type thumbnailPathEntry struct {
path string
expires time.Time
}
// New returns a Client backed by a single CarrierNode instance. baseURL is
@@ -536,15 +560,103 @@ func (c *Client) ProxyThumbnail(w http.ResponseWriter, r *http.Request, project,
if err != nil {
return false
}
cacheKey := project + "\x00" + id
cachedPath := c.cachedThumbnailPath(cacheKey)
if cachedPath != "" {
ordered := make([]string, 0, len(paths))
ordered = append(ordered, cachedPath)
for _, path := range paths {
if path != cachedPath {
ordered = append(ordered, path)
}
}
paths = ordered
}
for _, path := range paths {
if exists, _, _, probeErr := c.Probe(r.Context(), path); probeErr == nil && exists {
c.Proxy(w, r, path)
for _, baseURL := range c.candidateBaseURLs(r.Context()) {
request, err := c.newRequest(r.Context(), baseURL, r.Method, path, nil)
if err != nil {
continue
}
for _, header := range forwardRequestHeaders {
if value := r.Header.Get(header); value != "" {
request.Header.Set(header, value)
}
}
response, err := httpClient.Do(request)
if err != nil {
continue
}
if response.StatusCode >= http.StatusBadRequest {
response.Body.Close()
if path == cachedPath {
c.forgetThumbnailPath(cacheKey)
}
continue
}
for _, header := range forwardResponseHeaders {
if value := response.Header.Get(header); value != "" {
w.Header().Set(header, value)
}
}
w.WriteHeader(response.StatusCode)
if r.Method != http.MethodHead {
_, _ = io.Copy(w, response.Body)
}
response.Body.Close()
c.rememberThumbnailPath(cacheKey, path)
return true
}
}
return false
}
func (c *Client) cachedThumbnailPath(key string) string {
c.thumbnailMu.Lock()
defer c.thumbnailMu.Unlock()
entry, ok := c.thumbnailPaths[key]
if !ok {
return ""
}
if !time.Now().Before(entry.expires) {
delete(c.thumbnailPaths, key)
return ""
}
return entry.path
}
func (c *Client) rememberThumbnailPath(key, path string) {
c.thumbnailMu.Lock()
defer c.thumbnailMu.Unlock()
if c.thumbnailPaths == nil {
c.thumbnailPaths = make(map[string]thumbnailPathEntry)
}
now := time.Now()
for cacheKey, entry := range c.thumbnailPaths {
if !now.Before(entry.expires) {
delete(c.thumbnailPaths, cacheKey)
}
}
if len(c.thumbnailPaths) >= thumbnailPathCacheLimit {
var oldestKey string
var oldest time.Time
first := true
for cacheKey, entry := range c.thumbnailPaths {
if first || entry.expires.Before(oldest) {
oldestKey, oldest, first = cacheKey, entry.expires, false
}
}
delete(c.thumbnailPaths, oldestKey)
}
c.thumbnailPaths[key] = thumbnailPathEntry{path: path, expires: now.Add(thumbnailPathCacheTTL)}
}
func (c *Client) forgetThumbnailPath(key string) {
c.thumbnailMu.Lock()
delete(c.thumbnailPaths, key)
c.thumbnailMu.Unlock()
}
// FetchThumbnailToScratch downloads a stored thumbnail into an ephemeral local file, looking
// in the project's thumbnails mount and then the legacy root. Callers must invoke the returned
// cleanup once done.
@@ -1,265 +1,21 @@
package carriernodeclient
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestListFilesMergesAcrossInstances(t *testing.T) {
first := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"files":[{"rel":"a.mp4"}]}`))
}))
defer first.Close()
second := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"files":[{"rel":"b.mp4"}]}`))
}))
defer second.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{first.URL, second.URL} })
files, err := client.ListFiles(context.Background(), "", false, 0)
if err != nil {
t.Fatalf("ListFiles error: %v", err)
func TestHTTPClientBoundsResponseHeaderWaitWithoutLimitingStreams(t *testing.T) {
client := newHTTPClient()
if client.Timeout != 0 {
t.Fatalf("client total timeout = %s, want no total timeout for media streams", client.Timeout)
}
if len(files) != 2 {
t.Fatalf("ListFiles returned %d files, want 2: %+v", len(files), files)
transport, ok := client.Transport.(*http.Transport)
if !ok {
t.Fatalf("transport type = %T, want *http.Transport", client.Transport)
}
}
func TestRequestsCarryProjectAttribution(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("X-Internal-Auth"); got != "secret" {
t.Fatalf("X-Internal-Auth = %q, want secret", got)
}
if got := r.Header.Get("X-Project-Key"); got != "ContentScanner" {
t.Fatalf("X-Project-Key = %q, want ContentScanner", got)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"files":[]}`))
}))
defer server.Close()
client := New("secret", func(ctx context.Context) string { return server.URL })
client.ProjectKey = "ContentScanner"
if _, err := client.ListFiles(context.Background(), "", false, 0); err != nil {
t.Fatalf("ListFiles error: %v", err)
}
}
func TestListFilesSkipsUnreachableInstance(t *testing.T) {
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"files":[{"rel":"a.mp4"}]}`))
}))
defer up.Close()
down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
down.Close() // closed immediately so requests to it fail outright
client := NewMulti("", func(ctx context.Context) []string { return []string{down.URL, up.URL} })
files, err := client.ListFiles(context.Background(), "", false, 0)
if err != nil {
t.Fatalf("ListFiles error: %v", err)
}
if len(files) != 1 || files[0].Rel != "a.mp4" {
t.Fatalf("ListFiles = %+v, want just the reachable instance's file", files)
}
}
func TestListFilesErrorsWhenNoInstanceReachable(t *testing.T) {
down := httptest.NewServer(nil)
down.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{down.URL} })
if _, err := client.ListFiles(context.Background(), "", false, 0); err == nil {
t.Fatal("ListFiles error = nil, want an error when every instance is unreachable")
}
}
func TestProbeFallsBackToNextInstance(t *testing.T) {
notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer notFound.Close()
found := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Length", "42")
w.WriteHeader(http.StatusOK)
}))
defer found.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, found.URL} })
exists, size, _, err := client.Probe(context.Background(), "/media/a.mp4")
if err != nil {
t.Fatalf("Probe error: %v", err)
}
if !exists {
t.Fatal("Probe exists = false, want true (second instance has it)")
}
if size != 42 {
t.Fatalf("Probe size = %d, want 42", size)
}
}
func TestProbeExistsFalseWhenNoInstanceHasFile(t *testing.T) {
notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer notFound.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, notFound.URL} })
exists, _, _, err := client.Probe(context.Background(), "/media/missing.mp4")
if err != nil {
t.Fatalf("Probe error: %v", err)
}
if exists {
t.Fatal("Probe exists = true, want false")
}
}
func TestProxyPrefersPrimaryInstanceWhenItHasTheFile(t *testing.T) {
var primaryHit, secondaryHit bool
primary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
primaryHit = true
w.WriteHeader(http.StatusOK)
}))
defer primary.Close()
secondary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
secondaryHit = true
w.WriteHeader(http.StatusOK)
}))
defer secondary.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{primary.URL, secondary.URL} })
req := httptest.NewRequest(http.MethodGet, "/thumbnails/x.jpg", nil)
rec := httptest.NewRecorder()
client.Proxy(rec, req, "/thumbnails/x.jpg")
if !primaryHit {
t.Fatal("Proxy did not hit the primary instance")
}
if secondaryHit {
t.Fatal("Proxy hit the secondary instance even though the primary had the file")
}
}
func TestProxyFallsBackToSecondaryInstanceWhenPrimaryMisses(t *testing.T) {
primary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer primary.Close()
secondary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "video/mp4")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("video bytes"))
}))
defer secondary.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{primary.URL, secondary.URL} })
req := httptest.NewRequest(http.MethodGet, "/media/a.mp4", nil)
rec := httptest.NewRecorder()
client.Proxy(rec, req, "/media/a.mp4")
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 from the secondary instance", rec.Code)
}
if rec.Body.String() != "video bytes" {
t.Fatalf("body = %q, want secondary instance's bytes", rec.Body.String())
}
}
func TestProxyForwardsLastInstanceErrorWhenNoneHaveTheFile(t *testing.T) {
notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer notFound.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, notFound.URL} })
req := httptest.NewRequest(http.MethodGet, "/media/missing.mp4", nil)
rec := httptest.NewRecorder()
client.Proxy(rec, req, "/media/missing.mp4")
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404 forwarded from the last instance", rec.Code)
}
}
func mountListingServer(status int, body string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, _ = w.Write([]byte(body))
}))
}
func TestListMountFilesReportsNotFoundWhenEveryInstanceMisses(t *testing.T) {
first := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
defer first.Close()
second := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
defer second.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{first.URL, second.URL} })
_, err := client.ListMountFiles(context.Background(), "autocode", "repos", "gone")
if !errors.Is(err, ErrMountNotFound) {
t.Fatalf("ListMountFiles error = %v, want ErrMountNotFound", err)
}
}
func TestListMountFilesDoesNotReportNotFoundWhenAnInstanceIsUnreachable(t *testing.T) {
missing := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
defer missing.Close()
down := httptest.NewServer(nil)
down.Close() // closed immediately so requests to it fail outright
client := NewMulti("", func(ctx context.Context) []string { return []string{missing.URL, down.URL} })
_, err := client.ListMountFiles(context.Background(), "autocode", "repos", "maybe-on-the-down-instance")
if err == nil {
t.Fatal("ListMountFiles succeeded, want an error")
}
if errors.Is(err, ErrMountNotFound) {
t.Fatalf("ListMountFiles error = %v, must not claim the directory is missing when an instance could not be checked", err)
}
}
func TestListMountFilesDoesNotReportNotFoundOnServerError(t *testing.T) {
broken := mountListingServer(http.StatusInternalServerError, `{"error":"boom"}`)
defer broken.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{broken.URL} })
_, err := client.ListMountFiles(context.Background(), "autocode", "repos", "")
if err == nil || errors.Is(err, ErrMountNotFound) {
t.Fatalf("ListMountFiles error = %v, want a non-ErrMountNotFound failure", err)
}
}
func TestListMountFilesUsesTheInstanceThatHasTheDirectory(t *testing.T) {
missing := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
defer missing.Close()
present := mountListingServer(http.StatusOK, `{"files":[{"name":"repo","path":"repo","directory":true}]}`)
defer present.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{missing.URL, present.URL} })
files, err := client.ListMountFiles(context.Background(), "autocode", "repos", "")
if err != nil {
t.Fatalf("ListMountFiles error: %v", err)
}
if len(files) != 1 || files[0].Name != "repo" || !files[0].Directory {
t.Fatalf("ListMountFiles = %+v, want the one directory from the instance that has it", files)
if transport.ResponseHeaderTimeout != 10*time.Second {
t.Fatalf("response header timeout = %s, want 10s", transport.ResponseHeaderTimeout)
}
}
@@ -8,7 +8,6 @@ import (
"os"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
)
@@ -94,16 +93,15 @@ func TestProxyThumbnailPrefersProjectMount(t *testing.T) {
if rec.Body.String() != "from mount" {
t.Fatalf("body = %q, want the mount copy", rec.Body.String())
}
for _, request := range node.seen() {
if !strings.Contains(request, "/api/mount/") {
t.Fatalf("legacy root was consulted although the mount had the thumbnail: %v", node.seen())
}
want := []string{"GET " + mount}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want one direct GET to the mount", got)
}
}
func TestProxyThumbnailFallsBackToLegacyRoot(t *testing.T) {
legacy := "/thumbnails/" + testThumbnailID + ".jpg"
client, _ := newThumbnailTestClient(t, map[string]string{legacy: "from legacy"})
client, node := newThumbnailTestClient(t, map[string]string{legacy: "from legacy"})
rec := httptest.NewRecorder()
if !client.ProxyThumbnail(rec, thumbnailRequest(), "ContentScanner", testThumbnailID) {
@@ -112,10 +110,28 @@ func TestProxyThumbnailFallsBackToLegacyRoot(t *testing.T) {
if rec.Body.String() != "from legacy" {
t.Fatalf("body = %q, want the legacy copy", rec.Body.String())
}
want := []string{"GET /api/mount/ContentScanner/thumbnails/" + testThumbnailID + ".jpg", "GET " + legacy}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want mount miss followed by legacy GET", got)
}
}
func TestProxyThumbnailCachesResolvedPath(t *testing.T) {
mount := "/api/mount/MediaViewer/thumbnails/" + testThumbnailID + ".jpg"
client, node := newThumbnailTestClient(t, map[string]string{mount: "from mount"})
for range 2 {
if !client.ProxyThumbnail(httptest.NewRecorder(), thumbnailRequest(), "MediaViewer", testThumbnailID) {
t.Fatal("ProxyThumbnail missed although the mount holds the thumbnail")
}
}
want := []string{"GET " + mount, "GET " + mount}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want one direct GET per request to the cached path", got)
}
}
func TestProxyThumbnailReportsMissingWithoutWriting(t *testing.T) {
client, _ := newThumbnailTestClient(t, nil)
client, node := newThumbnailTestClient(t, nil)
rec := httptest.NewRecorder()
if client.ProxyThumbnail(rec, thumbnailRequest(), "ContentScanner", testThumbnailID) {
@@ -124,6 +140,13 @@ func TestProxyThumbnailReportsMissingWithoutWriting(t *testing.T) {
if rec.Body.Len() != 0 {
t.Fatalf("ProxyThumbnail wrote %q on a miss; the caller needs a clean fallback", rec.Body.String())
}
want := []string{
"GET /api/mount/ContentScanner/thumbnails/" + testThumbnailID + ".jpg",
"GET /thumbnails/" + testThumbnailID + ".jpg",
}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want one GET for each candidate path", got)
}
}
func TestFetchThumbnailToScratchFallsBackToLegacyRoot(t *testing.T) {
@@ -0,0 +1,52 @@
package coreconfig
import (
"encoding/json"
"os"
"testing"
)
// contractFile holds the fixtures the Go, Node and Python internal-secret checks must agree on. The
// Node and Python suites load the same file; see the "description" field in it.
const contractFile = "../../contract/auth-contract.json"
type internalSecretContract struct {
InternalSecret struct {
MinLength int `json:"minLength"`
Placeholders []string `json:"placeholders"`
Cases []struct {
Name string `json:"name"`
Secret string `json:"secret"`
Provided string `json:"provided"`
Matches bool `json:"matches"`
} `json:"cases"`
} `json:"internalSecret"`
}
func TestContractInternalSecret(t *testing.T) {
data, err := os.ReadFile(contractFile)
if os.IsNotExist(err) {
t.Skipf("%s is not part of this checkout", contractFile)
}
if err != nil {
t.Fatal(err)
}
var contract internalSecretContract
if err := json.Unmarshal(data, &contract); err != nil {
t.Fatalf("decode %s: %v", contractFile, err)
}
rule := contract.InternalSecret
if MinInternalSecretLength != rule.MinLength {
t.Fatalf("MinInternalSecretLength = %d, contract says %d", MinInternalSecretLength, rule.MinLength)
}
for _, placeholder := range rule.Placeholders {
if InternalSecretUsable(placeholder) {
t.Errorf("placeholder %q is usable, contract says it never gates a route", placeholder)
}
}
for _, entry := range rule.Cases {
if got := InternalSecretMatches(entry.Provided, entry.Secret); got != entry.Matches {
t.Errorf("%s: InternalSecretMatches = %v, contract says %v", entry.Name, got, entry.Matches)
}
}
}
+30 -3
View File
@@ -18,8 +18,35 @@ import (
"net/url"
"strings"
"sync"
"unicode/utf8"
)
// MinInternalSecretLength is the shortest SECRET a service accepts for its internal routes.
const MinInternalSecretLength = 16
// exampleInternalSecrets are the placeholders shipped in .env.example files, plus the bare variable
// name. They are public, so they never gate a route.
var exampleInternalSecrets = map[string]bool{
"SECRET": true,
"change-me-to-a-long-random-value": true,
}
// InternalSecretUsable reports whether secret is strong enough to gate an internal route: at least
// MinInternalSecretLength characters and not an example placeholder. Length counts characters, as
// the Python and Node helpers do, not bytes.
func InternalSecretUsable(secret string) bool {
return utf8.RuneCountInString(secret) >= MinInternalSecretLength && !exampleInternalSecrets[secret]
}
// InternalSecretMatches reports whether presented is the configured secret. A secret that is not
// usable (see InternalSecretUsable) never matches, and the comparison is constant-time.
func InternalSecretMatches(presented, secret string) bool {
if !InternalSecretUsable(secret) {
return false
}
return subtle.ConstantTimeCompare([]byte(presented), []byte(secret)) == 1
}
// Info is AuthGuard's, CarrierNode's, and ProjectConfigurator's current base URL(s), as pushed by
// ProjectConfigurator.
type Info struct {
@@ -178,11 +205,11 @@ func normalizeInfo(info Info) Info {
// ProjectConfigurator calls to push a fresh Info: mount it at that path (see
// ProjectConfigurator/README.md) behind a secret check for this service's own
// SECRET (the same value ProjectConfigurator and CarrierNode were configured
// with - an empty secret refuses every caller, the same fail-closed default ProjectConfigurator's
// own internal-auth-gated routes use).
// with - a secret that is not usable (see InternalSecretUsable) refuses every caller, the same
// fail-closed default ProjectConfigurator's own internal-auth-gated routes use).
func Handler(secret string, store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if secret == "" || subtle.ConstantTimeCompare([]byte(r.Header.Get("X-Internal-Auth")), []byte(secret)) != 1 {
if !InternalSecretMatches(r.Header.Get("X-Internal-Auth"), secret) {
writeError(w, http.StatusUnauthorized, "internal service authentication required")
return
}
+23 -5
View File
@@ -67,7 +67,7 @@ func TestStoreOnUpdateFiresWithNewInfo(t *testing.T) {
func TestHandlerRejectsMissingOrWrongSecret(t *testing.T) {
store := NewStore(Info{})
handler := Handler("s3cret", store)
handler := Handler("test-internal-secret", store)
body, _ := json.Marshal(Info{AuthGuardURL: "http://auth.example.com"})
cases := []string{"", "wrong"}
@@ -127,14 +127,14 @@ func equalStrings(got, want []string) bool {
func TestHandlerAppliesPushedInfo(t *testing.T) {
store := NewStore(Info{})
handler := Handler("s3cret", store)
handler := Handler("test-internal-secret", store)
body, _ := json.Marshal(Info{
AuthGuardURL: "http://auth.example.com", CarrierNodeURL: "http://carrier.example.com", CarrierNodeSecret: "carrier-secret",
ContentScannerURL: "http://scanner.example.com/", ContentScannerSecret: "scanner-secret",
})
req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body))
req.Header.Set("X-Internal-Auth", "s3cret")
req.Header.Set("X-Internal-Auth", "test-internal-secret")
rec := httptest.NewRecorder()
handler(rec, req)
@@ -152,7 +152,7 @@ func TestHandlerAppliesPushedInfo(t *testing.T) {
func TestHandlerRejectsNonHTTPURLsWithoutChangingStore(t *testing.T) {
store := NewStore(Info{AuthGuardURL: "http://auth.example.com"})
handler := Handler("s3cret", store)
handler := Handler("test-internal-secret", store)
for _, bad := range []Info{
{AuthGuardURL: "javascript:alert(1)"},
{AuthGuardURL: "auth.example.com"},
@@ -161,7 +161,7 @@ func TestHandlerRejectsNonHTTPURLsWithoutChangingStore(t *testing.T) {
} {
body, _ := json.Marshal(bad)
req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body))
req.Header.Set("X-Internal-Auth", "s3cret")
req.Header.Set("X-Internal-Auth", "test-internal-secret")
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -172,3 +172,21 @@ func TestHandlerRejectsNonHTTPURLsWithoutChangingStore(t *testing.T) {
t.Fatalf("store changed by a rejected push: %+v", got)
}
}
func TestHandlerRefusesAnUnusableSecret(t *testing.T) {
for _, secret := range []string{"short", "SECRET", "change-me-to-a-long-random-value"} {
store := NewStore(Info{})
handler := Handler(secret, store)
body, _ := json.Marshal(Info{AuthGuardURL: "http://auth.example.com"})
req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body))
req.Header.Set("X-Internal-Auth", secret)
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("secret %q: status = %d, want %d", secret, rec.Code, http.StatusUnauthorized)
}
if store.Get().AuthGuardURL != "" {
t.Fatalf("secret %q: store changed despite a refused push", secret)
}
}
}
+81 -16
View File
@@ -43,6 +43,7 @@ import (
"time"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
@@ -335,13 +336,25 @@ func (c *Core) mediaView(w http.ResponseWriter, r *http.Request) {
MediaKey string `json:"mediaKey"`
}
if r.Body != nil && r.ContentLength != 0 {
_ = decodeRequestJSON(r, &input)
if err := decodeRequestJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
}
key := strings.TrimSpace(firstNonEmpty(input.MediaKey, r.URL.Query().Get("mediaKey")))
if key == "" {
writeError(w, http.StatusBadRequest, "missing mediaKey")
return
}
exists, err := c.mediaExists(r.Context(), key)
if err != nil {
writeError(w, http.StatusInternalServerError, "media lookup failed")
return
}
if !exists {
writeError(w, http.StatusNotFound, "media not found")
return
}
var userID any
if user != nil {
userID = user.ID
@@ -368,15 +381,25 @@ func (c *Core) mediaViewSession(w http.ResponseWriter, r *http.Request) {
if duration <= 0 {
duration = input.Duration
}
if strings.TrimSpace(input.MediaKey) == "" || duration <= 0 {
writeError(w, http.StatusBadRequest, "mediaKey and positive duration are required")
key := strings.TrimSpace(input.MediaKey)
if key == "" || duration <= 0 || duration > maxViewSessionDurationMs {
writeError(w, http.StatusBadRequest, "mediaKey and duration between 1ms and 24h are required")
return
}
exists, err := c.mediaExists(r.Context(), key)
if err != nil {
writeError(w, http.StatusInternalServerError, "media lookup failed")
return
}
if !exists {
writeError(w, http.StatusNotFound, "media not found")
return
}
var userID any
if user != nil {
userID = user.ID
}
_, err := c.db.Exec(r.Context(), `INSERT INTO media_view_sessions (media_key, user_id, duration_ms) VALUES ($1, $2, $3)`, strings.TrimSpace(input.MediaKey), userID, duration)
_, err = c.db.Exec(r.Context(), `INSERT INTO media_view_sessions (media_key, user_id, duration_ms) VALUES ($1, $2, $3)`, key, userID, duration)
if err != nil {
writeError(w, http.StatusInternalServerError, "view session could not be recorded")
return
@@ -384,6 +407,15 @@ func (c *Core) mediaViewSession(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": map[string]any{"ok": true}})
}
const maxViewSessionDurationMs int64 = 24 * 60 * 60 * 1000
func (c *Core) mediaExists(ctx context.Context, identifier string) (bool, error) {
var exists bool
err := c.db.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM media WHERE media_key=$1 OR id=$2)`,
identifier, mediaIDArg(identifier)).Scan(&exists)
return exists, err
}
func (c *Core) mediaLiked(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context())
rows, err := c.db.Query(r.Context(), `SELECT media_key, created_at FROM media_stats WHERE user_id = $1 AND stat_type = 'like' ORDER BY created_at DESC`, user.ID)
@@ -793,9 +825,18 @@ func (c *Core) isHiddenMedia(ctx context.Context, identifier string) bool {
return err != nil || hidden
}
// findMedia looks up one media item by media key or numeric id. Hidden media is only returned
// when includeHidden is set.
func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden bool) (MediaRecord, error) {
// MediaLookupOptions controls which otherwise-hidden records a media lookup may return.
type MediaLookupOptions struct {
// IncludeHidden lets moderators look up media with active = FALSE.
IncludeHidden bool
// RequireContentScannerProcessed limits the result to items imported by ContentScanner.
RequireContentScannerProcessed bool
}
// FindMedia looks up one media item by media key or numeric id. Shared media routes
// preserve moderator access to hidden items; ContentScanner-backed consumers can also
// request the same processed-only filtering used by MediaViewer's library routes.
func (c *Core) FindMedia(ctx context.Context, identifier string, options MediaLookupOptions) (MediaRecord, error) {
identifier = strings.TrimSpace(identifier)
var record MediaRecord
row := c.db.QueryRow(ctx, `
@@ -804,7 +845,8 @@ func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden b
COALESCE(width, 0), COALESCE(height, 0), COALESCE(duration_ms, 0), COALESCE(size_bytes, 0),
COALESCE(is_vr, FALSE), COALESCE(has_funscript, FALSE), funscript_action_count,
funscript_avg_speed, funscript_max_speed, COALESCE(speed, 0), COALESCE(modified_at, created_at)
FROM media WHERE (media_key=$1 OR id=$2) AND (active OR $3) LIMIT 1`, identifier, mediaIDArg(identifier), includeHidden)
FROM media WHERE (media_key=$1 OR id=$2) AND (active OR $3) AND (NOT $4 OR content_scanner_processed) LIMIT 1`,
identifier, mediaIDArg(identifier), options.IncludeHidden, options.RequireContentScannerProcessed)
var title, description string
var width, height int
var duration, size int64
@@ -850,6 +892,12 @@ func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden b
return record, nil
}
// findMedia keeps the shared routes on the same lookup implementation used by
// media-family applications that need ContentScanner's processed-only filter.
func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden bool) (MediaRecord, error) {
return c.FindMedia(ctx, identifier, MediaLookupOptions{IncludeHidden: includeHidden})
}
// ToJSON is the shared wire shape for a media record, matching every
// mediacore route's own response shape (id/mediaKey/filename/url/thumbnail/
// etc.) - services with their own media listing routes (e.g. MediaViewer's
@@ -875,11 +923,28 @@ func (record MediaRecord) ToJSON() map[string]any {
}
}
// SettingValue reads one key from the shared `settings` table, returning
// fallback if it is unset or the read fails.
func SettingValue(ctx context.Context, db *pgxpool.Pool, key, fallback string) string {
// SettingValue reads one key from the shared `settings` table. An absent or empty
// setting returns fallback; database errors are returned to the caller.
func SettingValue(ctx context.Context, db *pgxpool.Pool, key, fallback string) (string, error) {
var value string
if err := db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key=$1`, key).Scan(&value); err != nil || value == "" {
err := db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key=$1`, key).Scan(&value)
if errors.Is(err, pgx.ErrNoRows) {
return fallback, nil
}
if err != nil {
return "", err
}
if value == "" {
return fallback, nil
}
return value, nil
}
// SettingValueOrFallback preserves the old fallback-on-error behavior for callers
// whose API cannot return a read error. New request paths should use SettingValue.
func SettingValueOrFallback(ctx context.Context, db *pgxpool.Pool, key, fallback string) string {
value, err := SettingValue(ctx, db, key, fallback)
if err != nil {
return fallback
}
return value
@@ -888,7 +953,7 @@ func SettingValue(ctx context.Context, db *pgxpool.Pool, key, fallback string) s
// SettingBool reads a boolean-ish setting ("1"/"true"/"yes"/"on" are true,
// anything else is fallback).
func SettingBool(ctx context.Context, db *pgxpool.Pool, key string, fallback bool) bool {
value := strings.ToLower(strings.TrimSpace(SettingValue(ctx, db, key, "")))
value := strings.ToLower(strings.TrimSpace(SettingValueOrFallback(ctx, db, key, "")))
if value == "" {
return fallback
}
@@ -922,19 +987,19 @@ var carrierNodeInstancePattern = regexp.MustCompile(`^carriernode(_\d+)?$`)
// Returns fallback if no carriernode* instance is registered (or none has a URL) yet.
func CarrierNodeURLs(ctx context.Context, db *pgxpool.Pool, fallback []string) []string {
var registered []string
_ = json.Unmarshal([]byte(SettingValue(ctx, db, "configured_central", "")), &registered)
_ = json.Unmarshal([]byte(SettingValueOrFallback(ctx, db, "configured_central", "")), &registered)
var urls []string
for _, project := range registered {
key := strings.ToLower(strings.TrimSpace(project))
if !carrierNodeInstancePattern.MatchString(key) {
continue
}
if url := strings.TrimSpace(SettingValue(ctx, db, key+"_url", "")); url != "" {
if url := strings.TrimSpace(SettingValueOrFallback(ctx, db, key+"_url", "")); url != "" {
urls = append(urls, url)
}
}
if len(urls) == 0 {
if url := strings.TrimSpace(SettingValue(ctx, db, "carriernode_url", "")); url != "" {
if url := strings.TrimSpace(SettingValueOrFallback(ctx, db, "carriernode_url", "")); url != "" {
urls = []string{url}
}
}
@@ -9,11 +9,28 @@ import (
"testing"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgxpool"
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
"repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
)
func TestSettingValueReturnsDatabaseErrors(t *testing.T) {
db, err := pgxpool.New(context.Background(), "postgres://nobody@127.0.0.1:1/none?sslmode=disable&connect_timeout=1")
if err != nil {
t.Fatalf("pgxpool.New: %v", err)
}
defer db.Close()
value, err := SettingValue(context.Background(), db, "example", "fallback")
if err == nil || value != "" {
t.Fatalf("SettingValue() = %q, %v; want empty value and database error", value, err)
}
if got := SettingValueOrFallback(context.Background(), db, "example", "fallback"); got != "fallback" {
t.Fatalf("SettingValueOrFallback() = %q, want fallback on error", got)
}
}
// loginRequiredStore is a ProxyStore that always requires login, so the auth gate can be
// exercised without a database.
type loginRequiredStore struct{}
+1 -1
View File
@@ -31,6 +31,7 @@ func (c *Core) Migrate(ctx context.Context) error {
var migrationStatements = []string{
`CREATE EXTENSION IF NOT EXISTS pgcrypto`,
`CREATE EXTENSION IF NOT EXISTS pg_trgm`,
`DROP INDEX IF EXISTS media_search_idx`,
`CREATE TABLE IF NOT EXISTS users (
id BIGSERIAL PRIMARY KEY,
@@ -85,7 +86,6 @@ var migrationStatements = []string{
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_max_speed REAL`,
`CREATE INDEX IF NOT EXISTS media_active_idx ON media (active)`,
`CREATE INDEX IF NOT EXISTS media_file_path_idx ON media (file_path)`,
`CREATE INDEX IF NOT EXISTS media_search_idx ON media USING GIN (to_tsvector('simple', COALESCE(title, '') || ' ' || COALESCE(original_filename, '') || ' ' || COALESCE(file_path, '')))`,
`CREATE INDEX IF NOT EXISTS media_active_type_idx ON media (active, media_type)`,
`CREATE TABLE IF NOT EXISTS media_stats (