start working on the frontend side

This commit is contained in:
Warp Agent
2025-12-24 19:53:45 +00:00
parent 3aa0169af0
commit c962a223c6
84 changed files with 14761 additions and 58 deletions

143
backend/internal/common/cache/cache.go vendored Normal file
View File

@@ -0,0 +1,143 @@
package cache
import (
"crypto/sha256"
"encoding/hex"
"sync"
"time"
)
// CacheEntry represents a cached value with expiration
type CacheEntry struct {
Value interface{}
ExpiresAt time.Time
CreatedAt time.Time
}
// IsExpired checks if the cache entry has expired
func (e *CacheEntry) IsExpired() bool {
return time.Now().After(e.ExpiresAt)
}
// Cache provides an in-memory cache with TTL support
type Cache struct {
entries map[string]*CacheEntry
mu sync.RWMutex
ttl time.Duration
}
// NewCache creates a new cache with a default TTL
func NewCache(defaultTTL time.Duration) *Cache {
c := &Cache{
entries: make(map[string]*CacheEntry),
ttl: defaultTTL,
}
// Start background cleanup goroutine
go c.cleanup()
return c
}
// Get retrieves a value from the cache
func (c *Cache) Get(key string) (interface{}, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
entry, exists := c.entries[key]
if !exists {
return nil, false
}
if entry.IsExpired() {
// Don't delete here, let cleanup handle it
return nil, false
}
return entry.Value, true
}
// Set stores a value in the cache with the default TTL
func (c *Cache) Set(key string, value interface{}) {
c.SetWithTTL(key, value, c.ttl)
}
// SetWithTTL stores a value in the cache with a custom TTL
func (c *Cache) SetWithTTL(key string, value interface{}, ttl time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.entries[key] = &CacheEntry{
Value: value,
ExpiresAt: time.Now().Add(ttl),
CreatedAt: time.Now(),
}
}
// Delete removes a value from the cache
func (c *Cache) Delete(key string) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.entries, key)
}
// Clear removes all entries from the cache
func (c *Cache) Clear() {
c.mu.Lock()
defer c.mu.Unlock()
c.entries = make(map[string]*CacheEntry)
}
// cleanup periodically removes expired entries
func (c *Cache) cleanup() {
ticker := time.NewTicker(1 * time.Minute)
defer ticker.Stop()
for range ticker.C {
c.mu.Lock()
for key, entry := range c.entries {
if entry.IsExpired() {
delete(c.entries, key)
}
}
c.mu.Unlock()
}
}
// Stats returns cache statistics
func (c *Cache) Stats() map[string]interface{} {
c.mu.RLock()
defer c.mu.RUnlock()
total := len(c.entries)
expired := 0
for _, entry := range c.entries {
if entry.IsExpired() {
expired++
}
}
return map[string]interface{}{
"total_entries": total,
"active_entries": total - expired,
"expired_entries": expired,
"default_ttl_seconds": int(c.ttl.Seconds()),
}
}
// GenerateKey generates a cache key from a string
func GenerateKey(prefix string, parts ...string) string {
key := prefix
for _, part := range parts {
key += ":" + part
}
// Hash long keys to keep them manageable
if len(key) > 200 {
hash := sha256.Sum256([]byte(key))
return prefix + ":" + hex.EncodeToString(hash[:])
}
return key
}

View File

@@ -14,6 +14,7 @@ type Config struct {
Database DatabaseConfig `yaml:"database"`
Auth AuthConfig `yaml:"auth"`
Logging LoggingConfig `yaml:"logging"`
Security SecurityConfig `yaml:"security"`
}
// ServerConfig holds HTTP server configuration
@@ -23,6 +24,14 @@ type ServerConfig struct {
ReadTimeout time.Duration `yaml:"read_timeout"`
WriteTimeout time.Duration `yaml:"write_timeout"`
IdleTimeout time.Duration `yaml:"idle_timeout"`
Cache CacheConfig `yaml:"cache"`
}
// CacheConfig holds response caching configuration
type CacheConfig struct {
Enabled bool `yaml:"enabled"`
DefaultTTL time.Duration `yaml:"default_ttl"`
MaxAge int `yaml:"max_age"` // seconds for Cache-Control header
}
// DatabaseConfig holds PostgreSQL connection configuration
@@ -60,6 +69,33 @@ type LoggingConfig struct {
Format string `yaml:"format"` // json or text
}
// SecurityConfig holds security-related configuration
type SecurityConfig struct {
CORS CORSConfig `yaml:"cors"`
RateLimit RateLimitConfig `yaml:"rate_limit"`
SecurityHeaders SecurityHeadersConfig `yaml:"security_headers"`
}
// CORSConfig holds CORS configuration
type CORSConfig struct {
AllowedOrigins []string `yaml:"allowed_origins"`
AllowedMethods []string `yaml:"allowed_methods"`
AllowedHeaders []string `yaml:"allowed_headers"`
AllowCredentials bool `yaml:"allow_credentials"`
}
// RateLimitConfig holds rate limiting configuration
type RateLimitConfig struct {
Enabled bool `yaml:"enabled"`
RequestsPerSecond float64 `yaml:"requests_per_second"`
BurstSize int `yaml:"burst_size"`
}
// SecurityHeadersConfig holds security headers configuration
type SecurityHeadersConfig struct {
Enabled bool `yaml:"enabled"`
}
// Load reads configuration from file and environment variables
func Load(path string) (*Config, error) {
cfg := DefaultConfig()
@@ -118,6 +154,22 @@ func DefaultConfig() *Config {
Level: getEnv("CALYPSO_LOG_LEVEL", "info"),
Format: getEnv("CALYPSO_LOG_FORMAT", "json"),
},
Security: SecurityConfig{
CORS: CORSConfig{
AllowedOrigins: []string{"*"}, // Default: allow all (should be restricted in production)
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"},
AllowedHeaders: []string{"Content-Type", "Authorization", "Accept", "Origin"},
AllowCredentials: true,
},
RateLimit: RateLimitConfig{
Enabled: true,
RequestsPerSecond: 100.0,
BurstSize: 50,
},
SecurityHeaders: SecurityHeadersConfig{
Enabled: true,
},
},
}
}

