diff --git a/internal/server/http.go b/internal/server/http.go new file mode 100644 index 0000000..45a50c2 --- /dev/null +++ b/internal/server/http.go @@ -0,0 +1,108 @@ +package server + +import ( + "crypto/subtle" + "encoding/json" + "net/http" + "strings" + + "github.com/longbin/agent-notify/internal/remote" +) + +func NewHandler(store *Store, token string) http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("/healthz", handleHealthz) + mux.Handle("/api/v1/status", bearerAuth(token, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodPost: + handleStatusPost(store, w, r) + case http.MethodGet: + handleStatusList(store, w, r) + default: + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } + }))) + mux.Handle("/api/v1/meta", bearerAuth(token, http.HandlerFunc(handleMeta(store)))) + return mux +} + +func handleHealthz(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + w.WriteHeader(http.StatusOK) +} + +func bearerAuth(token string, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !checkBearer(r, token) { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + next.ServeHTTP(w, r) + }) +} + +func checkBearer(r *http.Request, token string) bool { + if token == "" { + return false + } + h := r.Header.Get("Authorization") + const prefix = "Bearer " + if len(h) < len(prefix) || !strings.HasPrefix(h, prefix) { + return false + } + got := h[len(prefix):] + return subtle.ConstantTimeCompare([]byte(got), []byte(token)) == 1 +} + +func handleStatusPost(store *Store, w http.ResponseWriter, r *http.Request) { + defer r.Body.Close() + var report remote.StatusReport + if err := json.NewDecoder(r.Body).Decode(&report); err != nil { + http.Error(w, "bad json", http.StatusBadRequest) + return + } + if err := store.Upsert(report); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]bool{"ok": true}) +} + +func handleStatusList(store *Store, w http.ResponseWriter, r *http.Request) { + filters := ListFilters{ + Host: r.URL.Query().Get("host"), + CWD: r.URL.Query().Get("cwd"), + Agent: r.URL.Query().Get("agent"), + Status: r.URL.Query().Get("status"), + } + rows, err := store.List(filters) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + if rows == nil { + rows = []SessionRow{} + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(rows) +} + +func handleMeta(store *Store) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + meta, err := store.Meta() + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(meta) + } +} diff --git a/internal/server/http_test.go b/internal/server/http_test.go new file mode 100644 index 0000000..d1bfc3e --- /dev/null +++ b/internal/server/http_test.go @@ -0,0 +1,147 @@ +package server + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/longbin/agent-notify/internal/remote" +) + +func openTestStore(t *testing.T) *Store { + t.Helper() + db := filepath.Join(t.TempDir(), "test.db") + s, err := Open(db) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + return s +} + +func TestHTTPPostWithoutToken401(t *testing.T) { + store := openTestStore(t) + srv := httptest.NewServer(NewHandler(store, "secret")) + defer srv.Close() + + body := `{"hostname":"h","ips":["1.2.3.4"],"agent":"Cursor","cwd":"/x","status":"waiting","updated_at":"2026-06-02T00:00:00Z"}` + resp, err := http.Post(srv.URL+"/api/v1/status", "application/json", strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusUnauthorized { + t.Fatalf("status: got %d want %d", resp.StatusCode, http.StatusUnauthorized) + } +} + +func TestHTTPPostValidToken200(t *testing.T) { + store := openTestStore(t) + srv := httptest.NewServer(NewHandler(store, "secret")) + defer srv.Close() + + now := time.Now().UTC().Format(time.RFC3339Nano) + body := `{"hostname":"h","ips":["1.2.3.4"],"agent":"Cursor","cwd":"/x","status":"waiting","updated_at":"` + now + `"}` + req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/status", strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer secret") + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("status: got %d want %d", resp.StatusCode, http.StatusOK) + } + var okResp map[string]bool + if err := json.NewDecoder(resp.Body).Decode(&okResp); err != nil { + t.Fatal(err) + } + if !okResp["ok"] { + t.Fatalf("response: %+v", okResp) + } + + rows, err := store.List(ListFilters{Agent: "Cursor"}) + if err != nil { + t.Fatal(err) + } + if len(rows) != 1 { + t.Fatalf("expected 1 row in store, got %d", len(rows)) + } + if rows[0].Hostname != "h" || rows[0].Status != "waiting" { + t.Fatalf("row: %+v", rows[0]) + } +} + +func TestHTTPGetAgentFilter(t *testing.T) { + store := openTestStore(t) + now := time.Now().UTC() + for _, agent := range []string{"Cursor", "Claude"} { + if err := store.Upsert(remote.StatusReport{ + Hostname: "host-filter", + IPs: []string{"10.0.0.1"}, + Agent: agent, + CWD: "/proj", + Status: "waiting", + UpdatedAt: now, + }); err != nil { + t.Fatal(err) + } + } + + srv := httptest.NewServer(NewHandler(store, "secret")) + defer srv.Close() + + req, err := http.NewRequest(http.MethodGet, srv.URL+"/api/v1/status?agent=Cursor", nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer secret") + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("status: got %d want %d", resp.StatusCode, http.StatusOK) + } + data, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatal(err) + } + var rows []SessionRow + if err := json.Unmarshal(data, &rows); err != nil { + t.Fatal(err) + } + if len(rows) != 1 { + t.Fatalf("expected 1 row, got %d: %s", len(rows), data) + } + if rows[0].Agent != "Cursor" { + t.Fatalf("agent: got %q want Cursor", rows[0].Agent) + } +} + +func TestHTTPHealthz200(t *testing.T) { + store := openTestStore(t) + srv := httptest.NewServer(NewHandler(store, "secret")) + defer srv.Close() + + resp, err := http.Get(srv.URL + "/healthz") + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("status: got %d want %d", resp.StatusCode, http.StatusOK) + } +}