|
| 1 | +package model |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/rand" |
| 5 | + "encoding/base64" |
| 6 | + "errors" |
| 7 | + "os" |
| 8 | + |
| 9 | + "github.com/zxh326/kite/pkg/common" |
| 10 | + "gorm.io/gorm" |
| 11 | + "k8s.io/klog/v2" |
| 12 | +) |
| 13 | + |
| 14 | +// SystemSecret stores auto-generated application secrets in the database. |
| 15 | +// Values are stored as plain text (NOT SecretString) because one of the |
| 16 | +// secrets IS the encryption key itself — encrypting it would be circular. |
| 17 | +type SystemSecret struct { |
| 18 | + Name string `gorm:"primaryKey;column:name;type:varchar(64)"` |
| 19 | + Value string `gorm:"column:value;type:text;not null"` |
| 20 | +} |
| 21 | + |
| 22 | +const ( |
| 23 | + secretNameJWT = "jwt_secret" |
| 24 | + secretNameEncrypt = "encrypt_key" |
| 25 | + |
| 26 | + // Known insecure defaults shipped in source code and Helm chart. |
| 27 | + defaultJWTSecret = "kite-default-jwt-secret-key-change-in-production" |
| 28 | + defaultEncryptKey = "kite-default-encryption-key-change-in-production" |
| 29 | +) |
| 30 | + |
| 31 | +// EnsureSecrets guarantees that JwtSecret and KiteEncryptKey hold |
| 32 | +// cryptographically secure values. It must be called after InitDB() |
| 33 | +// and before any code that reads SecretString from the database. |
| 34 | +// |
| 35 | +// Priority for each secret: |
| 36 | +// 1. Environment variable (set via LoadEnvs) — always wins |
| 37 | +// 2. Value previously stored in the database — survives restarts |
| 38 | +// 3. Auto-generated random value — first boot |
| 39 | +// |
| 40 | +// For upgrades from older versions that ran with the hardcoded default |
| 41 | +// encryption key, existing encrypted data is detected and the default |
| 42 | +// is persisted so that data remains readable. A loud warning is emitted. |
| 43 | +func EnsureSecrets() { |
| 44 | + common.JwtSecret = ensureOneSecret( |
| 45 | + secretNameJWT, common.JwtSecret, "JWT_SECRET", defaultJWTSecret, false, |
| 46 | + os.Getenv("JWT_SECRET") != "", |
| 47 | + ) |
| 48 | + common.KiteEncryptKey = ensureOneSecret( |
| 49 | + secretNameEncrypt, common.KiteEncryptKey, "KITE_ENCRYPT_KEY", defaultEncryptKey, true, |
| 50 | + os.Getenv("KITE_ENCRYPT_KEY") != "", |
| 51 | + ) |
| 52 | +} |
| 53 | + |
| 54 | +func ensureOneSecret(dbName, currentValue, envName, knownDefault string, isEncryptionKey, envWasSet bool) string { |
| 55 | + // ── 1. Env var was explicitly set → use it directly ── |
| 56 | + // Do NOT persist to the database: operators who provide secrets via |
| 57 | + // env vars expect them to stay outside the DB. Writing them to |
| 58 | + // system_secrets would be a security regression (DB-only read |
| 59 | + // exposure would reveal the signing/encryption keys). |
| 60 | + if envWasSet { |
| 61 | + return currentValue |
| 62 | + } |
| 63 | + |
| 64 | + // ── 2. Previously stored in database → use it ── |
| 65 | + if stored := loadSecret(dbName); stored != "" { |
| 66 | + return stored |
| 67 | + } |
| 68 | + |
| 69 | + // ── 3. No env var, no stored value. Fresh install or upgrade? ── |
| 70 | + if isEncryptionKey && hasExistingEncryptedData() { |
| 71 | + // Upgrade path: existing data was encrypted with the default key. |
| 72 | + // Persist it so subsequent restarts keep working. Warn loudly. |
| 73 | + persistSecret(dbName, currentValue) |
| 74 | + klog.Warningf("════════════════════════════════════════════════════════════") |
| 75 | + klog.Warningf(" %s is using the insecure hardcoded default.", envName) |
| 76 | + klog.Warningf(" Existing encrypted data has been preserved.") |
| 77 | + klog.Warningf(" Please set %s to a secure random value", envName) |
| 78 | + klog.Warningf(" and re-encrypt your data.") |
| 79 | + klog.Warningf("════════════════════════════════════════════════════════════") |
| 80 | + return currentValue |
| 81 | + } |
| 82 | + |
| 83 | + // Fresh install → generate a cryptographically secure random secret. |
| 84 | + // persistSecret returns the winner's value on insert conflict. |
| 85 | + secret := persistSecret(dbName, generateRandomSecret(32)) |
| 86 | + klog.Infof("Auto-generated %s and stored in database (first boot)", envName) |
| 87 | + return secret |
| 88 | +} |
| 89 | + |
| 90 | +// generateRandomSecret returns a base64url-encoded string of n random bytes. |
| 91 | +func generateRandomSecret(n int) string { |
| 92 | + b := make([]byte, n) |
| 93 | + if _, err := rand.Read(b); err != nil { |
| 94 | + klog.Fatalf("Failed to generate random secret: %v", err) |
| 95 | + } |
| 96 | + return base64.RawURLEncoding.EncodeToString(b) |
| 97 | +} |
| 98 | + |
| 99 | +func loadSecret(name string) string { |
| 100 | + var s SystemSecret |
| 101 | + if err := DB.Where("name = ?", name).First(&s).Error; err != nil { |
| 102 | + return "" |
| 103 | + } |
| 104 | + return s.Value |
| 105 | +} |
| 106 | + |
| 107 | +// persistSecret inserts the secret into the database if no row exists yet. |
| 108 | +// If a row already exists (another replica won the race, or a previous boot |
| 109 | +// stored it), the existing value is returned unchanged — never overwritten. |
| 110 | +// This ensures all pods converge on whichever value was written first. |
| 111 | +func persistSecret(name, value string) string { |
| 112 | + var existing SystemSecret |
| 113 | + err := DB.Where("name = ?", name).First(&existing).Error |
| 114 | + |
| 115 | + if errors.Is(err, gorm.ErrRecordNotFound) { |
| 116 | + if err := DB.Create(&SystemSecret{Name: name, Value: value}).Error; err != nil { |
| 117 | + // Another replica may have inserted first — adopt the winner. |
| 118 | + if stored := loadSecret(name); stored != "" { |
| 119 | + klog.Infof("Secret %q was created by another instance, adopting its value", name) |
| 120 | + return stored |
| 121 | + } |
| 122 | + klog.Warningf("Failed to persist secret %q: %v", name, err) |
| 123 | + } |
| 124 | + return value |
| 125 | + } |
| 126 | + if err != nil { |
| 127 | + klog.Warningf("Failed to read secret %q: %v", name, err) |
| 128 | + return value |
| 129 | + } |
| 130 | + // Row already exists — adopt the stored value (first writer wins). |
| 131 | + return existing.Value |
| 132 | +} |
| 133 | + |
| 134 | +// hasExistingEncryptedData returns true when the database already contains |
| 135 | +// rows with non-empty SecretString columns — meaning data was encrypted |
| 136 | +// with whatever key was active at the time. Only checks columns that |
| 137 | +// actually hold encrypted payloads (not mere row existence). |
| 138 | +func hasExistingEncryptedData() bool { |
| 139 | + var count int64 |
| 140 | + // Cluster.Config is a SecretString; in-cluster entries may have it empty. |
| 141 | + DB.Model(&Cluster{}).Where("config IS NOT NULL AND config != ''").Count(&count) |
| 142 | + if count > 0 { |
| 143 | + return true |
| 144 | + } |
| 145 | + // OAuthProvider.ClientSecret is always encrypted when present. |
| 146 | + DB.Model(&OAuthProvider{}).Where("client_secret IS NOT NULL AND client_secret != ''").Count(&count) |
| 147 | + if count > 0 { |
| 148 | + return true |
| 149 | + } |
| 150 | + DB.Model(&User{}).Where("api_key IS NOT NULL AND api_key != ''").Count(&count) |
| 151 | + if count > 0 { |
| 152 | + return true |
| 153 | + } |
| 154 | + // GeneralSetting.AIAPIKey is also a SecretString field. |
| 155 | + DB.Model(&GeneralSetting{}).Where("ai_api_key IS NOT NULL AND ai_api_key != ''").Count(&count) |
| 156 | + return count > 0 |
| 157 | +} |
0 commit comments