package cisecret
import (
"crypto/rand"
"encoding/base64"
"strings"
"testing"
)
// A SEALED VALUE OPENS ONLY WITH ITS KEY, AT ITS OWN PLACE.
func TestASealedValueOpensOnlyWhereItLives(t *testing.T) {
key := make([]byte, 32)
rand.Read(key)
b, err := New(base64.StdEncoding.EncodeToString(key))
if err != nil || !b.Ready() {
t.Fatalf("FAIL: New: %v", err)
}
sealed, err := b.Seal("alpha", "production", "TOKEN", "s3cr3t")
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(sealed), "s3cr3t") {
t.Error("FAIL: the sealed bytes contain the value")
}
if got, err := b.Open("alpha", "production", "TOKEN", sealed); err != nil || got != "s3cr3t" {
t.Errorf("FAIL: Open = %q, %v", got, err)
}
if _, err := b.Open("alpha", "production", "OTHER", sealed); err == nil {
t.Error("FAIL: a value moved to another secret's row opened")
}
if _, err := b.Open("beta", "production", "TOKEN", sealed); err == nil {
t.Error("FAIL: a value moved to another repository opened")
}
other := make([]byte, 32)
rand.Read(other)
b2, _ := New(base64.StdEncoding.EncodeToString(other))
if _, err := b2.Open("alpha", "production", "TOKEN", sealed); err == nil {
t.Error("FAIL: another key opened the value")
}
var none Box
if _, err := none.Seal("alpha", "", "X", "v"); err != ErrNoKey {
t.Errorf("FAIL: sealing with no key answered %v; want ErrNoKey", err)
}
for _, bad := range []string{"not base64!", base64.StdEncoding.EncodeToString([]byte("short"))} {
if _, err := New(bad); err == nil {
t.Errorf("FAIL: key %q was accepted", bad)
}
}
t.Log("ok: sealed per place, per key; no key refuses")
}