Compare commits

...
Author SHA1 Message Date
BaaRai c4d1462eb7 server: bind custom HTTP tool secrets to one origin 2026-12-03 18:56:54 +01:00
3 changed files with 364 additions and 2 deletions
+1
View File
@@ -6,6 +6,7 @@ All notable changes to this project are documented in this file. The format is b
### Security
- **HTTP custom tools bind stored headers and body to one origin.** A tool saved with a masked secret kept it while the literal url template stayed the same, so a template with a parameterized host (`https://{host}/collect`) could send the stored `X-API-Key` and body to an attacker-chosen host. A redirect from the configured host could also replay them to another origin: Go copies custom headers, and 307/308 replay the body. A secret-bearing HTTP tool now needs a fixed scheme, host and port in its url template, the rendered url must stay on that origin, and a redirect to another origin is refused; an edit that keeps a masked value may not add or change the proxy either (clearing it is allowed, the request then goes to the fixed origin). Tools without stored headers or body are unchanged. Every non-empty header value and body counts as stored, so a saved tool with a parameterized url and a constant header (`Content-Type`) or a body template is now refused at save and at run, and a secret-bearing tool whose API redirects to another host, port or scheme (apex to `www`, `http` to `https`, a CDN) now fails on that redirect.
- **The target gate honors operator-approved egress grants.** The gate compared every target with pins only, while the sandbox proxy allowed every port of an operator-approved CIDR grant: a host already inside a granted task or company scope still raised per-port and bare-host approval prompts (pins match `host:port`, and a request naming the host without a port is covered only by a port-0 pin). `CheckTargets` now also consults the grants the operator approved for the task (its approved, unexpanded `task_scope` rows and the entries frozen into `task_scope_egress` by approved company grants, normalized as the proxy allowlist is): a domain matching a granted domain, an address inside a granted CIDR, or a range fully inside one passes as covered by `scope_grant`, recorded once per process and target key as a system-decided allowed row with the target outcome `scope_grant`. Pins, stored exemptions, block rules and human approvals are unchanged: anything outside a grant is decided as before, and task allow rules play no role, as everywhere in the gate. Related to #830, the mirror gap on the network side.
- **Chat-spawned tasks inherit fully operator-approved companies (#830).** Migration `0025_company_scope_approved.sql` made company scope an explicit operator decision, but `spawn_task` still stamped the whole company link `approved_by_operator=false`, so a chat-spawned task started with an empty egress allowlist and every connection was denied until an operator approved scope again per task (the trap #833 warns about). `CreateTaskWithOptions` now checks each LLM-selected company: one whose scope inventory exists and is entirely operator-approved and to which the calling task itself holds an operator-approved link carries standing consent, so its task link is inserted approved (a spawn with no task caller - chat session or direct API - inherits nothing, per review on #841) and its grant frozen into `task_scope_egress`, exactly as an operator selection does; a company holding any agent-written (unapproved) row, and one with no scope rows, stay coverage-only, so `add_company_scope`, the ScopeSentry sync and invented ids still grant nothing without a fresh operator decision. Provenance is preserved: `source` stays `agent` and the approval column records the inherited consent row by row. Related: #830, #833.
+138 -2
View File
@@ -12,6 +12,7 @@ import (
"fmt"
"io"
"log/slog"
"net"
"net/http"
"net/url"
"os"
@@ -413,8 +414,25 @@ func unmaskToolExec(storedKind string, stored json.RawMessage, kind string, in j
}
oldURL, _ := old["url"].(string)
newURL, _ := e["url"].(string)
if kept && (oldURL != newURL || storedKind != kind) {
return nil, fmt.Errorf("destination changed (url or kind) while a stored secret was kept: re-enter the masked header/proxy/body or clear it; stored secrets are not sent to a new destination")
oldProxy, _ := old["proxy"].(string)
newProxy, _ := e["proxy"].(string)
oldRecording, _ := old["use_recording_proxy"].(bool)
newRecording, _ := e["use_recording_proxy"].(bool)
if kept {
if oldURL != newURL || storedKind != kind || oldRecording != newRecording {
return nil, fmt.Errorf("destination or recording proxy changed while a stored secret was kept: re-enter the masked header/proxy/body or clear it; stored secrets are not sent to a new destination")
}
// Clearing the configured proxy sends the request to the tool's fixed
// destination, not to a third party. Switching to another proxy does not
// have that guarantee.
if newProxy != "" && newProxy != oldProxy {
return nil, fmt.Errorf("proxy changed while a stored secret was kept: re-enter the masked header/body or clear it; stored secrets are not sent to a new proxy")
}
}
if kind == "http" {
if err := validateHTTPToolExec(e); err != nil {
return nil, err
}
}
if !changed {
return in, nil
@@ -698,6 +716,13 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
if strings.TrimSpace(rawURL) == "" {
return actool.Errorf("http url is empty"), nil
}
// A tool with stored headers or body may only send them to the origin it was
// configured for: the scheme, host and port of the url template cannot be
// parameters, and the rendered url must stay on that origin.
secretOrigin, originErr := httpToolSecretOrigin(spec, rawURL)
if originErr != nil {
return actool.Errorf(originErr.Error()), nil
}
// ARTEX_SANDBOX=required: the request leaves from the panel process, not from
// the task's worker container and its egress proxy. The task's egress policy,
// the one WebFetch enforces, applies here to the URL, to every redirect hop
@@ -741,6 +766,9 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
if sbPolicy != nil {
client.CheckRedirect = sandboxRedirectCheck(sbPolicy, client.CheckRedirect)
}
if secretOrigin != "" {
client.CheckRedirect = secretOriginRedirectCheck(secretOrigin, client.CheckRedirect)
}
// The current egress governor paces every request and redirect hop per host
// under the noise profile (off by default: the base transport itself). It is
// resolved per request, so a changed profile applies to the next call.
@@ -765,6 +793,114 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
return actool.Text(actool.Capture(tc, string(b))), nil
}
// httpToolHasSecrets reports whether an HTTP tool carries stored values the API
// masks: any non-empty header value or body.
func httpToolHasSecrets(spec httpExec) bool {
for _, v := range spec.Headers {
if strings.TrimSpace(v) != "" {
return true
}
}
return strings.TrimSpace(spec.Body) != ""
}
// validateHTTPToolExec refuses a secret-bearing HTTP tool whose url authority is
// parameterized. The stored headers and body would otherwise follow the rendered
// host to any third party.
func validateHTTPToolExec(e map[string]any) error {
raw, err := json.Marshal(e)
if err != nil {
return nil
}
var spec httpExec
if json.Unmarshal(raw, &spec) != nil {
return errors.New("invalid HTTP tool exec")
}
if !httpToolHasSecrets(spec) {
return nil
}
if _, ok := fixedHTTPOrigin(spec.URL); !ok {
return errors.New("an HTTP tool with stored headers or body needs a fixed origin: the url scheme, host and port cannot contain parameters")
}
return nil
}
// httpToolSecretOrigin returns the origin a secret-bearing HTTP tool must stay
// on, or "" when the tool carries no stored header or body.
func httpToolSecretOrigin(spec httpExec, rawURL string) (string, error) {
if !httpToolHasSecrets(spec) {
return "", nil
}
fixed, ok := fixedHTTPOrigin(spec.URL)
if !ok {
return "", errors.New("this HTTP tool sends stored headers or body, so its url must have a fixed scheme, host and port (no parameters)")
}
u, err := url.Parse(rawURL)
if err != nil {
return "", errors.New("http url is invalid")
}
rendered, err := canonicalOrigin(u)
if err != nil || rendered != fixed {
return "", fmt.Errorf("this HTTP tool sends stored headers or body, so the rendered url must stay on %s", fixed)
}
return fixed, nil
}
// fixedHTTPOrigin returns the canonical origin of a url template whose scheme,
// host and port are literal. ok is false when a parameter or an invalid url
// makes the destination dynamic.
func fixedHTTPOrigin(template string) (string, bool) {
u, err := url.Parse(strings.TrimSpace(template))
if err != nil || u.Scheme == "" || u.Host == "" {
return "", false
}
if strings.ContainsAny(u.Scheme, "{}") || strings.ContainsAny(u.Host, "{}") ||
(u.User != nil && strings.ContainsAny(u.User.String(), "{}")) {
return "", false
}
origin, err := canonicalOrigin(u)
if err != nil {
return "", false
}
return origin, true
}
// canonicalOrigin normalizes scheme, host case and default port, so a redirect
// is same-origin only when it keeps all three.
func canonicalOrigin(u *url.URL) (string, error) {
scheme := strings.ToLower(strings.TrimSpace(u.Scheme))
if scheme != "http" && scheme != "https" {
return "", fmt.Errorf("scheme %q is not http or https", u.Scheme)
}
host := strings.ToLower(strings.TrimSuffix(u.Hostname(), "."))
if host == "" {
return "", errors.New("url has no host")
}
port := u.Port()
if (scheme == "http" && port == "80") || (scheme == "https" && port == "443") {
port = ""
}
if port != "" {
return scheme + "://" + net.JoinHostPort(host, port), nil
}
if strings.Contains(host, ":") {
return scheme + "://[" + host + "]", nil
}
return scheme + "://" + host, nil
}
// secretOriginRedirectCheck refuses a redirect hop that leaves the origin the
// tool's stored headers and body were configured for.
func secretOriginRedirectCheck(origin string, check func(*http.Request, []*http.Request) error) func(*http.Request, []*http.Request) error {
return func(req *http.Request, via []*http.Request) error {
next, err := canonicalOrigin(req.URL)
if err != nil || next != origin {
return errors.New("redirect to a different origin refused: this HTTP tool sends stored headers or body")
}
return check(req, via)
}
}
// assessmentRedirectCheck sheds the generated identifier on the first redirect
// to another origin. net/http copies headers from the initial request for each
// hop, so check the previous hop to keep the identifier off after that point.
+225
View File
@@ -0,0 +1,225 @@
package server
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/notify"
)
func TestFixedHTTPOrigin(t *testing.T) {
for _, tc := range []struct {
url string
want string
ok bool
}{
{"https://api.example.com/x", "https://api.example.com", true},
{"https://API.Example.com:443/x", "https://api.example.com", true},
{"http://api.example.com:80/x", "http://api.example.com", true},
{"http://api.example.com:8080/x", "http://api.example.com:8080", true},
{"https://api.example.com/{path}", "https://api.example.com", true},
{"https://[::1]:443/x", "https://[::1]", true},
{"https://[::1]:8443/x", "https://[::1]:8443", true},
{"https://{user}@api.example.com/x", "", false},
{"https://{host}/x", "", false},
{"https://api.{domain}/x", "", false},
{"https://api.example.com:{port}/x", "", false},
{"ftp://api.example.com/x", "", false},
{"/relative", "", false},
} {
got, ok := fixedHTTPOrigin(tc.url)
if ok != tc.ok || got != tc.want {
t.Errorf("fixedHTTPOrigin(%q) = %q, %v; want %q, %v", tc.url, got, ok, tc.want, tc.ok)
}
}
}
func TestHTTPToolSecretOrigin(t *testing.T) {
// A tool without stored headers or body may keep a parameterized authority.
if origin, err := httpToolSecretOrigin(httpExec{URL: "https://{host}/collect"}, "https://attacker.example/collect"); err != nil || origin != "" {
t.Fatalf("no-secret tool: origin=%q err=%v", origin, err)
}
// The rendered url must stay on the template origin.
if _, err := httpToolSecretOrigin(httpExec{
URL: "https://api.example.com/x",
Headers: map[string]string{"X-API-Key": "secret"},
}, "https://attacker.example/x"); err == nil {
t.Fatal("rendered url outside the template origin accepted")
}
}
func TestUnmaskToolExecRequiresFixedOriginForSecrets(t *testing.T) {
exec := func(url string, headers map[string]string) json.RawMessage {
b, _ := json.Marshal(map[string]any{"method": "GET", "url": url, "headers": headers})
return b
}
if _, err := unmaskToolExec("", nil, "http", exec("https://{host}/collect", map[string]string{"X-API-Key": "secret"})); err == nil {
t.Fatal("parameterized authority with a stored header accepted")
}
if _, err := unmaskToolExec("", nil, "http", exec("https://api.example.com/collect", map[string]string{"X-API-Key": "secret"})); err != nil {
t.Fatalf("fixed origin refused: %v", err)
}
if _, err := unmaskToolExec("", nil, "http", exec("https://{host}/collect", nil)); err != nil {
t.Fatalf("parameterized authority without secrets refused: %v", err)
}
if _, err := unmaskToolExec("", nil, "http", exec("https://api.example.com/{path}", map[string]string{"X-API-Key": "secret"})); err != nil {
t.Fatalf("path parameter with a fixed origin refused: %v", err)
}
}
func noSandbox(t *testing.T) {
t.Helper()
prev := agent.CurrentSandboxExecutor()
agent.SetSandboxExecutor(nil)
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
}
func TestHTTPToolRefusesParameterizedAuthorityWithSecrets(t *testing.T) {
noSandbox(t)
raw, _ := json.Marshal(map[string]any{
"method": "GET",
"url": "https://{host}/collect",
"headers": map[string]string{"X-API-Key": "secret"},
})
res, err := (&Server{}).runHTTPTool(context.Background(), "probe", raw, map[string]any{"host": "attacker.example"}, nil)
if err != nil {
t.Fatal(err)
}
if !res.IsError || !strings.Contains(res.Flatten(), "fixed scheme, host and port") {
t.Fatalf("parameterized authority not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
}
func TestUnmaskToolExecRejectsMalformedHTTPExec(t *testing.T) {
raw := json.RawMessage(`{"method":"GET","url":"https://api.example.com/","headers":{"X":1}}`)
if _, err := unmaskToolExec("", nil, "http", raw); err == nil {
t.Fatal("numeric header value accepted")
}
}
func TestUnmaskToolExecRefusesProxyChangeWithSecrets(t *testing.T) {
stored := json.RawMessage(`{"method":"GET","url":"https://api.example.com/collect","headers":{"X-API-Key":"secret"}}`)
masked := func(proxy string, recording bool) json.RawMessage {
m := map[string]any{
"method": "GET",
"url": "https://api.example.com/collect",
"headers": map[string]string{"X-API-Key": notify.MaskedPrefix},
}
if proxy != "" {
m["proxy"] = proxy
}
if recording {
m["use_recording_proxy"] = true
}
b, _ := json.Marshal(m)
return b
}
if _, err := unmaskToolExec("http", stored, "http", masked("http://attacker.example:8080", false)); err == nil {
t.Fatal("proxy change with a kept secret accepted")
}
if _, err := unmaskToolExec("http", stored, "http", masked("", true)); err == nil {
t.Fatal("recording proxy change with a kept secret accepted")
}
if _, err := unmaskToolExec("http", stored, "http", masked("", false)); err != nil {
t.Fatalf("unchanged destination refused: %v", err)
}
storedProxy := json.RawMessage(`{"method":"GET","url":"https://api.example.com/collect","headers":{"X-API-Key":"secret"},"proxy":"http://proxy.example:8080"}`)
if _, err := unmaskToolExec("http", storedProxy, "http", masked("", false)); err != nil {
t.Fatalf("clearing the configured proxy refused: %v", err)
}
}
func TestHTTPToolRefusesParameterizedAuthorityWithBodySecret(t *testing.T) {
noSandbox(t)
raw, _ := json.Marshal(map[string]any{
"method": "POST",
"url": "https://{host}/collect",
"body": "token=secret",
})
res, err := (&Server{}).runHTTPTool(context.Background(), "probe", raw, map[string]any{"host": "attacker.example"}, nil)
if err != nil {
t.Fatal(err)
}
if !res.IsError || !strings.Contains(res.Flatten(), "fixed scheme, host and port") {
t.Fatalf("body-bearing parameterized authority not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
}
func TestHTTPToolSecretStaysOnConfiguredOrigin(t *testing.T) {
noSandbox(t)
for _, code := range []int{http.StatusTemporaryRedirect, http.StatusPermanentRedirect} {
t.Run(http.StatusText(code), func(t *testing.T) {
var outsideHits atomic.Int32
outside := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
outsideHits.Add(1)
_, _ = w.Write([]byte("outside"))
}))
defer outside.Close()
var startHits atomic.Int32
start := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
startHits.Add(1)
if got := r.Header.Get("X-API-Key"); got != "secret" {
t.Errorf("first hop header = %q, want secret", got)
}
http.Redirect(w, r, outside.URL+"/stolen", code)
}))
defer start.Close()
raw, _ := json.Marshal(map[string]any{
"method": "GET",
"url": start.URL + "/start",
"headers": map[string]string{"X-API-Key": "secret"},
})
res, err := (&Server{}).runHTTPTool(context.Background(), "probe", raw, nil, nil)
if err != nil {
t.Fatal(err)
}
if !res.IsError || !strings.Contains(res.Flatten(), "different origin") {
t.Fatalf("cross-origin redirect not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := outsideHits.Load(); n != 0 {
t.Fatalf("outside origin received %d request(s)", n)
}
if n := startHits.Load(); n != 1 {
t.Fatalf("start origin hits = %d, want 1", n)
}
})
}
}
func TestHTTPToolSecretAllowsSameOriginRedirect(t *testing.T) {
noSandbox(t)
var finalHits atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/start" {
http.Redirect(w, r, "/final", http.StatusFound)
return
}
finalHits.Add(1)
_, _ = w.Write([]byte("final"))
}))
defer srv.Close()
raw, _ := json.Marshal(map[string]any{
"method": "GET",
"url": srv.URL + "/start",
"headers": map[string]string{"X-API-Key": "secret"},
})
res, err := (&Server{}).runHTTPTool(context.Background(), "probe", raw, nil, nil)
if err != nil {
t.Fatal(err)
}
if res.IsError {
t.Fatalf("same-origin redirect refused: %s", res.Flatten())
}
if n := finalHits.Load(); n != 1 {
t.Fatalf("final origin hits = %d, want 1", n)
}
}