AI Coding Assistant Leaks Email via User-Agent Header: Root Cause and Prevention Practices

    This article examines a real-world incident where an AI-powered coding assistant inadvertently exposed a developer's email address by writing it into the User-Agent header of outbound HTTP requests, leading to a wave of spam and phishing emails. It breaks down the leak chain into four stages, explains why simple path-based filtering is insufficient, and provides practical prevention measures including context isolation, proxy-level header sanitation, permission scoping, and canary-email testing for CI/CD pipelines.

    Incident Background

    A developer reported on a public issue tracker that they began receiving a large volume of phishing emails after using an AI-powered coding tool. Investigation traced the root cause to the tool’s behavior when making network requests or executing shell commands: the account email address was being inserted into the User-Agent field of HTTP request headers. Any third-party server that received these requests logged the real email address as a result.

    The issue stems from a data flow chain: account information enters the model’s conversation context, and when the model generates outbound requests, it treats that information as available material. The vendor stated this was not a designed feature of the product. When the model encountered prompts such as “script clients should include contact information,” it filled in the email address on its own.

    Normal Use of User-Agent and the Risk Boundary

    The User-Agent is a field in HTTP request headers that identifies the client type and version, allowing servers to perform compatibility checks and access statistics. Many websites and data services require script clients to include contact information so administrators can reach the responsible party when anomalous requests occur. This convention is reasonable in itself. The problem arises when contact details are inferred by the model from session context rather than being explicitly configured by a human.

    Request headers should be treated as externally published information. Any field written into a request header will be captured by the receiving party, intermediary proxies, and logging systems, and cannot be retracted after the fact. Therefore, any field that may be visible externally should be managed according to public-information standards.

    Anatomy of the Leak Chain

    The leak can be broken down into four stages:

    1. Sensitive data enters context: The tool reads login state or account profile information and places it in the session, making it visible to the model.
    2. Model generates outbound requests: The model writes scripts or invokes web tools based on task requirements, generating parameters such as User-Agent on its own.
    3. Tool executes and sends externally: Shell commands, webpage fetching, search, plugin calls, and other paths may all complete the actual transmission.
    4. Recipient retains the data: Third-party services write request headers into access logs or forward them to other organizations.

    Each stage represents a control point. The first stage offers the most effective control—if sensitive values never enter the context, subsequent stages have nothing to leak.

    Stage Typical Risk Available Control
    Context ingestion Model reads personal email or tokens Host program holds identity data; model only sees placeholders
    Request generation Model writes sensitive values into headers or parameters Fixed header templates; prohibit dynamic concatenation of user data
    Execution and sending Inconsistent coverage across tool paths Route all traffic through a proxy with domain allowlisting
    Recipient retention Third-party logs store personal information Sanitize before sending; no remediation possible afterward

    Why Blocking a Single Path Is Insufficient

    Some ad-hoc patches filter only for specific tool names, covering command-line invocations but missing paths such as webpage fetching, search, and plugin calls. Another bypass technique involves writing the script to a file first and executing it separately—filter rules struggle to detect outbound intent at the write stage.

    The fundamental issue is that filtering rules review commands after the fact, while the model can generate outbound content through any path. The proper fix is to ensure the model never has access to sensitive values in the first place. This aligns with a core security engineering principle: never hand secrets to untrusted components and treat model output as untrusted input.

    Prevention Measures

    1. Source Control: Keep Sensitive Data Away from the Model

    • Identity information is held by the host program; the model only sees placeholders or session identifiers.
    • When contact details are required, use project-specific aliases or organizational emails defined in configuration files, rather than reading from login credentials.
    • Clean personal email addresses from logs and debug output to prevent them from re-entering context.

    2. Egress Control: Centralized Handling at the Network Boundary

    Route all outbound requests through a proxy service that strips or rewrites email-pattern strings in request headers. Below is an example redaction function:

    1. import re
    2. EMAIL_PATTERN = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
    3. def redact_headers(headers: dict) -> dict:
    4. """Return a new sanitized dictionary without modifying the original headers."""
    5. return {
    6. name: EMAIL_PATTERN.sub("[REDACTED_EMAIL]", str(value))
    7. for name, value in headers.items()
    8. }
    9. raw = {"User-Agent": "client-tool/1.0 (contact: dev@example.com)"}
    10. print(redact_headers(raw))
    11. # {'User-Agent': 'client-tool/1.0 (contact: [REDACTED_EMAIL])'}

    In addition to redaction, the egress layer should enforce a domain allowlist. Requests to unauthorized domains are rejected and logged. This way, even if the redaction rule misses a particular format, outbound destinations remain constrained.

    3. Tool-Level Controls: Least Privilege

    • Assign minimal permissions per tool, such as restricting access to specific domains or directories.
    • Audit shell command arguments; block execution when strings resembling personal information are detected and prompt for manual confirmation.
    • For flows that write files before execution, scan file contents as well—not just the command itself.

    4. Standardization: Unified Client Identification

    Define a fixed identification template for script clients, such as "tool-name/version (contact: project-alias)". Add this template to the code review checklist and prohibit dynamic concatenation of user data in request headers. Once standardized, reviewers can quickly identify code that deviates from the template.

    Verification: Canary Email Testing

    Canary testing works by planting a unique test email in a test account, then running the full set of tools through routine tasks—network access, search, plugin calls, and write-then-execute flows. Finally, check request logs at the proxy or a dedicated echo service. If the canary email appears in any outbound content, the build fails immediately.

    1. CANARY = "canary-7f3a@test.example.org"
    2. def test_canary_not_in_outbound_requests(run_task, proxy_log):
    3. """Run all tool paths and verify the canary email does not appear in outbound records."""
    4. for task in ["fetch_page", "web_search", "run_shell", "write_then_run"]:
    5. run_task(task, account_email=CANARY)
    6. leaked = [req for req in proxy_log.requests() if CANARY in req.raw]
    7. assert not leaked, f"Found {len(leaked)} outbound requests containing the test email"

    Passing these tests only confirms safety for the covered paths. Every time a new tool or plugin is enabled, corresponding test cases should be added.

    Implementation Checklist

    • Inventory all tools and plugins with external network access
    • Confirm the session context contains no personal emails, tokens, or phone numbers
    • Enable request header redaction rules and domain allowlist at the proxy layer
    • Complete canary testing before onboarding each new tool
    • Periodically audit outbound logs for unauthorized domains