Skip to content

[fix]: harden daemon runtime directory validation - #3391

Merged
seanmcguire12 merged 5 commits into
mainfrom
fix-browse-daemon-dir-ownership
Nov 4, 2026
Merged

seanmcguire12 merged 5 commits into
mainfrom
fix-browse-daemon-dir-ownership

Conversation

@seanmcguire12

@seanmcguire12 seanmcguire12 commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

why

  • this PR strengthens runtime directory validation before daemon communication in browse

what changed

  • require directories owned by the current user, including when running as root
  • reject symlinks and non-directory paths

test plan

  • added regression coverage for directory validation and daemon connections

Summary by cubic

Harden daemon runtime directory validation in browse so the CLI never connects to a socket or modifies files in an unowned, symlinked, non-directory, or unsafe-parent path. Previously, a custom BROWSE_DAEMON_DIR could point anywhere and the client would connect and forward credentials before checking; now every client entry point (status, stop, open, and driver commands) validates the directory first and propagates the error instead of cleaning up stale daemon files.

Behavior

  • Requires the runtime directory and every parent to be owned by you or root; shared writable parents need sticky-bit protection, as standard /tmp provides. These checks also apply when TMPDIR changes the default location.
  • Rejects empty and dangling paths, symlinks, and non-directories before any socket connection, chmod, or lock operation, including ancestor symlinks whose targets are unsafe.
  • Revalidates ownership between lock and cleanup steps instead of trusting an earlier probe.
  • Adds regression coverage for all client entry points, root and unprivileged callers, and ancestor permission and symlink cases.

Written for commit c1d8c8f. Summary will update on new commits.

View guided diff Turn on auto-fix

@changeset-bot

changeset-bot Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: c1d8c8f

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
browse Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 5 files

Confidence score: 3/5

  • On Windows, paths.ts skips the ownership check for BROWSE_DAEMON_DIR, so a directory owned by another user may be accepted and expose captured requests. Add a Windows-compatible ownership check or reject directories whose ownership cannot be verified.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/cli/src/lib/driver/daemon/paths.ts">

<violation number="1" location="packages/cli/src/lib/driver/daemon/paths.ts:50">
P2: Windows skips this ownership check because Node 22 does not expose `process.getuid()` there, despite the CLI's Windows daemon path. A foreign-owned `BROWSE_DAEMON_DIR` is accepted, potentially exposing captured request headers and bodies when its ACLs permit access; add Windows owner validation or fail closed.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant CLI as Browse CLI
    participant VP as Validation Paths (ensurePrivateDir)
    participant FS as Filesystem
    participant DC as Daemon Client
    participant SOCK as Unix Socket
    participant DAEMON as Driver Daemon

    Note over CLI,DAEMON: Daemon Runtime Directory Validation Flow

    CLI->>VP: Ensure runtime directory valid
    VP->>FS: mkdir (recursive with 0700)

    alt Directory exists
        FS-->>VP: EEXIST or success
        VP->>FS: lstat (resolved path)
        FS-->>VP: Entry metadata

        alt Entry is not a directory (symlink, file, dangling)
            VP-->>CLI: FAIL: daemon_dir_invalid (exit 1)
        else Entry is a directory
            alt Entry UID mismatch (root or unprivileged)
                VP-->>CLI: FAIL: daemon_dir_not_owned (exit 1)
            else Directory owned by current user
                VP->>FS: chmod 0700 (if supported)
                FS-->>VP: Permission updated
                VP-->>CLI: Directory validated
            end
        end
    else Fresh directory created
        FS-->>VP: Directory created
        VP->>FS: chmod 0700
        FS-->>VP: Permission updated
        VP-->>CLI: Directory validated
    end

    CLI->>DC: getDriverStatus / stopDriver / open / driver command
    DC->>VP: Re-validate runtime directory (pre-connection guard)
    VP-->>DC: Valid directory

    DC->>SOCK: Create connection with socket path
    SOCK->>DAEMON: Connect to daemon socket
    DAEMON-->>SOCK: Socket ready
    SOCK-->>DC: Connection established

    DC->>DC: Ensure runtime directory (pre-request guard)
    DC->>DAEMON: Send request (status, stop, command)

    alt Request succeeds
        DAEMON-->>DC: Success response
        DC-->>CLI: Return result
    else Request fails with validation error
        DC-->>CLI: Throw daemon_dir_not_owned / daemon_dir_invalid
    else Request fails (communication error)
        DC->>DC: Clean up stale pid/lock files
        DC-->>CLI: Return null or error
    end
