This commit is contained in:
greeneclipse committed 2026-10-15 23:48:34 +02:00
1 parent 26e7453ad9
commit 6586722652
4 files changed
+173 -94

No files matched your search

+107
View File
@@ -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
}
@@ -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")
}
}