Skip to content

armgit / ARTEX

Public Imported from GitHub
0

ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)

fix: bind Bedrock headers to gateway and redact errors

James Khor3b367c143344
diff --git a/agent/bedrock_gateway.go b/agent/bedrock_gateway.go
index c970c52..c45af0e 100644
--- a/agent/bedrock_gateway.go
+++ b/agent/bedrock_gateway.go
@@ -149,9 +149,37 @@ func (t *bedrockGatewayTransport) RoundTrip(req *http.Request) (*http.Response,
q.Header[name] = append([]string(nil), values...)
}
resp, err := t.base.RoundTrip(q)
- if err != nil || resp.StatusCode < 200 || resp.StatusCode >= 300 || !streaming {
+ 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 &copy, 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")
@@ -171,7 +199,7 @@ func (t *bedrockGatewayTransport) RoundTrip(req *http.Request) (*http.Response,
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))
+ 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" {
diff --git a/agent/bedrock_gateway_test.go b/agent/bedrock_gateway_test.go
index 343698e..381d560 100644
--- a/agent/bedrock_gateway_test.go
+++ b/agent/bedrock_gateway_test.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/base64"
"encoding/json"
+ "io"
"net/http"
"net/http/httptest"
"strings"
@@ -105,7 +106,7 @@ func TestBedrockGatewayCompleteAndStream(t *testing.T) {
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"}`)})
+ _ = 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", "")
@@ -117,6 +118,9 @@ func TestBedrockGatewayStreamExceptionIsAnError(t *testing.T) {
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 {
@@ -124,6 +128,55 @@ func TestBedrockGatewayStreamExceptionIsAnError(t *testing.T) {
}
}
+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) }))
diff --git a/agent/provider.go b/agent/provider.go
index ec85b8e..2242d3c 100644
--- a/agent/provider.go
+++ b/agent/provider.go
@@ -614,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)
@@ -684,6 +694,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/db/bedrock_gateway_test.go b/db/bedrock_gateway_test.go
index cc8717a..d982ef6 100644
--- a/db/bedrock_gateway_test.go
+++ b/db/bedrock_gateway_test.go
@@ -58,4 +58,14 @@ func TestBedrockGatewayHeadersEncryptedAndWriteOnly(t *testing.T) {
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 d88c029..1e7c9e9 100644
--- a/db/config.go
+++ b/db/config.go
@@ -203,62 +203,50 @@ 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 {
+ // 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)
}
- if err == nil {
- err = d.saveProfileHeaders(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)
}
- 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`,
+ _, 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)
}
- 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/server/bedrock_gateway_test.go b/server/bedrock_gateway_test.go
index d745c96..af4a625 100644
--- a/server/bedrock_gateway_test.go
+++ b/server/bedrock_gateway_test.go
@@ -81,4 +81,66 @@ func TestBedrockGatewaySavedProfileAndConnection(t *testing.T) {
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/server.go b/server/server.go
index 895771f..9a50b51 100644
--- a/server/server.go
+++ b/server/server.go
@@ -459,9 +459,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
@@ -477,7 +483,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, CustomHeaders: cfg.CustomHeaders,
+ Retry: retry, CustomHeaders: cfg.CustomHeaders, ClearCustomHeaders: clearCustomHeaders,
})
if err != nil {
return err
@@ -1511,17 +1517,19 @@ func (s *Server) setLLM(w http.ResponseWriter, r *http.Request) {
}
cfg.ContextWindowK = k
}
- // Keyless formats (Ollama) need no key; the others keep/require one.
- if cfg.APIKey == "" && cfg.NeedsAPIKey() {
- s.cfgMu.Lock()
- if sameLLMEndpoint(req.Provider, req.BaseURL, s.llmCfg.Provider(), s.llmCfg.BaseURL) {
+ // 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.CustomHeaders = s.llmCfg.CustomHeaders
- }
}
- s.cfgMu.Unlock()
+ 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