Merge branch 'worktree-agent-a6787b14310453b9c'

This commit is contained in:
2026-12-03 23:41:55 +00:00
33 changed files with 771 additions and 58 deletions
+4 -2
View File
@@ -51,8 +51,10 @@ func main() {
if accessToken, err = servertoken.Read(*tokenFile); err != nil {
log.Fatalf("server token: %v", err)
}
// Stages, chat harnesses and their `pipelines` CLI calls inherit the
// file's location, never the token itself.
// Recorded for the server's own reads. Agent processes (stages, chat
// harnesses, `!` lines, checks) never inherit it: internal/agentenv
// drops it, and their `pipelines` CLI calls fall back to the default
// location (servertoken.DefaultPath).
_ = os.Setenv(servertoken.EnvKey, *tokenFile)
} else {
log.Printf("no server token configured (-token-file): local clients reach this server without the shared secret")
+35
View File
@@ -68,6 +68,34 @@ crafted link to a file the attacker has placed in the user's home directory.
| M6 | Medium | Chat transcripts and notifications are not redacted | Medium |
| L* | Low | Links open without confirmation; OSC 52 clipboard writes; notification `link=` to any URL; `ws://` peers; TOCTOU in `/files`; debug-keystore APK signing; and more | |
### Status (2026-12-03)
| ID | Status | Change |
| --- | --- | --- |
| H1 | **Fixed** | `e39a9560`: `/files` and `/artifacts/` send the sandbox CSP and `nosniff`; `/files` serves HTML, XHTML, SVG, XML, XSL, JavaScript and `multipart/x-mixed-replace` (including sniffed extensionless files) as attachments. The web proxy adds the same headers to every proxied `/files` and `/artifacts/` response, and the peer relay shares the helper. |
| H3 | **Partially fixed** (layer 1) | `b24fc317`: `internal/agentenv` drops every `PIPELINES_*` token, secret, password, auth or key variable from agent child environments (harness stages and chats, `!` lines, checks, delivery checks, OpenCode serve processes, MCP children through their harness). The secret files stay readable by the same OS user; no sandbox, by decision. |
| M1 | Removed | ntfy is being removed from Pipelines in a separate change. |
| H2, H4, M2, M3, M4, M5, M6, L* | Accepted | By design for a single-user self-hosted tool; see [Decisions](#decisions). |
### Decisions
The operator accepted the remaining findings as by design for a single-user,
self-hosted tool, keeping friction at zero:
- **Agents intentionally have full host access.** There is no OS sandbox
(bubblewrap, `sandbox-exec`, a separate user or a container) and none is
planned. Agents can read every file the user can, including Pipelines'
own secret files; layer 1 only removes the pointers from their environment.
- **The web password is the shell password.** Mode switches into Claude
`bypassPermissions` or Codex `full` are not gated by elevation, and the
elevation lifetime stays as it is (H2).
- **Stage defaults stay as they are** (H4): no `tools` block still grants
read/glob/grep/edit/shell.
- **`show_html` previews are not tightened** (M4): they may legitimately load
CDN scripts and CSS.
- **No supply-chain pinning, default run budget, concurrency cap or
redaction** (M2, M5, M6).
---
## 3. Findings in detail
@@ -276,6 +304,10 @@ shapes, not a pristine default): `ss -ltnH | awk '{print $4}'`
#### H3. Agents are unsandboxed and inherit every secret (High)
**Status: partially fixed in `b24fc317`.** Secret-pointer variables are now
scrubbed from agent environments. Being unsandboxed is accepted by design (see
Decisions).
- **Evidence:**
- Every harness runs as the server's UID with `os.Environ()`:
- `internal/stage/claude_stage.go:360`
@@ -397,6 +429,9 @@ shapes, not a pristine default): `ss -ltnH | awk '{print $4}'`
#### H1. `GET /files` serves HTML/SVG inline on the app origin (High)
**Status: fixed in `e39a9560`** (see the status table in section 2). The
evidence below describes the code before the fix.
- **Evidence:**
- `internal/server/home_files.go:68-92`: the type comes from the extension,
the disposition is `inline` by default, and only `nosniff` is set. There is
+85
View File
@@ -0,0 +1,85 @@
// Package agentenv builds the environment of every process the server starts
// on an agent's behalf: harness processes (stages and chats), `!` shell lines,
// check-stage commands and the tools those spawn.
//
// The server's own environment carries pointers to Pipelines' secrets (the
// server token, the web sign-in file with the cookie key, the update-signing
// key, harness service tokens). An agent has no use for them, and a
// prompt-injected one could follow them, so Scrub drops every such variable
// while keeping everything a harness legitimately needs (PATH, HOME, its own
// config directory and credentials, and the workspace's direnv/mise output).
//
// This only removes the pointers. The files themselves stay readable by the
// server's OS user: agents intentionally keep full host access (see
// docs/security-review.md, "Decisions").
// The operator's interactive terminal is deliberately out of scope.
package agentenv
import (
"os"
"strings"
)
// secretMarkers are name fragments that mark a PIPELINES_ variable as a
// secret, a credential or the path to one.
var secretMarkers = []string{"TOKEN", "SECRET", "PASSWORD", "PASSWD", "AUTH", "CREDENTIAL", "PRIVATE", "SIGNING", "KEY"}
// publicSuffixes name PIPELINES_ variables that match a marker but carry no
// secret (a public verification key).
var publicSuffixes = []string{"_PUBLIC_KEY"}
// Secret reports whether the variable name must not reach an agent process:
// any PIPELINES_ variable naming a token, password, auth file or key.
func Secret(name string) bool {
upper := strings.ToUpper(name)
if !strings.HasPrefix(upper, "PIPELINES_") {
return false
}
for _, suffix := range publicSuffixes {
if strings.HasSuffix(upper, suffix) {
return false
}
}
rest := strings.TrimPrefix(upper, "PIPELINES_")
for _, marker := range secretMarkers {
if strings.Contains(rest, marker) {
return true
}
}
return false
}
// Scrub returns env without the secret variables. A nil env means "inherit
// the server's environment" (exec.Cmd's convention), so it scrubs
// os.Environ() instead: a command given the result never falls back to the
// unscrubbed server environment. The input slice is not modified.
func Scrub(env []string) []string {
if env == nil {
env = os.Environ()
}
out := make([]string, 0, len(env))
for _, entry := range env {
name, _, _ := strings.Cut(entry, "=")
if Secret(name) {
continue
}
out = append(out, entry)
}
return out
}
// Environ is the server's environment without secrets: the base for any agent
// process that would otherwise inherit os.Environ().
func Environ() []string { return Scrub(nil) }
// Leaks returns the secret entries left in env, for tests and diagnostics.
func Leaks(env []string) []string {
var leaks []string
for _, entry := range env {
name, _, _ := strings.Cut(entry, "=")
if Secret(name) {
leaks = append(leaks, entry)
}
}
return leaks
}
+58
View File
@@ -0,0 +1,58 @@
package agentenv
import (
"slices"
"testing"
)
var planted = []string{
"PIPELINES_SERVER_TOKEN_FILE",
"PIPELINES_WEB_AUTH_FILE",
"PIPELINES_WEB_AUTH",
"PIPELINES_WEB_PASSWORD",
"PIPELINES_UPDATE_SIGNING_KEY",
"PIPELINES_CLAUDE_TOKEN_FILE",
"PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE",
"PIPELINES_NTFY_TOKEN_FILE",
"PIPELINES_NTFY_TOKEN",
"PIPELINES_SOMETHING_SECRET",
}
func TestSecretNames(t *testing.T) {
for _, name := range planted {
if !Secret(name) {
t.Errorf("%s should be secret", name)
}
}
for _, name := range []string{"PATH", "HOME", "CLAUDE_CONFIG_DIR", "CODEX_HOME", "CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY",
"PIPELINES_UPDATE_PUBLIC_KEY", "PIPELINES_DEFAULT_MODEL", "PIPELINES_WEB_PUBLIC_URL", "PIPELINES_NTFY_URL", "PIPELINES_ARTIFACTS_DIR", "PIPELINES_MDNS"} {
if Secret(name) {
t.Errorf("%s should be kept", name)
}
}
}
func TestScrubKeepsOrderAndInput(t *testing.T) {
in := []string{"PATH=/bin", "PIPELINES_SERVER_TOKEN_FILE=/x", "HOME=/h", "PIPELINES_WEB_AUTH_FILE=/y", "MALFORMED"}
out := Scrub(in)
if want := []string{"PATH=/bin", "HOME=/h", "MALFORMED"}; !slices.Equal(out, want) {
t.Fatalf("Scrub = %v, want %v", out, want)
}
if in[1] != "PIPELINES_SERVER_TOKEN_FILE=/x" {
t.Fatal("Scrub modified its input")
}
}
func TestScrubNilScrubsServerEnvironment(t *testing.T) {
for _, name := range planted {
t.Setenv(name, "/secret/"+name)
}
t.Setenv("KEEP_ME", "1")
out := Environ()
if !slices.Contains(out, "KEEP_ME=1") {
t.Fatal("ordinary variable dropped")
}
if leaks := Leaks(out); len(leaks) > 0 {
t.Fatalf("secrets leaked: %v", leaks)
}
}
+56
View File
@@ -0,0 +1,56 @@
package claude
import (
"context"
"testing"
)
// A chat's Claude Code process never sees Pipelines' own secret pointers,
// while the server still resolves its service token for it.
func TestChatProcessEnvironmentScrubsPipelinesSecrets(t *testing.T) {
chat := directoryChat(t)
t.Setenv("PIPELINES_SERVER_TOKEN_FILE", "/secret/server-token")
t.Setenv("PIPELINES_WEB_AUTH_FILE", "/secret/web-auth.json")
t.Setenv("PIPELINES_UPDATE_SIGNING_KEY", "/secret/update-signing-key.pem")
t.Setenv("FAKE_CLAUDE_ENV_KEYS", "PIPELINES_SERVER_TOKEN_FILE,PIPELINES_WEB_AUTH_FILE,PIPELINES_UPDATE_SIGNING_KEY,PIPELINES_CLAUDE_TOKEN_FILE,CLAUDE_CODE_OAUTH_TOKEN")
session := newCreatedChat(t, chat)
frames := subscribe(t, chat, session.ID)
if err := chat.Prompt(context.Background(), session.ID, "hello"); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
spawn := lastSpawn(t)
for _, key := range []string{"PIPELINES_SERVER_TOKEN_FILE", "PIPELINES_WEB_AUTH_FILE", "PIPELINES_UPDATE_SIGNING_KEY", ServiceTokenEnvKey} {
if got := envOf(spawn, key); got != "<unset>" {
t.Errorf("%s reached Claude Code: %q", key, got)
}
}
if envOf(spawn, "CLAUDE_CODE_OAUTH_TOKEN") != "service-token" {
t.Fatalf("service token no longer resolved for the chat: %v", spawn.Env)
}
}
// A hosted chat's Claude Code (server -> pipelines-claude-host -> CLI) never
// sees them either.
func TestHostedChatProcessEnvironmentScrubsPipelinesSecrets(t *testing.T) {
hostedSetup(t)
t.Setenv("PIPELINES_SERVER_TOKEN_FILE", "/secret/server-token")
t.Setenv("PIPELINES_WEB_AUTH_FILE", "/secret/web-auth.json")
t.Setenv("FAKE_CLAUDE_ENV_KEYS", "PIPELINES_SERVER_TOKEN_FILE,PIPELINES_WEB_AUTH_FILE,CLAUDE_CONFIG_DIR")
chat := hostedChat(t)
session := newCreatedChat(t, chat)
frames := subscribe(t, chat, session.ID)
if err := chat.Prompt(context.Background(), session.ID, "hello"); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
spawn := lastSpawn(t)
for _, key := range []string{"PIPELINES_SERVER_TOKEN_FILE", "PIPELINES_WEB_AUTH_FILE"} {
if got := envOf(spawn, key); got != "<unset>" {
t.Errorf("%s reached the hosted Claude Code: %q", key, got)
}
}
if envOf(spawn, "CLAUDE_CONFIG_DIR") == "<unset>" {
t.Fatalf("harness config directory dropped: %v", spawn.Env)
}
}
+3 -1
View File
@@ -10,6 +10,7 @@ import (
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/agentenv"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
@@ -124,7 +125,8 @@ func (c *Chat) processEnvFrom(ctx context.Context, directory string, base []stri
if value, ok := envValue(env, "CLAUDE_CONFIG_DIR"); ok {
rememberConfigDir(value)
}
return workenv.WithPWD(env, directory), dir.Warnings
// Pipelines' own secrets never reach the CLI or its tools.
return workenv.WithPWD(agentenv.Scrub(env), directory), dir.Warnings
}
// HintDirectory tells the adapter the recorded directory of a session it has
+2 -1
View File
@@ -14,6 +14,7 @@ import (
"sync/atomic"
"time"
"git.a-wan.net/alan/pipelines/internal/agentenv"
"git.a-wan.net/alan/pipelines/internal/claudehost"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
@@ -192,7 +193,7 @@ func (s *session) spawnOnce(ctx context.Context) (*process, error) {
func (s *session) startDirect(args []string, mode string, env []string) (*process, error) {
cmd := exec.CommandContext(s.chat.ctx, s.chat.binary, args...)
cmd.Dir = s.directory
cmd.Env = env
cmd.Env = agentenv.Scrub(env)
cmd.WaitDelay = 5 * time.Second
stdin, err := cmd.StdinPipe()
if err != nil {
+4 -1
View File
@@ -15,6 +15,8 @@ import (
"sync"
"syscall"
"time"
"git.a-wan.net/alan/pipelines/internal/agentenv"
)
// Conn is a server's connection to one host.
@@ -180,7 +182,8 @@ func Spawn(ctx context.Context, options SpawnOptions) (*exec.Cmd, error) {
args = append(args, options.Args...)
cmd := exec.Command(options.HostBinary, args...)
cmd.Dir = options.Cwd
cmd.Env = options.Env
// The host and the CLI it starts never see Pipelines' own secrets.
cmd.Env = agentenv.Scrub(options.Env)
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
logFile, err := os.OpenFile(paths.Log, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
if err != nil {
+3 -1
View File
@@ -17,6 +17,8 @@ import (
"sync"
"syscall"
"time"
"git.a-wan.net/alan/pipelines/internal/agentenv"
)
// Defaults for a host started without explicit limits.
@@ -197,7 +199,7 @@ func (h *host) start(command []string) error {
_ = os.Chmod(h.paths.Socket, 0o600)
h.listener = listener
cmd := exec.Command(command[0], command[1:]...)
cmd.Env = os.Environ()
cmd.Env = agentenv.Environ()
// Its own process group, so the CLI and its tool subprocesses stop together.
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
stdin, err := cmd.StdinPipe()
+2 -1
View File
@@ -20,6 +20,7 @@ import (
"syscall"
"unicode/utf8"
"git.a-wan.net/alan/pipelines/internal/agentenv"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/workenv"
"github.com/pmezard/go-difflib/difflib"
@@ -123,7 +124,7 @@ type Snapshot struct {
// (workenv.WithEnvironment) when ctx carries one, as the stage's own git sees.
func gitCommand(ctx context.Context, directory string, args ...string) *exec.Cmd {
cmd := exec.CommandContext(ctx, "git", args...)
cmd.Env = workenv.CommandEnv(ctx, directory)
cmd.Env = agentenv.Scrub(workenv.CommandEnv(ctx, directory))
return cmd
}
+31
View File
@@ -0,0 +1,31 @@
package opencode
import (
"os"
"slices"
"testing"
"git.a-wan.net/alan/pipelines/internal/agentenv"
)
// The OpenCode serve processes (chat service and owned stage services) and the
// tools they run never see Pipelines' own secret pointers.
func TestServiceEnvironmentScrubsPipelinesSecrets(t *testing.T) {
t.Setenv("PIPELINES_SERVER_TOKEN_FILE", "/secret/server-token")
t.Setenv("PIPELINES_WEB_AUTH_FILE", "/secret/web-auth.json")
t.Setenv("PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE", "/secret/opencode-password")
t.Setenv("KEEP_ME", "1")
for name, env := range map[string][]string{
"chat service": serviceEnvironment(`{"a":1}`),
"stage service (server env)": serviceEnvironmentFrom(nil, ""),
"stage service (run env)": serviceEnvironmentFrom(append(os.Environ(), "PIPELINES_X_TOKEN=envrc"), ""),
"stage service (owned config)": serviceEnvironmentFrom(os.Environ(), `{"b":2}`),
} {
if leaks := agentenv.Leaks(env); len(leaks) > 0 {
t.Errorf("%s leaks %v", name, leaks)
}
if !slices.Contains(env, "KEEP_ME=1") {
t.Errorf("%s dropped an ordinary variable", name)
}
}
}
+5 -2
View File
@@ -6,6 +6,8 @@ import (
"os"
"strconv"
"strings"
"git.a-wan.net/alan/pipelines/internal/agentenv"
)
// Stage and chat OpenCode limits. OpenCode reads tool_output and compaction
@@ -151,10 +153,11 @@ func serviceEnvironment(content string) []string {
}
// serviceEnvironmentFrom is serviceEnvironment over base instead of the
// server's own environment (a run directory's resolved environment).
// server's own environment (a run directory's resolved environment). Pipelines'
// own secrets never reach the serve process or the tools it runs.
func serviceEnvironmentFrom(base []string, content string) []string {
var env []string
for _, entry := range base {
for _, entry := range agentenv.Scrub(base) {
if strings.HasPrefix(entry, "OPENCODE_SERVER_PASSWORD=") || strings.HasPrefix(entry, "OPENCODE_SERVER_USERNAME=") ||
(content != "" && strings.HasPrefix(entry, "OPENCODE_CONFIG_CONTENT=")) {
continue
+81
View File
@@ -0,0 +1,81 @@
package server
import (
"context"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/agentenv"
"git.a-wan.net/alan/pipelines/internal/workenv"
"git.a-wan.net/alan/pipelines/internal/workenv/workenvtest"
)
func plantServerSecrets(t *testing.T) {
t.Helper()
t.Setenv("PIPELINES_SERVER_TOKEN_FILE", "/secret/server-token")
t.Setenv("PIPELINES_WEB_AUTH_FILE", "/secret/web-auth.json")
t.Setenv("PIPELINES_UPDATE_SIGNING_KEY", "/secret/update-signing-key.pem")
}
func assertNoSecretLines(t *testing.T, what, output string) {
t.Helper()
if leaks := agentenv.Leaks(strings.Split(strings.ReplaceAll(output, "\r", ""), "\n")); len(leaks) > 0 {
t.Fatalf("%s leaks Pipelines secrets: %v", what, leaks)
}
if !strings.Contains(output, "PATH=") {
t.Fatalf("%s lost PATH: %q", what, output)
}
}
// `!` shell lines run without Pipelines' own secret pointers.
func TestChatShellCommandEnvironmentIsScrubbed(t *testing.T) {
plantServerSecrets(t)
cmd := exec.Command("sh", "-c", "env")
reader, _, err := startChatShellCommand(cmd, 0, 0)
if err != nil {
t.Fatal(err)
}
output, _ := io.ReadAll(reader) // a pseudo-terminal ends with EIO
reader.Close()
_ = cmd.Wait()
assertNoSecretLines(t, "chat shell command", string(output))
}
// A delivery gate's check command runs without them too.
func TestDeliveryCheckEnvironmentIsScrubbed(t *testing.T) {
plantServerSecrets(t)
err := runDeliveryCheck(context.Background(), t.TempDir(), "env; exit 1")
if err == nil {
t.Fatal("the failing check passed")
}
assertNoSecretLines(t, "delivery check", err.Error())
}
// A run's resolved workspace environment, the base of every stage process,
// check and OpenCode stage service, starts from the scrubbed server
// environment.
func TestRunEnvironmentStartsScrubbed(t *testing.T) {
workenvtest.InstallDirenv(t)
plantServerSecrets(t)
project, _ := filepath.EvalSymlinks(t.TempDir())
workenvtest.WriteEnvrc(t, project, true, map[string]*string{"SCRATCH_VAR": workenvtest.Str("from-envrc")})
ctx, r, _ := concurrentStore(t)
r.dirEnv = &workenv.Resolver{}
env, _ := workenv.FromContext(r.withRunEnvironment(ctx, 1, project))
if !env.Applies() {
t.Fatalf("the workspace environment did not apply: %+v", env)
}
if leaks := agentenv.Leaks(env.Env); len(leaks) > 0 {
t.Fatalf("run environment leaks %v", leaks)
}
if value, _ := envValue(env.Env, "SCRATCH_VAR"); value != "from-envrc" {
t.Fatalf("workspace variable missing: %v", env.Env)
}
if _, ok := envValue(env.Env, "HOME"); !ok && os.Getenv("HOME") != "" {
t.Fatal("HOME dropped")
}
}
+1 -2
View File
@@ -291,8 +291,7 @@ func (r *runner) serveArtifact(w http.ResponseWriter, req *http.Request) {
// Enforce the boundary on the response itself: opening the raw HTML/SVG in
// a new tab must be as safe as the embedded sandboxed preview. No scripts,
// network calls, forms, same-origin authority or top-level navigation.
w.Header().Set("Content-Security-Policy", "sandbox; default-src 'none'; script-src 'none'; connect-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; media-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'self'")
w.Header().Set("X-Content-Type-Options", "nosniff")
setUntrustedContentHeaders(w.Header())
w.Header().Set("Cache-Control", "private, no-store")
http.ServeContent(w, req, path.Base(name), opened.ModTime(), file)
}
+5 -3
View File
@@ -8,17 +8,19 @@ import (
"syscall"
"unicode/utf8"
"git.a-wan.net/alan/pipelines/internal/agentenv"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// startChatShellCommand starts cmd with the server's environment, in a
// startChatShellCommand starts cmd with the server's environment (minus
// Pipelines' own secrets, agentenv), in a
// pseudo-terminal of cols x rows where the platform has one (TERM is then
// xterm-256color) and otherwise in its own process group with stdout and
// stderr on one pipe. It returns the output reader and, in a terminal, the
// terminal itself (the same file).
func startChatShellCommand(cmd *exec.Cmd, cols, rows int) (reader, terminal *os.File, err error) {
if chatShellTerminals {
cmd.Env = chatShellTerminalEnv(os.Environ())
cmd.Env = chatShellTerminalEnv(agentenv.Environ())
terminal, err = startChatShellTerminal(cmd, cols, rows)
return terminal, terminal, err
}
@@ -26,7 +28,7 @@ func startChatShellCommand(cmd *exec.Cmd, cols, rows int) (reader, terminal *os.
if err != nil {
return nil, nil, err
}
cmd.Env = os.Environ()
cmd.Env = agentenv.Environ()
cmd.Stdout, cmd.Stderr = writer, writer
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
err = cmd.Start()
+4 -3
View File
@@ -13,6 +13,7 @@ import (
"syscall"
"time"
"git.a-wan.net/alan/pipelines/internal/agentenv"
"git.a-wan.net/alan/pipelines/internal/stage"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
@@ -240,7 +241,7 @@ func cleanupDeliveryCandidate(workspace, candidate string) {
func boundedCommandOutput(ctx context.Context, directory string, args ...string) ([]byte, error) {
cmd := exec.CommandContext(ctx, "git", append([]string{"-C", directory}, args...)...)
cmd.Env = workenv.CommandEnv(ctx, directory)
cmd.Env = agentenv.Scrub(workenv.CommandEnv(ctx, directory))
var output boundedDeliveryOutput
cmd.Stdout = &output
cmd.Stderr = &output
@@ -252,8 +253,8 @@ func runDeliveryCheck(ctx context.Context, directory, check string) error {
cmd := exec.CommandContext(ctx, "sh", "-c", check)
cmd.Dir = directory
// The run workspace's own environment (direnv/mise), as a terminal there
// would have it; nil inherits the server's.
cmd.Env = workenv.CommandEnv(ctx, directory)
// would have it, else the server's; never Pipelines' own secrets.
cmd.Env = agentenv.Scrub(workenv.CommandEnv(ctx, directory))
var output boundedDeliveryOutput
cmd.Stdout = &output
cmd.Stderr = &output
+4 -2
View File
@@ -65,7 +65,9 @@ func serveHomeFileFrom(w http.ResponseWriter, r *http.Request, home string) {
defer file.Close()
w.Header().Set("Cache-Control", "private, no-cache")
w.Header().Set("X-Content-Type-Options", "nosniff")
// A home file is untrusted content (a download, a cloned repository, an
// agent's output), never part of the control UI.
setUntrustedContentHeaders(w.Header())
contentType := mime.TypeByExtension(filepath.Ext(realTarget))
if contentType == "" {
var sample [512]byte
@@ -85,7 +87,7 @@ func serveHomeFileFrom(w http.ResponseWriter, r *http.Request, home string) {
}
w.Header().Set("Content-Type", contentType)
disposition := "inline"
if r.URL.Query().Get("download") == "1" {
if r.URL.Query().Get("download") == "1" || scriptCapableType(contentType) {
disposition = "attachment"
}
w.Header().Set("Content-Disposition", contentDisposition(disposition, filepath.Base(realTarget)))
+51
View File
@@ -86,3 +86,54 @@ func TestServeHomeFile(t *testing.T) {
}
})
}
func TestServeHomeFileSandboxesScriptCapableTypes(t *testing.T) {
home := t.TempDir()
files := map[string]string{
"page.html": "<script>fetch('/connect')</script>",
"image.svg": `<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>`,
"page.xhtml": "<html xmlns='http://www.w3.org/1999/xhtml'></html>",
"feed.xml": "<?xml version='1.0'?><x/>",
"noext": "<!DOCTYPE html><html><script>alert(1)</script></html>",
"notes.txt": "plain",
"photo.png": "\x89PNG\r\n\x1a\n",
}
for name, body := range files {
if err := os.WriteFile(filepath.Join(home, name), []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
for name := range files {
t.Run(name, func(t *testing.T) {
recorder := httptest.NewRecorder()
serveHomeFileFrom(recorder, httptest.NewRequest(http.MethodGet, "/files?path=~/"+name, nil), home)
if recorder.Code != http.StatusOK {
t.Fatalf("status = %d", recorder.Code)
}
header := recorder.Header()
if csp := header.Get("Content-Security-Policy"); csp != untrustedContentPolicy || !strings.HasPrefix(csp, "sandbox;") {
t.Fatalf("csp = %q", csp)
}
if header.Get("X-Content-Type-Options") != "nosniff" {
t.Fatalf("nosniff = %q", header.Get("X-Content-Type-Options"))
}
wantAttachment := name != "notes.txt" && name != "photo.png"
if got := strings.HasPrefix(header.Get("Content-Disposition"), "attachment;"); got != wantAttachment {
t.Fatalf("disposition = %q (type %q), want attachment %v", header.Get("Content-Disposition"), header.Get("Content-Type"), wantAttachment)
}
})
}
}
func TestScriptCapableType(t *testing.T) {
for _, contentType := range []string{"text/html; charset=utf-8", "application/xhtml+xml", "image/svg+xml", "text/xml", "application/xml", "application/rss+xml", "TEXT/HTML"} {
if !scriptCapableType(contentType) {
t.Errorf("%q should be script-capable", contentType)
}
}
for _, contentType := range []string{"text/plain; charset=utf-8", "image/png", "application/pdf", "application/octet-stream", ""} {
if scriptCapableType(contentType) {
t.Errorf("%q should not be script-capable", contentType)
}
}
}
+4 -2
View File
@@ -3,9 +3,9 @@ package server
import (
"context"
"log"
"os"
"time"
"git.a-wan.net/alan/pipelines/internal/agentenv"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
@@ -22,7 +22,9 @@ func (r *runner) withRunEnvironment(ctx context.Context, id int64, workspace str
if resolver == nil {
resolver = workenv.Default
}
env := resolver.Environment(ctx, workspace, os.Environ())
// Every process started from the run's environment (stages, checks, the
// OpenCode stage service) builds on the server's minus Pipelines' secrets.
env := resolver.Environment(ctx, workspace, agentenv.Environ())
for _, warning := range env.Warnings {
log.Printf("run %d workspace %s: %s", id, workspace, warning)
}
+40
View File
@@ -0,0 +1,40 @@
package server
import (
"mime"
"net/http"
"strings"
)
// untrustedContentPolicy is the response boundary for every file the server
// hands back that it did not write itself: run artifacts, files under the
// operator's home and anything an agent produced. The `sandbox` directive gives
// the document an opaque origin even when opened as a top-level page, so a
// crafted HTML or SVG file cannot script the app origin, reach /connect or read
// other files. The web proxy and the peer relay add the same policy.
const untrustedContentPolicy = "sandbox; default-src 'none'; script-src 'none'; connect-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; media-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'self'"
// setUntrustedContentHeaders applies the sandbox policy and turns off MIME
// sniffing, so a response is never interpreted as a more powerful type.
func setUntrustedContentHeaders(h http.Header) {
h.Set("Content-Security-Policy", untrustedContentPolicy)
h.Set("X-Content-Type-Options", "nosniff")
}
// scriptCapableType reports whether a browser could run script in a document of
// this content type when it is opened as a page: HTML, XHTML, SVG and every XML
// flavour (XSLT and XML stylesheets can build HTML). Such files are served as
// downloads; the sandbox policy is the second layer.
func scriptCapableType(contentType string) bool {
media, _, err := mime.ParseMediaType(contentType)
if err != nil {
media = strings.ToLower(strings.TrimSpace(strings.SplitN(contentType, ";", 2)[0]))
}
switch media {
case "text/html", "application/xhtml+xml", "image/svg+xml", "text/xml", "application/xml",
"text/xsl", "application/xslt+xml", "application/javascript", "text/javascript",
"application/ecmascript", "text/ecmascript", "multipart/x-mixed-replace":
return true
}
return strings.HasSuffix(media, "+xml") || strings.HasSuffix(media, "/xml")
}
+4 -2
View File
@@ -1,6 +1,8 @@
// Package servertoken is the shared secret between the Pipelines server and its
// local clients (the authenticated web proxy, the CLI, the TUI and the
// harnesses the server launches).
// local clients (the authenticated web proxy, the CLI and the TUI). Processes
// the server launches for agents do not inherit PIPELINES_SERVER_TOKEN_FILE
// (internal/agentenv); a `pipelines` CLI call from an agent finds the token
// only at the default location.
//
// The installer writes a random token to a private (0600) file next to the web
// sign-in file, by default $XDG_CONFIG_HOME/pipelines/server-token (else
+120
View File
@@ -0,0 +1,120 @@
package stage
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/agentenv"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
// plantSecrets puts Pipelines' secret pointers in the server environment and
// returns a run environment that (as a hostile .envrc might) carries one too.
func plantSecrets(t *testing.T) []string {
t.Helper()
t.Setenv("PIPELINES_SERVER_TOKEN_FILE", "/secret/server-token")
t.Setenv("PIPELINES_WEB_AUTH_FILE", "/secret/web-auth.json")
t.Setenv("PIPELINES_UPDATE_SIGNING_KEY", "/secret/update-signing-key.pem")
return append(os.Environ(), "PIPELINES_SOMETHING_TOKEN=from-envrc", "SCRATCH_VAR=kept")
}
func assertScrubbed(t *testing.T, what string, env []string) {
t.Helper()
if leaks := agentenv.Leaks(env); len(leaks) > 0 {
t.Fatalf("%s leaks Pipelines secrets: %v", what, leaks)
}
if len(env) == 0 {
t.Fatalf("%s environment is empty", what)
}
}
func envLines(t *testing.T, path string) []string {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
return strings.Split(strings.TrimSpace(string(data)), "\n")
}
func TestClaudeStageProcessEnvironmentIsScrubbed(t *testing.T) {
plantSecrets(t)
client, root, _ := fakeClaudeClient(t, "success")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if _, err := client.Generate(ctx, claudeConfig(NewBudget(10, 1000)), "task"); err != nil {
t.Fatal(err)
}
env := envLines(t, filepath.Join(root, "env"))
assertScrubbed(t, "Claude stage", env)
if !strings.Contains(strings.Join(env, "\n"), "HOME="+root) {
t.Fatalf("HOME not kept: %v", env)
}
}
func TestPiStageProcessEnvironmentIsScrubbed(t *testing.T) {
root := t.TempDir()
t.Setenv("XDG_CACHE_HOME", root)
t.Setenv("HOME", root)
t.Setenv("PIPELINES_PI_FIXTURE", "1")
t.Setenv("PI_FIXTURE_CASE", "success")
out := filepath.Join(root, "env.txt")
t.Setenv("PI_FIXTURE_ENV_OUT", out)
runEnv := plantSecrets(t)
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
wrapper := filepath.Join(root, "pi")
if err := os.WriteFile(wrapper, []byte("#!/bin/sh\nexec '"+executable+"' -test.run=^TestPiRPCFixture$\n"), 0700); err != nil {
t.Fatal(err)
}
workspace := t.TempDir()
ctx, cancel := context.WithTimeout(workenv.WithEnvironment(context.Background(), workenv.Environment{Directory: workspace, Env: runEnv, Key: "k"}), 5*time.Second)
defer cancel()
client := &PiClient{Executable: wrapper, Directory: workspace, Tools: []string{}}
if _, err := client.Generate(ctx, ModelConfig{Provider: "fixture", Model: "model", Budget: NewBudget(0, 100)}, "task"); err != nil {
t.Fatal(err)
}
env := envLines(t, out)
assertScrubbed(t, "Pi stage", env)
if !strings.Contains(strings.Join(env, "\n"), "SCRATCH_VAR=kept") {
t.Fatalf("workspace environment lost: %v", env)
}
// Without a run environment the server's own is scrubbed too.
assertScrubbed(t, "Pi stage (server environment)", piEnvironmentFrom(nil, root, ""))
}
func TestOpenCodeStageCLIEnvironmentIsScrubbed(t *testing.T) {
runEnv := plantSecrets(t)
assertScrubbed(t, "OpenCode CLI (server environment)", openCodeCLIEnv(context.Background(), t.TempDir(), "/artifacts"))
directory := t.TempDir()
ctx := workenv.WithEnvironment(context.Background(), workenv.Environment{Directory: directory, Env: runEnv, Key: "k"})
env := openCodeCLIEnv(ctx, directory, "/artifacts")
assertScrubbed(t, "OpenCode CLI (run environment)", env)
if env[len(env)-1] != ArtifactsEnv+"=/artifacts" {
t.Fatalf("artifacts directory missing: %v", env)
}
}
func TestCheckCommandEnvironmentIsScrubbed(t *testing.T) {
runEnv := plantSecrets(t)
directory := t.TempDir()
for _, ctx := range []context.Context{
context.Background(),
workenv.WithEnvironment(context.Background(), workenv.Environment{Directory: directory, Env: runEnv, Key: "k"}),
} {
result := runCheckCommand(ctx, directory, "env", 10*time.Second)
if result.Status != CheckStatusPassed {
t.Fatalf("check failed: %+v", result)
}
assertScrubbed(t, "check command", strings.Split(result.Output, "\n"))
if !strings.Contains(result.Output, "PATH=") {
t.Fatalf("PATH not kept: %s", result.Output)
}
}
}
+8 -1
View File
@@ -12,6 +12,7 @@ import (
"time"
"unicode/utf8"
"git.a-wan.net/alan/pipelines/internal/agentenv"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
@@ -219,7 +220,7 @@ func runCheckCommand(ctx context.Context, directory, command string, timeout tim
defer cancel()
cmd := exec.CommandContext(commandCtx, "sh", "-c", command)
cmd.Dir = directory
cmd.Env = workenv.CommandEnv(ctx, directory)
cmd.Env = checkCommandEnv(ctx, directory)
// A test suite starts children; a timeout kills the whole process group,
// and WaitDelay bounds a child that keeps the output pipes open.
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
@@ -411,3 +412,9 @@ func (b *headTailBuffer) String() (string, bool) {
text := b.first.String() + fmt.Sprintf("\n[... %d bytes omitted ...]\n", b.dropped) + string(tail)
return strings.ToValidUTF8(strings.TrimRight(text, "\n"), "\uFFFD"), true
}
// checkCommandEnv is a check command's environment: the run directory's (or
// the server's) environment without Pipelines' own secrets.
func checkCommandEnv(ctx context.Context, directory string) []string {
return agentenv.Scrub(workenv.CommandEnv(ctx, directory))
}
+4 -5
View File
@@ -16,6 +16,7 @@ import (
"syscall"
"time"
"git.a-wan.net/alan/pipelines/internal/agentenv"
"git.a-wan.net/alan/pipelines/internal/claude"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
@@ -355,10 +356,8 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr
// fallback is added, as in a terminal opened there.
func (c *ClaudeStageClient) environment(ctx context.Context) []string {
run, _ := workenv.FromContext(ctx)
base := run.Command(c.Directory)
if base == nil {
base = os.Environ()
}
// Scrub(nil) is the server's own environment, minus Pipelines' secrets.
base := agentenv.Scrub(run.Command(c.Directory))
owned := map[string]bool{}
for _, key := range workenv.AccountEnvKeys {
owned[key] = true
@@ -767,7 +766,7 @@ func (c *ClaudeStageClient) start(env, args []string, n int, prompt string) (*cl
defer stderr.Close()
cmd := exec.Command(c.Executable, args...)
cmd.Dir = c.Directory
cmd.Env = env
cmd.Env = agentenv.Scrub(env)
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
cmd.Stdin, cmd.Stdout, cmd.Stderr = stdin, stdout, stderr
if err = cmd.Start(); err != nil {
+1
View File
@@ -20,6 +20,7 @@ import (
// prompt, then prints a canned stream-json conversation for FAKE_CLAUDE_CASE.
const fakeClaude = `#!/bin/sh
if [ "$1" = auth ]; then echo '{"loggedIn":true}'; exit 0; fi
env > "$FAKE_CLAUDE_OUT/env"
session=""; model=""; resumed=0; prev=""
for a in "$@"; do
printf '%s\n' "$a" >> "$FAKE_CLAUDE_OUT/args"
+13 -7
View File
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"git.a-wan.net/alan/pipelines/internal/agentenv"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/workenv"
"io"
@@ -138,13 +139,7 @@ func (c OpenCodeClient) call(ctx context.Context, method, path string, body any)
cmd := opencode.CommandContext(ctx, opencode.Executable(), args...)
cmd.Dir = directory
// The run's directory environment (workenv.WithEnvironment), if any.
cmd.Env = workenv.CommandEnv(ctx, directory)
if c.ArtifactsDir != "" {
if cmd.Env == nil {
cmd.Env = os.Environ()
}
cmd.Env = append(cmd.Env, ArtifactsEnv+"="+c.ArtifactsDir)
}
cmd.Env = openCodeCLIEnv(ctx, directory, c.ArtifactsDir)
if c.connection != nil {
c.connection.PinCLI(cmd)
}
@@ -517,3 +512,14 @@ func (b *boundedBuffer) Write(p []byte) (int, error) {
}
var _ io.Writer = (*boundedBuffer)(nil)
// openCodeCLIEnv is the environment of an OpenCode CLI call for a stage: the
// run directory's (or the server's) environment without Pipelines' own
// secrets, plus the stage's artifacts directory.
func openCodeCLIEnv(ctx context.Context, directory, artifactsDir string) []string {
env := agentenv.Scrub(workenv.CommandEnv(ctx, directory))
if artifactsDir != "" {
env = append(env, ArtifactsEnv+"="+artifactsDir)
}
return env
}
+3 -4
View File
@@ -17,6 +17,7 @@ import (
"syscall"
"time"
"git.a-wan.net/alan/pipelines/internal/agentenv"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
@@ -181,7 +182,7 @@ func (c *PiClient) Generate(ctx context.Context, config ModelConfig, prompt stri
c.cmd = exec.Command(c.Executable, args...)
c.cmd.Dir = c.Directory
c.cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
c.cmd.Env = env
c.cmd.Env = agentenv.Scrub(env)
stderr, err := os.OpenFile(filepath.Join(c.Reference, "stderr.log"), os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return "", err
@@ -404,9 +405,7 @@ func piEnvironment(reference, artifactsDir string) []string {
// piEnvironmentFrom builds the Pi environment over inherited (the run directory's
// environment), or over the server's own when inherited is nil.
func piEnvironmentFrom(inherited []string, reference, artifactsDir string) []string {
if inherited == nil {
inherited = os.Environ()
}
inherited = agentenv.Scrub(inherited)
env := make([]string, 0, len(inherited)+4)
for _, entry := range inherited {
if strings.HasPrefix(entry, ArtifactsEnv+"=") {
+3 -1
View File
@@ -8,6 +8,7 @@ import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
@@ -21,7 +22,8 @@ func TestPiRPCFixture(t *testing.T) {
sessionID := filepath.Base(root)
_ = os.WriteFile(filepath.Join(root, "ready"), []byte("ready"), 0600)
if out := os.Getenv("PI_FIXTURE_ENV_OUT"); out != "" {
_ = os.WriteFile(out, []byte("SCRATCH_VAR="+os.Getenv("SCRATCH_VAR")+"\nPWD="+os.Getenv("PWD")+"\n"), 0600)
// The whole environment, so tests can check what is (and is not) passed.
_ = os.WriteFile(out, []byte(strings.Join(os.Environ(), "\n")+"\n"), 0600)
}
message := map[string]any{"role": "assistant", "stopReason": "stop", "timestamp": 1, "content": []map[string]string{{"type": "text", "text": `# outcome
success
+11 -2
View File
@@ -45,6 +45,7 @@ import {
import { PeerRelay, proxyDiscovery } from "./src/peerRelay.js";
import { accessPolicy, PLAIN_LAN_REFUSAL } from "./src/listenPolicy.js";
import { AppFiles, ISOLATION_HEADERS, VERSIONED_PREFIX } from "./src/appFiles.js";
import { untrustedHeaders } from "./src/untrustedContent.js";
// The proxy's own directory holds the sign-in page's icons.
const HERE = resolve(fileURLToPath(new URL(".", import.meta.url)));
@@ -465,7 +466,8 @@ async function serveIndex(res) {
function proxyArtifact(req, res) {
let headers;
// An upload is gated by the session's elevation on the server.
const upload = req.method === "POST" && (req.url ?? "").split("?")[0] === "/files";
const pathname = (req.url ?? "").split("?")[0];
const upload = req.method === "POST" && pathname === "/files";
try {
headers = withServerToken(req.headers, undefined, upload ? elevationSession(req) : "");
} catch {
@@ -477,7 +479,14 @@ function proxyArtifact(req, res) {
const upstream = request(
{ host: targetHost, port: targetPort, method: req.method, path: req.url, headers },
(reply) => {
res.writeHead(reply.statusCode ?? 502, reply.headers);
// Served files are untrusted content: always sandboxed, and a home file
// a browser could script is a download. Defence in depth: the server
// sets the same headers.
const served = req.method === "GET" || req.method === "HEAD";
res.writeHead(
reply.statusCode ?? 502,
served ? untrustedHeaders(reply.headers, { download: pathname === "/files" }) : reply.headers,
);
reply.pipe(res);
},
);
+11 -15
View File
@@ -8,11 +8,9 @@ import {
import { PeerRegistry } from "./peerRegistry.js";
import { withServerToken } from "./serverToken.js";
import { rememberDiscovered } from "./peerAddress.js";
// Peer files are untrusted content, never privileged control-UI documents.
// Apply this even for older peers whose /files endpoint has no sandbox header.
const contentPolicy =
"sandbox; default-src 'none'; script-src 'none'; connect-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; media-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'self'";
// Peer files are untrusted content, never privileged control-UI documents:
// the sandbox applies even for older peers whose /files has no such header.
import { untrustedHeaders } from "./untrustedContent.js";
const allowed = (path) =>
path === "/files" ||
@@ -98,23 +96,21 @@ export class PeerRelay extends PeerRegistry {
"content-range",
"accept-ranges",
"content-disposition",
"content-security-policy",
])
if (response.headers[name]) safe[name] = response.headers[name];
// Multiple CSP policies intersect: preserve a peer's stricter
// restrictions while always imposing the local sandbox boundary. A
// peer home file a browser could script is a download.
res.writeHead(
response.statusCode >= 300 && response.statusCode < 400
? 502
: response.statusCode,
{
...safe,
"Cache-Control": "private, no-store",
// Multiple CSP policies intersect: preserve a peer's stricter
// restrictions while always imposing the local sandbox boundary.
"Content-Security-Policy": response.headers[
"content-security-policy"
]
? [response.headers["content-security-policy"], contentPolicy]
: contentPolicy,
"X-Content-Type-Options": "nosniff",
...untrustedHeaders(safe, {
download: target.url.pathname === "/files",
}),
"cache-control": "private, no-store",
},
);
response.pipe(res);
+50
View File
@@ -0,0 +1,50 @@
// The response boundary for files the proxy relays but did not write: run
// artifacts, files under a home directory and a peer's files. `sandbox` gives
// such a document an opaque origin even when it is opened as a page, so a
// crafted HTML or SVG file cannot script the app origin. The Go server sets the
// same policy; the proxy adds it again so an older server, or a peer, cannot
// serve a document with the app's authority.
export const CONTENT_POLICY =
"sandbox; default-src 'none'; script-src 'none'; connect-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; media-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'self'";
const SCRIPT_CAPABLE = new Set([
"text/html",
"application/xhtml+xml",
"image/svg+xml",
"text/xml",
"application/xml",
"text/xsl",
"application/xslt+xml",
"application/javascript",
"text/javascript",
"application/ecmascript",
"text/ecmascript",
"multipart/x-mixed-replace",
]);
/** Whether a browser could run script in a page of this content type. */
export function scriptCapable(contentType) {
const media = String(contentType ?? "").split(";")[0].trim().toLowerCase();
return SCRIPT_CAPABLE.has(media) || media.endsWith("+xml") || media.endsWith("/xml");
}
/**
* Copies [headers] (a Node response's headers, lower-case names) with the
* sandbox policy added. Multiple CSP headers intersect, so an upstream policy
* is kept beside the local one. With [download], a script-capable type is
* forced to an attachment, keeping any filename the upstream named.
*/
export function untrustedHeaders(headers, { download = false } = {}) {
const out = { ...headers };
const upstream = out["content-security-policy"];
out["content-security-policy"] = upstream
? [...(Array.isArray(upstream) ? upstream : [upstream]), CONTENT_POLICY]
: CONTENT_POLICY;
out["x-content-type-options"] = "nosniff";
if (download && scriptCapable(out["content-type"])) {
const current = String(out["content-disposition"] ?? "").trim();
if (/^inline\b/i.test(current)) out["content-disposition"] = current.replace(/^inline/i, "attachment");
else if (!/^attachment\b/i.test(current)) out["content-disposition"] = "attachment";
}
return out;
}
+31
View File
@@ -214,6 +214,37 @@ test("files require sign-in and proxy query, ranges and attachment headers", asy
]);
});
test("files and artifacts are sandboxed and home HTML is a download even from an old server", async (t) => {
// An older server that sets none of the boundary headers.
const upstream = createServer((req, res) => {
const html = req.url.startsWith("/files") || req.url.startsWith("/artifacts/");
res.writeHead(200, {
"Content-Type": html ? "text/html; charset=utf-8" : "text/plain",
"Content-Disposition": 'inline; filename="x.html"',
});
res.end("<script>alert(1)</script>");
}).listen(0, "127.0.0.1");
await once(upstream, "listening");
t.after(() => new Promise((done) => upstream.close(done)));
const port = await freePort();
const child = spawn(process.execPath, ["serve.mjs", "--port", String(port),
"--pipelines", `127.0.0.1:${upstream.address().port}`], {
cwd: here,
env: { ...process.env, PIPELINES_WEB_AUTH: "disabled" },
stdio: ["ignore", "pipe", "inherit"],
});
t.after(async () => { const exited = once(child, "exit"); child.kill(); await exited; });
await once(child.stdout, "data");
const base = `http://127.0.0.1:${port}`;
const file = await fetch(base + "/files?path=~/Downloads/x.html");
assert.match(file.headers.get("content-security-policy"), /(^|, )sandbox; default-src 'none'; script-src 'none'/);
assert.equal(file.headers.get("x-content-type-options"), "nosniff");
assert.equal(file.headers.get("content-disposition"), 'attachment; filename="x.html"');
const artifact = await fetch(base + "/artifacts/r/s/report.html");
assert.match(artifact.headers.get("content-security-policy"), /sandbox; default-src 'none'/);
assert.equal(artifact.headers.get("content-disposition"), 'inline; filename="x.html"');
});
test("file uploads require sign-in and reach the server with their name header", async (t) => {
const requests = [];
const upstream = createServer(async (req, res) => {
+34
View File
@@ -0,0 +1,34 @@
import test from "node:test";
import assert from "node:assert/strict";
import { CONTENT_POLICY, scriptCapable, untrustedHeaders } from "../src/untrustedContent.js";
test("script-capable types cover HTML, SVG and every XML flavour", () => {
for (const type of [
"text/html; charset=utf-8",
"application/xhtml+xml",
"image/svg+xml",
"text/xml",
"application/xml",
"application/rss+xml",
"TEXT/HTML",
])
assert.equal(scriptCapable(type), true, type);
for (const type of ["text/plain", "image/png", "application/pdf", "application/octet-stream", "", undefined])
assert.equal(scriptCapable(type), false, String(type));
});
test("untrusted headers add the sandbox beside an upstream policy", () => {
assert.equal(untrustedHeaders({})["content-security-policy"], CONTENT_POLICY);
const both = untrustedHeaders({ "content-security-policy": "img-src 'none'" });
assert.deepEqual(both["content-security-policy"], ["img-src 'none'", CONTENT_POLICY]);
assert.equal(both["x-content-type-options"], "nosniff");
});
test("downloads force script-capable types to attachments and keep the name", () => {
const html = { "content-type": "text/html", "content-disposition": 'inline; filename="a.html"' };
assert.equal(untrustedHeaders(html, { download: true })["content-disposition"], 'attachment; filename="a.html"');
assert.equal(untrustedHeaders({ "content-type": "image/svg+xml" }, { download: true })["content-disposition"], "attachment");
assert.equal(untrustedHeaders(html)["content-disposition"], 'inline; filename="a.html"');
const text = { "content-type": "text/plain", "content-disposition": "inline" };
assert.equal(untrustedHeaders(text, { download: true })["content-disposition"], "inline");
});