225 lines
9.4 KiB
Go
225 lines
9.4 KiB
Go
package registry
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"strings"
|
|
"testing"
|
|
"unicode/utf8"
|
|
|
|
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
|
|
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
|
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
|
|
npccodec "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/npcs"
|
|
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/npcs/identity"
|
|
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared/diagnostics"
|
|
)
|
|
|
|
func TestResolveAbsentRegistryUsesExactEmptyPrompt(t *testing.T) {
|
|
resolved, err := Resolve(contracts.ReferenceSet{})
|
|
if err != nil {
|
|
t.Fatalf("Resolve() error = %v, want nil", err)
|
|
}
|
|
if resolved.Bound() || resolved.Digest() != "" || resolved.Count() != 0 {
|
|
t.Fatalf("resolved unbound registry = %#v, want no semantic metadata", resolved)
|
|
}
|
|
input := resolved.PromptInput()
|
|
if input.Name != ReferenceSlot || input.MediaType != npccodec.MediaType || input.Digest != "" || input.OriginURI != "" {
|
|
t.Fatalf("unbound prompt input metadata = %#v, want name/media type only", input)
|
|
}
|
|
if got := string(input.Content); got != emptyPrompt {
|
|
t.Fatalf("unbound prompt input = %q, want exact empty registry", got)
|
|
}
|
|
if got := string(resolved.CanonicalBytes()); got != emptyPrompt {
|
|
t.Fatalf("unbound canonical bytes = %q, want exact empty registry", got)
|
|
}
|
|
}
|
|
|
|
func TestResolveCanonicalizesAndProvidesSemanticIdentity(t *testing.T) {
|
|
value := validRegistryList()
|
|
canonical := encodeRegistry(t, value)
|
|
raw := append([]byte(" \n"), canonical...)
|
|
raw = append(raw, []byte("\n ")...)
|
|
|
|
resolved, err := Resolve(registryReference(raw, "file:///another-session/npcs.json"))
|
|
if err != nil {
|
|
t.Fatalf("Resolve() error = %v, want nil", err)
|
|
}
|
|
if !resolved.Bound() || resolved.Count() != len(value.NPCs) {
|
|
t.Fatalf("resolved registry = %#v, want bound registry with %d NPC", resolved, len(value.NPCs))
|
|
}
|
|
if !bytes.Equal(resolved.CanonicalBytes(), canonical) || !bytes.Equal(resolved.PromptInput().Content, canonical) {
|
|
t.Fatalf("canonical content = %s, want %s", resolved.CanonicalBytes(), canonical)
|
|
}
|
|
if resolved.PromptInput().Digest != resolved.Digest() || !strings.HasPrefix(resolved.Digest(), "sha256:") {
|
|
t.Fatalf("semantic digest = %q, want SHA-256 digest", resolved.Digest())
|
|
}
|
|
if resolved.PromptInput().OriginURI != "" {
|
|
t.Fatalf("prompt input origin = %q, want no provenance path", resolved.PromptInput().OriginURI)
|
|
}
|
|
}
|
|
|
|
func TestResolveRejectsInvalidBoundaryValuesWithoutContent(t *testing.T) {
|
|
valid := validRegistryList()
|
|
second := valid.NPCs[0]
|
|
second.ID = identity.DeriveID("Captain Vale")
|
|
second.Name = "Captain Vale"
|
|
second.Aliases = []string{"The Greencloak"}
|
|
valueWithAliasCollision := dnd.NPCList{NPCs: []dnd.NPC{valid.NPCs[0], second}}
|
|
invalidID := valid
|
|
invalidID.NPCs[0].ID = "not-an-npc-id"
|
|
|
|
tests := []struct {
|
|
name string
|
|
reference contracts.ReferenceSet
|
|
wantError string
|
|
forbidden []string
|
|
}{
|
|
{name: "zero items", reference: contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ReferenceSlot: {Items: []contracts.ReferenceItem{}}}}, wantError: "exactly one"},
|
|
{name: "multiple", reference: contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ReferenceSlot: {Items: []contracts.ReferenceItem{{Content: []byte(emptyPrompt)}, {Content: []byte(emptyPrompt)}}}}}, wantError: "exactly one"},
|
|
{name: "wrong media type", reference: registryReferenceWithMedia([]byte(emptyPrompt), "text/plain"), wantError: "must be application/json"},
|
|
{name: "malformed JSON", reference: registryReference([]byte(`{"npcs":[],"MALFORMED_REGISTRY_SECRET":`), "file:///private.json"), wantError: "invalid approved NPC JSON", forbidden: []string{"MALFORMED_REGISTRY_SECRET"}},
|
|
{name: "unknown field", reference: registryReference([]byte(`{"npcs":[],"UNKNOWN_FIELD_SECRET":true}`), "file:///private.json"), wantError: "invalid approved NPC JSON", forbidden: []string{"UNKNOWN_FIELD_SECRET"}},
|
|
{name: "invalid ID", reference: registryReference(marshalRegistry(t, invalidID), "file:///private.json"), wantError: "decode NPC registry"},
|
|
{name: "alias collision", reference: registryReference(encodeRegistry(t, valueWithAliasCollision), "file:///private.json"), wantError: string(identity.IssueAliasOwnershipCollision)},
|
|
{name: "byte limit", reference: registryReference(bytes.Repeat([]byte("x"), MaxBytes+1), "file:///private.json"), wantError: "limit"},
|
|
}
|
|
for _, test := range tests {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
_, err := Resolve(test.reference)
|
|
if err == nil || !strings.Contains(err.Error(), test.wantError) {
|
|
t.Fatalf("Resolve() error = %v, want %q", err, test.wantError)
|
|
}
|
|
for _, forbidden := range append(test.forbidden, "Mira Thorn", "The Greencloak", "private.json") {
|
|
if strings.Contains(err.Error(), forbidden) {
|
|
t.Fatalf("error leaked registry content or provenance %q: %v", forbidden, err)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestResolveBoundsIdentityDiagnosticsWithoutContent(t *testing.T) {
|
|
const recordCount = 30
|
|
value := dnd.NPCList{NPCs: make([]dnd.NPC, recordCount)}
|
|
for index := range value.NPCs {
|
|
value.NPCs[index] = dnd.NPC{
|
|
ID: "npc:sha256:0000000000000000000000000000000000000000000000000000000000000000",
|
|
Name: fmt.Sprintf("PRIVATE NPC %d", index),
|
|
Aliases: []string{"PRIVATE SHARED ALIAS"},
|
|
Description: "PRIVATE DESCRIPTION",
|
|
Relationships: []dnd.NPCRelationship{},
|
|
SourceRefs: []source.SourceRef{{SourceID: "private-source", StartUnitID: 1, EndUnitID: 1}},
|
|
}
|
|
}
|
|
issues := identity.ValidateList(value)
|
|
if len(issues) <= diagnostics.MaxIssues {
|
|
t.Fatalf("identity issues = %d, want more than display limit", len(issues))
|
|
}
|
|
|
|
_, err := Resolve(registryReference(marshalRegistry(t, value), "file:///private-registry.json"))
|
|
if err == nil {
|
|
t.Fatal("Resolve() error = nil, want bounded identity rejection")
|
|
}
|
|
message := err.Error()
|
|
if !utf8.ValidString(message) || len([]byte(message)) > diagnostics.MaxMessageBytes {
|
|
t.Fatalf("identity error has invalid encoding or size: bytes=%d message=%q", len([]byte(message)), message)
|
|
}
|
|
wantOmitted := fmt.Sprintf("%d additional issue(s) omitted", len(issues)-diagnostics.MaxIssues)
|
|
if !strings.Contains(message, wantOmitted) {
|
|
t.Fatalf("identity error = %q, want %q", message, wantOmitted)
|
|
}
|
|
for _, forbidden := range []string{"PRIVATE NPC", "PRIVATE SHARED ALIAS", "PRIVATE DESCRIPTION", "private-source", "private-registry.json"} {
|
|
if strings.Contains(message, forbidden) {
|
|
t.Fatalf("identity error leaked %q: %s", forbidden, message)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestRegistryAccessorsAndLookupAreDefensive(t *testing.T) {
|
|
resolved, err := Resolve(registryReference(encodeRegistry(t, validRegistryList()), "file:///npc-registry.json"))
|
|
if err != nil {
|
|
t.Fatalf("Resolve() error = %v, want nil", err)
|
|
}
|
|
|
|
npcs := resolved.NPCs()
|
|
npcs[0].Name = "changed"
|
|
npcs[0].Aliases[0] = "changed alias"
|
|
npcs[0].Relationships[0].Target = "changed target"
|
|
npcs[0].SourceRefs[0].SourceID = "changed source"
|
|
if got, ok := resolved.Lookup("The Greencloak"); !ok || got.Name != "Mira Thorn" {
|
|
t.Fatalf("Lookup() after NPC mutation = %#v, %v, want original NPC", got, ok)
|
|
}
|
|
|
|
wantCanonical := string(resolved.CanonicalBytes())
|
|
content := resolved.CanonicalBytes()
|
|
content[0] = 'X'
|
|
input := resolved.PromptInput()
|
|
input.Content[0] = 'X'
|
|
if string(resolved.CanonicalBytes()) != wantCanonical || string(resolved.PromptInput().Content) != wantCanonical {
|
|
t.Fatal("registry content accessors share mutable state")
|
|
}
|
|
if got, ok := resolved.Lookup(" MIRA\u00a0THORN "); !ok || got.Name != "Mira Thorn" {
|
|
t.Fatalf("Lookup() canonical identity = %#v, %v, want Mira Thorn", got, ok)
|
|
}
|
|
if _, ok := resolved.Lookup("unknown NPC"); ok {
|
|
t.Fatal("Lookup() found unknown NPC")
|
|
}
|
|
}
|
|
|
|
func validRegistryList() dnd.NPCList {
|
|
return dnd.NPCList{NPCs: []dnd.NPC{{
|
|
ID: identity.DeriveID("Mira Thorn"),
|
|
Name: "Mira Thorn",
|
|
Aliases: []string{"The Greencloak"},
|
|
Description: "A guarded ranger who watches the northern road.",
|
|
Relationships: []dnd.NPCRelationship{{
|
|
Target: "Captain Vale", Relationship: "reports to",
|
|
}},
|
|
SourceRefs: []source.SourceRef{{SourceID: "npc-session", StartUnitID: 41, EndUnitID: 43}},
|
|
}}}
|
|
}
|
|
|
|
func encodeRegistry(t *testing.T, value dnd.NPCList) []byte {
|
|
t.Helper()
|
|
content, err := npccodec.New().Encode(value)
|
|
if err != nil {
|
|
t.Fatalf("encode NPC registry: %v", err)
|
|
}
|
|
return content
|
|
}
|
|
|
|
func marshalRegistry(t *testing.T, value dnd.NPCList) []byte {
|
|
t.Helper()
|
|
content, err := json.Marshal(value)
|
|
if err != nil {
|
|
t.Fatalf("marshal NPC registry: %v", err)
|
|
}
|
|
return content
|
|
}
|
|
|
|
func registryReference(content []byte, origin string) contracts.ReferenceSet {
|
|
references := registryReferenceWithMedia(content, "application/json; charset=utf-8")
|
|
item := references.Slots[ReferenceSlot].Items[0]
|
|
item.Origin.URI = origin
|
|
slot := references.Slots[ReferenceSlot]
|
|
slot.Items[0] = item
|
|
references.Slots[ReferenceSlot] = slot
|
|
return references
|
|
}
|
|
|
|
func registryReferenceWithMedia(content []byte, mediaType string) contracts.ReferenceSet {
|
|
return contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{
|
|
ReferenceSlot: {
|
|
Slot: contracts.ReferenceSlot{Name: ReferenceSlot, AcceptedMediaTypes: []string{npccodec.MediaType}, MaxBytes: MaxBytes},
|
|
Items: []contracts.ReferenceItem{{
|
|
SlotName: ReferenceSlot,
|
|
MediaType: mediaType,
|
|
Content: append([]byte(nil), content...),
|
|
Origin: contracts.ReferenceOrigin{Type: "file", URI: "file:///npc-registry.json"},
|
|
}},
|
|
},
|
|
}}
|
|
}
|