ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)
Go aiai-agentsautonomous-agentsbug-bountydockergolanglinuxllmmcpnextjspenetration-testingpentestpostgresqlreareactred-teamsecuritysecurity-automationsqlitetypescript
feat: add bearer-authenticated Bedrock gateway profiles
James Khorb1e419ba2c88
diff --git a/README.md b/README.mdindex 492701f..9594b90 100644--- a/README.md+++ b/README.md@@ -488,7 +488,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@@ -504,6 +504,24 @@ catalog (`GET /v1/models`) and pick a model; models the provider adds later appenext refresh. For example, [NotHoly](https://notholy.com) (offensive-security models) usesbase 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` tostore cold task packages in an S3-compatible bucket and release their localpackage space after verification. Existing local archives remain usable. See@@ -719,7 +737,7 @@ gunzip -c backups/artex-db-<timestamp>.sql.gz | docker compose exec -T postgrespsql -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, thecapture-proxy rewrite rules) areencrypted in the database with the key in `keys/secret.key` (generated at first start, mode 0600,@@ -906,7 +924,7 @@ Please report vulnerabilities privately through GitHub Security Advisories; seeOperational 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 trafficevidence snapshots are encryptedwith AES-256-GCM using `keys/secret.key` (or `ARTEX_SECRET_KEY`). ARTEX refuses to start whendiff --git a/agent/bedrock_gateway.go b/agent/bedrock_gateway.gonew file mode 100644index 0000000..c970c52--- /dev/null+++ b/agent/bedrock_gateway.go@@ -0,0 +1,240 @@+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 || resp.StatusCode < 200 || resp.StatusCode >= 300 || !streaming {+ return resp, err+ }+ 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(fmt.Errorf("Bedrock gateway stream exception: %s", frame.Payload))+ 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.gonew file mode 100644index 0000000..46acc48--- /dev/null+++ b/agent/bedrock_gateway_test.go@@ -0,0 +1,181 @@+package agent++import (+ "context"+ "encoding/base64"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "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 int+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ calls+++ 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 != 2 {+ t.Fatalf("stream = %q, tool = %q %q, calls = %d", streamed, toolName, toolInput, calls)+ }+}++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 failure"}`)})+ }))+ 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 !sawError {+ t.Fatal("stream exception was treated as success")+ }+}++func TestBedrockGatewayDoesNotFollowRedirectWithToken(t *testing.T) {+ redirected := false+ other := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { redirected = 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 {+ 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.goindex 96d39a6..ec85b8e 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.FormatAnthropicc.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,diff --git a/agent/provider_env_test.go b/agent/provider_env_test.goindex 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.gonew file mode 100644index 0000000..cc8717a--- /dev/null+++ b/db/bedrock_gateway_test.go@@ -0,0 +1,61 @@+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")+ }+}diff --git a/db/config.go b/db/config.goindex 983fa7f..d88c029 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,6 +203,11 @@ func (d *DB) SaveProfile(p *LLMProfile) (int64, error) {if err != nil {return 0, err}+ if p.CustomHeaders != "" || p.ClearCustomHeaders {+ if _, err := sealSecret(colLLMHeaders, p.CustomHeaders); err != nil {+ return 0, err+ }+ }r := p.Retry.Clamped()if p.ID == 0 {var id int64@@ -208,6 +218,9 @@ VALUES ($1,$2,NULLIF($3,''),NULLIF($4,''),$5,NULLIF($6,''),NULLIF($7,''),$8,$9,$if err == nil {_, err = d.saveProfilePrices(id, p)}+ if err == nil {+ err = d.saveProfileHeaders(id, p)+ }return id, err}if p.APIKey == "" {@@ -217,6 +230,9 @@ VALUES ($1,$2,NULLIF($3,''),NULLIF($4,''),$5,NULLIF($6,''),NULLIF($7,''),$8,$9,$if err == nil {_, err = d.saveProfilePrices(p.ID, p)}+ if err == nil {+ err = d.saveProfileHeaders(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`,@@ -225,9 +241,24 @@ VALUES ($1,$2,NULLIF($3,''),NULLIF($4,''),$5,NULLIF($6,''),NULLIF($7,''),$8,$9,$if err == nil {_, err = d.saveProfilePrices(p.ID, p)}+ if err == nil {+ err = d.saveProfileHeaders(p.ID, p)+ }return p.ID, err}+func (d *DB) saveProfileHeaders(id int64, p *LLMProfile) error {+ if p.CustomHeaders == "" && !p.ClearCustomHeaders {+ return nil+ }+ value, err := sealSecret(colLLMHeaders, p.CustomHeaders)+ if err != nil {+ return err+ }+ _, err = d.Exec(`UPDATE llm_profiles SET custom_headers=$1 WHERE id=$2`, value, id)+ return err+}+// saveProfilePrices writes the cost-ledger columns (kept out of the three main// statements so the pricing surface stays one small, auditable write).func (d *DB) saveProfilePrices(id int64, p *LLMProfile) (sql.Result, error) {diff --git a/db/migrate_test.go b/db/migrate_test.goindex 0227d96..9a68399 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)diff --git a/db/migrations/0014_bedrock_gateway_profiles.sql b/db/migrations/0014_bedrock_gateway_profiles.sqlnew file mode 100644index 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.sqlindex 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 NULLALTER 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_checkALTER 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'sdiff --git a/db/secrets.go b/db/secrets.goindex 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.<key>".diff --git a/go.mod b/go.modindex b95f4b9..8813069 100644--- a/go.mod+++ b/go.mod@@ -5,6 +5,7 @@ go 1.26.11require (github.com/Autumn-27/norma v0.4.11github.com/aws/aws-sdk-go-v2 v1.47.5+ github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.25github.com/aws/aws-sdk-go-v2/config v1.33.13github.com/aws/aws-sdk-go-v2/credentials v1.20.13github.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 // indirectgithub.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect- github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.25 // indirectgithub.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5 // indirectgithub.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 // indirectgithub.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 // indirectdiff --git a/server/bedrock_gateway_test.go b/server/bedrock_gateway_test.gonew file mode 100644index 0000000..d745c96--- /dev/null+++ b/server/bedrock_gateway_test.go@@ -0,0 +1,84 @@+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")+ }+}diff --git a/server/dto.go b/server/dto.goindex 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/server.go b/server/server.goindex 241ad17..895771f 100644--- a/server/server.go+++ b/server/server.go@@ -430,6 +430,7 @@ func (s *Server) loadLLMConfig() (agent.Config, bool) {cfg.MaxTokens, cfg.MaxTokensField = p.MaxTokens, p.MaxTokensFieldcfg.SessionHeaderKey = p.SessionHeaderKeycfg.UserAgent = p.UserAgent+ cfg.CustomHeaders = p.CustomHeaderss.applyProfileRetry(&cfg, p)// Ollama profiles run keyless (local server); the other formats need a key.if cfg.APIKey == "" && cfg.NeedsAPIKey() {@@ -476,7 +477,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,})if err != nil {return err@@ -609,6 +610,7 @@ func (s *Server) loadProfileConfig(id int64) (agent.Config, bool) {cfg.MaxTokens, cfg.MaxTokensField = p.MaxTokens, p.MaxTokensFieldcfg.SessionHeaderKey = p.SessionHeaderKeycfg.UserAgent = p.UserAgent+ cfg.CustomHeaders = p.CustomHeaderss.applyProfileRetry(&cfg, p)if cfg.APIKey == "" && cfg.NeedsAPIKey() {return cfg, false@@ -1487,6 +1489,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())@@ -1501,6 +1504,7 @@ func (s *Server) setLLM(w http.ResponseWriter, r *http.Request) {cfg.RatePerSecond, cfg.RatePerMinute = req.RatePerSecond, req.RatePerMinutecfg.ThinkingType = req.ThinkingTypecfg.ReasoningEffort = req.ReasoningEffort+ cfg.CustomHeaders = req.CustomHeadersif k := req.ContextWindowK; k > 0 { // 0 = keep default (200K); cap at 1Mif k > 1000 {k = 1000@@ -1510,7 +1514,12 @@ func (s *Server) setLLM(w http.ResponseWriter, r *http.Request) {// 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+ if sameLLMEndpoint(req.Provider, req.BaseURL, s.llmCfg.Provider(), s.llmCfg.BaseURL) {+ cfg.APIKey = s.llmCfg.APIKey+ if cfg.CustomHeaders == "" {+ cfg.CustomHeaders = s.llmCfg.CustomHeaders+ }+ }s.cfgMu.Unlock()}if cfg.APIKey == "" && cfg.NeedsAPIKey() {@@ -1553,6 +1562,7 @@ func (s *Server) testLLM(w http.ResponseWriter, r *http.Request) {Streaming *bool `json:"streaming"` // omitted = streaming, the same defaults as when saving a profileSessionHeaderKey string `json:"session_header_key"` // non-empty = the test also sends this custom session header, with a one-off random session id as the valueUserAgent 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())@@ -1634,6 +1644,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.@@ -1659,6 +1677,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.goindex 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.LLMProfilep.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.tsxindex 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<string, string> = {};// 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_tokensconst [sessionHeaderKey, setSessionHeaderKey] = React.useState(""); // custom session header name; empty = not sentconst [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<LLMRetryOverride>(ZERO_OVERRIDE); // retry override for this profile; all 0 = follow the globalconst [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({<SelectItem value="openai">OpenAI (Chat Completions)</SelectItem><SelectItem value="openai-responses">OpenAI (Responses API)</SelectItem><SelectItem value="ollama">{t("Ollama (local, no key needed)")}</SelectItem>+ <SelectItem value="bedrock-gateway">Bedrock gateway</SelectItem></SelectContent></Select></div>@@ -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({</div><div className="grid gap-2">- <Label htmlFor="p-base-url">{t("Base URL (optional)")}</Label>+ <Label htmlFor="p-base-url">{format === "bedrock-gateway" ? "Gateway base URL (required)" : t("Base URL (optional)")}</Label><Inputid="p-base-url"className="font-mono"- placeholder={format === "ollama" ? OLLAMA_DEFAULT_BASE_URL : "https://api.openai.com/v1"}+ placeholder={basePlaceholder}value={baseUrl}onChange={(e) => setBaseUrl(e.target.value)}/></div>+ {format === "bedrock-gateway" && (+ <div className="grid gap-2">+ <Label htmlFor="p-custom-headers">Custom gateway headers (optional)</Label>+ <textarea id="p-custom-headers" className="min-h-20 w-full rounded-md border bg-background px-3 py-2 font-mono text-sm" placeholder="X-Example-Route: demo" value={customHeaders} onChange={(e) => { setCustomHeaders(e.target.value); setClearCustomHeaders(false); }} spellCheck={false} />+ <p className="text-muted-foreground text-xs">One Name: Value per line. Values are encrypted and cannot be viewed after saving. Leave blank to keep saved headers.</p>+ {profile?.custom_headers_set && <label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={clearCustomHeaders} onChange={(e) => { setClearCustomHeaders(e.target.checked); if (e.target.checked) setCustomHeaders(""); }} />Clear saved custom headers</label>}+ </div>+ )}+<div className="grid gap-2"><Label htmlFor="p-proxy">{t("Proxy (optional)")}</Label><Input@@ -698,7 +723,7 @@ function ProfileSheet({<div className="grid gap-2"><Label htmlFor="p-api-key">- {format === "ollama" ? t("API Key (optional for Ollama)") : "API Key"}+ {keyLabel}</Label><Inputid="p-api-key"diff --git a/web/src/lib/api.ts b/web/src/lib/api.tsindex 790be32..69e53c2 100644--- a/web/src/lib/api.ts+++ b/web/src/lib/api.ts@@ -1120,6 +1120,7 @@ export const api = {streaming = true, // test with the profile's real streaming mode so "streaming works, non-streaming does not" never leaks into conversationssession_header_key = "", // non-empty = the test request also carries this custom session header (value is a one-off session id)user_agent = "", // non-empty = the test overrides the User-Agent header with this value+ custom_headers = "",) =>// reply = the model's actual reply (truncated); the backend marks a profile that replies with nothing as failedpost<{ ok: boolean; error?: string; latency_ms?: number; model?: string; reply?: string }>("/llm/test", {@@ -1134,6 +1135,7 @@ export const api = {streaming,session_header_key,user_agent,+ custom_headers,}),llmProfiles: () => get<{ profiles: LLMProfile[] }>("/llm/profiles").then((r) => arr(r.profiles)),saveLLMProfile: (p: {@@ -1156,6 +1158,8 @@ export const api = {max_tokens_field?: string; // ""=max_tokens (default) | "max_completion_tokens" (openai format only)session_header_key?: string; // non-empty = send this HTTP header on every request, value = the current session id; "" = not sentuser_agent?: string; // non-empty = override the User-Agent header on every request; "" = keep the default UA+ custom_headers?: string; // static Bedrock gateway headers; values are write-only+ clear_custom_headers?: boolean;retry?: LLMRetryOverride; // this profile's retry override; all zeros = follow the global retry policy}) => post<{ id: number }>("/llm/profiles", p),deleteLLMProfile: (id: string) => del<{ deleted: number }>(`/llm/profiles/${id}`),diff --git a/web/src/lib/types.ts b/web/src/lib/types.tsindex e8b23a2..71b4a8b 100644--- a/web/src/lib/types.ts+++ b/web/src/lib/types.ts@@ -1154,7 +1154,7 @@ export interface NotificationDelivery {export interface LLMProfile {id: string;name: string;- format: "openai" | "anthropic" | "openai-responses" | "ollama";+ format: "openai" | "anthropic" | "openai-responses" | "ollama" | "bedrock-gateway";base_url?: string;proxy?: string;model: string;@@ -1189,6 +1189,7 @@ export interface LLMProfile {session_header_key?: string;// 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).user_agent?: string;+ custom_headers_set?: boolean;// This profile's retry overrides (connect / empty response / same-provider safety window). Empty / all zeros = follow the global policy.retry?: LLMRetryOverride;}