From aee8db9b3f1a7f1795688cb1f16b23cbf256515e Mon Sep 17 00:00:00 2001 From: Aska Date: Sun, 9 Aug 2026 20:46:41 +0800 Subject: [PATCH] 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 --- backend/go.mod | 6 +- backend/go.sum | 4 + backend/internal/auth/.gitkeep | 0 backend/internal/auth/auth.go | 102 +++++++++++++++ backend/internal/auth/auth_test.go | 128 +++++++++++++++++++ backend/internal/platform/platform.go | 141 +++++++++++++++++++++ backend/internal/platform/platform_test.go | 64 ++++++++++ 7 files changed, 444 insertions(+), 1 deletion(-) delete mode 100644 backend/internal/auth/.gitkeep create mode 100644 backend/internal/auth/auth.go create mode 100644 backend/internal/auth/auth_test.go create mode 100644 backend/internal/platform/platform.go create mode 100644 backend/internal/platform/platform_test.go diff --git a/backend/go.mod b/backend/go.mod index 852595d..b75a4b3 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -4,4 +4,8 @@ go 1.25.0 require github.com/joho/godotenv v1.5.1 -require github.com/lib/pq v1.12.3 +require ( + github.com/golang-jwt/jwt/v5 v5.3.1 + github.com/lib/pq v1.12.3 + golang.org/x/crypto v0.54.0 +) diff --git a/backend/go.sum b/backend/go.sum index 0114102..5a291ca 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -1,4 +1,8 @@ +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/lib/pq v1.12.3 h1:tTWxr2YLKwIvK90ZXEw8GP7UFHtcbTtty8zsI+YjrfQ= github.com/lib/pq v1.12.3/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA= +golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= +golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= diff --git a/backend/internal/auth/.gitkeep b/backend/internal/auth/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/backend/internal/auth/auth.go b/backend/internal/auth/auth.go new file mode 100644 index 0000000..5971116 --- /dev/null +++ b/backend/internal/auth/auth.go @@ -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) +} diff --git a/backend/internal/auth/auth_test.go b/backend/internal/auth/auth_test.go new file mode 100644 index 0000000..aad594b --- /dev/null +++ b/backend/internal/auth/auth_test.go @@ -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) + } +} diff --git a/backend/internal/platform/platform.go b/backend/internal/platform/platform.go new file mode 100644 index 0000000..1cdfc4b --- /dev/null +++ b/backend/internal/platform/platform.go @@ -0,0 +1,141 @@ +// Package platform detects the runtime OS and environment, +// providing platform-specific paths and configuration defaults. +package platform + +import ( + "os" + "path/filepath" + "runtime" +) + +// Platform holds information about the current runtime environment. +type Platform struct { + OS string // "linux", "windows", "darwin" + Arch string // "amd64", "arm64" + + IsTermux bool // Running inside Termux (ANDROID_ROOT set) + IsWSL bool // Running inside WSL + IsDocker bool // Running inside a Docker container + IsWindows bool // runtime.GOOS == "windows" + IsLinux bool // runtime.GOOS == "linux" + IsDarwin bool // runtime.GOOS == "darwin" + IsARM64 bool // runtime.GOARCH == "arm64" +} + +// Detect returns the current platform information. +func Detect() *Platform { + p := &Platform{ + OS: runtime.GOOS, + Arch: runtime.GOARCH, + IsWindows: runtime.GOOS == "windows", + IsLinux: runtime.GOOS == "linux", + IsDarwin: runtime.GOOS == "darwin", + IsARM64: runtime.GOARCH == "arm64", + } + + // Detect Termux + if _, ok := os.LookupEnv("ANDROID_ROOT"); ok { + p.IsTermux = true + } + + // Detect WSL + if _, err := os.Stat("/proc/sys/fs/binfmt_misc/WSL"); err == nil { + p.IsWSL = true + } + + // Detect Docker + if _, err := os.Stat("/.dockerenv"); err == nil { + p.IsDocker = true + } + + return p +} + +// DataDir returns the default application data directory. +func (p *Platform) DataDir() string { + home, _ := os.UserHomeDir() + switch { + case p.IsWindows: + return filepath.Join(os.Getenv("APPDATA"), "Cyrene") + case p.IsDarwin: + return filepath.Join(home, "Library", "Application Support", "Cyrene") + case p.IsTermux: + return filepath.Join(home, "storage", "shared", "Cyrene") + default: // Linux + return filepath.Join(home, ".local", "share", "cyrene") + } +} + +// ConfigDir returns the default configuration directory. +func (p *Platform) ConfigDir() string { + home, _ := os.UserHomeDir() + switch { + case p.IsWindows: + return filepath.Join(os.Getenv("APPDATA"), "Cyrene", "config") + case p.IsDarwin: + return filepath.Join(home, "Library", "Application Support", "Cyrene", "config") + case p.IsTermux: + return filepath.Join(home, ".config", "cyrene") + default: // Linux + return filepath.Join(home, ".config", "cyrene") + } +} + +// CacheDir returns the default cache directory. +func (p *Platform) CacheDir() string { + home, _ := os.UserHomeDir() + switch { + case p.IsWindows: + return filepath.Join(os.Getenv("LOCALAPPDATA"), "Cyrene", "cache") + case p.IsDarwin: + return filepath.Join(home, "Library", "Caches", "Cyrene") + default: // Linux / Termux + return filepath.Join(home, ".cache", "cyrene") + } +} + +// EnsureDirs creates the data, config, and cache directories if they don't exist. +func (p *Platform) EnsureDirs() error { + for _, dir := range []string{p.DataDir(), p.ConfigDir(), p.CacheDir()} { + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + } + return nil +} + +// DefaultNATSURL returns the default NATS connection URL. +func (p *Platform) DefaultNATSURL() string { + return "nats://localhost:4222" +} + +// DefaultPGHost returns the default PostgreSQL host. +func (p *Platform) DefaultPGHost() string { + return "localhost" +} + +// Summary returns a human-readable platform description. +func (p *Platform) Summary() string { + s := p.OS + "/" + p.Arch + var tags []string + if p.IsDocker { + tags = append(tags, "docker") + } + if p.IsWSL { + tags = append(tags, "wsl") + } + if p.IsTermux { + tags = append(tags, "termux") + } + if len(tags) > 0 { + s += " (" + for i, t := range tags { + if i > 0 { + s += ", " + } + s += t + } + s += ")" + } + return s +} diff --git a/backend/internal/platform/platform_test.go b/backend/internal/platform/platform_test.go new file mode 100644 index 0000000..ef37516 --- /dev/null +++ b/backend/internal/platform/platform_test.go @@ -0,0 +1,64 @@ +package platform + +import ( + "runtime" + "testing" +) + +func TestDetect(t *testing.T) { + p := Detect() + + if p.OS != runtime.GOOS { + t.Errorf("expected OS=%s, got %s", runtime.GOOS, p.OS) + } + if p.Arch != runtime.GOARCH { + t.Errorf("expected Arch=%s, got %s", runtime.GOARCH, p.Arch) + } + if runtime.GOOS == "linux" && !p.IsLinux { + t.Error("expected IsLinux=true on Linux") + } +} + +func TestDataDir(t *testing.T) { + p := Detect() + dir := p.DataDir() + if dir == "" { + t.Error("DataDir should not be empty") + } +} + +func TestConfigDir(t *testing.T) { + p := Detect() + dir := p.ConfigDir() + if dir == "" { + t.Error("ConfigDir should not be empty") + } +} + +func TestCacheDir(t *testing.T) { + p := Detect() + dir := p.CacheDir() + if dir == "" { + t.Error("CacheDir should not be empty") + } +} + +func TestSummary(t *testing.T) { + p := Detect() + s := p.Summary() + if s == "" { + t.Error("Summary should not be empty") + } + // Should contain the OS name + if len(s) < 3 { + t.Errorf("Summary too short: %s", s) + } +} + +func TestDefaultNATSURL(t *testing.T) { + p := Detect() + url := p.DefaultNATSURL() + if url != "nats://localhost:4222" { + t.Errorf("expected nats://localhost:4222, got %s", url) + } +}