From ba04751f2a7f87ebbed5de3f8171dc60d7b30a8d Mon Sep 17 00:00:00 2001 From: BaaRai <130491490+BaaRai@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:35:38 +0100 Subject: [PATCH] security: bind stored LLM keys to their route, bearer-only sessions, SSRF and log hardening --- config/config.go | 27 +++- config/redact_escape_test.go | 39 ++++- db/chat_bridge_chat_type_backfill_test.go | 96 +++++++++++ db/migrate_test.go | 5 +- .../0020_chat_bridge_chat_type_backfill.sql | 16 ++ docs/OPS.md | 5 + mcphttp/client.go | 6 +- mcphttp/snippet_quote_test.go | 31 ++++ mcphttp/ssrf.go | 37 ++++- mcphttp/ssrf_test.go | 63 ++++++++ server/assembly.go | 11 +- server/auth.go | 49 ++---- server/csrf_test.go | 150 ++++++++--------- server/llm_route_rekey_test.go | 153 ++++++++++++++++++ server/mcp_log_quote_test.go | 31 ++++ server/secrets_api_test.go | 15 +- server/server.go | 8 +- server/server_mgmt.go | 41 +++-- web/scripts/auth.test.mjs | 16 ++ web/src/app/(main)/system/logs/page.tsx | 6 +- web/src/lib/auth.ts | 7 +- 21 files changed, 643 insertions(+), 169 deletions(-) create mode 100644 db/chat_bridge_chat_type_backfill_test.go create mode 100644 db/migrations/0020_chat_bridge_chat_type_backfill.sql create mode 100644 mcphttp/snippet_quote_test.go create mode 100644 server/llm_route_rekey_test.go create mode 100644 server/mcp_log_quote_test.go diff --git a/config/config.go b/config/config.go index a79e1aa7..c4691f89 100644 --- a/config/config.go +++ b/config/config.go @@ -254,7 +254,15 @@ func (d Database) buildDSN() string { return u.String() } -var libpqPassword = regexp.MustCompile(`(?i)\bpassword\s*=\s*`) +// libpqPassword matches the libpq secret keywords: password, and sslpassword +// (the passphrase of an encrypted client key), in any letter case. +var libpqPassword = regexp.MustCompile(`(?i)\b((?:ssl)?password)\s*=\s*`) + +// isDSNSecretParam reports whether a URL query parameter carries a secret. +func isDSNSecretParam(key string) bool { + k := strings.ToLower(key) + return k == "password" || k == "sslpassword" +} // redactKeywordPasswords consumes escaped characters as part of the password, // including escaped whitespace and quotes. An unterminated quoted value consumes @@ -262,13 +270,13 @@ var libpqPassword = regexp.MustCompile(`(?i)\bpassword\s*=\s*`) func redactKeywordPasswords(dsn string) string { var out strings.Builder for { - loc := libpqPassword.FindStringIndex(dsn) + loc := libpqPassword.FindStringSubmatchIndex(dsn) if loc == nil { out.WriteString(dsn) return out.String() } out.WriteString(dsn[:loc[0]]) - out.WriteString("password=****") + out.WriteString(strings.ToLower(dsn[loc[2]:loc[3]]) + "=****") i := loc[1] var quote byte if i < len(dsn) && (dsn[i] == '\'' || dsn[i] == '"') { @@ -301,7 +309,8 @@ func redactKeywordPasswords(dsn string) string { } // Redact is a log-safe view of a PostgreSQL DSN. It masks URL userinfo -// passwords, `?password=` query values, and libpq `password=` keywords. +// passwords, `?password=` and `?sslpassword=` query values, and libpq +// `password=` and `sslpassword=` keywords, in any letter case. // Unrecognised input still runs the userinfo and keyword masks so a parse // failure cannot print the secret. func Redact(dsn string) string { @@ -318,8 +327,14 @@ func Redact(dsn string) string { } } q := u.Query() - if q.Has("password") { - q.Set("password", "****") + masked := false + for k := range q { + if isDSNSecretParam(k) { + q[k] = []string{"****"} + masked = true + } + } + if masked { u.RawQuery = q.Encode() } return u.String() diff --git a/config/redact_escape_test.go b/config/redact_escape_test.go index 78b5e807..cf54a78d 100644 --- a/config/redact_escape_test.go +++ b/config/redact_escape_test.go @@ -1,6 +1,43 @@ package config -import "testing" +import ( + "strings" + "testing" +) + +// sslpassword (the passphrase of an encrypted client key) is as secret as +// password, and an upper-case keyword or query key names the same parameter. +func TestRedactSSLPasswordAndUpperCase(t *testing.T) { + keyword := []struct{ name, in, want string }{ + {"sslpassword keyword", `host=h sslmode=verify-full sslpassword=keypass dbname=d`, `host=h sslmode=verify-full sslpassword=**** dbname=d`}, + {"quoted sslpassword keyword", `sslpassword='key pass' host=h`, `sslpassword=**** host=h`}, + {"upper-case PASSWORD keyword", `host=h PASSWORD=secret dbname=d`, `host=h password=**** dbname=d`}, + {"upper-case SSLPASSWORD keyword", `host=h SSLPASSWORD = keypass`, `host=h sslpassword=****`}, + {"both keywords", `password=one sslpassword=two host=h`, `password=**** sslpassword=**** host=h`}, + {"sslpassword after a parse failure", `postgres://u:pa%zz@h/d sslpassword=keypass`, `postgres://[redacted]`}, + } + for _, tc := range keyword { + t.Run(tc.name, func(t *testing.T) { + if got := Redact(tc.in); got != tc.want { + t.Fatalf("Redact(%q) = %q; want %q", tc.in, got, tc.want) + } + }) + } + url := []struct{ name, in, secret, keep string }{ + {"sslpassword query", "postgres://u@h:5432/d?sslmode=verify-full&sslpassword=keypass", "keypass", "sslmode=verify-full"}, + {"upper-case PASSWORD query", "postgresql://u@h/d?PASSWORD=secret&sslmode=require", "secret", "sslmode=require"}, + {"upper-case SSLPASSWORD query", "postgres://u@h/d?SSLPASSWORD=keypass", "keypass", "SSLPASSWORD="}, + {"userinfo and sslpassword query", "postgres://u:userpass@h/d?sslpassword=keypass", "userpass", "sslpassword=%2A%2A%2A%2A"}, + } + for _, tc := range url { + t.Run(tc.name, func(t *testing.T) { + got := Redact(tc.in) + if strings.Contains(got, tc.secret) || !strings.Contains(got, tc.keep) { + t.Fatalf("Redact(%q) = %q; want %q masked and %q kept", tc.in, got, tc.secret, tc.keep) + } + }) + } +} func TestRedactEscapedAndMalformedPasswords(t *testing.T) { cases := []struct{ name, in, want string }{ diff --git a/db/chat_bridge_chat_type_backfill_test.go b/db/chat_bridge_chat_type_backfill_test.go new file mode 100644 index 00000000..c6e3e87b --- /dev/null +++ b/db/chat_bridge_chat_type_backfill_test.go @@ -0,0 +1,96 @@ +package db + +import ( + "context" + "io/fs" + "strconv" + "testing" +) + +// Migration 0020 backfills chat_type for Telegram chats saved before 0019, so +// a private chat that selected its task earlier receives approval pushes +// without running /task again. Needs PostgreSQL (ARTEX_PG_DSN); skipped +// without it. +func TestChatBridgeChatTypeBackfill(t *testing.T) { + d, err := Open(testDSN(t)) + if err != nil { + SkipPGUnavailable(t, err) + } + t.Cleanup(func() { _ = d.Close() }) + ctx := context.Background() + const other = "t-backfill-other" + var hadTelegram bool + if err := d.QueryRow(`SELECT EXISTS(SELECT 1 FROM chat_bridges WHERE kind='telegram')`).Scan(&hadTelegram); err != nil { + t.Fatal(err) + } + if !hadTelegram { + if _, err := d.Exec(`INSERT INTO chat_bridges(kind) VALUES('telegram')`); err != nil { + t.Fatal(err) + } + } + if _, err := d.Exec(`INSERT INTO chat_bridges(kind) VALUES($1) ON CONFLICT DO NOTHING`, other); err != nil { + t.Fatal(err) + } + task, err := d.CreateTask("chat type backfill", "", nil, 0, 0) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _, _ = d.Exec(`DELETE FROM chat_bridge_chats WHERE task_id=$1`, task.ID) + _, _ = d.Exec(`DELETE FROM chat_bridges WHERE kind=$1`, other) + if !hadTelegram { + _, _ = d.Exec(`DELETE FROM chat_bridges WHERE kind='telegram'`) + } + _ = d.DeleteTask(task.ID) + }) + // chat ids unlikely to collide with rows other tests leave behind. + rows := []struct{ kind, chat, before, want string }{ + {"telegram", "7340012001", "", "private"}, // private chat: the user's id + {"telegram", "-1007340012002", "", "group"}, // supergroup / channel + {"telegram", "-7340012003", "", "group"}, // basic group + {"telegram", "7340012004", "supergroup", "supergroup"}, // already typed: untouched + {"telegram", "x7340012005", "", ""}, // not a Telegram id: untouched + {"telegram", "-07340012006", "", ""}, // not canonical: untouched + {other, "7340012007", "", ""}, // other transport: untouched + } + for _, r := range rows { + if _, err := d.Exec(`INSERT INTO chat_bridge_chats(kind, chat_id, task_id, chat_type) VALUES($1,$2,$3,$4)`, r.kind, r.chat, task.ID, r.before); err != nil { + t.Fatal(err) + } + } + pending, err := d.CreateInterceptPending(0, 0, strconv.FormatInt(task.ID, 10), "worker-1", "bash", []byte(`{"command":"id"}`), "rule says ask") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM intercept_pending WHERE id=$1`, pending) }) + // Before the backfill the private chat counts as shared and gets no push + // while groups cannot act. + if got, err := d.ChatBridgeApprovalsToPush(ctx, "telegram", []string{"7340012001"}, false, 10); err != nil || len(got) != 0 { + t.Fatalf("before backfill: %+v %v", got, err) + } + + sql, err := fs.ReadFile(migrationsFS(), "0020_chat_bridge_chat_type_backfill.sql") + if err != nil { + t.Fatal(err) + } + // Open already applied it to the rows that existed then; running it again + // is what a database with pre-0019 rows sees, and it is idempotent. + for range 2 { + if _, err := d.Exec(string(sql)); err != nil { + t.Fatal(err) + } + } + for _, r := range rows { + var got string + if err := d.QueryRow(`SELECT chat_type FROM chat_bridge_chats WHERE kind=$1 AND chat_id=$2`, r.kind, r.chat).Scan(&got); err != nil { + t.Fatal(err) + } + if got != r.want { + t.Errorf("%s chat %s: chat_type=%q, want %q", r.kind, r.chat, got, r.want) + } + } + got, err := d.ChatBridgeApprovalsToPush(ctx, "telegram", []string{"7340012001", "-1007340012002"}, false, 10) + if err != nil || len(got) != 1 || got[0].ChatID != "7340012001" || got[0].ChatType != "private" { + t.Fatalf("after backfill, push to the private chat only: %+v %v", got, err) + } +} diff --git a/db/migrate_test.go b/db/migrate_test.go index 55cd1058..b9a0bd51 100644 --- a/db/migrate_test.go +++ b/db/migrate_test.go @@ -145,9 +145,10 @@ func assertEmbeddedApplied(t *testing.T, d *DB) []appliedMigration { {16, "0016_chat_bridge_access.sql"}, {17, "0017_legacy_fact_capture_provenance.sql"}, {18, "0018_chat_bridge_share_text.sql"}, - {19, "0019_chat_bridge_approvals.sql"}} + {19, "0019_chat_bridge_approvals.sql"}, + {20, "0020_chat_bridge_chat_type_backfill.sql"}} if len(applied) != len(want) { - t.Fatalf("schema_migrations = %+v, want versions 1 to 19", applied) + t.Fatalf("schema_migrations = %+v, want versions 1 to 20", applied) } for i, w := range want { content, err := fs.ReadFile(migrationsFS(), w.name) diff --git a/db/migrations/0020_chat_bridge_chat_type_backfill.sql b/db/migrations/0020_chat_bridge_chat_type_backfill.sql new file mode 100644 index 00000000..4f52b78c --- /dev/null +++ b/db/migrations/0020_chat_bridge_chat_type_backfill.sql @@ -0,0 +1,16 @@ +-- Chat bridge (issue #5): backfill chat_type for chats saved before 0019. +-- +-- 0019 added chat_bridge_chats.chat_type with DEFAULT '', and approval pushes +-- go to a chat only when chat_type='private' or groups can act. A private chat +-- that selected its task before 0019 therefore got no pushes until it ran +-- /task again. +-- +-- Telegram gives a private chat the user's own id, a positive number, and +-- every shared chat (group, supergroup, channel) a negative one. Only rows +-- still empty are touched; any other kind keeps '' and counts as shared, as +-- before. The next /task records the transport's exact type. +UPDATE chat_bridge_chats SET chat_type='private' +WHERE kind='telegram' AND chat_type='' AND chat_id ~ '^[1-9][0-9]*$'; + +UPDATE chat_bridge_chats SET chat_type='group' +WHERE kind='telegram' AND chat_type='' AND chat_id ~ '^-[1-9][0-9]*$'; diff --git a/docs/OPS.md b/docs/OPS.md index 78a3b846..e14b3f72 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -64,6 +64,11 @@ Back up the key directory as well: without it, JWTs cannot be verified and seale secrets cannot be decrypted. Keep it outside the database backup but under the same access controls. +Schema migrations are forward-only (`db/migrations/`, rules in `db/db.go`): there are +no down migrations. An older binary refuses to start against a database that has a +migration it does not ship. To roll back an upgrade, take a dump before upgrading, +then restore that dump into an empty database and start the previous release. + ## 4. Key rotation - **`jwt.key`** — signing key for the 7-day HS256 session tokens. Replacing it diff --git a/mcphttp/client.go b/mcphttp/client.go index b1447b92..22b7f8af 100644 --- a/mcphttp/client.go +++ b/mcphttp/client.go @@ -19,6 +19,7 @@ import ( "net" "net/http" "net/url" + "strconv" "strings" "sync" "time" @@ -726,7 +727,10 @@ func parseSSE(r io.Reader, wantID int) (*rpcResponse, error) { return nil, fmt.Errorf("mcp: no matching response in event stream") } +// readSnippet returns the start of an error response body, quoted: the body is +// remote input and ends up in log lines and the health status, where a raw CR +// or LF would let the server forge a line. func readSnippet(r io.Reader) string { b, _ := io.ReadAll(io.LimitReader(r, 2048)) - return strings.TrimSpace(string(b)) + return strconv.Quote(strings.TrimSpace(string(b))) } diff --git a/mcphttp/snippet_quote_test.go b/mcphttp/snippet_quote_test.go new file mode 100644 index 00000000..b6e44bec --- /dev/null +++ b/mcphttp/snippet_quote_test.go @@ -0,0 +1,31 @@ +package mcphttp + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// The body of an error response is remote input. The error built from it is +// logged and stored as the health status, so CR and LF must arrive escaped. +func TestErrorSnippetEscapesCRLF(t *testing.T) { + if got := readSnippet(strings.NewReader(" bad\r\n[auth] forged\rline\n ")); strings.ContainsAny(got, "\r\n") || got != `"bad\r\n[auth] forged\rline"` { + t.Fatalf("readSnippet = %q", got) + } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte("upstream down\r\n2026/11/29 12:00:00 [auth] admin password changed\n")) + })) + defer srv.Close() + ctx := context.Background() + _, err := New(ctx, "remote", srv.URL, nil, false, 1) + if err == nil || strings.ContainsAny(err.Error(), "\r\n") || !strings.Contains(err.Error(), `\r\n2026/11/29`) { + t.Fatalf("streamable HTTP error = %q", err) + } + _, err = NewSSE(ctx, "remote", srv.URL+"/sse", nil, false) + if err == nil || strings.ContainsAny(err.Error(), "\r\n") || !strings.Contains(err.Error(), `\r\n2026/11/29`) { + t.Fatalf("legacy SSE error = %q", err) + } +} diff --git a/mcphttp/ssrf.go b/mcphttp/ssrf.go index c8a9976a..17eb2679 100644 --- a/mcphttp/ssrf.go +++ b/mcphttp/ssrf.go @@ -16,7 +16,8 @@ import ( // boundary: it is the same defence-in-depth default that notify/ uses for // webhook delivery, so a configured URL cannot silently reach loopback, // link-local or the cloud metadata endpoint. A local MCP server is a legitimate -// setup, hence the explicit opt-out rather than a hardcoded allowance. +// setup, hence the explicit opt-out rather than a hardcoded allowance. The +// opt-out covers loopback only: metadata and link-local addresses stay refused. const AllowLocalTargetsEnv = "ARTEX_MCP_ALLOW_LOCAL" func allowLocalTargets() bool { @@ -28,9 +29,19 @@ func allowLocalTargets() bool { // intentionally allowed: LAN MCP servers are a normal deployment, while // loopback, link-local (including 169.254.169.254), unspecified and multicast // are the sensitive addresses the default should refuse. +// Cloud metadata services outside link-local: Alibaba Cloud (100.100.100.200), +// the Azure WireServer (168.63.129.16) and the AWS IMDS IPv6 endpoint +// (fd00:ec2::254, a unique-local address). var ( - alibabaMetadataIP = net.IPv4(100, 100, 100, 200) + metadataIPs = []net.IP{ + net.IPv4(100, 100, 100, 200), + net.IPv4(168, 63, 129, 16), + net.ParseIP("fd00:ec2::254"), + } _, nat64Prefix, _ = net.ParseCIDR("64:ff9b::/96") + // RFC 8215 local-use NAT64 prefix. The operator chooses where the IPv4 + // address sits inside it, so the whole prefix is refused. + _, nat64LocalPrefix, _ = net.ParseCIDR("64:ff9b:1::/48") ) func isBlockedDialIP(ip net.IP) bool { @@ -44,19 +55,31 @@ func isBlockedDialIP(ip net.IP) bool { // Check the embedded IPv4 address in RFC 6052 well-known NAT64 prefix. return isBlockedDialIP(net.IPv4(ip[12], ip[13], ip[14], ip[15])) } - if ip.Equal(alibabaMetadataIP) { + if nat64LocalPrefix != nil && nat64LocalPrefix.Contains(ip) { return true } + for _, m := range metadataIPs { + if ip.Equal(m) { + return true + } + } return ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsInterfaceLocalMulticast() || ip.IsUnspecified() || ip.IsMulticast() } +// dialAllowed applies the guard to one dialled IP. ARTEX_MCP_ALLOW_LOCAL lets +// a local MCP server through: it exempts loopback (127.0.0.0/8, ::1 and their +// IPv4-mapped forms) and nothing else. +func dialAllowed(ip net.IP, allowLocal bool) bool { + if allowLocal && ip != nil && ip.IsLoopback() { + return true + } + return !isBlockedDialIP(ip) +} + // blockInternalDial is a Dialer.Control hook: it sees the address actually // dialled, so it also covers DNS rebinding and same-origin redirects. func blockInternalDial(_, address string, _ syscall.RawConn) error { - if allowLocalTargets() { - return nil - } host, _, err := net.SplitHostPort(address) if err != nil { return err @@ -65,7 +88,7 @@ func blockInternalDial(_, address string, _ syscall.RawConn) error { if ip == nil { return fmt.Errorf("cannot parse mcp target address %q", host) } - if isBlockedDialIP(ip) { + if !dialAllowed(ip, allowLocalTargets()) { return fmt.Errorf("mcp: refusing to dial loopback/link-local address %s (set %s=1 for a local MCP server)", ip, AllowLocalTargetsEnv) } return nil diff --git a/mcphttp/ssrf_test.go b/mcphttp/ssrf_test.go index f19162ae..c17beacc 100644 --- a/mcphttp/ssrf_test.go +++ b/mcphttp/ssrf_test.go @@ -73,6 +73,20 @@ func TestIsBlockedDialIPMetadataAndNAT64(t *testing.T) { {"64:ff9b::8.8.8.8", false}, {"10.0.0.5", false}, {"192.168.1.20", false}, + // AWS IMDS over IPv6, the Azure WireServer, and the RFC 8215 + // local-use NAT64 prefix. + {"fd00:ec2::254", true}, + {"FD00:EC2:0:0:0:0:0:254", true}, + {"fd00:ec2::253", false}, + {"fd00::1", false}, + {"168.63.129.16", true}, + {"::ffff:168.63.129.16", true}, + {"64:ff9b::168.63.129.16", true}, + {"168.63.129.17", false}, + {"64:ff9b:1::1", true}, + {"64:ff9b:1::a9fe:a9fe", true}, + {"64:ff9b:1:ffff:ffff:ffff:ffff:ffff", true}, + {"64:ff9b:2::1", false}, } for _, tc := range cases { ip := net.ParseIP(tc.ip) @@ -81,3 +95,52 @@ func TestIsBlockedDialIPMetadataAndNAT64(t *testing.T) { } } } + +// ARTEX_MCP_ALLOW_LOCAL is the opt-out for a local MCP server: it exempts +// loopback and nothing else. Metadata, link-local, unspecified and multicast +// addresses stay refused with it set. +func TestAllowLocalExemptsOnlyLoopback(t *testing.T) { + cases := []struct { + ip string + allowed, allowedOn bool // without / with ARTEX_MCP_ALLOW_LOCAL + }{ + {"127.0.0.1", false, true}, + {"127.10.20.30", false, true}, + {"::1", false, true}, + {"::ffff:127.0.0.1", false, true}, + {"169.254.169.254", false, false}, + {"::ffff:169.254.169.254", false, false}, + {"169.254.10.1", false, false}, + {"fe80::1", false, false}, + {"fd00:ec2::254", false, false}, + {"100.100.100.200", false, false}, + {"168.63.129.16", false, false}, + {"64:ff9b::169.254.169.254", false, false}, + {"64:ff9b::127.0.0.1", false, false}, + {"64:ff9b:1::1", false, false}, + {"0.0.0.0", false, false}, + {"::", false, false}, + {"224.0.0.1", false, false}, + {"10.0.0.5", true, true}, + {"8.8.8.8", true, true}, + } + for _, tc := range cases { + ip := net.ParseIP(tc.ip) + if got := dialAllowed(ip, false); got != tc.allowed { + t.Errorf("dialAllowed(%q, allowLocal=false) = %v, want %v", tc.ip, got, tc.allowed) + } + if got := dialAllowed(ip, true); got != tc.allowedOn { + t.Errorf("dialAllowed(%q, allowLocal=true) = %v, want %v", tc.ip, got, tc.allowedOn) + } + } + // Through the real dial hook, with the environment variable set. + t.Setenv(AllowLocalTargetsEnv, "1") + if err := blockInternalDial("tcp", "127.0.0.1:80", nil); err != nil { + t.Errorf("loopback with opt-out refused: %v", err) + } + for _, addr := range []string{"169.254.169.254:80", "[fd00:ec2::254]:80", "168.63.129.16:80", "[fe80::1]:80"} { + if err := blockInternalDial("tcp", addr, nil); err == nil { + t.Errorf("%s dialled with %s=1; only loopback is exempt", addr, AllowLocalTargetsEnv) + } + } +} diff --git a/server/assembly.go b/server/assembly.go index de003c36..1b19cbb9 100644 --- a/server/assembly.go +++ b/server/assembly.go @@ -108,14 +108,14 @@ func wireAgentAugment(pg *db.DB, skillDir string, hostTools func() ([]actool.Cor } cl, err := connectMCP(ctx, dial, priv) if err != nil { - log.Printf("[mcp] %s connect failed: %v", m.Name, err) + logMCPFailure(m.Name, "connect", err) _ = pg.UpdateMCPHealth(m.ID, false, "connect: "+err.Error()) continue } closers = append(closers, cl) ts, err := cl.Tools(ctx) if err != nil { - log.Printf("[mcp] %s tools/list failed: %v", m.Name, err) + logMCPFailure(m.Name, "tools/list", err) _ = pg.UpdateMCPHealth(m.ID, false, "tools/list: "+err.Error()) continue } @@ -227,6 +227,13 @@ func wireAgentAugment(pg *db.DB, skillDir string, hostTools func() ([]actool.Cor }) } +// logMCPFailure logs a failed MCP connect or tools/list. The error text can +// carry the remote server's response, so it is quoted: a CR or LF in it must +// not start a forged log line. +func logMCPFailure(name, stage string, err error) { + log.Printf("[mcp] %s %s failed: %q", name, stage, err.Error()) +} + func idSet(ids []int64) map[int64]bool { m := make(map[int64]bool, len(ids)) for _, id := range ids { diff --git a/server/auth.go b/server/auth.go index 05b04881..d3f96cfd 100644 --- a/server/auth.go +++ b/server/auth.go @@ -273,40 +273,19 @@ func (s *Server) approver(r *http.Request) string { return jwtSubject(tok, s.jwtKey) } -// extractToken reads the JWT from Authorization: Bearer or the session cookie. -// URLs must never carry reusable session credentials, including for SSE. +// extractToken reads the JWT from Authorization: Bearer only. URLs must never +// carry reusable session credentials, including for SSE. A cookie is never a +// session either: the browser attaches cookies to requests a foreign page makes, +// while a bearer token is put there by the caller. The console sends the bearer +// header on every API call; its artex_token cookie only tells the Next.js +// route guard (web/src/proxy.ts) that a login happened. func extractToken(r *http.Request) string { if h := r.Header.Get("Authorization"); strings.HasPrefix(h, "Bearer ") { return strings.TrimPrefix(h, "Bearer ") } - if c, err := r.Cookie("artex_token"); err == nil && c.Value != "" { - return c.Value - } return "" } -// cookieAuthenticated reports whether extractToken takes the session from the -// artex_token cookie. The browser attaches that cookie on its own, to requests -// a foreign page makes as well; a bearer token is put there by the caller. -func cookieAuthenticated(r *http.Request) bool { - if strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") { - return false - } - c, err := r.Cookie("artex_token") - return err == nil && c.Value != "" -} - -// sameOrigin reports whether the browser states that the request comes from a -// page of this server: Sec-Fetch-Site is same-origin, or Origin names the -// scheme, host and port the request was sent to. Scripts can set neither -// header. A request that carries neither is not same-origin. -func sameOrigin(r *http.Request) bool { - if r.Header.Get("Sec-Fetch-Site") == "same-origin" { - return true - } - return originMatchesRequest(r) -} - // originMatchesRequest checks strictly whether the Origin header matches the // request's scheme and host:port, without trusting Sec-Fetch-Site. Used by // cors() before echoing Access-Control-Allow-Origin so a non-browser caller or @@ -341,7 +320,7 @@ func hostWithPort(host, scheme string) string { // loopback names, on any port. `next dev` serves the console on :3000 and opens // the live streams directly against the Go backend on :8787, which is a // cross-origin request that the strict same-origin policy refuses. Only cors() -// uses this: sameOrigin() keeps its strict check for cookie-based writes. +// uses this. func loopbackOrigin(r *http.Request) bool { o, err := url.Parse(r.Header.Get("Origin")) if err != nil || o.Host == "" { @@ -361,10 +340,9 @@ func isLoopbackHost(host string) bool { } // requireAuth wraps h with JWT validation. -// /api/auth/*, /api/health and /api/ready are exempt. -// A state-changing request whose session is the cookie must be same-origin -// (see sameOrigin), so that a foreign page cannot act with the operator's -// session. Requests that carry a bearer token, and GET and HEAD, are not checked. +// /api/auth/*, /api/health and /api/ready are exempt. The session is only ever +// the bearer token (extractToken), so a foreign page cannot act with the +// operator's session through a cookie the browser attaches on its own. func (s *Server) requireAuth(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { p := r.URL.Path @@ -381,13 +359,6 @@ func (s *Server) requireAuth(h http.Handler) http.Handler { writeErr(w, 401, "token is invalid or expired") return } - switch r.Method { - case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete: - if cookieAuthenticated(r) && !sameOrigin(r) { - writeErr(w, 403, "cross-origin request refused: a cookie session can change state only from the console's own origin; send the token as Authorization: Bearer instead") - return - } - } h.ServeHTTP(w, r) }) } diff --git a/server/csrf_test.go b/server/csrf_test.go index 9e9b7d13..80f18807 100644 --- a/server/csrf_test.go +++ b/server/csrf_test.go @@ -2,7 +2,6 @@ package server import ( "context" - "crypto/tls" "encoding/json" "fmt" "net/http" @@ -28,10 +27,12 @@ func csrfRequest(method, path, body string, headers map[string]string) *http.Req return r } -// A session that arrives as the artex_token cookie is sent by the browser on -// its own, so a state-changing request that carries it must come from the -// console's own origin. requireAuth is exercised directly, without a database. -func TestCookieStateChangeNeedsSameOrigin(t *testing.T) { +// The browser attaches the artex_token cookie on its own, to requests a +// foreign page makes as well, so the cookie is never a session: whatever the +// method or origin, a request with only the cookie is refused. A bearer token +// is put there by the caller and is the only session. requireAuth is +// exercised directly, without a database. +func TestCookieIsNeverASession(t *testing.T) { s := &Server{jwtKey: []byte("0123456789abcdef0123456789abcdef")} tok, err := signJWT(s.jwtKey) if err != nil { @@ -42,93 +43,54 @@ func TestCookieStateChangeNeedsSameOrigin(t *testing.T) { reached = true w.WriteHeader(204) })) - // The request host is example.com over plain HTTP, so its origin is - // http://example.com (port 80). for _, tc := range []struct { name string method string + path string headers map[string]string want int }{ - {"cookie, matching Origin", "POST", map[string]string{"Cookie": tok, "Origin": "http://example.com"}, 204}, - {"cookie, matching Origin with the default port written out", "POST", map[string]string{"Cookie": tok, "Origin": "http://EXAMPLE.com:80"}, 204}, - {"cookie, Sec-Fetch-Site same-origin, no Origin", "POST", map[string]string{"Cookie": tok, "Sec-Fetch-Site": "same-origin"}, 204}, - // A proxy that terminates TLS or rewrites Host changes what Origin is - // compared with; the browser's own same-origin statement still passes. - {"cookie, Origin differs, Sec-Fetch-Site same-origin", "POST", map[string]string{"Cookie": tok, "Origin": "https://console.example.org", "Sec-Fetch-Site": "same-origin"}, 204}, - {"cookie, foreign Origin", "POST", map[string]string{"Cookie": tok, "Origin": "https://evil.example"}, 403}, - {"cookie, foreign Origin, Sec-Fetch-Site cross-site", "POST", map[string]string{"Cookie": tok, "Origin": "https://evil.example", "Sec-Fetch-Site": "cross-site"}, 403}, - {"cookie, same site on another port", "POST", map[string]string{"Cookie": tok, "Origin": "http://example.com:3000", "Sec-Fetch-Site": "same-site"}, 403}, - {"cookie, same host over another scheme", "POST", map[string]string{"Cookie": tok, "Origin": "https://example.com"}, 403}, - {"cookie, sibling subdomain", "POST", map[string]string{"Cookie": tok, "Origin": "http://a.example.com", "Sec-Fetch-Site": "same-site"}, 403}, - {"cookie, host that only starts with the request host", "POST", map[string]string{"Cookie": tok, "Origin": "http://example.com.evil.example"}, 403}, - {"cookie, opaque Origin", "POST", map[string]string{"Cookie": tok, "Origin": "null"}, 403}, - {"cookie, neither header", "POST", map[string]string{"Cookie": tok}, 403}, - {"cookie, Sec-Fetch-Site none", "POST", map[string]string{"Cookie": tok, "Sec-Fetch-Site": "none"}, 403}, - {"cookie, foreign Origin, PUT", "PUT", map[string]string{"Cookie": tok, "Origin": "https://evil.example"}, 403}, - {"cookie, foreign Origin, PATCH", "PATCH", map[string]string{"Cookie": tok, "Origin": "https://evil.example"}, 403}, - {"cookie, foreign Origin, DELETE", "DELETE", map[string]string{"Cookie": tok, "Origin": "https://evil.example"}, 403}, - {"cookie, neither header, DELETE", "DELETE", map[string]string{"Cookie": tok}, 403}, - // Reads are not state changes. - {"cookie, foreign Origin, GET", "GET", map[string]string{"Cookie": tok, "Origin": "https://evil.example"}, 204}, - {"cookie, neither header, GET", "GET", map[string]string{"Cookie": tok}, 204}, - {"cookie, neither header, HEAD", "HEAD", map[string]string{"Cookie": tok}, 204}, - // A bearer token is not sent by the browser on its own. - {"bearer, foreign Origin", "POST", map[string]string{"Authorization": "Bearer " + tok, "Origin": "https://evil.example"}, 204}, - {"bearer, neither header", "POST", map[string]string{"Authorization": "Bearer " + tok}, 204}, - {"bearer and cookie, foreign Origin", "DELETE", map[string]string{"Authorization": "Bearer " + tok, "Cookie": tok, "Origin": "https://evil.example"}, 204}, + {"cookie, matching Origin", "POST", "/api/mcp", map[string]string{"Cookie": tok, "Origin": "http://example.com"}, 401}, + {"cookie, Sec-Fetch-Site same-origin", "POST", "/api/mcp", map[string]string{"Cookie": tok, "Sec-Fetch-Site": "same-origin"}, 401}, + {"cookie, foreign Origin", "POST", "/api/mcp", map[string]string{"Cookie": tok, "Origin": "https://evil.example"}, 401}, + {"cookie, neither header, DELETE", "DELETE", "/api/mcp", map[string]string{"Cookie": tok}, 401}, + {"cookie, foreign Origin, GET", "GET", "/api/mcp", map[string]string{"Cookie": tok, "Origin": "https://evil.example"}, 401}, + {"cookie, neither header, GET", "GET", "/api/mcp", map[string]string{"Cookie": tok}, 401}, + {"cookie, neither header, HEAD", "HEAD", "/api/mcp", map[string]string{"Cookie": tok}, 401}, + {"cookie and query token, foreign Origin", "POST", "/api/mcp?token=" + tok, map[string]string{"Cookie": tok, "Origin": "https://evil.example"}, 401}, + {"query token alone", "GET", "/api/mcp?token=" + tok, nil, 401}, + {"bearer, foreign Origin", "POST", "/api/mcp", map[string]string{"Authorization": "Bearer " + tok, "Origin": "https://evil.example"}, 204}, + {"bearer, neither header", "DELETE", "/api/mcp", map[string]string{"Authorization": "Bearer " + tok}, 204}, + {"bearer, GET", "GET", "/api/mcp", map[string]string{"Authorization": "Bearer " + tok}, 204}, + {"bearer and cookie, foreign Origin", "DELETE", "/api/mcp", map[string]string{"Authorization": "Bearer " + tok, "Cookie": tok, "Origin": "https://evil.example"}, 204}, // A bad bearer token does not fall back to the cookie. - {"bad bearer and cookie, matching Origin", "POST", map[string]string{"Authorization": "Bearer nope", "Cookie": tok, "Origin": "http://example.com"}, 401}, - {"no token", "POST", map[string]string{"Origin": "http://example.com"}, 401}, + {"bad bearer and cookie", "POST", "/api/mcp", map[string]string{"Authorization": "Bearer nope", "Cookie": tok, "Origin": "http://example.com"}, 401}, + {"no token", "POST", "/api/mcp", map[string]string{"Origin": "http://example.com"}, 401}, } { reached = false rec := httptest.NewRecorder() - h.ServeHTTP(rec, csrfRequest(tc.method, "/api/mcp", "", tc.headers)) + h.ServeHTTP(rec, csrfRequest(tc.method, tc.path, "", tc.headers)) if rec.Code != tc.want || reached != (tc.want == 204) { t.Errorf("%s: status=%d handler reached=%v, want %d", tc.name, rec.Code, reached, tc.want) } } - - // Query credentials are refused; with the cookie present the cookie is used - // and still requires the same-origin CSRF check. - rec := httptest.NewRecorder() - h.ServeHTTP(rec, csrfRequest("POST", "/api/mcp?token="+tok, "", map[string]string{"Origin": "https://evil.example"})) - if rec.Code != 401 { - t.Errorf("query token, foreign Origin: status=%d, want 401", rec.Code) + // The handlers that validate the session themselves (event streams, + // change-password, approver) read it through extractToken too. + r := csrfRequest("GET", "/api/logs/stream", "", map[string]string{"Cookie": tok}) + if got := extractToken(r); got != "" { + t.Errorf("extractToken took the session from the cookie: %q", got) } - rec = httptest.NewRecorder() - h.ServeHTTP(rec, csrfRequest("POST", "/api/mcp?token="+tok, "", map[string]string{"Cookie": tok, "Origin": "https://evil.example"})) - if rec.Code != 403 { - t.Errorf("query token and cookie, foreign Origin: status=%d, want 403", rec.Code) - } - - // Over TLS on a non-default port the origin is https://host:port. - for origin, want := range map[string]int{ - "https://console.test:8443": 204, - "http://console.test:8443": 403, - "https://console.test": 403, - "https://console.test:8444": 403, - } { - r := csrfRequest("POST", "https://console.test:8443/api/mcp", "", map[string]string{"Cookie": tok, "Origin": origin}) - r.TLS = &tls.ConnectionState{} - rec := httptest.NewRecorder() - h.ServeHTTP(rec, r) - if rec.Code != want { - t.Errorf("TLS request, Origin %s: status=%d, want %d", origin, rec.Code, want) - } - } - // An IPv6 literal host. - r := csrfRequest("POST", "http://[::1]:8787/api/mcp", "", map[string]string{"Cookie": tok, "Origin": "http://[::1]:8787"}) - rec = httptest.NewRecorder() - h.ServeHTTP(rec, r) - if rec.Code != 204 { - t.Errorf("IPv6 host, matching Origin: status=%d, want 204", rec.Code) + r = csrfRequest("GET", "/api/logs/stream", "", map[string]string{"Cookie": tok, "Authorization": "Bearer " + tok}) + if got := extractToken(r); got != tok { + t.Errorf("extractToken ignored the bearer token") } } -// The same rule through the real mux, on an endpoint that stores a command -// (POST /api/mcp): a foreign page must not be able to add an MCP server with +// The same rule through the real mux: a foreign page must not be able to add +// an MCP server (POST /api/mcp) or change the admin password +// (POST /api/auth/change-password, which validates the session itself) with // the operator's cookie. Setup and login need no session and keep working. +// Needs PostgreSQL (ARTEX_PG_DSN); skipped without it. func TestCookieCSRFThroughRealMux(t *testing.T) { m, err := NewManager(t.TempDir(), "") if err != nil { @@ -178,9 +140,6 @@ func TestCookieCSRFThroughRealMux(t *testing.T) { h.ServeHTTP(rec, csrfRequest("POST", "/api/auth/login", login, nil)) token(rec) rec = httptest.NewRecorder() - h.ServeHTTP(rec, csrfRequest("POST", "/api/auth/login", login, map[string]string{"Cookie": stale})) - token(rec) - rec = httptest.NewRecorder() h.ServeHTTP(rec, csrfRequest("POST", "/api/auth/login", login, map[string]string{"Cookie": stale, "Origin": "http://example.com", "Sec-Fetch-Site": "same-origin"})) tok := token(rec) @@ -189,11 +148,10 @@ func TestCookieCSRFThroughRealMux(t *testing.T) { headers map[string]string want int }{ - {"same-origin", map[string]string{"Cookie": tok, "Origin": "http://example.com", "Content-Type": "application/json"}, 200}, + {"cookie-same-origin", map[string]string{"Cookie": tok, "Origin": "http://example.com", "Content-Type": "application/json"}, 401}, // What a foreign page can send without a preflight: a text/plain body. - {"cross-origin", map[string]string{"Cookie": tok, "Origin": "https://evil.example", "Content-Type": "text/plain"}, 403}, - {"other-port", map[string]string{"Cookie": tok, "Origin": "http://example.com:3000", "Sec-Fetch-Site": "same-site", "Content-Type": "text/plain"}, 403}, - {"no-headers", map[string]string{"Cookie": tok}, 403}, + {"cookie-cross-origin", map[string]string{"Cookie": tok, "Origin": "https://evil.example", "Content-Type": "text/plain"}, 401}, + {"cookie-no-headers", map[string]string{"Cookie": tok}, 401}, {"bearer-cross-origin", map[string]string{"Authorization": "Bearer " + tok, "Origin": "https://evil.example"}, 200}, } { name := prefix + tc.name @@ -213,11 +171,37 @@ func TestCookieCSRFThroughRealMux(t *testing.T) { } } - // Reads with the cookie alone still work (the log page and the event - // streams send nothing else). + // change-password is under /api/auth/*, which requireAuth exempts; the + // handler validates the session itself. A cross-origin form post that + // carries only the cookie (and knows the old password) must not rotate it. + change := `{"old_password":"correct-horse-1","new_password":"attacker-chosen-9"}` + for _, headers := range []map[string]string{ + {"Cookie": tok, "Origin": "https://evil.example", "Content-Type": "text/plain"}, + {"Cookie": tok, "Origin": "http://example.com", "Sec-Fetch-Site": "same-origin", "Content-Type": "application/json"}, + } { + rec = httptest.NewRecorder() + h.ServeHTTP(rec, csrfRequest("POST", "/api/auth/change-password", change, headers)) + if rec.Code != 401 { + t.Errorf("change-password with the cookie only (%v): status=%d, want 401", headers["Origin"], rec.Code) + } + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, csrfRequest("POST", "/api/auth/login", login, nil)) + if rec.Code != 200 { + t.Fatalf("the cookie-only change-password request changed the password: login status=%d", rec.Code) + } + // Reads with the cookie alone are refused too: the log page and the event + // streams send the bearer token. rec = httptest.NewRecorder() h.ServeHTTP(rec, csrfRequest("GET", "/api/mcp", "", map[string]string{"Cookie": tok})) + if rec.Code != 401 { + t.Errorf("GET /api/mcp with the cookie: status=%d, want 401", rec.Code) + } + // The console's own request carries the bearer token and still works. + rec = httptest.NewRecorder() + h.ServeHTTP(rec, csrfRequest("POST", "/api/auth/change-password", `{"old_password":"correct-horse-1","new_password":"correct-horse-2"}`, + map[string]string{"Authorization": "Bearer " + tok, "Content-Type": "application/json"})) if rec.Code != 200 { - t.Errorf("GET /api/mcp with the cookie: status=%d, want 200", rec.Code) + t.Errorf("change-password with the bearer token: status=%d body=%s, want 200", rec.Code, rec.Body.String()) } } diff --git a/server/llm_route_rekey_test.go b/server/llm_route_rekey_test.go new file mode 100644 index 00000000..c34e9236 --- /dev/null +++ b/server/llm_route_rekey_test.go @@ -0,0 +1,153 @@ +package server + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/Autumn-27/artex/db" + "github.com/Autumn-27/artex/notify" +) + +// A blank api_key on a profile save keeps the stored key. For every format, +// that key may only stay with the provider, base URL and proxy it was saved +// for: a changed route without a new key is refused and leaves the profile +// unchanged. Needs PostgreSQL (ARTEX_PG_DSN); skipped without it. +func TestProfileRouteChangeNeedsKeyForEveryFormat(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()) + t.Cleanup(cancel) + s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir()) + + const oldKey = "synthetic-old-key" + const header = "X-Example-Route: synthetic-route" + for _, format := range []string{"openai", "anthropic", "bedrock-gateway"} { + t.Run(format, func(t *testing.T) { + name := fmt.Sprintf("t-rekey-%s-%d", format, time.Now().UnixNano()) + oldBase, newBase := "http://127.0.0.1:40121/old", "http://127.0.0.1:40122/new" + oldProxy, newProxy := "http://127.0.0.1:40131", "http://127.0.0.1:40132" + saved := &db.LLMProfile{Name: name, Format: format, Model: "test.model", BaseURL: oldBase, Proxy: oldProxy, APIKey: oldKey} + if format == "bedrock-gateway" { + saved.CustomHeaders = header + } + id, err := m.pg.SaveProfile(saved) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _, _ = m.pg.Exec(`DELETE FROM llm_profiles WHERE id=$1`, id) }) + post := func(base, proxy, key string) int { + t.Helper() + body, _ := json.Marshal(map[string]any{"id": id, "name": name, "format": format, "model": "test.model", "base_url": base, "proxy": proxy, "api_key": key, "streaming": false}) + rec := httptest.NewRecorder() + s.pgSaveProfile(rec, httptest.NewRequest(http.MethodPost, "/api/llm/profiles", bytes.NewReader(body))) + return rec.Code + } + unchanged := func(what string) { + t.Helper() + p, err := m.pg.ProfileByID(id) + if err != nil || p == nil || p.BaseURL != oldBase || p.Proxy != oldProxy || p.APIKey != oldKey { + t.Fatalf("%s: refused save changed the stored profile (err %v)", what, err) + } + if format == "bedrock-gateway" && p.CustomHeaders != header { + t.Fatalf("%s: refused save dropped the gateway headers", what) + } + } + + if code := post(newBase, oldProxy, ""); code != http.StatusBadRequest { + t.Fatalf("base URL change without a key: HTTP %d, want 400", code) + } + unchanged("base URL change") + if code := post(oldBase, newProxy, ""); code != http.StatusBadRequest { + t.Fatalf("proxy change without a key: HTTP %d, want 400", code) + } + unchanged("proxy change") + if code := post(oldBase, "", ""); code != http.StatusBadRequest { + t.Fatalf("proxy removal without a key: HTTP %d, want 400", code) + } + unchanged("proxy removal") + // The list returns the proxy masked; echoing the mask is the same route. + if code := post(oldBase, notify.MaskedPrefix+"0131", ""); code != http.StatusOK { + t.Fatalf("same route with the masked proxy: HTTP %d, want 200", code) + } + unchanged("same route") + + if code := post(newBase, newProxy, "synthetic-new-key"); code != http.StatusOK { + t.Fatalf("route change with a new key: HTTP %d, want 200", code) + } + p, err := m.pg.ProfileByID(id) + if err != nil || p == nil || p.BaseURL != newBase || p.Proxy != newProxy || p.APIKey != "synthetic-new-key" || p.CustomHeaders != "" { + t.Fatalf("route change with a new key was not stored as sent, or kept old headers (err %v)", err) + } + }) + } +} + +// The legacy single-provider endpoint (POST /api/llm) rewrites the "default" +// profile. A Bedrock gateway header saved for one egress proxy must not follow +// a proxy change. Needs PostgreSQL (ARTEX_PG_DSN); skipped without it. +func TestLegacyLLMEndpointProxyChangeClearsGatewayHeaders(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" + base := "http://127.0.0.1:40141/bedrock" + oldProxy, newProxy := "http://127.0.0.1:40151", "http://127.0.0.1:40152" + id, err := m.pg.SaveProfile(&db.LLMProfile{ + Name: "default", Format: "bedrock-gateway", Model: "test.model", + BaseURL: base, Proxy: oldProxy, 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(proxy, token string) int { + t.Helper() + body, _ := json.Marshal(map[string]string{ + "provider": "bedrock-gateway", "model": "test.model", "base_url": base, "proxy": proxy, "api_key": token, + }) + rec := httptest.NewRecorder() + s.setLLM(rec, httptest.NewRequest(http.MethodPost, "/api/llm", bytes.NewReader(body))) + return rec.Code + } + // Same route: token rotation keeps the gateway headers. + if code := post(oldProxy, "synthetic-rotated-token"); code != http.StatusOK { + t.Fatalf("same-route rotation: HTTP %d", code) + } + if p, err := m.pg.ProfileByID(id); err != nil || p.CustomHeaders != header { + t.Fatalf("same-route rotation lost the gateway headers: %v", err) + } + // A new proxy without a token is refused: the stored token stays with its route. + if code := post(newProxy, ""); code != http.StatusBadRequest { + t.Fatalf("proxy change without a token: HTTP %d, want 400", code) + } + // A new proxy with a token is saved, and the old route's headers are cleared. + if code := post(newProxy, "synthetic-new-token"); code != http.StatusOK { + t.Fatalf("proxy change with a token: HTTP %d", code) + } + p, err := m.pg.ProfileByID(id) + if err != nil || p.Proxy != newProxy || p.APIKey != "synthetic-new-token" || p.CustomHeaders != "" { + t.Fatalf("proxy change kept the old route's gateway headers or was not stored: %v", err) + } +} diff --git a/server/mcp_log_quote_test.go b/server/mcp_log_quote_test.go new file mode 100644 index 00000000..f93c6e26 --- /dev/null +++ b/server/mcp_log_quote_test.go @@ -0,0 +1,31 @@ +package server + +import ( + "bytes" + "errors" + "log" + "strings" + "testing" +) + +// An MCP connect error can carry the remote server's response body. Logged +// raw, a CR or LF in it would start a line that looks like ARTEX's own. +func TestMCPFailureLogQuotesCRLF(t *testing.T) { + var buf bytes.Buffer + prevOut, prevFlags := log.Writer(), log.Flags() + log.SetOutput(&buf) + log.SetFlags(0) + t.Cleanup(func() { log.SetOutput(prevOut); log.SetFlags(prevFlags) }) + + for _, stage := range []string{"connect", "tools/list"} { + buf.Reset() + logMCPFailure("remote", stage, errors.New("mcp http 500: bad\r\n[auth] admin password changed\rx\ny")) + line := strings.TrimSuffix(buf.String(), "\n") + if strings.ContainsAny(line, "\r\n") { + t.Fatalf("%s: log line contains a raw CR or LF: %q", stage, buf.String()) + } + if !strings.Contains(line, `\r\n[auth] admin password changed`) || !strings.HasPrefix(line, "[mcp] remote "+stage+" failed: ") { + t.Fatalf("%s: unexpected log line %q", stage, line) + } + } +} diff --git a/server/secrets_api_test.go b/server/secrets_api_test.go index 2298f6ae..f44a54a1 100644 --- a/server/secrets_api_test.go +++ b/server/secrets_api_test.go @@ -237,22 +237,27 @@ func TestProxySecretsAPI(t *testing.T) { t.Fatalf("profile proxy not masked: %+v", p) } } - save := func(proxyJSON string, want int) { + save := func(proxyJSON, apiKey string, want int) { t.Helper() - body := `{"id":` + strconv.FormatInt(id, 10) + `,"name":"t-proxy","format":"openai","model":"m","proxy":` + proxyJSON + `}` + body := `{"id":` + strconv.FormatInt(id, 10) + `,"name":"t-proxy","format":"openai","model":"m","proxy":` + proxyJSON + `,"api_key":"` + apiKey + `"}` if resp := request("POST", "/api/llm/profiles", body); resp.Code != want { t.Fatalf("save proxy %s: want HTTP %d, got %d %s", proxyJSON, want, resp.Code, resp.Body.String()) } } - save(`"__masked__"`, 200) + save(`"__masked__"`, "", 200) if proxy() != "http://u:llmp-pass-0011@llm.example:3128" { t.Fatal("the placeholder replaced the stored profile proxy") } - save(`"socks5://llm2.example:1080"`, 200) + // The stored key only stays with the proxy it was saved for. + save(`"socks5://llm2.example:1080"`, "", 400) + if proxy() != "http://u:llmp-pass-0011@llm.example:3128" { + t.Fatal("a refused proxy change replaced the stored profile proxy") + } + save(`"socks5://llm2.example:1080"`, "sk-rotated-0012", 200) if proxy() != "socks5://llm2.example:1080" { t.Fatal("explicit proxy not saved") } - save(`""`, 200) + save(`""`, "sk-rotated-0013", 200) if proxy() != "" { t.Fatal("empty proxy must clear") } diff --git a/server/server.go b/server/server.go index e4b72103..41327745 100644 --- a/server/server.go +++ b/server/server.go @@ -490,8 +490,9 @@ func (s *Server) saveLLMConfig(cfg agent.Config) error { 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) { + // endpoint's default profile to another destination or egress + // proxy. + if !sameLLMRoute(format, cfg.BaseURL, cfg.Proxy, p.Format, p.BaseURL, p.Proxy) { clearCustomHeaders = true } id, priority, poolExclude, streaming = p.ID, p.Priority, p.PoolExclude, p.Streaming @@ -4745,8 +4746,7 @@ func (s *Server) gc(w http.ResponseWriter, r *http.Request) { // Allow-Credentials and a Content-Type-only allow-list that could not grant a // cross-origin session, but it was still the wrong default for an authenticated // API. The loopback exception only reflects a loopback Origin against a -// loopback target, so a remote page cannot read the API through it. sameOrigin -// is the same check requireAuth applies to cookie sessions and stays strict. +// loopback target, so a remote page cannot read the API through it. func cors(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { origin := r.Header.Get("Origin") diff --git a/server/server_mgmt.go b/server/server_mgmt.go index 28f109f4..a36548c9 100644 --- a/server/server_mgmt.go +++ b/server/server_mgmt.go @@ -2170,27 +2170,36 @@ func (s *Server) pgSaveProfile(w http.ResponseWriter, r *http.Request) { } p.Proxy = stored.Proxy } + // A blank api_key keeps the stored key (db.SaveProfile). That key may only + // stay with the provider, endpoint and proxy it was saved for, whatever the + // format: a changed route needs the key entered again. + if p.ID != 0 { + stored, err := pg.ProfileByID(p.ID) + if err != nil { + writeErr(w, 500, err.Error()) + return + } + if stored != nil && !sameLLMRoute(p.Format, p.BaseURL, p.Proxy, stored.Format, stored.BaseURL, stored.Proxy) { + if strings.TrimSpace(p.APIKey) == "" { + if p.Format == "bedrock-gateway" { + writeErr(w, 400, "enter the bearer token when changing the Bedrock gateway endpoint or proxy") + return + } + if stored.APIKey != "" { + writeErr(w, 400, "enter the API key when changing the provider, base URL or proxy; the saved key is only sent over the route it was saved for") + return + } + } + if p.Format == "bedrock-gateway" && p.CustomHeaders == "" { + p.ClearCustomHeaders = true + } + } + } 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 && !sameLLMRoute(p.Format, p.BaseURL, p.Proxy, stored.Format, stored.BaseURL, stored.Proxy) { - if strings.TrimSpace(p.APIKey) == "" { - writeErr(w, 400, "enter the bearer token when changing the Bedrock gateway endpoint or proxy") - return - } - if p.CustomHeaders == "" { - p.ClearCustomHeaders = true - } - } - } } else if p.CustomHeaders != "" { writeErr(w, 400, "custom headers require the Bedrock gateway format") return diff --git a/web/scripts/auth.test.mjs b/web/scripts/auth.test.mjs index 79ac1702..76f441af 100644 --- a/web/scripts/auth.test.mjs +++ b/web/scripts/auth.test.mjs @@ -26,3 +26,19 @@ test("HTTPS marks the session cookie Secure while local HTTP remains usable", () assert.ok(document.cookie.includes("SameSite=Lax")); } }); + +test("the route-guard cookie is a marker and never carries the session token", () => { + const storage = new Map(); + const document = { cookie: "" }; + const exports = {}; + vm.runInNewContext(output, { + exports, + document, + window: { location: { protocol: "https:" } }, + localStorage: { setItem: (k, v) => storage.set(k, v) }, + }); + exports.auth.setToken("synthetic.session.token"); + assert.equal(storage.get("artex_token"), "synthetic.session.token"); + assert.ok(document.cookie.startsWith("artex_token=1;"), document.cookie); + assert.ok(!document.cookie.includes("synthetic"), document.cookie); +}); diff --git a/web/src/app/(main)/system/logs/page.tsx b/web/src/app/(main)/system/logs/page.tsx index 8865d5c3..5a7b90db 100644 --- a/web/src/app/(main)/system/logs/page.tsx +++ b/web/src/app/(main)/system/logs/page.tsx @@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { t } from "@/i18n"; import { openSSE } from "@/lib/api"; +import { auth } from "@/lib/auth"; import { MOCK } from "@/lib/mock/enabled"; import type { LogLine } from "@/lib/types"; import { cn } from "@/lib/utils"; @@ -125,7 +126,10 @@ export default function LogsPage() { setLoadingHistory(true); try { const params = minDbId > 0 ? `?before=${minDbId}&limit=200` : `?limit=200`; - const res = await fetch(`/api/logs/history${params}`); + const token = auth.getToken(); + const res = await fetch(`/api/logs/history${params}`, { + headers: token ? { Authorization: `Bearer ${token}` } : {}, + }); if (!res.ok) return; const data = (await res.json()) as { items: LogLine[]; has_more: boolean }; if (data.items?.length) { diff --git a/web/src/lib/auth.ts b/web/src/lib/auth.ts index f60ef004..5ce44e48 100644 --- a/web/src/lib/auth.ts +++ b/web/src/lib/auth.ts @@ -19,9 +19,12 @@ export const auth = { setToken(token: string): void { localStorage.setItem(TOKEN_KEY, token); - // Also write a cookie for the Next.js middleware to read server-side + // Also write a cookie for the Next.js route guard (src/proxy.ts), which only + // checks that it is present. It holds a marker, not the token: the API takes + // the session from the Authorization header only, and a cookie the browser + // sends on its own must not carry a credential. const secure = window.location.protocol === "https:" ? "; Secure" : ""; - document.cookie = `${TOKEN_KEY}=${encodeURIComponent(token)}; path=/; max-age=${COOKIE_MAX_AGE}; SameSite=Lax${secure}`; + document.cookie = `${TOKEN_KEY}=1; path=/; max-age=${COOKIE_MAX_AGE}; SameSite=Lax${secure}`; }, clearToken(): void {