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

+3 -3
View File
@@ -5,12 +5,12 @@ services, not application-specific SQL or HTTP handlers.
- `config` — environment string, required value, boolean, integer, and duration helpers.
- `postgres` — validated `DATABASE_URL` configuration, `pgxpool` creation/ping, transaction wrapper, and PostgreSQL error classification.
- `auth` — shared bcrypt policy, secure token generation/hashing, account/session schema, and account/session persistence.
- `authclient` — HTTP client and `net/http` middleware for services that adopt the centralized AuthServer instead of embedding `auth` against their own database.
- `auth` — versioned bcrypt password hashes (`HashPassword` writes a `bcrypt$` prefix; `VerifyAndUpgradePassword` rewrites older hashes on login), trusted-proxy client addresses (`ParseTrustedProxies` reads `TRUSTED_PROXIES`, a comma-separated CIDR list; `X-Forwarded-For` is honoured only from those peers), secure token generation/hashing, account/session schema (usernames are unique ignoring case once no clashing pair exists), account/session persistence, and attempt limits on the login and TOTP routes (per account and per client address, held in process memory).
- `authclient` — HTTP client and `net/http` middleware for services that adopt the centralized AuthServer instead of embedding `auth` against their own database. `WithClientIP(ctx, ip)` makes the credential calls send the end user's address as `X-Forwarded-For`; AuthServer reads it only from peers in its own `TRUSTED_PROXIES`.
- `migrate` — embedded filesystem adapter for Goose migrations.
- `logshipper` — client adapter for OmniLogger (Web/OmniLogger): batches and ships log entries centrally while mirroring the same human-readable output and Debug/Info/Warn/Error/Critical/Audit/*Ctx method surface as each project's local internal/logging package.
Run `go test ./...` and `go vet ./...` from this directory. The module path is
Run `go test ./...` and `go vet ./...` from this directory. Tests that need PostgreSQL skip themselves unless `DATABASE_URL` (auth store) or `SHARED_TEST_DATABASE_URL` (platform users, mediacore, migrate) names a scratch database; use `go test -p 1 ./...` when both are set. The module path is
`repos.gfranz.ch/Gabriel20xx/shared/backend`; change it if the shared folder is
hosted under a different repository path.
+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)
}
}
+52 -6
View File
@@ -68,7 +68,9 @@ type Client struct {
// restrictions can be enforced. Empty means "don't identify" - the
// caller is treated as unrestricted; see AuthServer's project-scoping
// feature and WithProjectKey.
projectKey string
projectKey string
validationMu sync.Mutex
validationCache map[[32]byte]validationCacheEntry
}
// ProjectKeyHeader is the header Client attaches to every request identifying
@@ -112,9 +114,10 @@ func WithProjectKey(key string) Option {
// is always left as-is, overriding the inference.
func New(baseURL string, opts ...Option) *Client {
c := &Client{
baseURL: normalizeBaseURL(baseURL),
httpClient: &http.Client{Timeout: 5 * time.Second},
cookieName: DefaultCookieName,
baseURL: normalizeBaseURL(baseURL),
httpClient: &http.Client{Timeout: 5 * time.Second},
cookieName: DefaultCookieName,
validationCache: make(map[[32]byte]validationCacheEntry),
}
for _, opt := range opts {
opt(c)
@@ -138,6 +141,7 @@ func (c *Client) SetBaseURL(baseURL string) {
c.baseURLMu.Lock()
c.baseURL = normalized
c.baseURLMu.Unlock()
c.clearValidationCache()
}
func (c *Client) getBaseURL() string {
@@ -155,6 +159,33 @@ func (c *Client) setProjectKeyHeader(req *http.Request) {
}
}
// ForwardedForHeader carries the end user's address to AuthServer on the
// credential calls (see WithClientIP). AuthServer reads it only when the
// calling service's own address is listed in its TRUSTED_PROXIES, so sending
// it changes nothing for a deployment that has not opted in.
const ForwardedForHeader = "X-Forwarded-For"
type clientIPKey struct{}
// WithClientIP returns a context that makes Login, Register, TOTPVerify,
// TOTPDisable and the password-reset calls send ip as X-Forwarded-For, so
// AuthServer's per-address limits see the end user instead of this service.
// Pass an address the caller has already verified (for example
// auth.Service's trusted-proxy-aware client address), never a raw request
// header. Anything that is not an IP address is ignored.
func WithClientIP(ctx context.Context, ip string) context.Context {
return context.WithValue(ctx, clientIPKey{}, strings.TrimSpace(ip))
}
// setClientIPHeader attaches ForwardedForHeader when ctx carries a valid
// address from WithClientIP; a no-op otherwise.
func setClientIPHeader(ctx context.Context, req *http.Request) {
ip, _ := ctx.Value(clientIPKey{}).(string)
if parsed := net.ParseIP(ip); parsed != nil {
req.Header.Set(ForwardedForHeader, parsed.String())
}
}
func normalizeBaseURL(baseURL string) string {
trimmed := strings.TrimRight(strings.TrimSpace(baseURL), "/")
if trimmed == "" {
@@ -211,6 +242,9 @@ func (c *Client) Validate(ctx context.Context, token string) (*User, error) {
if token == "" {
return nil, ErrInvalidSession
}
if user, cachedErr, ok := c.cachedValidation(token); ok {
return user, cachedErr
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/api/session/validate", nil)
if err != nil {
@@ -233,15 +267,22 @@ func (c *Client) Validate(ctx context.Context, token string) (*User, error) {
}
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
if resp.StatusCode == http.StatusUnauthorized {
c.cacheValidation(token, nil, false)
return nil, ErrInvalidSession
}
return nil, fmt.Errorf("authclient: decode AuthServer response: %w", err)
}
if resp.StatusCode != http.StatusOK || !payload.Valid {
if resp.StatusCode == http.StatusUnauthorized || (resp.StatusCode == http.StatusOK && !payload.Valid) {
c.cacheValidation(token, nil, false)
return nil, ErrInvalidSession
}
return &User{ID: payload.UserID, Username: payload.Username, Role: payload.Role}, nil
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("authclient: AuthServer returned HTTP %d", resp.StatusCode)
}
user := &User{ID: payload.UserID, Username: payload.Username, Role: payload.Role}
c.cacheValidation(token, user, true)
return user, nil
}
// contextKey is unexported so only this package can set/read the resolved
@@ -451,6 +492,7 @@ func (c *Client) call(ctx context.Context, method, path, token string, body, out
req.Header.Set("Authorization", "Bearer "+token)
}
c.setProjectKeyHeader(req)
setClientIPHeader(ctx, req)
resp, err := c.httpClient.Do(req)
if err != nil {
@@ -535,6 +577,7 @@ func (c *Client) Logout(ctx context.Context, token string) ([]*http.Cookie, erro
if err != nil {
return nil, err
}
c.invalidateValidation(token)
return resp.Cookies(), nil
}
@@ -623,6 +666,9 @@ func (c *Client) CreateManagedUser(ctx context.Context, token string, input Mana
// UpdateManagedUser calls PUT /api/admin/users/{id}.
func (c *Client) UpdateManagedUser(ctx context.Context, token string, id int64, input ManagedUserInput) error {
_, err := c.call(ctx, http.MethodPut, fmt.Sprintf("/api/admin/users/%d", id), token, input, nil)
if err == nil {
c.invalidateValidation(token)
}
return err
}
+40
View File
@@ -110,3 +110,43 @@ func TestSetBaseURLIgnoresBlank(t *testing.T) {
t.Fatalf("SetBaseURL(blank) changed baseURL to %q, want unchanged", got)
}
}
func TestWithClientIPSendsXForwardedForOnCredentialCalls(t *testing.T) {
var seen []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
seen = append(seen, r.Header.Get(ForwardedForHeader))
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"user":{"id":1,"username":"a"}}`))
}))
defer server.Close()
client := New(server.URL)
ctx := WithClientIP(context.Background(), " 203.0.113.9 ")
if _, err := client.Login(ctx, "a", "password123", ""); err != nil {
t.Fatal(err)
}
if _, err := client.Register(WithClientIP(context.Background(), "2001:db8::1"), "a", "a@b.com", "password123"); err != nil {
t.Fatal(err)
}
if err := client.TOTPVerify(ctx, "tok", "123456"); err != nil {
t.Fatal(err)
}
// No address, and values that are not IP addresses, send no header.
if _, err := client.Login(context.Background(), "a", "password123", ""); err != nil {
t.Fatal(err)
}
for _, bad := range []string{"", "not-an-ip", "203.0.113.9\r\nX-Evil: 1"} {
if _, err := client.Login(WithClientIP(context.Background(), bad), "a", "password123", ""); err != nil {
t.Fatal(err)
}
}
want := []string{"203.0.113.9", "2001:db8::1", "203.0.113.9", "", "", "", ""}
if len(seen) != len(want) {
t.Fatalf("server saw %d requests, want %d", len(seen), len(want))
}
for i := range want {
if seen[i] != want[i] {
t.Errorf("request %d X-Forwarded-For = %q, want %q", i, seen[i], want[i])
}
}
}
@@ -0,0 +1,78 @@
package authclient
import (
"crypto/sha256"
"time"
)
const (
validationCacheTTL = 2 * time.Second
maxValidationCacheSize = 10000
)
type validationCacheEntry struct {
user User
valid bool
expires time.Time
}
func (c *Client) cachedValidation(token string) (*User, error, bool) {
key := sha256.Sum256([]byte(token))
now := time.Now()
c.validationMu.Lock()
defer c.validationMu.Unlock()
entry, ok := c.validationCache[key]
if !ok {
return nil, nil, false
}
if !now.Before(entry.expires) {
delete(c.validationCache, key)
return nil, nil, false
}
if !entry.valid {
return nil, ErrInvalidSession, true
}
user := entry.user
return &user, nil, true
}
func (c *Client) cacheValidation(token string, user *User, valid bool) {
key := sha256.Sum256([]byte(token))
now := time.Now()
c.validationMu.Lock()
defer c.validationMu.Unlock()
if c.validationCache == nil {
c.validationCache = make(map[[32]byte]validationCacheEntry)
}
if len(c.validationCache) >= maxValidationCacheSize {
for existing, entry := range c.validationCache {
if !now.Before(entry.expires) {
delete(c.validationCache, existing)
}
}
if len(c.validationCache) >= maxValidationCacheSize {
for existing := range c.validationCache {
delete(c.validationCache, existing)
break
}
}
}
entry := validationCacheEntry{valid: valid, expires: now.Add(validationCacheTTL)}
if user != nil {
entry.user = *user
}
c.validationCache[key] = entry
}
func (c *Client) invalidateValidation(token string) {
key := sha256.Sum256([]byte(token))
c.validationMu.Lock()
delete(c.validationCache, key)
c.validationMu.Unlock()
}
func (c *Client) clearValidationCache() {
c.validationMu.Lock()
c.validationCache = make(map[[32]byte]validationCacheEntry)
c.validationMu.Unlock()
}
@@ -457,6 +457,30 @@ func thumbnailFile(id string) (string, error) {
return id + ".jpg", nil
}
// validName reports an error unless name can be used as one path segment: it must not be empty,
// ".", ".." or contain a path separator. Every push and delete helper checks its name with this.
func validName(name string) error {
if name == "" || name == "." || name == ".." || strings.ContainsAny(name, `/\`) {
return fmt.Errorf("invalid name %q", name)
}
return nil
}
// validRelativeName is validName for outputs, inputs and copies, which may sit in nested
// directories (for example CraftStudio's "<user>/<workflow>/<file>"). It refuses an empty or
// absolute name, a backslash, and any empty, "." or ".." segment.
func validRelativeName(name string) error {
if name == "" || strings.HasPrefix(name, "/") || strings.ContainsRune(name, '\\') {
return fmt.Errorf("invalid name %q", name)
}
for _, segment := range strings.Split(name, "/") {
if segment == "" || segment == "." || segment == ".." {
return fmt.Errorf("invalid name %q", name)
}
}
return nil
}
// thumbnailPaths lists every CarrierNode path a thumbnail may live at, in lookup order: the
// project's thumbnails mount first, then CarrierNode's legacy thumbnail root. Thumbnails
// stored before the mount existed sit in the legacy root, and reads keep finding them there
@@ -670,6 +694,9 @@ func pushedSize(response *http.Response) int64 {
// PushThumbnail uploads a locally-generated thumbnail to CarrierNode.
func (c *Client) PushThumbnail(ctx context.Context, id, localPath string) (int64, error) {
if err := validName(id); err != nil {
return 0, err
}
response, err := c.push(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath)
if err != nil {
return 0, err
@@ -680,6 +707,9 @@ func (c *Client) PushThumbnail(ctx context.Context, id, localPath string) (int64
// DeleteThumbnail removes a thumbnail from CarrierNode. A 404 is treated as
// already-deleted, not an error. Always targets the primary instance.
func (c *Client) DeleteThumbnail(ctx context.Context, id string) error {
if err := validName(id); err != nil {
return err
}
request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil)
if err != nil {
return err
@@ -698,6 +728,9 @@ func (c *Client) DeleteThumbnail(ctx context.Context, id string) error {
// PushOutput uploads a locally-produced output file (e.g. a converted or
// generated media file) to CarrierNode's OutputRoot.
func (c *Client) PushOutput(ctx context.Context, name, localPath string) (int64, error) {
if err := validRelativeName(name); err != nil {
return 0, err
}
response, err := c.push(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
@@ -707,6 +740,9 @@ func (c *Client) PushOutput(ctx context.Context, name, localPath string) (int64,
// PushInput uploads a local file to CarrierNode's InputRoot.
func (c *Client) PushInput(ctx context.Context, name, localPath string) (int64, error) {
if err := validRelativeName(name); err != nil {
return 0, err
}
response, err := c.push(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
@@ -716,6 +752,9 @@ func (c *Client) PushInput(ctx context.Context, name, localPath string) (int64,
// PushCopy uploads a local file to CarrierNode's CopyRoot.
func (c *Client) PushCopy(ctx context.Context, name, localPath string) (int64, error) {
if err := validRelativeName(name); err != nil {
return 0, err
}
response, err := c.push(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
@@ -181,3 +181,58 @@ func TestThumbnailIDsCannotEscapeTheThumbnailsDirectory(t *testing.T) {
t.Fatalf("invalid thumbnail ids reached CarrierNode: %v", got)
}
}
// TestPushAndDeleteNamesCannotEscapeTheirDirectory checks that the push and delete helpers refuse
// names that are "." or ".." or contain a separator before any request reaches CarrierNode.
func TestPushAndDeleteNamesCannotEscapeTheirDirectory(t *testing.T) {
client, node := newThumbnailTestClient(t, nil)
ctx := context.Background()
local := filepath.Join(t.TempDir(), "payload.bin")
if err := os.WriteFile(local, []byte("x"), 0o600); err != nil {
t.Fatal(err)
}
for _, name := range []string{"", ".", "..", "../escape", `..\escape`, "nested/name"} {
if _, err := client.PushThumbnail(ctx, name, local); err == nil {
t.Errorf("PushThumbnail accepted name %q", name)
}
if err := client.DeleteThumbnail(ctx, name); err == nil {
t.Errorf("DeleteThumbnail accepted name %q", name)
}
}
// Outputs, inputs and copies may nest, but no segment may climb out of its directory.
for _, name := range []string{"", ".", "..", "../escape", `..\escape`, "/abs", "a//b", "a/../b", "a/./b", "a/"} {
if _, err := client.PushOutput(ctx, name, local); err == nil {
t.Errorf("PushOutput accepted name %q", name)
}
if _, err := client.PushInput(ctx, name, local); err == nil {
t.Errorf("PushInput accepted name %q", name)
}
if _, err := client.PushCopy(ctx, name, local); err == nil {
t.Errorf("PushCopy accepted name %q", name)
}
}
if got := node.seen(); len(got) != 0 {
t.Fatalf("invalid names reached CarrierNode: %v", got)
}
}
// TestNestedOutputNamesAreAccepted checks that CraftStudio-style nested output names pass the
// relative-name check, so generator outputs keep their CarrierNode path.
func TestNestedOutputNamesAreAccepted(t *testing.T) {
for _, name := range []string{"CraftStudio/alice/flux/out.png", "a/b.txt"} {
if err := validRelativeName(name); err != nil {
t.Errorf("validRelativeName(%q) = %v, want nil", name, err)
}
}
}
// TestValidNamesAreNotRefused checks that ordinary names, including ones with spaces or query
// characters, pass the name check; the path escaping in MountPath and the push helpers handles them.
func TestValidNamesAreNotRefused(t *testing.T) {
for _, name := range []string{"clip.mp4", "my clip?.mp4", "a#b", "v1.2.final"} {
if err := validName(name); err != nil {
t.Errorf("validName(%q) = %v, want nil", name, err)
}
}
}
+57
View File
@@ -0,0 +1,57 @@
package config
import (
"testing"
"time"
)
func TestStringTrimsAndFallsBack(t *testing.T) {
t.Setenv("CFG_TEST_STRING", " value ")
if got := String("CFG_TEST_STRING", "fallback"); got != "value" {
t.Fatalf("String = %q, want the trimmed value", got)
}
t.Setenv("CFG_TEST_STRING", " ")
if got := String("CFG_TEST_STRING", "fallback"); got != "fallback" {
t.Fatalf("String of a blank value = %q, want the fallback", got)
}
if got := String("CFG_TEST_UNSET", "fallback"); got != "fallback" {
t.Fatalf("String of an unset variable = %q, want the fallback", got)
}
}
func TestRequiredNamesTheMissingVariable(t *testing.T) {
t.Setenv("CFG_TEST_REQUIRED", " secret ")
if got, err := Required("CFG_TEST_REQUIRED"); err != nil || got != "secret" {
t.Fatalf("Required = %q, %v; want the trimmed value", got, err)
}
t.Setenv("CFG_TEST_REQUIRED", " ")
if _, err := Required("CFG_TEST_REQUIRED"); err == nil || err.Error() != "CFG_TEST_REQUIRED is required" {
t.Fatalf("Required of a blank value error = %v, want it to name the variable", err)
}
}
func TestBoolIntAndDurationFallBackOnInvalidValues(t *testing.T) {
t.Setenv("CFG_TEST_BOOL", "true")
t.Setenv("CFG_TEST_INT", " 42 ")
t.Setenv("CFG_TEST_DURATION", "1m30s")
if !Bool("CFG_TEST_BOOL", false) || Int("CFG_TEST_INT", 0) != 42 || Duration("CFG_TEST_DURATION", 0) != 90*time.Second {
t.Fatal("valid values were not parsed")
}
t.Setenv("CFG_TEST_BOOL", "maybe")
t.Setenv("CFG_TEST_INT", "4x")
t.Setenv("CFG_TEST_DURATION", "soon")
if !Bool("CFG_TEST_BOOL", true) || Bool("CFG_TEST_BOOL", false) {
t.Fatal("an invalid boolean did not fall back")
}
if Int("CFG_TEST_INT", 7) != 7 || Duration("CFG_TEST_DURATION", time.Second) != time.Second {
t.Fatal("an invalid integer or duration did not fall back")
}
t.Setenv("CFG_TEST_BOOL", "")
t.Setenv("CFG_TEST_INT", "")
t.Setenv("CFG_TEST_DURATION", "")
if !Bool("CFG_TEST_BOOL", true) || Int("CFG_TEST_INT", 7) != 7 || Duration("CFG_TEST_DURATION", time.Second) != time.Second {
t.Fatal("an empty value did not fall back")
}
}
+25 -1
View File
@@ -11,8 +11,11 @@
package coreconfig
import (
"crypto/subtle"
"encoding/json"
"errors"
"net/http"
"net/url"
"strings"
"sync"
)
@@ -179,7 +182,7 @@ func normalizeInfo(info Info) Info {
// own internal-auth-gated routes use).
func Handler(secret string, store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if secret == "" || r.Header.Get("X-Internal-Auth") != secret {
if secret == "" || subtle.ConstantTimeCompare([]byte(r.Header.Get("X-Internal-Auth")), []byte(secret)) != 1 {
writeError(w, http.StatusUnauthorized, "internal service authentication required")
return
}
@@ -188,6 +191,10 @@ func Handler(secret string, store *Store) http.HandlerFunc {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
if err := validateServiceURLs(input); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
store.Set(input)
// Do not echo service credentials to the caller. The push is authenticated, but
// these credentials are needed only by the recipient.
@@ -198,6 +205,23 @@ func Handler(secret string, store *Store) http.HandlerFunc {
}
}
// validateServiceURLs refuses a pushed URL that is not an http or https URL with a host, so a push
// cannot point this service's clients at another scheme or at an empty host.
func validateServiceURLs(info Info) error {
urls := append([]string{info.AuthGuardURL, info.ComfyUIURL, info.ProjectConfiguratorURL, info.ContentScannerURL, info.CarrierNodeURL}, info.CarrierNodeURLs...)
for _, raw := range urls {
value := strings.TrimSpace(raw)
if value == "" {
continue
}
parsed, err := url.Parse(value)
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
return errors.New("core service URL must be an http or https URL with a host")
}
}
return nil
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
@@ -149,3 +149,26 @@ func TestHandlerAppliesPushedInfo(t *testing.T) {
t.Fatal("response echoed the ContentScanner secret")
}
}
func TestHandlerRejectsNonHTTPURLsWithoutChangingStore(t *testing.T) {
store := NewStore(Info{AuthGuardURL: "http://auth.example.com"})
handler := Handler("s3cret", store)
for _, bad := range []Info{
{AuthGuardURL: "javascript:alert(1)"},
{AuthGuardURL: "auth.example.com"},
{CarrierNodeURLs: []string{"http://carrier.example.com", "file:///etc/passwd"}},
{ContentScannerURL: "http://"},
} {
body, _ := json.Marshal(bad)
req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body))
req.Header.Set("X-Internal-Auth", "s3cret")
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d for %+v, want 400", rec.Code, bad)
}
}
if got := store.Get(); got.AuthGuardURL != "http://auth.example.com" || len(got.CarrierNodeURLs) != 0 {
t.Fatalf("store changed by a rejected push: %+v", got)
}
}
+1 -1
View File
@@ -18,5 +18,5 @@ require (
github.com/sethvargo/go-retry v0.4.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/text v0.40.0 // indirect
golang.org/x/text v0.41.0 // indirect
)
+2
View File
@@ -46,6 +46,8 @@ golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+300
View File
@@ -0,0 +1,300 @@
package logshipper
import (
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"time"
)
// captureStd runs fn with os.Stdout and os.Stderr redirected, and returns what it wrote to each.
func captureStd(t *testing.T, fn func()) (stdout, stderr string) {
t.Helper()
oldOut, oldErr := os.Stdout, os.Stderr
outR, outW, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
errR, errW, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
os.Stdout, os.Stderr = outW, errW
defer func() { os.Stdout, os.Stderr = oldOut, oldErr }()
fn()
outW.Close()
errW.Close()
os.Stdout, os.Stderr = oldOut, oldErr
outBytes, _ := io.ReadAll(outR)
errBytes, _ := io.ReadAll(errR)
return string(outBytes), string(errBytes)
}
// ingest is a stand-in OmniLogger that records every batch it is sent.
type ingest struct {
mu sync.Mutex
batches [][]wireEntry
auth []string
status int
server *httptest.Server
}
func newIngest(t *testing.T, status int) *ingest {
t.Helper()
in := &ingest{status: status}
in.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var batch []wireEntry
_ = json.NewDecoder(r.Body).Decode(&batch)
in.mu.Lock()
in.batches = append(in.batches, batch)
in.auth = append(in.auth, r.Method+" "+r.URL.Path+" "+r.Header.Get("Authorization"))
in.mu.Unlock()
w.WriteHeader(in.status)
}))
t.Cleanup(in.server.Close)
return in
}
func (in *ingest) entries() []wireEntry {
in.mu.Lock()
defer in.mu.Unlock()
var all []wireEntry
for _, batch := range in.batches {
all = append(all, batch...)
}
return all
}
// newTestShipper keeps the background loop quiet so a test decides when entries are sent, and
// points a shipper that names no sink at a throwaway one so closing it prints nothing.
func newTestShipper(t *testing.T, cfg Config) *Shipper {
t.Helper()
if cfg.FlushInterval == 0 {
cfg.FlushInterval = time.Hour
}
if cfg.BaseURL == "" {
cfg.BaseURL = newIngest(t, http.StatusAccepted).server.URL
}
return New(cfg)
}
func TestLevelOfAcceptsTheSharedLogVocabulary(t *testing.T) {
cases := map[string]Level{
"debug": LevelDebug, " DEBUG ": LevelDebug, "info": LevelInfo, "": LevelInfo, "bogus": LevelInfo,
"warn": LevelWarn, "warning": LevelWarn, "error": LevelError, "critical": LevelCritical,
"silent": LevelSilent, "none": LevelSilent, "off": LevelSilent,
}
for input, want := range cases {
if got := levelOf(input); got != want {
t.Errorf("levelOf(%q) = %d, want %d", input, got, want)
}
}
}
func TestSevNameGivesTheLowercaseNameOmniLoggerExpects(t *testing.T) {
for sev, want := range map[Level][2]string{
LevelDebug: {"DEBUG", "debug"}, LevelInfo: {"INFO", "info"}, LevelWarn: {"WARN", "warn"},
LevelError: {"ERROR", "error"}, LevelCritical: {"CRITICAL", "critical"},
} {
if upper, lower := sevName(sev); upper != want[0] || lower != want[1] {
t.Errorf("sevName(%d) = %q, %q; want %q, %q", sev, upper, lower, want[0], want[1])
}
}
}
func TestFormatArgsJoinsErrorsStringsAndValues(t *testing.T) {
got := formatArgs([]any{"failed:", errors.New("boom"), 42, map[string]int{"a": 1}, make(chan int)})
if !strings.HasPrefix(got, `failed: boom 42 {"a":1} `) {
t.Fatalf("formatArgs = %q", got)
}
if formatArgs(nil) != "" {
t.Fatal("formatArgs(nil) is not empty")
}
}
func TestScrubIDsDropsIdentifierFieldsFromTheLocalDump(t *testing.T) {
ctx := map[string]any{
"id": 1, "userId": 2, "user_id": 3, "requestID": "r", "path": "/x", "status": 200, "ok": true,
}
got := scrubIDs(ctx)
if len(got) != 3 || got["path"] != "/x" || got["status"] != 200 || got["ok"] != true {
t.Fatalf("scrubIDs = %v, want only path, status and ok", got)
}
if len(ctx) != 7 {
t.Fatal("scrubIDs modified its input")
}
}
func TestEmitGatesOnTheThresholdAndWritesTheLocalLine(t *testing.T) {
shipper := newTestShipper(t, Config{Service: "svc", Module: "mod", Level: "warn"})
defer shipper.Close()
stdout, stderr := captureStd(t, func() {
shipper.Info("below threshold")
shipper.Warn("warned")
shipper.Error("failed", errors.New("boom"))
})
if stdout != "" {
t.Fatalf("stdout = %q, want nothing", stdout)
}
if strings.Contains(stderr, "below threshold") || !strings.Contains(stderr, "[WARN] [mod] warned") || !strings.Contains(stderr, "[ERROR] [mod] failed boom") {
t.Fatalf("stderr = %q", stderr)
}
if got := len(shipper.buffer); got != 2 {
t.Fatalf("buffered %d entries, want the 2 at or above the threshold", got)
}
}
func TestSilentLevelWritesAndBuffersNothing(t *testing.T) {
shipper := newTestShipper(t, Config{Service: "svc", Level: "silent"})
defer shipper.Close()
stdout, stderr := captureStd(t, func() {
shipper.Critical("never shown")
})
if stdout != "" || stderr != "" || len(shipper.buffer) != 0 {
t.Fatalf("silent shipper wrote %q / %q and buffered %d entries", stdout, stderr, len(shipper.buffer))
}
}
func TestLogAllScrubsIDsLocallyButShipsTheFullContext(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc", LogAll: true})
defer shipper.Close()
stdout, _ := captureStd(t, func() {
shipper.InfoCtx(map[string]any{"userId": 7, "path": "/x"}, "request")
})
if !strings.Contains(stdout, `[DETAILS] {"path":"/x"}`) || strings.Contains(stdout, "userId") {
t.Fatalf("local dump = %q, want the ID scrubbed", stdout)
}
shipper.Flush()
entries := in.entries()
if len(entries) != 1 || !strings.Contains(string(entries[0].Context), `"userId":7`) {
t.Fatalf("shipped entries = %+v, want the unscrubbed context", entries)
}
}
func TestAuditShipsAnInfoEntryWithTheDetails(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc"})
defer shipper.Close()
captureStd(t, func() { shipper.Audit("login", map[string]any{"user": "a"}) })
shipper.Flush()
entries := in.entries()
if len(entries) != 1 || entries[0].Level != "info" || !strings.HasPrefix(entries[0].Message, "audit:login") {
t.Fatalf("entries = %+v", entries)
}
}
func TestFlushSendsOneAuthenticatedBatchAndEmptiesTheBuffer(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{BaseURL: in.server.URL + "/", IngestToken: "secret", Service: "svc"})
defer shipper.Close()
captureStd(t, func() {
shipper.Info("one")
shipper.Error("two")
})
shipper.Flush()
shipper.Flush() // nothing left: no second request
in.mu.Lock()
defer in.mu.Unlock()
if len(in.batches) != 1 || len(in.batches[0]) != 2 {
t.Fatalf("batches = %+v, want one batch of two entries", in.batches)
}
if in.auth[0] != "POST /api/logs Bearer secret" {
t.Fatalf("request = %q", in.auth[0])
}
first := in.batches[0][0]
if first.Service != "svc" || first.Level != "info" || first.Message != "one" || first.OccurredAt.IsZero() {
t.Fatalf("first entry = %+v", first)
}
}
func TestBufferDropsNewEntriesOnceFullInsteadOfBlocking(t *testing.T) {
shipper := newTestShipper(t, Config{Service: "svc", BufferCapacity: 3, MaxBatchSize: 1000})
defer shipper.Close()
_, stderr := captureStd(t, func() {
for i := 0; i < 10; i++ {
shipper.enqueue(wireEntry{Message: "m"})
}
})
if len(shipper.buffer) != 3 {
t.Fatalf("buffer holds %d entries, want the capacity of 3", len(shipper.buffer))
}
if strings.Count(stderr, "buffer full") != 1 {
t.Fatalf("stderr = %q, want the full-buffer warning exactly once", stderr)
}
}
func TestReachingTheBatchSizeFlushesWithoutWaitingForTheInterval(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc", MaxBatchSize: 2})
defer shipper.Close()
captureStd(t, func() {
shipper.Info("a")
shipper.Info("b")
})
deadline := time.Now().Add(5 * time.Second)
for len(in.entries()) < 2 {
if time.Now().After(deadline) {
t.Fatal("a full batch was not flushed ahead of the interval")
}
time.Sleep(10 * time.Millisecond)
}
}
func TestCloseFlushesWhatIsLeft(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc"})
captureStd(t, func() { shipper.Info("last words") })
if err := shipper.Close(); err != nil {
t.Fatal(err)
}
if err := shipper.Close(); err != nil {
t.Fatalf("second Close error = %v", err)
}
if entries := in.entries(); len(entries) != 1 || entries[0].Message != "last words" {
t.Fatalf("entries after Close = %+v", entries)
}
}
func TestAFailingSinkNeverFailsTheCallerAndWarnsOnlyOnce(t *testing.T) {
in := newIngest(t, http.StatusInternalServerError)
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc"})
defer shipper.Close()
_, stderr := captureStd(t, func() {
shipper.Info("one")
shipper.Flush()
shipper.Info("two")
shipper.Flush()
})
if strings.Count(stderr, "OmniLogger rejected") != 1 {
t.Fatalf("stderr = %q, want one rate-limited warning", stderr)
}
in.server.Close()
_, stderr = captureStd(t, func() {
shipper.Info("three")
shipper.Flush() // the sink is gone: swallowed, and still inside the warning interval
})
if strings.Contains(stderr, "send 1 entries") {
t.Fatalf("stderr = %q, want the second warning suppressed", stderr)
}
}
func TestNewAppliesDefaults(t *testing.T) {
shipper := New(Config{BaseURL: "http://omni:8090///", IngestToken: "t", Service: "svc"})
defer shipper.Close()
if shipper.url != "http://omni:8090/api/logs" || shipper.module != "svc" || shipper.threshold != LevelInfo {
t.Fatalf("url = %q, module = %q, threshold = %d", shipper.url, shipper.module, shipper.threshold)
}
if shipper.maxBatch != defaultMaxBatchSize || shipper.bufCap != defaultBufferCapacity || shipper.client == nil {
t.Fatalf("defaults not applied: %+v", shipper)
}
}
+90 -11
View File
@@ -51,6 +51,10 @@ import (
"repos.gfranz.ch/Gabriel20xx/shared/backend/syncsocket"
)
// maxPlaylistReorderItems caps one reorder request. The reorder runs as a single statement, so the
// cap bounds its size; a playlist longer than this is reordered in more than one request.
const maxPlaylistReorderItems = 10000
// Config wires a Core to the rest of one service's dependencies.
type Config struct {
DB *pgxpool.Pool
@@ -157,6 +161,8 @@ func (c *Core) putSyncState(w http.ResponseWriter, r *http.Request) {
state["playAt"] = playAt
}
c.sync.SetHTTPState(sessionID, state)
// Broadcast queues immutable messages without waiting for network writes, so a slow
// websocket peer does not hold this response or create one goroutine per request.
c.sync.Broadcast(sessionID)
writeJSON(w, http.StatusOK, map[string]any{"success": true, "state": state})
}
@@ -194,7 +200,12 @@ func (c *Core) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, ide
writeError(w, http.StatusNotFound, "media not found")
return
}
c.carrierNode.Proxy(w, r, "/media/"+urlPath(record.FilePath))
upstream, ok := upstreamMediaPath(record.FilePath)
if !ok {
writeError(w, http.StatusNotFound, "media not found")
return
}
c.carrierNode.Proxy(w, r, "/media/"+upstream)
}
func (c *Core) thumbnailMediaByQuery(w http.ResponseWriter, r *http.Request) {
@@ -222,9 +233,9 @@ func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request,
SELECT t.id::text
FROM thumbnails t
JOIN media m ON m.id = t.media_id OR t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key)
WHERE m.media_key=$1 OR CAST(m.id AS TEXT)=$1
WHERE m.media_key=$1 OR m.id=$2
ORDER BY t.created_at DESC
LIMIT 1`, id).Scan(&thumbnailID); err == nil && SafeRelative(thumbnailID) {
LIMIT 1`, id, mediaIDArg(id)).Scan(&thumbnailID); err == nil && SafeRelative(thumbnailID) {
// A row whose file CarrierNode no longer has falls through to the original image below,
// rather than proxying CarrierNode's 404.
if c.carrierNode.ProxyThumbnail(w, r, c.serviceName, thumbnailID) {
@@ -236,7 +247,12 @@ func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request,
writeError(w, http.StatusNotFound, "thumbnail not found")
return
}
c.carrierNode.Proxy(w, r, "/media/"+urlPath(record.FilePath))
upstream, ok := upstreamMediaPath(record.FilePath)
if !ok {
writeError(w, http.StatusNotFound, "thumbnail not found")
return
}
c.carrierNode.Proxy(w, r, "/media/"+upstream)
}
func (c *Core) mediaState(w http.ResponseWriter, r *http.Request) {
@@ -390,9 +406,9 @@ func (c *Core) mediaLiked(w http.ResponseWriter, r *http.Request) {
func (c *Core) mediaTags(w http.ResponseWriter, r *http.Request) {
key := strings.TrimSpace(chi.URLParam(r, "id"))
rows, err := c.db.Query(r.Context(), `
SELECT tag, COALESCE(SUM(vote), 0) AS score
SELECT mt.tag, COALESCE(SUM(mv.vote), 0) AS score
FROM media_tags mt LEFT JOIN media_tag_votes mv ON mv.media_key = mt.media_key AND LOWER(mv.tag) = LOWER(mt.tag)
WHERE mt.media_key = $1 GROUP BY tag ORDER BY score DESC, LOWER(tag)`, key)
WHERE mt.media_key = $1 GROUP BY mt.tag ORDER BY score DESC, LOWER(mt.tag)`, key)
if err != nil {
writeJSON(w, http.StatusOK, map[string]any{"tags": []any{}})
return
@@ -723,8 +739,31 @@ func (c *Core) reorderPlaylist(w http.ResponseWriter, r *http.Request) {
if len(ids) == 0 {
ids = input.ItemIDs
}
for position, itemID := range ids {
_, _ = c.db.Exec(r.Context(), `UPDATE playlist_items SET position=$1 WHERE id=$2 AND playlist_id=$3 AND EXISTS (SELECT 1 FROM playlists WHERE id=$3 AND user_id=$4)`, position, itemID, id, user.ID)
if len(ids) > maxPlaylistReorderItems {
writeError(w, http.StatusBadRequest, "too many items to reorder")
return
}
positions := make([]int32, len(ids))
for position := range ids {
positions[position] = int32(position)
}
tx, err := c.db.Begin(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "could not reorder playlist")
return
}
defer func() { _ = tx.Rollback(r.Context()) }()
if _, err := tx.Exec(r.Context(), `
UPDATE playlist_items AS i SET position=v.position
FROM unnest($1::bigint[], $2::int[]) AS v(item_id, position)
WHERE i.id=v.item_id AND i.playlist_id=$3
AND EXISTS (SELECT 1 FROM playlists WHERE id=$3 AND user_id=$4)`, ids, positions, id, user.ID); err != nil {
writeError(w, http.StatusInternalServerError, "could not reorder playlist")
return
}
if err := tx.Commit(r.Context()); err != nil {
writeError(w, http.StatusInternalServerError, "could not reorder playlist")
return
}
writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist reordered"))
}
@@ -749,8 +788,8 @@ func canSeeHidden(r *http.Request) bool {
func (c *Core) isHiddenMedia(ctx context.Context, identifier string) bool {
var hidden bool
err := c.db.QueryRow(ctx, `
SELECT EXISTS (SELECT 1 FROM media WHERE NOT active AND (media_key=$1 OR CAST(id AS TEXT)=$1))`,
strings.TrimSpace(identifier)).Scan(&hidden)
SELECT EXISTS (SELECT 1 FROM media WHERE NOT active AND (media_key=$1 OR id=$2))`,
strings.TrimSpace(identifier), mediaIDArg(strings.TrimSpace(identifier))).Scan(&hidden)
return err != nil || hidden
}
@@ -765,7 +804,7 @@ 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 CAST(id AS TEXT)=$1) AND (active OR $2) LIMIT 1`, identifier, includeHidden)
FROM media WHERE (media_key=$1 OR id=$2) AND (active OR $3) LIMIT 1`, identifier, mediaIDArg(identifier), includeHidden)
var title, description string
var width, height int
var duration, size int64
@@ -1029,6 +1068,46 @@ func urlPath(value string) string {
return value
}
// upstreamMediaPath returns the escaped CarrierNode path for a stored file path. It reports false
// when the stored path is not a safe relative path, or when it contains a query or fragment marker
// that CarrierNode would read as the end of the path.
func upstreamMediaPath(filePath string) (string, bool) {
relative := urlPath(filePath)
if !SafeRelative(relative) || strings.ContainsAny(relative, "?#") {
return "", false
}
// Escape each segment so percent-escapes and other reserved characters in a stored name
// reach CarrierNode as literal text, not as an escape or a traversal it decodes later.
segments := strings.Split(relative, "/")
for i, segment := range segments {
segments[i] = url.PathEscape(segment)
}
return strings.Join(segments, "/"), true
}
// canonicalMediaID returns the numeric media id that identifier spells exactly. Leading zeros, signs
// and whitespace are not canonical, so they never match an id.
func canonicalMediaID(identifier string) (int64, bool) {
if identifier == "" || strings.Trim(identifier, "0123456789") != "" {
return 0, false
}
id, err := strconv.ParseInt(identifier, 10, 64)
if err != nil || strconv.FormatInt(id, 10) != identifier {
return 0, false
}
return id, true
}
// mediaIDArg is the id query argument for identifier: the id when identifier is a canonical number,
// otherwise NULL, which matches no row. Comparing the id column directly, instead of casting it to
// text, lets the planner use the primary-key index for the id arm.
func mediaIDArg(identifier string) any {
if id, ok := canonicalMediaID(identifier); ok {
return id
}
return nil
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
+101
View File
@@ -0,0 +1,101 @@
package mediacore
import (
"errors"
"os"
"path/filepath"
"testing"
)
func TestSafeRelativeRejectsTraversalAndAbsolutePaths(t *testing.T) {
for _, value := range []string{"", ".", "..", "../x", "a/../../x", "sub/../a.mp4x", "/etc/passwd", `\etc\passwd`, `C:\x`, "a\x00b"} {
if SafeRelative(value) {
t.Errorf("SafeRelative(%q) = true, want false", value)
}
}
for _, value := range []string{"a.mp4", "sub/b.mp4", "v1..2/clip.mp4"} {
if !SafeRelative(value) {
t.Errorf("SafeRelative(%q) = false, want true", value)
}
}
}
func TestResolveUnderRootsStaysInsideTheRoots(t *testing.T) {
root := t.TempDir()
if err := os.MkdirAll(filepath.Join(root, "sub"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "a.mp4"), []byte("a"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "sub", "b.mp4"), []byte("b"), 0o600); err != nil {
t.Fatal(err)
}
outside := filepath.Join(t.TempDir(), "secret.txt")
if err := os.WriteFile(outside, []byte("s"), 0o600); err != nil {
t.Fatal(err)
}
_ = os.Symlink(outside, filepath.Join(root, "link.txt"))
for value, want := range map[string]string{
"a.mp4": filepath.Join(root, "a.mp4"),
"/media/a.mp4": filepath.Join(root, "a.mp4"),
"sub/b.mp4": filepath.Join(root, "sub", "b.mp4"),
"/media/sub/b.mp4": filepath.Join(root, "sub", "b.mp4"),
} {
got, err := ResolveUnderRoots(value, []string{root})
if err != nil || got != want {
t.Errorf("ResolveUnderRoots(%q) = %q, %v; want %q", value, got, err, want)
}
}
for _, value := range []string{"../secret.txt", "sub", "missing.mp4", "link.txt", "", "a\x00b"} {
if _, err := ResolveUnderRoots(value, []string{root}); err == nil {
t.Errorf("ResolveUnderRoots(%q) resolved, want an error", value)
}
}
if _, err := ResolveUnderRoots("missing.mp4", []string{root}); !errors.Is(err, os.ErrNotExist) {
t.Errorf("missing file error = %v, want os.ErrNotExist", err)
}
}
func TestUpstreamMediaPathRefusesQueryFragmentAndTraversal(t *testing.T) {
for _, stored := range []string{"x?y.mp4", "a#b.mp4", "../x.mp4", "media/../../x.mp4", `..\x.mp4`} {
if _, ok := upstreamMediaPath(stored); ok {
t.Errorf("upstreamMediaPath(%q) accepted, want refused", stored)
}
}
}
func TestUpstreamMediaPathEscapesEachSegment(t *testing.T) {
cases := map[string]string{
"clips/clip.mp4": "clips/clip.mp4",
"my clip.mp4": "my%20clip.mp4",
"100%.mp4": "100%25.mp4",
"media/a b/c.mp4": "a%20b/c.mp4",
"/leading.mp4": "leading.mp4",
}
for stored, want := range cases {
got, ok := upstreamMediaPath(stored)
if !ok || got != want {
t.Errorf("upstreamMediaPath(%q) = %q, %v; want %q", stored, got, ok, want)
}
}
}
func TestCanonicalMediaIDAcceptsOnlyCanonicalDecimals(t *testing.T) {
for _, value := range []string{"", "007", "+1", "-1", "4a", " 4", "4 ", "99999999999999999999"} {
if id, ok := canonicalMediaID(value); ok {
t.Errorf("canonicalMediaID(%q) = %d, want refused", value, id)
}
}
if id, ok := canonicalMediaID("42"); !ok || id != 42 {
t.Errorf("canonicalMediaID(42) = %d, %v; want 42, true", id, ok)
}
if mediaIDArg("abc") != nil {
t.Error("mediaIDArg(non-numeric) is not NULL")
}
if mediaIDArg("42") != int64(42) {
t.Error("mediaIDArg(42) is not 42")
}
}
+483
View File
@@ -0,0 +1,483 @@
package mediacore
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"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/carriernodeclient"
"repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
"repos.gfranz.ch/Gabriel20xx/shared/backend/syncsocket"
)
// The tests in this file run the media routes against a real PostgreSQL database and a stand-in
// CarrierNode. They create the media tables and a few rows, so they are 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 ./mediacore/
const (
aliceID = 9101
bobID = 9102
modID = 9103
)
// newIdentityAuthGuard answers GET /api/me for three fixed sessions: two ordinary users and a moderator.
func newIdentityAuthGuard(t *testing.T) *httptest.Server {
t.Helper()
people := map[string]struct {
id int64
role string
}{"alice-token": {aliceID, "user"}, "bob-token": {bobID, "user"}, "mod-token": {modID, "moderator"}}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
person, ok := people[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")]
if !ok || r.URL.Path != "/api/me" {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"user":{"id":%d,"username":"u%d","role":%q}}`, person.id, person.id, person.role)
}))
t.Cleanup(server.Close)
return server
}
// stubCarrierNode serves a body for every /media/ path and 404s the rest, recording what it was asked.
type stubCarrierNode struct {
mu sync.Mutex
requests []string
}
func (n *stubCarrierNode) ServeHTTP(w http.ResponseWriter, r *http.Request) {
n.mu.Lock()
n.requests = append(n.requests, r.Method+" "+r.URL.EscapedPath())
n.mu.Unlock()
if !strings.HasPrefix(r.URL.Path, "/media/") {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/octet-stream")
if r.Method != http.MethodHead {
_, _ = io.WriteString(w, "BYTES")
}
}
func (n *stubCarrierNode) seen() []string {
n.mu.Lock()
defer n.mu.Unlock()
return append([]string(nil), n.requests...)
}
type dbHarness struct {
pool *pgxpool.Pool
router chi.Router
carrier *stubCarrierNode
hub *syncsocket.Hub
}
func newDBHarness(t *testing.T) *dbHarness {
t.Helper()
url := os.Getenv("SHARED_TEST_DATABASE_URL")
if url == "" {
t.Skip("SHARED_TEST_DATABASE_URL not set; skipping Postgres route tests")
}
ctx := context.Background()
pool, err := postgres.Open(ctx, postgres.DefaultConfig(url))
if err != nil {
t.Fatalf("open pool: %v", err)
}
t.Cleanup(pool.Close)
carrier := &stubCarrierNode{}
carrierServer := httptest.NewServer(carrier)
t.Cleanup(carrierServer.Close)
guard := newIdentityAuthGuard(t)
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject")
hub := syncsocket.NewHub()
core := New(Config{
DB: pool,
Auth: auth,
Sync: hub,
CarrierNode: carriernodeclient.New("", func(context.Context) string { return carrierServer.URL }),
ServiceName: "routes-test",
})
if err := core.Migrate(ctx); err != nil {
t.Fatalf("Migrate() error = %v", err)
}
cleanup := func() {
for _, statement := range []string{
`DELETE FROM playlists WHERE user_id IN (9101, 9102, 9103)`,
`DELETE FROM media_stats WHERE media_key LIKE 'rt-%' OR user_id IN (9101, 9102, 9103)`,
`DELETE FROM media_view_sessions WHERE media_key LIKE 'rt-%'`,
`DELETE FROM media_tag_votes WHERE media_key LIKE 'rt-%'`,
`DELETE FROM media_tags WHERE media_key LIKE 'rt-%'`,
`DELETE FROM media WHERE media_key LIKE 'rt-%'`,
`DELETE FROM users WHERE id IN (9101, 9102, 9103)`,
} {
if _, err := pool.Exec(ctx, statement); err != nil {
t.Fatalf("cleanup %q: %v", statement, err)
}
}
}
cleanup()
t.Cleanup(cleanup)
for _, id := range []int64{aliceID, bobID, modID} {
if _, err := pool.Exec(ctx, `INSERT INTO users (id, email, username, password_hash) VALUES ($1, $2, $3, 'x')`, id, fmt.Sprintf("rt%d@example.com", id), fmt.Sprintf("rt%d", id)); err != nil {
t.Fatalf("insert user: %v", err)
}
}
router := chi.NewRouter()
core.Mount(router)
return &dbHarness{pool: pool, router: router, carrier: carrier, hub: hub}
}
func (h *dbHarness) insertMedia(t *testing.T, key, mediaType, filePath string, active bool) {
t.Helper()
if _, err := h.pool.Exec(context.Background(), `INSERT INTO media (media_key, media_type, file_path, active) VALUES ($1, $2, $3, $4)`, key, mediaType, filePath, active); err != nil {
t.Fatalf("insert media %s: %v", key, err)
}
}
func (h *dbHarness) do(method, target, token, body string) *httptest.ResponseRecorder {
var reader io.Reader
if body != "" {
reader = strings.NewReader(body)
}
request := httptest.NewRequest(method, target, reader)
if token != "" {
request.AddCookie(&http.Cookie{Name: "auth_session", Value: token})
}
response := httptest.NewRecorder()
h.router.ServeHTTP(response, request)
return response
}
func decode(t *testing.T, response *httptest.ResponseRecorder) map[string]any {
t.Helper()
var out map[string]any
if err := json.Unmarshal(response.Body.Bytes(), &out); err != nil {
t.Fatalf("body %q is not JSON: %v", response.Body.String(), err)
}
return out
}
func dataOf(t *testing.T, response *httptest.ResponseRecorder) map[string]any {
t.Helper()
data, _ := decode(t, response)["data"].(map[string]any)
if data == nil {
t.Fatalf("response %s has no data object", response.Body.String())
}
return data
}
func TestMediaStreamAndThumbnailAgainstPostgres(t *testing.T) {
h := newDBHarness(t)
h.insertMedia(t, "rt-visible", "video", "folder/clip one.mp4", true)
h.insertMedia(t, "rt-hidden", "video", "secret.mp4", false)
h.insertMedia(t, "rt-image", "image", "pics/photo.jpg", true)
h.insertMedia(t, "rt-escape", "video", "../etc/passwd", true)
h.insertMedia(t, "rt-query", "video", "a?b.mp4", true)
var visibleID int64
if err := h.pool.QueryRow(context.Background(), `SELECT id FROM media WHERE media_key='rt-visible'`).Scan(&visibleID); err != nil {
t.Fatal(err)
}
t.Run("an anonymous caller is refused while login is required", func(t *testing.T) {
if code := h.do(http.MethodGet, "/media/stream?mediaKey=rt-visible", "", "").Code; code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401", code)
}
})
t.Run("a stored path reaches CarrierNode escaped, by key or by id, for GET and HEAD", func(t *testing.T) {
for _, target := range []string{"/media/stream?mediaKey=rt-visible", fmt.Sprintf("/media/stream?id=%d", visibleID)} {
response := h.do(http.MethodGet, target, "alice-token", "")
if response.Code != http.StatusOK || response.Body.String() != "BYTES" {
t.Fatalf("GET %s = %d %q, want the proxied bytes", target, response.Code, response.Body.String())
}
}
if response := h.do(http.MethodHead, "/media/stream?mediaKey=rt-visible", "alice-token", ""); response.Code != http.StatusOK || response.Body.Len() != 0 {
t.Fatalf("HEAD = %d with %d body bytes, want 200 and none", response.Code, response.Body.Len())
}
for _, request := range h.carrier.seen() {
if request != "GET /media/folder/clip%20one.mp4" && request != "HEAD /media/folder/clip%20one.mp4" {
t.Fatalf("CarrierNode saw %q, want the escaped stored path", request)
}
}
})
t.Run("unsafe stored paths and unknown keys are not found, and never reach CarrierNode", func(t *testing.T) {
before := len(h.carrier.seen())
for _, key := range []string{"rt-escape", "rt-query", "rt-missing", ""} {
if code := h.do(http.MethodGet, "/media/stream?mediaKey="+key, "alice-token", "").Code; code != http.StatusNotFound {
t.Errorf("stream of %q status = %d, want 404", key, code)
}
}
if got := len(h.carrier.seen()); got != before {
t.Fatalf("CarrierNode got %d extra requests, want none", got-before)
}
})
t.Run("hidden media is visible to moderators only", func(t *testing.T) {
for _, target := range []string{"/media/stream?mediaKey=rt-hidden", "/media/thumb?mediaKey=rt-hidden"} {
if code := h.do(http.MethodGet, target, "alice-token", "").Code; code != http.StatusNotFound {
t.Errorf("viewer GET %s = %d, want 404", target, code)
}
}
if response := h.do(http.MethodGet, "/media/stream?mediaKey=rt-hidden", "mod-token", ""); response.Code != http.StatusOK {
t.Errorf("moderator stream of hidden media = %d, want 200", response.Code)
}
})
t.Run("a thumbnail falls back to the original image, and only for images", func(t *testing.T) {
response := h.do(http.MethodGet, "/media/thumb?mediaKey=rt-image", "alice-token", "")
if response.Code != http.StatusOK || response.Body.String() != "BYTES" {
t.Fatalf("image thumbnail = %d %q, want the original image", response.Code, response.Body.String())
}
if code := h.do(http.MethodGet, "/media/thumb?mediaKey=rt-visible", "alice-token", "").Code; code != http.StatusNotFound {
t.Errorf("video without a thumbnail = %d, want 404", code)
}
if code := h.do(http.MethodGet, "/media/thumb?mediaKey=../x", "alice-token", "").Code; code != http.StatusBadRequest {
t.Errorf("unsafe thumbnail id = %d, want 400", code)
}
})
}
func TestMediaStatsAndViewsAgainstPostgres(t *testing.T) {
h := newDBHarness(t)
state := func(token string) map[string]any {
return dataOf(t, h.do(http.MethodGet, "/media/state?mediaKey=rt-stats", token, ""))
}
if code := h.do(http.MethodGet, "/media/state", "", "").Code; code != http.StatusBadRequest {
t.Fatalf("state without a key = %d, want 400", code)
}
for _, body := range []string{`{}`, `{"mediaKey":"rt-stats","bogus":1}`, `nope`} {
if code := h.do(http.MethodPost, "/media/like", "alice-token", body).Code; code != http.StatusBadRequest {
t.Errorf("like with %q = %d, want 400", body, code)
}
}
h.do(http.MethodPost, "/media/like", "alice-token", `{"mediaKey":"rt-stats"}`)
h.do(http.MethodPost, "/media/like", "alice-token", `{"mediaKey":"rt-stats"}`) // a repeat is not a second like
h.do(http.MethodPost, "/media/like", "bob-token", `{"mediaKey":"rt-stats","like":true}`)
h.do(http.MethodPost, "/media/save", "alice-token", `{"mediaKey":"rt-stats"}`)
if got := state("alice-token"); got["likeCount"] != float64(2) || got["saveCount"] != float64(1) || got["likedByUser"] != true || got["savedByUser"] != true {
t.Fatalf("state for alice = %v", got)
}
if got := state("bob-token"); got["likedByUser"] != true || got["savedByUser"] != false {
t.Fatalf("state for bob = %v", got)
}
if response := h.do(http.MethodPost, "/media/like", "alice-token", `{"mediaKey":"rt-stats","like":false}`); dataOf(t, response)["enabled"] != false {
t.Fatalf("unlike = %s", response.Body.String())
}
if got := state("alice-token"); got["likeCount"] != float64(1) || got["likedByUser"] != false {
t.Fatalf("state after unliking = %v", got)
}
h.do(http.MethodPost, "/media/like", "bob-token", `{"mediaKey":"rt-stats","value":false}`)
if got := state(""); got["likeCount"] != float64(0) {
t.Fatalf("anonymous state after both unlikes = %v", got)
}
h.do(http.MethodPost, "/media/like", "alice-token", `{"mediaKey":"rt-liked"}`)
liked := decode(t, h.do(http.MethodGet, "/media/liked", "alice-token", ""))["items"].([]any)
if len(liked) != 1 || liked[0].(map[string]any)["mediaKey"] != "rt-liked" {
t.Fatalf("liked = %v, want only rt-liked", liked)
}
// Views and watch sessions can be recorded without logging in.
if code := h.do(http.MethodPost, "/media/view?mediaKey=rt-stats", "", "").Code; code != http.StatusOK {
t.Fatalf("anonymous view = %d, want 200", code)
}
if code := h.do(http.MethodPost, "/media/view", "", "").Code; code != http.StatusBadRequest {
t.Fatalf("view without a key = %d, want 400", code)
}
if code := h.do(http.MethodPost, "/media/view-session", "", `{"mediaKey":"rt-stats","durationMs":1500}`).Code; code != http.StatusOK {
t.Fatalf("view session = %d, want 200", code)
}
for _, body := range []string{`{"mediaKey":"rt-stats"}`, `{"mediaKey":"rt-stats","durationMs":-3}`, `{"durationMs":10}`} {
if code := h.do(http.MethodPost, "/media/view-session", "", body).Code; code != http.StatusBadRequest {
t.Errorf("view session %q = %d, want 400", body, code)
}
}
if got := state(""); got["viewCount"] != float64(1) {
t.Fatalf("view count = %v, want 1", got["viewCount"])
}
}
func TestTagsAgainstPostgres(t *testing.T) {
h := newDBHarness(t)
for _, body := range []string{`{}`, `{"tag":" "}`, `{"tag":"` + strings.Repeat("x", 81) + `"}`, `nope`} {
if code := h.do(http.MethodPost, "/media/rt-tags/tags", "alice-token", body).Code; code != http.StatusBadRequest {
t.Errorf("add tag %q = %d, want 400", body, code)
}
}
if code := h.do(http.MethodPost, "/media/rt-tags/tags", "alice-token", `{"tag":"Funny"}`).Code; code != http.StatusCreated {
t.Fatalf("add tag = %d, want 201", code)
}
h.do(http.MethodPost, "/media/rt-tags/tags", "alice-token", `{"tag":"Funny"}`) // the same user's repeat is ignored
h.do(http.MethodPost, "/media/rt-tags/tags", "bob-token", `{"tag":"Quiet"}`)
for _, vote := range []string{"2", "-2", "\"up\""} {
if code := h.do(http.MethodPost, "/media/rt-tags/tags/Funny/vote", "alice-token", `{"vote":`+vote+`}`).Code; code != http.StatusBadRequest {
t.Errorf("vote %s = %d, want 400", vote, code)
}
}
h.do(http.MethodPost, "/media/rt-tags/tags/Funny/vote", "alice-token", `{"vote":1}`)
h.do(http.MethodPost, "/media/rt-tags/tags/Funny/vote", "bob-token", `{"vote":1}`)
h.do(http.MethodPost, "/media/rt-tags/tags/Quiet/vote", "alice-token", `{"vote":-1}`)
h.do(http.MethodPost, "/media/rt-tags/tags/Funny/vote", "bob-token", `{"vote":0}`) // clears bob's vote
tags := decode(t, h.do(http.MethodGet, "/media/rt-tags/tags", "", ""))["tags"].([]any)
if len(tags) != 2 {
t.Fatalf("tags = %v, want Funny and Quiet", tags)
}
first, second := tags[0].(map[string]any), tags[1].(map[string]any)
if first["tag"] != "Funny" || first["score"] != float64(1) || second["tag"] != "Quiet" || second["score"] != float64(-1) {
t.Fatalf("tags = %v, want Funny at 1 ahead of Quiet at -1", tags)
}
suggestions := decode(t, h.do(http.MethodGet, "/tags/suggestions?limit=5", "", ""))["tags"].([]any)
if len(suggestions) == 0 {
t.Fatal("suggestions are empty")
}
listed := decode(t, h.do(http.MethodGet, "/tags/funny/media?limit=10", "", ""))["items"].([]any)
if len(listed) != 1 || listed[0].(map[string]any)["mediaKey"] != "rt-tags" {
t.Fatalf("media for the tag = %v, want rt-tags (the tag matches ignoring case)", listed)
}
}
func TestPlaylistsAgainstPostgres(t *testing.T) {
h := newDBHarness(t)
create := func(token, name string) *httptest.ResponseRecorder {
return h.do(http.MethodPost, "/playlists", token, `{"name":`+fmt.Sprintf("%q", name)+`}`)
}
for _, name := range []string{"", " ", strings.Repeat("n", 121)} {
if code := create("alice-token", name).Code; code != http.StatusBadRequest {
t.Errorf("create %q = %d, want 400", name, code)
}
}
response := create("alice-token", "Road trip")
if response.Code != http.StatusCreated {
t.Fatalf("create = %d, body %s", response.Code, response.Body.String())
}
id := int64(dataOf(t, response)["playlist"].(map[string]any)["id"].(float64))
if again := create("alice-token", "Road trip"); int64(dataOf(t, again)["playlist"].(map[string]any)["id"].(float64)) != id {
t.Fatal("creating the same name again made a second playlist")
}
base := fmt.Sprintf("/playlists/%d", id)
// Another user cannot see, change or delete it.
if code := h.do(http.MethodGet, base, "bob-token", "").Code; code != http.StatusNotFound {
t.Errorf("bob reading alice's playlist = %d, want 404", code)
}
if code := h.do(http.MethodPost, base+"/items", "bob-token", `{"mediaKey":"rt-a"}`).Code; code != http.StatusNotFound {
t.Errorf("bob adding to alice's playlist = %d, want 404", code)
}
if code := h.do(http.MethodDelete, base, "bob-token", "").Code; code != http.StatusNotFound {
t.Errorf("bob deleting alice's playlist = %d, want 404", code)
}
if code := h.do(http.MethodGet, base+"/items", "", "").Code; code != http.StatusNotFound {
t.Errorf("anonymous items = %d, want 404", code)
}
if code := h.do(http.MethodPost, "/playlists/abc/items", "alice-token", `{"mediaKey":"rt-a"}`).Code; code != http.StatusBadRequest {
t.Errorf("bad playlist id = %d, want 400", code)
}
for _, key := range []string{"rt-a", "rt-b", "rt-c"} {
if code := h.do(http.MethodPost, base+"/items", "alice-token", `{"mediaKey":"`+key+`"}`).Code; code != http.StatusCreated {
t.Fatalf("add %s = %d, want 201", key, code)
}
}
h.do(http.MethodPost, base+"/items", "alice-token", `{"media_key":"rt-a"}`) // a repeat is ignored
if code := h.do(http.MethodPost, base+"/items", "alice-token", `{}`).Code; code != http.StatusBadRequest {
t.Errorf("add without a key = %d, want 400", code)
}
keys := func() []string {
var out []string
for _, item := range dataOf(t, h.do(http.MethodGet, base+"/items", "alice-token", ""))["items"].([]any) {
out = append(out, item.(map[string]any)["mediaKey"].(string))
}
return out
}
itemIDs := map[string]int64{}
for _, item := range dataOf(t, h.do(http.MethodGet, base+"/items", "alice-token", ""))["items"].([]any) {
entry := item.(map[string]any)
itemIDs[entry["mediaKey"].(string)] = int64(entry["id"].(float64))
}
if len(itemIDs) != 3 {
t.Fatalf("items = %v, want three distinct entries", itemIDs)
}
reorder := fmt.Sprintf(`{"ids":[%d,%d,%d]}`, itemIDs["rt-c"], itemIDs["rt-a"], itemIDs["rt-b"])
if code := h.do(http.MethodPatch, base+"/items/reorder", "alice-token", reorder).Code; code != http.StatusOK {
t.Fatalf("reorder = %d, want 200", code)
}
if got := strings.Join(keys(), ","); got != "rt-c,rt-a,rt-b" {
t.Fatalf("order after reorder = %s, want rt-c,rt-a,rt-b", got)
}
// The older field name still works, and another user's reorder changes nothing.
h.do(http.MethodPatch, base+"/items/reorder", "alice-token", fmt.Sprintf(`{"itemIds":[%d,%d,%d]}`, itemIDs["rt-b"], itemIDs["rt-c"], itemIDs["rt-a"]))
if got := strings.Join(keys(), ","); got != "rt-b,rt-c,rt-a" {
t.Fatalf("order after itemIds reorder = %s, want rt-b,rt-c,rt-a", got)
}
h.do(http.MethodPatch, base+"/items/reorder", "bob-token", reorder)
if got := strings.Join(keys(), ","); got != "rt-b,rt-c,rt-a" {
t.Fatalf("bob's reorder changed alice's playlist to %s", got)
}
tooMany := make([]string, maxPlaylistReorderItems+1)
for i := range tooMany {
tooMany[i] = "1"
}
if code := h.do(http.MethodPatch, base+"/items/reorder", "alice-token", `{"ids":[`+strings.Join(tooMany, ",")+`]}`).Code; code != http.StatusBadRequest {
t.Errorf("an oversized reorder = %d, want 400", code)
}
random := dataOf(t, h.do(http.MethodGet, base+"/random", "alice-token", ""))
if key, _ := random["mediaKey"].(string); key != "rt-a" && key != "rt-b" && key != "rt-c" {
t.Fatalf("random item = %v", random)
}
if code := h.do(http.MethodGet, base+"/random", "bob-token", "").Code; code != http.StatusNotFound {
t.Errorf("bob's random pick from alice's playlist = %d, want 404", code)
}
summary := dataOf(t, h.do(http.MethodGet, "/playlists/summary", "alice-token", ""))["playlists"].([]any)
if len(summary) != 1 || summary[0].(map[string]any)["item_count"] != float64(3) {
t.Fatalf("summary = %v, want one playlist with three items", summary)
}
if anonymous := dataOf(t, h.do(http.MethodGet, "/playlists/summary", "", ""))["playlists"].([]any); len(anonymous) != 0 {
t.Fatalf("anonymous summary = %v, want none", anonymous)
}
deleteBody := `{"mediaKey":"rt-a"}`
if code := h.do(http.MethodDelete, base+"/items", "bob-token", deleteBody).Code; code != http.StatusNotFound {
t.Errorf("bob removing alice's item = %d, want 404", code)
}
if code := h.do(http.MethodDelete, base+"/items", "alice-token", deleteBody).Code; code != http.StatusOK {
t.Errorf("alice removing her item = %d, want 200", code)
}
if code := h.do(http.MethodDelete, base+"/items", "alice-token", deleteBody).Code; code != http.StatusNotFound {
t.Errorf("removing it twice = %d, want 404", code)
}
if code := h.do(http.MethodDelete, base, "alice-token", "").Code; code != http.StatusOK {
t.Errorf("deleting the playlist = %d, want 200", code)
}
if code := h.do(http.MethodGet, base, "alice-token", "").Code; code != http.StatusNotFound {
t.Errorf("the deleted playlist = %d, want 404", code)
}
if listed := dataOf(t, h.do(http.MethodGet, "/playlists", "alice-token", ""))["playlists"].([]any); len(listed) != 0 {
t.Fatalf("playlists after deleting = %v, want none", listed)
}
}
+227
View File
@@ -0,0 +1,227 @@
package mediacore
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/coder/websocket"
"github.com/go-chi/chi/v5"
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
"repos.gfranz.ch/Gabriel20xx/shared/backend/syncsocket"
)
// TestSessionRoutesRefuseAnonymousRequests walks the route table: every route mounted behind
// Require answers 401 to a caller with no session, before any handler runs. The Core has no
// database, sync hub or CarrierNode client, so a request that got past the gate would panic.
func TestSessionRoutesRefuseAnonymousRequests(t *testing.T) {
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject")
router := chi.NewRouter()
New(Config{Auth: auth}).Mount(router)
for _, route := range []struct{ method, target string }{
{http.MethodGet, "/security/totp/status"},
{http.MethodGet, "/security/totp/initiate"},
{http.MethodPost, "/security/totp/verify"},
{http.MethodPost, "/security/totp/disable"},
{http.MethodPut, "/sync"},
{http.MethodPost, "/media/like"},
{http.MethodPost, "/media/save"},
{http.MethodGet, "/media/liked"},
{http.MethodPost, "/media/7/tags"},
{http.MethodPost, "/media/7/tags/funny/vote"},
{http.MethodGet, "/playlists"},
{http.MethodPost, "/playlists"},
{http.MethodDelete, "/playlists/3"},
{http.MethodPost, "/playlists/3/items"},
{http.MethodDelete, "/playlists/3/items"},
{http.MethodPatch, "/playlists/3/items/reorder"},
} {
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(route.method, route.target, strings.NewReader(`{}`)))
if response.Code != http.StatusUnauthorized {
t.Errorf("%s %s status = %d, want 401", route.method, route.target, response.Code)
}
}
}
// syncRouter mounts the sync routes on a Core with no database. Auth is disabled, so every caller
// is the placeholder administrator.
func syncRouter(hub *syncsocket.Hub) chi.Router {
auth := sharedauth.NewWithStore(loginOffStore{}, "session", false, "", "testproject", sharedauth.Disabled())
router := chi.NewRouter()
New(Config{Auth: auth, Sync: hub}).Mount(router)
return router
}
func putSync(router http.Handler, target, body string) *httptest.ResponseRecorder {
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodPut, target, strings.NewReader(body)))
return response
}
func TestPutSyncRejectsBadInput(t *testing.T) {
router := syncRouter(syncsocket.NewHub())
for name, body := range map[string]string{
"not JSON": `nope`,
"missing clientId": `{"mediaId":"m1"}`,
"blank clientId": `{"clientId":" ","mediaId":"m1"}`,
"object mediaId": `{"clientId":"c1","mediaId":{"a":1}}`,
"boolean mediaId": `{"clientId":"c1","mediaId":true}`,
"array playAt": `{"clientId":"c1","mediaId":"m1","playAt":[1]}`,
"object playAt": `{"clientId":"c1","mediaId":"m1","playAt":{"a":1}}`,
"clientId not text": `{"clientId":5,"mediaId":"m1"}`,
} {
if response := putSync(router, "/sync", body); response.Code != http.StatusBadRequest {
t.Errorf("%s: status = %d, want 400 (body %s)", name, response.Code, response.Body.String())
}
}
}
func TestPutSyncStoresBoundedStateThatGetSyncReturns(t *testing.T) {
hub := syncsocket.NewHub()
router := syncRouter(hub)
response := putSync(router, "/sync?sessionId=room-1", `{"clientId":"c1","mediaId":42,"timeMs":-5,"paused":true,"fps":100000,"frame":9,"playAt":"2026-10-19T10:00:00Z"}`)
if response.Code != http.StatusOK {
t.Fatalf("PUT status = %d, body %s", response.Code, response.Body.String())
}
var written struct {
Success bool `json:"success"`
State map[string]any `json:"state"`
}
if err := json.Unmarshal(response.Body.Bytes(), &written); err != nil || !written.Success {
t.Fatalf("PUT body = %s, %v", response.Body.String(), err)
}
state := written.State
if state["sessionId"] != "room-1" || state["fromClientId"] != "c1" || state["mediaId"] != float64(42) || state["paused"] != true {
t.Fatalf("state = %v", state)
}
if state["timeMs"] != float64(0) || state["fps"] != float64(240) || state["frame"] != float64(9) || state["playAt"] != "2026-10-19T10:00:00Z" {
t.Fatalf("a negative time was not clamped to 0, or fps to 240: %v", state)
}
get := httptest.NewRecorder()
router.ServeHTTP(get, httptest.NewRequest(http.MethodGet, "/sync?sessionId=room-1", nil))
var read map[string]any
if err := json.Unmarshal(get.Body.Bytes(), &read); err != nil || read["fromClientId"] != "c1" || read["mediaId"] != float64(42) {
t.Fatalf("GET /sync = %s, %v; want the stored state", get.Body.String(), err)
}
other := httptest.NewRecorder()
router.ServeHTTP(other, httptest.NewRequest(http.MethodGet, "/sync?sessionId=room-2", nil))
var empty map[string]any
if err := json.Unmarshal(other.Body.Bytes(), &empty); err != nil || empty["fromClientId"] == "c1" {
t.Fatalf("another session got %s, %v; want it untouched", other.Body.String(), err)
}
}
func TestPutSyncBoundsAnOversizedSessionAndClientID(t *testing.T) {
router := syncRouter(syncsocket.NewHub())
long := strings.Repeat("s", 300)
response := putSync(router, "/sync", `{"clientId":"`+strings.Repeat("c", 300)+`","mediaId":null,"sessionId":"`+long+`"}`)
if response.Code != http.StatusOK {
t.Fatalf("status = %d, body %s", response.Code, response.Body.String())
}
var written struct{ State map[string]any }
if err := json.Unmarshal(response.Body.Bytes(), &written); err != nil {
t.Fatal(err)
}
if got := written.State["sessionId"].(string); len(got) != 128 {
t.Errorf("sessionId length = %d, want 128", len(got))
}
if got := written.State["fromClientId"].(string); len(got) != 128 {
t.Errorf("fromClientId length = %d, want 128", len(got))
}
}
// TestPutSyncBroadcastsToThePeersOfThatSession checks the HTTP write reaches websocket peers in
// the session, and only those.
func TestPutSyncBroadcastsToThePeersOfThatSession(t *testing.T) {
hub := syncsocket.NewHub()
router := syncRouter(hub)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hub.ServeWebSocket(w, r, "")
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
url := "ws" + strings.TrimPrefix(server.URL, "http")
join := func(session string) (*websocket.Conn, string) {
conn, _, err := websocket.Dial(ctx, url, nil)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { conn.CloseNow() })
hello := readFrame(t, ctx, conn, "hello")
id := hello["clientId"].(string)
data, _ := json.Marshal(map[string]any{"type": "sync:hello", "clientId": id, "sessionId": session})
if err := conn.Write(ctx, websocket.MessageText, data); err != nil {
t.Fatal(err)
}
readFrame(t, ctx, conn, "sync:state")
return conn, id
}
inRoom, _ := join("room-1")
elsewhere, _ := join("room-2")
if response := putSync(router, "/sync?sessionId=room-1", `{"clientId":"http-client","mediaId":"clip-9","timeMs":1500}`); response.Code != http.StatusOK {
t.Fatalf("PUT status = %d", response.Code)
}
frame := readFrame(t, ctx, inRoom, "sync:state")
state, _ := frame["state"].(map[string]any)
if state["mediaId"] != "clip-9" || state["timeMs"] != float64(1500) {
t.Fatalf("the session peer got %v", frame)
}
short, shortCancel := context.WithTimeout(ctx, 300*time.Millisecond)
defer shortCancel()
if _, _, err := elsewhere.Read(short); err == nil {
t.Fatal("a peer in another session received the broadcast")
}
}
func readFrame(t *testing.T, ctx context.Context, conn *websocket.Conn, want string) map[string]any {
t.Helper()
for {
_, data, err := conn.Read(ctx)
if err != nil {
t.Fatalf("read while waiting for %q: %v", want, err)
}
var message map[string]any
if err := json.Unmarshal(data, &message); err != nil {
t.Fatal(err)
}
if message["type"] == want {
return message
}
}
}
func TestProfileReportsTheSessionUser(t *testing.T) {
guard := newRoleAuthGuard(t)
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject")
router := chi.NewRouter()
New(Config{Auth: auth}).Mount(router)
anonymous := httptest.NewRecorder()
router.ServeHTTP(anonymous, httptest.NewRequest(http.MethodGet, "/profile", nil))
if anonymous.Code != http.StatusOK || strings.TrimSpace(anonymous.Body.String()) != `{"user":null}` {
t.Fatalf("anonymous profile = %d %s, want a null user", anonymous.Code, anonymous.Body.String())
}
request := httptest.NewRequest(http.MethodGet, "/profile", nil)
request.AddCookie(&http.Cookie{Name: "auth_session", Value: "viewer-token"})
known := httptest.NewRecorder()
router.ServeHTTP(known, request)
var body struct{ User map[string]any }
if err := json.Unmarshal(known.Body.Bytes(), &body); err != nil || body.User["username"] != "tester" || body.User["role"] != "user" {
t.Fatalf("profile = %s, %v", known.Body.String(), err)
}
}
+74
View File
@@ -0,0 +1,74 @@
package migrate
import (
"context"
"database/sql"
"os"
"strings"
"testing"
"testing/fstest"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
func TestUpRefusesMissingInputsBeforeConnecting(t *testing.T) {
files := fstest.MapFS{"migrations/001_init.sql": {Data: []byte("-- +goose Up\nSELECT 1;\n")}}
if err := Up(context.Background(), "", files, "migrations"); err == nil || !strings.Contains(err.Error(), "database URL is required") {
t.Fatalf("empty URL error = %v", err)
}
if err := Up(context.Background(), "postgres://localhost/none", nil, "migrations"); err == nil || !strings.Contains(err.Error(), "migration filesystem is required") {
t.Fatalf("nil filesystem error = %v", err)
}
}
func TestUpReportsAnUnreachableDatabase(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
files := fstest.MapFS{"migrations/001_init.sql": {Data: []byte("-- +goose Up\nSELECT 1;\n")}}
err := Up(ctx, "postgres://nobody@127.0.0.1:1/none?sslmode=disable&connect_timeout=2", files, "migrations")
if err == nil || !strings.Contains(err.Error(), "ping migration database") {
t.Fatalf("unreachable database error = %v, want a ping failure", err)
}
}
// TestUpAppliesMigrationsOnce runs real migrations. It creates goose_db_version and a table, so 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 ./migrate/
func TestUpAppliesMigrationsOnce(t *testing.T) {
url := os.Getenv("SHARED_TEST_DATABASE_URL")
if url == "" {
t.Skip("SHARED_TEST_DATABASE_URL not set; skipping Postgres migration test")
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
db, err := sql.Open("pgx", url)
if err != nil {
t.Fatal(err)
}
defer db.Close()
t.Cleanup(func() {
_, _ = db.Exec(`DROP TABLE IF EXISTS migrate_test_widgets; DROP TABLE IF EXISTS goose_db_version`)
})
_, _ = db.Exec(`DROP TABLE IF EXISTS migrate_test_widgets; DROP TABLE IF EXISTS goose_db_version`)
files := fstest.MapFS{
"migrations/001_widgets.sql": {Data: []byte("-- +goose Up\nCREATE TABLE migrate_test_widgets (id INT PRIMARY KEY);\n-- +goose Down\nDROP TABLE migrate_test_widgets;\n")},
"migrations/002_seed.sql": {Data: []byte("-- +goose Up\nINSERT INTO migrate_test_widgets (id) VALUES (1);\n-- +goose Down\nDELETE FROM migrate_test_widgets;\n")},
}
for run := 1; run <= 2; run++ {
if err := Up(ctx, url, files, "migrations"); err != nil {
t.Fatalf("run %d: Up() error = %v", run, err)
}
}
var rows int
if err := db.QueryRowContext(ctx, `SELECT count(*) FROM migrate_test_widgets`).Scan(&rows); err != nil || rows != 1 {
t.Fatalf("widgets = %d, %v; want the seed applied exactly once", rows, err)
}
broken := fstest.MapFS{"migrations/003_broken.sql": {Data: []byte("-- +goose Up\nSELECT * FROM no_such_table;\n")}}
if err := Up(ctx, url, broken, "migrations"); err == nil || !strings.Contains(err.Error(), "run migrations") {
t.Fatalf("broken migration error = %v, want a run-migrations failure", err)
}
}
+156 -45
View File
@@ -19,7 +19,10 @@ package syncsocket
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"math"
"net/http"
"net/url"
@@ -31,18 +34,22 @@ import (
)
const (
maxSyncIdentifier = 128
maxSyncSessions = 1000
maxSyncConnections = 1000
maxSyncIdentifier = 128
maxSyncSessions = 1000
maxSyncConnections = 1000
maxPeerWriteQueue = 64
maxPeerMessagesPerSecond = 120
)
type peer struct {
conn *websocket.Conn
writeMu sync.Mutex
out chan []byte
done chan struct{}
closeOnce sync.Once
messageWindow time.Time
messageCount int
clientID string
sessionID string
userAgent string
ipAddress string
remoteControlEnabled bool
uiView string
uiMediaID any
@@ -77,11 +84,15 @@ func NewHub() *Hub {
// add registers a peer, or reports false when the hub already holds maxSyncConnections peers.
func (h *Hub) add(p *peer) bool {
h.mu.Lock()
defer h.mu.Unlock()
if len(h.peers) >= maxSyncConnections {
h.mu.Unlock()
return false
}
p.out = make(chan []byte, maxPeerWriteQueue)
p.done = make(chan struct{})
h.peers[p] = struct{}{}
h.mu.Unlock()
go p.writeLoop()
return true
}
@@ -89,6 +100,7 @@ func (h *Hub) remove(p *peer) string {
h.mu.Lock()
defer h.mu.Unlock()
delete(h.peers, p)
p.closeOnce.Do(func() { close(p.done) })
if p.clientID != "" && !h.hasClientLocked(p.clientID) {
delete(h.controlOwners, p.clientID)
for targetID, ownerID := range h.controlOwners {
@@ -109,11 +121,8 @@ func (h *Hub) hasClientLocked(clientID string) bool {
return false
}
func (h *Hub) updatePeer(p *peer, clientID, sessionID string) {
func (h *Hub) updatePeer(p *peer, sessionID string) {
h.mu.Lock()
if clientID != "" {
p.clientID = clientID
}
if sessionID != "" {
p.sessionID = sessionID
}
@@ -151,8 +160,6 @@ func (h *Hub) clientsLocked(sessionID string) []map[string]any {
if !exists {
entry = map[string]any{
"clientId": p.clientID,
"userAgent": p.userAgent,
"ipAddress": p.ipAddress,
"remoteControlEnabled": p.remoteControlEnabled,
"controlOwnerClientId": nil,
}
@@ -250,9 +257,13 @@ func (h *Hub) Broadcast(sessionID string) {
h.mu.Unlock()
message := map[string]any{"type": "sync:state", "state": state, "clients": clients}
data, err := json.Marshal(message)
if err != nil {
return
}
for _, p := range peers {
if err := p.send(message); err != nil {
_ = p.conn.Close(websocket.StatusGoingAway, "write failed")
if err := p.sendData(data); err != nil {
p.drop(websocket.StatusGoingAway, "slow or closed peer")
}
}
}
@@ -262,20 +273,76 @@ func (p *peer) send(message any) error {
if err != nil {
return err
}
p.writeMu.Lock()
defer p.writeMu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
return p.conn.Write(ctx, websocket.MessageText, data)
return p.sendData(data)
}
func (p *peer) sendData(data []byte) error {
select {
case <-p.done:
return context.Canceled
default:
}
select {
case p.out <- data:
return nil
case <-p.done:
return context.Canceled
default:
return errPeerWriteQueueFull
}
}
var errPeerWriteQueueFull = errors.New("sync websocket peer write queue is full")
func (p *peer) writeLoop() {
for {
select {
case <-p.done:
return
case data := <-p.out:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
err := p.conn.Write(ctx, websocket.MessageText, data)
cancel()
if err != nil {
p.stop(websocket.StatusGoingAway, "write failed")
return
}
}
}
}
func (p *peer) allowMessage(now time.Time) bool {
if now.Sub(p.messageWindow) >= time.Second {
p.messageWindow = now
p.messageCount = 0
}
p.messageCount++
return p.messageCount <= maxPeerMessagesPerSecond
}
func (p *peer) close() {
p.stop(websocket.StatusPolicyViolation, "message rate exceeded")
}
func (p *peer) stop(status websocket.StatusCode, reason string) {
p.closeOnce.Do(func() { close(p.done) })
_ = p.conn.Close(status, reason)
}
// drop stops a peer on behalf of code that is serving other peers or an HTTP request. Close waits
// for the peer's close frame (up to five seconds), which a stuck peer never sends, so it runs in
// its own goroutine instead of holding up the caller.
func (p *peer) drop(status websocket.StatusCode, reason string) {
p.closeOnce.Do(func() { close(p.done) })
go func() { _ = p.conn.Close(status, reason) }()
}
// websocketAcceptOptions enables origin verification for every connection. A
// configured origin and the request's own host are accepted. "*" adds no
// extra origin, so it does not turn the check off: a page on another site
// cannot open the socket unless its origin is listed explicitly.
func websocketAcceptOptions(r *http.Request, allowedOrigin string) *websocket.AcceptOptions {
options := &websocket.AcceptOptions{}
if allowedOrigin == "*" {
options.InsecureSkipVerify = true
return options
}
patterns := make([]string, 0, 2)
addOrigin := func(value string) {
parsed, err := url.Parse(strings.TrimSpace(value))
@@ -293,19 +360,51 @@ func websocketAcceptOptions(r *http.Request, allowedOrigin string) *websocket.Ac
return options
}
// newClientID returns a random identifier for one connection. The hub issues it
// at upgrade time and clients cannot choose it, so two connections never share
// an identity.
func newClientID() (string, error) {
var buf [16]byte
if _, err := rand.Read(buf[:]); err != nil {
return "", err
}
return hex.EncodeToString(buf[:]), nil
}
// acceptsClientID reports whether a message's clientId, if it carries one,
// names the identity issued to this connection. A message without clientId
// is taken as this connection's own.
func (p *peer) acceptsClientID(message map[string]any) bool {
requested := boundedSyncString(syncString(message, "clientId"))
return requested == "" || requested == p.clientID
}
// refuseClientID drops a message that named another identity. The connection
// stays open, and the error frame repeats the identity the client holds.
func (p *peer) refuseClientID() {
_ = p.send(map[string]any{"type": "error", "code": "client-id-mismatch", "clientId": p.clientID})
}
// ServeWebSocket upgrades the request to a websocket connection and services
// it until the client disconnects. allowedOrigin should be the service's own
// CORS_ORIGIN config value (or "*" to accept any origin).
// explicit CORS_ORIGIN value; "*" does not bypass origin verification.
//
// Each connection is issued a clientId at upgrade time. It is sent in the
// first "hello" frame, and every later message must either omit clientId or
// repeat it. A message naming any other identity gets a "client-id-mismatch"
// error frame and is otherwise ignored. A reconnect is a new connection with a
// new identity.
func (h *Hub) ServeWebSocket(w http.ResponseWriter, r *http.Request, allowedOrigin string) {
conn, err := websocket.Accept(w, r, websocketAcceptOptions(r, allowedOrigin))
if err != nil {
return
}
p := &peer{
conn: conn,
userAgent: firstNonEmpty(r.Header.Get("User-Agent"), "Unknown"),
ipAddress: firstNonEmpty(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0], r.RemoteAddr, "Unknown"),
clientID, err := newClientID()
if err != nil {
_ = conn.Close(websocket.StatusInternalError, "could not issue client identity")
return
}
p := &peer{conn: conn, clientID: clientID}
if !h.add(p) {
_ = conn.Close(websocket.StatusTryAgainLater, "too many sync connections")
return
@@ -318,12 +417,16 @@ func (h *Hub) ServeWebSocket(w http.ResponseWriter, r *http.Request, allowedOrig
}
}()
_ = p.send(map[string]any{"type": "hello", "ts": time.Now().UnixMilli()})
_ = p.send(map[string]any{"type": "hello", "clientId": clientID, "ts": time.Now().UnixMilli()})
for {
messageType, payload, readErr := conn.Read(r.Context())
if readErr != nil {
return
}
if !p.allowMessage(time.Now()) {
p.close()
return
}
if messageType != websocket.MessageText {
continue
}
@@ -346,20 +449,23 @@ func (h *Hub) handleMessage(p *peer, message map[string]any) {
"serverReceivedAt": time.Now().UnixMilli(),
})
case "sync:hello":
clientID := boundedSyncString(syncString(message, "clientId"))
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), "default"))
if clientID == "" || sessionID == "" {
if !p.acceptsClientID(message) {
p.refuseClientID()
return
}
h.updatePeer(p, clientID, sessionID)
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), "default"))
if sessionID == "" {
return
}
h.updatePeer(p, sessionID)
h.Broadcast(sessionID)
case "client:status":
clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID))
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
if clientID == "" {
if !p.acceptsClientID(message) {
p.refuseClientID()
return
}
h.updatePeer(p, clientID, sessionID)
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
h.updatePeer(p, sessionID)
mediaID, mediaIDSet := syncMediaID(message)
remote, remoteSet := message["remoteControlEnabled"].(bool)
h.clientStatus(p, sessionID, boundedSyncString(syncString(message, "uiView")), mediaID, mediaIDSet, remoteSet, remote)
@@ -372,10 +478,14 @@ func (h *Hub) handleMessage(p *peer, message map[string]any) {
}
func (h *Hub) handleControlMessage(p *peer, typ string, message map[string]any) {
requesterID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID))
if !p.acceptsClientID(message) {
p.refuseClientID()
return
}
requesterID := p.clientID
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
targetID := boundedSyncString(syncString(message, "targetClientId"))
if requesterID == "" || targetID == "" || requesterID != p.clientID {
if targetID == "" {
return
}
@@ -422,11 +532,12 @@ func (h *Hub) handleControlMessage(p *peer, typ string, message map[string]any)
}
func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) {
clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID))
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
if clientID == "" || clientID != p.clientID {
if !p.acceptsClientID(message) {
p.refuseClientID()
return
}
clientID := p.clientID
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
mediaID, _ := syncMediaID(message)
paused := syncBool(message, "paused")
state := map[string]any{
@@ -490,7 +601,7 @@ func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) {
if toClientID != "" {
for _, target := range peers {
if err := target.send(messageOut); err != nil {
_ = target.conn.Close(websocket.StatusGoingAway, "write failed")
target.drop(websocket.StatusGoingAway, "write failed")
}
}
return
@@ -1,8 +1,17 @@
package syncsocket
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"time"
"github.com/coder/websocket"
)
// TestSessionTimingMapsStayBounded checks that fresh client-chosen session IDs cannot grow the
@@ -44,3 +53,266 @@ func TestHubRefusesPeersBeyondTheConnectionCap(t *testing.T) {
t.Fatal("add accepted a peer beyond maxSyncConnections")
}
}
// TestWildcardOriginKeepsOriginVerification checks that CORS_ORIGIN "*" does not disable the
// websocket origin check: only the request's own host is accepted.
func TestWildcardOriginKeepsOriginVerification(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "http://hub.example.com/ws", nil)
options := websocketAcceptOptions(req, "*")
if options.InsecureSkipVerify {
t.Fatal("wildcard origin disabled origin verification")
}
if want := []string{"http://hub.example.com"}; !slices.Equal(options.OriginPatterns, want) {
t.Fatalf("origin patterns = %v, want %v", options.OriginPatterns, want)
}
}
// TestExplicitOriginIsAcceptedAlongsideTheRequestHost checks that a listed origin is accepted
// without turning the check off.
func TestExplicitOriginIsAcceptedAlongsideTheRequestHost(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "https://hub.example.com/ws", nil)
options := websocketAcceptOptions(req, "https://app.example.com/")
if options.InsecureSkipVerify {
t.Fatal("explicit origin disabled origin verification")
}
for _, want := range []string{"https://app.example.com", "https://hub.example.com"} {
if !slices.Contains(options.OriginPatterns, want) {
t.Errorf("origin patterns %v missing %q", options.OriginPatterns, want)
}
}
}
// TestClientListOmitsPeerAddressAndUserAgent checks that broadcast client entries carry no peer
// IP address or user agent.
func TestClientListOmitsPeerAddressAndUserAgent(t *testing.T) {
hub := NewHub()
hub.add(&peer{clientID: "client-1", sessionID: "session-1", remoteControlEnabled: true})
clients := hub.clientsLocked("session-1")
if len(clients) != 1 {
t.Fatalf("clients = %d, want 1", len(clients))
}
for _, key := range []string{"ipAddress", "userAgent"} {
if _, ok := clients[0][key]; ok {
t.Errorf("client entry carries %q", key)
}
}
if clients[0]["clientId"] != "client-1" {
t.Errorf("clientId = %v, want client-1", clients[0]["clientId"])
}
}
// TestClientIdentityIsIssuedAtUpgradeAndEnforced checks the protocol change: each connection gets a
// server-issued clientId in its hello frame, a message naming another identity is refused with an
// error frame, and a message carrying the issued identity is applied.
func TestClientIdentityIsIssuedAtUpgradeAndEnforced(t *testing.T) {
hub := NewHub()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hub.ServeWebSocket(w, r, "")
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
url := "ws" + strings.TrimPrefix(server.URL, "http")
first := dialSyncSocket(t, ctx, url)
defer first.CloseNow()
second := dialSyncSocket(t, ctx, url)
defer second.CloseNow()
firstID := readSyncFrame(t, ctx, first, "hello")["clientId"].(string)
secondID := readSyncFrame(t, ctx, second, "hello")["clientId"].(string)
if len(firstID) != 32 || firstID == secondID {
t.Fatalf("issued identities = %q and %q, want two distinct 32-character IDs", firstID, secondID)
}
writeSyncFrame(t, ctx, first, map[string]any{"type": "sync:hello", "clientId": secondID, "sessionId": "s1"})
refusal := readSyncFrame(t, ctx, first, "error")
if refusal["code"] != "client-id-mismatch" || refusal["clientId"] != firstID {
t.Fatalf("refusal = %v, want client-id-mismatch carrying the issued identity", refusal)
}
writeSyncFrame(t, ctx, first, map[string]any{"type": "sync:hello", "clientId": firstID, "sessionId": "s1"})
state := readSyncFrame(t, ctx, first, "sync:state")
clients, _ := state["clients"].([]any)
found := false
for _, entry := range clients {
if client, ok := entry.(map[string]any); ok && client["clientId"] == firstID {
found = true
}
}
if !found {
t.Fatalf("clients = %v, want the issued identity %q listed", clients, firstID)
}
}
func TestAcceptsClientIDOnlyForTheIssuedIdentity(t *testing.T) {
p := &peer{clientID: "issued"}
for _, tt := range []struct {
name string
message map[string]any
want bool
}{
{"no clientId", map[string]any{}, true},
{"the issued identity", map[string]any{"clientId": "issued"}, true},
{"another identity", map[string]any{"clientId": "other"}, false},
{"an oversized identity", map[string]any{"clientId": strings.Repeat("x", maxSyncIdentifier+1)}, false},
} {
if got := p.acceptsClientID(tt.message); got != tt.want {
t.Errorf("%s: acceptsClientID = %v, want %v", tt.name, got, tt.want)
}
}
}
// TestPeerMessageRateWindow checks the per-peer limit: maxPeerMessagesPerSecond messages are
// allowed in a one-second window, the next is refused, and the count restarts with the next window.
func TestPeerMessageRateWindow(t *testing.T) {
p := &peer{}
start := time.Unix(1000, 0)
for i := 0; i < maxPeerMessagesPerSecond; i++ {
if !p.allowMessage(start.Add(time.Duration(i) * time.Millisecond)) {
t.Fatalf("message %d refused inside the limit", i+1)
}
}
if p.allowMessage(start.Add(500 * time.Millisecond)) {
t.Fatal("a message past the limit was allowed")
}
if !p.allowMessage(start.Add(time.Second)) {
t.Fatal("the count did not restart with the next window")
}
}
// TestPeerExceedingTheMessageRateIsDisconnected checks that a client flooding messages is closed
// with a policy-violation status instead of being fanned out.
func TestPeerExceedingTheMessageRateIsDisconnected(t *testing.T) {
hub := NewHub()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hub.ServeWebSocket(w, r, "")
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
conn := dialSyncSocket(t, ctx, "ws"+strings.TrimPrefix(server.URL, "http"))
defer conn.CloseNow()
readSyncFrame(t, ctx, conn, "hello")
go func() {
for i := 0; i < maxPeerMessagesPerSecond*4; i++ {
if conn.Write(ctx, websocket.MessageText, []byte(`{"type":"ws:ping"}`)) != nil {
return
}
}
}()
for {
if _, _, err := conn.Read(ctx); err != nil {
if got := websocket.CloseStatus(err); got != websocket.StatusPolicyViolation {
t.Fatalf("close status = %v (error %v), want policy violation", got, err)
}
return
}
}
}
// TestBroadcastDropsAPeerWithAFullQueueWithoutBlocking checks that a peer that never drains its
// write queue is stopped by Broadcast, which returns at once, and that a healthy peer in the same
// session still receives the state.
func TestBroadcastDropsAPeerWithAFullQueueWithoutBlocking(t *testing.T) {
hub := NewHub()
slowReady := make(chan *peer, 1)
release := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/slow" {
hub.ServeWebSocket(w, r, "")
return
}
conn, err := websocket.Accept(w, r, nil)
if err != nil {
return
}
defer conn.CloseNow()
p := &peer{
conn: conn, clientID: "slow", sessionID: "s1",
out: make(chan []byte, maxPeerWriteQueue), done: make(chan struct{}),
}
for i := 0; i < maxPeerWriteQueue; i++ {
p.out <- []byte("{}")
}
hub.mu.Lock()
hub.peers[p] = struct{}{}
hub.mu.Unlock()
slowReady <- p
<-release
}))
defer server.Close()
defer close(release)
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
url := "ws" + strings.TrimPrefix(server.URL, "http")
fast := dialSyncSocket(t, ctx, url)
defer fast.CloseNow()
fastID := readSyncFrame(t, ctx, fast, "hello")["clientId"].(string)
writeSyncFrame(t, ctx, fast, map[string]any{"type": "sync:hello", "clientId": fastID, "sessionId": "s1"})
readSyncFrame(t, ctx, fast, "sync:state")
slowClient := dialSyncSocket(t, ctx, url+"/slow")
defer slowClient.CloseNow()
slow := <-slowReady
// Stopping a peer waits for a close frame that a stuck peer never sends, so Broadcast must not
// do it inline: it would hold up the caller (an HTTP request, or another peer's read loop).
started := time.Now()
hub.Broadcast("s1")
if elapsed := time.Since(started); elapsed > time.Second {
t.Fatalf("Broadcast took %v behind a stuck peer, want it to return at once", elapsed)
}
select {
case <-slow.done:
default:
t.Fatal("the peer with a full queue was not stopped")
}
state := readSyncFrame(t, ctx, fast, "sync:state")
if _, ok := state["clients"].([]any); !ok {
t.Fatalf("the healthy peer got %v, want a state with the client list", state)
}
if elapsed := time.Since(started); elapsed > time.Second {
t.Fatalf("the healthy peer's state took %v, want it at once", elapsed)
}
}
func dialSyncSocket(t *testing.T, ctx context.Context, url string) *websocket.Conn {
t.Helper()
conn, _, err := websocket.Dial(ctx, url, nil)
if err != nil {
t.Fatalf("dial %s: %v", url, err)
}
return conn
}
func writeSyncFrame(t *testing.T, ctx context.Context, conn *websocket.Conn, message map[string]any) {
t.Helper()
data, err := json.Marshal(message)
if err != nil {
t.Fatal(err)
}
if err := conn.Write(ctx, websocket.MessageText, data); err != nil {
t.Fatalf("write %v: %v", message["type"], err)
}
}
// readSyncFrame reads frames until one of the wanted type arrives, failing if the connection ends first.
func readSyncFrame(t *testing.T, ctx context.Context, conn *websocket.Conn, want string) map[string]any {
t.Helper()
for {
_, data, err := conn.Read(ctx)
if err != nil {
t.Fatalf("read while waiting for %q: %v", want, err)
}
var message map[string]any
if err := json.Unmarshal(data, &message); err != nil {
t.Fatalf("decode frame: %v", err)
}
if message["type"] == want {
return message
}
}
}