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") } }