-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler_test.go
More file actions
285 lines (258 loc) · 8.64 KB
/
Copy pathhandler_test.go
File metadata and controls
285 lines (258 loc) · 8.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package web
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
// stubModels 是 ModelsSource 的测试替身。
type stubModels struct {
raw []byte
err error
at time.Time
}
func (s stubModels) GetRaw(ctx context.Context) ([]byte, error) { return s.raw, s.err }
func (s stubModels) CachedAt() time.Time { return s.at }
func testConfig() Config {
return Config{Username: "admin", Password: "pass123", SessionHours: 1}
}
func newTestMux(t *testing.T, source ModelsSource) *http.ServeMux {
t.Helper()
mux := http.NewServeMux()
NewHandler(testConfig(), source).Register(mux)
return mux
}
// doLogin 执行登录并返回会话 cookie。
func doLogin(t *testing.T, mux *http.ServeMux, username, password string) *http.Cookie {
t.Helper()
body := strings.NewReader(`{"username":"` + username + `","password":"` + password + `"}`)
req := httptest.NewRequest(http.MethodPost, "/auth/login", body)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("login status = %d, want 200 (body: %s)", rec.Code, rec.Body.String())
}
for _, c := range rec.Result().Cookies() {
if c.Name == "copilotgateway_session" {
return c
}
}
t.Fatal("login response missing session cookie")
return nil
}
func TestConfigFromEnv(t *testing.T) {
tests := []struct {
name string
user, pass string
hours string
wantEnabled bool
wantHours int
}{
{name: "both set enables", user: "u", pass: "p", wantEnabled: true, wantHours: 24},
{name: "custom hours", user: "u", pass: "p", hours: "8", wantEnabled: true, wantHours: 8},
{name: "invalid hours falls back", user: "u", pass: "p", hours: "zero", wantEnabled: true, wantHours: 24},
{name: "missing password disables", user: "u", wantEnabled: false},
{name: "missing username disables", pass: "p", wantEnabled: false},
{name: "nothing set disables", wantEnabled: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("COPILOTGW_WEB_USERNAME", tt.user)
t.Setenv("COPILOTGW_WEB_PASSWORD", tt.pass)
t.Setenv("COPILOTGW_WEB_SESSION_HOURS", tt.hours)
cfg, enabled := ConfigFromEnv()
if enabled != tt.wantEnabled {
t.Fatalf("enabled = %v, want %v", enabled, tt.wantEnabled)
}
if enabled && cfg.SessionHours != tt.wantHours {
t.Errorf("SessionHours = %d, want %d", cfg.SessionHours, tt.wantHours)
}
})
}
}
func TestLogin(t *testing.T) {
mux := newTestMux(t, stubModels{})
t.Run("valid credentials set session cookie", func(t *testing.T) {
c := doLogin(t, mux, "admin", "pass123")
if !c.HttpOnly {
t.Error("session cookie should be HttpOnly")
}
if c.SameSite != http.SameSiteLaxMode {
t.Error("session cookie should be SameSite=Lax")
}
})
t.Run("wrong password rejected", func(t *testing.T) {
body := strings.NewReader(`{"username":"admin","password":"wrong"}`)
req := httptest.NewRequest(http.MethodPost, "/auth/login", body)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Errorf("status = %d, want 401", rec.Code)
}
})
t.Run("malformed body rejected", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/auth/login", strings.NewReader("not json"))
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Errorf("status = %d, want 401", rec.Code)
}
})
}
func TestPageGuard(t *testing.T) {
mux := newTestMux(t, stubModels{})
t.Run("index without session redirects to login", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusFound {
t.Fatalf("status = %d, want 302", rec.Code)
}
if loc := rec.Header().Get("Location"); loc != "/login" {
t.Errorf("Location = %q, want /login", loc)
}
})
t.Run("index with session serves page", func(t *testing.T) {
c := doLogin(t, mux, "admin", "pass123")
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.AddCookie(c)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/html") {
t.Errorf("Content-Type = %q, want text/html", ct)
}
})
t.Run("login page is public", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/login", nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("status = %d, want 200", rec.Code)
}
})
}
func TestSessionEndpointAndLogout(t *testing.T) {
mux := newTestMux(t, stubModels{})
t.Run("session endpoint reports state", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/auth/session", nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
var got struct {
Authenticated bool `json:"authenticated"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
if got.Authenticated {
t.Error("should be unauthenticated without cookie")
}
})
t.Run("logout invalidates session", func(t *testing.T) {
c := doLogin(t, mux, "admin", "pass123")
req := httptest.NewRequest(http.MethodPost, "/auth/logout", nil)
req.AddCookie(c)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("logout status = %d, want 200", rec.Code)
}
req = httptest.NewRequest(http.MethodGet, "/web/api/models", nil)
req.AddCookie(c)
rec = httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Errorf("after logout status = %d, want 401", rec.Code)
}
})
}
func TestConfigEndpoint(t *testing.T) {
mux := http.NewServeMux()
cfg := testConfig()
cfg.APIKeys = []string{"sk-demo-1", "sk-demo-2"}
NewHandler(cfg, stubModels{}).Register(mux)
t.Run("without session returns 401", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/web/api/config", nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Errorf("status = %d, want 401", rec.Code)
}
})
t.Run("with session returns api keys", func(t *testing.T) {
c := doLogin(t, mux, "admin", "pass123")
req := httptest.NewRequest(http.MethodGet, "/web/api/config", nil)
req.AddCookie(c)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
var got struct {
APIKeys []string `json:"api_keys"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
if len(got.APIKeys) != 2 || got.APIKeys[0] != "sk-demo-1" {
t.Errorf("api_keys = %v, want [sk-demo-1 sk-demo-2]", got.APIKeys)
}
})
}
func TestModelsEndpoint(t *testing.T) {
upstreamRaw := []byte(`{"object":"list","data":[{"id":"claude-fable-5","name":"Claude Fable 5"}]}`)
fixedAt := time.Date(2026, 7, 8, 12, 0, 0, 0, time.UTC)
t.Run("without session returns 401", func(t *testing.T) {
mux := newTestMux(t, stubModels{raw: upstreamRaw, at: fixedAt})
req := httptest.NewRequest(http.MethodGet, "/web/api/models", nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Errorf("status = %d, want 401", rec.Code)
}
})
t.Run("with session returns cached data", func(t *testing.T) {
mux := newTestMux(t, stubModels{raw: upstreamRaw, at: fixedAt})
c := doLogin(t, mux, "admin", "pass123")
req := httptest.NewRequest(http.MethodGet, "/web/api/models", nil)
req.AddCookie(c)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (body: %s)", rec.Code, rec.Body.String())
}
var got struct {
CachedAt time.Time `json:"cached_at"`
Data []json.RawMessage `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
if !got.CachedAt.Equal(fixedAt) {
t.Errorf("cached_at = %v, want %v", got.CachedAt, fixedAt)
}
if len(got.Data) != 1 {
t.Errorf("data length = %d, want 1", len(got.Data))
}
})
t.Run("upstream failure returns 502 with error", func(t *testing.T) {
mux := newTestMux(t, stubModels{err: context.DeadlineExceeded})
c := doLogin(t, mux, "admin", "pass123")
req := httptest.NewRequest(http.MethodGet, "/web/api/models", nil)
req.AddCookie(c)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusBadGateway {
t.Fatalf("status = %d, want 502", rec.Code)
}
if !strings.Contains(rec.Body.String(), "error") {
t.Errorf("body should contain error message, got: %s", rec.Body.String())
}
})
}