package memory import ( "context" "errors" "log/slog" "net/http" "testing" "github.com/danielgtaylor/huma/v2" "github.com/google/uuid" "github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/memory/internal/store" ) // notesAPI is the module as a signed-in person reaches it. func notesAPI(notes *noteFake) *Module { return &Module{orgID: string(governance.DefaultOrgID), log: slog.New(slog.DiscardHandler), notes: notes, shared: notes, deleted: &deletionFake{}} } // as is ctx carrying the signed-in person the handlers read their scope from. func as(person string) context.Context { return governance.WithPrincipal(context.Background(), governance.Principal{ IdentityID: governance.IdentityID(person), Kind: governance.KindUser, Org: governance.DefaultOrgID, }) } // statusOf is the HTTP status a handler's error answers with. func statusOf(t *testing.T, err error) int { t.Helper() if err == nil { return http.StatusOK } var se huma.StatusError if !errors.As(err, &se) { t.Fatalf("%v carries no status", err) } return se.GetStatus() } // TestOwnNotesOnlyByID guards the caller scope of the note routes: every route // that takes an id reaches only the caller's own note, and another person's id // answers not found rather than a refusal or a success. func TestOwnNotesOnlyByID(t *testing.T) { anothers := uuid.New() own := store.Note{ID: uuid.New(), OwnerID: "alice", Scope: string(ScopePerson), State: string(StatePublished), Class: string(ClassDurableFact), Text: "a fact"} elsewhere := store.Note{ID: anothers, OwnerID: "bob", Scope: string(ScopePerson), State: string(StatePublished), Class: string(ClassDurableFact), Text: "bob's fact"} cases := []struct { name string call func(*Module, string) error }{ {"correct", func(m *Module, id string) error { in := &correctInput{ID: id} in.Body.Text = "a corrected fact" _, err := m.correctNote(as("alice"), in) return err }}, {"disable", func(m *Module, id string) error { _, err := m.disableNote(as("alice"), &disabledInput{ID: id}) return err }}, {"forget", func(m *Module, id string) error { _, err := m.forgetNote(as("alice"), &idInput{ID: id}) return err }}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { // The own note is the success control: without it a route that // answered not found to everything would pass. if got := statusOf(t, tc.call(notesAPI(¬eFake{added: []store.Note{own, elsewhere}}), own.ID.String())); got != http.StatusOK { t.Fatalf("the caller's own note answered %d, want 200", got) } if got := statusOf(t, tc.call(notesAPI(¬eFake{added: []store.Note{own, elsewhere}}), anothers.String())); got != http.StatusNotFound { t.Fatalf("another person's note answered %d, want 404", got) } }) } }