feat(internal): add platform detection and auth packages
- internal/platform: cross-platform path detection, 6 tests - internal/auth: JWT generation/validation + bcrypt, 8 tests - 89 total tests, build + vet clean
This commit is contained in:
1 parent
ca106f71ae
commit
aee8db9b3f
7 files changed
+444
-1
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,102 @@
|
||||
// Package auth provides JWT token generation and validation for the Cyrene platform.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// Claims represents the JWT claims for a Cyrene user.
|
||||
type Claims struct {
|
||||
jwt.RegisteredClaims
|
||||
UserID string `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"` // "admin" | "user"
|
||||
}
|
||||
|
||||
// TokenManager handles JWT creation and validation.
|
||||
type TokenManager struct {
|
||||
secret []byte
|
||||
expiry time.Duration
|
||||
}
|
||||
|
||||
// NewTokenManager creates a new TokenManager.
|
||||
// secret must be at least 32 characters.
|
||||
func NewTokenManager(secret string, expiryHours int) *TokenManager {
|
||||
return &TokenManager{
|
||||
secret: []byte(secret),
|
||||
expiry: time.Duration(expiryHours) * time.Hour,
|
||||
}
|
||||
}
|
||||
|
||||
// Generate creates a signed JWT token for the given user.
|
||||
func (tm *TokenManager) Generate(userID, username, role string) (string, error) {
|
||||
now := time.Now()
|
||||
claims := &Claims{
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Issuer: "cyrene",
|
||||
Subject: userID,
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
ExpiresAt: jwt.NewNumericDate(now.Add(tm.expiry)),
|
||||
ID: generateTokenID(),
|
||||
},
|
||||
UserID: userID,
|
||||
Username: username,
|
||||
Role: role,
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString(tm.secret)
|
||||
}
|
||||
|
||||
// Validate parses and validates a JWT token string.
|
||||
// Returns the Claims if valid, or an error.
|
||||
func (tm *TokenManager) Validate(tokenStr string) (*Claims, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(token *jwt.Token) (any, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return tm.secret, nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse token: %w", err)
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*Claims)
|
||||
if !ok || !token.Valid {
|
||||
return nil, fmt.Errorf("invalid token")
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
// IsAdmin checks if the claims belong to an admin user.
|
||||
func (c *Claims) IsAdmin() bool {
|
||||
return c.Role == "admin"
|
||||
}
|
||||
|
||||
// HashPassword creates a bcrypt hash of the password.
|
||||
func HashPassword(password string) (string, error) {
|
||||
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("hash password: %w", err)
|
||||
}
|
||||
return string(bytes), nil
|
||||
}
|
||||
|
||||
// CheckPassword compares a password with its bcrypt hash.
|
||||
func CheckPassword(password, hash string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func generateTokenID() string {
|
||||
b := make([]byte, 16)
|
||||
rand.Read(b)
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestGenerateAndValidate(t *testing.T) {
|
||||
tm := NewTokenManager("a-very-long-secret-key-that-is-at-least-32-bytes!!", 720)
|
||||
|
||||
token, err := tm.Generate("user-123", "testuser", "admin")
|
||||
if err != nil {
|
||||
t.Fatalf("Generate error: %v", err)
|
||||
}
|
||||
if token == "" {
|
||||
t.Fatal("token should not be empty")
|
||||
}
|
||||
|
||||
claims, err := tm.Validate(token)
|
||||
if err != nil {
|
||||
t.Fatalf("Validate error: %v", err)
|
||||
}
|
||||
|
||||
if claims.UserID != "user-123" {
|
||||
t.Errorf("expected UserID=user-123, got %s", claims.UserID)
|
||||
}
|
||||
if claims.Username != "testuser" {
|
||||
t.Errorf("expected Username=testuser, got %s", claims.Username)
|
||||
}
|
||||
if claims.Role != "admin" {
|
||||
t.Errorf("expected Role=admin, got %s", claims.Role)
|
||||
}
|
||||
if !claims.IsAdmin() {
|
||||
t.Error("expected IsAdmin()=true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateInvalidToken(t *testing.T) {
|
||||
tm := NewTokenManager("the-real-secret-key-that-is-32-bytes!!", 720)
|
||||
|
||||
_, err := tm.Validate("invalid.token.here")
|
||||
if err == nil {
|
||||
t.Error("expected error for invalid token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateWrongSecret(t *testing.T) {
|
||||
tm1 := NewTokenManager("secret-key-number-one-that-is-32-bytes!", 720)
|
||||
tm2 := NewTokenManager("secret-key-number-two-that-is-32-bytes!", 720)
|
||||
|
||||
token, _ := tm1.Generate("user-1", "test", "user")
|
||||
_, err := tm2.Validate(token)
|
||||
if err == nil {
|
||||
t.Error("expected error when validating with wrong secret")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpiredToken(t *testing.T) {
|
||||
tm := NewTokenManager("a-very-long-secret-key-that-is-at-least-32-bytes!!", -1) // expired immediately
|
||||
|
||||
token, err := tm.Generate("user-1", "test", "user")
|
||||
if err != nil {
|
||||
t.Fatalf("Generate error: %v", err)
|
||||
}
|
||||
|
||||
_, err = tm.Validate(token)
|
||||
if err == nil {
|
||||
t.Error("expected error for expired token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashPassword(t *testing.T) {
|
||||
hash, err := HashPassword("my-secure-password")
|
||||
if err != nil {
|
||||
t.Fatalf("HashPassword error: %v", err)
|
||||
}
|
||||
if hash == "" {
|
||||
t.Fatal("hash should not be empty")
|
||||
}
|
||||
if hash == "my-secure-password" {
|
||||
t.Error("hash should not be the plaintext password")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckPassword(t *testing.T) {
|
||||
hash, _ := HashPassword("correct-password")
|
||||
|
||||
if !CheckPassword("correct-password", hash) {
|
||||
t.Error("expected password to match")
|
||||
}
|
||||
if CheckPassword("wrong-password", hash) {
|
||||
t.Error("expected wrong password to not match")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaimsIsAdmin(t *testing.T) {
|
||||
admin := &Claims{Role: "admin"}
|
||||
user := &Claims{Role: "user"}
|
||||
empty := &Claims{}
|
||||
|
||||
if !admin.IsAdmin() {
|
||||
t.Error("admin claims should have IsAdmin()=true")
|
||||
}
|
||||
if user.IsAdmin() {
|
||||
t.Error("user claims should have IsAdmin()=false")
|
||||
}
|
||||
if empty.IsAdmin() {
|
||||
t.Error("empty claims should have IsAdmin()=false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenManagerExpiry(t *testing.T) {
|
||||
tm := NewTokenManager("a-very-long-secret-key-that-is-at-least-32-bytes!!", 1) // 1 hour
|
||||
|
||||
token, _ := tm.Generate("user-1", "test", "user")
|
||||
claims, err := tm.Validate(token)
|
||||
if err != nil {
|
||||
t.Fatalf("Validate error: %v", err)
|
||||
}
|
||||
|
||||
issuedAt := claims.IssuedAt.Time
|
||||
expiresAt := claims.ExpiresAt.Time
|
||||
diff := expiresAt.Sub(issuedAt)
|
||||
|
||||
if diff < 59*time.Minute || diff > 61*time.Minute {
|
||||
t.Errorf("expected expiry ~1 hour from issue, got %v", diff)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user