This commit is contained in:
CFOU
2026-09-14 20:50:19 +02:00
commit 3091fb4020
135 changed files with 10262 additions and 0 deletions
+104
View File
@@ -0,0 +1,104 @@
package security
import (
"errors"
"fmt"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
)
// Audience separates admin-space tokens from customer-space tokens so a
// token issued for one space can never be accepted by the other, even
// though both are signed with the same server secret.
type Audience string
const (
AudienceAdmin Audience = "admin"
AudienceCustomer Audience = "customer"
)
// Claims are the JWT claims carried by access tokens issued by this platform.
type Claims struct {
Role string `json:"role"`
jwt.RegisteredClaims
}
// IssueAccessToken creates a signed, short-lived access token for the given
// user, role and audience (admin or customer space).
func IssueAccessToken(secret string, ttl time.Duration, userID uuid.UUID, role string, aud Audience) (string, error) {
if role == "" {
return "", fmt.Errorf("role must not be empty")
}
now := time.Now()
claims := Claims{
Role: role,
RegisteredClaims: jwt.RegisteredClaims{
Subject: userID.String(),
Audience: jwt.ClaimStrings{string(aud)},
IssuedAt: jwt.NewNumericDate(now),
NotBefore: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(ttl)),
ID: uuid.NewString(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signed, err := token.SignedString([]byte(secret))
if err != nil {
return "", fmt.Errorf("sign token: %w", err)
}
return signed, nil
}
// ParseAccessToken verifies signature, algorithm and every claim explicitly:
// - signing method must be HMAC (rejects "alg":"none" and any asymmetric swap attempt)
// - exp/iat/nbf must be present and internally consistent (no expired/not-yet-valid tokens)
// - aud must match exactly the expected audience (admin token can never pass as a customer token, or vice versa)
// - sub must be present and a well-formed UUID (matches our user ID format)
// - role must be present and non-empty
// - jti must be present (reserved for future revocation lookups)
func ParseAccessToken(secret string, tokenString string, expectedAud Audience) (*Claims, error) {
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
}
return []byte(secret), nil
}, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Name}))
if err != nil {
return nil, fmt.Errorf("parse token: %w", err)
}
if !token.Valid {
return nil, errors.New("invalid token")
}
if claims.ExpiresAt == nil {
return nil, errors.New("missing exp claim")
}
if claims.IssuedAt == nil {
return nil, errors.New("missing iat claim")
}
if claims.ID == "" {
return nil, errors.New("missing jti claim")
}
if claims.Subject == "" {
return nil, errors.New("missing sub claim")
}
if _, err := uuid.Parse(claims.Subject); err != nil {
return nil, fmt.Errorf("invalid sub claim: %w", err)
}
if claims.Role == "" {
return nil, errors.New("missing role claim")
}
if len(claims.Audience) != 1 || claims.Audience[0] != string(expectedAud) {
return nil, fmt.Errorf("token audience does not match expected space %q", expectedAud)
}
return claims, nil
}
@@ -0,0 +1,82 @@
// Package security provides password hashing and JWT issuing/verification
// shared across auth modules.
package security
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
const (
argon2Time = 3
argon2Memory = 64 * 1024 // 64 MB
argon2Threads = 2
argon2SaltLen = 16
argon2KeyLen = 32
)
// HashPassword hashes a plaintext password using argon2id and returns the
// PHC-formatted string ($argon2id$v=19$m=...,t=...,p=...$salt$hash).
func HashPassword(password string) (string, error) {
salt := make([]byte, argon2SaltLen)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("generate salt: %w", err)
}
hash := argon2.IDKey([]byte(password), salt, argon2Time, argon2Memory, argon2Threads, argon2KeyLen)
encoded := fmt.Sprintf(
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version,
argon2Memory,
argon2Time,
argon2Threads,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(hash),
)
return encoded, nil
}
// VerifyPassword checks a plaintext password against a PHC-formatted argon2id hash.
func VerifyPassword(encodedHash, password string) (bool, error) {
parts := strings.Split(encodedHash, "$")
if len(parts) != 6 || parts[1] != "argon2id" {
return false, fmt.Errorf("invalid hash format")
}
var version int
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
return false, fmt.Errorf("invalid hash version segment: %w", err)
}
if version != argon2.Version {
return false, fmt.Errorf("unsupported argon2 version: %d", version)
}
var memory uint32
var time uint32
var threads uint8
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &time, &threads); err != nil {
return false, fmt.Errorf("invalid hash params segment: %w", err)
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil {
return false, fmt.Errorf("decode salt: %w", err)
}
wantHash, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil {
return false, fmt.Errorf("decode hash: %w", err)
}
gotHash := argon2.IDKey([]byte(password), salt, time, memory, threads, uint32(len(wantHash)))
if subtle.ConstantTimeCompare(gotHash, wantHash) == 1 {
return true, nil
}
return false, nil
}