View File

@@ -48,3 +48,10 @@ func (db *DB) Close() error {
return db.DB.Close()
}
// Ping checks the database connection
func (db *DB) Ping() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return db.PingContext(ctx)
}

View File

@@ -0,0 +1,174 @@
-- AtlasOS - Calypso
-- Performance Optimization: Database Indexes
-- Version: 3.0
-- Description: Adds indexes for frequently queried columns to improve query performance
-- ============================================================================
-- Authentication & Authorization Indexes
-- ============================================================================
-- Users table indexes
-- Username is frequently queried during login
CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);
-- Email lookups
CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
-- Active user lookups
CREATE INDEX IF NOT EXISTS idx_users_is_active ON users(is_active) WHERE is_active = true;
-- Sessions table indexes
-- Token hash lookups are very frequent (every authenticated request)
CREATE INDEX IF NOT EXISTS idx_sessions_token_hash ON sessions(token_hash);
-- User session lookups
CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id);
-- Expired session cleanup (index on expires_at for efficient cleanup queries)
CREATE INDEX IF NOT EXISTS idx_sessions_expires_at ON sessions(expires_at);
-- User roles junction table
-- Lookup roles for a user (frequent during permission checks)
CREATE INDEX IF NOT EXISTS idx_user_roles_user_id ON user_roles(user_id);
-- Lookup users with a role
CREATE INDEX IF NOT EXISTS idx_user_roles_role_id ON user_roles(role_id);
-- Role permissions junction table
-- Lookup permissions for a role
CREATE INDEX IF NOT EXISTS idx_role_permissions_role_id ON role_permissions(role_id);
-- Lookup roles with a permission
CREATE INDEX IF NOT EXISTS idx_role_permissions_permission_id ON role_permissions(permission_id);
-- ============================================================================
-- Audit & Monitoring Indexes
-- ============================================================================
-- Audit log indexes
-- Time-based queries (most common audit log access pattern)
CREATE INDEX IF NOT EXISTS idx_audit_log_created_at ON audit_log(created_at DESC);
-- User activity queries
CREATE INDEX IF NOT EXISTS idx_audit_log_user_id ON audit_log(user_id);
-- Resource-based queries
CREATE INDEX IF NOT EXISTS idx_audit_log_resource ON audit_log(resource_type, resource_id);
-- Alerts table indexes
-- Time-based ordering (default ordering in ListAlerts)
CREATE INDEX IF NOT EXISTS idx_alerts_created_at ON alerts(created_at DESC);
-- Severity filtering
CREATE INDEX IF NOT EXISTS idx_alerts_severity ON alerts(severity);
-- Source filtering
CREATE INDEX IF NOT EXISTS idx_alerts_source ON alerts(source);
-- Acknowledgment status
CREATE INDEX IF NOT EXISTS idx_alerts_acknowledged ON alerts(is_acknowledged) WHERE is_acknowledged = false;
-- Resource-based queries
CREATE INDEX IF NOT EXISTS idx_alerts_resource ON alerts(resource_type, resource_id);
-- Composite index for common filter combinations
CREATE INDEX IF NOT EXISTS idx_alerts_severity_acknowledged ON alerts(severity, is_acknowledged, created_at DESC);
-- ============================================================================
-- Task Management Indexes
-- ============================================================================
-- Tasks table indexes
-- Status filtering (very common in task queries)
CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(status);
-- Created by user
CREATE INDEX IF NOT EXISTS idx_tasks_created_by ON tasks(created_by);
-- Time-based queries
CREATE INDEX IF NOT EXISTS idx_tasks_created_at ON tasks(created_at DESC);
-- Status + time composite (common query pattern)
CREATE INDEX IF NOT EXISTS idx_tasks_status_created_at ON tasks(status, created_at DESC);
-- Failed tasks lookup (for alerting)
CREATE INDEX IF NOT EXISTS idx_tasks_failed_recent ON tasks(status, created_at DESC) WHERE status = 'failed';
-- ============================================================================
-- Storage Indexes
-- ============================================================================
-- Disk repositories indexes
-- Active repository lookups
CREATE INDEX IF NOT EXISTS idx_disk_repositories_is_active ON disk_repositories(is_active) WHERE is_active = true;
-- Name lookups
CREATE INDEX IF NOT EXISTS idx_disk_repositories_name ON disk_repositories(name);
-- Volume group lookups
CREATE INDEX IF NOT EXISTS idx_disk_repositories_vg ON disk_repositories(volume_group);
-- Physical disks indexes
-- Device path lookups (for sync operations)
CREATE INDEX IF NOT EXISTS idx_physical_disks_device_path ON physical_disks(device_path);
-- ============================================================================
-- SCST Indexes
-- ============================================================================
-- SCST targets indexes
-- IQN lookups (frequent during target operations)
CREATE INDEX IF NOT EXISTS idx_scst_targets_iqn ON scst_targets(iqn);
-- Active target lookups
CREATE INDEX IF NOT EXISTS idx_scst_targets_is_active ON scst_targets(is_active) WHERE is_active = true;
-- SCST LUNs indexes
-- Target + LUN lookups (very frequent)
CREATE INDEX IF NOT EXISTS idx_scst_luns_target_lun ON scst_luns(target_id, lun_number);
-- Device path lookups
CREATE INDEX IF NOT EXISTS idx_scst_luns_device_path ON scst_luns(device_path);
-- SCST initiator groups indexes
-- Target + group name lookups
CREATE INDEX IF NOT EXISTS idx_scst_initiator_groups_target ON scst_initiator_groups(target_id);
-- Group name lookups
CREATE INDEX IF NOT EXISTS idx_scst_initiator_groups_name ON scst_initiator_groups(group_name);
-- SCST initiators indexes
-- Group + IQN lookups
CREATE INDEX IF NOT EXISTS idx_scst_initiators_group_iqn ON scst_initiators(group_id, iqn);
-- Active initiator lookups
CREATE INDEX IF NOT EXISTS idx_scst_initiators_is_active ON scst_initiators(is_active) WHERE is_active = true;
-- ============================================================================
-- Tape Library Indexes
-- ============================================================================
-- Physical tape libraries indexes
-- Serial number lookups (for discovery)
CREATE INDEX IF NOT EXISTS idx_physical_tape_libraries_serial ON physical_tape_libraries(serial_number);
-- Active library lookups
CREATE INDEX IF NOT EXISTS idx_physical_tape_libraries_is_active ON physical_tape_libraries(is_active) WHERE is_active = true;
-- Physical tape drives indexes
-- Library + drive number lookups (very frequent)
CREATE INDEX IF NOT EXISTS idx_physical_tape_drives_library_drive ON physical_tape_drives(library_id, drive_number);
-- Status filtering
CREATE INDEX IF NOT EXISTS idx_physical_tape_drives_status ON physical_tape_drives(status);
-- Physical tape slots indexes
-- Library + slot number lookups
CREATE INDEX IF NOT EXISTS idx_physical_tape_slots_library_slot ON physical_tape_slots(library_id, slot_number);
-- Barcode lookups
CREATE INDEX IF NOT EXISTS idx_physical_tape_slots_barcode ON physical_tape_slots(barcode) WHERE barcode IS NOT NULL;
-- Virtual tape libraries indexes
-- MHVTL library ID lookups
CREATE INDEX IF NOT EXISTS idx_virtual_tape_libraries_mhvtl_id ON virtual_tape_libraries(mhvtl_library_id);
-- Active library lookups
CREATE INDEX IF NOT EXISTS idx_virtual_tape_libraries_is_active ON virtual_tape_libraries(is_active) WHERE is_active = true;
-- Virtual tape drives indexes
-- Library + drive number lookups (very frequent)
CREATE INDEX IF NOT EXISTS idx_virtual_tape_drives_library_drive ON virtual_tape_drives(library_id, drive_number);
-- Status filtering
CREATE INDEX IF NOT EXISTS idx_virtual_tape_drives_status ON virtual_tape_drives(status);
-- Current tape lookups
CREATE INDEX IF NOT EXISTS idx_virtual_tape_drives_current_tape ON virtual_tape_drives(current_tape_id) WHERE current_tape_id IS NOT NULL;
-- Virtual tapes indexes
-- Library + slot number lookups
CREATE INDEX IF NOT EXISTS idx_virtual_tapes_library_slot ON virtual_tapes(library_id, slot_number);
-- Barcode lookups
CREATE INDEX IF NOT EXISTS idx_virtual_tapes_barcode ON virtual_tapes(barcode) WHERE barcode IS NOT NULL;
-- Status filtering
CREATE INDEX IF NOT EXISTS idx_virtual_tapes_status ON virtual_tapes(status);
-- ============================================================================
-- Statistics Update
-- ============================================================================
-- Update table statistics for query planner
ANALYZE;

