package api import ( "net/http" "net/http/httptest" "testing" "git.golem15.com/golem15/summercms/modules/backpack" "git.golem15.com/golem15/summercms/modules/bouncer" ) // TestOptionalBackendPrincipalDispatch pins the D-17 fix: a request the MCP // endpoint dispatches in-process carries no Authorization header but the // backend dispatch marker, and the list and show handlers must see its // principal; a request with neither stays anonymous. func TestOptionalBackendPrincipalDispatch(t *testing.T) { app := backpack.New(nil) admin := &bouncer.Principal{ID: 42, Backend: true} req := httptest.NewRequest(http.MethodGet, "/_journal/api/v1/posts", nil) req = req.WithContext(bouncer.WithDispatch(req.Context(), &bouncer.Dispatch{Guards: []string{"backend"}, Principal: admin})) out := optionalBackendPrincipal(app, req) if pr, ok := bouncer.User(out.Context()); !ok || pr != admin { t.Fatalf("dispatched request principal = %+v (%v), want the marker's admin", pr, ok) } anon := httptest.NewRequest(http.MethodGet, "/_journal/api/v1/posts", nil) if out := optionalBackendPrincipal(app, anon); out != anon { t.Fatal("a request without a bearer or marker was changed") } if _, ok := bouncer.User(anon.Context()); ok { t.Fatal("an anonymous request gained a principal") } // A marker for another guard is not the backend's. other := httptest.NewRequest(http.MethodGet, "/_journal/api/v1/posts", nil) other = other.WithContext(bouncer.WithDispatch(other.Context(), &bouncer.Dispatch{Guards: []string{"api_token"}, Principal: &bouncer.Principal{ID: 7}})) if out := optionalBackendPrincipal(app, other); out != other { t.Fatal("a marker of another guard yielded a backend principal") } }