Add initial shared code packages
This commit is contained in:
commit
838a97d344
54 files changed
+6265
No files matched your search
@@ -0,0 +1,21 @@
|
||||
package auth
|
||||
|
||||
import "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.
|
||||
const BcryptCost = 12
|
||||
|
||||
// HashPassword returns a bcrypt 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
|
||||
}
|
||||
|
||||
// VerifyPassword checks a plaintext password against a stored bcrypt hash.
|
||||
func VerifyPassword(hash, password string) bool {
|
||||
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
// Package auth contains the shared single-account/session persistence used by
|
||||
// the self-hosted web services. HTTP handlers, cookies, authorization policy,
|
||||
// and application-specific roles remain in each service.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// User is the shared account record. PasswordHash should never be serialized
|
||||
// into an API response.
|
||||
type User struct {
|
||||
ID int64
|
||||
Username string
|
||||
Email string
|
||||
PasswordHash string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// Store performs common auth persistence against a caller-owned pool.
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
// NewStore creates an auth store. The pool remains owned by the caller.
|
||||
func NewStore(pool *pgxpool.Pool) *Store {
|
||||
return &Store{pool: pool}
|
||||
}
|
||||
|
||||
// SchemaOptions controls optional auth schema features.
|
||||
type SchemaOptions struct {
|
||||
// SingleUser adds a constraint that allows exactly one account. This is the
|
||||
// default model for GameStream, SimpleCollection, and home-server tools.
|
||||
SingleUser bool
|
||||
// APITokens creates the optional per-user API token table.
|
||||
APITokens bool
|
||||
}
|
||||
|
||||
// DefaultSchemaOptions returns the single-account schema used by most small
|
||||
// self-hosted services.
|
||||
func DefaultSchemaOptions() SchemaOptions {
|
||||
return SchemaOptions{SingleUser: true}
|
||||
}
|
||||
|
||||
// EnsureSchema creates the shared auth tables and indexes idempotently.
|
||||
func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions) error {
|
||||
if pool == nil {
|
||||
return errors.New("auth postgres pool is nil")
|
||||
}
|
||||
|
||||
_, err := pool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS auth_users (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
email TEXT NOT NULL DEFAULT '',
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
|
||||
ON auth_users (lower(email)) WHERE email <> '';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS auth_sessions (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at);
|
||||
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);
|
||||
`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ensure auth schema: %w", err)
|
||||
}
|
||||
|
||||
if options.SingleUser {
|
||||
if _, err := pool.Exec(ctx, `
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
|
||||
`); err != nil {
|
||||
return fmt.Errorf("ensure single-user auth constraint: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if options.APITokens {
|
||||
if _, err := pool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS auth_api_tokens (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS auth_api_tokens_user_idx ON auth_api_tokens (user_id);
|
||||
`); err != nil {
|
||||
return fmt.Errorf("ensure auth API-token schema: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CountUsers returns the number of configured accounts.
|
||||
func (s *Store) CountUsers(ctx context.Context) (int, error) {
|
||||
if err := s.validate(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var count int
|
||||
if err := s.pool.QueryRow(ctx, `SELECT count(*) FROM auth_users`).Scan(&count); err != nil {
|
||||
return 0, fmt.Errorf("count auth users: %w", err)
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// CreateUser inserts an account and returns ErrUserExists for a uniqueness
|
||||
// conflict, including the single-user constraint.
|
||||
func (s *Store) CreateUser(ctx context.Context, username, email, passwordHash string) (*User, error) {
|
||||
if err := s.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var user User
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
INSERT INTO auth_users (username, email, password_hash, updated_at)
|
||||
VALUES ($1, $2, $3, now())
|
||||
RETURNING id, username, email, password_hash, created_at, updated_at
|
||||
`, username, email, passwordHash).Scan(
|
||||
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.CreatedAt, &user.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return nil, ErrUserExists
|
||||
}
|
||||
return nil, fmt.Errorf("create auth user: %w", err)
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// FindByIdentifier looks up a user by exact username or case-insensitive email.
|
||||
func (s *Store) FindByIdentifier(ctx context.Context, identifier string) (*User, error) {
|
||||
if err := s.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.find(ctx, `
|
||||
SELECT id, username, email, password_hash, created_at, updated_at
|
||||
FROM auth_users
|
||||
WHERE username = $1 OR lower(email) = lower($1)
|
||||
`, identifier)
|
||||
}
|
||||
|
||||
// FindByID looks up a user by primary key.
|
||||
func (s *Store) FindByID(ctx context.Context, id int64) (*User, error) {
|
||||
if err := s.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.find(ctx, `
|
||||
SELECT id, username, email, password_hash, created_at, updated_at
|
||||
FROM auth_users WHERE id = $1
|
||||
`, id)
|
||||
}
|
||||
|
||||
// UpdateCredentials updates the normalized account fields and password hash.
|
||||
func (s *Store) UpdateCredentials(ctx context.Context, id int64, username, email, passwordHash string) error {
|
||||
if err := s.validate(); 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 {
|
||||
return fmt.Errorf("update auth credentials: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateSession stores a hash of a session token until expiresAt.
|
||||
func (s *Store) CreateSession(ctx context.Context, userID int64, tokenHash string, expiresAt time.Time) error {
|
||||
if err := s.validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO auth_sessions (user_id, token_hash, expires_at)
|
||||
VALUES ($1, $2, $3)
|
||||
`, userID, tokenHash, expiresAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create auth session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FindSessionUser resolves an unexpired session to its user.
|
||||
func (s *Store) FindSessionUser(ctx context.Context, tokenHash string) (*User, error) {
|
||||
if err := s.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.find(ctx, `
|
||||
SELECT u.id, u.username, u.email, u.password_hash, u.created_at, u.updated_at
|
||||
FROM auth_sessions s
|
||||
JOIN auth_users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1 AND s.expires_at > now()
|
||||
`, tokenHash)
|
||||
}
|
||||
|
||||
// DeleteSession removes one session, typically during logout.
|
||||
func (s *Store) DeleteSession(ctx context.Context, tokenHash string) error {
|
||||
if err := s.validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE token_hash = $1`, tokenHash); err != nil {
|
||||
return fmt.Errorf("delete auth session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteSessionsForUser invalidates all sessions after credential changes.
|
||||
func (s *Store) DeleteSessionsForUser(ctx context.Context, userID int64) error {
|
||||
if err := s.validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE user_id = $1`, userID); err != nil {
|
||||
return fmt.Errorf("delete auth sessions for user: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteExpiredSessions performs the periodic session cleanup shared by the
|
||||
// services. A caller can run it from its own scheduler.
|
||||
func (s *Store) DeleteExpiredSessions(ctx context.Context) error {
|
||||
if err := s.validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE expires_at < now()`); err != nil {
|
||||
return fmt.Errorf("delete expired auth sessions: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var ErrUserExists = errors.New("auth user already exists")
|
||||
|
||||
func (s *Store) validate() error {
|
||||
if s == nil || s.pool == nil {
|
||||
return errors.New("auth store has no postgres pool")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) find(ctx context.Context, query string, arg any) (*User, error) {
|
||||
var user User
|
||||
err := s.pool.QueryRow(ctx, query, arg).Scan(
|
||||
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.CreatedAt, &user.UpdatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("find auth user: %w", err)
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func TestPasswordRoundTrip(t *testing.T) {
|
||||
hash, err := HashPassword("correct horse battery staple")
|
||||
if err != nil {
|
||||
t.Fatalf("HashPassword() error = %v", err)
|
||||
}
|
||||
if !VerifyPassword(hash, "correct horse battery staple") {
|
||||
t.Fatal("VerifyPassword() rejected the original password")
|
||||
}
|
||||
if VerifyPassword(hash, "wrong password") {
|
||||
t.Fatal("VerifyPassword() accepted the wrong password")
|
||||
}
|
||||
if cost, err := bcrypt.Cost([]byte(hash)); err != nil || cost != BcryptCost {
|
||||
t.Fatalf("bcrypt cost = %d, error = %v; want %d", cost, err, BcryptCost)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewSessionToken(t *testing.T) {
|
||||
raw, hash, err := NewSessionToken()
|
||||
if err != nil {
|
||||
t.Fatalf("NewSessionToken() error = %v", err)
|
||||
}
|
||||
if raw == "" || hash == "" {
|
||||
t.Fatal("NewSessionToken() returned an empty token or hash")
|
||||
}
|
||||
if got := HashToken(raw); got != hash {
|
||||
diff := got
|
||||
t.Fatalf("HashToken(raw) = %q, want %q", diff, hash)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
)
|
||||
|
||||
// NewSessionToken creates a random bearer token and its SHA-256 storage hash.
|
||||
// Store only the hash; return the raw token to the caller that sets the cookie
|
||||
// or authorization header.
|
||||
func NewSessionToken() (raw string, hash string, err error) {
|
||||
bytes := make([]byte, 32)
|
||||
if _, err := rand.Read(bytes); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
raw = base64.RawURLEncoding.EncodeToString(bytes)
|
||||
return raw, HashToken(raw), nil
|
||||
}
|
||||
|
||||
// HashToken creates the stable database key for a raw session/API token.
|
||||
func HashToken(raw string) string {
|
||||
sum := sha256.Sum256([]byte(raw))
|
||||
return base64.RawURLEncoding.EncodeToString(sum[:])
|
||||
}
|
||||
Reference in new issue
Block a user