View File

@@ -0,0 +1,127 @@
package database
import (
"context"
"database/sql"
"fmt"
"time"
)
// QueryStats holds query performance statistics
type QueryStats struct {
Query string
Duration time.Duration
Rows int64
Error error
Timestamp time.Time
}
// QueryOptimizer provides query optimization utilities
type QueryOptimizer struct {
db *DB
}
// NewQueryOptimizer creates a new query optimizer
func NewQueryOptimizer(db *DB) *QueryOptimizer {
return &QueryOptimizer{db: db}
}
// ExecuteWithTimeout executes a query with a timeout
func (qo *QueryOptimizer) ExecuteWithTimeout(ctx context.Context, timeout time.Duration, query string, args ...interface{}) (sql.Result, error) {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
return qo.db.ExecContext(ctx, query, args...)
}
// QueryWithTimeout executes a query with a timeout and returns rows
func (qo *QueryOptimizer) QueryWithTimeout(ctx context.Context, timeout time.Duration, query string, args ...interface{}) (*sql.Rows, error) {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
return qo.db.QueryContext(ctx, query, args...)
}
// QueryRowWithTimeout executes a query with a timeout and returns a single row
func (qo *QueryOptimizer) QueryRowWithTimeout(ctx context.Context, timeout time.Duration, query string, args ...interface{}) *sql.Row {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
return qo.db.QueryRowContext(ctx, query, args...)
}
// BatchInsert performs a batch insert operation
// This is more efficient than multiple individual INSERT statements
func (qo *QueryOptimizer) BatchInsert(ctx context.Context, table string, columns []string, values [][]interface{}) error {
if len(values) == 0 {
return nil
}
// Build the query
query := fmt.Sprintf("INSERT INTO %s (%s) VALUES ", table, joinColumns(columns))
// Build value placeholders
placeholders := make([]string, len(values))
args := make([]interface{}, 0, len(values)*len(columns))
argIndex := 1
for i, row := range values {
rowPlaceholders := make([]string, len(columns))
for j := range columns {
rowPlaceholders[j] = fmt.Sprintf("$%d", argIndex)
args = append(args, row[j])
argIndex++
}
placeholders[i] = fmt.Sprintf("(%s)", joinStrings(rowPlaceholders, ", "))
}
query += joinStrings(placeholders, ", ")
_, err := qo.db.ExecContext(ctx, query, args...)
return err
}
// helper functions
func joinColumns(columns []string) string {
return joinStrings(columns, ", ")
}
func joinStrings(strs []string, sep string) string {
if len(strs) == 0 {
return ""
}
if len(strs) == 1 {
return strs[0]
}
result := strs[0]
for i := 1; i < len(strs); i++ {
result += sep + strs[i]
}
return result
}
// OptimizeConnectionPool optimizes database connection pool settings
// This should be called after analyzing query patterns
func OptimizeConnectionPool(db *sql.DB, maxConns, maxIdleConns int, maxLifetime time.Duration) {
db.SetMaxOpenConns(maxConns)
db.SetMaxIdleConns(maxIdleConns)
db.SetConnMaxLifetime(maxLifetime)
// Set connection idle timeout (how long an idle connection can stay in pool)
// Default is 0 (no timeout), but setting a timeout helps prevent stale connections
db.SetConnMaxIdleTime(10 * time.Minute)
}
// GetConnectionStats returns current connection pool statistics
func GetConnectionStats(db *sql.DB) map[string]interface{} {
stats := db.Stats()
return map[string]interface{}{
"max_open_connections": stats.MaxOpenConnections,
"open_connections": stats.OpenConnections,
"in_use": stats.InUse,
"idle": stats.Idle,
"wait_count": stats.WaitCount,
"wait_duration": stats.WaitDuration.String(),
"max_idle_closed": stats.MaxIdleClosed,
"max_idle_time_closed": stats.MaxIdleTimeClosed,
"max_lifetime_closed": stats.MaxLifetimeClosed,
}
}

View File

@@ -0,0 +1,106 @@
package password
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"github.com/atlasos/calypso/internal/common/config"
"golang.org/x/crypto/argon2"
)
// HashPassword hashes a password using Argon2id
func HashPassword(password string, params config.Argon2Params) (string, error) {
// Generate a random salt
salt := make([]byte, params.SaltLength)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("failed to generate salt: %w", err)
}
// Hash the password
hash := argon2.IDKey(
[]byte(password),
salt,
params.Iterations,
params.Memory,
params.Parallelism,
params.KeyLength,
)
// Encode the hash and salt in the standard format
// Format: $argon2id$v=<version>$m=<memory>,t=<iterations>,p=<parallelism>$<salt>$<hash>
b64Salt := base64.RawStdEncoding.EncodeToString(salt)
b64Hash := base64.RawStdEncoding.EncodeToString(hash)
encodedHash := fmt.Sprintf(
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version,
params.Memory,
params.Iterations,
params.Parallelism,
b64Salt,
b64Hash,
)
return encodedHash, nil
}
// VerifyPassword verifies a password against an Argon2id hash
func VerifyPassword(password, encodedHash string) (bool, error) {
// Parse the encoded hash
parts := strings.Split(encodedHash, "$")
if len(parts) != 6 {
return false, errors.New("invalid hash format")
}
if parts[1] != "argon2id" {
return false, errors.New("unsupported hash algorithm")
}
// Parse version
var version int
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
return false, fmt.Errorf("failed to parse version: %w", err)
}
if version != argon2.Version {
return false, errors.New("incompatible version")
}
// Parse parameters
var memory, iterations uint32
var parallelism uint8
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, &parallelism); err != nil {
return false, fmt.Errorf("failed to parse parameters: %w", err)
}
// Decode salt and hash
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil {
return false, fmt.Errorf("failed to decode salt: %w", err)
}
hash, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil {
return false, fmt.Errorf("failed to decode hash: %w", err)
}
// Compute the hash of the provided password
otherHash := argon2.IDKey(
[]byte(password),
salt,
iterations,
memory,
parallelism,
uint32(len(hash)),
)
// Compare hashes using constant-time comparison
if subtle.ConstantTimeCompare(hash, otherHash) == 1 {
return true, nil
}
return false, nil
}

