Vendor SharedCode locally
Docker / Docker Build & Push (push) Failing after 1m19s
Lint / Lint (push) Successful in 15s
Tests / Go backend (push) Successful in 19s
Tests / Dashboard checks (push) Successful in 18s

This commit is contained in:
Gabriel20xx committed 2026-08-06 15:52:56 +02:00
1 parent a8c51b8484
commit 6eb8f4ad60
88 files changed
+9708 -275

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
# Shared Go backend packages
The Go packages under this directory hold infrastructure shared by the
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.
- `migrate` — embedded filesystem adapter for Goose migrations.
Run `go test ./...` and `go vet ./...` from this directory. The module path is
`repos.gfranz.ch/Gabriel20xx/shared/backend`; change it if the shared folder is
hosted under a different repository path.
Application-specific table definitions and HTTP behavior stay in the service.
That lets a service reuse reliable connection/auth plumbing without coupling
its domain model to another project.
+21
View File
@@ -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
}
+80
View File
@@ -0,0 +1,80 @@
package auth
import (
"crypto/rand"
"crypto/subtle"
"encoding/hex"
"fmt"
"strings"
"sync"
"time"
)
// ResetCodeTTL is the amount of time a printed admin reset code remains valid.
const ResetCodeTTL = 5 * time.Minute
// ResetManager creates and validates the short-lived, one-time code used by
// the public "reset admin account" flow. Account deletion remains owned by
// each application because its account table and session policy may differ.
type ResetManager struct {
mu sync.Mutex
code string
expiresAt time.Time
}
// NewResetManager creates an independent reset-code manager for one server.
func NewResetManager() *ResetManager {
return &ResetManager{}
}
// Request creates a reset code and prints it to the server console. A new
// request invalidates any code previously issued by this manager.
func (m *ResetManager) Request() (string, error) {
if m == nil {
return "", fmt.Errorf("auth reset manager is nil")
}
raw := make([]byte, 4)
if _, err := rand.Read(raw); err != nil {
return "", fmt.Errorf("generate auth reset code: %w", err)
}
code := strings.ToUpper(hex.EncodeToString(raw))
m.mu.Lock()
m.code = code
m.expiresAt = time.Now().Add(ResetCodeTTL)
m.mu.Unlock()
fmt.Printf("\n%s\nADMIN RESET CODE: %s\nExpires in 5 minutes. Enter it on the login page.\n%s\n\n", strings.Repeat("=", 50), code, strings.Repeat("=", 50))
return code, nil
}
// Confirm validates a code and consumes it on success. Invalid codes do not
// consume the pending code, while expired codes are cleared immediately.
func (m *ResetManager) Confirm(candidate string) bool {
if m == nil {
return false
}
m.mu.Lock()
defer m.mu.Unlock()
if m.code == "" {
return false
}
if time.Now().After(m.expiresAt) {
m.code = ""
m.expiresAt = time.Time{}
return false
}
want := []byte(m.code)
got := []byte(strings.ToUpper(strings.TrimSpace(candidate)))
if len(want) != len(got) || subtle.ConstantTimeCompare(want, got) != 1 {
return false
}
m.code = ""
m.expiresAt = time.Time{}
return true
}
+34
View File
@@ -0,0 +1,34 @@
package auth
// Role is the shared account-management role used by the web applications.
type Role string
const (
RoleSuperAdmin Role = "superadmin"
RoleAdmin Role = "admin"
RoleUser Role = "user"
)
// NormalizeRole keeps persisted role values inside the shared contract.
func NormalizeRole(value string) Role {
switch Role(value) {
case RoleSuperAdmin:
return RoleSuperAdmin
case RoleAdmin:
return RoleAdmin
default:
return RoleUser
}
}
// CanManageUsers is the common authorization gate for account CRUD.
func CanManageUsers(role string) bool {
role = string(NormalizeRole(role))
return role == string(RoleSuperAdmin) || role == string(RoleAdmin)
}
// CanAssignRole prevents an administrator from creating or promoting another
// administrator. Only the first-created superadmin can delegate admin access.
func CanAssignRole(actorRole, targetRole string) bool {
return NormalizeRole(actorRole) == RoleSuperAdmin && NormalizeRole(targetRole) != RoleSuperAdmin
}
+435
View File
@@ -0,0 +1,435 @@
// 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
Role Role
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,
role TEXT NOT NULL DEFAULT 'user',
totp_secret TEXT NOT NULL DEFAULT '',
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
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 role TEXT NOT NULL DEFAULT 'user';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
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 <> '';
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)
}
} else if _, err := pool.Exec(ctx, `DROP INDEX IF EXISTS auth_users_singleton_idx`); err != nil {
return fmt.Errorf("remove 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
}
// TOTPState is the private provisioning state for one account. Secret must
// never be included in an API response.
type TOTPState struct {
Secret string
Enabled bool
}
// GetTOTPState reads the stored TOTP provisioning state for an account.
func (s *Store) GetTOTPState(ctx context.Context, userID int64) (TOTPState, error) {
if err := s.validate(); err != nil {
return TOTPState{}, err
}
var state TOTPState
err := s.pool.QueryRow(ctx, `SELECT COALESCE(totp_secret, ''), COALESCE(totp_enabled, false) FROM auth_users WHERE id = $1`, userID).Scan(&state.Secret, &state.Enabled)
if errors.Is(err, pgx.ErrNoRows) {
return TOTPState{}, nil
}
if err != nil {
return TOTPState{}, fmt.Errorf("get TOTP state: %w", err)
}
return state, nil
}
// SetTOTPSecret stores a pending secret without enabling two-factor auth.
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)
if err != nil {
return fmt.Errorf("set TOTP secret: %w", err)
}
return nil
}
// EnableTOTP marks a previously provisioned secret as active.
func (s *Store) EnableTOTP(ctx context.Context, userID int64) error {
if err := s.validate(); err != nil {
return err
}
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''`, userID)
if err != nil {
return fmt.Errorf("enable TOTP: %w", err)
}
return nil
}
// DisableTOTP clears both the active and pending TOTP secret.
func (s *Store) DisableTOTP(ctx context.Context, userID int64) error {
if err := s.validate(); err != nil {
return err
}
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1`, userID)
if err != nil {
return fmt.Errorf("disable TOTP: %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, role, updated_at)
VALUES ($1, $2, $3,
CASE WHEN EXISTS (SELECT 1 FROM auth_users) THEN 'user' ELSE 'superadmin' END,
now())
RETURNING id, username, email, password_hash, role, created_at, updated_at
`, username, email, passwordHash).Scan(
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &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, role, 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, role, 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
}
// ListUsers returns the non-secret account fields used by the shared user
// management screen.
func (s *Store) ListUsers(ctx context.Context) ([]User, error) {
if err := s.validate(); err != nil {
return nil, err
}
rows, err := s.pool.Query(ctx, `
SELECT id, username, email, role, created_at, updated_at
FROM auth_users ORDER BY created_at, id
`)
if err != nil {
return nil, fmt.Errorf("list auth users: %w", err)
}
defer rows.Close()
users := make([]User, 0)
for rows.Next() {
var user User
if err := rows.Scan(&user.ID, &user.Username, &user.Email, &user.Role, &user.CreatedAt, &user.UpdatedAt); err != nil {
return nil, fmt.Errorf("scan auth user: %w", err)
}
users = append(users, user)
}
return users, rows.Err()
}
// CreateManagedUser creates a user with an explicit, already-authorized role.
func (s *Store) CreateManagedUser(ctx context.Context, username, email, passwordHash string, role Role) (*User, error) {
if err := s.validate(); err != nil {
return nil, err
}
role = NormalizeRole(string(role))
var user User
err := s.pool.QueryRow(ctx, `
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
VALUES ($1, $2, $3, $4, now())
RETURNING id, username, email, password_hash, role, created_at, updated_at
`, username, email, passwordHash, role).Scan(
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &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 managed auth user: %w", err)
}
return &user, nil
}
// UpdateUser updates account fields and, when supplied, its role.
func (s *Store) UpdateUser(ctx context.Context, id int64, username, email, passwordHash string, role *Role) error {
if err := s.validate(); err != nil {
return err
}
if role == nil {
return s.UpdateCredentials(ctx, id, username, email, passwordHash)
}
*role = NormalizeRole(string(*role))
_, err := s.pool.Exec(ctx, `
UPDATE auth_users
SET username = $1, email = $2, password_hash = $3, role = $4, updated_at = now()
WHERE id = $5
`, username, email, passwordHash, *role, id)
if err != nil {
return fmt.Errorf("update managed auth user: %w", err)
}
return nil
}
// DeleteUser removes one account. Callers enforce the superadmin/self policy.
func (s *Store) DeleteUser(ctx context.Context, id int64) error {
if err := s.validate(); err != nil {
return err
}
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_users WHERE id = $1`, id); err != nil {
return fmt.Errorf("delete auth user: %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.role, 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
}
// DeleteAllUsers removes every shared account. The auth schema's foreign keys
// cascade this to browser sessions and API tokens, allowing a fresh bootstrap.
func (s *Store) DeleteAllUsers(ctx context.Context) error {
if err := s.validate(); err != nil {
return err
}
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_users`); err != nil {
return fmt.Errorf("delete all auth users: %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
}
+69
View File
@@ -0,0 +1,69 @@
package auth
import (
"strings"
"testing"
"time"
"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)
}
}
func TestResetManagerRoundTrip(t *testing.T) {
manager := NewResetManager()
code, err := manager.Request()
if err != nil {
t.Fatalf("Request() error = %v", err)
}
if len(code) != 8 || strings.ToUpper(code) != code {
t.Fatalf("reset code = %q, want eight uppercase characters", code)
}
if !manager.Confirm(" " + strings.ToLower(code) + " ") {
t.Fatal("Confirm() rejected a valid reset code")
}
if manager.Confirm(code) {
t.Fatal("Confirm() accepted a reset code twice")
}
}
func TestResetManagerExpiresCode(t *testing.T) {
manager := NewResetManager()
if _, err := manager.Request(); err != nil {
t.Fatalf("Request() error = %v", err)
}
manager.mu.Lock()
manager.expiresAt = time.Now().Add(-time.Second)
manager.mu.Unlock()
if manager.Confirm("anything") {
t.Fatal("Confirm() accepted an expired reset code")
}
}
+25
View File
@@ -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[:])
}
+104
View File
@@ -0,0 +1,104 @@
package auth
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha1"
"crypto/subtle"
"encoding/base32"
"encoding/binary"
"fmt"
"net/url"
"strconv"
"strings"
"time"
)
// TOTP follows RFC 6238's default interoperable profile.
const (
TOTPPeriod = 30 * time.Second
TOTPDigits = 6
TOTPSecretBytes = 20
TOTPWindow = 1
TOTPSecretLength = 32
)
// GenerateTOTPSecret returns a base32 secret suitable for authenticator apps.
func GenerateTOTPSecret() (string, error) {
raw := make([]byte, TOTPSecretBytes)
if _, err := rand.Read(raw); err != nil {
return "", fmt.Errorf("generate TOTP secret: %w", err)
}
return base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(raw), nil
}
// TOTPProvisioningURI builds the otpauth URI accepted by common authenticator apps.
func TOTPProvisioningURI(issuer, account, secret string) string {
issuer = strings.TrimSpace(issuer)
account = strings.TrimSpace(account)
secret = normalizeTOTPSecret(secret)
label := account
if issuer != "" {
label = issuer + ":" + account
}
query := url.Values{}
query.Set("secret", secret)
if issuer != "" {
query.Set("issuer", issuer)
}
query.Set("algorithm", "SHA1")
query.Set("digits", strconv.Itoa(TOTPDigits))
query.Set("period", strconv.Itoa(int(TOTPPeriod/time.Second)))
return "otpauth://totp/" + url.PathEscape(label) + "?" + query.Encode()
}
// VerifyTOTP checks a six-digit token with a one-period clock-skew window.
func VerifyTOTP(secret, token string, now time.Time) bool {
secret = normalizeTOTPSecret(secret)
token = normalizeTOTPToken(token)
if secret == "" || len(token) != TOTPDigits {
return false
}
key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(secret)
if err != nil || len(key) == 0 {
return false
}
period := now.Unix() / int64(TOTPPeriod/time.Second)
for offset := int64(-TOTPWindow); offset <= TOTPWindow; offset++ {
if period+offset < 0 {
continue
}
var counter [8]byte
binary.BigEndian.PutUint64(counter[:], uint64(period+offset))
hash := hmac.New(sha1.New, key)
_, _ = hash.Write(counter[:])
digest := hash.Sum(nil)
index := digest[len(digest)-1] & 0x0f
value := (uint32(digest[index])&0x7f)<<24 |
uint32(digest[index+1])<<16 |
uint32(digest[index+2])<<8 |
uint32(digest[index+3])
candidate := fmt.Sprintf("%06d", value%1000000)
if subtle.ConstantTimeCompare([]byte(candidate), []byte(token)) == 1 {
return true
}
}
return false
}
func normalizeTOTPSecret(value string) string {
return strings.TrimRight(strings.ReplaceAll(strings.ToUpper(strings.TrimSpace(value)), " ", ""), "=")
}
func normalizeTOTPToken(value string) string {
value = strings.TrimSpace(value)
if len(value) > TOTPDigits {
return ""
}
for _, character := range value {
if character < '0' || character > '9' {
return ""
}
}
return value
}
+32
View File
@@ -0,0 +1,32 @@
package auth
import (
"testing"
"time"
)
func TestVerifyTOTPRFC6238SHA1Vectors(t *testing.T) {
secret := "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
cases := []struct {
unix int64
code string
}{
{unix: 59, code: "287082"},
{unix: 1111111109, code: "081804"},
{unix: 1111111111, code: "050471"},
{unix: 1234567890, code: "005924"},
{unix: 2000000000, code: "279037"},
}
for _, testCase := range cases {
if !VerifyTOTP(secret, testCase.code, time.Unix(testCase.unix, 0)) {
t.Errorf("VerifyTOTP(%d, %q) = false", testCase.unix, testCase.code)
}
}
}
func TestTOTPProvisioningURI(t *testing.T) {
uri := TOTPProvisioningURI("Example App", "admin@example.com", "abc123")
if uri == "" || len(uri) < len("otpauth://totp/") || uri[:15] != "otpauth://totp/" {
t.Fatalf("unexpected provisioning URI: %q", uri)
}
}
+71
View File
@@ -0,0 +1,71 @@
// Package config contains small, dependency-free environment helpers shared
// by the Go services. It intentionally does not define an application's full
// configuration struct.
package config
import (
"fmt"
"os"
"strconv"
"strings"
"time"
)
// String returns the environment value or fallback when the variable is empty.
func String(key, fallback string) string {
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
return value
}
return fallback
}
// Required returns a trimmed environment value or an actionable error.
func Required(key string) (string, error) {
value := strings.TrimSpace(os.Getenv(key))
if value == "" {
return "", fmt.Errorf("%s is required", key)
}
return value, nil
}
// Bool returns a parsed boolean environment value or fallback for an unset or
// invalid value. Invalid values are deliberately non-fatal for optional flags.
func Bool(key string, fallback bool) bool {
value := strings.TrimSpace(os.Getenv(key))
if value == "" {
return fallback
}
parsed, err := strconv.ParseBool(value)
if err != nil {
return fallback
}
return parsed
}
// Int returns a parsed integer environment value or fallback for an unset or
// invalid value. Callers should validate application-specific ranges.
func Int(key string, fallback int) int {
value := strings.TrimSpace(os.Getenv(key))
if value == "" {
return fallback
}
parsed, err := strconv.Atoi(value)
if err != nil {
return fallback
}
return parsed
}
// Duration returns a parsed duration environment value or fallback for an
// unset or invalid value.
func Duration(key string, fallback time.Duration) time.Duration {
value := strings.TrimSpace(os.Getenv(key))
if value == "" {
return fallback
}
parsed, err := time.ParseDuration(value)
if err != nil {
return fallback
}
return parsed
}
+20
View File
@@ -0,0 +1,20 @@
module repos.gfranz.ch/Gabriel20xx/shared/backend
go 1.25.7
require (
github.com/jackc/pgx/v5 v5.10.0
github.com/pressly/goose/v3 v3.27.3
golang.org/x/crypto v0.54.0
)
require (
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/mfridman/interpolate v0.0.2 // indirect
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
)
+56
View File
@@ -0,0 +1,56 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/mattn/go-isatty v0.0.23 h1:cYwCQTQf3HB6xUC+BtyCLZNr7IzbOmoZbmssVNzSyiQ=
github.com/mattn/go-isatty v0.0.23/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pressly/goose/v3 v3.27.3 h1:pIglVHjw99r4e/hDHHwbl9vfOsDMqUokfkXo6+n/RxA=
github.com/pressly/goose/v3 v3.27.3/go.mod h1:Dag+xpV6o20HR2LFY1j0q6MDwc3f7vPUFDA77R+0yGY=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw=
github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
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=
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=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/libc v1.74.3 h1:a4J+Z8aVaxPyjyxRAdJzw246PqpcFGvVPnfT/AuM5Ws=
modernc.org/libc v1.74.3/go.mod h1:4H7h/MJ8wnjL8RAbp9v3OXgnk22X7MouHIhDbvP3gj4=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.54.0 h1:JCxR4qwkJvOaqAoYcgDoO25Nc+ROg6EJ2LfBVzdrgog=
modernc.org/sqlite v1.54.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
+42
View File
@@ -0,0 +1,42 @@
// Package migrate provides a small embedded-filesystem wrapper around Goose.
// Applications still own their SQL files and migration policy.
package migrate
import (
"context"
"database/sql"
"fmt"
"io/fs"
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/pressly/goose/v3"
)
// Up applies all pending PostgreSQL migrations in migrationsFS/dir. The
// filesystem is normally an embed.FS supplied by the consuming application.
func Up(ctx context.Context, databaseURL string, migrationsFS fs.FS, dir string) error {
if databaseURL == "" {
return fmt.Errorf("database URL is required")
}
if migrationsFS == nil {
return fmt.Errorf("migration filesystem is required")
}
db, err := sql.Open("pgx", databaseURL)
if err != nil {
return fmt.Errorf("open migration database: %w", err)
}
defer db.Close()
if err := db.PingContext(ctx); err != nil {
return fmt.Errorf("ping migration database: %w", err)
}
goose.SetBaseFS(migrationsFS)
if err := goose.SetDialect("postgres"); err != nil {
return fmt.Errorf("set migration dialect: %w", err)
}
if err := goose.UpContext(ctx, db, dir); err != nil {
return fmt.Errorf("run migrations: %w", err)
}
return nil
}
+153
View File
@@ -0,0 +1,153 @@
// Package postgres centralizes PostgreSQL pool creation and the small pieces
// of error/transaction handling that are repeated by the Go services.
package postgres
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"repos.gfranz.ch/Gabriel20xx/shared/backend/config"
)
// Config controls a shared pgx connection pool. URL is normally read from
// DATABASE_URL with FromEnv.
type Config struct {
URL string
MaxConns int32
MinConns int32
MaxConnLifetime time.Duration
MaxConnIdleTime time.Duration
HealthCheckPeriod time.Duration
ConnectTimeout time.Duration
}
// DefaultConfig returns sensible defaults for a small self-hosted service.
func DefaultConfig(url string) Config {
return Config{
URL: strings.TrimSpace(url),
MaxConns: 20,
MinConns: 0,
MaxConnLifetime: time.Hour,
MaxConnIdleTime: 30 * time.Minute,
HealthCheckPeriod: 30 * time.Second,
ConnectTimeout: 10 * time.Second,
}
}
// FromEnv loads DATABASE_URL and optional pool settings. Duration values use
// Go duration syntax, for example 30s or 1h. Invalid optional values fall back
// to defaults; the URL is the only required setting.
func FromEnv() (Config, error) {
url, err := config.Required("DATABASE_URL")
if err != nil {
return Config{}, err
}
cfg := DefaultConfig(url)
cfg.MaxConns = int32(config.Int("DATABASE_MAX_CONNS", int(cfg.MaxConns)))
cfg.MinConns = int32(config.Int("DATABASE_MIN_CONNS", int(cfg.MinConns)))
cfg.MaxConnLifetime = config.Duration("DATABASE_MAX_CONN_LIFETIME", cfg.MaxConnLifetime)
cfg.MaxConnIdleTime = config.Duration("DATABASE_MAX_CONN_IDLE_TIME", cfg.MaxConnIdleTime)
cfg.HealthCheckPeriod = config.Duration("DATABASE_HEALTH_CHECK_PERIOD", cfg.HealthCheckPeriod)
cfg.ConnectTimeout = config.Duration("DATABASE_CONNECT_TIMEOUT", cfg.ConnectTimeout)
if cfg.MaxConns < 1 {
return Config{}, fmt.Errorf("DATABASE_MAX_CONNS must be at least 1")
}
if cfg.MinConns < 0 || cfg.MinConns > cfg.MaxConns {
return Config{}, fmt.Errorf("DATABASE_MIN_CONNS must be between 0 and DATABASE_MAX_CONNS")
}
if cfg.ConnectTimeout <= 0 {
return Config{}, fmt.Errorf("DATABASE_CONNECT_TIMEOUT must be greater than 0")
}
return cfg, nil
}
// Open creates and verifies a PostgreSQL pool. A failed ping closes the pool
// before returning so callers do not leak connections during startup errors.
func Open(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
if strings.TrimSpace(cfg.URL) == "" {
return nil, errors.New("postgres URL is required")
}
poolConfig, err := pgxpool.ParseConfig(cfg.URL)
if err != nil {
return nil, fmt.Errorf("parse postgres URL: %w", err)
}
if cfg.MaxConns > 0 {
poolConfig.MaxConns = cfg.MaxConns
}
if cfg.MinConns >= 0 {
poolConfig.MinConns = cfg.MinConns
}
if cfg.MaxConnLifetime > 0 {
poolConfig.MaxConnLifetime = cfg.MaxConnLifetime
}
if cfg.MaxConnIdleTime > 0 {
poolConfig.MaxConnIdleTime = cfg.MaxConnIdleTime
}
if cfg.HealthCheckPeriod > 0 {
poolConfig.HealthCheckPeriod = cfg.HealthCheckPeriod
}
if cfg.ConnectTimeout > 0 {
poolConfig.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
}
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
return nil, fmt.Errorf("create postgres pool: %w", err)
}
if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping postgres: %w", err)
}
return pool, nil
}
// WithTx runs fn in a transaction and rolls back on all error paths.
func WithTx(ctx context.Context, pool *pgxpool.Pool, fn func(pgx.Tx) error) error {
if pool == nil {
return errors.New("postgres pool is nil")
}
if fn == nil {
return errors.New("postgres transaction callback is nil")
}
tx, err := pool.Begin(ctx)
if err != nil {
return fmt.Errorf("begin postgres transaction: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
if err := fn(tx); err != nil {
return err
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("commit postgres transaction: %w", err)
}
return nil
}
// IsNoRows reports whether err is pgx's not-found sentinel.
func IsNoRows(err error) bool {
return errors.Is(err, pgx.ErrNoRows)
}
// IsUniqueViolation reports a PostgreSQL unique/exclusion constraint error.
func IsUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && (pgErr.Code == "23505" || pgErr.Code == "23P01")
}
// IsForeignKeyViolation reports a PostgreSQL foreign-key constraint error.
func IsForeignKeyViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23503"
}
@@ -0,0 +1,31 @@
package postgres
import (
"os"
"testing"
)
func TestFromEnvRequiresDatabaseURL(t *testing.T) {
t.Setenv("DATABASE_URL", "")
if _, err := FromEnv(); err == nil {
t.Fatal("FromEnv() returned nil error without DATABASE_URL")
}
}
func TestFromEnvLoadsPoolSettings(t *testing.T) {
t.Setenv("DATABASE_URL", "postgres://user:password@localhost:5432/app")
t.Setenv("DATABASE_MAX_CONNS", "7")
t.Setenv("DATABASE_MIN_CONNS", "2")
defer func() {
_ = os.Unsetenv("DATABASE_MAX_CONNS")
_ = os.Unsetenv("DATABASE_MIN_CONNS")
}()
cfg, err := FromEnv()
if err != nil {
t.Fatalf("FromEnv() error = %v", err)
}
if cfg.MaxConns != 7 || cfg.MinConns != 2 {
t.Fatalf("pool limits = (%d, %d), want (7, 2)", cfg.MaxConns, cfg.MinConns)
}
}