From 90274e48ddee9ddc172a610912d17ab42c0ab8da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E4=BA=91=E5=91=A8?= <154221037+YunzhouLi-hub@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:00:32 +0800 Subject: [PATCH 01/32] build: pin base images to multi-platform digests --- CONTRIBUTING.md | 8 ++++++++ Dockerfile | 8 ++++---- docker-compose.yml | 2 +- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cc70af0..10a7d19 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,6 +7,14 @@ - **Describe the change.** State the problem, the behavior change and what you tested. A pull request with no description is a request for changes. - **Provider support stays generic.** Any OpenAI- or Anthropic-compatible endpoint works through a model profile; provider convenience goes in as a neutral preset (name and base URL) or a docs recipe, with no vendor logos, promotional codes, baked vendor endpoints, or vendor-specific environment variables. A new wire format needs a schema migration, a profile save/load test, and a live connection test. +## Updating Docker image pins + +The Dockerfile and the PostgreSQL service in `docker-compose.yml` use a readable tag followed +by a digest. Review these pins regularly for upstream security updates. When refreshing a pin, +run `docker buildx imagetools inspect :` and use the top-level index digest. Check +that the index includes `linux/amd64` and `linux/arm64` before proposing the update. Record the +old and new digests in the PR so reviewers can verify the change. + ## Issues - One problem per issue. Include the version or commit, what you ran and what you expected. diff --git a/Dockerfile b/Dockerfile index 183f8cb..f7db0d8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,7 +13,7 @@ # ---------------------------------------------------------------- frontend --- # Pinned to the Node 22 line the CI/release workflows use. On the build platform # only; the frontend static export is architecture-independent. -FROM --platform=$BUILDPLATFORM node:22-bookworm-slim AS web +FROM --platform=$BUILDPLATFORM node:22-bookworm-slim@sha256:e9f565d32859f0cbfb52125eafe8be39390f24dac302dc3cdf566e8ba3ab21ee AS web WORKDIR /src/web COPY web/package.json web/package-lock.json ./ RUN npm ci --ignore-scripts @@ -24,7 +24,7 @@ RUN npm run build:static # Pinned to the Go 1.26 line (matches go.mod and the release binaries job). The # binary is CGO-free, so this stage runs on the build platform and cross-compiles # to $TARGETARCH without QEMU. -FROM --platform=$BUILDPLATFORM golang:1.26-bookworm AS build +FROM --platform=$BUILDPLATFORM golang:1.26-bookworm@sha256:dc40a13b61304647ed7e5d581d246b86413dfc29d63c6d018310feb93cd98fc0 AS build WORKDIR /src COPY go.mod go.sum ./ RUN go mod download @@ -52,7 +52,7 @@ RUN ARTEX_SKIP_FRONTEND=1 \ # release channel as the archive, so it catches corrupted or swapped downloads and # moved tags, not a compromised publisher. sqlmap has no release binaries: it is a # shallow clone of a pinned tag, checked against the expected commit. -FROM --platform=$BUILDPLATFORM debian:bookworm-slim AS tools +FROM --platform=$BUILDPLATFORM debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc AS tools ARG TARGETARCH ARG NUCLEI_VERSION=v3.11.1 ARG HTTPX_VERSION=v1.12.0 @@ -103,7 +103,7 @@ RUN set -eux; \ rm -rf /opt/sqlmap/.git # ---------------------------------------------------------------- runtime --- -FROM python:3.12-slim-bookworm +FROM python:3.12-slim-bookworm@sha256:935c3c5b12357a7e10caa9c1e6ca5692344d97cf229832ef584be2cec9fc03df ARG TARGETARCH # Common tools: ripgrep / curl / vim, plus a set of recon staples (add/remove as needed). RUN apt-get update && apt-get install -y --no-install-recommends \ diff --git a/docker-compose.yml b/docker-compose.yml index 00e28c5..042aab5 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,6 +1,6 @@ services: postgres: - image: postgres:16-alpine + image: postgres:16-alpine@sha256:1d5b02d3a9941fbd52437db4107f8c52d6297dac553ca1e5c299ebb3756b4857 environment: POSTGRES_USER: ${POSTGRES_USER:-artex} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Please set POSTGRES_PASSWORD in .env} From 00def89a66dd057d36872ed6be1f8c6a62da0dc5 Mon Sep 17 00:00:00 2001 From: Coff0xc <184964491+Coff0xc@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:55:14 +0000 Subject: [PATCH 02/32] fix(web): clear and mask test-account passwords on the task form Creating a task left the credential rows in the form, and the password input was plain text. The rows are cleared after a successful create, and the password field is masked. --- CHANGELOG.md | 1 + web/src/app/(main)/function/tasks/page.tsx | 3 +++ 2 files changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5af6fb6..e2669b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project are documented in this file. The format is b ### Fixed +- **Task form does not keep test-account secrets on screen**: after a task is created the credential rows are cleared, and the password field is masked. - **Docker Compose database passwords with URL-special characters**: `docker-compose.yml` no longer pastes `POSTGRES_PASSWORD` into `ARTEX_PG_DSN`. The server builds the URL from `ARTEX_PG_HOST`, `ARTEX_PG_PORT`, `ARTEX_PG_USER`, `ARTEX_PG_PASSWORD`, `ARTEX_PG_DBNAME` and `ARTEX_PG_SSLMODE`, percent-encoding the user and password, so `/`, `?`, `%`, `@`, `:` and spaces connect. An explicit `ARTEX_PG_DSN` still wins and is not rewritten. `ARTEX_PG_PASSWORD` is removed from the environment with the other startup secrets (#450). ## [0.7.0] - 2026-11-21 diff --git a/web/src/app/(main)/function/tasks/page.tsx b/web/src/app/(main)/function/tasks/page.tsx index d6ac89a..27345fe 100644 --- a/web/src/app/(main)/function/tasks/page.tsx +++ b/web/src/app/(main)/function/tasks/page.tsx @@ -3273,6 +3273,7 @@ function CreateTaskSheet({ setSeedFirstIntent(false); setCoverageEnabled(true); setInterceptRules([]); + setCredentials([]); setUploadCount(0); draftIdRef.current = ""; setOpen(false); @@ -3457,6 +3458,8 @@ function CreateTaskSheet({ onChange={(e) => setCredentials((prev) => prev.map((x, j) => (j === i ? { ...x, username: e.target.value } : x)))} /> setCredentials((prev) => prev.map((x, j) => (j === i ? { ...x, password: e.target.value } : x)))} From b1e419ba2c88ed3643d7b8c70dc1dac3982dc218 Mon Sep 17 00:00:00 2001 From: James Khor Date: Sun, 22 Nov 2026 18:27:43 +0800 Subject: [PATCH 03/32] feat: add bearer-authenticated Bedrock gateway profiles --- README.md | 24 +- agent/bedrock_gateway.go | 240 ++++++++++++++++++ agent/bedrock_gateway_test.go | 181 +++++++++++++ agent/provider.go | 27 ++ agent/provider_env_test.go | 17 ++ db/bedrock_gateway_test.go | 61 +++++ db/config.go | 57 ++++- db/migrate_test.go | 4 +- .../0014_bedrock_gateway_profiles.sql | 5 + db/schema.sql | 8 +- db/secrets.go | 3 +- go.mod | 2 +- server/bedrock_gateway_test.go | 84 ++++++ server/dto.go | 4 +- server/server.go | 25 +- server/server_mgmt.go | 58 ++++- web/src/app/(main)/system/llm/page.tsx | 37 ++- web/src/lib/api.ts | 4 + web/src/lib/types.ts | 3 +- 19 files changed, 809 insertions(+), 35 deletions(-) create mode 100644 agent/bedrock_gateway.go create mode 100644 agent/bedrock_gateway_test.go create mode 100644 db/bedrock_gateway_test.go create mode 100644 db/migrations/0014_bedrock_gateway_profiles.sql create mode 100644 server/bedrock_gateway_test.go diff --git a/README.md b/README.md index 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 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 @@ -719,7 +737,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, @@ -906,7 +924,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..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.go new file mode 100644 index 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.go index 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.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, 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..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.go index 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.go index 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.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 b95f4b9..8813069 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..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.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/server.go b/server/server.go index 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.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() { @@ -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.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 @@ -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.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 @@ -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 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()) @@ -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.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" && ( +
+ +