View File

@@ -0,0 +1,182 @@
package password
import (
"testing"
"github.com/atlasos/calypso/internal/common/config"
)
func min(a, b int) int {
if a < b {
return a
}
return b
}
func contains(s, substr string) bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}
func TestHashPassword(t *testing.T) {
params := config.Argon2Params{
Memory: 64 * 1024,
Iterations: 3,
Parallelism: 4,
SaltLength: 16,
KeyLength: 32,
}
password := "test-password-123"
hash, err := HashPassword(password, params)
if err != nil {
t.Fatalf("HashPassword failed: %v", err)
}
// Verify hash format
if hash == "" {
t.Error("HashPassword returned empty string")
}
// Verify hash starts with Argon2id prefix
if len(hash) < 12 || hash[:12] != "$argon2id$v=" {
t.Errorf("Hash does not start with expected prefix, got: %s", hash[:min(30, len(hash))])
}
// Verify hash contains required components
if !contains(hash, "$m=") || !contains(hash, ",t=") || !contains(hash, ",p=") {
t.Errorf("Hash missing required components, got: %s", hash[:min(50, len(hash))])
}
// Verify hash is different each time (due to random salt)
hash2, err := HashPassword(password, params)
if err != nil {
t.Fatalf("HashPassword failed on second call: %v", err)
}
if hash == hash2 {
t.Error("HashPassword returned same hash for same password (salt should be random)")
}
}
func TestVerifyPassword(t *testing.T) {
params := config.Argon2Params{
Memory: 64 * 1024,
Iterations: 3,
Parallelism: 4,
SaltLength: 16,
KeyLength: 32,
}
password := "test-password-123"
hash, err := HashPassword(password, params)
if err != nil {
t.Fatalf("HashPassword failed: %v", err)
}
// Test correct password
valid, err := VerifyPassword(password, hash)
if err != nil {
t.Fatalf("VerifyPassword failed: %v", err)
}
if !valid {
t.Error("VerifyPassword returned false for correct password")
}
// Test wrong password
valid, err = VerifyPassword("wrong-password", hash)
if err != nil {
t.Fatalf("VerifyPassword failed: %v", err)
}
if valid {
t.Error("VerifyPassword returned true for wrong password")
}
// Test empty password
valid, err = VerifyPassword("", hash)
if err != nil {
t.Fatalf("VerifyPassword failed: %v", err)
}
if valid {
t.Error("VerifyPassword returned true for empty password")
}
}
func TestVerifyPassword_InvalidHash(t *testing.T) {
tests := []struct {
name string
hash string
}{
{"empty hash", ""},
{"invalid format", "not-a-hash"},
{"wrong algorithm", "$argon2$v=19$m=65536,t=3,p=4$salt$hash"},
{"incomplete hash", "$argon2id$v=19"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
valid, err := VerifyPassword("test-password", tt.hash)
if err == nil {
t.Error("VerifyPassword should return error for invalid hash")
}
if valid {
t.Error("VerifyPassword should return false for invalid hash")
}
})
}
}
func TestHashPassword_DifferentPasswords(t *testing.T) {
params := config.Argon2Params{
Memory: 64 * 1024,
Iterations: 3,
Parallelism: 4,
SaltLength: 16,
KeyLength: 32,
}
password1 := "password1"
password2 := "password2"
hash1, err := HashPassword(password1, params)
if err != nil {
t.Fatalf("HashPassword failed: %v", err)
}
hash2, err := HashPassword(password2, params)
if err != nil {
t.Fatalf("HashPassword failed: %v", err)
}
// Hashes should be different
if hash1 == hash2 {
t.Error("Different passwords produced same hash")
}
// Each password should verify against its own hash
valid, err := VerifyPassword(password1, hash1)
if err != nil || !valid {
t.Error("Password1 should verify against its own hash")
}
valid, err = VerifyPassword(password2, hash2)
if err != nil || !valid {
t.Error("Password2 should verify against its own hash")
}
// Passwords should not verify against each other's hash
valid, err = VerifyPassword(password1, hash2)
if err != nil || valid {
t.Error("Password1 should not verify against password2's hash")
}
valid, err = VerifyPassword(password2, hash1)
if err != nil || valid {
t.Error("Password2 should not verify against password1's hash")
}
}

View File

