How Cookie Security Works in Agent Reach: File Permissions, Validation, and Safe Storage

Agent Reach secures cookies using atomic file writes with 0o600 permissions, owner-only access controls, input validation before persistence, and shell-safe quoting to prevent credential leakage.

Agent Reach handles browser cookies and authentication tokens as sensitive credentials requiring filesystem-level protection. The codebase implements a defense-in-depth strategy that combines restricted-permission storage, secure extraction libraries, and rigorous input sanitization. This article examines the specific implementation details found in the Panniantong/Agent-Reach source code to explain how cookie security is enforced end-to-end.

Atomic File Writes with Owner-Only Permissions

The Config.save() Implementation

In agent_reach/config.py, the Config.save() method ensures that configuration files containing credentials are never created with world-readable permissions. The implementation uses a low-level os.open() call that atomically sets the file mode to 0o600 (owner read/write only) before any content is written:


# From agent_reach/config.py lines 55-60

fd = os.open(
    self.config_path,
    os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
    mode=0o600
)
with os.fdopen(fd, 'w') as f:
    yaml.dump(self._config, f)

This approach guarantees that the file is born secure—if the process crashes during writing, the partially written file never exists with insecure permissions.

Directory-Level Protection

Before writing the configuration file, Agent Reach ensures the parent directory is created with restricted access. In agent_reach/config.py at lines 38-40, the code uses mkdir() with exist_ok=True to establish the configuration hierarchy:

self.config_path.parent.mkdir(parents=True, exist_ok=True)

While the directory permissions are not explicitly set to 0o700 in the provided snippets, the atomic file creation ensures that credential files themselves maintain strict owner-only access even if the directory has broader permissions.

Extraction Libraries and Validation

The agent_reach/cookie_extract.py module extracts cookies from browsers using either rookiepy (preferred) or browser-cookie3. These libraries access browser-specific storage to retrieve session data without requiring manual copy-paste of cookie strings.

Before persisting any cookies, the code validates their contents. For Xueqiu authentication, the implementation explicitly refuses to store the cookie string unless the required xq_a_token is present, as anonymous cookies provide no API access. This validation occurs at lines 78-84:


# From agent_reach/cookie_extract.py

if "xq_a_token" not in cookie_string:
    logging.warning("No xq_a_token found in cookies, skipping Xueqiu")
    return None

Extracted data remains in memory only until validation completes, at which point it is written through the secured Config.set() pathway.

Protected Credential Synchronization

For integrations requiring external credential files (such as the legacy xfetch session file or the bird CLI environment file), Agent Reach uses a helper function _open_owner_only() defined at lines 62-68 in agent_reach/cookie_extract.py. This utility creates target files with mode 0o600 before writing:

def _open_owner_only(path: Path):
    """Open file with owner-only permissions (0o600)."""
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    return os.fdopen(fd, 'w')

This ensures that even temporary synchronization files never become world-readable during their lifecycle.

CLI Input Parsing and Shell Safety

When users manually supply Twitter credentials via the CLI, agent_reach/cli.py implements _parse_twitter_cookie_input() (lines 32-50) to handle raw input safely. The parser accepts either a full cookie header string or separate token values:


# Full cookie header format

python -m agent_reach.cli configure twitter-cookies "auth_token=AAA; ct0=BBB"

# Separate token format

python -m agent_reach.cli configure twitter-cookies "AAA BBB"

The parser extracts only the required fields (auth_token and ct0) and immediately passes them to Config.set(), which invokes the atomic write procedure. The raw input string is never logged or displayed.

Shell-Safe Environment Variables

When synchronizing credentials for the bird CLI tool, Agent Reach writes to ~/.config/bird/credentials.env. At lines 99-106 in agent_reach/cookie_extract.py, each value passes through shlex.quote() to neutralize shell metacharacters:


# From agent_reach/cookie_extract.py

f.write(f"TWITTER_AUTH_TOKEN={shlex.quote(auth_token)}\n")
f.write(f"TWITTER_CT0={shlex.quote(ct0)}\n")

This prevents injection attacks if the environment file is later sourced by a shell script, protecting against characters like quotes, $, or backticks that could break out of variable assignment syntax.

Configuration Schema Design

Agent Reach maintains an explicit separation between normal API keys (patterned as *_api_key) and Twitter-specific legacy keys (twitter_auth_token, twitter_ct0). This segregation serves two security purposes:

  1. Access Control: Different credential types can be subject to different validation rules and storage mechanisms
  2. Diagnostic Safety: The doctor diagnostics module can identify missing credentials without requiring the logging of actual values, preventing accidental credential leakage in debug output

Summary

  • Atomic Permission Setting: Config.save() in agent_reach/config.py uses os.open() with mode 0o600 to create files with owner-only permissions before writing begins
  • Browser Extraction Security: Cookies are extracted via rookiepy or browser-cookie3 in agent_reach/cookie_extract.py and validated (e.g., checking for xq_a_token) before persistence
  • Helper Utilities: The _open_owner_only() function ensures all credential files, including temporary sync files, are created with restrictive permissions
  • Input Sanitization: shlex.quote() protects shell environment files from injection vulnerabilities when storing Twitter credentials
  • Safe CLI Parsing: _parse_twitter_cookie_input() in agent_reach/cli.py extracts specific token fields without exposing raw cookie headers in logs or output

Frequently Asked Questions

Agent Reach creates all credential files with mode 0o600 (owner read/write only). This is implemented in agent_reach/config.py through an atomic os.open() call that sets permissions before the file descriptor is opened for writing, ensuring the file never exists in a world-readable state.

How does Agent Reach validate cookies before storing them?

The extraction logic in agent_reach/cookie_extract.py validates cookies by checking for required tokens before persistence. For example, when processing Xueqiu cookies, the code explicitly verifies the presence of xq_a_token and refuses to store anonymous cookies that would provide no API access.

Is it safe to manually enter cookies via the CLI?

Yes. The CLI handler _parse_twitter_cookie_input() in agent_reach/cli.py parses input to extract only required fields (auth_token and ct0) without logging or displaying the raw cookie string. The values are immediately passed to Config.set(), which writes them through the secured atomic file creation pathway.

How does Agent Reach protect shell environment files?

When creating environment files for external tools (such as the bird CLI credentials at ~/.config/bird/credentials.env), Agent Reach uses shlex.quote() to escape all values. This prevents shell injection attacks if the file is sourced, neutralizing special characters like quotes, dollar signs, and backticks that could otherwise execute arbitrary commands.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →