feat(auth): implement TOTP setup and management
Lint / Lint (Node/Svelte) (push) Successful in 24s
Lint / Lint (Go) (push) Successful in 28s
Lint / Lint (Python) (push) Failing after 14s
Tests / Test (Node/Svelte) (push) Successful in 18s
Tests / Test (Go) (push) Successful in 25s
Tests / Test (Python) (push) Successful in 12s
Lint / Lint (Node/Svelte) (push) Successful in 24s
Lint / Lint (Go) (push) Successful in 28s
Lint / Lint (Python) (push) Failing after 14s
Tests / Test (Node/Svelte) (push) Successful in 18s
Tests / Test (Go) (push) Successful in 25s
Tests / Test (Python) (push) Successful in 12s
- Added TOTP support for two-factor authentication in the auth module. - Introduced new types and interfaces for TOTP setup and token actions in the web UI. - Created backend logic for generating and verifying TOTP secrets and tokens. - Implemented user management features including role assignments and user CRUD operations. - Enhanced UI components for managing users and TOTP settings. - Added styles for optional labels and authentication reset links. - Implemented reset code generation and validation for admin accounts.
This commit is contained in:
1 parent
2f57554154
commit
da97fd4fb1
30 files changed
+2145
-27
No files matched your search
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
+172
-7
@@ -21,6 +21,7 @@ type User struct {
|
||||
Username string
|
||||
Email string
|
||||
PasswordHash string
|
||||
Role Role
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
@@ -62,12 +63,21 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
|
||||
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 <> '';
|
||||
|
||||
@@ -91,6 +101,8 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
|
||||
`); 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 {
|
||||
@@ -109,6 +121,65 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
|
||||
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 {
|
||||
@@ -129,11 +200,13 @@ func (s *Store) CreateUser(ctx context.Context, username, email, passwordHash st
|
||||
}
|
||||
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
|
||||
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.CreatedAt, &user.UpdatedAt,
|
||||
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
@@ -151,7 +224,7 @@ func (s *Store) FindByIdentifier(ctx context.Context, identifier string) (*User,
|
||||
return nil, err
|
||||
}
|
||||
return s.find(ctx, `
|
||||
SELECT id, username, email, password_hash, created_at, updated_at
|
||||
SELECT id, username, email, password_hash, role, created_at, updated_at
|
||||
FROM auth_users
|
||||
WHERE username = $1 OR lower(email) = lower($1)
|
||||
`, identifier)
|
||||
@@ -163,7 +236,7 @@ func (s *Store) FindByID(ctx context.Context, id int64) (*User, error) {
|
||||
return nil, err
|
||||
}
|
||||
return s.find(ctx, `
|
||||
SELECT id, username, email, password_hash, created_at, updated_at
|
||||
SELECT id, username, email, password_hash, role, created_at, updated_at
|
||||
FROM auth_users WHERE id = $1
|
||||
`, id)
|
||||
}
|
||||
@@ -184,6 +257,86 @@ func (s *Store) UpdateCredentials(ctx context.Context, id int64, username, email
|
||||
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 {
|
||||
@@ -205,7 +358,7 @@ func (s *Store) FindSessionUser(ctx context.Context, tokenHash string) (*User, e
|
||||
return nil, err
|
||||
}
|
||||
return s.find(ctx, `
|
||||
SELECT u.id, u.username, u.email, u.password_hash, u.created_at, u.updated_at
|
||||
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()
|
||||
@@ -234,6 +387,18 @@ func (s *Store) DeleteSessionsForUser(ctx context.Context, userID int64) error {
|
||||
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 {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
@@ -35,3 +37,33 @@ func TestNewSessionToken(t *testing.T) {
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user