@@ -0,0 +1,171 @@
package router
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"net/http"
"time"
"github.com/atlasos/calypso/internal/common/cache"
"github.com/gin-gonic/gin"
)
// GenerateKey generates a cache key from parts (local helper)
func GenerateKey(prefix string, parts ...string) string {
key := prefix
for _, part := range parts {
key += ":" + part
}
// Hash long keys to keep them manageable
if len(key) > 200 {
hash := sha256.Sum256([]byte(key))
return prefix + ":" + hex.EncodeToString(hash[:])
}
return key
}
// CacheConfig holds cache configuration
type CacheConfig struct {
Enabled bool
DefaultTTL time.Duration
MaxAge int // seconds for Cache-Control header
}
// cacheMiddleware creates a caching middleware
func cacheMiddleware(cfg CacheConfig, cache *cache.Cache) gin.HandlerFunc {
if !cfg.Enabled || cache == nil {
return func(c *gin.Context) {
c.Next()
}
}
return func(c *gin.Context) {
// Only cache GET requests
if c.Request.Method != http.MethodGet {
c.Next()
return
}
// Generate cache key from request path and query string
keyParts := []string{c.Request.URL.Path}
if c.Request.URL.RawQuery != "" {
keyParts = append(keyParts, c.Request.URL.RawQuery)
}
cacheKey := GenerateKey("http", keyParts...)
// Try to get from cache
if cached, found := cache.Get(cacheKey); found {
if cachedResponse, ok := cached.([]byte); ok {
// Set cache headers
if cfg.MaxAge > 0 {
c.Header("Cache-Control", fmt.Sprintf("public, max-age=%d", cfg.MaxAge))
c.Header("X-Cache", "HIT")
}
c.Data(http.StatusOK, "application/json", cachedResponse)
c.Abort()
return
}
}
// Cache miss - capture response
writer := &responseWriter{
ResponseWriter: c.Writer,
body: &bytes.Buffer{},
}
c.Writer = writer
c.Next()
// Only cache successful responses
if writer.Status() == http.StatusOK {
// Cache the response body
responseBody := writer.body.Bytes()
cache.Set(cacheKey, responseBody)
// Set cache headers
if cfg.MaxAge > 0 {
c.Header("Cache-Control", fmt.Sprintf("public, max-age=%d", cfg.MaxAge))
c.Header("X-Cache", "MISS")
}
}
}
}
// responseWriter wraps gin.ResponseWriter to capture response body
type responseWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (w *responseWriter) Write(b []byte) (int, error) {
w.body.Write(b)
return w.ResponseWriter.Write(b)
}
func (w *responseWriter) WriteString(s string) (int, error) {
w.body.WriteString(s)
return w.ResponseWriter.WriteString(s)
}
// cacheControlMiddleware adds Cache-Control headers based on endpoint
func cacheControlMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
path := c.Request.URL.Path
// Set appropriate cache control for different endpoints
switch {
case path == "/api/v1/health":
// Health check can be cached for a short time
c.Header("Cache-Control", "public, max-age=30")
case path == "/api/v1/monitoring/metrics":
// Metrics can be cached for a short time
c.Header("Cache-Control", "public, max-age=60")
case path == "/api/v1/monitoring/alerts":
// Alerts should have minimal caching
c.Header("Cache-Control", "public, max-age=10")
case path == "/api/v1/storage/disks":
// Disk list can be cached for a moderate time
c.Header("Cache-Control", "public, max-age=300")
case path == "/api/v1/storage/repositories":
// Repositories can be cached
c.Header("Cache-Control", "public, max-age=180")
case path == "/api/v1/system/services":
// Service list can be cached briefly
c.Header("Cache-Control", "public, max-age=60")
default:
// Default: no cache for other endpoints
c.Header("Cache-Control", "no-cache, no-store, must-revalidate")
}
c.Next()
}
}
// InvalidateCacheKey invalidates a specific cache key
func InvalidateCacheKey(cache *cache.Cache, key string) {
if cache != nil {
cache.Delete(key)
}
}
// InvalidateCachePattern invalidates all cache keys matching a pattern
func InvalidateCachePattern(cache *cache.Cache, pattern string) {
if cache == nil {
return
}
// Get all keys and delete matching ones
// Note: This is a simple implementation. For production, consider using
// a cache library that supports pattern matching (like Redis)
stats := cache.Stats()
if total, ok := stats["total_entries"].(int); ok && total > 0 {
// For now, we'll clear the entire cache if pattern matching is needed
// In production, use Redis with pattern matching
cache.Clear()
}
}

View File

