From 8e6f2f7c1e14cf9f5144e435315a57e1174ced8e Mon Sep 17 00:00:00 2001 From: omsherikar Date: Tue, 20 Oct 2026 16:48:37 +0530 Subject: [PATCH] feat(cli): agent run reads the scope token from a descriptor or a private file agent run could only receive a scope token it was handed through an environment variable, and the OS keeps reporting a process's starting environment for its whole life (/proc//environ, KERN_PROCARGS2), where same-user processes can often read it even when they can't read the launcher's files or memory. Add --scope-token-fd (Unix: read from an inherited descriptor, up to a newline or EOF, 128 bytes at most, closed before the command starts) and --scope-token-file (one read of an owner-only regular file, not a symlink, still the inspected file after open). They are exclusive with --scope and with an exported --scope-token-env variable; the existing routes and the child environment are unchanged. mcp stdio --remote --scope-token-file shares the same reader. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015f6iGxVJzudUSNWEjQvemb --- adapters/README.md | 2 + cmd/october-bus/launch_record_darwin_test.go | 10 ++ cmd/october-bus/launch_record_linux_test.go | 17 ++ cmd/october-bus/main.go | 38 ++++- cmd/october-bus/remote_scope.go | 17 +- cmd/october-bus/scope_token.go | 98 +++++++++++ cmd/october-bus/scope_token_launch_test.go | 115 +++++++++++++ cmd/october-bus/scope_token_test.go | 122 +++++++++++++ cmd/october-bus/scope_token_unix_test.go | 170 +++++++++++++++++++ docs/threat-model.md | 4 +- 10 files changed, 572 insertions(+), 21 deletions(-) create mode 100644 cmd/october-bus/launch_record_darwin_test.go create mode 100644 cmd/october-bus/launch_record_linux_test.go create mode 100644 cmd/october-bus/scope_token.go create mode 100644 cmd/october-bus/scope_token_launch_test.go create mode 100644 cmd/october-bus/scope_token_test.go create mode 100644 cmd/october-bus/scope_token_unix_test.go diff --git a/adapters/README.md b/adapters/README.md index 2e45bba..a052830 100644 --- a/adapters/README.md +++ b/adapters/README.md @@ -54,6 +54,8 @@ or wake an idle model. For a local scope, use `agent run --scope --id --name -- `. This reads protected local discovery and the saved scope credential without a token export. It rejects explicit remote addresses or inherited scope/agent authority; the older `--scope-token-env` route remains available separately for remote/operator-managed launches. +An operator-managed launcher that holds the scope token itself can keep it out of the launcher's environment, where same-user tools can read it for the launcher's whole life, with `--scope-token-fd ` or `--scope-token-file `. `--scope-token-fd` (Unix) reads the token from an inherited descriptor (3 or more, typically a pipe) up to a newline or end of file, then closes it before the command starts, so nothing touches the environment, arguments or disk. `--scope-token-file` reads an owner-only regular file once and rejects symlinks. Address resolution is unchanged (`--address`, `OCTOBER_BUS_ADDRESS`, then local discovery). Each refuses to combine with `--scope`, with the other, or with a set `--scope-token-env` variable; `--scope-token-env` itself is unchanged. + Do not mix managed credentials with self-registering flags. Missing identity fails with an actionable error, not a tool-less server. Prefer configuration-only setup for independently launched editors. ## Removal and recovery diff --git a/cmd/october-bus/launch_record_darwin_test.go b/cmd/october-bus/launch_record_darwin_test.go new file mode 100644 index 0000000..90e7401 --- /dev/null +++ b/cmd/october-bus/launch_record_darwin_test.go @@ -0,0 +1,10 @@ +package main + +import "golang.org/x/sys/unix" + +// processLaunchRecord returns what macOS reports to same-user processes about +// how pid was started (KERN_PROCARGS2): its argument count, executable path, +// arguments and the environment it was started with. +func processLaunchRecord(pid int) ([]byte, error) { + return unix.SysctlRaw("kern.procargs2", pid) +} diff --git a/cmd/october-bus/launch_record_linux_test.go b/cmd/october-bus/launch_record_linux_test.go new file mode 100644 index 0000000..45147c7 --- /dev/null +++ b/cmd/october-bus/launch_record_linux_test.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" + "os" +) + +// processLaunchRecord returns what Linux reports to same-user processes about +// how pid was started: its arguments and the environment it was started with. +func processLaunchRecord(pid int) ([]byte, error) { + arguments, err := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid)) + if err != nil { + return nil, err + } + environment, err := os.ReadFile(fmt.Sprintf("/proc/%d/environ", pid)) + return append(arguments, environment...), err +} diff --git a/cmd/october-bus/main.go b/cmd/october-bus/main.go index 5aae981..0bdf941 100644 --- a/cmd/october-bus/main.go +++ b/cmd/october-bus/main.go @@ -41,7 +41,7 @@ Usage: october-bus message receipt [--json] [--address ] october-bus agent list [--json] [--address ] october-bus link --scope - october-bus agent run --id --name [--scope ] [--connect-to ] -- [args...] + october-bus agent run --id --name [--scope | --scope-token-file | --scope-token-fd ] [--connect-to ] -- [args...] october-bus task add --title [--description <text>] [--depends-on <task-id>] [--json] [--address <addr>] october-bus task list [--ready] [--json] [--limit <1-500>] [--after <cursor>] [--address <addr>] october-bus mcp stdio [--scope <scope-id> --agent <id> --name <display>] @@ -877,6 +877,8 @@ func runAgent(args []string) error { address := flags.String("address", "", "October Bus address") localScope := flags.String("scope", "", "local scope ID; uses protected cached credentials, not environment authority") scopeTokenEnv := flags.String("scope-token-env", "OCTOBER_BUS_SCOPE_TOKEN", "environment variable containing the scope token") + scopeTokenFile := flags.String("scope-token-file", "", "owner-only file containing the scope token; read once, never placed in the environment") + scopeTokenFD := flags.Int("scope-token-fd", -1, "inherited descriptor (3 or more) to read the scope token from, up to a newline or end of file; closed before the command starts") lease := flags.Duration("lease", 5*time.Minute, "execution lease") heartbeat := flags.Duration("heartbeat", 0, "heartbeat interval") var connectTo stringList @@ -895,7 +897,23 @@ func runAgent(args []string) error { } scopeToken := os.Getenv(*scopeTokenEnv) resolvedAddress := *address - if *localScope != "" { + // One source of scope authority. A token read from a file or descriptor is + // never in this process's environment, where same-user tools can read it + // for the life of the process (e.g. /proc/<pid>/environ, KERN_PROCARGS2). + sources := 0 + for _, set := range []bool{*localScope != "", *scopeTokenFile != "", *scopeTokenFD != -1} { + if set { + sources++ + } + } + if sources > 1 { + return errors.New("use only one of --scope, --scope-token-file and --scope-token-fd") + } + if (*scopeTokenFile != "" || *scopeTokenFD != -1) && scopeToken != "" { + return fmt.Errorf("--scope-token-file and --scope-token-fd keep the scope token out of the environment; unset %s", *scopeTokenEnv) + } + switch { + case *localScope != "": if *address != "" || scopeToken != "" || os.Getenv("OCTOBER_BUS_AGENT_TOKEN") != "" { return errors.New("--scope uses local discovery only; do not mix --address or inherited scope/agent credentials") } @@ -904,8 +922,20 @@ func runAgent(args []string) error { return err } scopeToken, resolvedAddress = owner.Token, owner.Address - } else if scopeToken == "" { - return fmt.Errorf("use --scope <local-scope-id> or provide %s", *scopeTokenEnv) + case *scopeTokenFile != "": + token, err := readScopeTokenFile(*scopeTokenFile) + if err != nil { + return fmt.Errorf("--scope-token-file: %w", err) + } + scopeToken = token + case *scopeTokenFD != -1: + token, err := readScopeTokenFD(*scopeTokenFD) + if err != nil { + return err + } + scopeToken = token + case scopeToken == "": + return fmt.Errorf("use --scope <local-scope-id>, --scope-token-file, --scope-token-fd, or provide %s", *scopeTokenEnv) } if resolvedAddress == "" { resolvedAddress = os.Getenv("OCTOBER_BUS_ADDRESS") diff --git a/cmd/october-bus/remote_scope.go b/cmd/october-bus/remote_scope.go index 5cafc4e..4d3076a 100644 --- a/cmd/october-bus/remote_scope.go +++ b/cmd/october-bus/remote_scope.go @@ -1,12 +1,9 @@ package main import ( - "encoding/base64" "errors" "net/http" "net/url" - "os" - "runtime" "strings" "time" @@ -23,21 +20,9 @@ func remoteScopeClient(address, tokenPath string) (bus.Client, error) { if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" { return bus.Client{}, errors.New("--remote must be an HTTPS Bus base URL without credentials, query, or fragment") } - info, err := os.Lstat(tokenPath) + token, err := readScopeTokenFile(tokenPath) if err != nil { return bus.Client{}, err } - if !info.Mode().IsRegular() || info.Size() > 128 || (runtime.GOOS != "windows" && info.Mode().Perm()&0o077 != 0) { - return bus.Client{}, errors.New("scope token must be an owner-only regular file of at most 128 bytes") - } - data, err := os.ReadFile(tokenPath) - if err != nil { - return bus.Client{}, err - } - token := strings.TrimSpace(string(data)) - decoded, err := base64.RawURLEncoding.DecodeString(token) - if err != nil || len(decoded) != 32 { - return bus.Client{}, errors.New("scope token file is invalid") - } return bus.Client{Address: address, Token: token, HTTP: &http.Client{Timeout: 30 * time.Second, CheckRedirect: rejectBusRedirect}}, nil } diff --git a/cmd/october-bus/scope_token.go b/cmd/october-bus/scope_token.go new file mode 100644 index 0000000..56a0157 --- /dev/null +++ b/cmd/october-bus/scope_token.go @@ -0,0 +1,98 @@ +package main + +import ( + "bufio" + "errors" + "fmt" + "io" + "os" + "runtime" + "strings" +) + +// maxScopeTokenBytes bounds a scope credential read from a file or an +// inherited descriptor. A token is 43 characters; the rest allows a newline. +const maxScopeTokenBytes = 128 + +var errScopeTokenFile = errors.New("scope token must be an owner-only regular file of at most 128 bytes") + +// parseScopeToken accepts one scope credential in the shape every authority +// mints (the shape validExecutionToken checks: 32 random bytes, canonical +// unpadded base64url), with surrounding whitespace removed. The canonical +// check also refuses line breaks inside the value, which the base64 decoder +// alone would skip. Errors name the source, never the content. +func parseScopeToken(data []byte, source string) (string, error) { + token := strings.TrimSpace(string(data)) + if !validExecutionToken(token) { + return "", fmt.Errorf("%s is invalid", source) + } + return token, nil +} + +func privateScopeTokenFile(info os.FileInfo) bool { + // Windows uses the user's profile ACL; Unix mode bits are not a Windows ACL. + return info.Mode().IsRegular() && info.Size() <= maxScopeTokenBytes && + (runtime.GOOS == "windows" || info.Mode().Perm()&0o077 == 0) +} + +// readScopeTokenFile reads a scope credential once from a private file. The +// path must name a regular file, not a symlink, with owner-only permissions on +// Unix, and the file opened must be the file inspected. +func readScopeTokenFile(path string) (string, error) { + before, err := os.Lstat(path) + if err != nil { + return "", err + } + if !privateScopeTokenFile(before) { + return "", errScopeTokenFile + } + file, err := os.Open(path) + if err != nil { + return "", err + } + defer file.Close() + after, err := file.Stat() + if err != nil { + return "", err + } + if !os.SameFile(before, after) || !privateScopeTokenFile(after) { + return "", errScopeTokenFile + } + data, err := io.ReadAll(io.LimitReader(file, maxScopeTokenBytes+1)) + if err != nil { + return "", err + } + if len(data) > maxScopeTokenBytes { + return "", errScopeTokenFile + } + return parseScopeToken(data, "scope token file") +} + +// readScopeTokenFD reads a scope credential from a descriptor the caller left +// open across exec, typically the read end of a pipe, so the credential never +// appears in this process's environment, arguments or on disk. It reads up to +// the first newline or end of file, whichever comes first, so a writer need not +// close its end. The descriptor is closed before returning, success or not, so +// the managed command never inherits it. +func readScopeTokenFD(fd int) (string, error) { + if runtime.GOOS == "windows" { + return "", errors.New("--scope-token-fd is not supported on Windows; use --scope-token-file") + } + // 0-2 are the managed command's standard streams. + if fd < 3 { + return "", errors.New("--scope-token-fd must name an inherited descriptor of 3 or more") + } + file := os.NewFile(uintptr(fd), "scope-token-fd") + if file == nil { + return "", errors.New("--scope-token-fd names an invalid descriptor") + } + defer file.Close() + line, err := bufio.NewReader(io.LimitReader(file, maxScopeTokenBytes+1)).ReadSlice('\n') + if err != nil && !errors.Is(err, io.EOF) { + return "", fmt.Errorf("could not read --scope-token-fd: %w", err) + } + if len(line) > maxScopeTokenBytes { + return "", errors.New("--scope-token-fd held more than 128 bytes before a newline") + } + return parseScopeToken(line, "scope token from --scope-token-fd") +} diff --git a/cmd/october-bus/scope_token_launch_test.go b/cmd/october-bus/scope_token_launch_test.go new file mode 100644 index 0000000..a3073ec --- /dev/null +++ b/cmd/october-bus/scope_token_launch_test.go @@ -0,0 +1,115 @@ +//go:build linux || darwin + +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "os" + "os/exec" + "testing" + "time" + + "github.com/october-dev/october-bus/bus" +) + +func TestScopeTokenWrapperHelper(t *testing.T) { + raw := os.Getenv("BUS_WRAPPER_ARGS") + if raw == "" { + return + } + var args []string + if json.Unmarshal([]byte(raw), &args) != nil { + os.Exit(2) + } + if err := runAgent(args); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + os.Exit(0) +} + +func TestScopeTokenWaitingChild(t *testing.T) { + if os.Getenv("BUS_WAITING_CHILD") != "1" { + return + } + _, _ = io.Copy(io.Discard, os.Stdin) + os.Exit(0) +} + +// The operating system keeps reporting the environment a process was started +// with (Linux /proc/<pid>/environ, macOS KERN_PROCARGS2) to other processes of +// the same user, whatever the process later removes. A scope token passed by +// descriptor is never part of that record; one passed by environment is, for +// the launcher's whole life. +func TestAgentRunLaunchRecordHoldsNoDescriptorScopeToken(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + runtimeValue, err := bus.Open(":memory:") + requireNoError(t, err) + server := bus.NewServer(runtimeValue, bus.ServerOptions{}) + address, err := server.Start() + requireNoError(t, err) + defer server.Stop(context.Background()) + scope, err := runtimeValue.CreateScope(ctx, bus.CreateScopeInput{ID: "launch-record"}) + requireNoError(t, err) + owner := bus.Client{Address: address, Token: scope.ScopeToken} + + // launch starts agent run in its own process and reads its launch record + // while its managed command is running. + launch := func(id string, byDescriptor bool) ([]byte, error) { + args := []string{"--id", id, "--name", id, "--address", address} + env := removeEnvironment(os.Environ(), "OCTOBER_BUS_SCOPE_TOKEN", "OCTOBER_BUS_ADMIN_TOKEN", "OCTOBER_BUS_AGENT_TOKEN", "BUS_AUDIT_CHILD") + wrapper := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestScopeTokenWrapperHelper$") + var reader, writer *os.File + if byDescriptor { + var pipeErr error + reader, writer, pipeErr = os.Pipe() + requireNoError(t, pipeErr) + wrapper.ExtraFiles = []*os.File{reader} // descriptor 3 + args = append(args, "--scope-token-fd", "3") + } else { + env = setEnvironment(env, "OCTOBER_BUS_SCOPE_TOKEN", scope.ScopeToken) + } + args = append(args, "--", os.Args[0], "-test.run=^TestScopeTokenWaitingChild$") + encoded, err := json.Marshal(args) + requireNoError(t, err) + wrapper.Env = setEnvironment(env, "BUS_WRAPPER_ARGS", string(encoded), "BUS_WAITING_CHILD", "1") + stdin, err := wrapper.StdinPipe() + requireNoError(t, err) + stderr := new(bytes.Buffer) + wrapper.Stderr = stderr + requireNoError(t, wrapper.Start()) + if byDescriptor { + reader.Close() + _, err = writer.WriteString(scope.ScopeToken + "\n") + requireNoError(t, err) + writer.Close() + } + registered := false + for !registered && ctx.Err() == nil { + agents, _ := owner.ListAgents(ctx) + for _, agent := range agents { + registered = registered || (agent.ID == id && agent.Reachable) + } + time.Sleep(20 * time.Millisecond) + } + record, recordErr := processLaunchRecord(wrapper.Process.Pid) + stdin.Close() + waitErr := wrapper.Wait() + require(t, registered && waitErr == nil, "%s launch did not register and exit cleanly: %v; %s", id, waitErr, stderr.String()) + return record, recordErr + } + + control, err := launch("environment", false) + if err != nil { + t.Skipf("this system does not report another process's launch record: %v", err) + } + require(t, bytes.Contains(control, []byte(scope.ScopeToken)), "control: an environment-launched agent run's record did not show its scope token, so this check reads nothing") + record, err := launch("descriptor", true) + requireNoError(t, err) + require(t, len(record) > 0 && !bytes.Contains(record, []byte(scope.ScopeToken)), "the launch record of agent run --scope-token-fd holds the scope token") +} diff --git a/cmd/october-bus/scope_token_test.go b/cmd/october-bus/scope_token_test.go new file mode 100644 index 0000000..7121ed9 --- /dev/null +++ b/cmd/october-bus/scope_token_test.go @@ -0,0 +1,122 @@ +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/october-dev/october-bus/bus" +) + +func scopeTokenDigest(value string) string { + sum := sha256.Sum256([]byte(value)) + return hex.EncodeToString(sum[:]) +} + +// auditScopeTokenChild runs inside a managed child. It reports only presence, +// never a value: no privileged variable is set, and no environment entry +// contains the scope token, which the parent names by its digest alone. +func auditScopeTokenChild(t *testing.T) { + for _, name := range []string{"OCTOBER_BUS_ADMIN_TOKEN", "OCTOBER_BUS_SCOPE_TOKEN"} { + if os.Getenv(name) != "" { + t.Errorf("managed child inherited privileged variable %s", name) + } + } + digest, size := os.Getenv("BUS_AUDIT_SCOPE_DIGEST"), base64.RawURLEncoding.EncodedLen(32) + for _, entry := range os.Environ() { + for start := 0; start+size <= len(entry); start++ { + if scopeTokenDigest(entry[start:start+size]) == digest { + name, _, _ := strings.Cut(entry, "=") + t.Errorf("managed child variable %s contains the scope token", name) + } + } + } +} + +func TestScopeTokenChild(t *testing.T) { + if os.Getenv("BUS_AUDIT_CHILD") != "1" { + return + } + auditScopeTokenChild(t) +} + +func TestReadScopeTokenFileRequiresPrivateRegularFile(t *testing.T) { + dir := t.TempDir() + token := base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{0x5a}, 32)) + path := filepath.Join(dir, "scope.token") + requireNoError(t, os.WriteFile(path, []byte(token+"\n"), 0o600)) + got, err := readScopeTokenFile(path) + require(t, err == nil && got == token, "private scope token file refused: %v", err) + + write := func(name string, data []byte, mode os.FileMode) string { + file := filepath.Join(dir, name) + requireNoError(t, os.WriteFile(file, data, mode)) + requireNoError(t, os.Chmod(file, mode)) + return file + } + refused := map[string]string{ + "empty": write("empty", nil, 0o600), + "malformed": write("malformed", []byte("not-a-scope-token\n"), 0o600), + "line break": write("split", []byte(token[:20]+"\n"+token[20:]+"\n"), 0o600), + "oversized": write("oversized", bytes.Repeat([]byte("A"), maxScopeTokenBytes+1), 0o600), + "missing": filepath.Join(dir, "missing"), + "not regular file": dir, + } + if runtime.GOOS != "windows" { + refused["group readable"] = write("group", []byte(token), 0o640) + refused["world readable"] = write("world", []byte(token), 0o644) + link := filepath.Join(dir, "link") + requireNoError(t, os.Symlink(path, link)) + refused["symlink"] = link + } + for name, file := range refused { + _, err := readScopeTokenFile(file) + require(t, err != nil, "%s scope token file accepted", name) + require(t, !strings.Contains(err.Error(), token), "%s: error revealed the scope token", name) + } +} + +func TestAgentRunReadsScopeTokenFromPrivateFile(t *testing.T) { + ctx := context.Background() + runtimeValue, err := bus.Open(":memory:") + requireNoError(t, err) + server := bus.NewServer(runtimeValue, bus.ServerOptions{}) + address, err := server.Start() + requireNoError(t, err) + defer server.Stop(ctx) + scope, err := runtimeValue.CreateScope(ctx, bus.CreateScopeInput{ID: "token-file"}) + requireNoError(t, err) + path := filepath.Join(t.TempDir(), "scope.token") + requireNoError(t, os.WriteFile(path, []byte(scope.ScopeToken+"\n"), 0o600)) + t.Setenv("OCTOBER_BUS_SCOPE_TOKEN", "") + t.Setenv("OCTOBER_BUS_ADMIN_TOKEN", "synthetic-admin-marker") + t.Setenv("BUS_AUDIT_CHILD", "1") + t.Setenv("BUS_AUDIT_SCOPE_DIGEST", scopeTokenDigest(scope.ScopeToken)) + args := func(extra ...string) []string { + return append(append([]string{"--id", "worker", "--name", "Worker", "--address", address}, extra...), + "--", os.Args[0], "-test.run=^TestScopeTokenChild$") + } + requireNoError(t, runAgent(args("--scope-token-file", path))) + agents, err := (bus.Client{Address: address, Token: scope.ScopeToken}).ListAgents(ctx) + require(t, err == nil && len(agents) == 1 && agents[0].ID == "worker" && agents[0].Lifecycle == bus.LifecycleOffline, + "file-launched agent did not register and retire: %#v, %v", agents, err) + + err = runAgent(args("--scope-token-file", path, "--scope", "token-file")) + require(t, err != nil && strings.Contains(err.Error(), "use only one of"), "accepted two scope token sources: %v", err) + t.Setenv("OCTOBER_BUS_SCOPE_TOKEN", scope.ScopeToken) + err = runAgent(args("--scope-token-file", path)) + require(t, err != nil && strings.Contains(err.Error(), "unset OCTOBER_BUS_SCOPE_TOKEN"), "accepted a file token beside an environment token: %v", err) + t.Setenv("OCTOBER_BUS_SCOPE_TOKEN", "") + if runtime.GOOS != "windows" { + requireNoError(t, os.Chmod(path, 0o644)) + err = runAgent(args("--scope-token-file", path)) + require(t, err != nil && strings.Contains(err.Error(), "owner-only"), "accepted a shared scope token file: %v", err) + } +} diff --git a/cmd/october-bus/scope_token_unix_test.go b/cmd/october-bus/scope_token_unix_test.go new file mode 100644 index 0000000..c3bab9d --- /dev/null +++ b/cmd/october-bus/scope_token_unix_test.go @@ -0,0 +1,170 @@ +//go:build unix + +package main + +import ( + "context" + "fmt" + "os" + "strconv" + "strings" + "syscall" + "testing" + "time" + + "github.com/october-dev/october-bus/bus" + "golang.org/x/sys/unix" +) + +// scopeTokenPipe returns the read end of a pipe holding data, left open across +// exec as a launcher's descriptor would be, so a reader that forgot to close it +// would hand it to the managed command. The write end stays open only when +// asked; close it with the returned function. +func scopeTokenPipe(t *testing.T, data string, keepWriter bool) (int, func()) { + t.Helper() + var fds [2]int + syscall.ForkLock.RLock() + err := syscall.Pipe(fds[:]) + if err == nil { + syscall.CloseOnExec(fds[0]) + syscall.CloseOnExec(fds[1]) + } + syscall.ForkLock.RUnlock() + requireNoError(t, err) + if data != "" { + _, err = syscall.Write(fds[1], []byte(data)) + requireNoError(t, err) + } + closeWriter := func() { _ = syscall.Close(fds[1]) } + if !keepWriter { + closeWriter() + closeWriter = func() {} + } + _, err = unix.FcntlInt(uintptr(fds[0]), unix.F_SETFD, 0) + requireNoError(t, err) + return fds[0], closeWriter +} + +// descriptorIdentity names an open descriptor by number and file, so a later +// check is not fooled by an unrelated file reusing the number. +func descriptorIdentity(fd int) string { + var stat syscall.Stat_t + if syscall.Fstat(fd, &stat) != nil { + return "" + } + return fmt.Sprintf("%d:%d:%d", fd, stat.Dev, stat.Ino) +} + +func TestScopeTokenFDChild(t *testing.T) { + if os.Getenv("BUS_AUDIT_CHILD") != "1" { + return + } + auditScopeTokenChild(t) + identity := os.Getenv("BUS_AUDIT_FD") + number, _, _ := strings.Cut(identity, ":") + if fd, err := strconv.Atoi(number); err != nil || descriptorIdentity(fd) == identity { + t.Errorf("managed child inherited the scope token descriptor") + } +} + +func TestAgentRunReadsScopeTokenFromDescriptor(t *testing.T) { + ctx := context.Background() + runtimeValue, err := bus.Open(":memory:") + requireNoError(t, err) + server := bus.NewServer(runtimeValue, bus.ServerOptions{}) + address, err := server.Start() + requireNoError(t, err) + defer server.Stop(ctx) + scope, err := runtimeValue.CreateScope(ctx, bus.CreateScopeInput{ID: "token-fd"}) + requireNoError(t, err) + fd, _ := scopeTokenPipe(t, scope.ScopeToken+"\n", false) + identity := descriptorIdentity(fd) + t.Setenv("OCTOBER_BUS_SCOPE_TOKEN", "") + t.Setenv("OCTOBER_BUS_ADMIN_TOKEN", "synthetic-admin-marker") + t.Setenv("BUS_AUDIT_CHILD", "1") + t.Setenv("BUS_AUDIT_SCOPE_DIGEST", scopeTokenDigest(scope.ScopeToken)) + t.Setenv("BUS_AUDIT_FD", identity) + requireNoError(t, runAgent([]string{ + "--id", "worker", "--name", "Worker", "--address", address, "--scope-token-fd", strconv.Itoa(fd), + "--", os.Args[0], "-test.run=^TestScopeTokenFDChild$", + })) + require(t, descriptorIdentity(fd) != identity, "agent run left the scope token descriptor open") + agents, err := (bus.Client{Address: address, Token: scope.ScopeToken}).ListAgents(ctx) + require(t, err == nil && len(agents) == 1 && agents[0].ID == "worker" && agents[0].Lifecycle == bus.LifecycleOffline, + "descriptor-launched agent did not register and retire: %#v, %v", agents, err) +} + +func TestAgentRunRefusesMixedScopeTokenSources(t *testing.T) { + token := "synthetic-scope-token-marker" + fd, _ := scopeTokenPipe(t, token, false) + defer syscall.Close(fd) + file := t.TempDir() + "/scope.token" + requireNoError(t, os.WriteFile(file, []byte(token), 0o600)) + t.Setenv("OCTOBER_BUS_SCOPE_TOKEN", "") + t.Setenv("BUS_ALTERNATE_SCOPE_TOKEN", "") + descriptor := strconv.Itoa(fd) + for _, testCase := range []struct { + env, value string + args []string + want string + }{ + {args: []string{"--scope", "local", "--scope-token-fd", descriptor}, want: "use only one of"}, + {args: []string{"--scope-token-file", file, "--scope-token-fd", descriptor}, want: "use only one of"}, + {env: "OCTOBER_BUS_SCOPE_TOKEN", value: "inherited", args: []string{"--scope-token-fd", descriptor}, want: "unset OCTOBER_BUS_SCOPE_TOKEN"}, + {env: "BUS_ALTERNATE_SCOPE_TOKEN", value: "inherited", args: []string{"--scope-token-env", "BUS_ALTERNATE_SCOPE_TOKEN", "--scope-token-fd", descriptor}, want: "unset BUS_ALTERNATE_SCOPE_TOKEN"}, + } { + if testCase.env != "" { + t.Setenv(testCase.env, testCase.value) + } + args := append(append([]string{"--id", "worker", "--name", "Worker", "--address", "http://127.0.0.1:1"}, testCase.args...), "--", "true") + err := runAgent(args) + require(t, err != nil && strings.Contains(err.Error(), testCase.want), "%v: want %q, got %v", testCase.args, testCase.want, err) + if testCase.env != "" { + t.Setenv(testCase.env, "") + } + } + // A refused launch never read the descriptor: the token is still there. + buffer := make([]byte, 64) + count, err := syscall.Read(fd, buffer) + require(t, err == nil && string(buffer[:count]) == token, "a refused launch consumed the descriptor: %v", err) +} + +func TestReadScopeTokenFDBoundsAndCloses(t *testing.T) { + token := strings.Repeat("A", 42) + "Q" + for _, fd := range []int{0, 1, 2, -1} { + _, err := readScopeTokenFD(fd) + require(t, err != nil && strings.Contains(err.Error(), "3 or more"), "accepted descriptor %d: %v", fd, err) + } + require(t, descriptorIdentity(0) != "", "a refused standard descriptor was closed") + + for name, data := range map[string]string{ + "empty": "", + "malformed": "not-a-scope-token\n", + "oversized": strings.Repeat("A", maxScopeTokenBytes+1), + } { + fd, _ := scopeTokenPipe(t, data, false) + identity := descriptorIdentity(fd) + _, err := readScopeTokenFD(fd) + require(t, err != nil, "%s descriptor accepted", name) + require(t, descriptorIdentity(fd) != identity, "%s descriptor left open", name) + } + + // A newline ends the token, so a writer that keeps its end open does not + // block the launcher, and anything after the newline is ignored. + fd, closeWriter := scopeTokenPipe(t, token+"\nignored", true) + defer closeWriter() + result := make(chan error, 1) + go func() { + got, err := readScopeTokenFD(fd) + if err == nil && got != token { + err = fmt.Errorf("read the wrong token") + } + result <- err + }() + select { + case err := <-result: + requireNoError(t, err) + case <-time.After(5 * time.Second): + t.Fatal("reading a newline-terminated token waited for end of file") + } +} diff --git a/docs/threat-model.md b/docs/threat-model.md index b8e00c8..a007b4f 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -32,7 +32,7 @@ Adapters and harnesses remain responsible for their own model access, files, too | Message or task flood | Per-scope and per-agent limits return explicit backpressure | | Agent resolves its own escalation | Only scope authority can resolve human escalation | | Context expands permission | Context is bounded metadata or content and grants no file, URL, tool, or account access | -| Credential disclosure | Tokens stay out of process arguments, private paths reject symlinks, and responses use `Cache-Control: no-store` | +| Credential disclosure | Tokens stay out of process arguments, launchers can keep scope tokens out of the environment (`agent run --scope`, `--scope-token-file`, `--scope-token-fd`), private paths reject symlinks, and responses use `Cache-Control: no-store` | | Network exposure | The local profile binds to loopback by default | ## Local process risk @@ -41,6 +41,8 @@ The runtime and data directories request owner-only permissions where the operat Do not place scope or admin credentials in model context. Give a harness only its execution-bound agent token when possible. +A process's environment is often readable where its files and memory are not. Removing a variable after start does not remove it from what the operating system reports (`/proc/<pid>/environ` on Linux, `KERN_PROCARGS2` on macOS), and that view can stay readable to same-user tools, including sandboxed ones, that cannot open the process's files or memory. Launchers that hold a scope token should pass it with `agent run --scope-token-fd` or `--scope-token-file` rather than `--scope-token-env`. The managed child still receives its execution-bound agent token in its environment. + Configuration-only adapters keep both scope and execution tokens inside the Go bridge. Their protected local scope-token files are sensitive credentials, including after daemon shutdown. Creation/import/rotation/deletion through the local CLI maintain that cache; remote API operations do not. Hashing scope IDs makes portable filenames, not encryption. Unix modes are enforced on reads, but Windows deployments must check owner-only ACLs separately. Neither mode protects against a malicious process running as the same OS user. Portable archives exclude reusable credentials and execution authority. They still contain collaboration content such as messages, context, tasks, escalation answers, and output values. Store and transfer them as sensitive project data.