Skip to content

test(cli): adversarial fast-check verification and bug fixes across browse CLI - #3562

Open
miguelg719 wants to merge 2 commits into
mainfrom
fv/cli-formal-verification
Open

miguelg719 wants to merge 2 commits into
mainfrom
fv/cli-formal-verification

Conversation

@miguelg719

@miguelg719 miguelg719 commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds deterministic adversarial fast-check property suites across packages/cli (HPKE secret sealing, secret API client, daemon IPC/paths/forwarded-env/server, URL normalization, selector resolution, snapshot formatting, log reduction, error classification, command suggestions, and stateful DriverSessionManager lifecycle) and fixes 11 real bugs surfaced by shrinking counterexamples.

Bugs Surfaced & Fixed

  1. UNIX socket sun_path overflow (packages/cli/src/lib/driver/daemon/paths.ts): Unbounded session names exceeded POSIX sun_path limits (<= 103 bytes on macOS, <= 107 on Linux), causing listen EINVAL. Bounded sanitizeSessionName with deterministic SHA-256 suffixing and added dynamic sun_path fallback in getSocketPath.
  2. Daemon shutdown hang on half-open / multi-message sockets (packages/cli/src/lib/driver/daemon/server.ts, client.ts): handleConnection closed the readline interface without resuming the socket to drain trailing bytes/FIN, causing server.close() during shutdown to hang indefinitely. Resumed sockets on close, tracked active sockets in runDriverDaemon, added 200ms fallback teardown, guarded formatError against null-prototype throws, and guarded post-settle data chunks in client.ts.
  3. URL path traversal in secrets & function-secrets API (packages/cli/src/lib/secrets/api.ts): encodeURIComponent left "", ".", and ".." unencoded (turning detachFunctionSecret(opts, "..", secretId) into DELETE /v1/secrets/<secretId>) and threw raw URIError on lone UTF-16 surrogates. Added encodePathSegment validation and structured CommandFailure wrapping.
  4. forwardedEnvSignature NUL-byte collision & prototype inheritance (packages/cli/src/lib/driver/daemon/forwarded-env.ts): Bare \0 delimiting collided { a: "b\0c\0d" } with { a: "b", c: "d" }, and collectForwardedEnv read inherited prototype properties. Length-prefixed entries and added Object.prototype.hasOwnProperty checks.
  5. Invalid URL & relative dot-path prefixing (packages/cli/src/lib/normalize-url.ts): Accepted whitespace (\r\n), dot-paths (".", "./index.html"), and out-of-range IPv4 ("999.999.999.999"). Enforced /\s/ rejection, IPv4 octet validation, domain label rules, and URL.canParse verification.
  6. Prototype property leak in resolveSelector (packages/cli/src/lib/driver/commands/selectors.ts): resolveSelector("@toString", ...) returned Object.prototype.toString instead of throwing stale_ref. Guarded with Object.prototype.hasOwnProperty and non-empty string check.
  7. Stateful /g//y regex drop & O(N²) ancestor scan (packages/cli/src/lib/driver/commands/snapshot-format.ts): Reusing /g or /y regexes mutated lastIndex and skipped alternating matching lines; backward ancestor scanning degraded quadratically. Reset regex.lastIndex = 0 per line and replaced with an O(N) monotonic depth stack.
  8. Null entry & non-string exception crashes (packages/cli/src/lib/cloud/reduce-logs.ts): Non-object entries and non-string exception.description values crashed with TypeError. Added entry/params object guards and safe string formatting.
  9. Null-prototype throw crash (packages/cli/src/lib/driver/error-classifier.ts): classifyDriverError(Object.create(null)) threw TypeError in String(error). Wrapped string coercion safely.
  10. Unbounded token split & edit distance DoS (packages/cli/src/lib/command-suggestions.ts): Bounded id.split(":", maxCommandTokens + 1) and added length-difference early exit before Myers distance.
  11. Concurrent init/close browser leak, zombie resurrection & NaN backoff (packages/cli/src/lib/driver/session-manager.ts): Closing during an in-flight launch/init leaked the browser and flipped status().initialized back to true; close() left stale refMaps/selectedTargetId; initFailureBackoffMs(NaN) returned NaN. Added closeGeneration fencing across async boundaries, in-flight teardown, state clearing, and finite clamping.

New Property Suites

  • packages/cli/tests/secrets-and-daemon.prop.test.ts (14 property tests)
  • packages/cli/tests/cli-parsing-and-driver.prop.test.ts (15 property tests)

Verification

  • oxfmt --check & oxlint (0 errors, 0 warnings)
  • pnpm --filter browse run check, build:local-only, build
  • Full packages/cli suite (739/739 existing tests) + targeted & property suites (223/223 tests, 29/29 new property tests)

Made with Cursor


Summary by cubic

Adds deterministic adversarial property tests with fast-check across the CLI and fixes 11 real bugs the shrinking counterexamples surfaced. The suites cover HPKE secret sealing, the secrets API, daemon IPC and paths, URL normalization, selector resolution, snapshot formatting, log reduction, error classification, command suggestions, and the stateful DriverSessionManager lifecycle.

