package secretbox import ( "os" "strings" "testing" ) func withTestKey(t *testing.T) { t.Helper() t.Setenv("OPSLIC_MASTER_KEY", strings.Repeat("ab", 32)) if err := LoadMasterKey(); err != nil { t.Fatalf("LoadMasterKey: %v", err) } } func TestRoundtrip(t *testing.T) { withTestKey(t) for _, plain := range []string{"waffo-secret-123", "-----BEGIN RSA PRIVATE KEY-----\nabc\n-----END RSA PRIVATE KEY-----", "x", ""} { enc, err := Encrypt(plain) if err != nil { t.Fatalf("Encrypt(%q): %v", plain, err) } if plain != "" && !strings.HasPrefix(enc, Prefix) { t.Fatalf("密文缺少前缀: %q", enc) } got, err := Decrypt(enc) if err != nil { t.Fatalf("Decrypt: %v", err) } if got != plain { t.Fatalf("roundtrip 不一致: got %q want %q", got, plain) } } } func TestEncryptIdempotent(t *testing.T) { withTestKey(t) once, _ := Encrypt("same-value") twice, _ := Encrypt(once) if once != twice { t.Fatal("对已加密值再次 Encrypt 必须原样返回(幂等)") } } func TestDecryptPlaintextPassthrough(t *testing.T) { withTestKey(t) got, err := Decrypt("legacy-plaintext") if err != nil || got != "legacy-plaintext" { t.Fatalf("历史明文应原样返回: got %q err %v", got, err) } } func TestTamperDetection(t *testing.T) { withTestKey(t) enc, _ := Encrypt("secret") tampered := enc[:len(enc)-2] + "A=" if _, err := Decrypt(tampered); err == nil { t.Fatal("篡改后的密文必须解密失败") } } func TestLoadMasterKeyFailFast(t *testing.T) { t.Setenv("OPSLIC_MASTER_KEY", "") if err := LoadMasterKey(); err == nil { t.Fatal("缺失主密钥必须报错") } t.Setenv("OPSLIC_MASTER_KEY", "not-hex") if err := LoadMasterKey(); err == nil { t.Fatal("非法主密钥必须报错") } } func TestMain(m *testing.M) { os.Exit(m.Run()) }