Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions adapters/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ or wake an idle model.

For a local scope, use `agent run --scope <id> --id <agent> --name <name> -- <host-command>`. 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 <n>` or `--scope-token-file <private-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
Expand Down
10 changes: 10 additions & 0 deletions cmd/agentintercom/launch_record_darwin_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
17 changes: 17 additions & 0 deletions cmd/agentintercom/launch_record_linux_test.go
Original file line number Diff line number Diff line change
@@ -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
}
43 changes: 39 additions & 4 deletions cmd/agentintercom/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ Usage:
agentintercom message receipt <message-id> [--json] [--address <addr>]
agentintercom agent list [--json] [--address <addr>]
agentintercom link --scope <scope-id> <agent-a> <agent-b>
agentintercom agent run --id <id> --name <name> [--scope <local-scope-id>] [--connect-to <peer>] -- <command> [args...]
agentintercom agent run --id <id> --name <name> [--scope <local-scope-id> | --scope-token-file <file> | --scope-token-fd <n>] [--connect-to <peer>] -- <command> [args...]
agentintercom task add --title <title> [--description <text>] [--depends-on <task-id>] [--json] [--address <addr>]
agentintercom task list [--ready] [--json] [--limit <1-500>] [--after <cursor>] [--address <addr>]
agentintercom task claim --id <task-id> [--json] [--address <addr>]
Expand Down Expand Up @@ -928,6 +928,8 @@ func runAgent(args []string) error {
address := flags.String("address", "", "Agent Intercom 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
Expand All @@ -937,6 +939,11 @@ func runAgent(args []string) error {
if err := flags.Parse(args); err != nil {
return err
}
// flag.Visit tells an explicit --scope-token-fd apart from its default, so
// an invalid number such as -1 is refused rather than silently routed to
// another credential source.
scopeTokenFDSet := false
flags.Visit(func(value *flag.Flag) { scopeTokenFDSet = scopeTokenFDSet || value.Name == "scope-token-fd" })
commandArgs := flags.Args()
if *id == "" || *name == "" || len(commandArgs) == 0 {
return errors.New("agent run requires --id, --name, and a command after --")
Expand All @@ -946,7 +953,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 != "", scopeTokenFDSet} {
if set {
sources++
}
}
if sources > 1 {
return errors.New("use only one of --scope, --scope-token-file and --scope-token-fd")
}
if (*scopeTokenFile != "" || scopeTokenFDSet) && 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")
}
Expand All @@ -955,8 +978,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 scopeTokenFDSet:
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")
Expand Down
17 changes: 1 addition & 16 deletions cmd/agentintercom/remote_scope.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
package main

import (
"encoding/base64"
"errors"
"net/http"
"net/url"
"os"
"runtime"
"strings"
"time"

Expand All @@ -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
}
98 changes: 98 additions & 0 deletions cmd/agentintercom/scope_token.go
Original file line number Diff line number Diff line change
@@ -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")
}
115 changes: 115 additions & 0 deletions cmd/agentintercom/scope_token_launch_test.go
Original file line number Diff line number Diff line change
@@ -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/agentintercom/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")
}
Loading
Loading