package events import ( "database/sql" "errors" "testing" "github.com/danielgtaylor/huma/v2" "github.com/samcharles93/archie-core/modules/events/internal/store" "github.com/samcharles93/archie-core/modules/governance" ) // TestPersonSourceIsUsableOnlyByItsOwner guards source scopes: an // organisation's source is visible to every member, and a person's source reads // as missing to everyone but that person, so its existence isn't disclosed and // no one else can bind a trigger or event type to it. func TestPersonSourceIsUsableOnlyByItsOwner(t *testing.T) { person := func(id string) store.Source { return store.Source{ ID: hookID, Scope: store.ScopePerson, OrgID: "org", Label: "mine", PersonID: sql.NullString{String: id, Valid: true}, } } tests := []struct { name string src store.Source caller governance.IdentityID want bool }{ {"an organisation source, any member", store.Source{ID: hookID, Scope: store.ScopeOrg, OrgID: "org", Label: "alerts"}, "bob", true}, {"a person source, its owner", person("alice"), "alice", true}, {"a person source, another member", person("alice"), "bob", false}, {"a person source, the system caller", person("alice"), governance.SystemID, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { m := &Module{orgID: "org", reader: fakeSources{tt.src}} ctx := governance.WithPrincipal(t.Context(), governance.Principal{IdentityID: tt.caller}) if got, err := m.canUse(ctx, hookID); err != nil || got != tt.want { t.Fatalf("canUse = %v, %v, want %v", got, err, tt.want) } _, err := m.readSource(ctx, hookID.String()) var refused *huma.ErrorModel if tt.want && err != nil { t.Fatalf("readSource: %v", err) } if !tt.want && (!errors.As(err, &refused) || refused.Status != 404) { t.Fatalf("readSource error = %v, want a 404", err) } }) } }