feat(crypto): AES-256-GCM field encryption keyed from EMCLI_KEY

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-21 23:32:23 +01:00
parent afad3bf3f1
commit 8d04b0fde9
2 changed files with 134 additions and 0 deletions
+69
View File
@@ -0,0 +1,69 @@
package crypto
import (
"bytes"
"encoding/base64"
"testing"
)
func testKey() []byte {
k := make([]byte, 32)
for i := range k {
k[i] = byte(i)
}
return k
}
func TestSealOpenRoundTrip(t *testing.T) {
key := testKey()
msg := []byte("hunter2-the-password")
blob, err := Seal(key, msg)
if err != nil {
t.Fatalf("Seal: %v", err)
}
if bytes.Contains(blob, msg) {
t.Fatal("ciphertext must not contain plaintext")
}
got, err := Open(key, blob)
if err != nil {
t.Fatalf("Open: %v", err)
}
if !bytes.Equal(got, msg) {
t.Fatalf("round-trip mismatch: %q", got)
}
}
func TestSealUsesRandomNonce(t *testing.T) {
key := testKey()
a, _ := Seal(key, []byte("x"))
b, _ := Seal(key, []byte("x"))
if bytes.Equal(a, b) {
t.Fatal("two seals of same plaintext must differ (random nonce)")
}
}
func TestOpenWrongKeyFails(t *testing.T) {
blob, _ := Seal(testKey(), []byte("secret"))
wrong := make([]byte, 32) // all zeros
if _, err := Open(wrong, blob); err == nil {
t.Fatal("Open with wrong key must fail")
}
}
func TestKeyFromEnv(t *testing.T) {
t.Setenv("EMCLI_KEY", base64.StdEncoding.EncodeToString(testKey()))
k, err := KeyFromEnv()
if err != nil || len(k) != 32 {
t.Fatalf("KeyFromEnv: key=%d err=%v", len(k), err)
}
t.Setenv("EMCLI_KEY", "")
if _, err := KeyFromEnv(); err != ErrNoKey {
t.Fatalf("empty key: want ErrNoKey, got %v", err)
}
t.Setenv("EMCLI_KEY", base64.StdEncoding.EncodeToString([]byte("tooshort")))
if _, err := KeyFromEnv(); err != ErrBadKey {
t.Fatalf("short key: want ErrBadKey, got %v", err)
}
}