miaopanel
1package httpapi
2
3import (
4 "bytes"
5 "encoding/json"
6 "net/http"
7 "net/url"
8 "testing"
9 "time"
10
11 "github.com/miaopanel/miaopanel/internal/security"
12 "github.com/miaopanel/miaopanel/internal/store"
13)
14
15type qrCreated struct {
16 Ticket string `json:"ticket"`
17 Secret string `json:"secret"`
18 Payload string `json:"payload"`
19 ExpiresAt int64 `json:"expires_at"`
20 PollInterval int `json:"poll_interval"`
21 Entry string `json:"entry"`
22 Scheme string `json:"scheme"`
23}
24
25func qrCreate(t *testing.T, h *harness) qrCreated {
26 t.Helper()
27 code, env := h.do(t, http.MethodPost, "/api/v1/auth/qr/create", map[string]any{}, "")
28 if code != http.StatusOK {
29 t.Fatalf("qr create status %d: %v", code, env)
30 }
31 raw, err := json.Marshal(env["data"])
32 if err != nil {
33 t.Fatal(err)
34 }
35 var out qrCreated
36 if err := json.Unmarshal(raw, &out); err != nil {
37 t.Fatal(err)
38 }
39 if out.Ticket == "" || out.Secret == "" || out.Payload == "" {
40 t.Fatalf("incomplete create response: %s", raw)
41 }
42 return out
43}
44
45func qrStatus(t *testing.T, h *harness, ticket string) string {
46 t.Helper()
47 code, env := h.do(t, http.MethodGet,
48 "/api/v1/auth/qr/status?ticket="+url.QueryEscape(ticket), nil, "")
49 if code != http.StatusOK {
50 t.Fatalf("qr status %d: %v", code, env)
51 }
52 data, _ := env["data"].(map[string]any)
53 status, _ := data["status"].(string)
54 return status
55}
56
57// doBearer mimics the app: no cookie jar, credential in the Authorization
58// header, therefore no CSRF token.
59func (h *harness) doBearer(t *testing.T, token, method, path string, body any) (int, map[string]any) {
60 t.Helper()
61 var rdr *bytes.Reader
62 if body != nil {
63 raw, err := json.Marshal(body)
64 if err != nil {
65 t.Fatal(err)
66 }
67 rdr = bytes.NewReader(raw)
68 } else {
69 rdr = bytes.NewReader(nil)
70 }
71 req, err := http.NewRequest(method, h.url+"/"+testEntry+path, rdr)
72 if err != nil {
73 t.Fatal(err)
74 }
75 req.Header.Set("Authorization", "Bearer "+token)
76 req.Header.Set(nativeClientHeader, "app")
77 if body != nil {
78 req.Header.Set("Content-Type", "application/json")
79 }
80 resp, err := (&http.Client{}).Do(req)
81 if err != nil {
82 t.Fatal(err)
83 }
84 defer resp.Body.Close()
85 var env map[string]any
86 _ = json.NewDecoder(resp.Body).Decode(&env)
87 return resp.StatusCode, env
88}
89
90func TestQRLoginHappyPath(t *testing.T) {
91 h := newHarness(t)
92 qr := qrCreate(t, h)
93
94 // The payload must be self describing enough for the app to route it back
95 // to the right panel and entry.
96 u, err := url.Parse(qr.Payload)
97 if err != nil {
98 t.Fatalf("payload not a URL: %v", err)
99 }
100 if u.Scheme != "miaopanel" || u.Host != "qrlogin" {
101 t.Fatalf("payload scheme = %s://%s", u.Scheme, u.Host)
102 }
103 q := u.Query()
104 if q.Get("t") != qr.Ticket || q.Get("s") != qr.Secret {
105 t.Fatal("payload does not carry the ticket and secret")
106 }
107 if q.Get("e") != testEntry {
108 t.Fatalf("payload entry = %q", q.Get("e"))
109 }
110 if q.Get("h") == "" {
111 t.Fatal("payload must carry the panel host")
112 }
113 if qr.PollInterval <= 0 {
114 t.Fatal("poll interval missing")
115 }
116
117 if st := qrStatus(t, h, qr.Ticket); st != store.QRStatusPending {
118 t.Fatalf("initial status = %s", st)
119 }
120
121 token, _ := nativeLogin(t, h)
122 code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/scan",
123 map[string]any{"ticket": qr.Ticket})
124 if code != http.StatusOK {
125 t.Fatalf("scan status %d: %v", code, env)
126 }
127 data, _ := env["data"].(map[string]any)
128 if data["status"] != store.QRStatusScanned {
129 t.Fatalf("scan response = %v", data)
130 }
131 if data["ua"] == "" {
132 t.Fatal("scan must report the browser user agent for review")
133 }
134 if st := qrStatus(t, h, qr.Ticket); st != store.QRStatusScanned {
135 t.Fatalf("status after scan = %s", st)
136 }
137
138 // A second phone may open the same code while it is still undecided.
139 if code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/scan",
140 map[string]any{"ticket": qr.Ticket}); code != http.StatusOK {
141 t.Fatalf("re-scan status %d: %v", code, env)
142 }
143
144 code, env = h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/approve",
145 map[string]any{"ticket": qr.Ticket, "approve": true})
146 if code != http.StatusOK {
147 t.Fatalf("approve status %d: %v", code, env)
148 }
149
150 // Once decided, the code must not be handed to another phone.
151 if code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/scan",
152 map[string]any{"ticket": qr.Ticket}); code != http.StatusConflict {
153 t.Fatalf("scan after approve status %d: %v", code, env)
154 }
155 if code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/approve",
156 map[string]any{"ticket": qr.Ticket, "approve": false}); code != http.StatusConflict {
157 t.Fatalf("second decision status %d: %v", code, env)
158 }
159 if st := qrStatus(t, h, qr.Ticket); st != store.QRStatusConfirmed {
160 t.Fatalf("status after approve = %s", st)
161 }
162
163 code, env = h.do(t, http.MethodPost, "/api/v1/auth/qr/exchange",
164 map[string]string{"ticket": qr.Ticket, "secret": qr.Secret}, "")
165 if code != http.StatusOK {
166 t.Fatalf("exchange status %d: %v", code, env)
167 }
168 sess, _ := env["data"].(map[string]any)
169 if csrf, _ := sess["csrf"].(string); csrf == "" {
170 t.Fatal("exchange did not return a csrf token")
171 }
172 if _, ok := sess["token"]; ok {
173 t.Fatal("browser exchange must not leak a bearer token")
174 }
175
176 // The browser is now signed in.
177 code, env = h.do(t, http.MethodGet, "/api/v1/auth/session", nil, "")
178 if code != http.StatusOK {
179 t.Fatalf("session after exchange %d: %v", code, env)
180 }
181 if body := env["data"].(map[string]any); body["user"] == nil {
182 t.Fatal("session payload missing user")
183 }
184
185 // One QR code, one session.
186 code, _ = h.do(t, http.MethodPost, "/api/v1/auth/qr/exchange",
187 map[string]string{"ticket": qr.Ticket, "secret": qr.Secret}, "")
188 if code != http.StatusConflict {
189 t.Fatalf("replay exchange status %d", code)
190 }
191 if st := qrStatus(t, h, qr.Ticket); st != store.QRStatusConsumed {
192 t.Fatalf("status after exchange = %s", st)
193 }
194}
195
196func TestQRPayloadSanitizesHostAndEntry(t *testing.T) {
197 payload := buildQRPayload("evil.example.com&t=hijack", "entry&approve=1", "tk", "sc")
198 u, err := url.Parse(payload)
199 if err != nil {
200 t.Fatal(err)
201 }
202 values := u.Query()
203 if values.Get("t") != "tk" || values.Get("s") != "sc" {
204 t.Fatalf("ticket/secret order changed: %v", values)
205 }
206 // The injected parameters must stay inside the h/e values.
207 if values.Get("approve") != "" {
208 t.Fatalf("entry injected a parameter: %v", values)
209 }
210 if got := values.Get("h"); got != "evil.example.comthijack" {
211 t.Fatalf("host = %q", got)
212 }
213 if len(values) != 4 {
214 t.Fatalf("unexpected parameter count: %v", values)
215 }
216}
217
218func TestQRLoginRejectsWrongSecret(t *testing.T) {
219 h := newHarness(t)
220 qr := qrCreate(t, h)
221 token, _ := nativeLogin(t, h)
222 if code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/approve",
223 map[string]any{"ticket": qr.Ticket, "approve": true}); code != http.StatusOK {
224 t.Fatalf("approve %d: %v", code, env)
225 }
226 code, env := h.do(t, http.MethodPost, "/api/v1/auth/qr/exchange",
227 map[string]string{"ticket": qr.Ticket, "secret": "not-the-secret"}, "")
228 if code != http.StatusForbidden {
229 t.Fatalf("wrong secret status %d: %v", code, env)
230 }
231 // A failed attempt must not burn the ticket.
232 if st := qrStatus(t, h, qr.Ticket); st != store.QRStatusConfirmed {
233 t.Fatalf("status after bad secret = %s", st)
234 }
235 if code, env := h.do(t, http.MethodPost, "/api/v1/auth/qr/exchange",
236 map[string]string{"ticket": qr.Ticket, "secret": qr.Secret}, ""); code != http.StatusOK {
237 t.Fatalf("valid exchange after retry %d: %v", code, env)
238 }
239}
240
241func TestQRLoginDeniedOnPhone(t *testing.T) {
242 h := newHarness(t)
243 qr := qrCreate(t, h)
244 token, _ := nativeLogin(t, h)
245 code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/approve",
246 map[string]any{"ticket": qr.Ticket, "approve": false})
247 if code != http.StatusOK {
248 t.Fatalf("deny %d: %v", code, env)
249 }
250 if st := qrStatus(t, h, qr.Ticket); st != store.QRStatusDenied {
251 t.Fatalf("status after deny = %s", st)
252 }
253 code, env = h.do(t, http.MethodPost, "/api/v1/auth/qr/exchange",
254 map[string]string{"ticket": qr.Ticket, "secret": qr.Secret}, "")
255 if code != http.StatusForbidden {
256 t.Fatalf("exchange of denied ticket %d: %v", code, env)
257 }
258}
259
260func TestQRLoginExpiredAndUnknown(t *testing.T) {
261 h := newHarness(t)
262 now := time.Now().Unix()
263 // Plant an already expired challenge. The API only ever sees the token
264 // hash, so we can address the row by hashing the token ourselves.
265 const staleTicket = "stale-ticket-value"
266 const staleSecret = "stale-secret-value"
267 stale := &store.QRTicket{
268 ID: security.HashToken(staleTicket), SecretHash: security.HashToken(staleSecret),
269 Status: store.QRStatusConfirmed, IP: "203.0.113.4", UA: "browser",
270 UserID: 1, CreatedAt: now - 300, ExpiresAt: now - 60, UpdatedAt: now - 120,
271 }
272 if err := h.db.CreateQRTicket(t.Context(), stale); err != nil {
273 t.Fatal(err)
274 }
275
276 token, _ := nativeLogin(t, h)
277 code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/scan",
278 map[string]any{"ticket": "anything"})
279 if code != http.StatusNotFound {
280 t.Fatalf("scan unknown ticket %d: %v", code, env)
281 }
282 code, env = h.do(t, http.MethodPost, "/api/v1/auth/qr/exchange",
283 map[string]string{"ticket": "anything", "secret": "anything"}, "")
284 if code != http.StatusGone {
285 t.Fatalf("exchange unknown ticket %d: %v", code, env)
286 }
287 // An unknown ticket is reported as "invalid" rather than an error so the
288 // login page has a single polling code path.
289 if st := qrStatus(t, h, "unknown-ticket"); st != "invalid" {
290 t.Fatalf("unknown status = %s", st)
291 }
292
293 // An expired challenge must not be usable even when it was confirmed
294 // before the deadline.
295 if st := qrStatus(t, h, staleTicket); st != "expired" {
296 t.Fatalf("stale status = %s", st)
297 }
298 if code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/scan",
299 map[string]any{"ticket": staleTicket}); code != http.StatusGone {
300 t.Fatalf("scan stale ticket %d: %v", code, env)
301 }
302 if code, env := h.do(t, http.MethodPost, "/api/v1/auth/qr/exchange",
303 map[string]string{"ticket": staleTicket, "secret": staleSecret}, ""); code != http.StatusGone {
304 t.Fatalf("exchange stale ticket %d: %v", code, env)
305 }
306 if code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/approve",
307 map[string]any{"ticket": staleTicket, "approve": true}); code != http.StatusGone {
308 t.Fatalf("approve stale ticket %d: %v", code, env)
309 }
310}
311
312func TestQRLoginRequiresExplicitDecision(t *testing.T) {
313 h := newHarness(t)
314 qr := qrCreate(t, h)
315 token, _ := nativeLogin(t, h)
316 code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/approve",
317 map[string]any{"ticket": qr.Ticket})
318 if code != http.StatusBadRequest {
319 t.Fatalf("missing approve field must fail, got %d: %v", code, env)
320 }
321 if st := qrStatus(t, h, qr.Ticket); st != store.QRStatusPending {
322 t.Fatalf("status changed without a decision: %s", st)
323 }
324}
325
326func TestQRLoginPhoneEndpointsRequireAuth(t *testing.T) {
327 h := newHarness(t)
328 qr := qrCreate(t, h)
329 for _, path := range []string{"/api/v1/auth/qr/scan", "/api/v1/auth/qr/approve"} {
330 req, err := http.NewRequest(http.MethodPost, h.url+"/"+testEntry+path,
331 bytes.NewReader([]byte(`{"ticket":"`+qr.Ticket+`","approve":true}`)))
332 if err != nil {
333 t.Fatal(err)
334 }
335 req.Header.Set("Content-Type", "application/json")
336 req.Header.Set("Origin", h.url)
337 resp, err := (&http.Client{}).Do(req)
338 if err != nil {
339 t.Fatal(err)
340 }
341 _ = resp.Body.Close()
342 if resp.StatusCode != http.StatusUnauthorized {
343 t.Fatalf("%s without a session returned %d", path, resp.StatusCode)
344 }
345 }
346}
347
348func TestQRCreateRateLimited(t *testing.T) {
349 h := newHarness(t)
350 for i := 0; i < qrMaxCreatePerMinute; i++ {
351 if code, env := h.do(t, http.MethodPost, "/api/v1/auth/qr/create", map[string]any{}, ""); code != http.StatusOK {
352 t.Fatalf("create %d status %d: %v", i, code, env)
353 }
354 }
355 code, env := h.do(t, http.MethodPost, "/api/v1/auth/qr/create", map[string]any{}, "")
356 if code != http.StatusTooManyRequests {
357 t.Fatalf("expected 429, got %d: %v", code, env)
358 }
359}