package sealbox import ( "crypto/ed25519" "crypto/rand" "errors" "os" "testing" "time" "amadan.net/oficina/equipo/internal/wire" "amadan.net/rastrillo/rastrillo/budget" "golang.org/x/crypto/curve25519" "golang.org/x/crypto/nacl/box" ) func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } func keys(t *testing.T) (ed25519.PublicKey, Keys) { pub, priv, err := ed25519.GenerateKey(rand.Reader) if err != nil { t.Fatal(err) } k, err := FromEd25519(priv) if err != nil { t.Fatal(err) } return pub, k } func payload(now time.Time) wire.SealedPayload { return wire.SealedPayload{Secret: "sk-ant-oat01-canary", RunnerID: "rn_1", ConnectionID: "cn_1", Provider: wire.ProviderClaude, Endpoint: wire.EndpointAnthropic, Attempt: 1, ExpiresAt: now.Add(wire.SealedTTL).UTC().Truncate(time.Second)} } func TestSealOpen(t *testing.T) { _, k := keys(t) now := time.Now() s, err := Seal(k.PublicString(), payload(now)) if err != nil { t.Fatal(err) } p, err := k.Open(s, now) if err != nil || p.Secret != "sk-ant-oat01-canary" { t.Fatalf("open %+v %v", p, err) } // Any clear field changed beside the box is refused. for name, change := range map[string]func(*wire.Sealed){ "runner": func(s *wire.Sealed) { s.RunnerID = "rn_2" }, "connection": func(s *wire.Sealed) { s.ConnectionID = "cn_2" }, "provider": func(s *wire.Sealed) { s.Provider = wire.ProviderCodex }, "endpoint": func(s *wire.Sealed) { s.Endpoint = "https://api.anthropic.com:8443" }, "attempt": func(s *wire.Sealed) { s.Attempt = 2 }, "expiry": func(s *wire.Sealed) { s.ExpiresAt = s.ExpiresAt.Add(time.Minute) }, } { bad := s change(&bad) if _, err := k.Open(bad, now); !errors.Is(err, ErrBinding) { t.Errorf("%s changed: %v", name, err) } } if _, err := k.Open(s, now.Add(wire.SealedTTL+time.Second)); !errors.Is(err, ErrExpired) { t.Fatalf("expired box opened: %v", err) } // Another runner's key does not open it. _, other := keys(t) if _, err := other.Open(s, now); !errors.Is(err, ErrOpen) { t.Fatalf("another runner opened it: %v", err) } } // The seal key is the X25519 form of the approved ed25519 public key: the // private scalar's public point matches a box sealed by libsodium's // construction (here: x/crypto's, which follows it) to that key. func TestSealKeyFromEnrolmentKey(t *testing.T) { _, k := keys(t) pub, err := curve25519.X25519(k.private[:], curve25519.Basepoint) if err != nil || string(pub) != string(k.Public[:]) { t.Fatal("public key is not the private scalar's") } out, err := box.SealAnonymous(nil, []byte("x"), &k.Public, rand.Reader) if err != nil { t.Fatal(err) } if msg, ok := box.OpenAnonymous(nil, out, &k.Public, &k.private); !ok || string(msg) != "x" { t.Fatal("does not open") } }