Loading

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

}
// chmod is not an ownership check: root can chmod another user's directory
// without taking ownership, leaving that user in control of its contents.
if (typeof process.getuid === "function" && entry.uid !== process.getuid()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Windows skips this ownership check because Node 22 does not expose process.getuid() there, despite the CLI's Windows daemon path. A foreign-owned BROWSE_DAEMON_DIR is accepted, potentially exposing captured request headers and bodies when its ACLs permit access; add Windows owner validation or fail closed.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/cli/src/lib/driver/daemon/paths.ts, line 50:

<comment>Windows skips this ownership check because Node 22 does not expose `process.getuid()` there, despite the CLI's Windows daemon path. A foreign-owned `BROWSE_DAEMON_DIR` is accepted, potentially exposing captured request headers and bodies when its ACLs permit access; add Windows owner validation or fail closed.</comment>

<file context>
@@ -25,8 +27,34 @@ export async function ensureRuntimeDir(): Promise<string> {
+  }
+  // chmod is not an ownership check: root can chmod another user's directory
+  // without taking ownership, leaving that user in control of its contents.
+  if (typeof process.getuid === "function" && entry.uid !== process.getuid()) {
+    fail(
+      `Refusing to use ${dir}: it is owned by another user. Set BROWSE_DAEMON_DIR to a directory you own.`,
</file context>

Comment thread .changeset/three-plums-exist.md Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 6 files (changes from recent commits).

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 existing issue remains and 1 new issue found across 8 files

Confidence score: 3/5

  • On Windows, paths.ts accepts a shared BROWSE_DAEMON_DIR without checking ownership or restricting its ACL, so other users may be able to manipulate daemon lock files. Verify ownership and restrict the directory ACL.
  • In paths.ts, opening an owned runtime directory with O_RDONLY fails when its mode is 0300 or 000, so the subsequent chmod(0700) cannot repair it; this regresses the previous behavior. Preserve a way to repair these modes without requiring directory read permission.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/cli/src/lib/driver/daemon/paths.ts">

<violation number="1" location="packages/cli/src/lib/driver/daemon/paths.ts:54">
P2: `O_RDONLY` requires read permission on the directory, so an owned runtime directory with mode `0300` or `000` fails before `handle.chmod(0700)` can repair it; the previous implementation could restore these modes. Preserve recovery for owned directories while retaining race-safe validation.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant CLI as browse CLI
    participant Client as Daemon Client
    participant Paths as Runtime Paths
    participant FS as File System
    participant Daemon as Driver Daemon

    Note over CLI,Daemon: Daemon Runtime Directory Validation Flow

    CLI->>Client: getDriverStatus(session)
    Client->>Paths: ensureRuntimeDir()
    Paths->>FS: lstat(runtimeDir)
    FS-->>Paths: Directory metadata
    Paths->>FS: open(dir, O_DIRECTORY | O_NOFOLLOW)
    FS-->>Paths: Directory handle
    Paths->>Paths: Validate ownership (uid matches caller)
    Paths-->>Client: Validated runtime dir

    Client->>Paths: getSocketPath(session)
    Paths-->>Client: Socket path

    Client->>Daemon: Status probe (request)
    alt Daemon responsive
        Daemon-->>Client: Status response
        Client-->>CLI: Driver status
    else Daemon unresponsive
        Client->>Paths: ensureRuntimeDir()
        Paths->>FS: Revalidate ownership
        FS-->>Paths: Metadata
        Paths-->>Client: Validated
        Client->>Paths: cleanupStaleDaemonFiles(session)
        Paths->>Paths: Revalidate ownership between deletions
        Paths->>FS: unlink(socket, pid, lock)
        Client-->>CLI: Null status
    end

    Note over CLI,Daemon: Command Request Flow (credentials at risk)

    CLI->>Client: runDriverCommandViaDaemon(session, cmd)
    Client->>Paths: ensureRuntimeDir()
    Paths->>FS: Validate dir + parents
    FS-->>Paths: Validation result
    Paths-->>Client: Validated runtime dir

    Client->>Paths: acquireLock(session)
    Paths->>Paths: ensureRuntimeDir() (pre-lock)
    Paths->>FS: open(lockPath, "wx")
    FS-->>Paths: Lock handle
    Paths-->>Client: Lock acquired

    Client->>Daemon: Command request with API key
    Daemon-->>Client: Command response
    Client->>Paths: releaseLock(session)
    Paths->>Paths: ensureRuntimeDir() (pre-cleanup)
    Paths->>FS: unlink(lockPath)
    Client-->>CLI: Command result

    alt Invalid runtime directory (UNSAFE PARENT)
        Paths->>Paths: ensureTrustedParents(dir, uid)
        Paths->>FS: Inspect each ancestor (root downward)
        FS-->>Paths: Parent metadata
        Paths->>Path: fail("daemon_dir_unsafe_parent", exit 1)
        Paths-->>Client: CommandFailure
        Client-->>CLI: Error (no socket connection)
    end

    alt Invalid runtime directory (SYMLINK or FILE)
        Paths->>FS: open(dir, O_DIRECTORY | O_NOFOLLOW)
        FS-->>Paths: ELOOP or ENOTDIR
        Paths->>Paths: fail("daemon_dir_invalid", exit 1)
        Paths-->>Client: CommandFailure
        Client-->>CLI: Error (no socket connection)
    end

    alt Invalid runtime directory (FOREIGN OWNER)
        Paths->>Paths: Check entry.uid vs caller uid
        Paths->>Paths: fail("daemon_dir_not_owned", exit 1)
        Paths-->>Client: CommandFailure
        Client-->>CLI: Error (no socket connection)
    end

    Note over Paths,FS: Ownership revalidation between steps
    Client->>Paths: cleanupDaemonFiles(session)
    Paths->>Paths: ensureRuntimeDir() per artifact
    alt Ownership lost mid-cleanup
        Paths->>Paths: fail("daemon_dir_not_owned")
        Paths-->Client: Abort cleanup
        Client-->>CLI: Error (stale files preserved)
    else Ownership stable
        Paths->>FS: unlink(socket)
        Paths->>FS: unlink(pid)
        Paths-->>Client: Cleanup complete
    end
Loading

Requires human review: Auto-approval blocked because this review re-detected 1 unresolved issue already reported by Cubic.

View guided diff | Turn on auto-fix | Re-trigger cubic

}

const handle = await fs
.open(resolvedDir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: O_RDONLY requires read permission on the directory, so an owned runtime directory with mode 0300 or 000 fails before handle.chmod(0700) can repair it; the previous implementation could restore these modes. Preserve recovery for owned directories while retaining race-safe validation.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/cli/src/lib/driver/daemon/paths.ts, line 54:

<comment>`O_RDONLY` requires read permission on the directory, so an owned runtime directory with mode `0300` or `000` fails before `handle.chmod(0700)` can repair it; the previous implementation could restore these modes. Preserve recovery for owned directories while retaining race-safe validation.</comment>

<file context>
@@ -25,8 +29,137 @@ export async function ensureRuntimeDir(): Promise<string> {
+  }
+
+  const handle = await fs
+    .open(resolvedDir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)
+    .catch((error: NodeJS.ErrnoException) => {
+      if (error.code === "ELOOP" || error.code === "ENOTDIR") failInvalidDirectory(dir);
</file context>

@seanmcguire12
seanmcguire12 merged commit 3fbda6b into main Nov 4, 2026
23 checks passed
@seanmcguire12
seanmcguire12 deleted the fix-browse-daemon-dir-ownership branch November 4, 2026 20:00
shrey150 pushed a commit that referenced this pull request Nov 13, 2026
Release Browse independently of the Stagehand SDKs. Merging this PR
publishes the CLI from the merged commit.

## 0.11.4

### Patch Changes

- [#3426](#3426)
[`f93e6d1`](f93e6d1)
Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - Report an
error when an active browser session disconnects during command startup
instead of automatically starting a replacement.

- [#3379](#3379)
[`73fdba0`](73fdba0)
Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - remove
unused deepmerge dependency

- [#3330](#3330)
[`dc8eb40`](dc8eb40)
Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - bump zod to
4.6.6

- [#3289](#3289)
[`aa67fee`](aa67fee)
Thanks [@shrey150](https://github.com/shrey150)! - Add `--stagehand`
flag to `browse cloud extensions upload`.

- [#3439](#3439)
[`2fe947c`](2fe947c)
Thanks [@github-actions](https://github.com/apps/github-actions)! - Make
`browse doctor` fail and show the cause when the session's last browser
start failed

- [#3400](#3400)
[`ce298c6`](ce298c6)
Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - Add token
validation to internal local Functions runtime requests

- [#3408](#3408)
[`6a56cbb`](6a56cbb)
Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - Fix Windows
package-manager command launching for Functions and templates, and
terminate child processes when skill installation times out.

- [#3391](#3391)
[`3fbda6b`](3fbda6b)
Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - Validate
daemon directory locations before connecting to a session.

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants