Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(server): remove generic LLM passthrough endpoints (MUL-4309) (#5154)
Multica Eve619b1b78e7c9
diff --git a/.env.example b/.env.exampleindex 45525016ed..50bcd9f3e5 100644--- a/.env.example+++ b/.env.example@@ -60,11 +60,10 @@ MULTICA_PUBLIC_URL=# e.g. "127.0.0.1/32" for a same-host reverse proxy, or the CDN's# announced ranges for cloud deployments.MULTICA_TRUSTED_PROXIES=-# Basic LLM API layer (MUL-4238). Backs the OpenAI-compatible chat-# completions endpoints (POST /api/llm/v1/chat/completions and-# .../stream) and internal one-shot LLM helpers. Both endpoints require a-# logged-in user. When both API key and base URL are empty the layer is-# disabled and the endpoints return 503.+# Basic LLM API layer (MUL-4238). Backs server-internal LLM helpers such as+# chat title generation (the generic OpenAI-compatible passthrough endpoints+# were removed in MUL-4309 — LLM access is internal-only). When both API key+# and base URL are empty the layer is disabled and callers fall back silently.# - API key for the upstream (OpenAI or any OpenAI-compatible gateway).MULTICA_LLM_API_KEY=# - Base URL of the upstream. Leave unset to use OpenAI's defaultdiff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex a7f5f19357..066bd2f010 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -780,14 +780,13 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/api/upload-file", h.UploadFile)r.Post("/api/feedback", h.CreateFeedback)- // OpenAI-compatible LLM endpoints (MUL-4238). User-scoped (auth-only,- // no workspace context needed): the basic LLM layer is a shared- // utility, not a per-workspace resource. Both accept the standard- // OpenAI chat-completions request body; model is taken from the request- // with a configured default fallback. Return 503 when the LLM layer is- // unconfigured (no MULTICA_LLM_API_KEY / MULTICA_LLM_BASE_URL).- r.Post("/api/llm/v1/chat/completions", h.LLMChatCompletions)- r.Post("/api/llm/v1/chat/completions/stream", h.LLMChatCompletionsStream)+ // Note (MUL-4309): the generic OpenAI-compatible passthrough endpoints+ // (POST /api/llm/v1/chat/completions[/stream]) were intentionally+ // removed. Exposing a general LLM proxy backed by the deployment's own+ // key let any logged-in user run arbitrary completions on our dime.+ // LLM access is now server-internal only (see pkg/llm); anything the+ // web/client needs must go through a purpose-built business endpoint+ // that fixes the prompt/model server-side (e.g. chat title generation).// Attachment download — user-scoped (auth-only), NOT// workspace-scoped. The handler self-resolves the workspacediff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex b3c828c48c..a387df997c 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -96,9 +96,11 @@ type Config struct {// can frame API-hosted PDFs without allowing arbitrary third-party frames.AttachmentFrameAncestors []string// LLM* configure the basic LLM API layer (MUL-4238). They back the- // OpenAI-compatible chat-completions endpoints and any internal one-shot- // LLM helpers. When both LLMAPIKey and LLMBaseURL are empty the layer is- // disabled and the endpoints return 503.+ // server-internal LLM helpers in pkg/llm (e.g. chat title generation).+ // The generic OpenAI-compatible passthrough endpoints were removed in+ // MUL-4309; LLM access is internal-only now. When both LLMAPIKey and+ // LLMBaseURL are empty the layer is disabled and callers fall back+ // silently (see maybeGenerateChatTitleAsync).// - LLMAPIKey -> MULTICA_LLM_API_KEY// - LLMBaseURL -> MULTICA_LLM_BASE_URL (OpenAI or any compatible gateway)// - LLMDefaultModel -> MULTICA_LLM_DEFAULT_MODEL (used when a request omits `model`)@@ -208,10 +210,11 @@ type Handler struct {// integration". A future platform satisfies the same reader interface.SlackHistory ChatChannelHistoryReader// LLM is the basic LLM API layer (MUL-4238): a thin wrapper over the- // OpenAI Go SDK backing the OpenAI-compatible chat-completions endpoints- // and any internal one-shot LLM helpers. Always non-nil (New builds it- // from Config); when unconfigured its Enabled() reports false and the- // handlers return 503.+ // OpenAI Go SDK backing server-internal one-shot LLM helpers such as chat+ // title generation. The generic passthrough endpoints were removed in+ // MUL-4309, so it is internal-only now. Always non-nil (New builds it from+ // Config); when unconfigured its Enabled() reports false and callers fall+ // back silently.LLM *llm.Clientcfg Config}diff --git a/server/internal/handler/llm.go b/server/internal/handler/llm.godeleted file mode 100644index 12d9bdce92..0000000000--- a/server/internal/handler/llm.go+++ /dev/null@@ -1,210 +0,0 @@-package handler--import (- "errors"- "io"- "log/slog"- "net/http"-- openai "github.com/openai/openai-go/v3"-- "github.com/multica-ai/multica/server/internal/logger"- "github.com/multica-ai/multica/server/pkg/llm"-)--// llmRequestBodyLimit caps the request body for the chat-completions endpoints.-// 1 MiB comfortably fits large multi-message conversations (including small-// inline image data URLs) while preventing an authenticated client from-// streaming unbounded bytes into the JSON decoder.-const llmRequestBodyLimit = 1 << 20 // 1 MiB--// decodeLLMChatParams reads and validates the OpenAI chat-completions request-// body. It decodes directly into the SDK's ChatCompletionNewParams (which-// implements UnmarshalJSON with full OpenAI fidelity) so every supported field-// — messages, tools, response_format, temperature, etc. — passes through-// untouched. On any failure it writes the appropriate 4xx and returns ok=false.-func decodeLLMChatParams(w http.ResponseWriter, r *http.Request) (openai.ChatCompletionNewParams, bool) {- var params openai.ChatCompletionNewParams-- r.Body = http.MaxBytesReader(w, r.Body, llmRequestBodyLimit)- body, err := io.ReadAll(r.Body)- if err != nil {- // MaxBytesReader surfaces an oversize body as an error here.- writeError(w, http.StatusRequestEntityTooLarge, "request body too large")- return params, false- }- if len(body) == 0 {- writeError(w, http.StatusBadRequest, "request body is required")- return params, false- }- if err := params.UnmarshalJSON(body); err != nil {- writeError(w, http.StatusBadRequest, "invalid request body")- return params, false- }- if len(params.Messages) == 0 {- writeError(w, http.StatusBadRequest, "messages is required")- return params, false- }- return params, true-}--// writeUpstreamError maps an error from the LLM layer to an HTTP response.-// Upstream OpenAI errors carry their own status code, which we preserve so the-// caller sees e.g. a 401 (bad key) or 429 (rate limited) rather than a blanket-// 500. A missing configuration is a 503; anything else is a 502 (bad gateway).-func writeUpstreamError(w http.ResponseWriter, r *http.Request, err error) {- if errors.Is(err, llm.ErrNotConfigured) {- writeError(w, http.StatusServiceUnavailable, "LLM API is not configured")- return- }-- var apiErr *openai.Error- if errors.As(err, &apiErr) && apiErr.StatusCode >= 400 {- slog.Warn("llm upstream error",- append(logger.RequestAttrs(r), "status", apiErr.StatusCode, "error", err)...)- // Preserve the upstream OpenAI-shaped error body so OpenAI clients can- // parse it as they would a direct call. Fall back to a plain message if- // the SDK gave us no body.- if raw := apiErr.RawJSON(); raw != "" {- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(apiErr.StatusCode)- _, _ = io.WriteString(w, raw)- return- }- writeError(w, apiErr.StatusCode, "upstream error")- return- }-- slog.Warn("llm request failed", append(logger.RequestAttrs(r), "error", err)...)- writeError(w, http.StatusBadGateway, "failed to reach LLM upstream")-}--// LLMChatCompletions is an OpenAI-compatible, non-streaming chat-completions-// endpoint (POST /api/llm/v1/chat/completions). It accepts the standard OpenAI-// request body and returns the byte-exact upstream ChatCompletion object.-//-// Auth: user-scoped (the route sits inside the authenticated group). Model is-// taken from the request; when omitted, the configured default is used.-func (h *Handler) LLMChatCompletions(w http.ResponseWriter, r *http.Request) {- if _, ok := requireUserID(w, r); !ok {- return- }- if h.LLM == nil || !h.LLM.Enabled() {- writeError(w, http.StatusServiceUnavailable, "LLM API is not configured")- return- }-- params, ok := decodeLLMChatParams(w, r)- if !ok {- return- }-- completion, err := h.LLM.Chat(r.Context(), params)- if err != nil {- writeUpstreamError(w, r, err)- return- }-- // Relay the upstream response verbatim to preserve full OpenAI-format- // compatibility (fields the SDK struct doesn't model are still present in- // RawJSON). Fall back to marshaling the typed object if RawJSON is empty.- if raw := completion.RawJSON(); raw != "" {- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(http.StatusOK)- _, _ = io.WriteString(w, raw)- return- }- writeJSON(w, http.StatusOK, completion)-}--// LLMChatCompletionsStream is an OpenAI-compatible streaming chat-completions-// endpoint (POST /api/llm/v1/chat/completions/stream). It emits server-sent-// events whose `data:` payloads are the byte-exact upstream-// chat.completion.chunk objects, terminated by the OpenAI `data: [DONE]`-// sentinel — identical to calling OpenAI with stream=true.-//-// Auth: user-scoped (the route sits inside the authenticated group). Model is-// taken from the request; when omitted, the configured default is used.-func (h *Handler) LLMChatCompletionsStream(w http.ResponseWriter, r *http.Request) {- if _, ok := requireUserID(w, r); !ok {- return- }- if h.LLM == nil || !h.LLM.Enabled() {- writeError(w, http.StatusServiceUnavailable, "LLM API is not configured")- return- }-- params, ok := decodeLLMChatParams(w, r)- if !ok {- return- }-- stream, err := h.LLM.ChatStream(r.Context(), params)- if err != nil {- writeUpstreamError(w, r, err)- return- }- defer stream.Close()-- // SSE headers. Disable proxy buffering so chunks flush promptly through- // nginx-style reverse proxies.- w.Header().Set("Content-Type", "text/event-stream")- w.Header().Set("Cache-Control", "no-cache")- w.Header().Set("Connection", "keep-alive")- w.Header().Set("X-Accel-Buffering", "no")-- rc := http.NewResponseController(w)-- // Peek the first chunk before committing a 200 so a fast upstream failure- // (bad key, unknown model) can still be reported as a JSON error with the- // correct status instead of a half-open 200 stream.- if !stream.Next() {- if err := stream.Err(); err != nil {- writeUpstreamError(w, r, err)- return- }- // No content at all: emit a well-formed, empty SSE stream.- w.WriteHeader(http.StatusOK)- writeSSEData(w, rc, "[DONE]")- return- }-- w.WriteHeader(http.StatusOK)-- // First chunk (already fetched), then the rest.- if chunk := stream.Current(); chunk.RawJSON() != "" {- if !writeSSEData(w, rc, chunk.RawJSON()) {- return- }- }- for stream.Next() {- chunk := stream.Current()- if chunk.RawJSON() == "" {- continue- }- if !writeSSEData(w, rc, chunk.RawJSON()) {- return- }- }- if err := stream.Err(); err != nil {- // The connection is already a 200 SSE stream; we cannot change the- // status. Emit an OpenAI-style error event so the client can detect the- // mid-stream failure, then stop.- slog.Warn("llm stream error mid-flight", append(logger.RequestAttrs(r), "error", err)...)- writeSSEData(w, rc, `{"error":{"message":"upstream stream error","type":"upstream_error"}}`)- return- }-- writeSSEData(w, rc, "[DONE]")-}--// writeSSEData writes a single SSE `data:` event and flushes it. It returns-// false if the write failed (client disconnected), signaling the caller to-// stop. Flush errors are non-fatal (some ResponseWriters don't support it).-func writeSSEData(w http.ResponseWriter, rc *http.ResponseController, payload string) bool {- if _, err := io.WriteString(w, "data: "+payload+"\n\n"); err != nil {- return false- }- _ = rc.Flush()- return true-}diff --git a/server/internal/handler/llm_test.go b/server/internal/handler/llm_test.godeleted file mode 100644index 17f8db4a0f..0000000000--- a/server/internal/handler/llm_test.go+++ /dev/null@@ -1,150 +0,0 @@-package handler--import (- "io"- "net/http"- "net/http/httptest"- "strings"- "testing"-- "github.com/multica-ai/multica/server/pkg/llm"-)--// newLLMUpstream returns a stub OpenAI upstream and a Handler wired to it.-func newLLMUpstream(t *testing.T, upstream http.HandlerFunc) *Handler {- t.Helper()- srv := httptest.NewServer(upstream)- t.Cleanup(srv.Close)- return &Handler{- LLM: llm.New(llm.Config{APIKey: "test-key", BaseURL: srv.URL, DefaultModel: "test-model"}),- }-}--func postLLM(t *testing.T, h http.HandlerFunc, body, userID string) *httptest.ResponseRecorder {- t.Helper()- req := httptest.NewRequest(http.MethodPost, "/api/llm/v1/chat/completions", strings.NewReader(body))- if userID != "" {- req.Header.Set("X-User-ID", userID)- }- rec := httptest.NewRecorder()- h(rec, req)- return rec-}--func TestLLMChatCompletions_Unauthenticated(t *testing.T) {- h := &Handler{LLM: llm.New(llm.Config{APIKey: "k"})}- rec := postLLM(t, h.LLMChatCompletions, `{"messages":[{"role":"user","content":"hi"}]}`, "")- if rec.Code != http.StatusUnauthorized {- t.Fatalf("expected 401, got %d", rec.Code)- }-}--func TestLLMChatCompletions_NotConfigured(t *testing.T) {- h := &Handler{LLM: llm.New(llm.Config{})} // disabled- rec := postLLM(t, h.LLMChatCompletions, `{"messages":[{"role":"user","content":"hi"}]}`, "user-1")- if rec.Code != http.StatusServiceUnavailable {- t.Fatalf("expected 503, got %d", rec.Code)- }-}--func TestLLMChatCompletions_BadBody(t *testing.T) {- h := &Handler{LLM: llm.New(llm.Config{APIKey: "k"})}- rec := postLLM(t, h.LLMChatCompletions, `not json`, "user-1")- if rec.Code != http.StatusBadRequest {- t.Fatalf("expected 400 for malformed body, got %d", rec.Code)- }-}--func TestLLMChatCompletions_MissingMessages(t *testing.T) {- h := &Handler{LLM: llm.New(llm.Config{APIKey: "k"})}- rec := postLLM(t, h.LLMChatCompletions, `{"model":"x"}`, "user-1")- if rec.Code != http.StatusBadRequest {- t.Fatalf("expected 400 for missing messages, got %d", rec.Code)- }-}--func TestLLMChatCompletions_Success(t *testing.T) {- h := newLLMUpstream(t, func(w http.ResponseWriter, r *http.Request) {- if got := r.Header.Get("Authorization"); got != "Bearer test-key" {- t.Errorf("expected upstream auth header, got %q", got)- }- w.Header().Set("Content-Type", "application/json")- _, _ = io.WriteString(w, `{"id":"cmpl-42","object":"chat.completion","model":"test-model","choices":[{"index":0,"message":{"role":"assistant","content":"pong"},"finish_reason":"stop"}]}`)- })-- rec := postLLM(t, h.LLMChatCompletions, `{"messages":[{"role":"user","content":"ping"}]}`, "user-1")- if rec.Code != http.StatusOK {- t.Fatalf("expected 200, got %d (body=%s)", rec.Code, rec.Body.String())- }- if ct := rec.Header().Get("Content-Type"); ct != "application/json" {- t.Fatalf("expected application/json, got %q", ct)- }- if !strings.Contains(rec.Body.String(), `"cmpl-42"`) || !strings.Contains(rec.Body.String(), `"pong"`) {- t.Fatalf("expected upstream body relayed verbatim, got %s", rec.Body.String())- }-}--func TestLLMChatCompletions_UpstreamErrorStatusPreserved(t *testing.T) {- h := newLLMUpstream(t, func(w http.ResponseWriter, r *http.Request) {- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(http.StatusUnauthorized)- _, _ = io.WriteString(w, `{"error":{"message":"bad key","type":"invalid_request_error"}}`)- })-- rec := postLLM(t, h.LLMChatCompletions, `{"messages":[{"role":"user","content":"ping"}]}`, "user-1")- if rec.Code != http.StatusUnauthorized {- t.Fatalf("expected upstream 401 preserved, got %d (body=%s)", rec.Code, rec.Body.String())- }- if !strings.Contains(rec.Body.String(), "bad key") {- t.Fatalf("expected upstream error body relayed, got %s", rec.Body.String())- }-}--func TestLLMChatCompletionsStream_Success(t *testing.T) {- h := newLLMUpstream(t, func(w http.ResponseWriter, r *http.Request) {- w.Header().Set("Content-Type", "text/event-stream")- flusher, _ := w.(http.Flusher)- for _, ch := range []string{- `{"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Hel"}}]}`,- `{"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"lo"}}]}`,- } {- _, _ = io.WriteString(w, "data: "+ch+"\n\n")- if flusher != nil {- flusher.Flush()- }- }- _, _ = io.WriteString(w, "data: [DONE]\n\n")- })-- req := httptest.NewRequest(http.MethodPost, "/api/llm/v1/chat/completions/stream",- strings.NewReader(`{"messages":[{"role":"user","content":"hi"}]}`))- req.Header.Set("X-User-ID", "user-1")- rec := httptest.NewRecorder()- h.LLMChatCompletionsStream(rec, req)-- if rec.Code != http.StatusOK {- t.Fatalf("expected 200, got %d", rec.Code)- }- if ct := rec.Header().Get("Content-Type"); ct != "text/event-stream" {- t.Fatalf("expected text/event-stream, got %q", ct)- }- out := rec.Body.String()- if !strings.Contains(out, `"Hel"`) || !strings.Contains(out, `"lo"`) {- t.Fatalf("expected relayed chunks, got %s", out)- }- if !strings.Contains(out, "data: [DONE]") {- t.Fatalf("expected terminating [DONE] sentinel, got %s", out)- }-}--func TestLLMChatCompletionsStream_NotConfigured(t *testing.T) {- h := &Handler{LLM: llm.New(llm.Config{})}- req := httptest.NewRequest(http.MethodPost, "/api/llm/v1/chat/completions/stream",- strings.NewReader(`{"messages":[{"role":"user","content":"hi"}]}`))- req.Header.Set("X-User-ID", "user-1")- rec := httptest.NewRecorder()- h.LLMChatCompletionsStream(rec, req)- if rec.Code != http.StatusServiceUnavailable {- t.Fatalf("expected 503, got %d", rec.Code)- }-}diff --git a/server/pkg/llm/client.go b/server/pkg/llm/client.goindex 668849d423..7ab2c8689c 100644--- a/server/pkg/llm/client.go+++ b/server/pkg/llm/client.go@@ -8,9 +8,9 @@//// - It owns the SDK client construction (base URL + API key + retry/timeout// defaults) so callers never touch option.RequestOption directly.-// - It exposes both the raw Chat Completions surface (Chat / ChatStream),-// used by the OpenAI-compatible HTTP proxy handlers, and a convenience-// GenerateText helper for simple internal one-shot completions.+// - It exposes both the raw Chat Completions surface (Chat / ChatStream)+// and a convenience GenerateText helper, used by server-internal callers+// for simple one-shot completions (e.g. chat title generation).// - The default model is configurable; when a request omits the model we// fall back to it, and when it too is empty we fall back to a sane// built-in default so a misconfigured deployment still returns a clear@@ -44,9 +44,10 @@ const FallbackModel = "gpt-4o-mini"const defaultRequestTimeout = 60 * time.Second// ErrNotConfigured is returned by Chat/ChatStream/GenerateText when the client-// was constructed without any credentials or base URL. Callers (e.g. the HTTP-// handlers) should translate this into a 503 so a misconfigured self-hosted-// deployment surfaces a clear error instead of dialing OpenAI with no key.+// was constructed without any credentials or base URL. Internal callers should+// treat this as a disabled-LLM signal and fall back gracefully (e.g. chat+// title generation keeps the original title) so a misconfigured self-hosted+// deployment never dials OpenAI with no key.var ErrNotConfigured = errors.New("llm: no API key or base URL configured")// Config holds the tunables for the LLM layer. All fields are optional; an