|
| 1 | +package model |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/rand" |
| 5 | + "encoding/base64" |
| 6 | + "errors" |
| 7 | + |
| 8 | + "github.com/zxh326/kite/pkg/common" |
| 9 | + "gorm.io/gorm" |
| 10 | + "k8s.io/klog/v2" |
| 11 | +) |
| 12 | + |
| 13 | +// SystemSecret stores auto-generated application secrets in the database. |
| 14 | +// Values are stored as plain text (NOT SecretString) because one of the |
| 15 | +// secrets IS the encryption key itself — encrypting it would be circular. |
| 16 | +type SystemSecret struct { |
| 17 | + Name string `gorm:"primaryKey;column:name;type:varchar(64)"` |
| 18 | + Value string `gorm:"column:value;type:text;not null"` |
| 19 | +} |
| 20 | + |
| 21 | +const ( |
| 22 | + secretNameJWT = "jwt_secret" |
| 23 | + secretNameEncrypt = "encrypt_key" |
| 24 | + |
| 25 | + // Known insecure defaults shipped in source code and Helm chart. |
| 26 | + defaultJWTSecret = "kite-default-jwt-secret-key-change-in-production" |
| 27 | + defaultEncryptKey = "kite-default-encryption-key-change-in-production" |
| 28 | +) |
| 29 | + |
| 30 | +// EnsureSecrets guarantees that JwtSecret and KiteEncryptKey hold |
| 31 | +// cryptographically secure values. It must be called after InitDB() |
| 32 | +// and before any code that reads SecretString from the database. |
| 33 | +// |
| 34 | +// Priority for each secret: |
| 35 | +// 1. Environment variable (set via LoadEnvs) — always wins |
| 36 | +// 2. Value previously stored in the database — survives restarts |
| 37 | +// 3. Auto-generated random value — first boot |
| 38 | +// |
| 39 | +// For upgrades from older versions that ran with the hardcoded default |
| 40 | +// encryption key, existing encrypted data is detected and the default |
| 41 | +// is persisted so that data remains readable. A loud warning is emitted. |
| 42 | +func EnsureSecrets() { |
| 43 | + common.JwtSecret = ensureOneSecret( |
| 44 | + secretNameJWT, common.JwtSecret, "JWT_SECRET", defaultJWTSecret, false, |
| 45 | + ) |
| 46 | + common.KiteEncryptKey = ensureOneSecret( |
| 47 | + secretNameEncrypt, common.KiteEncryptKey, "KITE_ENCRYPT_KEY", defaultEncryptKey, true, |
| 48 | + ) |
| 49 | +} |
| 50 | + |
| 51 | +func ensureOneSecret(dbName, currentValue, envName, knownDefault string, isEncryptionKey bool) string { |
| 52 | + isDefault := currentValue == knownDefault |
| 53 | + |
| 54 | + // ── 1. Env var was explicitly set → use it, persist for consistency ── |
| 55 | + if !isDefault { |
| 56 | + persistSecret(dbName, currentValue) |
| 57 | + return currentValue |
| 58 | + } |
| 59 | + |
| 60 | + // ── 2. Previously stored in database → use it ── |
| 61 | + if stored := loadSecret(dbName); stored != "" { |
| 62 | + return stored |
| 63 | + } |
| 64 | + |
| 65 | + // ── 3. No env var, no stored value. Fresh install or upgrade? ── |
| 66 | + if isEncryptionKey && hasExistingEncryptedData() { |
| 67 | + // Upgrade path: existing data was encrypted with the default key. |
| 68 | + // Persist it so subsequent restarts keep working. Warn loudly. |
| 69 | + persistSecret(dbName, currentValue) |
| 70 | + klog.Warningf("════════════════════════════════════════════════════════════") |
| 71 | + klog.Warningf(" %s is using the insecure hardcoded default.", envName) |
| 72 | + klog.Warningf(" Existing encrypted data has been preserved.") |
| 73 | + klog.Warningf(" Please set %s to a secure random value", envName) |
| 74 | + klog.Warningf(" and re-encrypt your data.") |
| 75 | + klog.Warningf("════════════════════════════════════════════════════════════") |
| 76 | + return currentValue |
| 77 | + } |
| 78 | + |
| 79 | + // Fresh install → generate a cryptographically secure random secret. |
| 80 | + secret := generateRandomSecret(32) |
| 81 | + persistSecret(dbName, secret) |
| 82 | + klog.Infof("Auto-generated %s and stored in database (first boot)", envName) |
| 83 | + return secret |
| 84 | +} |
| 85 | + |
| 86 | +// generateRandomSecret returns a base64url-encoded string of n random bytes. |
| 87 | +func generateRandomSecret(n int) string { |
| 88 | + b := make([]byte, n) |
| 89 | + if _, err := rand.Read(b); err != nil { |
| 90 | + klog.Fatalf("Failed to generate random secret: %v", err) |
| 91 | + } |
| 92 | + return base64.RawURLEncoding.EncodeToString(b) |
| 93 | +} |
| 94 | + |
| 95 | +func loadSecret(name string) string { |
| 96 | + var s SystemSecret |
| 97 | + if err := DB.Where("name = ?", name).First(&s).Error; err != nil { |
| 98 | + return "" |
| 99 | + } |
| 100 | + return s.Value |
| 101 | +} |
| 102 | + |
| 103 | +func persistSecret(name, value string) { |
| 104 | + var existing SystemSecret |
| 105 | + err := DB.Where("name = ?", name).First(&existing).Error |
| 106 | + |
| 107 | + if errors.Is(err, gorm.ErrRecordNotFound) { |
| 108 | + if err := DB.Create(&SystemSecret{Name: name, Value: value}).Error; err != nil { |
| 109 | + klog.Warningf("Failed to persist secret %q: %v", name, err) |
| 110 | + } |
| 111 | + return |
| 112 | + } |
| 113 | + if err != nil { |
| 114 | + klog.Warningf("Failed to read secret %q: %v", name, err) |
| 115 | + return |
| 116 | + } |
| 117 | + // Update only if the value changed (env var takes precedence). |
| 118 | + if existing.Value != value { |
| 119 | + if err := DB.Model(&existing).Update("value", value).Error; err != nil { |
| 120 | + klog.Warningf("Failed to update secret %q: %v", name, err) |
| 121 | + } |
| 122 | + } |
| 123 | +} |
| 124 | + |
| 125 | +// hasExistingEncryptedData returns true when the database already contains |
| 126 | +// rows with SecretString columns — meaning data was encrypted with whatever |
| 127 | +// key was active at the time. |
| 128 | +func hasExistingEncryptedData() bool { |
| 129 | + var count int64 |
| 130 | + DB.Model(&Cluster{}).Count(&count) |
| 131 | + if count > 0 { |
| 132 | + return true |
| 133 | + } |
| 134 | + DB.Model(&OAuthProvider{}).Count(&count) |
| 135 | + if count > 0 { |
| 136 | + return true |
| 137 | + } |
| 138 | + DB.Model(&User{}).Where("api_key IS NOT NULL AND api_key != ''").Count(&count) |
| 139 | + return count > 0 |
| 140 | +} |
0 commit comments