Files
krow_backend/go-api/internal/httpserver/owliver_test.go
2026-08-25 16:37:05 +05:30

316 lines
11 KiB
Go

package httpserver_test
import (
"net/http"
"net/url"
"testing"
)
// GET /api/v1/owliver/suggestions.
//
// The ranking itself is tested in internal/owliver, against no database and no
// server. What is tested here is only what the HTTP boundary adds: the session
// requirement, the query-string contract, the response envelope, and the fact
// that the role deciding which readings exist is the session's rather than
// anything the caller can set.
const suggestPath = "/api/v1/owliver/suggestions"
// suggestURL builds the endpoint's address, escaping as a browser would.
func suggestURL(page, query string) string {
v := url.Values{}
if page != "" {
v.Set("page", page)
}
if query != "" {
v.Set("query", query)
}
return suggestPath + "?" + v.Encode()
}
// suggestions reads the list out of the data envelope, failing the test if the
// response is not shaped as the contract says.
func suggestions(t *testing.T, r response) []map[string]any {
t.Helper()
if r.code != http.StatusOK {
t.Fatalf("status %d, body %v", r.code, r.body)
}
data, ok := r.body["data"].(map[string]any)
if !ok {
t.Fatalf("data is not an object: %v", r.body)
}
raw, ok := data["suggestions"].([]any)
if !ok {
// json null decodes to nil, and an absent key to nothing at all. Both
// break a client that iterates the list without checking.
t.Fatalf("suggestions is not an array (got %#v)", data["suggestions"])
}
out := make([]map[string]any, len(raw))
for i, item := range raw {
entry, ok := item.(map[string]any)
if !ok {
t.Fatalf("suggestion %d is not an object: %#v", i, item)
}
out[i] = entry
}
return out
}
/* ── Authentication ─────────────────────────────────────────────────────── */
// The endpoint is not on the public allowlist. Which readings exist depends on
// who is asking, so an anonymous suggestion has no meaning.
func TestOwliverSuggestionsRequireASession(t *testing.T) {
a := newAPI(t)
got := a.doAnon("GET", suggestURL("positions", "pipeline"), nil)
if got.code != http.StatusUnauthorized {
t.Fatalf("status %d, want 401", got.code)
}
if code := got.codeOrEmpty(); code != "unauthorized" {
t.Fatalf("error code %q, want unauthorized", code)
}
// A refusal must not describe the catalogue it refused to rank.
if _, present := got.body["data"]; present {
t.Fatalf("an unauthenticated refusal carried data: %v", got.body)
}
}
/* ── The query string ───────────────────────────────────────────────────── */
func TestOwliverSuggestionsValidation(t *testing.T) {
a := newAPI(t)
cases := []struct {
name string
path string
want int
}{
{"no page", suggestPath, http.StatusBadRequest},
{"blank page", suggestPath + "?page=%20", http.StatusBadRequest},
{"unknown page", suggestURL("nowhere", "pipeline"), http.StatusBadRequest},
{"a route, not a surface", suggestURL("/admin/positions", "pipeline"), http.StatusBadRequest},
{"unknown parameter", suggestURL("positions", "pipeline") + "&role=admin", http.StatusBadRequest},
// A query is optional: with nothing typed there is nothing to rank, and
// that is an empty list rather than a refusal.
{"no query", suggestURL("positions", ""), http.StatusOK},
{"page alias", suggestURL("hired", "recent"), http.StatusOK},
{"page spelled loosely", suggestURL("Talent Pool", "availability"), http.StatusOK},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got := a.do("GET", c.path, nil)
if got.code != c.want {
t.Fatalf("status %d, want %d (body %v)", got.code, c.want, got.body)
}
if c.want == http.StatusBadRequest && got.codeOrEmpty() != "invalid_query" {
t.Fatalf("error code %q, want invalid_query", got.codeOrEmpty())
}
})
}
}
// The mux answers anything but GET, so the endpoint cannot be reached with a
// body that might carry a page, a role or an identity.
func TestOwliverSuggestionsAreReadOnly(t *testing.T) {
a := newAPI(t)
for _, method := range []string{"POST", "PATCH", "DELETE", "PUT"} {
got := a.do(method, suggestURL("positions", "pipeline"), map[string]any{"page": "positions"})
if got.code != http.StatusMethodNotAllowed {
t.Errorf("%s: status %d, want 405", method, got.code)
}
}
}
/* ── The response ───────────────────────────────────────────────────────── */
func TestOwliverSuggestionsResponseShape(t *testing.T) {
a := newAPI(t) // the seeded user is an admin
got := suggestions(t, a.do("GET", suggestURL("positions", "pipeline"), nil))
if len(got) == 0 {
t.Fatal("pipeline on positions returned nothing")
}
if len(got) > 3 {
t.Fatalf("%d suggestions, the cap is 3", len(got))
}
seenIntent, seenText := map[string]bool{}, map[string]bool{}
for i, s := range got {
text, _ := s["text"].(string)
intent, _ := s["intent"].(string)
if text == "" || intent == "" {
t.Fatalf("suggestion %d is incomplete: %v", i, s)
}
if seenIntent[intent] {
t.Fatalf("duplicate intent %q", intent)
}
if seenText[text] {
t.Fatalf("duplicate text %q", text)
}
seenIntent[intent], seenText[text] = true, true
// Nothing internal may ride along: no terms, no resource names, no
// scores, no page keys.
for key := range s {
switch key {
case "text", "intent", "capability":
default:
t.Fatalf("suggestion %d exposes %q: %v", i, key, s)
}
}
}
}
// Asking for a rendering names it in the answer — and only where the reading
// can actually be drawn that way.
func TestOwliverSuggestionsCarryARequestedShape(t *testing.T) {
a := newAPI(t)
got := suggestions(t, a.do("GET", suggestURL("positions", "show hiring activity as a flow"), nil))
if len(got) != 1 {
t.Fatalf("got %d suggestions, want 1: %v", len(got), got)
}
if got[0]["intent"] != "hiring-operations" || got[0]["capability"] != "flow" {
t.Fatalf("got %v", got[0])
}
// With no shape asked for, the field is absent rather than empty.
plain := suggestions(t, a.do("GET", suggestURL("positions", "draft"), nil))
if len(plain) == 0 {
t.Fatal("draft on positions returned nothing")
}
if _, present := plain[0]["capability"]; present {
t.Fatalf("capability was sent for an unshaped query: %v", plain[0])
}
}
// No match is an empty array, not an error and not null.
func TestOwliverSuggestionsEmptyResults(t *testing.T) {
a := newAPI(t)
for _, c := range []struct{ name, query string }{
{"nothing typed", ""},
{"one character", "p"},
{"irrelevant", "sourdough starter recipe"},
} {
t.Run(c.name, func(t *testing.T) {
if got := suggestions(t, a.do("GET", suggestURL("positions", c.query), nil)); len(got) != 0 {
t.Fatalf("got %v, want none", got)
}
})
}
// A real surface the catalogue holds no readings for is the same answer.
if got := suggestions(t, a.do("GET", suggestURL("settings", "owliver"), nil)); len(got) != 0 {
t.Fatalf("settings returned %v", got)
}
}
// The page decides the answer, so the same word must not produce the same list
// everywhere.
func TestOwliverSuggestionsAreScopedToThePage(t *testing.T) {
a := newAPI(t)
read := func(page string) []string {
out := []string{}
for _, s := range suggestions(t, a.do("GET", suggestURL(page, "pipeline"), nil)) {
out = append(out, s["intent"].(string))
}
return out
}
positions, candidates := read("positions"), read("candidates")
if len(positions) == 0 || len(candidates) == 0 {
t.Fatalf("positions=%v candidates=%v", positions, candidates)
}
if len(positions) == len(candidates) {
same := true
for i := range positions {
if positions[i] != candidates[i] {
same = false
break
}
}
if same {
t.Fatalf("both pages answered pipeline with %v", positions)
}
}
}
/* ── Authorization ──────────────────────────────────────────────────────── */
// Who is asking comes from the session, and it decides which readings exist.
//
// Talent may list job applications — but only their own, by a predicate in the
// repository — so the organization-wide readings the operator console offers
// are not theirs, and are absent rather than refused.
func TestOwliverSuggestionsFollowTheCallersRole(t *testing.T) {
r := newRBAC(t)
// A query each page can actually answer, so an empty list means the role
// was filtered rather than that the words matched nothing.
operatorPages := []struct{ page, query string }{
{"control-center", "pipeline attention"},
{"positions", "pipeline attention"},
{"candidates", "candidate score"},
{"hired-history", "recent hires outcomes"},
{"talent-pool", "talent pool availability"},
{"activity", "audit unusual activity"},
}
for _, c := range operatorPages {
for _, act := range []actor{r.admin, r.empA} {
got := suggestions(t, r.as(act, "GET", suggestURL(c.page, c.query), nil))
if len(got) == 0 {
t.Errorf("%s was offered nothing on %s for %q", act.name, c.page, c.query)
}
}
if got := suggestions(t, r.as(r.talA, "GET", suggestURL(c.page, c.query), nil)); len(got) != 0 {
t.Errorf("talent was offered %v on %s", got, c.page)
}
}
// Still 200 with an empty list, never 403: refusing would tell a caller
// which pages hold readings they cannot have.
refused := r.as(r.talA, "GET", suggestURL("positions", "pipeline"), nil)
if refused.code != http.StatusOK {
t.Fatalf("talent got status %d, want 200 with an empty list", refused.code)
}
}
// The role filter is not a blanket refusal for talent: what they may genuinely
// ask — about their own account — is still offered. Without this, the test
// above would pass with the permission check stubbed out to deny everything.
func TestOwliverSuggestionsStillServeTalentTheirOwnReadings(t *testing.T) {
r := newRBAC(t)
got := suggestions(t, r.as(r.talA, "GET", suggestURL("profile", "permission"), nil))
if len(got) == 0 {
t.Fatal("talent was offered nothing about their own account")
}
if got[0]["intent"] != "profile-permissions" {
t.Fatalf("got %v", got[0])
}
}
// A permission-sensitive reading: Hired History reads the staff table, which
// policy.go grants to operators only. Nothing about the request differs — only
// the session behind it.
func TestOwliverSuggestionsHideReadingsARoleCannotPerform(t *testing.T) {
r := newRBAC(t)
const path = suggestPath + "?page=hired-history&query=recent+hires"
for _, act := range []actor{r.admin, r.empA} {
if got := suggestions(t, r.as(act, "GET", path, nil)); len(got) == 0 {
t.Errorf("%s was offered no hiring outcomes", act.name)
}
}
if got := suggestions(t, r.as(r.talA, "GET", path, nil)); len(got) != 0 {
t.Fatalf("talent was offered readings of the staff table: %v", got)
}
}