Bug fixes

  • Bounded session names to avoid UNIX sun_path overflow and added a hashed fallback for long socket paths.
  • Fixed daemon shutdown hangs by resuming sockets on close, tracking active sockets, and adding a 200ms teardown fallback.
  • Rejected URL path traversal (., .., lone surrogates) in secrets and function-secrets API calls with structured errors.
  • Made forwardedEnvSignature collision-free with length-prefixed entries and stopped prototype property leakage in forwarded env and selector resolution.
  • Tightened URL normalization to reject whitespace, dot-paths, and out-of-range IPv4 addresses.
  • Reset lastIndex on stateful regexes in snapshot filtering and replaced an O(N²) ancestor scan with an O(N) stack.
  • Guarded against non-object log entries, non-string exception descriptions, and null-prototype throws.
  • Bounded token splitting and edit distance computation in command suggestions.
  • Fixed concurrent init/close browser leaks, zombie session resurrection, and NaN backoff in the session manager with a close-generation fence.

New property suites: packages/cli/tests/secrets-and-daemon.prop.test.ts and packages/cli/tests/cli-parsing-and-driver.prop.test.ts (29 tests total). fast-check added as a dev dependency.

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

View guided diff Turn on auto-fix

@changeset-bot

changeset-bot Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: bac8795

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

@socket-security

socket-security Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Addednpm/​fast-check@​4.11.010010010093100

View full report

@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 17 files

Architecture diagram
sequenceDiagram
    participant CLI as CLI / Secrets API
    participant Daemon as Driver Daemon (server.ts)
    participant DM as DriverSessionManager
    participant Sock as UNIX Socket / Pipe
    participant Net as Network / HTTP
    participant Remote as Remote Services
    participant U as URL Normalizer
    participant R as Selector Resolver
    participant SS as Snapshot Formatter
    participant RL as Log Reducer
    participant EC as Error Classifier
    participant CS as Command Suggestions

    Note over CLI,Remote: CLI utility flows (secrets, daemon, normalize, etc.)

    CLI->>CLI: normalizeUrlScheme(input)
    alt valid host / idempotent / crash-free
        CLI->>CLI: Return cleaned URL (no scheme, whitespace, dot-paths, invalid IPv4)
    else invalid input
        CLI->>CLI: Return original input
    end

    CLI->>CLI: resolveSelector(selector, refMaps)
    alt ref present and own-property
        CLI->>CLI: Resolve to xpath (never prototype leak)
    else missing / non-string / empty
        CLI->>CLI: Throw DriverError("stale_ref")
    end

    CLI->>CLI: formatSnapshotTree(tree, opts)
    CLI->>CLI: matchLine() (resets regex.lastIndex)
    Note over CLI: O(N) ancestor scan with monotonic depth stack
    CLI-->>SS: Snapshot string (no O(N^2))

    CLI->>CLI: reduceLogs(rawLogs)
    alt valid console / exception entries
        CLI->>CLI: Format args safely (non-string / non-object guarded)
    else malformed / null entries
        CLI->>CLI: Skip entry (no crash)
    end

    CLI->>CLI: classifyDriverError(error)
    alt Error instance
        CLI->>CLI: Use message
    else null-prototype / non-coercible
        CLI->>CLI: Return null (no throw)
    end

    CLI->>CLI: extractCommandTokens / suggestCommand
    CLI->>CLI: Split with max token limit + length early-exit (avoid DoS)

    CLI->>Daemon: runDriverCommandViaDaemon(session, request)
    Daemon->>Sock: Write JSON request
    Note over Daemon,Sock: Client guards against post-settle data chunks

    Daemon->>DM: initialize(generation)
    alt close() during init (closeGeneration mismatch)
        DM->>DM: Close stale browser / stagehand
        DM->>DM: Throw DriverError("session_closed")
    else init success
        DM->>DM: Store browser / stagehand / context
    end

    DM->>Sock: resolve / status / command / stop
    Sock-->>Daemon: Response JSON

    Daemon->>Daemon: shutdown(triggerSocket)
    Daemon->>Sock: Destroy active sockets (except trigger)
    Sock-->>Daemon: Socket close
    Daemon->>DM: close()
    DM->>DM: Await pending init + close stagehand/browser
    Daemon->>Daemon: cleanupDaemonFiles(session)
    alt half-open / multi-message socket
        Daemon->>Sock: resume() + force-close fallback (200ms)
    end

    Note over CLI,Net: Secrets API path handling

    CLI->>CLI: encodePathSegment(id) (reject "", ".", "..", lone surrogates)
    alt valid id
        CLI->>Net: requestBrowserbase / requestBrowserbaseJson
        Net-->>CLI: Response
    else malformed id
        CLI->>CLI: fail(CommandFailure)
    end

    Note over CLI,Remote: Forwarded env signature & proto safety

    CLI->>CLI: collectForwardedEnv(env, keys)
    CLI->>CLI: ForwardedEnvSignature (length-prefixed entries)
    Note over CLI: hasOwnProperty guard on keys

    Note over CLI,Daemon: Socket path bounds & session sanitization

    CLI->>CLI: sanitizeSessionName(session)
    CLI->>Daemon: getSocketPath(session) (respect sun_path limit)

    Note over CLI,Remote: Property suites (fast-check) drive inputs across all flows
Loading

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

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

This branch has not been deployed

No deployments
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.

1 participant