@@ -0,0 +1,83 @@
package router
import (
"net/http"
"sync"
"github.com/atlasos/calypso/internal/common/config"
"github.com/atlasos/calypso/internal/common/logger"
"github.com/gin-gonic/gin"
"golang.org/x/time/rate"
)
// rateLimiter manages rate limiting per IP address
type rateLimiter struct {
limiters map[string]*rate.Limiter
mu sync.RWMutex
config config.RateLimitConfig
logger *logger.Logger
}
// newRateLimiter creates a new rate limiter
func newRateLimiter(cfg config.RateLimitConfig, log *logger.Logger) *rateLimiter {
return &rateLimiter{
limiters: make(map[string]*rate.Limiter),
config: cfg,
logger: log,
}
}
// getLimiter returns a rate limiter for the given IP address
func (rl *rateLimiter) getLimiter(ip string) *rate.Limiter {
rl.mu.RLock()
limiter, exists := rl.limiters[ip]
rl.mu.RUnlock()
if exists {
return limiter
}
// Create new limiter for this IP
rl.mu.Lock()
defer rl.mu.Unlock()
// Double-check after acquiring write lock
if limiter, exists := rl.limiters[ip]; exists {
return limiter
}
// Create limiter with configured rate
limiter = rate.NewLimiter(rate.Limit(rl.config.RequestsPerSecond), rl.config.BurstSize)
rl.limiters[ip] = limiter
return limiter
}
// rateLimitMiddleware creates rate limiting middleware
func rateLimitMiddleware(cfg *config.Config, log *logger.Logger) gin.HandlerFunc {
if !cfg.Security.RateLimit.Enabled {
// Rate limiting disabled, return no-op middleware
return func(c *gin.Context) {
c.Next()
}
}
limiter := newRateLimiter(cfg.Security.RateLimit, log)
return func(c *gin.Context) {
ip := c.ClientIP()
limiter := limiter.getLimiter(ip)
if !limiter.Allow() {
log.Warn("Rate limit exceeded", "ip", ip, "path", c.Request.URL.Path)
c.JSON(http.StatusTooManyRequests, gin.H{
"error": "rate limit exceeded",
})
c.Abort()
return
}
c.Next()
}
}

View File

@@ -1,12 +1,17 @@
package router
import (
"context"
"time"
"github.com/atlasos/calypso/internal/common/cache"
"github.com/atlasos/calypso/internal/common/config"
"github.com/atlasos/calypso/internal/common/database"
"github.com/atlasos/calypso/internal/common/logger"
"github.com/atlasos/calypso/internal/audit"
"github.com/atlasos/calypso/internal/auth"
"github.com/atlasos/calypso/internal/iam"
"github.com/atlasos/calypso/internal/monitoring"
"github.com/atlasos/calypso/internal/scst"
"github.com/atlasos/calypso/internal/storage"
"github.com/atlasos/calypso/internal/system"
@@ -26,13 +31,104 @@ func NewRouter(cfg *config.Config, db *database.DB, log *logger.Logger) *gin.Eng
r := gin.New()
// Initialize cache if enabled
var responseCache *cache.Cache
if cfg.Server.Cache.Enabled {
responseCache = cache.NewCache(cfg.Server.Cache.DefaultTTL)
log.Info("Response caching enabled", "default_ttl", cfg.Server.Cache.DefaultTTL)
}
// Middleware
r.Use(ginLogger(log))
r.Use(gin.Recovery())
r.Use(corsMiddleware())
r.Use(securityHeadersMiddleware(cfg))
r.Use(rateLimitMiddleware(cfg, log))
r.Use(corsMiddleware(cfg))
// Cache control headers (always applied)
r.Use(cacheControlMiddleware())
// Response caching middleware (if enabled)
if cfg.Server.Cache.Enabled {
cacheConfig := CacheConfig{
Enabled: cfg.Server.Cache.Enabled,
DefaultTTL: cfg.Server.Cache.DefaultTTL,
MaxAge: cfg.Server.Cache.MaxAge,
}
r.Use(cacheMiddleware(cacheConfig, responseCache))
}
// Health check (no auth required)
r.GET("/api/v1/health", healthHandler(db))
// Initialize monitoring services
eventHub := monitoring.NewEventHub(log)
alertService := monitoring.NewAlertService(db, log)
alertService.SetEventHub(eventHub) // Connect alert service to event hub
metricsService := monitoring.NewMetricsService(db, log)
healthService := monitoring.NewHealthService(db, log, metricsService)
// Start event hub in background
go eventHub.Run()
// Start metrics broadcaster in background
go func() {
ticker := time.NewTicker(30 * time.Second) // Broadcast metrics every 30 seconds
defer ticker.Stop()
for {
select {
case <-ticker.C:
if metrics, err := metricsService.CollectMetrics(context.Background()); err == nil {
eventHub.BroadcastMetrics(metrics)
}
}
}
}()
// Initialize and start alert rule engine
alertRuleEngine := monitoring.NewAlertRuleEngine(db, log, alertService)
// Register default alert rules
alertRuleEngine.RegisterRule(monitoring.NewAlertRule(
"storage-capacity-warning",
"Storage Capacity Warning",
monitoring.AlertSourceStorage,
&monitoring.StorageCapacityCondition{ThresholdPercent: 80.0},
monitoring.AlertSeverityWarning,
true,
"Alert when storage repositories exceed 80% capacity",
))
alertRuleEngine.RegisterRule(monitoring.NewAlertRule(
"storage-capacity-critical",
"Storage Capacity Critical",
monitoring.AlertSourceStorage,
&monitoring.StorageCapacityCondition{ThresholdPercent: 95.0},
monitoring.AlertSeverityCritical,
true,
"Alert when storage repositories exceed 95% capacity",
))
alertRuleEngine.RegisterRule(monitoring.NewAlertRule(
"task-failure",
"Task Failure",
monitoring.AlertSourceTask,
&monitoring.TaskFailureCondition{LookbackMinutes: 60},
monitoring.AlertSeverityWarning,
true,
"Alert when tasks fail within the last hour",
))
// Start alert rule engine in background
ctx := context.Background()
go alertRuleEngine.Start(ctx)
// Health check (no auth required) - enhanced
r.GET("/api/v1/health", func(c *gin.Context) {
health := healthService.CheckHealth(c.Request.Context())
statusCode := 200
if health.Status == "unhealthy" {
statusCode = 503
} else if health.Status == "degraded" {
statusCode = 200 // Still 200 but with degraded status
}
c.JSON(statusCode, health)
})
// API v1 routes
v1 := r.Group("/api/v1")
@@ -132,7 +228,7 @@ func NewRouter(cfg *config.Config, db *database.DB, log *logger.Logger) *gin.Eng
}
// IAM (admin only)
iamHandler := iam.NewHandler(db, log)
iamHandler := iam.NewHandler(db, cfg, log)
iamGroup := protected.Group("/iam")
iamGroup.Use(requireRole("admin"))
{
@@ -142,6 +238,24 @@ func NewRouter(cfg *config.Config, db *database.DB, log *logger.Logger) *gin.Eng
iamGroup.PUT("/users/:id", iamHandler.UpdateUser)
iamGroup.DELETE("/users/:id", iamHandler.DeleteUser)
}
// Monitoring
monitoringHandler := monitoring.NewHandler(db, log, alertService, metricsService, eventHub)
monitoringGroup := protected.Group("/monitoring")
monitoringGroup.Use(requirePermission("monitoring", "read"))
{
// Alerts
monitoringGroup.GET("/alerts", monitoringHandler.ListAlerts)
monitoringGroup.GET("/alerts/:id", monitoringHandler.GetAlert)
monitoringGroup.POST("/alerts/:id/acknowledge", monitoringHandler.AcknowledgeAlert)
monitoringGroup.POST("/alerts/:id/resolve", monitoringHandler.ResolveAlert)
// Metrics
monitoringGroup.GET("/metrics", monitoringHandler.GetMetrics)
// WebSocket (no permission check needed, handled by auth middleware)
monitoringGroup.GET("/events", monitoringHandler.WebSocketHandler)
}
}
}
@@ -163,39 +277,5 @@ func ginLogger(log *logger.Logger) gin.HandlerFunc {
}
}
// corsMiddleware adds CORS headers
func corsMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE, PATCH")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}
// healthHandler returns system health status
func healthHandler(db *database.DB) gin.HandlerFunc {
return func(c *gin.Context) {
// Check database connection
if err := db.Ping(); err != nil {
c.JSON(503, gin.H{
"status": "unhealthy",
"error": "database connection failed",
})
return
}
c.JSON(200, gin.H{
"status": "healthy",
"service": "calypso-api",
})
}
}

