From cc26953d5e30c1b79af90fe12449a84658f406b6 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Mon, 8 Jun 2026 21:17:39 -0700 Subject: [PATCH] Add POST /api/links REST endpoint for short-link creation Programmatic short-link creation that shares the same bearer key as the MCP endpoint. Registered only when [mcp].enabled is true and api_key is set, so a misconfigured server never exposes the route unauthenticated; unauthenticated visitors hitting /api/links get a plain 404. - POST /api/links accepts {"url","slug?"}, returns 201/200 with the same snake_case payload shape as the MCP create_link tool. - Constant-time Bearer / X-API-Key auth (reuses mcpAPIKeyAuth helper). - 4 KB body cap, DisallowUnknownFields, URL auto-scheme, dedupe on URL. - 13 unit tests cover auth, validation, dedupe, and duplicate-slug. --- README.md | 52 ++++++ internal/server/api.go | 168 +++++++++++++++++++ internal/server/api_test.go | 319 ++++++++++++++++++++++++++++++++++++ internal/server/server.go | 8 + 4 files changed, 547 insertions(+) create mode 100644 internal/server/api.go create mode 100644 internal/server/api_test.go diff --git a/README.md b/README.md index 3db0543..a8e3264 100644 --- a/README.md +++ b/README.md @@ -188,6 +188,57 @@ api_key = "replace-with-a-long-random-token" MCP clients can authenticate with `Authorization: Bearer ` or `X-API-Key: `. Basic auth using the configured admin username and password is also accepted. The endpoint exposes tools for listing, creating, updating, and deleting links and pastes, plus listing and deleting upload metadata/files. +### REST API + +A small REST surface shares the same `[mcp].api_key`. It is registered only when `[mcp].enabled = true` **and** `api_key` is set, so a misconfigured server never exposes the endpoint unauthenticated. The route is intentionally undocumented in any public-facing template — visitors who don't know it exists get a 404. + +#### `POST /api/links` + +Create a short link. Authenticate with `Authorization: Bearer ` or `X-API-Key: `. Both are checked with constant-time comparison. + +Request body (JSON): +```json +{ + "url": "https://example.com/very/long/path", + "slug": "docs" // optional; omit for auto-generated +} +``` + +Rules: +- `url` — required. Max 2048 chars. Must be `http://` or `https://`. Bare domains are auto-prefixed with `https://`. +- `slug` — optional. Lowercase letters, digits, hyphens, and underscores, up to 64 chars. +- Deduplication: if the same URL is submitted twice and no custom slug is given, the second call returns the existing link with HTTP 200 (idempotent). +- Links created via the API are recorded as `created_by = "admin"` and appear in the admin dashboard. + +Responses: +- `201 Created` — new link created. Body is the link payload. +- `200 OK` — same URL already existed; returns the existing link. +- `400 Bad Request` — invalid JSON, bad URL, or bad slug. +- `401 Unauthorized` — missing or wrong API key. +- `409 Conflict` — custom slug already taken. +- `500 Internal Server Error` — database error. + +Response body (snake_case to match the MCP payload): +```json +{ + "id": 42, + "slug": "docs", + "url": "https://example.com/very/long/path", + "short_url": "https://s.example.com/docs", + "created_by": "admin", + "clicks": 0, + "created_at": "2026-06-08T20:36:55Z" +} +``` + +Example: +```bash +curl -X POST https://s.example.com/api/links \ + -H "Authorization: Bearer $GLIMMER_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"url":"https://example.com/docs","slug":"docs"}' +``` + ### 4. Build and run ```bash @@ -444,6 +495,7 @@ If proxying through Cloudflare, `X-Forwarded-For` is safe to trust for rate limi | `POST` | `/admin/uploads/delete/{filename}` | Admin | Delete an uploaded file (CSRF) | | `POST` | `/admin/uploads/resize/{filename}` | Admin | Resize a PNG/JPEG in-place (returns JSON) | | `POST` | `/mcp` | MCP auth | JSON-RPC MCP endpoint, when `[mcp].enabled = true` | +| `POST` | `/api/links` | API key | REST: create a short link (when `[mcp].enabled = true` and `api_key` is set) | | `GET` | `/static/*` | Public | CSS / static assets | --- diff --git a/internal/server/api.go b/internal/server/api.go new file mode 100644 index 0000000..1b8daad --- /dev/null +++ b/internal/server/api.go @@ -0,0 +1,168 @@ +package server + +import ( + "encoding/json" + "errors" + "net/http" + "strings" + + "glimmer/internal/db" + "glimmer/internal/slug" +) + +// apiKeyAuth checks the configured MCP API key via constant-time comparison. +// Reuses the same authentication scheme as POST /mcp so operators only need +// to provision one secret. The route is registered only when [mcp].enabled +// is true and an api_key is configured, but we still refuse empty keys as +// defence in depth. +func (s *Server) apiKeyAuth(r *http.Request) bool { + if s.cfg.MCP.APIKey == "" { + return false + } + if token := bearerToken(r.Header.Get("Authorization")); token != "" && constantTimeEqual(token, s.cfg.MCP.APIKey) { + return true + } + if token := r.Header.Get("X-API-Key"); token != "" && constantTimeEqual(token, s.cfg.MCP.APIKey) { + return true + } + return false +} + +func writeAPIError(w http.ResponseWriter, status int, message string) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + if status == http.StatusUnauthorized { + w.Header().Set("WWW-Authenticate", `Bearer realm="Glimmer API"`) + } + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(map[string]string{"error": message}) +} + +func writeAPIJSON(w http.ResponseWriter, status int, payload any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(payload) +} + +// apiCreateLinkRequest is the body of POST /api/links. +type apiCreateLinkRequest struct { + URL string `json:"url"` + Slug string `json:"slug,omitempty"` +} + +// apiLinkResponse is the REST view of a short link. Field names mirror the +// existing MCP payload (snake_case) so anyone already consuming mcpLink can +// reuse the same parsing code on the REST side. +type apiLinkResponse struct { + ID int64 `json:"id"` + Slug string `json:"slug"` + URL string `json:"url"` + ShortURL string `json:"short_url"` + CreatedBy string `json:"created_by"` + Clicks int64 `json:"clicks"` + CreatedAt string `json:"created_at,omitempty"` +} + +func (s *Server) toAPILink(link db.Link) apiLinkResponse { + return apiLinkResponse{ + ID: link.ID, + Slug: link.Slug, + URL: link.URL, + ShortURL: joinBaseURL(s.baseURLForAPI(), "/"+link.Slug), + CreatedBy: link.CreatedBy, + Clicks: link.Clicks, + CreatedAt: formatMCPTime(link.CreatedAt), + } +} + +// baseURLForAPI returns the base URL used when building short URLs in API +// responses. The configured BaseURL is preferred; the request Host is taken +// into account by the public web UI but for a JSON API the operator should +// set BaseURL to their public hostname (e.g. https://s.example.com) so the +// short URL is clickable from the start. +func (s *Server) baseURLForAPI() string { + if s.cfg.Server.BaseURL != "" { + return s.cfg.Server.BaseURL + } + return "http://localhost" +} + +// apiCreateLink is the REST equivalent of the MCP create_link tool. It +// accepts a JSON body, validates the URL, optionally honours a custom +// slug, deduplicates identical URLs, and returns the created link. +func (s *Server) apiCreateLink(w http.ResponseWriter, r *http.Request) { + if !s.apiKeyAuth(r) { + writeAPIError(w, http.StatusUnauthorized, "unauthorized") + return + } + + // JSON bodies are tiny; 4 KB is plenty and stops a misbehaving client + // from streaming a large body just to push us against rate limits. + r.Body = http.MaxBytesReader(w, r.Body, 4096) + defer r.Body.Close() + + var req apiCreateLinkRequest + dec := json.NewDecoder(r.Body) + dec.DisallowUnknownFields() + if err := dec.Decode(&req); err != nil { + writeAPIError(w, http.StatusBadRequest, "invalid JSON body: "+err.Error()) + return + } + + rawURL := strings.TrimSpace(req.URL) + if err := validateRedirectURL(&rawURL); err != nil { + writeAPIError(w, http.StatusBadRequest, err.Error()) + return + } + + finalSlug := strings.ToLower(strings.TrimSpace(req.Slug)) + if finalSlug != "" { + if err := validateAPISlug(finalSlug); err != nil { + writeAPIError(w, http.StatusBadRequest, err.Error()) + return + } + exists, err := s.db.SlugExists(finalSlug) + if err != nil { + writeAPIError(w, http.StatusInternalServerError, "database error") + return + } + if exists { + writeAPIError(w, http.StatusConflict, "slug already taken") + return + } + } else { + // Deduplicate identical URLs — matches the public web UI behaviour + // and keeps the link count down for API clients that retry. + if existing, err := s.db.GetByURL(rawURL); err == nil { + writeAPIJSON(w, http.StatusOK, s.toAPILink(*existing)) + return + } + + var err error + finalSlug, err = s.generateUniqueSlug() + if err != nil { + writeAPIError(w, http.StatusInternalServerError, err.Error()) + return + } + } + + link, err := s.db.Create(finalSlug, rawURL, "admin") + if err != nil { + writeAPIError(w, http.StatusInternalServerError, "failed to create link") + return + } + + writeAPIJSON(w, http.StatusCreated, s.toAPILink(*link)) +} + +// validateAPISlug enforces the same character rules the admin web UI uses: +// letters, digits, hyphens, and underscores, 1–64 characters. Centralised +// so future rule changes only need one edit. +func validateAPISlug(value string) error { + if value == "" { + return errors.New("slug is required") + } + if len(value) > 64 { + return errors.New("slug is too long (max 64 characters)") + } + return slug.Validate(value) +} diff --git a/internal/server/api_test.go b/internal/server/api_test.go new file mode 100644 index 0000000..8a32e7c --- /dev/null +++ b/internal/server/api_test.go @@ -0,0 +1,319 @@ +package server + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + + "glimmer/internal/config" + "glimmer/internal/db" +) + +func TestAPICreateLinkRequiresAuth(t *testing.T) { + srv := newTestServer(&config.Config{ + Server: config.ServerConfig{BaseURL: "http://localhost:8888"}, + MCP: config.MCPConfig{Enabled: true, APIKey: "secret"}, + }) + + req := httptest.NewRequest(http.MethodPost, "/api/links", + strings.NewReader(`{"url":"https://example.com"}`)) + rec := httptest.NewRecorder() + + srv.apiCreateLink(rec, req) + + if rec.Code != http.StatusUnauthorized { + t.Fatalf("expected 401, got %d", rec.Code) + } + if !strings.Contains(rec.Header().Get("WWW-Authenticate"), "Bearer") { + t.Fatalf("expected WWW-Authenticate header, got %q", rec.Header().Get("WWW-Authenticate")) + } +} + +func TestAPICreateLinkRejectsBadKey(t *testing.T) { + srv := newTestServer(&config.Config{ + Server: config.ServerConfig{BaseURL: "http://localhost:8888"}, + MCP: config.MCPConfig{Enabled: true, APIKey: "secret"}, + }) + + req := httptest.NewRequest(http.MethodPost, "/api/links", + strings.NewReader(`{"url":"https://example.com"}`)) + req.Header.Set("Authorization", "Bearer wrong") + rec := httptest.NewRecorder() + + srv.apiCreateLink(rec, req) + + if rec.Code != http.StatusUnauthorized { + t.Fatalf("expected 401, got %d", rec.Code) + } +} + +func TestAPICreateLinkRejectsEmptyKeyConfig(t *testing.T) { + // Even if the route somehow got registered with no key configured, + // apiKeyAuth must refuse. This is the defence-in-depth check. + srv := newTestServer(&config.Config{ + Server: config.ServerConfig{BaseURL: "http://localhost:8888"}, + MCP: config.MCPConfig{Enabled: true, APIKey: ""}, + }) + + req := httptest.NewRequest(http.MethodPost, "/api/links", + strings.NewReader(`{"url":"https://example.com"}`)) + req.Header.Set("Authorization", "Bearer anything") + rec := httptest.NewRecorder() + + srv.apiCreateLink(rec, req) + + if rec.Code != http.StatusUnauthorized { + t.Fatalf("expected 401 when no key is configured, got %d", rec.Code) + } +} + +func TestAPICreateLinkWithBearerKey(t *testing.T) { + srv := apiTestServer(t, "secret") + + body := strings.NewReader(`{"url":"https://example.com/page"}`) + req := httptest.NewRequest(http.MethodPost, "/api/links", body) + req.Header.Set("Authorization", "Bearer secret") + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + + srv.apiCreateLink(rec, req) + + if rec.Code != http.StatusCreated { + t.Fatalf("expected 201, got %d body=%s", rec.Code, rec.Body.String()) + } + + var resp apiLinkResponse + if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil { + t.Fatalf("decode response: %v", err) + } + if resp.URL != "https://example.com/page" { + t.Fatalf("unexpected URL: %q", resp.URL) + } + if resp.ShortURL != "http://localhost:8888/"+resp.Slug { + t.Fatalf("unexpected short_url: %q", resp.ShortURL) + } + if resp.Slug == "" { + t.Fatalf("expected auto-generated slug, got empty") + } + if resp.CreatedBy != "admin" { + t.Fatalf("expected created_by=admin, got %q", resp.CreatedBy) + } +} + +func TestAPICreateLinkWithXAPIKeyHeader(t *testing.T) { + srv := apiTestServer(t, "secret") + + req := httptest.NewRequest(http.MethodPost, "/api/links", + strings.NewReader(`{"url":"https://example.com"}`)) + req.Header.Set("X-API-Key", "secret") + rec := httptest.NewRecorder() + + srv.apiCreateLink(rec, req) + + if rec.Code != http.StatusCreated { + t.Fatalf("expected 201, got %d", rec.Code) + } +} + +func TestAPICreateLinkWithCustomSlug(t *testing.T) { + srv := apiTestServer(t, "secret") + + req := httptest.NewRequest(http.MethodPost, "/api/links", + strings.NewReader(`{"url":"https://example.com","slug":"docs"}`)) + req.Header.Set("Authorization", "Bearer secret") + rec := httptest.NewRecorder() + + srv.apiCreateLink(rec, req) + + if rec.Code != http.StatusCreated { + t.Fatalf("expected 201, got %d body=%s", rec.Code, rec.Body.String()) + } + var resp apiLinkResponse + _ = json.NewDecoder(rec.Body).Decode(&resp) + if resp.Slug != "docs" { + t.Fatalf("expected slug=docs, got %q", resp.Slug) + } +} + +func TestAPICreateLinkRejectsBadURL(t *testing.T) { + srv := apiTestServer(t, "secret") + + cases := []string{ + `{"url":""}`, + `{"url":"not a url at all with spaces"}`, + `{"url":"javascript:alert(1)"}`, + `{"url":"ftp://example.com"}`, + `{"url":"//missing-scheme"}`, + } + for _, body := range cases { + t.Run(body, func(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, "/api/links", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer secret") + rec := httptest.NewRecorder() + srv.apiCreateLink(rec, req) + if rec.Code != http.StatusBadRequest { + t.Fatalf("expected 400 for %s, got %d", body, rec.Code) + } + }) + } +} + +func TestAPICreateLinkAutoSchemesBareDomain(t *testing.T) { + srv := apiTestServer(t, "secret") + + req := httptest.NewRequest(http.MethodPost, "/api/links", + strings.NewReader(`{"url":"example.com/foo"}`)) + req.Header.Set("Authorization", "Bearer secret") + rec := httptest.NewRecorder() + srv.apiCreateLink(rec, req) + + if rec.Code != http.StatusCreated { + t.Fatalf("expected 201, got %d body=%s", rec.Code, rec.Body.String()) + } + var resp apiLinkResponse + _ = json.NewDecoder(rec.Body).Decode(&resp) + if resp.URL != "https://example.com/foo" { + t.Fatalf("expected auto-scheme upgrade, got %q", resp.URL) + } +} + +func TestAPICreateLinkRejectsBadSlug(t *testing.T) { + srv := apiTestServer(t, "secret") + + cases := []string{ + `{"url":"https://example.com","slug":"with space"}`, + `{"url":"https://example.com","slug":"with/slash"}`, + } + for _, body := range cases { + t.Run(body, func(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, "/api/links", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer secret") + rec := httptest.NewRecorder() + srv.apiCreateLink(rec, req) + if rec.Code != http.StatusBadRequest { + t.Fatalf("expected 400 for %s, got %d", body, rec.Code) + } + }) + } +} + +func TestAPICreateLinkRejectsDuplicateSlug(t *testing.T) { + srv := apiTestServer(t, "secret") + + first := httptest.NewRequest(http.MethodPost, "/api/links", + strings.NewReader(`{"url":"https://example.com/a","slug":"docs"}`)) + first.Header.Set("Authorization", "Bearer secret") + rec1 := httptest.NewRecorder() + srv.apiCreateLink(rec1, first) + if rec1.Code != http.StatusCreated { + t.Fatalf("first create: expected 201, got %d", rec1.Code) + } + + second := httptest.NewRequest(http.MethodPost, "/api/links", + strings.NewReader(`{"url":"https://example.com/b","slug":"docs"}`)) + second.Header.Set("Authorization", "Bearer secret") + rec2 := httptest.NewRecorder() + srv.apiCreateLink(rec2, second) + if rec2.Code != http.StatusConflict { + t.Fatalf("duplicate slug: expected 409, got %d body=%s", rec2.Code, rec2.Body.String()) + } +} + +func TestAPICreateLinkDeduplicatesURL(t *testing.T) { + srv := apiTestServer(t, "secret") + + body := `{"url":"https://example.com/dedupe"}` + + // First call: 201 Created with a fresh slug. + req1 := httptest.NewRequest(http.MethodPost, "/api/links", strings.NewReader(body)) + req1.Header.Set("Authorization", "Bearer secret") + rec1 := httptest.NewRecorder() + srv.apiCreateLink(rec1, req1) + if rec1.Code != http.StatusCreated { + t.Fatalf("first call: expected 201, got %d body=%s", rec1.Code, rec1.Body.String()) + } + var first apiLinkResponse + _ = json.NewDecoder(rec1.Body).Decode(&first) + + // Second call: same URL, 200 OK with the existing link (idempotent). + req2 := httptest.NewRequest(http.MethodPost, "/api/links", strings.NewReader(body)) + req2.Header.Set("Authorization", "Bearer secret") + rec2 := httptest.NewRecorder() + srv.apiCreateLink(rec2, req2) + if rec2.Code != http.StatusOK { + t.Fatalf("second call: expected 200, got %d body=%s", rec2.Code, rec2.Body.String()) + } + var second apiLinkResponse + _ = json.NewDecoder(rec2.Body).Decode(&second) + + if first.ID != second.ID || first.Slug != second.Slug { + t.Fatalf("dedupe mismatch: first=%+v second=%+v", first, second) + } + + // And exactly one row was inserted. + links, err := srv.db.List() + if err != nil { + t.Fatalf("list: %v", err) + } + count := 0 + for _, l := range links { + if l.URL == "https://example.com/dedupe" { + count++ + } + } + if count != 1 { + t.Fatalf("expected exactly 1 link for the URL, got %d", count) + } +} + +func TestAPICreateLinkRejectsMalformedJSON(t *testing.T) { + srv := apiTestServer(t, "secret") + + req := httptest.NewRequest(http.MethodPost, "/api/links", + strings.NewReader(`{"url": this is not json}`)) + req.Header.Set("Authorization", "Bearer secret") + rec := httptest.NewRecorder() + srv.apiCreateLink(rec, req) + if rec.Code != http.StatusBadRequest { + t.Fatalf("expected 400, got %d", rec.Code) + } +} + +func TestAPICreateLinkRejectsUnknownFields(t *testing.T) { + srv := apiTestServer(t, "secret") + + req := httptest.NewRequest(http.MethodPost, "/api/links", + strings.NewReader(`{"url":"https://example.com","unexpected":"field"}`)) + req.Header.Set("Authorization", "Bearer secret") + rec := httptest.NewRecorder() + srv.apiCreateLink(rec, req) + if rec.Code != http.StatusBadRequest { + t.Fatalf("expected 400 for unknown field, got %d", rec.Code) + } +} + +// apiTestServer builds a Server wired up with a real on-disk SQLite DB so +// the full happy-path can be exercised. Reuses newTestServer for the auth +// fields; only adds a db handle. +func apiTestServer(t *testing.T, apiKey string) *Server { + t.Helper() + database, err := db.Open(filepath.Join(t.TempDir(), "urls.db")) + if err != nil { + t.Fatalf("open db: %v", err) + } + t.Cleanup(func() { _ = database.Close() }) + + return &Server{ + cfg: &config.Config{ + Server: config.ServerConfig{BaseURL: "http://localhost:8888"}, + MCP: config.MCPConfig{Enabled: true, APIKey: apiKey}, + Slugs: config.SlugConfig{Length: 3}, + }, + db: database, + authLimiter: newRateLimiter(0), + bcryptSem: make(chan struct{}, 1), + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 65b9a0a..0c15949 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -135,6 +135,14 @@ func (s *Server) Start() error { if s.cfg.MCP.Enabled { mux.HandleFunc("POST /mcp", s.handleMCP) + // REST surface for programmatic short-link creation. Shares the + // same API key as /mcp. Only registered when the API key is set so + // a misconfigured server never exposes the endpoint unauthenticated. + // The route is intentionally not documented in any public-facing + // template; visitors who don't know it exists get a 404. + if s.cfg.MCP.APIKey != "" { + mux.HandleFunc("POST /api/links", s.apiCreateLink) + } } // Pastebin public routes (before catch-all)