package httpapi import ( "context" "knowledge-governance/internal/qaopsmirror" "net/http" "net/http/httptest" "strings" "testing" "time" ) type departmentStatisticsFixture struct { masterFixtureReader reads int } func (f *departmentStatisticsFixture) ReadDepartmentStatistics(context.Context, qaopsmirror.DepartmentStatisticsQuery, time.Time) (qaopsmirror.DepartmentStatisticsResult, error) { f.reads++ return qaopsmirror.DepartmentStatisticsResult{State: "pending", RetryAfter: 1}, nil } func TestDepartmentStatisticsRouteIsAsynchronousStrictAndAdminOnly(t *testing.T) { auth := newFakeAuthStore() auth.sessions["dept-fixture-admin"] = "usr-boss" auth.sessions["dept-fixture-viewer"] = "usr-eye" reader := &departmentStatisticsFixture{} h, e := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: reader, QAOpsTenantKey: "fixture-tenant", Now: func() time.Time { return time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC) }}) if e != nil { t.Fatal(e) } for _, c := range []struct { body, token, intent, site string want int }{ {`{"period":"all"}`, "dept-fixture-admin", "qa-department-statistics", "", 202}, {`{"period":"month","month":"2026-10"}`, "dept-fixture-admin", "qa-department-statistics", "same-origin", 202}, {`{"period":"all"}`, "", "qa-department-statistics", "", 401}, {`{"period":"all"}`, "dept-fixture-viewer", "qa-department-statistics", "", 403}, {`{"period":"all"}`, "dept-fixture-admin", "", "", 403}, {`{"period":"all"}`, "dept-fixture-admin", "qa-department-statistics", "cross-site", 403}, {`{"period":"all","tenant":"other"}`, "dept-fixture-admin", "qa-department-statistics", "", 400}, {`{"period":"all","period":"all"}`, "dept-fixture-admin", "qa-department-statistics", "", 400}, {`null`, "dept-fixture-admin", "qa-department-statistics", "", 400}, {`{"period":"month","month":"2027-01"}`, "dept-fixture-admin", "qa-department-statistics", "", 400}, {`{"period":"all","month":"2026-10"}`, "dept-fixture-admin", "qa-department-statistics", "", 400}, } { r := httptest.NewRequest("POST", "/api/v1/qa-ops/departments/statistics", strings.NewReader(c.body)) if c.token != "" { r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: c.token}) } if c.intent != "" { r.Header.Set("X-Governance-Action", c.intent) } if c.site != "" { r.Header.Set("Sec-Fetch-Site", c.site) } w := httptest.NewRecorder() h.ServeHTTP(w, r) if w.Code != c.want { t.Fatalf("department statistics got %d want %d", w.Code, c.want) } if w.Header().Get("Cache-Control") != "no-store" { t.Fatal("employee department stats became publicly cacheable") } } if reader.reads != 2 { t.Fatal("malformed or unauthorized request reached aggregation", reader.reads) } }