diff --git a/README.md b/README.md index 3b40c83..e492e31 100644 --- a/README.md +++ b/README.md @@ -493,7 +493,7 @@ runtime supports it. **LLM**: `export ANTHROPIC_API_KEY=sk-...` (or `OPENAI_API_KEY`), or configure it in the UI's "LLM Configuration" page, which can also add a local Ollama server as a keyless provider (format "Ollama", default base URL `http://127.0.0.1:11434/v1`). Optional: -`ARTEX_LLM_PROVIDER` (`anthropic | openai | openai-responses | ollama`), `ARTEX_LLM_MODEL`, +`ARTEX_LLM_PROVIDER` (`anthropic | openai | openai-responses | ollama | bedrock-gateway`), `ARTEX_LLM_MODEL`, `ARTEX_LLM_BASE_URL`, `ARTEX_LLM_PROXY`. **Base URL gotcha**: for the Anthropic format, enter the host **without** `/v1` (for example @@ -509,6 +509,24 @@ catalog (`GET /v1/models`) and pick a model; models the provider adds later appe next refresh. For example, [NotHoly](https://notholy.com) (offensive-security models) uses base URL `https://api.notholy.com/v1` with an API key from its console. +**Bedrock gateway**: select **Bedrock gateway** in System → LLM for a gateway that +exposes the Bedrock `InvokeModel` and `InvokeModelWithResponseStream` paths and accepts +bearer-token authentication. Enter the gateway's base URL (for example, +`https://gateway.example.com/bedrock`), the full Bedrock model ID, and the token +in **Bearer token**. If required, enter static headers as one `Name: Value` per line +in **Custom gateway headers**. ARTEX adds `/model/{model}/invoke` (or +`/invoke-with-response-stream`), sends `anthropic_version: bedrock-2023-05-31`, +and decodes Bedrock's binary event stream. Enter the model ID manually; this +gateway format does not have a model-list operation. The token and custom header +values are encrypted in the database and are write-only in the UI. Editing the +gateway URL requires re-entering the token, so saved credentials cannot be sent +to a different host by changing the URL. This format is for bearer-authenticated +gateways; direct AWS Bedrock with SigV4 credentials is not supported. + +For environment-based setup, set `ARTEX_LLM_PROVIDER=bedrock-gateway`, +`ARTEX_LLM_BASE_URL`, `ARTEX_LLM_MODEL`, and `ARTEX_LLM_API_KEY`. Optional +`ARTEX_LLM_CUSTOM_HEADERS` uses the same newline-separated `Name: Value` format. + **Task archive storage**: local disk by default. Set `ARTEX_ARCHIVE_STORAGE=s3` to store cold task packages in an S3-compatible bucket and release their local package space after verification. Existing local archives remain usable. See @@ -743,7 +761,7 @@ gunzip -c backups/artex-db-.sql.gz | docker compose exec -T postgres psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" ``` -Stored secrets (LLM API keys and proxies, MCP env, task credentials, notification channel config, +Stored secrets (LLM API keys, proxies and gateway custom headers, MCP env, task credentials, notification channel config, Brave/Tavily search keys, web search and global proxies, the execution spec of custom tools, the capture-proxy rewrite rules) are encrypted in the database with the key in `keys/secret.key` (generated at first start, mode 0600, @@ -930,7 +948,7 @@ Please report vulnerabilities privately through GitHub Security Advisories; see Operational security properties: -- **Secrets at rest**: LLM keys/proxies, MCP environment, task credentials, notification config, +- **Secrets at rest**: LLM keys/proxies/gateway headers, MCP environment, task credentials, notification config, search keys, proxies, custom-tool execution specs, capture-proxy rewrite rules and traffic evidence snapshots are encrypted with AES-256-GCM using `keys/secret.key` (or `ARTEX_SECRET_KEY`). ARTEX refuses to start when diff --git a/agent/bedrock_gateway.go b/agent/bedrock_gateway.go new file mode 100644 index 0000000..c45af0e --- /dev/null +++ b/agent/bedrock_gateway.go @@ -0,0 +1,268 @@ +package agent + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/textproto" + "net/url" + "strings" + + "github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream" +) + +// BedrockGatewayHeaders are newline-separated HTTP headers, stored encrypted with +// the profile. The bearer token is held separately in the existing API key field. +func ParseBedrockGatewayHeaders(raw string) (http.Header, error) { + h := make(http.Header) + if len(raw) > 8192 { + return nil, errors.New("custom headers exceed 8 KiB") + } + for _, line := range strings.Split(raw, "\n") { + line = strings.TrimSuffix(line, "\r") + if strings.TrimSpace(line) == "" { + continue + } + if len(h) >= 20 { + return nil, errors.New("too many custom headers") + } + name, value, ok := strings.Cut(line, ":") + name = strings.TrimSpace(name) + value = strings.TrimSpace(value) + if !ok || !validHeaderName(name) || !validHeaderValue(value) { + return nil, errors.New("invalid custom header") + } + switch strings.ToLower(name) { + case "authorization", "proxy-authorization", "host", "x-api-key", "content-type", "accept", "content-length", "transfer-encoding", "connection", "proxy-connection", "keep-alive", "te", "trailer", "upgrade", "cookie", "anthropic-version", "x-amzn-bedrock-accept", "x-amzn-bedrock-content-type": + return nil, fmt.Errorf("custom header %q is reserved", name) + } + name = textproto.CanonicalMIMEHeaderKey(name) + if _, exists := h[name]; exists { + return nil, fmt.Errorf("duplicate custom header %q", name) + } + h.Set(name, value) + } + return h, nil +} + +func validHeaderName(s string) bool { + if s == "" { + return false + } + for _, c := range []byte(s) { + if !(c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || strings.ContainsRune("!#$%&'*+-.^_`|~", rune(c))) { + return false + } + } + return true +} + +func validHeaderValue(s string) bool { + if s == "" { + return false + } + for _, c := range []byte(s) { + if c < 0x20 || c == 0x7f { + return false + } + } + return true +} + +func validateBedrockGateway(baseURL, token, model, headers string) (http.Header, error) { + u, err := url.Parse(baseURL) + if err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Scheme != "https" && !(u.Scheme == "http" && (u.Hostname() == "localhost" || u.Hostname() == "127.0.0.1" || u.Hostname() == "::1"))) { + return nil, errors.New("Bedrock gateway requires an HTTPS base URL (HTTP only for localhost)") + } + if !validHeaderValue(strings.TrimSpace(token)) { + return nil, errors.New("Bedrock gateway requires a bearer token") + } + if strings.TrimSpace(model) == "" || strings.ContainsAny(model, "?#\r\n") { + return nil, errors.New("Bedrock gateway requires a valid model ID") + } + return ParseBedrockGatewayHeaders(headers) +} + +// bedrockGatewayTransport adapts Norma's Anthropic Messages request/response +// to Bedrock InvokeModel. It never changes the destination host. +type bedrockGatewayTransport struct { + base http.RoundTripper + baseURL string + token string + model string + headers http.Header +} + +func (t *bedrockGatewayTransport) RoundTrip(req *http.Request) (*http.Response, error) { + if req.URL.Path != strings.TrimRight(mustURLPath(t.baseURL), "/")+"/v1/messages" { + return nil, errors.New("unexpected Bedrock gateway request path") + } + raw, err := io.ReadAll(req.Body) + _ = req.Body.Close() + if err != nil { + return nil, err + } + var body map[string]json.RawMessage + if err := json.Unmarshal(raw, &body); err != nil { + return nil, err + } + var streaming bool + if err := json.Unmarshal(body["stream"], &streaming); err != nil { + return nil, errors.New("missing stream mode") + } + delete(body, "stream") + delete(body, "model") + body["anthropic_version"] = json.RawMessage(`"bedrock-2023-05-31"`) + raw, err = json.Marshal(body) + if err != nil { + return nil, err + } + u, _ := url.Parse(t.baseURL) + basePath, escapedBasePath := strings.TrimRight(u.Path, "/"), strings.TrimRight(u.EscapedPath(), "/") + u.Path = basePath + "/model/" + t.model + "/invoke" + u.RawPath = escapedBasePath + "/model/" + url.PathEscape(t.model) + "/invoke" + if streaming { + u.Path += "-with-response-stream" + u.RawPath += "-with-response-stream" + } + q := req.Clone(req.Context()) + q.URL = u + q.Host = u.Host + q.Body = io.NopCloser(bytes.NewReader(raw)) + q.ContentLength = int64(len(raw)) + q.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(raw)), nil } + q.Header = req.Header.Clone() + q.Header.Del("x-api-key") + q.Header.Del("anthropic-version") + q.Header.Set("Authorization", "Bearer "+t.token) + q.Header.Set("Content-Type", "application/json") + q.Header.Set("X-Amzn-Bedrock-Accept", "application/json") + q.Header.Set("Accept", "application/json") + if streaming { + q.Header.Set("Accept", "application/vnd.amazon.eventstream") + } + for name, values := range t.headers { + q.Header[name] = append([]string(nil), values...) + } + resp, err := t.base.RoundTrip(q) + if err != nil { + return resp, err + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + // Gateways may echo authorization material in error bodies or headers. + // Keep the status for callers and retries without exposing that echo. + // Preserve only the quota classification used by the outer transport. + quotaExhausted := false + if resp.StatusCode == http.StatusTooManyRequests { + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) + quotaExhausted = IsQuotaExhaustedMessage(string(raw)) + } + _ = resp.Body.Close() + message := fmt.Sprintf("Bedrock gateway returned HTTP %d", resp.StatusCode) + if quotaExhausted { + message += ": quota_exceeded" + } + body := []byte(fmt.Sprintf(`{"message":%q}`, message)) + copy := *resp + copy.Body = io.NopCloser(bytes.NewReader(body)) + copy.ContentLength = int64(len(body)) + copy.Header = make(http.Header) + copy.Header.Set("Content-Type", "application/json") + if retryAfter := resp.Header.Get("Retry-After"); retryAfter != "" { + copy.Header.Set("Retry-After", retryAfter) + } + return ©, nil + } + if !streaming { + return resp, nil + } + if !strings.HasPrefix(strings.ToLower(resp.Header.Get("Content-Type")), "application/vnd.amazon.eventstream") { + resp.Body.Close() + return nil, errors.New("Bedrock gateway returned a non-eventstream response") + } + reader, writer := io.Pipe() + go func() { + defer resp.Body.Close() + defer writer.Close() + decoder := eventstream.NewDecoder() + for { + frame, err := decoder.Decode(resp.Body, nil) + if err == io.EOF { + return + } + if err != nil { + writer.CloseWithError(err) + return + } + if kind := fmt.Sprint(frame.Headers.Get(":message-type")); kind == "exception" || kind == "error" { + writer.CloseWithError(errors.New("Bedrock gateway stream exception")) + return + } + if fmt.Sprint(frame.Headers.Get(":message-type")) != "event" || fmt.Sprint(frame.Headers.Get(":event-type")) != "chunk" { + writer.CloseWithError(errors.New("unexpected Bedrock gateway event frame")) + return + } + payload := frame.Payload + var wrapper struct { + Bytes string `json:"bytes"` + } + if json.Unmarshal(payload, &wrapper) == nil && wrapper.Bytes != "" { + payload, err = base64.StdEncoding.DecodeString(wrapper.Bytes) + if err != nil { + writer.CloseWithError(err) + return + } + } + var event struct { + Type string `json:"type"` + } + if json.Unmarshal(payload, &event) != nil || !validEventType(event.Type) { + writer.CloseWithError(errors.New("invalid Bedrock gateway event")) + return + } + var compact bytes.Buffer + if err = json.Compact(&compact, payload); err != nil { + writer.CloseWithError(err) + return + } + if _, err = fmt.Fprintf(writer, "event: %s\ndata: %s\n\n", event.Type, compact.Bytes()); err != nil { + return + } + } + }() + copy := *resp + copy.Body = &bedrockStreamBody{PipeReader: reader, upstream: resp.Body} + copy.Header = resp.Header.Clone() + copy.Header.Set("Content-Type", "text/event-stream") + copy.Header.Del("Content-Length") + copy.ContentLength = -1 + return ©, nil +} + +func mustURLPath(raw string) string { u, _ := url.Parse(raw); return u.Path } + +func validEventType(s string) bool { + if s == "" { + return false + } + for _, c := range []byte(s) { + if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '_') { + return false + } + } + return true +} + +type bedrockStreamBody struct { + *io.PipeReader + upstream io.ReadCloser +} + +func (b *bedrockStreamBody) Close() error { + _ = b.upstream.Close() + return b.PipeReader.Close() +} diff --git a/agent/bedrock_gateway_test.go b/agent/bedrock_gateway_test.go new file mode 100644 index 0000000..381d560 --- /dev/null +++ b/agent/bedrock_gateway_test.go @@ -0,0 +1,235 @@ +package agent + +import ( + "context" + "encoding/base64" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "github.com/Autumn-27/norma/llm" + "github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream" +) + +func TestBedrockGatewayCompleteAndStream(t *testing.T) { + const token = "synthetic-test-token" + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + if r.Method != http.MethodPost || !strings.HasPrefix(r.URL.Path, "/bedrock/model/test.model/invoke") { + t.Errorf("path = %s", r.URL.Path) + } + if got := r.Header.Get("Authorization"); got != "Bearer "+token { + t.Errorf("auth = %q", got) + } + if got := r.Header.Get("X-Example-Route"); got != "demo" { + t.Errorf("custom header = %q", got) + } + if got := r.Header.Get("X-Api-Key"); got != "" { + t.Errorf("unexpected x-api-key") + } + var body map[string]json.RawMessage + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + } + if _, ok := body["model"]; ok { + t.Error("model remained in body") + } + if _, ok := body["stream"]; ok { + t.Error("stream remained in body") + } + if string(body["anthropic_version"]) != `"bedrock-2023-05-31"` { + t.Errorf("version = %s", body["anthropic_version"]) + } + if !strings.Contains(r.URL.Path, "response-stream") { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"type":"message","content":[{"type":"text","text":"done"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`)) + return + } + w.Header().Set("Content-Type", "application/vnd.amazon.eventstream") + enc := eventstream.NewEncoder() + for i, payload := range []string{ + `{"type":"message_start","message":{"usage":{"input_tokens":1,"output_tokens":0}}}`, + `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"streamed"}}`, + `{"type":"content_block_stop","index":0}`, + `{"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"tool-1","name":"lookup","input":{}}}`, + `{"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"q\":\"x\"}"}}`, + `{"type":"content_block_stop","index":1}`, + `{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":1}}`, + `{"type":"message_stop"}`, + } { + if i == 0 { + payload = `{"bytes":"` + base64.StdEncoding.EncodeToString([]byte(payload)) + `"}` + } + err := enc.Encode(w, eventstream.Message{Headers: eventstream.Headers{{Name: ":message-type", Value: eventstream.StringValue("event")}, {Name: ":event-type", Value: eventstream.StringValue("chunk")}}, Payload: []byte(payload)}) + if err != nil { + t.Error(err) + } + } + })) + defer server.Close() + cfg := ConfigFrom("bedrock-gateway", "test.model", server.URL+"/bedrock", token, "") + cfg.CustomHeaders = "X-Example-Route: demo" + p, err := cfg.NewProvider() + if err != nil { + t.Fatal(err) + } + req := llm.CompletionRequest{Messages: []llm.Message{llm.UserText("hello")}} + msg, _, _, err := p.Complete(context.Background(), req) + if err != nil || msg.Text() != "done" { + t.Fatalf("complete: %q, %v", msg.Text(), err) + } + var streamed, toolName, toolInput string + for ev, err := range p.Stream(context.Background(), req) { + if err != nil { + t.Fatal(err) + } + switch ev.Type { + case llm.SETextDelta: + streamed += ev.Text + case llm.SEToolUseStart: + toolName = ev.ToolName + case llm.SEToolInputJSON: + toolInput += ev.Text + } + } + if streamed != "streamed" || toolName != "lookup" || toolInput != `{"q":"x"}` || calls.Load() != 2 { + t.Fatalf("stream = %q, tool = %q %q, calls = %d", streamed, toolName, toolInput, calls.Load()) + } +} + +func TestBedrockGatewayStreamExceptionIsAnError(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/vnd.amazon.eventstream") + _ = eventstream.NewEncoder().Encode(w, eventstream.Message{Headers: eventstream.Headers{{Name: ":message-type", Value: eventstream.StringValue("exception")}, {Name: ":event-type", Value: eventstream.StringValue("validationException")}}, Payload: []byte(`{"message":"synthetic-secret"}`)}) + })) + defer server.Close() + cfg := ConfigFrom("bedrock-gateway", "test.model", server.URL, "synthetic-token", "") + p, err := cfg.NewProvider() + if err != nil { + t.Fatal(err) + } + var sawError bool + for _, err := range p.Stream(context.Background(), llm.CompletionRequest{Messages: []llm.Message{llm.UserText("hello")}}) { + if err != nil { + sawError = true + if strings.Contains(err.Error(), "synthetic-secret") { + t.Fatal("stream exception exposed gateway response body") + } + } + } + if !sawError { + t.Fatal("stream exception was treated as success") + } +} + +func TestBedrockGatewayErrorBodyIsRedacted(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusUnauthorized) + _, _ = w.Write([]byte(`{"message":"echoed synthetic-token and private-route"}`)) + })) + defer server.Close() + cfg := ConfigFrom("bedrock-gateway", "test.model", server.URL+"/private-route", "synthetic-token", "") + cfg.Stream = false + _, _, err := TestConnection(context.Background(), cfg) + if err == nil || !strings.Contains(err.Error(), "HTTP 401") || strings.Contains(err.Error(), "synthetic-token") || strings.Contains(err.Error(), "private-route") { + t.Fatalf("unsafe connection error: %v", err) + } +} + +func TestBedrockGatewayQuotaClassificationAfterRedaction(t *testing.T) { + for _, tc := range []struct { + name, upstreamBody string + wantStatus int + }{ + {"exhausted", `{"message":"quota_exceeded synthetic-secret"}`, http.StatusPaymentRequired}, + {"transient", `{"message":"rate limit reached synthetic-secret"}`, http.StatusTooManyRequests}, + } { + t.Run(tc.name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusTooManyRequests) + _, _ = w.Write([]byte(tc.upstreamBody)) + })) + defer server.Close() + transport := quotaAwareTransport{base: &bedrockGatewayTransport{ + base: http.DefaultTransport, baseURL: server.URL, token: "synthetic-token", model: "test.model", + }} + req, err := http.NewRequest(http.MethodPost, server.URL+"/v1/messages", strings.NewReader(`{"stream":false}`)) + if err != nil { + t.Fatal(err) + } + resp, err := transport.RoundTrip(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil || resp.StatusCode != tc.wantStatus || strings.Contains(string(body), "synthetic-secret") { + t.Fatalf("status=%d body=%q err=%v", resp.StatusCode, body, err) + } + }) + } +} + +func TestBedrockGatewayDoesNotFollowRedirectWithToken(t *testing.T) { + var redirected atomic.Bool + other := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { redirected.Store(true) })) + defer other.Close() + first := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, other.URL, http.StatusTemporaryRedirect) + })) + defer first.Close() + cfg := ConfigFrom("bedrock-gateway", "test.model", first.URL, "synthetic-token", "") + p, err := cfg.NewProvider() + if err != nil { + t.Fatal(err) + } + _, _, _, err = p.Complete(context.Background(), llm.CompletionRequest{Messages: []llm.Message{llm.UserText("hello")}}) + if err == nil || redirected.Load() { + t.Fatal("redirect followed or treated as success") + } +} + +func TestBedrockGatewayEscapesModelARN(t *testing.T) { + const model = "arn:aws:bedrock:region:123456789012:foundation-model/test.model" + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.Contains(r.URL.EscapedPath(), "foundation-model%2Ftest.model") { + t.Errorf("model path not escaped: %s", r.URL.EscapedPath()) + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"type":"message","content":[{"type":"text","text":"OK"}],"stop_reason":"end_turn"}`)) + })) + defer server.Close() + cfg := ConfigFrom("bedrock-gateway", model, server.URL, "synthetic-token", "") + p, err := cfg.NewProvider() + if err != nil { + t.Fatal(err) + } + if _, _, _, err := p.Complete(context.Background(), llm.CompletionRequest{Messages: []llm.Message{llm.UserText("hello")}}); err != nil { + t.Fatal(err) + } +} + +func TestBedrockGatewayRejectsUnsafeConfig(t *testing.T) { + for _, cfg := range []Config{ + ConfigFrom("bedrock-gateway", "model", "", "token", ""), + ConfigFrom("bedrock-gateway", "model", "https://example.com", "", ""), + ConfigFrom("bedrock-gateway", "model", "https://example.com", "token", ""), + } { + if cfg.BaseURL != "" && cfg.APIKey != "" { + cfg.CustomHeaders = "Authorization: stolen" + } + if _, err := cfg.NewProvider(); err == nil { + t.Errorf("accepted unsafe config: %+v", cfg) + } + } + if _, err := ParseBedrockGatewayHeaders("X-Test: ok\nInjected: x\r\nBad: y\x00"); err == nil { + t.Fatal("accepted control characters") + } +} diff --git a/agent/provider.go b/agent/provider.go index 088fcbb..cf82517 100644 --- a/agent/provider.go +++ b/agent/provider.go @@ -92,6 +92,8 @@ type Config struct { // LLM request built from this config. Empty = don't set it, leaving the Go/Norma // default UA untouched (the historical behavior). Validated by ValidateUserAgent. UserAgent string + // CustomHeaders are static Bedrock gateway headers, one Name: Value per line. + CustomHeaders string // Retry holds the retry parameters resolved for this config (profile override → // global policy → built-in default, resolved server-side). See RetryConfig for // the per-layer semantics; zero values = fully inherit the built-in defaults. @@ -141,6 +143,7 @@ const ( // forcing our base-URL/key defaults so an empty key never falls back to // OpenAI's public endpoint). const FormatOllama llm.Format = "ollama" +const FormatBedrockGateway llm.Format = "bedrock-gateway" // DefaultOllamaBaseURL is the base of Ollama's OpenAI-compatible endpoint the // provider appends /chat/completions to. Must never end up empty: with an @@ -273,6 +276,13 @@ func FromEnv() (Config, bool) { if c.Model == "" { c.Model = "llama3.2" } + case "bedrock-gateway": + c.Format = FormatBedrockGateway + c.APIKey = strings.TrimSpace(os.Getenv("ARTEX_LLM_API_KEY")) + c.CustomHeaders = os.Getenv("ARTEX_LLM_CUSTOM_HEADERS") + if c.BaseURL == "" || c.Model == "" { + return Config{}, false + } default: c.Format = llm.FormatAnthropic c.APIKey = anthKey @@ -324,6 +334,10 @@ func ConfigFrom(provider, model, baseURL, apiKey, proxy string) Config { if c.Model == "" { c.Model = "llama3.2" } + case "bedrock-gateway": + c.Format = FormatBedrockGateway + // No public-provider defaults: an absent URL, model or token fails closed. + c.BaseURL = strings.TrimRight(strings.TrimSuffix(strings.TrimSuffix(c.BaseURL, "/invoke-with-response-stream"), "/invoke"), "/") default: c.Format = llm.FormatAnthropic // provider appends "/v1/messages". @@ -355,6 +369,8 @@ func (c Config) Provider() string { return "openai-responses" case FormatOllama: return "ollama" + case FormatBedrockGateway: + return "bedrock-gateway" } return "anthropic" } @@ -384,6 +400,17 @@ func (c Config) NewProvider() (llm.Provider, error) { apiKey = ollamaPlaceholderKey } } + if wireFormat == FormatBedrockGateway { + headers, err := validateBedrockGateway(baseURL, apiKey, c.Model, c.CustomHeaders) + if err != nil { + return nil, err + } + wireFormat = llm.FormatAnthropic + qt := client.Transport.(quotaAwareTransport) + qt.base = &bedrockGatewayTransport{base: qt.base, baseURL: baseURL, token: apiKey, model: c.Model, headers: headers} + client.Transport = qt + client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + } lc := llm.Config{ Format: wireFormat, BaseURL: baseURL, @@ -587,6 +614,16 @@ func ValidateUserAgent(raw string) (string, error) { // SSE stream from flooding the log. func logTestConnection(c Config, capt *llmrec.Capture) { attempts := capt.Attempts() + if c.Format == FormatBedrockGateway { + if len(attempts) == 0 { + log.Print("[llm-test] bedrock-gateway — no HTTP request was sent") + return + } + for i, a := range attempts { + log.Printf("[llm-test] bedrock-gateway — attempt %d/%d HTTP %d", i+1, len(attempts), a.Status) + } + return + } if len(attempts) == 0 { log.Printf("[llm-test] %s / %s @ %s — no HTTP request was ever sent (config resolution or connection setup failed)", c.Provider(), c.Model, c.BaseURL) @@ -662,6 +699,13 @@ func TestConnection(ctx context.Context, c Config) (time.Duration, string, error }, "ping") lat := time.Since(start) if err != nil { + if c.Format == FormatBedrockGateway { + attempts := capt.Attempts() + if len(attempts) > 0 && attempts[len(attempts)-1].Status >= 400 { + return lat, "", fmt.Errorf("Bedrock gateway returned HTTP %d", attempts[len(attempts)-1].Status) + } + return lat, "", fmt.Errorf("Bedrock gateway connection failed") + } return lat, "", err } // err==nil is not enough: requests that go through while the model emits nothing diff --git a/agent/provider_env_test.go b/agent/provider_env_test.go index 6d58003..35b3b6e 100644 --- a/agent/provider_env_test.go +++ b/agent/provider_env_test.go @@ -35,3 +35,20 @@ func TestFromEnvProviderIsCaseInsensitive(t *testing.T) { } } } + +func TestBedrockGatewayEnvDoesNotInheritPublicProviderKey(t *testing.T) { + t.Setenv("ARTEX_LLM_PROVIDER", "bedrock-gateway") + t.Setenv("ARTEX_LLM_BASE_URL", "https://gateway.example.com/bedrock") + t.Setenv("ARTEX_LLM_MODEL", "test.model") + t.Setenv("ANTHROPIC_API_KEY", "unrelated-anthropic-key") + t.Setenv("ARTEX_LLM_API_KEY", "") + if _, ok := FromEnv(); ok { + t.Fatal("gateway inherited an unrelated key") + } + t.Setenv("ARTEX_LLM_API_KEY", "synthetic-gateway-token") + t.Setenv("ARTEX_LLM_CUSTOM_HEADERS", "X-Example-Route: demo") + c, ok := FromEnv() + if !ok || c.Format != FormatBedrockGateway || c.APIKey != "synthetic-gateway-token" || c.CustomHeaders != "X-Example-Route: demo" { + t.Fatal("gateway environment was not resolved") + } +} diff --git a/db/bedrock_gateway_test.go b/db/bedrock_gateway_test.go new file mode 100644 index 0000000..d982ef6 --- /dev/null +++ b/db/bedrock_gateway_test.go @@ -0,0 +1,71 @@ +package db + +import ( + "encoding/json" + "fmt" + "strings" + "testing" + "time" +) + +func TestBedrockGatewayHeadersEncryptedAndWriteOnly(t *testing.T) { + d, err := Open(testDSN(t)) + if err != nil { + SkipPGUnavailable(t, err) + } + defer d.Close() + const headers = "X-Example-Route: synthetic-secret" + id, err := d.SaveProfile(&LLMProfile{Name: fmt.Sprintf("t-bedrock-%d", time.Now().UnixNano()), Format: "bedrock-gateway", BaseURL: "https://gateway.example.com/bedrock", Model: "test.model", APIKey: "synthetic-token", CustomHeaders: headers}) + if err != nil { + t.Fatal(err) + } + defer deleteTestProfile(t, d, id) + var stored string + if err := d.QueryRow(`SELECT custom_headers FROM llm_profiles WHERE id=$1`, id).Scan(&stored); err != nil { + t.Fatal(err) + } + if !isEncrypted(stored) || strings.Contains(stored, "synthetic-secret") { + t.Fatal("headers were stored in plaintext") + } + p, err := d.ProfileByID(id) + if err != nil || p.CustomHeaders != headers { + t.Fatalf("keyed load failed: %v", err) + } + list, err := d.ListProfiles() + if err != nil { + t.Fatal(err) + } + for _, item := range list { + if item.ID != id { + continue + } + b, _ := json.Marshal(item) + if strings.Contains(string(b), "synthetic-secret") || strings.Contains(string(b), "synthetic-token") { + t.Fatal("profile list leaked a secret") + } + } + if _, err := d.SaveProfile(&LLMProfile{ID: id, Name: p.Name, Format: p.Format, BaseURL: p.BaseURL, Model: p.Model}); err != nil { + t.Fatal(err) + } + p, err = d.ProfileByID(id) + if err != nil || p.CustomHeaders != headers { + t.Fatal("blank update did not preserve headers") + } + if _, err := d.SaveProfile(&LLMProfile{ID: id, Name: p.Name, Format: p.Format, BaseURL: p.BaseURL, Model: p.Model, ClearCustomHeaders: true}); err != nil { + t.Fatal(err) + } + p, err = d.ProfileByID(id) + if err != nil || p.CustomHeaders != "" { + t.Fatal("clear did not remove headers") + } + if _, err := d.SaveProfile(&LLMProfile{ID: id, Name: p.Name, Format: p.Format, BaseURL: p.BaseURL, Model: p.Model, APIKey: "synthetic-token", CustomHeaders: headers}); err != nil { + t.Fatal(err) + } + if _, err := d.SaveProfile(&LLMProfile{ID: id, Name: p.Name, Format: p.Format, BaseURL: "https://other.example.com/bedrock", Model: p.Model}); err != nil { + t.Fatal(err) + } + p, err = d.ProfileByID(id) + if err != nil || p.APIKey != "" || p.CustomHeaders != "" { + t.Fatal("direct endpoint edit retained gateway credentials") + } +} diff --git a/db/config.go b/db/config.go index 983fa7f..1e7c9e9 100644 --- a/db/config.go +++ b/db/config.go @@ -13,16 +13,18 @@ import ( // ---------- LLM profiles ---------- type LLMProfile struct { - ID int64 `json:"id"` - Name string `json:"name"` - Format string `json:"format"` - BaseURL string `json:"base_url,omitempty"` - Proxy string `json:"proxy,omitempty"` // LLM outbound proxy (http/https/socks5); empty = use environment variables - Model string `json:"model"` - APIKey string `json:"-"` // never serialized to UI - APIKeyHint string `json:"api_key_hint,omitempty"` - RatePerSecond float64 `json:"rate_per_second"` - RatePerMinute float64 `json:"rate_per_minute"` + ID int64 `json:"id"` + Name string `json:"name"` + Format string `json:"format"` + BaseURL string `json:"base_url,omitempty"` + Proxy string `json:"proxy,omitempty"` // LLM outbound proxy (http/https/socks5); empty = use environment variables + Model string `json:"model"` + APIKey string `json:"-"` // never serialized to UI + CustomHeaders string `json:"-"` // encrypted at rest; never serialized to UI + ClearCustomHeaders bool `json:"-"` + APIKeyHint string `json:"api_key_hint,omitempty"` + RatePerSecond float64 `json:"rate_per_second"` + RatePerMinute float64 `json:"rate_per_minute"` // ContextWindowK is the model's context window in K tokens, used to size // compaction thresholds. 0 = use a 200K default; capped at 1000 (1M). ContextWindowK int `json:"context_window_k"` @@ -93,8 +95,8 @@ type RetryOverride struct { // profileCols is the read column list (hint variant, no api key) shared by the // list query; profileColsKey is the same with api_key for the single-row loads. const profileRetryCols = `COALESCE(retry_connect_attempts,0),COALESCE(retry_connect_interval_ms,0),COALESCE(retry_empty_attempts,0),COALESCE(retry_empty_interval_ms,0),COALESCE(retry_stream_attempts,0),COALESCE(retry_stream_interval_ms,0)` -const profileCols = `id,name,format,COALESCE(base_url,''),COALESCE(proxy,''),model,COALESCE(api_key_hint,''),rate_per_second,rate_per_minute,context_window_k,COALESCE(reasoning_effort,''),is_default,priority,pool_exclude,COALESCE(thinking_type,''),COALESCE(streaming,true),COALESCE(max_tokens,0),COALESCE(max_tokens_field,''),COALESCE(session_header_key,''),` + profileRetryCols + `,COALESCE(price_input_per_m,0),COALESCE(price_output_per_m,0),COALESCE(price_cache_read_per_m,0),COALESCE(price_cache_write_per_m,0),COALESCE(user_agent,'')` -const profileColsKey = `id,name,format,COALESCE(base_url,''),COALESCE(proxy,''),model,COALESCE(api_key,''),rate_per_second,rate_per_minute,context_window_k,COALESCE(reasoning_effort,''),is_default,priority,pool_exclude,COALESCE(thinking_type,''),COALESCE(streaming,true),COALESCE(max_tokens,0),COALESCE(max_tokens_field,''),COALESCE(session_header_key,''),` + profileRetryCols + `,COALESCE(price_input_per_m,0),COALESCE(price_output_per_m,0),COALESCE(price_cache_read_per_m,0),COALESCE(price_cache_write_per_m,0),COALESCE(user_agent,'')` +const profileCols = `id,name,format,COALESCE(base_url,''),COALESCE(proxy,''),model,COALESCE(api_key_hint,''),rate_per_second,rate_per_minute,context_window_k,COALESCE(reasoning_effort,''),is_default,priority,pool_exclude,COALESCE(thinking_type,''),COALESCE(streaming,true),COALESCE(max_tokens,0),COALESCE(max_tokens_field,''),COALESCE(session_header_key,''),` + profileRetryCols + `,COALESCE(price_input_per_m,0),COALESCE(price_output_per_m,0),COALESCE(price_cache_read_per_m,0),COALESCE(price_cache_write_per_m,0),COALESCE(user_agent,''),COALESCE(custom_headers,'')` +const profileColsKey = `id,name,format,COALESCE(base_url,''),COALESCE(proxy,''),model,COALESCE(api_key,''),rate_per_second,rate_per_minute,context_window_k,COALESCE(reasoning_effort,''),is_default,priority,pool_exclude,COALESCE(thinking_type,''),COALESCE(streaming,true),COALESCE(max_tokens,0),COALESCE(max_tokens_field,''),COALESCE(session_header_key,''),` + profileRetryCols + `,COALESCE(price_input_per_m,0),COALESCE(price_output_per_m,0),COALESCE(price_cache_read_per_m,0),COALESCE(price_cache_write_per_m,0),COALESCE(user_agent,''),COALESCE(custom_headers,'')` // scanProfile reads one row in the profileCols / profileColsKey column order. The // 7th column lands in APIKeyHint or APIKey depending on which list the caller used. @@ -106,13 +108,16 @@ func scanProfile(sc interface{ Scan(...any) error }, into *string, p *LLMProfile &p.Retry.Empty.Attempts, &p.Retry.Empty.IntervalMS, &p.Retry.Stream.Attempts, &p.Retry.Stream.IntervalMS, &p.PriceInputPerM, &p.PriceOutputPerM, &p.PriceCacheReadPerM, &p.PriceCacheWritePerM, - &p.UserAgent) + &p.UserAgent, &p.CustomHeaders) if err != nil { return err } if p.Proxy, err = openSecret(colLLMProxy, p.Proxy); err != nil || into != &p.APIKey { return err } + if p.CustomHeaders, err = openSecret(colLLMHeaders, p.CustomHeaders); err != nil { + return err + } p.APIKey, err = openSecret(colLLMKey, p.APIKey) return err } @@ -198,30 +203,44 @@ func (d *DB) SaveProfile(p *LLMProfile) (int64, error) { if err != nil { return 0, err } + // Keep the endpoint and its secret headers in the same SQL write. A second + // UPDATE would let a concurrent reader see a new gateway with old headers. + replaceHeaders := p.CustomHeaders != "" || p.ClearCustomHeaders + if p.Format != "bedrock-gateway" { + p.CustomHeaders = "" + replaceHeaders = true + } + headerValue := "" + if replaceHeaders { + headerValue, err = sealSecret(colLLMHeaders, p.CustomHeaders) + if err != nil { + return 0, err + } + } r := p.Retry.Clamped() if p.ID == 0 { var id int64 - err := d.QueryRow(`INSERT INTO llm_profiles(name,format,base_url,proxy,model,api_key,api_key_hint,rate_per_second,rate_per_minute,context_window_k,reasoning_effort,priority,pool_exclude,thinking_type,streaming,max_tokens,max_tokens_field,session_header_key,retry_connect_attempts,retry_connect_interval_ms,retry_empty_attempts,retry_empty_interval_ms,retry_stream_attempts,retry_stream_interval_ms,user_agent) -VALUES ($1,$2,NULLIF($3,''),NULLIF($4,''),$5,NULLIF($6,''),NULLIF($7,''),$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25) RETURNING id`, + err := d.QueryRow(`INSERT INTO llm_profiles(name,format,base_url,proxy,model,api_key,api_key_hint,rate_per_second,rate_per_minute,context_window_k,reasoning_effort,priority,pool_exclude,thinking_type,streaming,max_tokens,max_tokens_field,session_header_key,retry_connect_attempts,retry_connect_interval_ms,retry_empty_attempts,retry_empty_interval_ms,retry_stream_attempts,retry_stream_interval_ms,user_agent,custom_headers) +VALUES ($1,$2,NULLIF($3,''),NULLIF($4,''),$5,NULLIF($6,''),NULLIF($7,''),$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26) RETURNING id`, p.Name, p.Format, p.BaseURL, proxy, p.Model, key, hint, p.RatePerSecond, p.RatePerMinute, p.ContextWindowK, p.ReasoningEffort, p.Priority, p.PoolExclude, p.ThinkingType, p.Streaming, p.MaxTokens, p.MaxTokensField, p.SessionHeaderKey, - r.Connect.Attempts, r.Connect.IntervalMS, r.Empty.Attempts, r.Empty.IntervalMS, r.Stream.Attempts, r.Stream.IntervalMS, p.UserAgent).Scan(&id) + r.Connect.Attempts, r.Connect.IntervalMS, r.Empty.Attempts, r.Empty.IntervalMS, r.Stream.Attempts, r.Stream.IntervalMS, p.UserAgent, headerValue).Scan(&id) if err == nil { _, err = d.saveProfilePrices(id, p) } return id, err } if p.APIKey == "" { - _, err := d.Exec(`UPDATE llm_profiles SET name=$1,format=$2,base_url=NULLIF($3,''),proxy=NULLIF($4,''),model=$5,rate_per_second=$6,rate_per_minute=$7,context_window_k=$8,reasoning_effort=$9,priority=$10,pool_exclude=$11,thinking_type=$12,streaming=$13,max_tokens=$14,max_tokens_field=$15,session_header_key=$16,retry_connect_attempts=$17,retry_connect_interval_ms=$18,retry_empty_attempts=$19,retry_empty_interval_ms=$20,retry_stream_attempts=$21,retry_stream_interval_ms=$22,user_agent=$23 WHERE id=$24`, + _, err := d.Exec(`UPDATE llm_profiles SET name=$1,format=$2,base_url=NULLIF($3,''),proxy=NULLIF($4,''),model=$5,api_key=CASE WHEN $2='bedrock-gateway' AND (format <> $2 OR COALESCE(base_url,'') <> $3) THEN '' ELSE api_key END,api_key_hint=CASE WHEN $2='bedrock-gateway' AND (format <> $2 OR COALESCE(base_url,'') <> $3) THEN '' ELSE api_key_hint END,rate_per_second=$6,rate_per_minute=$7,context_window_k=$8,reasoning_effort=$9,priority=$10,pool_exclude=$11,thinking_type=$12,streaming=$13,max_tokens=$14,max_tokens_field=$15,session_header_key=$16,retry_connect_attempts=$17,retry_connect_interval_ms=$18,retry_empty_attempts=$19,retry_empty_interval_ms=$20,retry_stream_attempts=$21,retry_stream_interval_ms=$22,user_agent=$23,custom_headers=CASE WHEN $25 THEN $26 WHEN format <> $2 OR COALESCE(base_url,'') <> $3 THEN '' ELSE custom_headers END WHERE id=$24`, p.Name, p.Format, p.BaseURL, proxy, p.Model, p.RatePerSecond, p.RatePerMinute, p.ContextWindowK, p.ReasoningEffort, p.Priority, p.PoolExclude, p.ThinkingType, p.Streaming, p.MaxTokens, p.MaxTokensField, p.SessionHeaderKey, - r.Connect.Attempts, r.Connect.IntervalMS, r.Empty.Attempts, r.Empty.IntervalMS, r.Stream.Attempts, r.Stream.IntervalMS, p.UserAgent, p.ID) + r.Connect.Attempts, r.Connect.IntervalMS, r.Empty.Attempts, r.Empty.IntervalMS, r.Stream.Attempts, r.Stream.IntervalMS, p.UserAgent, p.ID, replaceHeaders, headerValue) if err == nil { _, err = d.saveProfilePrices(p.ID, p) } return p.ID, err } - _, err = d.Exec(`UPDATE llm_profiles SET name=$1,format=$2,base_url=NULLIF($3,''),proxy=NULLIF($4,''),model=$5,api_key=$6,api_key_hint=$7,rate_per_second=$8,rate_per_minute=$9,context_window_k=$10,reasoning_effort=$11,priority=$12,pool_exclude=$13,thinking_type=$14,streaming=$15,max_tokens=$16,max_tokens_field=$17,session_header_key=$18,retry_connect_attempts=$19,retry_connect_interval_ms=$20,retry_empty_attempts=$21,retry_empty_interval_ms=$22,retry_stream_attempts=$23,retry_stream_interval_ms=$24,user_agent=$25 WHERE id=$26`, + _, err = d.Exec(`UPDATE llm_profiles SET name=$1,format=$2,base_url=NULLIF($3,''),proxy=NULLIF($4,''),model=$5,api_key=$6,api_key_hint=$7,rate_per_second=$8,rate_per_minute=$9,context_window_k=$10,reasoning_effort=$11,priority=$12,pool_exclude=$13,thinking_type=$14,streaming=$15,max_tokens=$16,max_tokens_field=$17,session_header_key=$18,retry_connect_attempts=$19,retry_connect_interval_ms=$20,retry_empty_attempts=$21,retry_empty_interval_ms=$22,retry_stream_attempts=$23,retry_stream_interval_ms=$24,user_agent=$25,custom_headers=CASE WHEN $27 THEN $28 WHEN format <> $2 OR COALESCE(base_url,'') <> $3 THEN '' ELSE custom_headers END WHERE id=$26`, p.Name, p.Format, p.BaseURL, proxy, p.Model, key, hint, p.RatePerSecond, p.RatePerMinute, p.ContextWindowK, p.ReasoningEffort, p.Priority, p.PoolExclude, p.ThinkingType, p.Streaming, p.MaxTokens, p.MaxTokensField, p.SessionHeaderKey, - r.Connect.Attempts, r.Connect.IntervalMS, r.Empty.Attempts, r.Empty.IntervalMS, r.Stream.Attempts, r.Stream.IntervalMS, p.UserAgent, p.ID) + r.Connect.Attempts, r.Connect.IntervalMS, r.Empty.Attempts, r.Empty.IntervalMS, r.Stream.Attempts, r.Stream.IntervalMS, p.UserAgent, p.ID, replaceHeaders, headerValue) if err == nil { _, err = d.saveProfilePrices(p.ID, p) } diff --git a/db/migrate_test.go b/db/migrate_test.go index 0227d96..bdbd6a4 100644 --- a/db/migrate_test.go +++ b/db/migrate_test.go @@ -140,9 +140,9 @@ func assertEmbeddedApplied(t *testing.T, d *DB) []appliedMigration { {5, "0005_traffic_rewrite_rules.sql"}, {6, "0006_activity_outbox.sql"}, {7, "0007_finding_report_state.sql"}, {8, "0008_traffic_evidence_rewrite_flag.sql"}, {9, "0009_llm_context.sql"}, {10, "0010_dashboard_usage_indexes.sql"}, {11, "0011_traffic_tamper_hooks.sql"}, {12, "0012_lesson_withdrawn.sql"}, - {13, "0013_lesson_evidence_history.sql"}} + {13, "0013_lesson_evidence_history.sql"}, {14, "0014_bedrock_gateway_profiles.sql"}} if len(applied) != len(want) { - t.Fatalf("schema_migrations = %+v, want versions 1 to 13", applied) + t.Fatalf("schema_migrations = %+v, want versions 1 to 14", applied) } for i, w := range want { content, err := fs.ReadFile(migrationsFS(), w.name) @@ -437,7 +437,7 @@ func TestLessonWithdrawnMigrationKeepsExistingEvidence(t *testing.T) { `ALTER TABLE rsi_lesson_evidence DROP COLUMN withdrawn_at`, string(migrationSQL), `ALTER TABLE rsi_lesson_evidence DROP COLUMN withdrawn_at`, - `DELETE FROM schema_migrations WHERE version IN (12, 13)`, + `DELETE FROM schema_migrations WHERE version >= 12`, `INSERT INTO rsi_lessons(dedupe_key,kind,cue,action,status) VALUES ('legacy-lesson','positive','xss','Confirmed xss: legacy','adopted')`, `INSERT INTO rsi_lesson_evidence(lesson_id,source_kind,source_id,detail) diff --git a/db/migrations/0014_bedrock_gateway_profiles.sql b/db/migrations/0014_bedrock_gateway_profiles.sql new file mode 100644 index 0000000..8993232 --- /dev/null +++ b/db/migrations/0014_bedrock_gateway_profiles.sql @@ -0,0 +1,5 @@ +-- The idempotent schema supplies the DDL; this migration records the feature version. +ALTER TABLE llm_profiles ADD COLUMN IF NOT EXISTS custom_headers TEXT NOT NULL DEFAULT ''; +ALTER TABLE llm_profiles DROP CONSTRAINT IF EXISTS llm_profiles_format_check; +ALTER TABLE llm_profiles ADD CONSTRAINT llm_profiles_format_check + CHECK (format IN ('openai','anthropic','openai-responses','ollama','bedrock-gateway')); diff --git a/db/schema.sql b/db/schema.sql index 7d323e6..62331a3 100644 --- a/db/schema.sql +++ b/db/schema.sql @@ -370,7 +370,7 @@ CREATE TABLE IF NOT EXISTS settings ( CREATE TABLE IF NOT EXISTS llm_profiles ( id BIGSERIAL PRIMARY KEY, name TEXT NOT NULL UNIQUE, - format TEXT NOT NULL CHECK (format IN ('openai','anthropic','openai-responses','ollama')), + format TEXT NOT NULL CHECK (format IN ('openai','anthropic','openai-responses','ollama','bedrock-gateway')), base_url TEXT, proxy TEXT, model TEXT NOT NULL, @@ -405,6 +405,7 @@ CREATE TABLE IF NOT EXISTS llm_profiles ( session_header_key TEXT NOT NULL DEFAULT '', -- Custom User-Agent: when non-empty, every outbound LLM request overrides the User-Agent header with this value. ''=do not override (keep the default UA). user_agent TEXT NOT NULL DEFAULT '', + custom_headers TEXT NOT NULL DEFAULT '', -- Retry overrides: attempts 0=use global default / -1=disable / >0=use this value; interval 0=use default exponential backoff / >0=fixed milliseconds. -- The three groups correspond to connect retry, empty-response retry, and same-provider safe-window retry; see the ALTER comment below. retry_connect_attempts INTEGER NOT NULL DEFAULT 0, @@ -427,10 +428,10 @@ ALTER TABLE llm_profiles ADD COLUMN IF NOT EXISTS pool_exclude BOOLEAN NOT NULL ALTER TABLE llm_profiles ADD COLUMN IF NOT EXISTS streaming BOOLEAN NOT NULL DEFAULT true; -- Relax the format constraint to allow openai-responses (OpenAI Responses API) and -- ollama (local Ollama server, keyless OpenAI-compatible endpoint); backfills old databases. --- Runs at every startup, idempotent: drop the old CHECK first, then create the new four-value CHECK. +-- Runs at every startup, idempotent: drop the old CHECK first, then create the current format CHECK. ALTER TABLE llm_profiles DROP CONSTRAINT IF EXISTS llm_profiles_format_check; ALTER TABLE llm_profiles ADD CONSTRAINT llm_profiles_format_check - CHECK (format IN ('openai','anthropic','openai-responses','ollama')); + CHECK (format IN ('openai','anthropic','openai-responses','ollama','bedrock-gateway')); -- Output cap and its field name; backfills old databases. Defaults 0 / '' = send no cap and keep the max_tokens field name; -- old configs behave exactly as before. @@ -447,6 +448,7 @@ ALTER TABLE llm_profiles ADD CONSTRAINT llm_profiles_max_tokens_check ALTER TABLE llm_profiles ADD COLUMN IF NOT EXISTS session_header_key TEXT NOT NULL DEFAULT ''; -- Custom User-Agent; backfills old databases. Default '' = do not override (keep the default UA); old configs behave unchanged. ALTER TABLE llm_profiles ADD COLUMN IF NOT EXISTS user_agent TEXT NOT NULL DEFAULT ''; +ALTER TABLE llm_profiles ADD COLUMN IF NOT EXISTS custom_headers TEXT NOT NULL DEFAULT ''; -- Per-profile retry overrides (see the LLM retry design doc). Each of the three groups is a pair of -- "attempts + fixed interval" with unified semantics: attempts 0=use the global default, -1=disable this layer's diff --git a/db/secrets.go b/db/secrets.go index 596bfb7..2a47e58 100644 --- a/db/secrets.go +++ b/db/secrets.go @@ -79,6 +79,7 @@ func (c secretColumn) valueExpr() string { var ( colLLMKey = secretColumn{"llm_profiles", "api_key", false, ""} colLLMProxy = secretColumn{"llm_profiles", "proxy", false, ""} // may carry user:pass + colLLMHeaders = secretColumn{"llm_profiles", "custom_headers", false, ""} colMCPEnv = secretColumn{"mcp_servers", "env", true, ""} colCredPass = secretColumn{"task_credentials", "password", false, ""} colNotifConfig = secretColumn{"notification_channels", "config", true, ""} @@ -95,7 +96,7 @@ var ( colHookSource = secretColumn{"traffic_tamper_hooks", "source", false, ""} colHookVerMatchers = secretColumn{"traffic_tamper_hook_versions", "matchers", true, ""} colHookVerSource = secretColumn{"traffic_tamper_hook_versions", "source", false, ""} - secretColumns = append([]secretColumn{colLLMKey, colLLMProxy, colMCPEnv, colCredPass, colNotifConfig, colToolExec, colEvReqHead, colEvRespHead, colRewriteMatchers, colRewriteActions, colHookMatchers, colHookSource, colHookVerMatchers, colHookVerSource}, secretSettingColumns()...) + secretColumns = append([]secretColumn{colLLMKey, colLLMProxy, colLLMHeaders, colMCPEnv, colCredPass, colNotifConfig, colToolExec, colEvReqHead, colEvRespHead, colRewriteMatchers, colRewriteActions, colHookMatchers, colHookSource, colHookVerMatchers, colHookVerSource}, secretSettingColumns()...) ) // secretSettingKeys are the settings stored encrypted, AAD "settings.". diff --git a/go.mod b/go.mod index ebbf876..d3950d5 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.26.11 require ( github.com/Autumn-27/norma v0.4.11 github.com/aws/aws-sdk-go-v2 v1.47.5 + github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.25 github.com/aws/aws-sdk-go-v2/config v1.33.13 github.com/aws/aws-sdk-go-v2/credentials v1.20.13 github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.23.19 @@ -27,7 +28,6 @@ require ( require ( github.com/andybalholm/brotli v1.2.7 // indirect github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect - github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.25 // indirect github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5 // indirect github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 // indirect github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 // indirect diff --git a/server/bedrock_gateway_test.go b/server/bedrock_gateway_test.go new file mode 100644 index 0000000..af4a625 --- /dev/null +++ b/server/bedrock_gateway_test.go @@ -0,0 +1,146 @@ +package server + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "github.com/Autumn-27/artex/db" +) + +func TestBedrockGatewaySavedProfileAndConnection(t *testing.T) { + skipWithoutDSN(t) + m, err := NewManager(t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { m.Close() }) + if m.pg == nil { + db.SkipNoPG(t) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir()) + const token = "synthetic-gateway-token" + const header = "X-Example-Route: synthetic-route" + var calls atomic.Int32 + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + if r.URL.Path != "/bedrock/model/test.model/invoke" || r.Header.Get("Authorization") != "Bearer "+token || r.Header.Get("X-Example-Route") != "synthetic-route" { + t.Errorf("unexpected gateway request") + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"m","type":"message","role":"assistant","model":"test.model","content":[{"type":"text","text":"OK"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`)) + })) + defer fake.Close() + id, err := m.pg.SaveProfile(&db.LLMProfile{Name: "t-bedrock-server", Format: "bedrock-gateway", Model: "test.model", BaseURL: fake.URL + "/bedrock", APIKey: token, CustomHeaders: header, Streaming: false}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _, _ = m.pg.Exec(`DELETE FROM llm_profiles WHERE id=$1`, id) }) + list, err := m.pg.ListProfiles() + if err != nil { + t.Fatal(err) + } + for _, p := range list { + if p.ID != id { + continue + } + b, _ := json.Marshal(llmProfileDTO(p)) + if !strings.Contains(string(b), `"custom_headers_set":true`) || strings.Contains(string(b), token) || strings.Contains(string(b), "synthetic-route") { + t.Fatal("profile DTO exposed a secret or omitted header status") + } + } + body, _ := json.Marshal(map[string]any{"profile_id": id}) + rec := httptest.NewRecorder() + s.testLLM(rec, httptest.NewRequest(http.MethodPost, "/api/llm/test", bytes.NewReader(body))) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"ok":true`) || calls.Load() != 1 { + t.Fatalf("stored profile test failed: HTTP %d %s calls=%d", rec.Code, rec.Body.String(), calls.Load()) + } + otherCalls := atomic.Int32{} + other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { otherCalls.Add(1) })) + defer other.Close() + body, _ = json.Marshal(map[string]any{"provider": "bedrock-gateway", "model": "test.model", "base_url": other.URL + "/bedrock", "profile_id": id, "streaming": false}) + rec = httptest.NewRecorder() + s.testLLM(rec, httptest.NewRequest(http.MethodPost, "/api/llm/test", bytes.NewReader(body))) + if otherCalls.Load() != 0 || !strings.Contains(rec.Body.String(), `"ok":false`) { + t.Fatal("stored bearer token was used at a different endpoint") + } + body, _ = json.Marshal(map[string]any{"id": id, "name": "t-bedrock-server", "format": "bedrock-gateway", "model": "test.model", "base_url": other.URL + "/bedrock", "api_key": ""}) + rec = httptest.NewRecorder() + s.pgSaveProfile(rec, httptest.NewRequest(http.MethodPost, "/api/llm/profiles", bytes.NewReader(body))) + if rec.Code != http.StatusBadRequest { + t.Fatalf("endpoint edit without a new token accepted: HTTP %d", rec.Code) + } + stored, err := m.pg.ProfileByID(id) + if err != nil || stored.BaseURL != fake.URL+"/bedrock" { + t.Fatal("rejected endpoint edit changed the saved profile") + } + body, _ = json.Marshal(map[string]any{"id": id, "name": "t-bedrock-server", "format": "bedrock-gateway", "model": "test.model", "base_url": other.URL + "/bedrock", "api_key": "synthetic-new-token"}) + rec = httptest.NewRecorder() + s.pgSaveProfile(rec, httptest.NewRequest(http.MethodPost, "/api/llm/profiles", bytes.NewReader(body))) + if rec.Code != http.StatusOK { + t.Fatalf("endpoint edit with new token returned HTTP %d: %s", rec.Code, rec.Body.String()) + } + stored, err = m.pg.ProfileByID(id) + if err != nil || stored.BaseURL != other.URL+"/bedrock" || stored.CustomHeaders != "" { + t.Fatalf("endpoint edit retained old gateway headers: %v", err) + } +} + +func TestLegacyLLMEndpointDoesNotCarryGatewayHeaders(t *testing.T) { + skipWithoutDSN(t) + m, err := NewManager(t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { m.Close() }) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + const header = "X-Example-Route: synthetic-route" + oldBase := "http://127.0.0.1:40111/old" + newBase := "http://127.0.0.1:40112/new" + id, err := m.pg.SaveProfile(&db.LLMProfile{ + Name: "default", Format: "bedrock-gateway", Model: "test.model", + BaseURL: oldBase, APIKey: "synthetic-old-token", CustomHeaders: header, + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _, _ = m.pg.Exec(`DELETE FROM llm_profiles WHERE id=$1`, id) }) + if err := m.pg.SetActiveProfile(id); err != nil { + t.Fatal(err) + } + s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir()) + post := func(baseURL, token string) { + t.Helper() + body, _ := json.Marshal(map[string]string{ + "provider": "bedrock-gateway", "model": "test.model", "base_url": baseURL, "api_key": token, + }) + rec := httptest.NewRecorder() + s.setLLM(rec, httptest.NewRequest(http.MethodPost, "/api/llm", bytes.NewReader(body))) + if rec.Code != http.StatusOK { + t.Fatalf("legacy update returned HTTP %d: %s", rec.Code, rec.Body.String()) + } + } + post(oldBase, "") + stored, err := m.pg.ProfileByID(id) + if err != nil || stored.CustomHeaders != header { + t.Fatalf("same-endpoint update lost gateway headers: %v", err) + } + post(oldBase, "synthetic-rotated-token") + stored, err = m.pg.ProfileByID(id) + if err != nil || stored.CustomHeaders != header { + t.Fatalf("same-endpoint token rotation lost gateway headers: %v", err) + } + post(newBase, "synthetic-new-token") + stored, err = m.pg.ProfileByID(id) + if err != nil || stored.BaseURL != newBase || stored.CustomHeaders != "" { + t.Fatalf("endpoint change retained gateway headers: %v", err) + } +} diff --git a/server/dto.go b/server/dto.go index 691d983..3de6307 100644 --- a/server/dto.go +++ b/server/dto.go @@ -644,7 +644,8 @@ type LLMProfileDTO struct { SessionHeaderKey string `json:"session_header_key"` // Custom User-Agent: when non-empty, every outbound LLM request overrides its // User-Agent header with this value. '' = do not override (keep the default UA). - UserAgent string `json:"user_agent"` + UserAgent string `json:"user_agent"` + CustomHeadersSet bool `json:"custom_headers_set"` // This profile's retry overrides (connect / empty response / same-provider safe // window). Per item attempts: 0=inherit the global policy | -1=disable that retry // layer | >0=count; interval_ms: 0=default exponential backoff | >0=use that fixed millisecond interval. All zero = fully follow the global policy, i.e. the historical behavior. @@ -674,6 +675,7 @@ func llmProfileDTO(p *db.LLMProfile) LLMProfileDTO { MaxTokensField: p.MaxTokensField, SessionHeaderKey: p.SessionHeaderKey, UserAgent: p.UserAgent, + CustomHeadersSet: p.CustomHeaders != "", Retry: p.Retry, } } diff --git a/server/env_scrub.go b/server/env_scrub.go index b276f81..5a17591 100644 --- a/server/env_scrub.go +++ b/server/env_scrub.go @@ -5,7 +5,7 @@ import "os" // secretEnv lists the credentials read from the environment only at startup: // ARTEX_PG_DSN and ARTEX_PG_PASSWORD by NewManager (the password is a separate // variable so Docker Compose does not paste it into a URL), ARTEX_SECRET_KEY, -// and the API keys by agent.FromEnv inside New. +// and the LLM API keys and custom headers by agent.FromEnv inside New. // agent.FromEnv also reads ARTEX_LLM_PROXY and ARTEX_LLM_BASE_URL: both are URLs that // can carry credentials in their userinfo (http://user:pass@proxy:3128). The archive // store also captures ARTEX_ARCHIVE_S3_* credentials during New, before the scrub, @@ -19,6 +19,7 @@ import "os" // the environment: the scrub does not hide them from child processes. var secretEnv = []string{ "ARTEX_PG_DSN", "ARTEX_PG_PASSWORD", "ARTEX_SECRET_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY", + "ARTEX_LLM_API_KEY", "ARTEX_LLM_CUSTOM_HEADERS", "ARTEX_LLM_PROXY", "ARTEX_LLM_BASE_URL", "ARTEX_ARCHIVE_S3_ACCESS_KEY_ID", "ARTEX_ARCHIVE_S3_SECRET_ACCESS_KEY", "ARTEX_ARCHIVE_S3_SESSION_TOKEN", "AWS_ACCESS_KEY_ID", "AWS_ACCESS_KEY", "AWS_SECRET_ACCESS_KEY", "AWS_SECRET_KEY", "AWS_SESSION_TOKEN", diff --git a/server/env_scrub_test.go b/server/env_scrub_test.go index db88054..335b6bf 100644 --- a/server/env_scrub_test.go +++ b/server/env_scrub_test.go @@ -39,6 +39,24 @@ func TestScrubSecretEnvHidesSecretsFromChildren(t *testing.T) { } } +func TestScrubSecretEnvClearsBedrockGatewayCredentials(t *testing.T) { + // Preserve every startup secret that ScrubSecretEnv may unset for later tests. + for _, k := range secretEnv { + t.Setenv(k, os.Getenv(k)) + } + // Set these independently of secretEnv so the test catches missing entries. + t.Setenv("ARTEX_LLM_API_KEY", "synthetic-gateway-token") + t.Setenv("ARTEX_LLM_CUSTOM_HEADERS", "X-Example-Secret: synthetic-header-value") + + ScrubSecretEnv() + + for _, k := range []string{"ARTEX_LLM_API_KEY", "ARTEX_LLM_CUSTOM_HEADERS"} { + if _, ok := os.LookupEnv(k); ok { + t.Errorf("%s is still set after ScrubSecretEnv", k) + } + } +} + // New must apply the options it receives. An earlier version accepted // ...Option and never called them, so the binary kept the secrets in the // environment while the unit test above still passed. diff --git a/server/envseal_linux_test.go b/server/envseal_linux_test.go index a11176b..e9fae29 100644 --- a/server/envseal_linux_test.go +++ b/server/envseal_linux_test.go @@ -55,6 +55,9 @@ func TestSealedEnvironmentHandoff(t *testing.T) { "ARTEX_SECRET_KEY": "", "ANTHROPIC_API_KEY": "sk-ant-test", "OPENAI_API_KEY": "=leading-equals", + // The Bedrock gateway reads a bearer token and supports multiline headers. + "ARTEX_LLM_API_KEY": "synthetic-gateway-token", + "ARTEX_LLM_CUSTOM_HEADERS": "X-Example-Secret: synthetic-header-value\nX-Example-Route: demo", // Proxy and endpoint URLs can carry credentials in their userinfo. "ARTEX_LLM_PROXY": "http://proxyuser:proxypass@proxy.internal:3128", "ARTEX_LLM_BASE_URL": "https://apiuser:apipass@llm.internal/v1", diff --git a/server/server.go b/server/server.go index a40ddde..b694e8d 100644 --- a/server/server.go +++ b/server/server.go @@ -432,6 +432,7 @@ func (s *Server) loadLLMConfig() (agent.Config, bool) { cfg.MaxTokens, cfg.MaxTokensField = p.MaxTokens, p.MaxTokensField cfg.SessionHeaderKey = p.SessionHeaderKey cfg.UserAgent = p.UserAgent + cfg.CustomHeaders = p.CustomHeaders s.applyProfileRetry(&cfg, p) // Ollama profiles run keyless (local server); the other formats need a key. if cfg.APIKey == "" && cfg.NeedsAPIKey() { @@ -460,9 +461,15 @@ func (s *Server) saveLLMConfig(cfg agent.Config) error { var sessionHeaderKey string var userAgent string var retry db.RetryOverride + clearCustomHeaders := format != "bedrock-gateway" if profs, _ := s.m.pg.ListProfiles(); profs != nil { for _, p := range profs { if p.Name == "default" { + // A header saved for one gateway must not follow the legacy + // endpoint's default profile to another destination. + if !sameLLMEndpoint(format, cfg.BaseURL, p.Format, p.BaseURL) { + clearCustomHeaders = true + } id, priority, poolExclude, streaming = p.ID, p.Priority, p.PoolExclude, p.Streaming maxTokens, maxTokensField = p.MaxTokens, p.MaxTokensField sessionHeaderKey = p.SessionHeaderKey @@ -478,7 +485,7 @@ func (s *Server) saveLLMConfig(cfg agent.Config) error { ContextWindowK: cfg.ContextWindowK, ThinkingType: cfg.ThinkingType, ReasoningEffort: cfg.ReasoningEffort, IsDefault: true, Priority: priority, PoolExclude: poolExclude, Streaming: streaming, MaxTokens: maxTokens, MaxTokensField: maxTokensField, SessionHeaderKey: sessionHeaderKey, UserAgent: userAgent, - Retry: retry, + Retry: retry, CustomHeaders: cfg.CustomHeaders, ClearCustomHeaders: clearCustomHeaders, }) if err != nil { return err @@ -611,6 +618,7 @@ func (s *Server) loadProfileConfig(id int64) (agent.Config, bool) { cfg.MaxTokens, cfg.MaxTokensField = p.MaxTokens, p.MaxTokensField cfg.SessionHeaderKey = p.SessionHeaderKey cfg.UserAgent = p.UserAgent + cfg.CustomHeaders = p.CustomHeaders s.applyProfileRetry(&cfg, p) if cfg.APIKey == "" && cfg.NeedsAPIKey() { return cfg, false @@ -1498,6 +1506,7 @@ func (s *Server) setLLM(w http.ResponseWriter, r *http.Request) { ContextWindowK int `json:"context_window_k"` ThinkingType string `json:"thinking_type"` ReasoningEffort string `json:"reasoning_effort"` + CustomHeaders string `json:"custom_headers"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { writeErr(w, 400, err.Error()) @@ -1512,18 +1521,26 @@ func (s *Server) setLLM(w http.ResponseWriter, r *http.Request) { cfg.RatePerSecond, cfg.RatePerMinute = req.RatePerSecond, req.RatePerMinute cfg.ThinkingType = req.ThinkingType cfg.ReasoningEffort = req.ReasoningEffort + cfg.CustomHeaders = req.CustomHeaders if k := req.ContextWindowK; k > 0 { // 0 = keep default (200K); cap at 1M if k > 1000 { k = 1000 } cfg.ContextWindowK = k } - // Keyless formats (Ollama) need no key; the others keep/require one. - if cfg.APIKey == "" && cfg.NeedsAPIKey() { - s.cfgMu.Lock() - cfg.APIKey = s.llmCfg.APIKey // keep existing key if not re-entered - s.cfgMu.Unlock() + // A rotated token at the same gateway still uses that gateway's saved + // headers. Neither secret follows a changed endpoint. + s.cfgMu.Lock() + if sameLLMEndpoint(req.Provider, req.BaseURL, s.llmCfg.Provider(), s.llmCfg.BaseURL) { + if cfg.APIKey == "" && cfg.NeedsAPIKey() { + cfg.APIKey = s.llmCfg.APIKey + } + if cfg.CustomHeaders == "" && cfg.Format == agent.FormatBedrockGateway { + cfg.CustomHeaders = s.llmCfg.CustomHeaders + } } + s.cfgMu.Unlock() + // Keyless formats (Ollama) need no key; the others keep/require one. if cfg.APIKey == "" && cfg.NeedsAPIKey() { writeErr(w, 400, "api_key required") return @@ -1564,6 +1581,7 @@ func (s *Server) testLLM(w http.ResponseWriter, r *http.Request) { Streaming *bool `json:"streaming"` // omitted = streaming, the same defaults as when saving a profile SessionHeaderKey string `json:"session_header_key"` // non-empty = the test also sends this custom session header, with a one-off random session id as the value UserAgent string `json:"user_agent"` // non-empty = the test overrides the User-Agent header with this value (mirrors production) + CustomHeaders string `json:"custom_headers"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { writeErr(w, 400, err.Error()) @@ -1645,6 +1663,14 @@ func (s *Server) testLLM(w http.ResponseWriter, r *http.Request) { return } cfg.UserAgent = ua + cfg.CustomHeaders = req.CustomHeaders + if stored != nil && cfg.CustomHeaders == "" && sameLLMEndpoint(req.Provider, req.BaseURL, stored.Format, stored.BaseURL) { + cfg.CustomHeaders = stored.CustomHeaders + } + if _, err := agent.ParseBedrockGatewayHeaders(cfg.CustomHeaders); err != nil { + writeErr(w, 400, err.Error()) + return + } // Keyless formats (Ollama) skip the key resolution entirely. if cfg.NeedsAPIKey() { // API key resolution precedence: form input > the named profile's stored key > the global config's key. @@ -1670,6 +1696,9 @@ func (s *Server) testLLM(w http.ResponseWriter, r *http.Request) { if global.APIKey != "" { if sameLLMEndpoint(req.Provider, req.BaseURL, global.Provider(), global.BaseURL) { cfg.APIKey = global.APIKey + if cfg.CustomHeaders == "" { + cfg.CustomHeaders = global.CustomHeaders + } } else { withheld = true } diff --git a/server/server_mgmt.go b/server/server_mgmt.go index 732f99a..701c7e8 100644 --- a/server/server_mgmt.go +++ b/server/server_mgmt.go @@ -2121,8 +2121,10 @@ func (s *Server) pgSaveProfile(w http.ResponseWriter, r *http.Request) { // would get wrong — legacy/partial clients that never send it stay streaming. var body struct { db.LLMProfile - APIKey string `json:"api_key"` - Streaming *bool `json:"streaming"` + APIKey string `json:"api_key"` + CustomHeaders string `json:"custom_headers"` + ClearCustomHeaders bool `json:"clear_custom_headers"` + Streaming *bool `json:"streaming"` } if err := decode(w, r, &body); err != nil { writeErr(w, 400, err.Error()) @@ -2130,6 +2132,35 @@ func (s *Server) pgSaveProfile(w http.ResponseWriter, r *http.Request) { } p := body.LLMProfile p.APIKey = body.APIKey + p.CustomHeaders = body.CustomHeaders + p.ClearCustomHeaders = body.ClearCustomHeaders + if p.Format == "bedrock-gateway" { + if _, err := agent.ParseBedrockGatewayHeaders(p.CustomHeaders); err != nil { + writeErr(w, 400, err.Error()) + return + } + if p.ID != 0 { + stored, err := pg.ProfileByID(p.ID) + if err != nil { + writeErr(w, 500, err.Error()) + return + } + if stored != nil && !sameLLMEndpoint(p.Format, p.BaseURL, stored.Format, stored.BaseURL) { + if strings.TrimSpace(p.APIKey) == "" { + writeErr(w, 400, "enter the bearer token when changing the Bedrock gateway endpoint") + return + } + if p.CustomHeaders == "" { + p.ClearCustomHeaders = true + } + } + } + } else if p.CustomHeaders != "" { + writeErr(w, 400, "custom headers require the Bedrock gateway format") + return + } else { + p.ClearCustomHeaders = true + } p.Streaming = body.Streaming == nil || *body.Streaming // The list returns the proxy masked: the placeholder sent back keeps the // stored proxy and is never stored itself. @@ -2158,6 +2189,25 @@ func (s *Server) pgSaveProfile(w http.ResponseWriter, r *http.Request) { return } p.UserAgent = ua + if p.Format == "bedrock-gateway" { + validate := agent.ConfigFrom(p.Format, p.Model, p.BaseURL, p.APIKey, p.Proxy) + validate.CustomHeaders = p.CustomHeaders + if p.ID != 0 { + stored, _ := pg.ProfileByID(p.ID) + if stored != nil && sameLLMEndpoint(p.Format, p.BaseURL, stored.Format, stored.BaseURL) { + if validate.APIKey == "" { + validate.APIKey = stored.APIKey + } + if validate.CustomHeaders == "" && !p.ClearCustomHeaders { + validate.CustomHeaders = stored.CustomHeaders + } + } + } + if _, err := validate.NewProvider(); err != nil { + writeErr(w, 400, err.Error()) + return + } + } id, err := pg.SaveProfile(&p) if err != nil { writeErr(w, 500, err.Error()) @@ -2592,6 +2642,10 @@ func (s *Server) pgListModels(w http.ResponseWriter, r *http.Request) { writeErr(w, 400, err.Error()) return } + if strings.TrimSpace(req.Provider) == "bedrock-gateway" { + writeJSON(w, 200, map[string]any{"ok": false, "error": "enter the Bedrock model ID manually; this gateway has no model-list endpoint"}) + return + } // Resolve API key: form input > profile stored key. The stored key is only // sent to the endpoint it was saved for, since base_url comes from the form. apiKey := strings.TrimSpace(req.APIKey) diff --git a/web/src/app/(main)/system/llm/page.tsx b/web/src/app/(main)/system/llm/page.tsx index 6b92300..52ac7c9 100644 --- a/web/src/app/(main)/system/llm/page.tsx +++ b/web/src/app/(main)/system/llm/page.tsx @@ -67,7 +67,7 @@ const MAX_TOKENS_FIELD_HINTS: Record = { }; // LLM profile formats. The default in the create form is "anthropic"; "ollama" is the // keyless local-server format (base URL defaults to http://127.0.0.1:11434/v1). -type ProfileFormat = "anthropic" | "openai" | "openai-responses" | "ollama"; +type ProfileFormat = "anthropic" | "openai" | "openai-responses" | "ollama" | "bedrock-gateway"; const OLLAMA_DEFAULT_BASE_URL = "http://127.0.0.1:11434/v1"; const EFFORT_LEVELS: { value: string; label: string }[] = [ { value: NONE, label: t("Not sent (default)") }, @@ -354,6 +354,8 @@ function ProfileSheet({ const [maxTokensField, setMaxTokensField] = React.useState(NONE); // which field name carries the cap; NONE = max_tokens const [sessionHeaderKey, setSessionHeaderKey] = React.useState(""); // custom session header name; empty = not sent const [userAgent, setUserAgent] = React.useState(""); // custom User-Agent; empty = keep the default UA + const [customHeaders, setCustomHeaders] = React.useState(""); + const [clearCustomHeaders, setClearCustomHeaders] = React.useState(false); const [retry, setRetry] = React.useState(ZERO_OVERRIDE); // retry override for this profile; all 0 = follow the global const [testing, setTesting] = React.useState(false); const [saving, setSaving] = React.useState(false); @@ -368,7 +370,7 @@ function ProfileSheet({ if (!open) return; setName(profile?.name ?? ""); setFormat( - profile?.format === "openai" || profile?.format === "openai-responses" || profile?.format === "ollama" + profile?.format === "openai" || profile?.format === "openai-responses" || profile?.format === "ollama" || profile?.format === "bedrock-gateway" ? profile.format : "anthropic", ); @@ -387,6 +389,8 @@ function ProfileSheet({ setMaxTokensField(fromStore(profile?.max_tokens_field)); setSessionHeaderKey(profile?.session_header_key ?? ""); setUserAgent(profile?.user_agent ?? ""); + setCustomHeaders(""); + setClearCustomHeaders(false); setRetry(profile?.retry ?? ZERO_OVERRIDE); setApiKey(""); setKeyHint(profile?.api_key_hint ?? ""); @@ -444,6 +448,7 @@ function ProfileSheet({ streaming, sessionHeaderKey.trim(), userAgent.trim(), + customHeaders, ); // Show the reply too: only when the model demonstrably spoke is this the same as working inside a session. if (r.ok) @@ -488,6 +493,8 @@ function ProfileSheet({ max_tokens_field: format === "openai" ? toStore(maxTokensField) : "", session_header_key: sessionHeaderKey.trim(), user_agent: userAgent.trim(), + custom_headers: format === "bedrock-gateway" ? customHeaders : "", + clear_custom_headers: clearCustomHeaders, retry, }); if (isNew) toast.success(t('Created: {name} (use "Set as active" on its card to enable it)', { name: name.trim() })); @@ -505,8 +512,16 @@ function ProfileSheet({ } let keyPlaceholder = "sk-…"; + let keyLabel = "API Key"; + let basePlaceholder = "https://api.openai.com/v1"; if (format === "ollama") { keyPlaceholder = t("optional — a local Ollama server runs keyless"); + keyLabel = t("API Key (optional for Ollama)"); + basePlaceholder = OLLAMA_DEFAULT_BASE_URL; + } else if (format === "bedrock-gateway") { + keyLabel = "Bearer token"; + basePlaceholder = "https://gateway.example.com/bedrock"; + if (keyHint) keyPlaceholder = t("Set ({hint}); leave empty to keep it", { hint: keyHint }); } else if (keyHint) { keyPlaceholder = t("Set ({hint}); leave empty to keep it", { hint: keyHint }); } @@ -555,6 +570,7 @@ function ProfileSheet({ OpenAI (Chat Completions) OpenAI (Responses API) {t("Ollama (local, no key needed)")} + Bedrock gateway @@ -586,7 +602,7 @@ function ProfileSheet({ variant="outline" size="icon" className="shrink-0" - disabled={loadingModels} + disabled={loadingModels || format === "bedrock-gateway"} onClick={loadModels} title={t("Load available models from the API")} > @@ -634,16 +650,25 @@ function ProfileSheet({
- + setBaseUrl(e.target.value)} />
+ {format === "bedrock-gateway" && ( +
+ +