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

+115
View File
@@ -0,0 +1,115 @@
package auth
import (
"context"
"fmt"
"net"
"net/http"
"strings"
"repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
)
// ParseTrustedProxies parses the TRUSTED_PROXIES setting: a comma-separated
// list of CIDR ranges or bare IP addresses. Only a request whose TCP peer is
// inside one of these ranges may have its X-Forwarded-For header honoured. An
// empty value trusts no proxy.
func ParseTrustedProxies(value string) ([]*net.IPNet, error) {
var networks []*net.IPNet
for _, entry := range strings.Split(value, ",") {
entry = strings.TrimSpace(entry)
if entry == "" {
continue
}
if !strings.Contains(entry, "/") {
ip := net.ParseIP(entry)
if ip == nil {
return nil, fmt.Errorf("trusted proxy %q is neither an IP address nor a CIDR range", entry)
}
bits := 8 * net.IPv6len
if ip.To4() != nil {
bits = 8 * net.IPv4len
}
entry = fmt.Sprintf("%s/%d", ip.String(), bits)
}
_, network, err := net.ParseCIDR(entry)
if err != nil {
return nil, fmt.Errorf("trusted proxy %q is not a valid CIDR range: %w", entry, err)
}
networks = append(networks, network)
}
return networks, nil
}
// clientAddress returns the address a login attempt is counted against. The
// TCP peer is used unless it is a trusted proxy. For a trusted peer,
// X-Forwarded-For is read from the right and trusted hops are skipped, so the
// first untrusted address is the one the proxy chain actually saw. A malformed
// entry makes the peer address the answer, so a bad header can never choose the
// key.
func (s *Service) clientAddress(r *http.Request) string {
peer := peerHost(r)
if !s.isTrustedProxy(peer) {
return peer
}
hops := forwardedHops(r.Header.Values("X-Forwarded-For"))
if len(hops) == 0 {
return peer
}
for i := len(hops) - 1; i >= 0; i-- {
ip := net.ParseIP(hops[i])
if ip == nil {
return peer
}
if !s.isTrustedProxyIP(ip) {
return ip.String()
}
}
// Every hop is a trusted proxy, so the left-most one is closest to the client.
return net.ParseIP(hops[0]).String()
}
// withClientIP returns the request context carrying clientAddress, so the
// credential calls to AuthGuard report the end user's address (as
// X-Forwarded-For) instead of this service's. AuthGuard honours that header
// only for peers in its own TRUSTED_PROXIES list.
func (s *Service) withClientIP(r *http.Request) context.Context {
return authclient.WithClientIP(r.Context(), s.clientAddress(r))
}
func (s *Service) isTrustedProxy(host string) bool {
ip := net.ParseIP(host)
return ip != nil && s.isTrustedProxyIP(ip)
}
func (s *Service) isTrustedProxyIP(ip net.IP) bool {
for _, network := range s.trustedProxies {
if network.Contains(ip) {
return true
}
}
return false
}
// peerHost is the host part of the address the TCP connection came from.
func peerHost(r *http.Request) string {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return host
}
// forwardedHops flattens every X-Forwarded-For header line into its entries,
// left to right.
func forwardedHops(values []string) []string {
var hops []string
for _, value := range values {
for _, part := range strings.Split(value, ",") {
if part = strings.TrimSpace(part); part != "" {
hops = append(hops, part)
}
}
}
return hops
}
+91
View File
@@ -0,0 +1,91 @@
package auth
import (
"net"
"net/http"
"net/http/httptest"
"testing"
)
func mustTrustedProxies(t *testing.T, value string) []*net.IPNet {
t.Helper()
networks, err := ParseTrustedProxies(value)
if err != nil {
t.Fatalf("ParseTrustedProxies(%q) error = %v", value, err)
}
return networks
}
func TestParseTrustedProxiesAcceptsCIDRsAndBareAddresses(t *testing.T) {
networks := mustTrustedProxies(t, " 10.0.0.0/8, 192.168.1.5 , ::1 ,")
if len(networks) != 3 {
t.Fatalf("networks = %d, want 3", len(networks))
}
for _, ip := range []string{"10.20.30.40", "192.168.1.5", "::1"} {
if !(&Service{trustedProxies: networks}).isTrustedProxy(ip) {
t.Errorf("%s not trusted", ip)
}
}
if (&Service{trustedProxies: networks}).isTrustedProxy("192.168.1.6") {
t.Error("192.168.1.6 trusted, but only 192.168.1.5 was listed")
}
}
func TestParseTrustedProxiesRejectsInvalidEntries(t *testing.T) {
for _, value := range []string{"10.0.0.0/33", "proxy.internal", "10.0.0.1/8/8"} {
if _, err := ParseTrustedProxies(value); err == nil {
t.Errorf("ParseTrustedProxies(%q) accepted an invalid entry", value)
}
}
networks, err := ParseTrustedProxies(" ")
if err != nil || len(networks) != 0 {
t.Fatalf("empty setting = %v, %v; want no proxies and no error", networks, err)
}
}
func clientAddressFor(s *Service, remote string, forwarded ...string) string {
r := httptest.NewRequest(http.MethodPost, "/auth/login", nil)
r.RemoteAddr = remote
for _, value := range forwarded {
r.Header.Add("X-Forwarded-For", value)
}
return s.clientAddress(r)
}
func TestClientAddressIgnoresForwardedForWithoutTrustedProxies(t *testing.T) {
s := &Service{}
if got := clientAddressFor(s, "203.0.113.7:4444", "198.51.100.1"); got != "203.0.113.7" {
t.Fatalf("clientAddress = %q, want the TCP peer 203.0.113.7", got)
}
}
func TestClientAddressIgnoresForwardedForFromAnUnknownPeer(t *testing.T) {
s := &Service{trustedProxies: mustTrustedProxies(t, "10.0.0.0/8")}
if got := clientAddressFor(s, "203.0.113.7:4444", "198.51.100.1"); got != "203.0.113.7" {
t.Fatalf("clientAddress = %q, want the TCP peer 203.0.113.7", got)
}
}
func TestClientAddressHonoursForwardedForFromATrustedPeer(t *testing.T) {
s := &Service{trustedProxies: mustTrustedProxies(t, "10.0.0.0/8, 172.16.0.0/12")}
tests := []struct {
name string
forwarded []string
want string
}{
{"single client", []string{"198.51.100.9"}, "198.51.100.9"},
{"client behind a second trusted hop", []string{"198.51.100.9, 172.16.4.4"}, "198.51.100.9"},
{"spoofed left-most entry is skipped", []string{"6.6.6.6, 198.51.100.9, 172.16.4.4"}, "198.51.100.9"},
{"entries across header lines", []string{"6.6.6.6", "198.51.100.9"}, "198.51.100.9"},
{"malformed entry falls back to the peer", []string{"198.51.100.9, not-an-ip"}, "10.0.0.2"},
{"no header falls back to the peer", nil, "10.0.0.2"},
{"every hop trusted uses the left-most", []string{"10.1.1.1, 172.16.4.4"}, "10.1.1.1"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := clientAddressFor(s, "10.0.0.2:1000", tt.forwarded...); got != tt.want {
t.Fatalf("clientAddress = %q, want %q", got, tt.want)
}
})
}
}
+145
View File
@@ -0,0 +1,145 @@
package auth
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
)
// contractFile holds the fixtures the Go, Node and Python auth helpers 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 authContract struct {
Password struct {
Plaintext string `json:"plaintext"`
WrongPassword string `json:"wrongPassword"`
Hashes []struct {
Name string `json:"name"`
Hash string `json:"hash"`
Verifies map[string]bool `json:"verifies"`
NeedsUpgrade map[string]bool `json:"needsUpgrade"`
} `json:"hashes"`
TooLongToHash struct {
Bytes int `json:"bytes"`
Accepted map[string]bool `json:"accepted"`
} `json:"tooLongToHash"`
} `json:"password"`
TOTP struct {
Secret string `json:"secret"`
Cases []struct {
Name string `json:"name"`
Unix int64 `json:"unix"`
Code string `json:"code"`
Secret *string `json:"secret"`
Valid bool `json:"valid"`
} `json:"cases"`
} `json:"totp"`
ClientAddress struct {
InvalidTrustedProxyLists []string `json:"invalidTrustedProxyLists"`
Cases []struct {
Name string `json:"name"`
Trusted string `json:"trusted"`
Peer string `json:"peer"`
Forwarded []string `json:"forwarded"`
Want string `json:"want"`
} `json:"cases"`
} `json:"clientAddress"`
}
func loadContract(t *testing.T) authContract {
t.Helper()
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 authContract
if err := json.Unmarshal(data, &contract); err != nil {
t.Fatalf("decode %s: %v", contractFile, err)
}
return contract
}
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"] {
t.Errorf("VerifyPassword = %v, want %v", got, entry.Verifies["go"])
}
if VerifyPassword(entry.Hash, contract.Password.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)
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)) {
t.Errorf("the upgraded hash %q is not a verifiable current-scheme hash", upgraded)
}
}
})
}
}
func TestContractPasswordLength(t *testing.T) {
contract := loadContract(t)
_, err := HashPassword(strings.Repeat("a", contract.Password.TooLongToHash.Bytes))
if accepted := err == nil; accepted != contract.Password.TooLongToHash.Accepted["go"] {
t.Fatalf("HashPassword of %d bytes accepted = %v, want %v (error %v)", contract.Password.TooLongToHash.Bytes, accepted, contract.Password.TooLongToHash.Accepted["go"], err)
}
}
func TestContractTOTP(t *testing.T) {
contract := loadContract(t)
for _, entry := range contract.TOTP.Cases {
t.Run(entry.Name, func(t *testing.T) {
secret := contract.TOTP.Secret
if entry.Secret != nil {
secret = *entry.Secret
}
if got := VerifyTOTP(secret, entry.Code, time.Unix(entry.Unix, 0)); got != entry.Valid {
t.Errorf("VerifyTOTP = %v, want %v", got, entry.Valid)
}
})
}
}
func TestContractClientAddress(t *testing.T) {
contract := loadContract(t)
for _, entry := range contract.ClientAddress.Cases {
t.Run(entry.Name, func(t *testing.T) {
networks, err := ParseTrustedProxies(entry.Trusted)
if err != nil {
t.Fatal(err)
}
request := httptest.NewRequest(http.MethodPost, "/auth/login", nil)
request.RemoteAddr = entry.Peer + ":4000"
if strings.Contains(entry.Peer, ":") {
request.RemoteAddr = "[" + entry.Peer + "]:4000"
}
for _, line := range entry.Forwarded {
request.Header.Add("X-Forwarded-For", line)
}
if got := (&Service{trustedProxies: networks}).clientAddress(request); got != entry.Want {
t.Errorf("clientAddress = %q, want %q", got, entry.Want)
}
})
}
for _, list := range contract.ClientAddress.InvalidTrustedProxyLists {
if _, err := ParseTrustedProxies(list); err == nil {
t.Errorf("ParseTrustedProxies(%q) accepted an invalid list", list)
}
}
}
+65 -6
View File
@@ -1,21 +1,80 @@
package auth
import "golang.org/x/crypto/bcrypt"
import (
"strings"
"golang.org/x/crypto/bcrypt"
)
// BcryptCost is kept in one place so all services use the same password
// storage policy. Existing hashes remain valid when this value is raised.
// storage policy. Hashes stored at a lower cost are rewritten on the next
// successful login (see VerifyAndUpgradePassword).
const BcryptCost = 12
// HashPassword returns a bcrypt password hash suitable for storage.
// bcryptScheme prefixes every hash HashPassword writes, so verification picks
// the algorithm from the stored value. The bcrypt string follows unchanged, so
// a stored value reads "bcrypt$$2a$12$..." (the bcrypt string itself starts
// with "$"). Unprefixed bcrypt hashes from before the prefix still verify and
// are upgraded on login.
const bcryptScheme = "bcrypt$"
// HashPassword returns a versioned password hash suitable for storage.
func HashPassword(password string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), BcryptCost)
if err != nil {
return "", err
}
return string(hash), nil
return bcryptScheme + string(hash), nil
}
// VerifyPassword checks a plaintext password against a stored bcrypt hash.
// VerifyPassword checks a plaintext password against a stored hash. It accepts
// hashes from HashPassword and unprefixed bcrypt hashes; any other format
// fails closed.
func VerifyPassword(hash, password string) bool {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
bcryptHash, ok := bcryptHashOf(hash)
if !ok {
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 {
bcryptHash, prefixed := strings.CutPrefix(hash, bcryptScheme)
if !prefixed {
return true
}
cost, err := bcrypt.Cost([]byte(bcryptHash))
return err != nil || cost < BcryptCost
}
// VerifyAndUpgradePassword checks password against a stored hash. When it
// matches a hash that is not in the current scheme, it returns a replacement
// from HashPassword for the caller to store; upgraded is empty when no rewrite
// is needed or the password does not match. A non-nil error with valid set
// means the login succeeded but the replacement could not be made.
func VerifyAndUpgradePassword(hash, password string) (valid bool, upgraded string, err error) {
if !VerifyPassword(hash, password) {
return false, "", nil
}
if !PasswordHashNeedsUpgrade(hash) {
return true, "", nil
}
upgraded, err = HashPassword(password)
if err != nil {
return true, "", err
}
return true, upgraded, nil
}
// bcryptHashOf returns the bcrypt string inside a stored hash.
func bcryptHashOf(stored string) (string, bool) {
if rest, prefixed := strings.CutPrefix(stored, bcryptScheme); prefixed {
return rest, true
}
if strings.HasPrefix(stored, "$2a$") || strings.HasPrefix(stored, "$2b$") || strings.HasPrefix(stored, "$2y$") {
return stored, true
}
return "", false
}
+106
View File
@@ -0,0 +1,106 @@
package auth
import (
"strings"
"testing"
"golang.org/x/crypto/bcrypt"
)
const testPassword = "correct horse battery staple"
func TestHashPasswordWritesTheSchemePrefix(t *testing.T) {
hash, err := HashPassword(testPassword)
if err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(hash, "bcrypt$$2") {
t.Fatalf("hash = %q, want the bcrypt$ scheme prefix before a bcrypt string", hash)
}
if PasswordHashNeedsUpgrade(hash) {
t.Fatal("a fresh hash in the current scheme needs no upgrade")
}
}
func TestVerifyPasswordAcceptsUnprefixedLegacyBcrypt(t *testing.T) {
legacy, err := bcrypt.GenerateFromPassword([]byte(testPassword), BcryptCost)
if err != nil {
t.Fatal(err)
}
if !VerifyPassword(string(legacy), testPassword) {
t.Fatal("legacy unprefixed bcrypt hash no longer verifies")
}
if VerifyPassword(string(legacy), "wrong password") {
t.Fatal("legacy unprefixed bcrypt hash accepted the wrong password")
}
if !PasswordHashNeedsUpgrade(string(legacy)) {
t.Fatal("unprefixed hash should be marked for upgrade")
}
}
func TestVerifyPasswordFailsClosedOnUnknownFormats(t *testing.T) {
for _, stored := range []string{
"",
"salt:0123abcd",
"pbkdf2-sha256$600000$00$00",
"argon2id$v=19$whatever",
"bcrypt$",
"bcrypt$not-a-bcrypt-string",
} {
if VerifyPassword(stored, testPassword) {
t.Errorf("VerifyPassword accepted unknown format %q", stored)
}
}
}
func TestVerifyAndUpgradeRewritesLegacyHashesOnSuccess(t *testing.T) {
legacy, err := bcrypt.GenerateFromPassword([]byte(testPassword), BcryptCost)
if err != nil {
t.Fatal(err)
}
valid, upgraded, err := VerifyAndUpgradePassword(string(legacy), testPassword)
if err != nil || !valid {
t.Fatalf("VerifyAndUpgradePassword() = %v, %v; want valid", valid, err)
}
if !strings.HasPrefix(upgraded, bcryptScheme) {
t.Fatalf("upgraded hash = %q, want the current scheme", upgraded)
}
if !VerifyPassword(upgraded, testPassword) {
t.Fatal("upgraded hash does not verify the password")
}
}
func TestVerifyAndUpgradeRewritesLowCostHashes(t *testing.T) {
lowCost, err := bcrypt.GenerateFromPassword([]byte(testPassword), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
stored := bcryptScheme + string(lowCost)
if !PasswordHashNeedsUpgrade(stored) {
t.Fatal("a prefixed hash below BcryptCost should be marked for upgrade")
}
valid, upgraded, err := VerifyAndUpgradePassword(stored, testPassword)
if err != nil || !valid || upgraded == "" {
t.Fatalf("VerifyAndUpgradePassword() = %v, %q, %v; want a rewrite", valid, upgraded, err)
}
}
func TestVerifyAndUpgradeLeavesCurrentAndFailedChecksAlone(t *testing.T) {
current, err := HashPassword(testPassword)
if err != nil {
t.Fatal(err)
}
valid, upgraded, err := VerifyAndUpgradePassword(current, testPassword)
if err != nil || !valid || upgraded != "" {
t.Fatalf("current hash: VerifyAndUpgradePassword() = %v, %q, %v; want valid with no rewrite", valid, upgraded, err)
}
legacy, err := bcrypt.GenerateFromPassword([]byte(testPassword), BcryptCost)
if err != nil {
t.Fatal(err)
}
valid, upgraded, err = VerifyAndUpgradePassword(string(legacy), "wrong password")
if err != nil || valid || upgraded != "" {
t.Fatalf("wrong password: VerifyAndUpgradePassword() = %v, %q, %v; want a plain refusal", valid, upgraded, err)
}
}
@@ -0,0 +1,175 @@
package auth
import (
"context"
"net/url"
"os"
"strings"
"testing"
"repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
)
// platformUsersSchema holds the test's own `users` table, so it never meets the fuller table that
// mediacore's migration creates in the same database.
const platformUsersSchema = "platform_users_test"
// withSearchPath returns databaseURL with its search_path set to schema.
func withSearchPath(t *testing.T, databaseURL, schema string) string {
t.Helper()
parsed, err := url.Parse(databaseURL)
if err != nil {
t.Fatalf("parse database URL: %v", err)
}
query := parsed.Query()
query.Set("search_path", schema)
parsed.RawQuery = query.Encode()
return parsed.String()
}
// TestPlatformUserSQL runs the moderatable platform-user methods (CreateUser, ListUsers,
// UpdateUser, SetPassword, DeleteUser) against a real database. The `users` table normally comes
// from mediacore's migration, which this package cannot import, so the test creates the columns it
// needs in a schema of its own. It is skipped unless SHARED_TEST_DATABASE_URL points at a scratch
// database, for example:
//
// SHARED_TEST_DATABASE_URL=postgres://user:pass@localhost:5432/scratch?sslmode=disable go test ./auth/ -run TestPlatformUserSQL
func TestPlatformUserSQL(t *testing.T) {
databaseURL := os.Getenv("SHARED_TEST_DATABASE_URL")
if databaseURL == "" {
t.Skip("SHARED_TEST_DATABASE_URL not set; skipping Postgres platform-user test")
}
ctx := context.Background()
admin, err := postgres.Open(ctx, postgres.DefaultConfig(databaseURL))
if err != nil {
t.Fatalf("open pool: %v", err)
}
t.Cleanup(admin.Close)
if _, err := admin.Exec(ctx, `DROP SCHEMA IF EXISTS `+platformUsersSchema+` CASCADE; CREATE SCHEMA `+platformUsersSchema); err != nil {
t.Fatalf("create schema: %v", err)
}
t.Cleanup(func() {
_, _ = admin.Exec(context.Background(), `DROP SCHEMA IF EXISTS `+platformUsersSchema+` CASCADE`)
})
pool, err := postgres.Open(ctx, postgres.DefaultConfig(withSearchPath(t, databaseURL, platformUsersSchema)))
if err != nil {
t.Fatalf("open pool: %v", err)
}
t.Cleanup(pool.Close)
if _, err := pool.Exec(ctx, `
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
username TEXT,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
disabled BOOLEAN NOT NULL DEFAULT FALSE,
last_login_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`); err != nil {
t.Fatalf("create users table: %v", err)
}
service := New(pool, "session", false, "", "testproject")
if _, err := service.CreateUser(ctx, "not-an-email", "x", "password123", "user"); err == nil {
t.Fatal("CreateUser accepted an invalid email")
}
if _, err := service.CreateUser(ctx, "platform-test-bad@example.com", "x@y", "password123", "user"); err == nil {
t.Fatal("CreateUser accepted a username containing @")
}
if _, err := service.CreateUser(ctx, "platform-test-bad@example.com", "x", strings.Repeat("p", 73), "user"); err == nil {
t.Fatal("CreateUser accepted a password longer than 72 bytes")
}
alice, err := service.CreateUser(ctx, " Platform-Test-Alice@Example.com ", "alice-platform", "password123", "MODERATOR")
if err != nil {
t.Fatalf("CreateUser(alice) error = %v", err)
}
if alice.Email != "platform-test-alice@example.com" || alice.Username != "alice-platform" || alice.Role != "moderator" {
t.Fatalf("created user = %+v, want a lower-cased email and the normalized moderator role", alice)
}
bob, err := service.CreateUser(ctx, "platform-test-bob@example.com", "bob-platform", "password123", "superuser")
if err != nil {
t.Fatalf("CreateUser(bob) error = %v", err)
}
if bob.Role != "user" {
t.Fatalf("an unknown role was stored as %q, want it reduced to user", bob.Role)
}
if _, err := service.CreateUser(ctx, "platform-test-alice@example.com", "other", "password123", "user"); err == nil {
t.Fatal("CreateUser accepted a duplicate email")
}
var storedHash string
if err := pool.QueryRow(ctx, `SELECT password_hash FROM users WHERE id=$1`, alice.ID).Scan(&storedHash); err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(storedHash, bcryptScheme) || !VerifyPassword(storedHash, "password123") {
t.Fatalf("stored hash %q is not a verifiable versioned hash", storedHash)
}
listed, total, err := service.ListUsers(ctx, "platform-test-", 1, 0)
if err != nil || total != 2 || len(listed) != 1 {
t.Fatalf("ListUsers page 1 = %d rows, total %d, %v; want 1 row of 2", len(listed), total, err)
}
if listed[0]["id"] != bob.ID {
t.Fatalf("first row = %v, want the newest user (ordered by id descending)", listed[0]["id"])
}
if page, _, _ := service.ListUsers(ctx, "platform-test-", 1, 1); len(page) != 1 || page[0]["id"] != alice.ID {
t.Fatalf("second page = %v, want alice", page)
}
if found, total, _ := service.ListUsers(ctx, "ALICE-platform", 50, 0); total != 1 || len(found) != 1 || found[0]["email"] != "platform-test-alice@example.com" {
t.Fatalf("search by username = %v (total %d), want alice, matched ignoring case", found, total)
}
if found, total, _ := service.ListUsers(ctx, "no-such-person-anywhere", 50, 0); total != 0 || len(found) != 0 {
t.Fatalf("search with no match = %v (total %d)", found, total)
}
disabled := true
if err := service.UpdateUser(ctx, alice.ID, "", "alice-renamed", "", &disabled); err != nil {
t.Fatalf("UpdateUser error = %v", err)
}
account, err := service.managedAccount(ctx, alice.ID)
if err != nil || account == nil {
t.Fatalf("managedAccount = %v, %v", account, err)
}
if account.Username != "alice-renamed" || account.Email != "platform-test-alice@example.com" || account.Role != "moderator" || !account.Disabled {
t.Fatalf("after a partial update = %+v, want only the username and disabled flag changed", account)
}
if err := service.UpdateUser(ctx, alice.ID, "", "", " ADMIN ", nil); err != nil {
t.Fatal(err)
}
if account, _ := service.managedAccount(ctx, alice.ID); account.Role != "admin" || !account.Disabled {
t.Fatalf("after a role-only update = %+v, want the admin role and the disabled flag kept", account)
}
if err := service.UpdateUser(ctx, alice.ID, "", "", "wizard", nil); err != nil {
t.Fatal(err)
}
if account, _ := service.managedAccount(ctx, alice.ID); account.Role != "user" {
t.Fatalf("an unknown role was stored as %q, want it reduced to user", account.Role)
}
if missing, err := service.managedAccount(ctx, -1); err != nil || missing != nil {
t.Fatalf("managedAccount of a missing id = %v, %v; want nil, nil", missing, err)
}
if err := service.SetPassword(ctx, bob.ID, "short"); err == nil {
t.Fatal("SetPassword accepted a short password")
}
if err := service.SetPassword(ctx, bob.ID, "a-new-password-1"); err != nil {
t.Fatalf("SetPassword error = %v", err)
}
if err := pool.QueryRow(ctx, `SELECT password_hash FROM users WHERE id=$1`, bob.ID).Scan(&storedHash); err != nil {
t.Fatal(err)
}
if !VerifyPassword(storedHash, "a-new-password-1") || VerifyPassword(storedHash, "password123") {
t.Fatal("SetPassword did not replace the stored hash")
}
if err := service.DeleteUser(ctx, alice.ID); err != nil {
t.Fatal(err)
}
if gone, _ := service.managedAccount(ctx, alice.ID); gone != nil {
t.Fatal("DeleteUser left the account in place")
}
}
+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)
}
+663
View File
@@ -0,0 +1,663 @@
package auth
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
)
// recordedCall is one request a fakeAuthGuard received.
type recordedCall struct {
Method string
Path string
Forwarded string
Authorization string
Body map[string]any
}
// fakeAuthGuard is an httptest AuthGuard that records every call and answers from a route table.
type fakeAuthGuard struct {
mu sync.Mutex
calls []recordedCall
routes map[string]func(w http.ResponseWriter, body map[string]any)
server *httptest.Server
}
func newFakeAuthGuard(t *testing.T) *fakeAuthGuard {
t.Helper()
f := &fakeAuthGuard{routes: map[string]func(http.ResponseWriter, map[string]any){}}
f.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, _ := io.ReadAll(r.Body)
var body map[string]any
_ = json.Unmarshal(raw, &body)
f.mu.Lock()
f.calls = append(f.calls, recordedCall{
Method: r.Method, Path: r.URL.Path, Forwarded: r.Header.Get("X-Forwarded-For"),
Authorization: r.Header.Get("Authorization"), Body: body,
})
route := f.routes[r.Method+" "+r.URL.Path]
f.mu.Unlock()
if route == nil {
http.NotFound(w, r)
return
}
route(w, body)
}))
t.Cleanup(f.server.Close)
return f
}
func (f *fakeAuthGuard) handle(route string, handler func(w http.ResponseWriter, body map[string]any)) {
f.mu.Lock()
defer f.mu.Unlock()
f.routes[route] = handler
}
func (f *fakeAuthGuard) reply(route string, status int, payload any) {
f.handle(route, func(w http.ResponseWriter, _ map[string]any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(payload)
})
}
func (f *fakeAuthGuard) callsTo(route string) []recordedCall {
f.mu.Lock()
defer f.mu.Unlock()
var matched []recordedCall
for _, call := range f.calls {
if call.Method+" "+call.Path == route {
matched = append(matched, call)
}
}
return matched
}
func (f *fakeAuthGuard) service(t *testing.T, options ...ServiceOption) (*Service, *fakeProxyStore) {
t.Helper()
store := &fakeProxyStore{loginRequired: true}
return NewWithStore(store, "session", false, f.server.URL, "testproject", options...), store
}
func jsonRequest(method, target, body string) *http.Request {
req := httptest.NewRequest(method, target, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
return req
}
func withSession(req *http.Request, token string) *http.Request {
req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: token})
return req
}
func withUser(req *http.Request, user *ProxyUser) *http.Request {
return req.WithContext(context.WithValue(req.Context(), proxyUserContextKey, user))
}
func decodeBody(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
t.Helper()
var out map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatalf("response body %q is not JSON: %v", rec.Body.String(), err)
}
return out
}
func TestLoginForwardsTheVerifiedClientAddressToAuthGuard(t *testing.T) {
tests := []struct {
name string
trusted string
remote string
forwarded string
want string
}{
{"peer without trusted proxies", "", "203.0.113.7:4444", "", "203.0.113.7"},
{"spoofed header from an untrusted peer", "10.0.0.0/8", "203.0.113.7:4444", "6.6.6.6", "203.0.113.7"},
{"client behind a trusted proxy", "10.0.0.0/8", "10.0.0.2:4444", "6.6.6.6, 198.51.100.9", "198.51.100.9"},
{"unparseable peer sends nothing", "", "not-an-address", "", ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("POST /api/login", http.StatusOK, map[string]any{"user": map[string]any{"id": 1, "username": "a", "role": "user"}})
networks, err := ParseTrustedProxies(tt.trusted)
if err != nil {
t.Fatal(err)
}
service, _ := guard.service(t, WithTrustedProxies(networks))
req := jsonRequest(http.MethodPost, "/auth/login", `{"identifier":"a","password":"password123"}`)
req.RemoteAddr = tt.remote
if tt.forwarded != "" {
req.Header.Set("X-Forwarded-For", tt.forwarded)
}
rec := httptest.NewRecorder()
service.Login(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("login status = %d, body %s", rec.Code, rec.Body.String())
}
calls := guard.callsTo("POST /api/login")
if len(calls) != 1 || calls[0].Forwarded != tt.want {
t.Fatalf("AuthGuard saw X-Forwarded-For %+v, want %q", calls, tt.want)
}
})
}
}
func TestLoginMapsAuthGuardAnswers(t *testing.T) {
login := func(guard *fakeAuthGuard) *httptest.ResponseRecorder {
service, _ := guard.service(t)
rec := httptest.NewRecorder()
service.Login(rec, jsonRequest(http.MethodPost, "/auth/login", `{"email":"a@b.com","password":"password123"}`))
return rec
}
t.Run("success forwards the session cookie", func(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.handle("POST /api/login", func(w http.ResponseWriter, _ map[string]any) {
http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: "tok", Path: "/", HttpOnly: true})
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"user":{"id":3,"username":"a","email":"a@b.com","role":"admin","totp_enabled":true}}`))
})
rec := login(guard)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d", rec.Code)
}
user := decodeBody(t, rec)["user"].(map[string]any)
if user["role"] != "admin" || user["canManageUsers"] != true || user["mfaEnabled"] != true {
t.Fatalf("user = %v", user)
}
if cookies := rec.Result().Cookies(); len(cookies) != 1 || cookies[0].Value != "tok" {
t.Fatalf("cookies = %v, want the AuthGuard session cookie", cookies)
}
if body := guard.callsTo("POST /api/login")[0].Body; body["username_or_email"] != "a@b.com" {
t.Fatalf("AuthGuard body = %v, want the email used as the identifier", body)
}
})
t.Run("wrong credentials answer 401 with the generic message", func(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("POST /api/login", http.StatusUnauthorized, map[string]any{"error": "no such account"})
rec := login(guard)
if rec.Code != http.StatusUnauthorized || decodeBody(t, rec)["error"] != ErrInvalidLogin.Error() {
t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String())
}
})
t.Run("a required second factor is reported as mfaRequired", func(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("POST /api/login", http.StatusUnauthorized, map[string]any{"error": "code required", "totp_required": true})
rec := login(guard)
if rec.Code != http.StatusUnauthorized || decodeBody(t, rec)["mfaRequired"] != true {
t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String())
}
})
t.Run("an unreachable AuthGuard answers 500 with the unavailable message", func(t *testing.T) {
guard := newFakeAuthGuard(t)
service, _ := guard.service(t)
guard.server.Close()
rec := httptest.NewRecorder()
service.Login(rec, jsonRequest(http.MethodPost, "/auth/login", `{"identifier":"a","password":"password123"}`))
if rec.Code != http.StatusInternalServerError || decodeBody(t, rec)["error"] != errAuthGuardUnavailable.Error() {
t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String())
}
})
t.Run("a missing identifier and a non-JSON body are refused before AuthGuard", func(t *testing.T) {
guard := newFakeAuthGuard(t)
service, _ := guard.service(t)
rec := httptest.NewRecorder()
service.Login(rec, jsonRequest(http.MethodPost, "/auth/login", `{"password":"password123"}`))
if rec.Code != http.StatusUnauthorized {
t.Fatalf("missing identifier status = %d, want 401", rec.Code)
}
plain := httptest.NewRequest(http.MethodPost, "/auth/login", strings.NewReader(`{"identifier":"a"}`))
rec = httptest.NewRecorder()
service.Login(rec, plain)
if rec.Code != http.StatusBadRequest {
t.Fatalf("form-typed body status = %d, want 400", rec.Code)
}
if len(guard.callsTo("POST /api/login")) != 0 {
t.Fatal("a refused login still reached AuthGuard")
}
})
}
func TestLoginIsLimitedPerClientAddress(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("POST /api/login", http.StatusUnauthorized, map[string]any{"error": "bad"})
service, _ := guard.service(t)
attempt := func(i int, remote string) int {
req := jsonRequest(http.MethodPost, "/auth/login", `{"identifier":"user`+strings.Repeat("x", i)+`","password":"guess"}`)
req.RemoteAddr = remote
rec := httptest.NewRecorder()
service.Login(rec, req)
return rec.Code
}
for i := 0; i < loginClientLimit; i++ {
if code := attempt(i, "203.0.113.7:1"); code == http.StatusTooManyRequests {
t.Fatalf("attempt %d refused before the limit", i+1)
}
}
if code := attempt(loginClientLimit, "203.0.113.7:1"); code != http.StatusTooManyRequests {
t.Fatalf("attempt past the per-address limit status = %d, want 429", code)
}
if code := attempt(loginClientLimit+1, "203.0.113.8:1"); code == http.StatusTooManyRequests {
t.Fatal("a different client address was refused")
}
}
func TestSignupForwardsTheClientAddressAndClaimsSetup(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("GET /api/setup-status", http.StatusOK, map[string]any{"setup_required": true})
guard.reply("POST /api/register", http.StatusCreated, map[string]any{"user": map[string]any{"id": 1, "username": "root", "email": "root@example.com", "role": "superadmin"}})
service, store := guard.service(t)
req := jsonRequest(http.MethodPost, "/auth/signup", `{"email":"Root@Example.com","username":"root","password":"password123"}`)
req.RemoteAddr = "198.51.100.20:5555"
rec := httptest.NewRecorder()
service.Signup(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("signup status = %d, body %s", rec.Code, rec.Body.String())
}
if !store.setupClaimed {
t.Fatal("signup did not claim the setup flag")
}
calls := guard.callsTo("POST /api/register")
if len(calls) != 1 || calls[0].Forwarded != "198.51.100.20" || calls[0].Body["email"] != "root@example.com" {
t.Fatalf("register call = %+v", calls)
}
}
func TestSignupValidatesInputBeforeClaimingSetup(t *testing.T) {
guard := newFakeAuthGuard(t)
service, store := guard.service(t)
for name, body := range map[string]string{
"missing username": `{"email":"a@b.com","password":"password123"}`,
"bad email": `{"email":"nope","username":"a","password":"password123"}`,
"at in username": `{"email":"a@b.com","username":"a@b.com","password":"password123"}`,
"short password": `{"email":"a@b.com","username":"a","password":"short"}`,
} {
rec := httptest.NewRecorder()
service.Signup(rec, jsonRequest(http.MethodPost, "/auth/signup", body))
if rec.Code != http.StatusBadRequest {
t.Errorf("%s: status = %d, want 400", name, rec.Code)
}
}
if store.setupClaimed || len(guard.calls) != 0 {
t.Fatal("a refused signup claimed setup or reached AuthGuard")
}
}
func TestSignupReleasesTheClaimWhenAuthGuardAlreadyHasAnAccount(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("GET /api/setup-status", http.StatusOK, map[string]any{"setup_required": false})
service, store := guard.service(t)
rec := httptest.NewRecorder()
service.Signup(rec, jsonRequest(http.MethodPost, "/auth/signup", `{"email":"a@b.com","username":"a","password":"password123"}`))
if rec.Code != http.StatusConflict || store.setupClaimed {
t.Fatalf("status = %d, claimed = %v; want 409 and a released claim", rec.Code, store.setupClaimed)
}
}
func TestTOTPVerifyAndDisableForwardTheAddressAndShareAUserLimit(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("POST /api/totp/verify", http.StatusUnauthorized, map[string]any{"error": "bad code"})
guard.reply("POST /api/totp/disable", http.StatusUnauthorized, map[string]any{"error": "bad code"})
service, _ := guard.service(t)
user := &ProxyUser{ID: 7, Role: "user"}
post := func(handler http.HandlerFunc, body string) int {
req := withUser(withSession(jsonRequest(http.MethodPost, "/totp", body), "tok-7"), user)
req.RemoteAddr = "198.51.100.30:9"
rec := httptest.NewRecorder()
handler(rec, req)
return rec.Code
}
for i := 0; i < totpAttemptLimit-1; i++ {
if code := post(service.TOTPVerify, `{"totpToken":"000000"}`); code != http.StatusUnauthorized {
t.Fatalf("verify attempt %d status = %d, want 401", i+1, code)
}
}
if code := post(service.TOTPDisable, `{"token":"000000"}`); code != http.StatusUnauthorized {
t.Fatalf("disable attempt status = %d, want 401", code)
}
if code := post(service.TOTPVerify, `{"totpToken":"123456"}`); code != http.StatusTooManyRequests {
t.Fatalf("verify past the shared limit status = %d, want 429", code)
}
if code := post(service.TOTPDisable, `{"token":"123456"}`); code != http.StatusTooManyRequests {
t.Fatalf("disable past the shared limit status = %d, want 429", code)
}
verifies, disables := guard.callsTo("POST /api/totp/verify"), guard.callsTo("POST /api/totp/disable")
if len(verifies) != totpAttemptLimit-1 || len(disables) != 1 {
t.Fatalf("AuthGuard saw %d verify and %d disable calls, want %d and 1", len(verifies), len(disables), totpAttemptLimit-1)
}
for _, call := range append(verifies, disables...) {
if call.Forwarded != "198.51.100.30" || call.Authorization != "Bearer tok-7" {
t.Fatalf("call = %+v, want the client address and the session token", call)
}
}
if verifies[0].Body["token"] != "000000" {
t.Fatalf("verify body = %v, want the totpToken sent as token", verifies[0].Body)
}
other := withUser(withSession(jsonRequest(http.MethodPost, "/totp", `{"token":"1"}`), "tok-8"), &ProxyUser{ID: 8})
rec := httptest.NewRecorder()
service.TOTPVerify(rec, other)
if rec.Code == http.StatusTooManyRequests {
t.Fatal("another user shares the first user's TOTP limit")
}
}
func TestTOTPHandlersNeedASessionUser(t *testing.T) {
guard := newFakeAuthGuard(t)
service, _ := guard.service(t)
for name, handler := range map[string]http.HandlerFunc{
"status": service.TOTPStatus, "initiate": service.TOTPInitiate, "verify": service.TOTPVerify, "disable": service.TOTPDisable,
} {
rec := httptest.NewRecorder()
handler(rec, jsonRequest(http.MethodPost, "/totp", `{}`))
if rec.Code != http.StatusUnauthorized {
t.Errorf("%s without a session user: status = %d, want 401", name, rec.Code)
}
}
if len(guard.calls) != 0 {
t.Fatal("an unauthenticated TOTP request reached AuthGuard")
}
}
func TestTOTPInitiateAndStatus(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("POST /api/totp/enable", http.StatusOK, map[string]any{"secret": "JBSWY3DP", "otpauth_url": "otpauth://totp/x", "enabled": false})
service, _ := guard.service(t)
rec := httptest.NewRecorder()
service.TOTPStatus(rec, withUser(httptest.NewRequest(http.MethodGet, "/totp/status", nil), &ProxyUser{ID: 1, MFAEnabled: true}))
if body := decodeBody(t, rec); body["enabled"] != true || body["mfaEnabled"] != true {
t.Fatalf("status = %v", body)
}
rec = httptest.NewRecorder()
service.TOTPInitiate(rec, withUser(withSession(httptest.NewRequest(http.MethodPost, "/totp/initiate", nil), "tok"), &ProxyUser{ID: 1}))
data := decodeBody(t, rec)["data"].(map[string]any)
if rec.Code != http.StatusOK || data["secret"] != "JBSWY3DP" || data["otpauthUrl"] != "otpauth://totp/x" {
t.Fatalf("initiate status = %d, data %v", rec.Code, data)
}
rec = httptest.NewRecorder()
service.TOTPInitiate(rec, withUser(httptest.NewRequest(http.MethodPost, "/totp/initiate", nil), &ProxyUser{ID: 1, MFAEnabled: true}))
if rec.Code != http.StatusConflict {
t.Fatalf("initiate while enabled status = %d, want 409", rec.Code)
}
cross := withUser(httptest.NewRequest(http.MethodPost, "/totp/initiate", nil), &ProxyUser{ID: 1})
cross.Header.Set("Sec-Fetch-Site", "cross-site")
rec = httptest.NewRecorder()
service.TOTPInitiate(rec, cross)
if rec.Code != http.StatusForbidden {
t.Fatalf("cross-site initiate status = %d, want 403", rec.Code)
}
}
func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
guard := newFakeAuthGuard(t)
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)
update := func(user *ProxyUser, body string) *httptest.ResponseRecorder {
req := withSession(jsonRequest(http.MethodPut, "/auth/me", body), "tok-7")
if user != nil {
req = withUser(req, user)
}
rec := httptest.NewRecorder()
service.UpdateMe(rec, req)
return rec
}
manager := &ProxyUser{ID: 7, Role: "admin"}
if rec := update(nil, `{}`); rec.Code != http.StatusUnauthorized {
t.Fatalf("no session user: status = %d, want 401", rec.Code)
}
if rec := update(&ProxyUser{ID: 7, Role: "user"}, `{"email":"a@b.com"}`); rec.Code != http.StatusForbidden {
t.Fatalf("ordinary user: status = %d, want 403", rec.Code)
}
for name, body := range map[string]string{
"bad email": `{"email":"nope","username":"boss"}`,
"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) + `"}`,
"not JSON": `nope`,
} {
if rec := update(manager, body); rec.Code != http.StatusBadRequest {
t.Errorf("%s: status = %d, want 400", name, rec.Code)
}
}
if len(guard.callsTo("PUT /api/admin/users/7")) != 0 {
t.Fatal("a refused update reached AuthGuard")
}
rec := update(manager, `{"email":"Boss@Example.com","username":" boss "}`)
if rec.Code != http.StatusOK {
t.Fatalf("update status = %d, body %s", rec.Code, rec.Body.String())
}
calls := guard.callsTo("PUT /api/admin/users/7")
if len(calls) != 1 || calls[0].Authorization != "Bearer tok-7" || calls[0].Body["email"] != "boss@example.com" || calls[0].Body["username"] != "boss" {
t.Fatalf("AuthGuard update = %+v", calls)
}
if _, sent := calls[0].Body["password"]; sent {
t.Fatal("an update without a password sent one to AuthGuard")
}
if user := decodeBody(t, rec)["user"].(map[string]any); user["username"] != "boss" {
t.Fatalf("response user = %v", user)
}
}
func TestManagedUserHandlers(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("GET /api/admin/users", http.StatusOK, map[string]any{"users": []map[string]any{
{"id": 1, "username": "root", "email": "root@example.com", "role": "superadmin"},
{"id": 2, "username": "pat", "email": "pat@example.com", "role": "weird-role"},
}})
guard.reply("POST /api/admin/users", http.StatusCreated, map[string]any{"user": map[string]any{"id": 3, "username": "new", "email": "new@example.com", "role": "admin"}})
guard.reply("PUT /api/admin/users/2", http.StatusOK, map[string]any{})
guard.reply("DELETE /api/admin/users/2", http.StatusOK, map[string]any{})
guard.reply("DELETE /api/admin/users/1", http.StatusForbidden, map[string]any{"error": "the superadmin cannot be deleted"})
service, _ := guard.service(t)
t.Run("list normalizes roles", func(t *testing.T) {
rec := httptest.NewRecorder()
service.ManagedUsers(rec, withSession(httptest.NewRequest(http.MethodGet, "/users", nil), "tok"))
var users []map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &users); err != nil || len(users) != 2 {
t.Fatalf("users = %s, %v", rec.Body.String(), err)
}
if users[0]["role"] != "superadmin" || users[1]["role"] != "user" {
t.Fatalf("roles = %v, %v; want superadmin and the unknown role reduced to user", users[0]["role"], users[1]["role"])
}
if call := guard.callsTo("GET /api/admin/users")[0]; call.Authorization != "Bearer tok" {
t.Fatalf("list call = %+v, want the session token", call)
}
})
t.Run("create forwards the role", func(t *testing.T) {
rec := httptest.NewRecorder()
req := withSession(jsonRequest(http.MethodPost, "/users", `{"email":"new@example.com","username":"new","password":"password123","role":" admin "}`), "tok")
service.ManagedCreateUser(rec, req)
if rec.Code != http.StatusCreated || decodeBody(t, rec)["role"] != "admin" {
t.Fatalf("create status = %d, body %s", rec.Code, rec.Body.String())
}
if body := guard.callsTo("POST /api/admin/users")[0].Body; body["role"] != "admin" || body["username"] != "new" {
t.Fatalf("create body = %v", body)
}
})
t.Run("update answers with the refreshed user, or 404", func(t *testing.T) {
req := withSession(jsonRequest(http.MethodPut, "/users/2", `{"username":"pat2"}`), "tok")
req.SetPathValue("id", "2")
rec := httptest.NewRecorder()
service.ManagedUpdateUser(rec, req)
if rec.Code != http.StatusOK || decodeBody(t, rec)["username"] != "pat" {
t.Fatalf("update status = %d, body %s", rec.Code, rec.Body.String())
}
missing := withSession(jsonRequest(http.MethodPut, "/users/9", `{}`), "tok")
missing.SetPathValue("id", "9")
guard.reply("PUT /api/admin/users/9", http.StatusOK, map[string]any{})
rec = httptest.NewRecorder()
service.ManagedUpdateUser(rec, missing)
if rec.Code != http.StatusNotFound {
t.Fatalf("update of an id that is not listed: status = %d, want 404", rec.Code)
}
})
t.Run("delete", func(t *testing.T) {
del := func(id string, header http.Header) *httptest.ResponseRecorder {
req := withSession(httptest.NewRequest(http.MethodDelete, "/users/"+id, nil), "tok")
req.SetPathValue("id", id)
for key, values := range header {
req.Header[key] = values
}
rec := httptest.NewRecorder()
service.ManagedDeleteUser(rec, req)
return rec
}
if rec := del("2", nil); rec.Code != http.StatusOK {
t.Fatalf("delete status = %d", rec.Code)
}
if rec := del("1", nil); rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "superadmin") {
t.Fatalf("AuthGuard refusal status = %d, body %s; want it forwarded", rec.Code, rec.Body.String())
}
if rec := del("abc", nil); rec.Code != http.StatusBadRequest {
t.Fatalf("bad id status = %d, want 400", rec.Code)
}
before := len(guard.callsTo("DELETE /api/admin/users/2"))
if rec := del("2", http.Header{"Sec-Fetch-Site": {"cross-site"}}); rec.Code != http.StatusForbidden {
t.Fatalf("cross-site delete status = %d, want 403", rec.Code)
}
if len(guard.callsTo("DELETE /api/admin/users/2")) != before {
t.Fatal("a cross-site delete reached AuthGuard")
}
})
}
func TestLogoutForwardsTheTokenAndClearsCookies(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.handle("POST /api/logout", func(w http.ResponseWriter, _ map[string]any) {
http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: "", Path: "/", MaxAge: -1})
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{}`))
})
service, _ := guard.service(t)
rec := httptest.NewRecorder()
service.Logout(rec, withSession(httptest.NewRequest(http.MethodPost, "/auth/logout", nil), "tok"))
if rec.Code != http.StatusOK {
t.Fatalf("logout status = %d", rec.Code)
}
if calls := guard.callsTo("POST /api/logout"); len(calls) != 1 || calls[0].Authorization != "Bearer tok" {
t.Fatalf("logout calls = %+v", calls)
}
cleared := false
for _, cookie := range rec.Result().Cookies() {
if cookie.Name == "auth_session" && cookie.MaxAge < 0 {
cleared = true
}
}
if !cleared {
t.Fatalf("cookies = %v, want the session cookie cleared", rec.Result().Cookies())
}
guard.reply("POST /api/logout", http.StatusUnauthorized, map[string]any{"error": "expired"})
rec = httptest.NewRecorder()
service.Logout(rec, withSession(httptest.NewRequest(http.MethodPost, "/auth/logout", nil), "stale"))
if rec.Code != http.StatusOK {
t.Fatalf("logout of an expired session status = %d, want 200", rec.Code)
}
cross := withSession(httptest.NewRequest(http.MethodPost, "/auth/logout", nil), "tok")
cross.Header.Set("Sec-Fetch-Site", "cross-site")
rec = httptest.NewRecorder()
service.Logout(rec, cross)
if rec.Code != http.StatusForbidden {
t.Fatalf("cross-site logout status = %d, want 403", rec.Code)
}
}
func TestGatingMiddlewaresResolveSessionsThroughAuthGuard(t *testing.T) {
guard := newFakeAuthGuard(t)
roles := map[string]string{"user-tok": "user", "admin-tok": "admin", "mod-tok": "moderator"}
service, _ := guard.service(t)
served := func(role string) {
guard.reply("GET /api/me", http.StatusOK, map[string]any{"user": map[string]any{"id": 5, "username": "u", "role": role}})
}
ok := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) })
run := func(mw func(http.Handler) http.Handler, token string) int {
req := httptest.NewRequest(http.MethodGet, "/x", nil)
if token != "" {
withSession(req, token)
}
rec := httptest.NewRecorder()
mw(ok).ServeHTTP(rec, req)
return rec.Code
}
guard.reply("GET /api/me", http.StatusUnauthorized, map[string]any{"error": "no session"})
if code := run(service.Require, ""); code != http.StatusUnauthorized {
t.Fatalf("Require without a cookie = %d, want 401", code)
}
if code := run(service.Require, "stale"); code != http.StatusUnauthorized {
t.Fatalf("Require with an expired session = %d, want 401", code)
}
for token, role := range roles {
served(role)
wantAdmin := http.StatusForbidden
if role == "admin" || role == "moderator" {
wantAdmin = http.StatusNoContent
}
wantManager := http.StatusForbidden
if role == "admin" {
wantManager = http.StatusNoContent
}
if code := run(service.Require, token); code != http.StatusNoContent {
t.Errorf("Require as %s = %d, want 204", role, code)
}
if code := run(service.RequireAdmin, token); code != wantAdmin {
t.Errorf("RequireAdmin as %s = %d, want %d", role, code, wantAdmin)
}
if code := run(service.RequireUserManager, token); code != wantManager {
t.Errorf("RequireUserManager as %s = %d, want %d", role, code, wantManager)
}
}
guard.server.Close()
if code := run(service.Require, "any-token"); code != http.StatusInternalServerError {
t.Fatalf("Require with AuthGuard down = %d, want 500", code)
}
}
func TestMeReportsTheSessionUserAndLoginRequirement(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("GET /api/me", http.StatusOK, map[string]any{"user": map[string]any{"id": 5, "username": "u", "email": "u@example.com", "role": "user"}})
service, store := guard.service(t)
rec := httptest.NewRecorder()
service.Me(rec, withSession(httptest.NewRequest(http.MethodGet, "/auth/me", nil), "tok"))
body := decodeBody(t, rec)
if rec.Code != http.StatusOK || body["authRequired"] != true || body["user"].(map[string]any)["username"] != "u" {
t.Fatalf("me status = %d, body %v", rec.Code, body)
}
// The login setting is cached for a moment, so the second answer comes from a fresh Service.
service, store = guard.service(t)
store.loginRequired = false
rec = httptest.NewRecorder()
service.Me(rec, httptest.NewRequest(http.MethodGet, "/auth/me", nil))
body = decodeBody(t, rec)
if body["authRequired"] != false || body["user"].(map[string]any)["username"] != "Admin" {
t.Fatalf("me with login off = %v, want the local admin and authRequired false", body)
}
}
+143 -3
View File
@@ -4,7 +4,10 @@ import (
"context"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
)
// fakeProxyStore is a minimal in-memory ProxyStore for constructing a
@@ -95,7 +98,10 @@ func TestLoginDisabledUsesAdminIdentityWithoutCredentials(t *testing.T) {
}
}
func TestInternalLoginOverrideWorksWithNoOpStore(t *testing.T) {
// TestNoOpStoreDoesNotKeepAProcessLocalLoginOverride checks that the login-required setting is read
// from the store on each call. A store that discards writes keeps login required everywhere, rather
// than letting one process diverge from the rest.
func TestNoOpStoreDoesNotKeepAProcessLocalLoginOverride(t *testing.T) {
store := &noOpLoginProxyStore{fakeProxyStore: fakeProxyStore{loginRequired: true}}
service := NewWithStore(store, "session", false, "", "testproject")
if err := service.SetLoginRequired(context.Background(), false); err != nil {
@@ -103,8 +109,142 @@ func TestInternalLoginOverrideWorksWithNoOpStore(t *testing.T) {
}
user, err := service.CurrentUser(httptest.NewRequest(http.MethodGet, "/", nil))
if err != nil || user == nil || user.Username != "Admin" {
t.Fatalf("no-op store override resolved user=%+v err=%v, want Admin", user, err)
if err != nil || user != nil {
t.Fatalf("no-op store resolved user=%+v err=%v, want no user while login is still required", user, err)
}
}
// TestBodylessStateChangesRefuseCrossSite checks the routes that take no JSON body, which
// decodeProxyJSON cannot guard, refuse a request the browser marks as cross-site.
func TestBodylessStateChangesRefuseCrossSite(t *testing.T) {
service := NewWithStore(&fakeProxyStore{loginRequired: true}, "session", false, "", "testproject")
handlers := map[string]http.HandlerFunc{
"logout": service.Logout,
"totp initiate": service.TOTPInitiate,
"delete user": service.ManagedDeleteUser,
}
for name, handler := range handlers {
req := httptest.NewRequest(http.MethodPost, "/", nil)
req.Header.Set("Sec-Fetch-Site", "cross-site")
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusForbidden {
t.Errorf("%s with Sec-Fetch-Site: cross-site returned %d, want 403", name, rec.Code)
}
}
}
func TestSetLoginRequiredNeedsAStore(t *testing.T) {
service := NewWithStore(nil, "session", false, "", "testproject")
if err := service.SetLoginRequired(context.Background(), false); err == nil {
t.Fatal("SetLoginRequired with no store succeeded, want an error")
}
}
func TestDecodeProxyJSONRequiresAJSONBodyAndRefusesCrossSite(t *testing.T) {
decode := func(contentType, fetchSite string) error {
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"loginRequired":true}`))
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
if fetchSite != "" {
req.Header.Set("Sec-Fetch-Site", fetchSite)
}
var input struct {
LoginRequired bool `json:"loginRequired"`
}
return decodeProxyJSON(req, &input)
}
if err := decode("application/json", ""); err != nil {
t.Fatalf("application/json body refused: %v", err)
}
if err := decode("application/json; charset=utf-8", "same-site"); err != nil {
t.Fatalf("same-site application/json body refused: %v", err)
}
for _, contentType := range []string{"", "text/plain", "application/x-www-form-urlencoded", "multipart/form-data; boundary=x"} {
if err := decode(contentType, ""); err == nil {
t.Errorf("Content-Type %q accepted, want refused", contentType)
}
}
if err := decode("application/json", "cross-site"); err == nil {
t.Error("cross-site application/json body accepted, want refused")
}
}
func TestSignupIsRefusedWhileLoginIsNotRequired(t *testing.T) {
store := &fakeProxyStore{loginRequired: false}
service := NewWithStore(store, "session", false, "", "testproject")
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"email":"a@b.com","username":"a","password":"password123"}`))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
service.Signup(rec, req)
if rec.Code != http.StatusConflict {
t.Fatalf("signup with login off status = %d, want 409", rec.Code)
}
if store.setupClaimed {
t.Fatal("refused signup still claimed the setup flag")
}
}
func TestLoginIsRateLimitedPerAccount(t *testing.T) {
service := NewWithStore(&fakeProxyStore{loginRequired: true}, "session", false, "", "testproject")
post := func() int {
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"identifier":"Victim","password":"guess"}`))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
service.Login(rec, req)
return rec.Code
}
for i := 0; i < loginAccountLimit; i++ {
if code := post(); code == http.StatusTooManyRequests {
t.Fatalf("attempt %d refused before the limit", i+1)
}
}
if code := post(); code != http.StatusTooManyRequests {
t.Fatalf("attempt past the limit status = %d, want 429", code)
}
}
func TestAttemptLimiterWindowAndTableBound(t *testing.T) {
now := time.Now()
limiter := newAttemptLimiter(time.Minute, 2)
if !limiter.allow("k", now) || !limiter.allow("k", now) {
t.Fatal("attempts within the limit were refused")
}
if limiter.allow("k", now) {
t.Fatal("attempt past the limit was allowed")
}
if !limiter.allow("k", now.Add(time.Minute)) {
t.Fatal("limit did not reset after the window")
}
full := newAttemptLimiter(time.Hour, 1)
for i := 0; i < maxTrackedAttemptKeys; i++ {
full.allow(strconv.Itoa(i), now)
}
if full.allow("new-key", now) {
t.Fatal("a new key was tracked past the table bound")
}
}
func TestValidateProxyPasswordRefusesMoreThan72Bytes(t *testing.T) {
if err := validateProxyPassword(strings.Repeat("a", 72)); err != nil {
t.Fatalf("72-byte password refused: %v", err)
}
if err := validateProxyPassword(strings.Repeat("a", 73)); err == nil {
t.Fatal("73-byte password accepted, want refused")
}
if err := validateProxyPassword(strings.Repeat("é", 40)); err == nil {
t.Fatal("80-byte multi-byte password accepted, want refused")
}
}
func TestNormalizeProxyUsernameRefusesAt(t *testing.T) {
if _, err := normalizeProxyUsername("name@example.com"); err == nil {
t.Fatal("username containing @ accepted")
}
if got, err := normalizeProxyUsername(" plain "); err != nil || got != "plain" {
t.Fatalf("plain username = %q, %v", got, err)
}
}
+59
View File
@@ -0,0 +1,59 @@
package auth
import (
"sync"
"time"
)
// Attempt limits for the credential endpoints (login and the TOTP verify/disable routes). Each key
// may make limit attempts per window; further attempts are refused until the window ends. The
// counters live in this process, and AuthGuard's own limits still apply on top.
const (
attemptWindow = 15 * time.Minute
loginAccountLimit = 10
loginClientLimit = 200
totpAttemptLimit = 5
maxTrackedAttemptKeys = 10000
)
type attemptCounter struct {
windowStart time.Time
count int
}
// attemptLimiter is a fixed-window counter keyed by an account, a client address or a user.
type attemptLimiter struct {
mu sync.Mutex
window time.Duration
limit int
counts map[string]attemptCounter
}
func newAttemptLimiter(window time.Duration, limit int) *attemptLimiter {
return &attemptLimiter{window: window, limit: limit, counts: make(map[string]attemptCounter)}
}
// allow records one attempt for key at time now and reports whether it is within the limit. When
// the table is full of live keys, a new key is refused rather than tracked, so flooding distinct
// keys cannot grow memory without bound.
func (l *attemptLimiter) allow(key string, now time.Time) bool {
l.mu.Lock()
defer l.mu.Unlock()
counter, tracked := l.counts[key]
if !tracked && len(l.counts) >= maxTrackedAttemptKeys {
for existing, state := range l.counts {
if now.Sub(state.windowStart) >= l.window {
delete(l.counts, existing)
}
}
if len(l.counts) >= maxTrackedAttemptKeys {
return false
}
}
if counter.windowStart.IsZero() || now.Sub(counter.windowStart) >= l.window {
counter = attemptCounter{windowStart: now}
}
counter.count++
l.counts[key] = counter
return counter.count <= l.limit
}
+130 -6
View File
@@ -7,6 +7,7 @@ import (
"context"
"errors"
"fmt"
"log"
"strings"
"time"
@@ -66,6 +67,17 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
return errors.New("auth postgres pool is nil")
}
// Only a table that predates the role column needs its oldest account promoted, so the
// promotion below runs once, in the migration that adds the column.
var roleColumnMissing bool
if err := pool.QueryRow(ctx, `
SELECT NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = current_schema() AND table_name = 'auth_users' AND column_name = 'role'
)`).Scan(&roleColumnMissing); err != nil {
return fmt.Errorf("check auth schema: %w", err)
}
_, err := pool.Exec(ctx, `
CREATE TABLE IF NOT EXISTS auth_users (
id BIGSERIAL PRIMARY KEY,
@@ -89,9 +101,6 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
-- alone does not count, only a successful POST /api/login) and has no
-- DEFAULT, unlike every other column here.
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_login_at TIMESTAMPTZ;
UPDATE auth_users SET role = 'superadmin'
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
ON auth_users (lower(email)) WHERE email <> '';
@@ -109,6 +118,20 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
return fmt.Errorf("ensure auth schema: %w", err)
}
if err := ensureUsernameCaseIndex(ctx, pool); err != nil {
return err
}
if roleColumnMissing {
if _, err := pool.Exec(ctx, `
UPDATE auth_users SET role = 'superadmin'
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
`); err != nil {
return fmt.Errorf("promote oldest auth user: %w", err)
}
}
if options.SingleUser {
if _, err := pool.Exec(ctx, `
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
@@ -153,6 +176,47 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
return nil
}
// ensureUsernameCaseIndex makes usernames unique ignoring case, so "Admin" and "admin" cannot both
// be registered. The index is created only while no such pair exists: a database that already
// holds one still starts, logs the clashing names, and gets the index on the first start after an
// operator has renamed or removed one of each pair.
func ensureUsernameCaseIndex(ctx context.Context, pool *pgxpool.Pool) error {
rows, err := pool.Query(ctx, `
SELECT min(username) FROM auth_users GROUP BY lower(username) HAVING count(*) > 1
ORDER BY 1 LIMIT 10
`)
if err != nil {
return fmt.Errorf("check duplicate usernames: %w", err)
}
var clashing []string
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
rows.Close()
return fmt.Errorf("check duplicate usernames: %w", err)
}
clashing = append(clashing, name)
}
rows.Close()
if err := rows.Err(); err != nil {
return fmt.Errorf("check duplicate usernames: %w", err)
}
if len(clashing) > 0 {
log.Printf("[auth] usernames that differ only by case exist (%q); the case-insensitive username index was not created. Rename or remove one account of each pair and restart.", clashing)
return nil
}
if _, err := pool.Exec(ctx, `CREATE UNIQUE INDEX IF NOT EXISTS auth_users_username_lower_idx ON auth_users (lower(username))`); err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
// An account was registered between the check and the index build; the next start retries.
log.Printf("[auth] the case-insensitive username index was not created because a clashing username was just added: %v", err)
return nil
}
return fmt.Errorf("ensure username index: %w", err)
}
return nil
}
// TOTPState is the private provisioning state for one account. Secret must
// never be included in an API response.
type TOTPState struct {
@@ -176,15 +240,25 @@ func (s *Store) GetTOTPState(ctx context.Context, userID int64) (TOTPState, erro
return state, nil
}
// SetTOTPSecret stores a pending secret without enabling two-factor auth.
// SetTOTPSecret stores a pending secret without enabling two-factor auth. It refuses while TOTP is
// already enabled, so a replaced secret cannot silently switch the second factor off.
func (s *Store) SetTOTPSecret(ctx context.Context, userID int64, secret string) error {
if err := s.validate(); err != nil {
return err
}
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2`, secret, userID)
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)
if err != nil {
return fmt.Errorf("set TOTP secret: %w", err)
}
if tag.RowsAffected() == 0 {
state, err := s.GetTOTPState(ctx, userID)
if err != nil {
return err
}
if state.Enabled {
return ErrTOTPAlreadyEnabled
}
}
return nil
}
@@ -230,6 +304,9 @@ func (s *Store) CreateUser(ctx context.Context, username, email, passwordHash st
if err := s.validate(); err != nil {
return nil, err
}
if err := validateCredentials(username, passwordHash); err != nil {
return nil, err
}
var user User
err := s.pool.QueryRow(ctx, `
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
@@ -255,10 +332,19 @@ func (s *Store) FindByIdentifier(ctx context.Context, identifier string) (*User,
if err := s.validate(); err != nil {
return nil, err
}
// Usernames are tried before emails, so an identifier resolves to one account in a fixed order.
user, err := s.find(ctx, `
SELECT id, username, email, password_hash, role, created_at, updated_at, last_login_at
FROM auth_users
WHERE username = $1
`, identifier)
if err != nil || user != nil {
return user, err
}
return s.find(ctx, `
SELECT id, username, email, password_hash, role, created_at, updated_at, last_login_at
FROM auth_users
WHERE username = $1 OR lower(email) = lower($1)
WHERE lower(email) = lower($1)
`, identifier)
}
@@ -278,12 +364,19 @@ func (s *Store) UpdateCredentials(ctx context.Context, id int64, username, email
if err := s.validate(); err != nil {
return err
}
if err := validateCredentials(username, passwordHash); err != nil {
return err
}
_, err := s.pool.Exec(ctx, `
UPDATE auth_users
SET username = $1, email = $2, password_hash = $3, updated_at = now()
WHERE id = $4
`, username, email, passwordHash, id)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return ErrUserExists
}
return fmt.Errorf("update auth credentials: %w", err)
}
return nil
@@ -319,6 +412,9 @@ func (s *Store) CreateManagedUser(ctx context.Context, username, email, password
if err := s.validate(); err != nil {
return nil, err
}
if err := validateCredentials(username, passwordHash); err != nil {
return nil, err
}
role = NormalizeRole(string(role))
var user User
err := s.pool.QueryRow(ctx, `
@@ -343,6 +439,9 @@ func (s *Store) UpdateUser(ctx context.Context, id int64, username, email, passw
if err := s.validate(); err != nil {
return err
}
if err := validateCredentials(username, passwordHash); err != nil {
return err
}
if role == nil {
return s.UpdateCredentials(ctx, id, username, email, passwordHash)
}
@@ -353,6 +452,10 @@ func (s *Store) UpdateUser(ctx context.Context, id int64, username, email, passw
WHERE id = $5
`, username, email, passwordHash, *role, id)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return ErrUserExists
}
return fmt.Errorf("update managed auth user: %w", err)
}
return nil
@@ -627,6 +730,27 @@ func (s *Store) IsProjectAllowed(ctx context.Context, userID int64, project stri
var ErrUserExists = errors.New("auth user already exists")
// ErrTOTPAlreadyEnabled is returned by SetTOTPSecret while two-factor auth is on.
var ErrTOTPAlreadyEnabled = errors.New("auth: TOTP is already enabled; disable it before setting a new secret")
// ErrEmptyPasswordHash is returned when a credential write has no password hash.
var ErrEmptyPasswordHash = errors.New("auth: password hash is required")
// ErrInvalidUsername is returned for a username containing "@", which would be read as an email.
var ErrInvalidUsername = errors.New("auth: username cannot contain @")
// validateCredentials refuses a credential write that would leave an account without a password
// hash, or that stores a username which could be mistaken for another account's email.
func validateCredentials(username, passwordHash string) error {
if passwordHash == "" {
return ErrEmptyPasswordHash
}
if strings.Contains(username, "@") {
return ErrInvalidUsername
}
return nil
}
func (s *Store) validate() error {
if s == nil || s.pool == nil {
return errors.New("auth store has no postgres pool")
@@ -2,10 +2,13 @@ package auth
import (
"context"
"errors"
"os"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
)
@@ -119,3 +122,135 @@ func TestStoreIntegration(t *testing.T) {
t.Fatalf("FindByID() after UpdateLastLogin = %+v, want LastLoginAt set", afterLogin)
}
}
// openScratchStore opens DATABASE_URL (a scratch database, see TestStoreIntegration), applies the
// schema and removes every account before and after the test.
func openScratchStore(t *testing.T) (context.Context, *pgxpool.Pool, *Store) {
t.Helper()
url := os.Getenv("DATABASE_URL")
if url == "" {
t.Skip("DATABASE_URL not set; skipping Postgres integration test")
}
ctx := context.Background()
pool, err := postgres.Open(ctx, postgres.DefaultConfig(url))
if err != nil {
t.Fatalf("open pool: %v", err)
}
t.Cleanup(pool.Close)
if err := EnsureSchema(ctx, pool, SchemaOptions{SingleUser: false}); err != nil {
t.Fatalf("EnsureSchema() error = %v", err)
}
store := NewStore(pool)
if err := store.DeleteAllUsers(ctx); err != nil {
t.Fatalf("DeleteAllUsers() (pre-test cleanup) error = %v", err)
}
t.Cleanup(func() {
if err := store.DeleteAllUsers(context.Background()); err != nil {
t.Logf("cleanup: DeleteAllUsers() error = %v", err)
}
})
return ctx, pool, store
}
// TestStoreRefusesUsernamesThatDifferOnlyByCase covers the unique index on lower(username).
func TestStoreRefusesUsernamesThatDifferOnlyByCase(t *testing.T) {
ctx, _, store := openScratchStore(t)
hash, err := HashPassword("correct horse battery staple")
if err != nil {
t.Fatal(err)
}
if _, err := store.CreateUser(ctx, "Admin", "", hash); err != nil {
t.Fatalf("CreateUser(Admin) error = %v", err)
}
if _, err := store.CreateUser(ctx, "admin", "", hash); !errors.Is(err, ErrUserExists) {
t.Fatalf("CreateUser(admin) error = %v, want ErrUserExists", err)
}
if _, err := store.CreateManagedUser(ctx, "ADMIN", "", hash, RoleUser); !errors.Is(err, ErrUserExists) {
t.Fatalf("CreateManagedUser(ADMIN) error = %v, want ErrUserExists", err)
}
bob, err := store.CreateUser(ctx, "bob", "", hash)
if err != nil {
t.Fatalf("CreateUser(bob) error = %v", err)
}
if err := store.UpdateCredentials(ctx, bob.ID, "admin", "", hash); !errors.Is(err, ErrUserExists) {
t.Fatalf("UpdateCredentials(admin) error = %v, want ErrUserExists", err)
}
role := RoleUser
if err := store.UpdateUser(ctx, bob.ID, "Admin", "", hash, &role); !errors.Is(err, ErrUserExists) {
t.Fatalf("UpdateUser(Admin) error = %v, want ErrUserExists", err)
}
}
// TestEnsureSchemaStartsWithExistingCaseVariantUsernames checks that a database already holding
// "Admin" and "admin" still starts, gets no index, and gets one after the pair is resolved.
func TestEnsureSchemaStartsWithExistingCaseVariantUsernames(t *testing.T) {
ctx, pool, store := openScratchStore(t)
if _, err := pool.Exec(ctx, `DROP INDEX IF EXISTS auth_users_username_lower_idx`); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `INSERT INTO auth_users (username, password_hash) VALUES ('Admin', 'x'), ('admin', 'x')`); err != nil {
t.Fatal(err)
}
indexExists := func() bool {
var exists bool
if err := pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM pg_indexes WHERE indexname = 'auth_users_username_lower_idx')`).Scan(&exists); err != nil {
t.Fatal(err)
}
return exists
}
if err := EnsureSchema(ctx, pool, SchemaOptions{SingleUser: false}); err != nil {
t.Fatalf("EnsureSchema() with clashing usernames error = %v, want it to start", err)
}
if indexExists() {
t.Fatal("the case-insensitive index was created over clashing usernames")
}
if err := store.DeleteAllUsers(ctx); err != nil {
t.Fatal(err)
}
if err := EnsureSchema(ctx, pool, SchemaOptions{SingleUser: false}); err != nil {
t.Fatalf("EnsureSchema() after cleanup error = %v", err)
}
if !indexExists() {
t.Fatal("the case-insensitive index was not created once the clash was gone")
}
}
// TestStoreTOTPAndIdentifierPrimitives covers SetTOTPSecret refusing to replace an enabled second
// factor and FindByIdentifier trying usernames before emails.
func TestStoreTOTPAndIdentifierPrimitives(t *testing.T) {
ctx, pool, store := openScratchStore(t)
hash, err := HashPassword("correct horse battery staple")
if err != nil {
t.Fatal(err)
}
owner, err := store.CreateUser(ctx, "owner", "owner@example.com", hash)
if err != nil {
t.Fatal(err)
}
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 err := store.SetTOTPSecret(ctx, owner.ID, "OTHERSECRET"); !errors.Is(err, ErrTOTPAlreadyEnabled) {
t.Fatalf("SetTOTPSecret() while enabled error = %v, want ErrTOTPAlreadyEnabled", err)
}
if state, err := store.GetTOTPState(ctx, owner.ID); err != nil || !state.Enabled || state.Secret != "JBSWY3DPEHPK3PXP" {
t.Fatalf("TOTP state after a refused replace = %+v, %v; want the original secret still enabled", state, err)
}
// A username equal to another account's email (a row written outside the store's validation)
// resolves to the username's own account, not to the email's owner.
if _, err := pool.Exec(ctx, `INSERT INTO auth_users (username, email, password_hash) VALUES ('owner@example.com', 'second@example.com', 'x')`); err != nil {
t.Fatal(err)
}
found, err := store.FindByIdentifier(ctx, "owner@example.com")
if err != nil || found == nil || found.Username != "owner@example.com" {
t.Fatalf("FindByIdentifier() = %+v, %v; want the account whose username matches", found, err)
}
if err := store.UpdateCredentials(ctx, owner.ID, "owner", "owner@example.com", ""); !errors.Is(err, ErrEmptyPasswordHash) {
t.Fatalf("UpdateCredentials() with an empty hash error = %v, want ErrEmptyPasswordHash", err)
}
}
+28 -1
View File
@@ -1,6 +1,7 @@
package auth
import (
"errors"
"strings"
"testing"
"time"
@@ -19,7 +20,7 @@ func TestPasswordRoundTrip(t *testing.T) {
if VerifyPassword(hash, "wrong password") {
t.Fatal("VerifyPassword() accepted the wrong password")
}
if cost, err := bcrypt.Cost([]byte(hash)); err != nil || cost != BcryptCost {
if cost, err := bcrypt.Cost([]byte(strings.TrimPrefix(hash, bcryptScheme))); err != nil || cost != BcryptCost {
t.Fatalf("bcrypt cost = %d, error = %v; want %d", cost, err, BcryptCost)
}
}
@@ -67,3 +68,29 @@ func TestResetManagerExpiresCode(t *testing.T) {
t.Fatal("Confirm() accepted an expired reset code")
}
}
func TestValidateCredentialsRefusesEmptyHashAndAtUsername(t *testing.T) {
if err := validateCredentials("alice", ""); !errors.Is(err, ErrEmptyPasswordHash) {
t.Fatalf("empty hash error = %v, want ErrEmptyPasswordHash", err)
}
if err := validateCredentials("alice@example.com", "hash"); !errors.Is(err, ErrInvalidUsername) {
t.Fatalf("@ username error = %v, want ErrInvalidUsername", err)
}
if err := validateCredentials("alice", "hash"); err != nil {
t.Fatalf("valid credentials refused: %v", err)
}
}
func TestHashPasswordUsesTheSharedBcryptCost(t *testing.T) {
hash, err := HashPassword("correct horse battery staple")
if err != nil {
t.Fatal(err)
}
cost, err := bcrypt.Cost([]byte(strings.TrimPrefix(hash, bcryptScheme)))
if err != nil {
t.Fatal(err)
}
if cost != BcryptCost {
t.Fatalf("bcrypt cost = %d, want %d", cost, BcryptCost)
}
}