first
This commit is contained in:
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user