package httpapi import ( "bytes" "encoding/json" "net/http" "net/url" "testing" "time" "github.com/miaopanel/miaopanel/internal/security" "github.com/miaopanel/miaopanel/internal/store" ) type qrCreated struct { Ticket string `json:"ticket"` Secret string `json:"secret"` Payload string `json:"payload"` ExpiresAt int64 `json:"expires_at"` PollInterval int `json:"poll_interval"` Entry string `json:"entry"` Scheme string `json:"scheme"` } func qrCreate(t *testing.T, h *harness) qrCreated { t.Helper() code, env := h.do(t, http.MethodPost, "/api/v1/auth/qr/create", map[string]any{}, "") if code != http.StatusOK { t.Fatalf("qr create status %d: %v", code, env) } raw, err := json.Marshal(env["data"]) if err != nil { t.Fatal(err) } var out qrCreated if err := json.Unmarshal(raw, &out); err != nil { t.Fatal(err) } if out.Ticket == "" || out.Secret == "" || out.Payload == "" { t.Fatalf("incomplete create response: %s", raw) } return out } func qrStatus(t *testing.T, h *harness, ticket string) string { t.Helper() code, env := h.do(t, http.MethodGet, "/api/v1/auth/qr/status?ticket="+url.QueryEscape(ticket), nil, "") if code != http.StatusOK { t.Fatalf("qr status %d: %v", code, env) } data, _ := env["data"].(map[string]any) status, _ := data["status"].(string) return status } // doBearer mimics the app: no cookie jar, credential in the Authorization // header, therefore no CSRF token. func (h *harness) doBearer(t *testing.T, token, method, path string, body any) (int, map[string]any) { t.Helper() var rdr *bytes.Reader if body != nil { raw, err := json.Marshal(body) if err != nil { t.Fatal(err) } rdr = bytes.NewReader(raw) } else { rdr = bytes.NewReader(nil) } req, err := http.NewRequest(method, h.url+"/"+testEntry+path, rdr) if err != nil { t.Fatal(err) } req.Header.Set("Authorization", "Bearer "+token) req.Header.Set(nativeClientHeader, "app") if body != nil { req.Header.Set("Content-Type", "application/json") } resp, err := (&http.Client{}).Do(req) if err != nil { t.Fatal(err) } defer resp.Body.Close() var env map[string]any _ = json.NewDecoder(resp.Body).Decode(&env) return resp.StatusCode, env } func TestQRLoginHappyPath(t *testing.T) { h := newHarness(t) qr := qrCreate(t, h) // The payload must be self describing enough for the app to route it back // to the right panel and entry. u, err := url.Parse(qr.Payload) if err != nil { t.Fatalf("payload not a URL: %v", err) } if u.Scheme != "miaopanel" || u.Host != "qrlogin" { t.Fatalf("payload scheme = %s://%s", u.Scheme, u.Host) } q := u.Query() if q.Get("t") != qr.Ticket || q.Get("s") != qr.Secret { t.Fatal("payload does not carry the ticket and secret") } if q.Get("e") != testEntry { t.Fatalf("payload entry = %q", q.Get("e")) } if q.Get("h") == "" { t.Fatal("payload must carry the panel host") } if qr.PollInterval <= 0 { t.Fatal("poll interval missing") } if st := qrStatus(t, h, qr.Ticket); st != store.QRStatusPending { t.Fatalf("initial status = %s", st) } token, _ := nativeLogin(t, h) code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/scan", map[string]any{"ticket": qr.Ticket}) if code != http.StatusOK { t.Fatalf("scan status %d: %v", code, env) } data, _ := env["data"].(map[string]any) if data["status"] != store.QRStatusScanned { t.Fatalf("scan response = %v", data) } if data["ua"] == "" { t.Fatal("scan must report the browser user agent for review") } if st := qrStatus(t, h, qr.Ticket); st != store.QRStatusScanned { t.Fatalf("status after scan = %s", st) } // A second phone may open the same code while it is still undecided. if code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/scan", map[string]any{"ticket": qr.Ticket}); code != http.StatusOK { t.Fatalf("re-scan status %d: %v", code, env) } code, env = h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/approve", map[string]any{"ticket": qr.Ticket, "approve": true}) if code != http.StatusOK { t.Fatalf("approve status %d: %v", code, env) } // Once decided, the code must not be handed to another phone. if code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/scan", map[string]any{"ticket": qr.Ticket}); code != http.StatusConflict { t.Fatalf("scan after approve status %d: %v", code, env) } if code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/approve", map[string]any{"ticket": qr.Ticket, "approve": false}); code != http.StatusConflict { t.Fatalf("second decision status %d: %v", code, env) } if st := qrStatus(t, h, qr.Ticket); st != store.QRStatusConfirmed { t.Fatalf("status after approve = %s", st) } code, env = h.do(t, http.MethodPost, "/api/v1/auth/qr/exchange", map[string]string{"ticket": qr.Ticket, "secret": qr.Secret}, "") if code != http.StatusOK { t.Fatalf("exchange status %d: %v", code, env) } sess, _ := env["data"].(map[string]any) if csrf, _ := sess["csrf"].(string); csrf == "" { t.Fatal("exchange did not return a csrf token") } if _, ok := sess["token"]; ok { t.Fatal("browser exchange must not leak a bearer token") } // The browser is now signed in. code, env = h.do(t, http.MethodGet, "/api/v1/auth/session", nil, "") if code != http.StatusOK { t.Fatalf("session after exchange %d: %v", code, env) } if body := env["data"].(map[string]any); body["user"] == nil { t.Fatal("session payload missing user") } // One QR code, one session. code, _ = h.do(t, http.MethodPost, "/api/v1/auth/qr/exchange", map[string]string{"ticket": qr.Ticket, "secret": qr.Secret}, "") if code != http.StatusConflict { t.Fatalf("replay exchange status %d", code) } if st := qrStatus(t, h, qr.Ticket); st != store.QRStatusConsumed { t.Fatalf("status after exchange = %s", st) } } func TestQRPayloadSanitizesHostAndEntry(t *testing.T) { payload := buildQRPayload("evil.example.com&t=hijack", "entry&approve=1", "tk", "sc") u, err := url.Parse(payload) if err != nil { t.Fatal(err) } values := u.Query() if values.Get("t") != "tk" || values.Get("s") != "sc" { t.Fatalf("ticket/secret order changed: %v", values) } // The injected parameters must stay inside the h/e values. if values.Get("approve") != "" { t.Fatalf("entry injected a parameter: %v", values) } if got := values.Get("h"); got != "evil.example.comthijack" { t.Fatalf("host = %q", got) } if len(values) != 4 { t.Fatalf("unexpected parameter count: %v", values) } } func TestQRLoginRejectsWrongSecret(t *testing.T) { h := newHarness(t) qr := qrCreate(t, h) token, _ := nativeLogin(t, h) if code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/approve", map[string]any{"ticket": qr.Ticket, "approve": true}); code != http.StatusOK { t.Fatalf("approve %d: %v", code, env) } code, env := h.do(t, http.MethodPost, "/api/v1/auth/qr/exchange", map[string]string{"ticket": qr.Ticket, "secret": "not-the-secret"}, "") if code != http.StatusForbidden { t.Fatalf("wrong secret status %d: %v", code, env) } // A failed attempt must not burn the ticket. if st := qrStatus(t, h, qr.Ticket); st != store.QRStatusConfirmed { t.Fatalf("status after bad secret = %s", st) } if code, env := h.do(t, http.MethodPost, "/api/v1/auth/qr/exchange", map[string]string{"ticket": qr.Ticket, "secret": qr.Secret}, ""); code != http.StatusOK { t.Fatalf("valid exchange after retry %d: %v", code, env) } } func TestQRLoginDeniedOnPhone(t *testing.T) { h := newHarness(t) qr := qrCreate(t, h) token, _ := nativeLogin(t, h) code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/approve", map[string]any{"ticket": qr.Ticket, "approve": false}) if code != http.StatusOK { t.Fatalf("deny %d: %v", code, env) } if st := qrStatus(t, h, qr.Ticket); st != store.QRStatusDenied { t.Fatalf("status after deny = %s", st) } code, env = h.do(t, http.MethodPost, "/api/v1/auth/qr/exchange", map[string]string{"ticket": qr.Ticket, "secret": qr.Secret}, "") if code != http.StatusForbidden { t.Fatalf("exchange of denied ticket %d: %v", code, env) } } func TestQRLoginExpiredAndUnknown(t *testing.T) { h := newHarness(t) now := time.Now().Unix() // Plant an already expired challenge. The API only ever sees the token // hash, so we can address the row by hashing the token ourselves. const staleTicket = "stale-ticket-value" const staleSecret = "stale-secret-value" stale := &store.QRTicket{ ID: security.HashToken(staleTicket), SecretHash: security.HashToken(staleSecret), Status: store.QRStatusConfirmed, IP: "203.0.113.4", UA: "browser", UserID: 1, CreatedAt: now - 300, ExpiresAt: now - 60, UpdatedAt: now - 120, } if err := h.db.CreateQRTicket(t.Context(), stale); err != nil { t.Fatal(err) } token, _ := nativeLogin(t, h) code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/scan", map[string]any{"ticket": "anything"}) if code != http.StatusNotFound { t.Fatalf("scan unknown ticket %d: %v", code, env) } code, env = h.do(t, http.MethodPost, "/api/v1/auth/qr/exchange", map[string]string{"ticket": "anything", "secret": "anything"}, "") if code != http.StatusGone { t.Fatalf("exchange unknown ticket %d: %v", code, env) } // An unknown ticket is reported as "invalid" rather than an error so the // login page has a single polling code path. if st := qrStatus(t, h, "unknown-ticket"); st != "invalid" { t.Fatalf("unknown status = %s", st) } // An expired challenge must not be usable even when it was confirmed // before the deadline. if st := qrStatus(t, h, staleTicket); st != "expired" { t.Fatalf("stale status = %s", st) } if code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/scan", map[string]any{"ticket": staleTicket}); code != http.StatusGone { t.Fatalf("scan stale ticket %d: %v", code, env) } if code, env := h.do(t, http.MethodPost, "/api/v1/auth/qr/exchange", map[string]string{"ticket": staleTicket, "secret": staleSecret}, ""); code != http.StatusGone { t.Fatalf("exchange stale ticket %d: %v", code, env) } if code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/approve", map[string]any{"ticket": staleTicket, "approve": true}); code != http.StatusGone { t.Fatalf("approve stale ticket %d: %v", code, env) } } func TestQRLoginRequiresExplicitDecision(t *testing.T) { h := newHarness(t) qr := qrCreate(t, h) token, _ := nativeLogin(t, h) code, env := h.doBearer(t, token, http.MethodPost, "/api/v1/auth/qr/approve", map[string]any{"ticket": qr.Ticket}) if code != http.StatusBadRequest { t.Fatalf("missing approve field must fail, got %d: %v", code, env) } if st := qrStatus(t, h, qr.Ticket); st != store.QRStatusPending { t.Fatalf("status changed without a decision: %s", st) } } func TestQRLoginPhoneEndpointsRequireAuth(t *testing.T) { h := newHarness(t) qr := qrCreate(t, h) for _, path := range []string{"/api/v1/auth/qr/scan", "/api/v1/auth/qr/approve"} { req, err := http.NewRequest(http.MethodPost, h.url+"/"+testEntry+path, bytes.NewReader([]byte(`{"ticket":"`+qr.Ticket+`","approve":true}`))) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/json") req.Header.Set("Origin", h.url) resp, err := (&http.Client{}).Do(req) if err != nil { t.Fatal(err) } _ = resp.Body.Close() if resp.StatusCode != http.StatusUnauthorized { t.Fatalf("%s without a session returned %d", path, resp.StatusCode) } } } func TestQRCreateRateLimited(t *testing.T) { h := newHarness(t) for i := 0; i < qrMaxCreatePerMinute; i++ { if code, env := h.do(t, http.MethodPost, "/api/v1/auth/qr/create", map[string]any{}, ""); code != http.StatusOK { t.Fatalf("create %d status %d: %v", i, code, env) } } code, env := h.do(t, http.MethodPost, "/api/v1/auth/qr/create", map[string]any{}, "") if code != http.StatusTooManyRequests { t.Fatalf("expected 429, got %d: %v", code, env) } }