View File

@@ -0,0 +1,102 @@
package router
import (
"github.com/atlasos/calypso/internal/common/config"
"github.com/gin-gonic/gin"
)
// securityHeadersMiddleware adds security headers to responses
func securityHeadersMiddleware(cfg *config.Config) gin.HandlerFunc {
if !cfg.Security.SecurityHeaders.Enabled {
return func(c *gin.Context) {
c.Next()
}
}
return func(c *gin.Context) {
// Prevent clickjacking
c.Header("X-Frame-Options", "DENY")
// Prevent MIME type sniffing
c.Header("X-Content-Type-Options", "nosniff")
// Enable XSS protection
c.Header("X-XSS-Protection", "1; mode=block")
// Strict Transport Security (HSTS) - only if using HTTPS
// c.Header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
// Content Security Policy (basic)
c.Header("Content-Security-Policy", "default-src 'self'")
// Referrer Policy
c.Header("Referrer-Policy", "strict-origin-when-cross-origin")
// Permissions Policy
c.Header("Permissions-Policy", "geolocation=(), microphone=(), camera=()")
c.Next()
}
}
// corsMiddleware creates configurable CORS middleware
func corsMiddleware(cfg *config.Config) gin.HandlerFunc {
return func(c *gin.Context) {
origin := c.Request.Header.Get("Origin")
// Check if origin is allowed
allowed := false
for _, allowedOrigin := range cfg.Security.CORS.AllowedOrigins {
if allowedOrigin == "*" || allowedOrigin == origin {
allowed = true
break
}
}
if allowed {
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
}
if cfg.Security.CORS.AllowCredentials {
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
}
// Set allowed methods
methods := cfg.Security.CORS.AllowedMethods
if len(methods) == 0 {
methods = []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"}
}
c.Writer.Header().Set("Access-Control-Allow-Methods", joinStrings(methods, ", "))
// Set allowed headers
headers := cfg.Security.CORS.AllowedHeaders
if len(headers) == 0 {
headers = []string{"Content-Type", "Authorization", "Accept", "Origin"}
}
c.Writer.Header().Set("Access-Control-Allow-Headers", joinStrings(headers, ", "))
// Handle preflight requests
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}
// joinStrings joins a slice of strings with a separator
func joinStrings(strs []string, sep string) string {
if len(strs) == 0 {
return ""
}
if len(strs) == 1 {
return strs[0]
}
result := strs[0]
for _, s := range strs[1:] {
result += sep + s
}
return result
}