package api import ( "bufio" "bytes" "context" "errors" "fmt" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/glebarez/sqlite" "github.com/iniwex5/vohive/internal/balance" "github.com/iniwex5/vohive/internal/carrierquery" "github.com/iniwex5/vohive/internal/commandcenter" "github.com/iniwex5/vohive/internal/config" "github.com/iniwex5/vohive/internal/db" "github.com/iniwex5/vohive/internal/notify" "gorm.io/gorm" ) type apiBalanceGateway struct { smsCalls int } func (g *apiBalanceGateway) Snapshot(deviceID string) (balance.DeviceSnapshot, error) { return balance.DeviceSnapshot{DeviceID: deviceID, ICCID: "iccid-1", MCC: "234", MNC: "10"}, nil } func (g *apiBalanceGateway) SendVoWiFiSMS(context.Context, string, string, string) error { return errors.New("unexpected VoWiFi route") } func (g *apiBalanceGateway) SendBackendSMS(context.Context, string, string, string) error { g.smsCalls++ return nil } func (*apiBalanceGateway) SendVoWiFiUSSD(context.Context, string, string) (balance.USSDResponse, error) { return balance.USSDResponse{}, errors.New("unexpected VoWiFi USSD route") } func (*apiBalanceGateway) SendBackendUSSD(context.Context, string, string) (balance.USSDResponse, error) { return balance.USSDResponse{}, errors.New("unexpected backend USSD route") } type apiRuleResolver struct{} func (apiRuleResolver) Resolve(context.Context, balance.DeviceSnapshot) (carrierquery.Rule, error) { return carrierquery.Rule{ID: "giffgaff", MCC: "234", MNC: "10", Operator: "giffgaff", Transport: carrierquery.TransportSMS, Destination: "85075", Payload: "INFO", ResponseMode: carrierquery.ResponseSMS, ExpectedSenders: []string{"giffgaff"}, Enabled: true}, nil } func (apiRuleResolver) ByID(context.Context, string) (carrierquery.Rule, error) { return apiRuleResolver{}.Resolve(context.Background(), balance.DeviceSnapshot{}) } type apiCarrierRuleStore struct { rules map[string]carrierquery.Rule saveCalls int } func (s *apiCarrierRuleStore) ListCustomCarrierQueryRules() ([]carrierquery.Rule, error) { rules := make([]carrierquery.Rule, 0, len(s.rules)) for _, rule := range s.rules { rules = append(rules, rule) } return rules, nil } func (s *apiCarrierRuleStore) SaveCustomCarrierQueryRule(rule carrierquery.Rule) error { if err := rule.Validate(); err != nil { return err } s.saveCalls++ s.rules[rule.ID] = rule return nil } func (s *apiCarrierRuleStore) DeleteCustomCarrierQueryRule(id string) error { delete(s.rules, id) return nil } func TestCommandCenterRoutesRequireAuthAndPersistExecution(t *testing.T) { server, token, _ := newCommandCenterAPITestServer(t) router := server.newRouter() unauthorized := performAPIRequest(router, apiRequestOptions{method: http.MethodGet, path: "/api/command-center/commands"}) if unauthorized.Code != http.StatusUnauthorized { t.Fatalf("unauthorized status = %d", unauthorized.Code) } body := bytes.NewBufferString(`{"input":"/list"}`) accepted := performAPIRequest(router, apiRequestOptions{method: http.MethodPost, path: "/api/command-center/executions", token: token, body: body}) if accepted.Code != http.StatusAccepted { t.Fatalf("execute status = %d body=%s", accepted.Code, accepted.Body.String()) } waitForAPIEvents(t, server.commandCenter, 2) events := performAPIRequest(router, apiRequestOptions{method: http.MethodGet, path: "/api/command-center/events?after_id=0", token: token}) if events.Code != http.StatusOK || !strings.Contains(events.Body.String(), `"state":"completed"`) { t.Fatalf("events status=%d body=%s", events.Code, events.Body.String()) } } func TestBalanceQueryRouteUsesInjectedProductionService(t *testing.T) { server, token, gateway := newCommandCenterAPITestServer(t) response := performAPIRequest(server.newRouter(), apiRequestOptions{ method: http.MethodPost, path: "/api/devices/wwan0/balance-queries", token: token, }) if response.Code != http.StatusAccepted || gateway.smsCalls != 1 { t.Fatalf("balance status=%d calls=%d body=%s", response.Code, gateway.smsCalls, response.Body.String()) } } func TestApprovedCommandCenterRoutesAreProtected(t *testing.T) { server, _, _ := newCommandCenterAPITestServer(t) router := server.newRouter() routes := []apiRequestOptions{ {method: http.MethodGet, path: "/api/command-center/commands"}, {method: http.MethodPost, path: "/api/command-center/executions"}, {method: http.MethodGet, path: "/api/command-center/events"}, {method: http.MethodGet, path: "/api/command-center/stream"}, {method: http.MethodDelete, path: "/api/command-center/history"}, {method: http.MethodGet, path: "/api/balances"}, {method: http.MethodPost, path: "/api/devices/wwan0/balance-queries"}, {method: http.MethodGet, path: "/api/devices/wwan0/balance-queries"}, {method: http.MethodGet, path: "/api/carrier-query-rules"}, {method: http.MethodPost, path: "/api/carrier-query-rules"}, {method: http.MethodPut, path: "/api/carrier-query-rules/custom"}, {method: http.MethodDelete, path: "/api/carrier-query-rules/custom"}, } for _, route := range routes { response := performAPIRequest(router, route) if response.Code != http.StatusUnauthorized { t.Errorf("%s %s status = %d, want 401", route.method, route.path, response.Code) } } } func TestCarrierRuleCollectionPostValidatesReplySenders(t *testing.T) { server, token, _ := newCommandCenterAPITestServer(t) store := server.carrierRules.(*apiCarrierRuleStore) body := bytes.NewBufferString(`{"id":"custom","mcc":"234","mnc":"10","operator":"custom","transport":"sms","destination":"85075","payload":"INFO","response_mode":"sms","enabled":true}`) response := performAPIRequest(server.newRouter(), apiRequestOptions{ method: http.MethodPost, path: "/api/carrier-query-rules", token: token, body: body, }) if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "预期发送者") { t.Fatalf("empty sender status=%d body=%s", response.Code, response.Body.String()) } if store.saveCalls != 0 { t.Fatalf("invalid rule persisted, save calls=%d", store.saveCalls) } validBody := bytes.NewBufferString(`{"id":"custom","mcc":"234","mnc":"10","operator":"custom","transport":"sms","destination":"85075","payload":"INFO","response_mode":"sms","expected_senders":["85075"],"enabled":true}`) valid := performAPIRequest(server.newRouter(), apiRequestOptions{ method: http.MethodPost, path: "/api/carrier-query-rules", token: token, body: validBody, }) if valid.Code != http.StatusOK || store.saveCalls != 1 { t.Fatalf("valid rule status=%d calls=%d body=%s", valid.Code, store.saveCalls, valid.Body.String()) } } func TestCommandEventStreamResumesAfterLastEventID(t *testing.T) { server, token, _ := newCommandCenterAPITestServer(t) if _, err := server.commandCenter.Execute(context.Background(), commandcenter.ExecuteRequest{Input: "/list"}); err != nil { t.Fatal(err) } events := waitForAPIEvents(t, server.commandCenter, 2) httpServer := httptest.NewServer(server.newRouter()) defer httpServer.Close() ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() request, _ := http.NewRequestWithContext(ctx, http.MethodGet, httpServer.URL+"/api/command-center/stream", nil) request.Header.Set("Authorization", "Bearer "+token) request.Header.Set("Last-Event-ID", fmt.Sprint(events[0].ID)) response, err := http.DefaultClient.Do(request) if err != nil { t.Fatal(err) } defer response.Body.Close() scanner := bufio.NewScanner(response.Body) for scanner.Scan() { if strings.HasPrefix(scanner.Text(), "id:") { if got := strings.TrimSpace(strings.TrimPrefix(scanner.Text(), "id:")); got != fmt.Sprint(events[1].ID) { t.Fatalf("resumed event id = %s, want %d", got, events[1].ID) } return } } t.Fatalf("stream ended without event: %v", scanner.Err()) } func newCommandCenterAPITestServer(t *testing.T) (*Server, string, *apiBalanceGateway) { t.Helper() database, err := gorm.Open(sqlite.Open(fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())), &gorm.Config{}) if err != nil { t.Fatal(err) } if err := database.AutoMigrate(&db.CommandExecution{}, &db.CommandEvent{}, &db.BalanceQuery{}); err != nil { t.Fatal(err) } commands := notify.NewCommandService(map[string]notify.CommandHandler{ "list": func(_ notify.CommandContext, _ []string) string { return "设备列表 / 完成" }, }) gateway := &apiBalanceGateway{} server := &Server{auth: config.WebConfig{Username: "admin", Password: "secret"}, commandCenter: commandcenter.NewService(commands, commandcenter.NewDatabaseStore(database)), balance: balance.NewService(gateway, balance.NewDatabaseStore(database), apiRuleResolver{}), carrierRules: &apiCarrierRuleStore{rules: make(map[string]carrierquery.Rule)}, shutdownCh: make(chan struct{}), } token, _, err := server.issueSessionToken() if err != nil { t.Fatal(err) } return server, token, gateway } type apiRequestOptions struct { method string path string token string body *bytes.Buffer } func performAPIRequest(handler http.Handler, options apiRequestOptions) *httptest.ResponseRecorder { var request *http.Request if options.body == nil { request = httptest.NewRequest(options.method, options.path, nil) } else { request = httptest.NewRequest(options.method, options.path, options.body) request.Header.Set("Content-Type", "application/json") } if options.token != "" { request.Header.Set("Authorization", "Bearer "+options.token) } recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, request) return recorder } func waitForAPIEvents(t *testing.T, service *commandcenter.Service, count int) []commandcenter.Event { t.Helper() deadline := time.Now().Add(time.Second) for time.Now().Before(deadline) { events, err := service.ListEvents(context.Background(), 0, 20) if err != nil { t.Fatal(err) } if len(events) >= count { return events } time.Sleep(10 * time.Millisecond) } t.Fatal("timed out waiting for command events") return nil }