refactor: follow the google go style guide
Document every package and exported identifier, return the log level from NewLogger instead of keeping it in a package variable, and stop tests from mutating the argon2 parameters. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
048e114fd9
commit
d20225982a
21 files changed
+147
-36
No files matched your search
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Names shared with the browser side.
|
||||
const (
|
||||
CookieName = "__Host-session"
|
||||
CSRFHeader = "X-CSRF-Token"
|
||||
@@ -15,6 +16,8 @@ const (
|
||||
ctxKey = "auth.session"
|
||||
)
|
||||
|
||||
// SetCookie sends the session cookie. The __Host- prefix makes browsers
|
||||
// reject it unless it is Secure, host-only and scoped to /.
|
||||
func SetCookie(c *gin.Context, sess *Session, maxAge int) {
|
||||
http.SetCookie(c.Writer, &http.Cookie{
|
||||
Name: CookieName,
|
||||
@@ -27,6 +30,7 @@ func SetCookie(c *gin.Context, sess *Session, maxAge int) {
|
||||
})
|
||||
}
|
||||
|
||||
// ClearCookie removes the session cookie.
|
||||
func ClearCookie(c *gin.Context) {
|
||||
http.SetCookie(c.Writer, &http.Cookie{Name: CookieName, Value: "", Path: "/", MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
|
||||
}
|
||||
@@ -54,6 +58,7 @@ func (s *Sessions) Load() gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// Require aborts with 401 unless Load attached a session.
|
||||
func Require() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if Current(c) == nil {
|
||||
@@ -104,6 +109,7 @@ func sameOrigin(r *http.Request) bool {
|
||||
return err == nil && u.Host == r.Host
|
||||
}
|
||||
|
||||
// Current returns the session attached by Load, or nil.
|
||||
func Current(c *gin.Context) *Session {
|
||||
v, ok := c.Get(ctxKey)
|
||||
if !ok {
|
||||
|
||||
@@ -7,11 +7,11 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
// OWASP 2024 baseline for argon2id.
|
||||
type argonParams struct {
|
||||
memory uint32
|
||||
time uint32
|
||||
@@ -19,24 +19,32 @@ type argonParams struct {
|
||||
keyLen uint32
|
||||
}
|
||||
|
||||
var current = argonParams{memory: 19 * 1024, time: 2, threads: 1, keyLen: 32}
|
||||
// defaultParams is the OWASP baseline for argon2id. Raising it makes
|
||||
// VerifyPassword request a rehash of older hashes on their next login.
|
||||
var defaultParams = argonParams{memory: 19 * 1024, time: 2, threads: 1, keyLen: 32}
|
||||
|
||||
// MinPasswordLength follows NIST SP 800-63B; no composition rules apply.
|
||||
const MinPasswordLength = 12
|
||||
|
||||
// ErrPasswordTooShort is returned by HashPassword.
|
||||
var ErrPasswordTooShort = fmt.Errorf("auth: password must have at least %d characters", MinPasswordLength)
|
||||
|
||||
// HashPassword returns an argon2id hash in PHC string format.
|
||||
func HashPassword(pw string) (string, error) {
|
||||
if len([]rune(pw)) < MinPasswordLength {
|
||||
return "", ErrPasswordTooShort
|
||||
}
|
||||
return hashPassword(pw, defaultParams), nil
|
||||
}
|
||||
|
||||
func hashPassword(pw string, p argonParams) string {
|
||||
salt := make([]byte, 16)
|
||||
_, _ = rand.Read(salt)
|
||||
p := current
|
||||
hash := argon2.IDKey([]byte(pw), salt, p.time, p.memory, p.threads, p.keyLen)
|
||||
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, p.memory, p.time, p.threads,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(hash)), nil
|
||||
base64.RawStdEncoding.EncodeToString(hash))
|
||||
}
|
||||
|
||||
// VerifyPassword reports whether pw matches and whether the stored hash uses
|
||||
@@ -48,13 +56,14 @@ func VerifyPassword(encoded, pw string) (ok, rehash bool, err error) {
|
||||
}
|
||||
got := argon2.IDKey([]byte(pw), salt, p.time, p.memory, p.threads, uint32(len(want)))
|
||||
ok = subtle.ConstantTimeCompare(got, want) == 1
|
||||
return ok, ok && p != current, nil
|
||||
return ok, ok && p != defaultParams, nil
|
||||
}
|
||||
|
||||
// dummyHash keeps the response time of unknown accounts equal to known ones.
|
||||
var dummyHash, _ = HashPassword("not-a-real-password-for-timing")
|
||||
var dummyHash = sync.OnceValue(func() string { return hashPassword("timing-equalizer", defaultParams) })
|
||||
|
||||
func BurnPasswordCheck(pw string) { _, _, _ = VerifyPassword(dummyHash, pw) }
|
||||
// BurnPasswordCheck spends the time of a real verification. Call it when the
|
||||
// account does not exist so response times do not reveal that.
|
||||
func BurnPasswordCheck(pw string) { _, _, _ = VerifyPassword(dummyHash(), pw) }
|
||||
|
||||
func decodeHash(s string) (argonParams, []byte, []byte, error) {
|
||||
var p argonParams
|
||||
|
||||
@@ -7,10 +7,12 @@ import (
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// Limiter counts attempts per key in fixed windows stored in Redis.
|
||||
type Limiter struct {
|
||||
rdb redis.UniversalClient
|
||||
}
|
||||
|
||||
// NewLimiter returns a Limiter backed by rdb.
|
||||
func NewLimiter(rdb redis.UniversalClient) *Limiter { return &Limiter{rdb: rdb} }
|
||||
|
||||
var incrWithTTL = redis.NewScript(`
|
||||
@@ -27,6 +29,7 @@ func (l *Limiter) Allow(ctx context.Context, key string, limit int, window time.
|
||||
return n <= limit, nil
|
||||
}
|
||||
|
||||
// Reset clears the counter for key, e.g. after a successful login.
|
||||
func (l *Limiter) Reset(ctx context.Context, key string) error {
|
||||
return l.rdb.Del(ctx, "rl:"+key).Err()
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
// Package auth implements sessions, password and TOTP verification, rate
|
||||
// limiting and CSRF protection.
|
||||
package auth
|
||||
|
||||
import (
|
||||
@@ -16,8 +18,11 @@ import (
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// ErrNoSession is returned for unknown, expired or malformed sessions.
|
||||
var ErrNoSession = errors.New("auth: no session")
|
||||
|
||||
// Session is a signed-in browser. Token is the cookie value and never
|
||||
// stored server side.
|
||||
type Session struct {
|
||||
Token string
|
||||
UserID uuid.UUID
|
||||
@@ -27,10 +32,12 @@ type Session struct {
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// CheckCSRF compares token with the session's CSRF token in constant time.
|
||||
func (s *Session) CheckCSRF(token string) bool {
|
||||
return token != "" && subtle.ConstantTimeCompare([]byte(token), []byte(s.CSRF)) == 1
|
||||
}
|
||||
|
||||
// Sessions stores sessions in Redis so any API replica can serve any request.
|
||||
type Sessions struct {
|
||||
rdb redis.UniversalClient
|
||||
idle time.Duration
|
||||
@@ -38,6 +45,8 @@ type Sessions struct {
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// NewSessions returns a store whose sessions expire after idle without use
|
||||
// and after absolute regardless of use.
|
||||
func NewSessions(rdb redis.UniversalClient, idle, absolute time.Duration) *Sessions {
|
||||
return &Sessions{rdb: rdb, idle: idle, absolute: absolute, now: time.Now}
|
||||
}
|
||||
@@ -51,12 +60,14 @@ func key(token string) string {
|
||||
|
||||
func userIndex(id uuid.UUID) string { return "user_sessions:" + id.String() }
|
||||
|
||||
// RandomToken returns 256 bits of randomness, URL-safe encoded.
|
||||
func RandomToken() string {
|
||||
b := make([]byte, 32)
|
||||
_, _ = rand.Read(b)
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
// Create starts a session. org and locale may be empty.
|
||||
func (s *Sessions) Create(ctx context.Context, user, org uuid.UUID, locale string) (*Session, error) {
|
||||
sess := &Session{
|
||||
Token: RandomToken(),
|
||||
@@ -86,6 +97,7 @@ func (s *Sessions) Create(ctx context.Context, user, org uuid.UUID, locale strin
|
||||
return sess, nil
|
||||
}
|
||||
|
||||
// Get loads the session for token and extends its idle expiry.
|
||||
func (s *Sessions) Get(ctx context.Context, token string) (*Session, error) {
|
||||
if token == "" {
|
||||
return nil, ErrNoSession
|
||||
@@ -115,6 +127,8 @@ func (s *Sessions) Get(ctx context.Context, token string) (*Session, error) {
|
||||
return sess, nil
|
||||
}
|
||||
|
||||
// SwitchOrg changes the active organization. Membership must be checked
|
||||
// by the caller.
|
||||
func (s *Sessions) SwitchOrg(ctx context.Context, sess *Session, org uuid.UUID) error {
|
||||
if err := s.rdb.HSet(ctx, key(sess.Token), "org", orgString(org)).Err(); err != nil {
|
||||
return fmt.Errorf("auth: switch org: %w", err)
|
||||
@@ -123,6 +137,7 @@ func (s *Sessions) SwitchOrg(ctx context.Context, sess *Session, org uuid.UUID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetLocale changes the session language.
|
||||
func (s *Sessions) SetLocale(ctx context.Context, sess *Session, locale string) error {
|
||||
if err := s.rdb.HSet(ctx, key(sess.Token), "locale", locale).Err(); err != nil {
|
||||
return fmt.Errorf("auth: set locale: %w", err)
|
||||
@@ -131,6 +146,7 @@ func (s *Sessions) SetLocale(ctx context.Context, sess *Session, locale string)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Delete ends sess.
|
||||
func (s *Sessions) Delete(ctx context.Context, sess *Session) error {
|
||||
k := key(sess.Token)
|
||||
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
|
||||
|
||||
@@ -12,6 +12,8 @@ import (
|
||||
|
||||
const totpIssuer = "uptimesebi"
|
||||
|
||||
// NewTOTPKey generates a secret for account using the defaults every common
|
||||
// authenticator app supports (SHA-1, 6 digits, 30 s).
|
||||
func NewTOTPKey(account string) (*otp.Key, error) {
|
||||
return totp.Generate(totp.GenerateOpts{Issuer: totpIssuer, AccountName: account})
|
||||
}
|
||||
@@ -23,10 +25,13 @@ type TOTPVerifier struct {
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// NewTOTPVerifier returns a verifier that records used codes in rdb.
|
||||
func NewTOTPVerifier(rdb redis.UniversalClient) *TOTPVerifier {
|
||||
return &TOTPVerifier{rdb: rdb, now: time.Now}
|
||||
}
|
||||
|
||||
// Verify accepts code for secret within one step of clock skew, at most once
|
||||
// per user.
|
||||
func (v *TOTPVerifier) Verify(ctx context.Context, user uuid.UUID, secret, code string) (bool, error) {
|
||||
ok, err := totp.ValidateCustom(code, secret, v.now(), totp.ValidateOpts{
|
||||
Period: 30, Skew: 1, Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1,
|
||||
|
||||
Reference in new issue
Block a user