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

+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)
}
}