checkEncryptionMismatch detects encryption configuration mismatches
(c *gin.Context)
| 416 | |
| 417 | // checkEncryptionMismatch detects encryption configuration mismatches |
| 418 | func (s *Server) checkEncryptionMismatch(c *gin.Context) (bool, string, string, string) { |
| 419 | encryptionKey := s.config.GetEncryptionKey() |
| 420 | |
| 421 | // Sample check API keys |
| 422 | var sampleKeys []models.APIKey |
| 423 | if err := s.DB.Limit(20).Where("key_hash IS NOT NULL AND key_hash != ''").Find(&sampleKeys).Error; err != nil { |
| 424 | logrus.WithError(err).Error("Failed to fetch sample keys for encryption check") |
| 425 | return false, ScenarioNone, "", "" |
| 426 | } |
| 427 | |
| 428 | if len(sampleKeys) == 0 { |
| 429 | // No keys in database, no mismatch |
| 430 | return false, ScenarioNone, "", "" |
| 431 | } |
| 432 | |
| 433 | // Check hash consistency with unencrypted data |
| 434 | noopService, err := encryption.NewService("") |
| 435 | if err != nil { |
| 436 | logrus.WithError(err).Error("Failed to create noop encryption service") |
| 437 | return false, ScenarioNone, "", "" |
| 438 | } |
| 439 | |
| 440 | unencryptedHashMatchCount := 0 |
| 441 | for _, key := range sampleKeys { |
| 442 | // For unencrypted data: key_hash should match SHA256(key_value) |
| 443 | expectedHash := noopService.Hash(key.KeyValue) |
| 444 | if expectedHash == key.KeyHash { |
| 445 | unencryptedHashMatchCount++ |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | unencryptedConsistencyRate := float64(unencryptedHashMatchCount) / float64(len(sampleKeys)) |
| 450 | |
| 451 | // If ENCRYPTION_KEY is configured, also check if current key can decrypt the data |
| 452 | var currentKeyHashMatchCount int |
| 453 | if encryptionKey != "" { |
| 454 | currentService, err := encryption.NewService(encryptionKey) |
| 455 | if err == nil { |
| 456 | for _, key := range sampleKeys { |
| 457 | // Try to decrypt and re-hash to check if current key matches |
| 458 | decrypted, err := currentService.Decrypt(key.KeyValue) |
| 459 | if err == nil { |
| 460 | // Successfully decrypted, check if hash matches |
| 461 | expectedHash := currentService.Hash(decrypted) |
| 462 | if expectedHash == key.KeyHash { |
| 463 | currentKeyHashMatchCount++ |
| 464 | } |
| 465 | } |
| 466 | } |
| 467 | } |
| 468 | } |
| 469 | currentKeyConsistencyRate := float64(currentKeyHashMatchCount) / float64(len(sampleKeys)) |
| 470 | |
| 471 | // Scenario A: ENCRYPTION_KEY configured but data not encrypted |
| 472 | if encryptionKey != "" && unencryptedConsistencyRate > 0.8 { |
| 473 | return true, |
| 474 | ScenarioDataNotEncrypted, |
| 475 | i18n.Message(c, "dashboard.encryption_key_configured_but_data_not_encrypted"), |
no test coverage detected