package httpapi import ( "context" "encoding/json" "knowledge-governance/internal/dingtalkdiscovery" "net/http" "net/http/httptest" "testing" ) func TestDWSLoginHTTPAuthenticationOwnershipAndOrigin(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() manager := dingtalkdiscovery.NewDeviceLoginManager(ctx, dingtalkdiscovery.ExecRunner{Binary: "/nonexistent/dws"}) h, err := NewHandler(Config{Store: &fakeJobStore{}, DWSLogin: manager}) if err != nil { t.Fatal(err) } call := func(method, path, role, session, origin, intent string) *httptest.ResponseRecorder { r := httptest.NewRequest(method, path, nil) if role != "" { r = r.WithContext(context.WithValue(r.Context(), sessionKey{}, sessionIdentity{UserID: "admin-user", Username: "tester", Role: role, SessionID: session})) } r.Header.Set("Origin", origin) r.Header.Set("X-Governance-Action", intent) w := httptest.NewRecorder() h.ServeHTTP(w, r) return w } for _, role := range []string{"", roleViewer, roleEngineer} { w := call("POST", "/api/v1/dws-login", role, "s1", "", "dws-login") if w.Code != 401 && w.Code != 403 { t.Fatalf("role=%q status=%d", role, w.Code) } } for _, input := range [][2]string{{"", ""}, {"https://foreign.invalid", "dws-login"}} { w := call("POST", "/api/v1/dws-login", roleAdmin, "s1", input[0], input[1]) if w.Code != 403 { t.Fatalf("origin/intent not enforced: %d", w.Code) } } w := call("POST", "/api/v1/dws-login", roleAdmin, "s1", "", "dws-login") if w.Code != 202 || w.Header().Get("Cache-Control") != "no-store" { t.Fatalf("start=%d body=%s", w.Code, w.Body) } var body struct { Data dingtalkdiscovery.DeviceLoginView `json:"data"` } if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Data.ID == "" { t.Fatal("missing session", err) } path := "/api/v1/dws-login/" + body.Data.ID for _, method := range []string{"GET", "DELETE"} { w = call(method, path, roleAdmin, "other-session", "", "dws-login") if w.Code != 404 { t.Fatalf("foreign session %s=%d", method, w.Code) } w = call(method, path, roleEngineer, "s1", "", "dws-login") if w.Code != 403 { t.Fatalf("engineer %s=%d", method, w.Code) } } w = call("GET", path, roleAdmin, "s1", "", "") if w.Code != 200 { t.Fatalf("get=%d", w.Code) } w = call("DELETE", path, roleAdmin, "s1", "", "dws-login") if w.Code != 200 { t.Fatalf("cancel=%d", w.Code) } } func TestDWSLoginRoutesAreAdminOnly(t *testing.T) { for _, method := range []string{http.MethodGet, http.MethodPost, http.MethodDelete} { for _, path := range []string{"/api/v1/dws-login", "/api/v1/dws-login/session-id"} { if got := classifyRole(method, path); got != roleAdmin { t.Errorf("%s %s role=%s; authorization artifacts must be admin-only", method, path, got) } } } }