diff --git a/apps/api/internal/feeds/headers.go b/apps/api/internal/feeds/headers.go index dc3bbc7..e7d6dc4 100644 --- a/apps/api/internal/feeds/headers.go +++ b/apps/api/internal/feeds/headers.go @@ -7,7 +7,7 @@ import ( "os" "strings" - "github.com/descrybe/descrybe-v2/apps/api/internal/platformsettings" + "github.com/descrybe/descrybe-v2/apps/api/internal/secretcrypto" ) // Custom remote source headers are stored only as encrypted options; never in response DTOs. @@ -48,7 +48,7 @@ func secretEncryptionKey() []byte { if material == "" { material = os.Getenv("CREDENTIALS_ENCRYPTION_KEY") } - return platformsettings.DeriveKey(material, os.Getenv("TOKEN_SIGNING_SECRET")) + return secretcrypto.DeriveKey(material, os.Getenv("TOKEN_SIGNING_SECRET")) } func encryptFeedHeaders(headers map[string]string) (string, error) { clean, err := validatedFeedHeaders(headers) @@ -66,7 +66,7 @@ func encryptFeedHeaders(headers map[string]string) (string, error) { if err != nil { return "", err } - return platformsettings.EncryptSecret(key, string(b)) + return secretcrypto.EncryptSecret(key, string(b)) } func decryptFeedHeaders(options any) (map[string]string, error) { opt, ok := options.(map[string]any) @@ -77,7 +77,7 @@ func decryptFeedHeaders(options any) (map[string]string, error) { if encrypted == "" { return nil, nil } - plain, err := platformsettings.DecryptSecret(secretEncryptionKey(), encrypted) + plain, err := secretcrypto.DecryptSecret(secretEncryptionKey(), encrypted) if err != nil { return nil, errors.New("cannot decrypt feed credentials; ensure same APP_ENCRYPTION_KEY on API and worker") } diff --git a/apps/api/internal/platformsettings/crypto.go b/apps/api/internal/platformsettings/crypto.go index c2f4593..dfa6d14 100644 --- a/apps/api/internal/platformsettings/crypto.go +++ b/apps/api/internal/platformsettings/crypto.go @@ -1,109 +1,24 @@ package platformsettings import ( - "crypto/aes" - "crypto/cipher" - "crypto/rand" - "crypto/sha256" - "encoding/base64" - "encoding/hex" - "errors" - "io" "strings" - "github.com/descrybe/descrybe-v2/apps/api/internal/config" + "github.com/descrybe/descrybe-v2/apps/api/internal/secretcrypto" ) +// Retain the encrypted value prefix for platform settings records and migrations. const encPrefix = "enc:v1:" -// DeriveKey builds a 32-byte AES key from APP_ENCRYPTION_KEY material. -// In production, empty explicit key returns nil (fail closed). func DeriveKey(explicitKey, fallbackMaterial string) []byte { - explicitKey = strings.TrimSpace(explicitKey) - if explicitKey != "" { - if b, err := decodeKeyMaterial(explicitKey); err == nil { - return b - } - sum := sha256.Sum256([]byte(explicitKey)) - return sum[:] - } - if config.IsProductionEnv() { - return nil - } - sum := sha256.Sum256([]byte("descrybe-platform-settings-v1|" + fallbackMaterial)) - return sum[:] -} - -func decodeKeyMaterial(s string) ([]byte, error) { - if b, err := base64.StdEncoding.DecodeString(s); err == nil && len(b) == 32 { - return b, nil - } - if b, err := base64.RawStdEncoding.DecodeString(s); err == nil && len(b) == 32 { - return b, nil - } - if b, err := hex.DecodeString(s); err == nil && len(b) == 32 { - return b, nil - } - return nil, errors.New("invalid key material") + return secretcrypto.DeriveKey(explicitKey, fallbackMaterial) } func EncryptSecret(key []byte, plaintext string) (string, error) { - if plaintext == "" { - return "", nil - } - if len(key) != 32 { - return "", errors.New("encryption key must be 32 bytes") - } - block, err := aes.NewCipher(key) - if err != nil { - return "", err - } - gcm, err := cipher.NewGCM(block) - if err != nil { - return "", err - } - nonce := make([]byte, gcm.NonceSize()) - if _, err := io.ReadFull(rand.Reader, nonce); err != nil { - return "", err - } - sealed := gcm.Seal(nonce, nonce, []byte(plaintext), nil) - return encPrefix + base64.RawStdEncoding.EncodeToString(sealed), nil + return secretcrypto.EncryptSecret(key, plaintext) } func DecryptSecret(key []byte, stored string) (string, error) { - if stored == "" { - return "", nil - } - if !strings.HasPrefix(stored, encPrefix) { - if config.IsProductionEnv() { - return "", errors.New("plaintext secrets are not allowed when APP_ENV=production") - } - return stored, nil - } - if len(key) != 32 { - return "", errors.New("encryption key must be 32 bytes") - } - raw, err := base64.RawStdEncoding.DecodeString(strings.TrimPrefix(stored, encPrefix)) - if err != nil { - return "", err - } - block, err := aes.NewCipher(key) - if err != nil { - return "", err - } - gcm, err := cipher.NewGCM(block) - if err != nil { - return "", err - } - if len(raw) < gcm.NonceSize() { - return "", errors.New("ciphertext too short") - } - nonce, ciphertext := raw[:gcm.NonceSize()], raw[gcm.NonceSize():] - plain, err := gcm.Open(nil, nonce, ciphertext, nil) - if err != nil { - return "", err - } - return string(plain), nil + return secretcrypto.DecryptSecret(key, stored) } func maskSecret(plain string) string { diff --git a/apps/api/internal/secretcrypto/crypto.go b/apps/api/internal/secretcrypto/crypto.go new file mode 100644 index 0000000..39408d9 --- /dev/null +++ b/apps/api/internal/secretcrypto/crypto.go @@ -0,0 +1,107 @@ +package secretcrypto + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "errors" + "io" + "strings" + + "github.com/descrybe/descrybe-v2/apps/api/internal/config" +) + +const encPrefix = "enc:v1:" + +// DeriveKey builds a 32-byte AES key from APP_ENCRYPTION_KEY material. +// In production, empty explicit key returns nil (fail closed). +func DeriveKey(explicitKey, fallbackMaterial string) []byte { + explicitKey = strings.TrimSpace(explicitKey) + if explicitKey != "" { + if b, err := decodeKeyMaterial(explicitKey); err == nil { + return b + } + sum := sha256.Sum256([]byte(explicitKey)) + return sum[:] + } + if config.IsProductionEnv() { + return nil + } + sum := sha256.Sum256([]byte("descrybe-platform-settings-v1|" + fallbackMaterial)) + return sum[:] +} + +func decodeKeyMaterial(s string) ([]byte, error) { + if b, err := base64.StdEncoding.DecodeString(s); err == nil && len(b) == 32 { + return b, nil + } + if b, err := base64.RawStdEncoding.DecodeString(s); err == nil && len(b) == 32 { + return b, nil + } + if b, err := hex.DecodeString(s); err == nil && len(b) == 32 { + return b, nil + } + return nil, errors.New("invalid key material") +} + +func EncryptSecret(key []byte, plaintext string) (string, error) { + if plaintext == "" { + return "", nil + } + if len(key) != 32 { + return "", errors.New("encryption key must be 32 bytes") + } + block, err := aes.NewCipher(key) + if err != nil { + return "", err + } + gcm, err := cipher.NewGCM(block) + if err != nil { + return "", err + } + nonce := make([]byte, gcm.NonceSize()) + if _, err := io.ReadFull(rand.Reader, nonce); err != nil { + return "", err + } + sealed := gcm.Seal(nonce, nonce, []byte(plaintext), nil) + return encPrefix + base64.RawStdEncoding.EncodeToString(sealed), nil +} + +func DecryptSecret(key []byte, stored string) (string, error) { + if stored == "" { + return "", nil + } + if !strings.HasPrefix(stored, encPrefix) { + if config.IsProductionEnv() { + return "", errors.New("plaintext secrets are not allowed when APP_ENV=production") + } + return stored, nil + } + if len(key) != 32 { + return "", errors.New("encryption key must be 32 bytes") + } + raw, err := base64.RawStdEncoding.DecodeString(strings.TrimPrefix(stored, encPrefix)) + if err != nil { + return "", err + } + block, err := aes.NewCipher(key) + if err != nil { + return "", err + } + gcm, err := cipher.NewGCM(block) + if err != nil { + return "", err + } + if len(raw) < gcm.NonceSize() { + return "", errors.New("ciphertext too short") + } + nonce, ciphertext := raw[:gcm.NonceSize()], raw[gcm.NonceSize():] + plain, err := gcm.Open(nil, nonce, ciphertext, nil) + if err != nil { + return "", err + } + return string(plain), nil +} diff --git a/apps/api/internal/secretcrypto/crypto_test.go b/apps/api/internal/secretcrypto/crypto_test.go new file mode 100644 index 0000000..19876e5 --- /dev/null +++ b/apps/api/internal/secretcrypto/crypto_test.go @@ -0,0 +1,57 @@ +package secretcrypto + +import ( + "bytes" + "encoding/base64" + "strings" + "testing" +) + +func TestDeriveKeyMatchesLegacyPlatformSettings(t *testing.T) { + t.Setenv("APP_ENV", "development") + + key := DeriveKey("migration-compatibility-passphrase", "unused") + if len(key) != 32 { + t.Fatalf("expected 32 byte key, got %d", len(key)) + } + fallback := DeriveKey("", "signing-secret") + if len(fallback) != 32 { + t.Fatalf("expected 32 byte fallback key, got %d", len(fallback)) + } + + base64Key := base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{0x67}, 32)) + decoded := DeriveKey(base64Key, "unused") + if !bytes.Equal(decoded, bytes.Repeat([]byte{0x67}, 32)) { + t.Fatal("base64 key material was not decoded") + } +} + +func TestEncryptedFeedHeaderRoundTripAndWrongKey(t *testing.T) { + t.Setenv("APP_ENV", "production") + key := DeriveKey("stable-production-encryption-key", "") + plaintext := `{"X-API-Key":"private-token","Authorization":"Bearer token"}` + encrypted, err := EncryptSecret(key, plaintext) + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(encrypted, "enc:v1:") || strings.Contains(encrypted, "private-token") { + t.Fatalf("unexpected ciphertext: %s", encrypted) + } + decrypted, err := DecryptSecret(key, encrypted) + if err != nil || decrypted != plaintext { + t.Fatalf("round-trip failed: %v", err) + } + if _, err := DecryptSecret(DeriveKey("other-key", ""), encrypted); err == nil { + t.Fatal("wrong encryption key must fail") + } +} + +func TestProductionRejectsMissingKeyAndPlaintext(t *testing.T) { + t.Setenv("APP_ENV", "production") + if key := DeriveKey("", "fallback"); key != nil { + t.Fatal("production must not use a fallback encryption key") + } + if _, err := DecryptSecret(DeriveKey("some-key", ""), "plaintext-secret"); err == nil { + t.Fatal("plaintext credential accepted in production") + } +}