Preventing AI Agents from Leaking Your Email in HTTP Headers: Root Causes and Practical Defenses

    An AI coding agent can inadvertently write your account email into the User-Agent header of outbound HTTP requests, exposing it to third-party sites. This article examines why this happens—sensitive data sitting in model context combined with template-following behavior—and presents a three-layer defense: context redaction, whitelist-based header construction, and egress proxying, with example Python code for each layer.

    1. What Happened

    According to publicly available discussions, a developer reported on a code collaboration community that while using a certain AI coding tool, the tool wrote the email address bound to the account into the User-Agent field of HTTP requests when invoking networking features and command-line scripts. As a result, third-party websites obtained the email, and the developer subsequently received a large volume of spam and phishing messages.

    The tool vendor reportedly responded that this was not intentional. The model read the login email from the conversation context and, in scenarios requiring “script clients to provide contact information,” wrote it into the request header on its own. A community contributor also offered an interception plugin, but based on public feedback, it provided incomplete coverage for web scraping, search APIs, external protocol calls, and paths such as “write a file first, then execute the script.” All of the above comes from public discussions; the scope and details have not been independently verified.

    The root cause is clear: sensitive data entered the range that the model can both read and output. As long as the data remains in the context, it can appear in any output.

    This article does not cover attack reproduction, only defenses. All domains and email addresses in this article are reserved or fictional and do not involve any real accounts.

    2. Root Causes and Boundaries

    2.1 Context Is an Output Surface

    All text processed by a large language model resides in the context window. Tool call arguments, code, logs, and network requests generated by the model may contain arbitrary fragments from the context. Therefore, the context should be treated as a potential exfiltration channel, not as private memory.

    2.2 Courtesy Filling and Template Following

    Many public data services recommend that clients include contact information in the User-Agent so that service operators can reach the maintainer when problems arise. Models are good at following such templates. When an email happens to be in the context and the model is asked to “complete the contact information,” it may fill the email in as an appropriate value. The model has no malicious intent. It completes the field according to the format requirements, but it does not judge whether this value should be visible to the outside world.

    2.3 Trigger Conditions

    The risk does not apply to every scenario. An email can end up in a request header only when all of the following conditions hold:

    1. The context contains the account email or other identity information.
    2. The tool has automatic header filling or template-following features enabled.
    3. Request parameters are generated by the model rather than constructed by fixed code.

    The table below lists common risk surfaces, examples, and corresponding control points.

    Risk Surface Example Control Point
    Model context Email in system prompt or conversation history Redact context; keep identity information out of system prompts
    Request construction Model-generated User-Agent or custom headers Header whitelist; validate each value
    Command line and on-disk scripts Scripts written to disk and then executed that contain contact information Scan after generation; review before execution
    Outbound network External calls to arbitrary domains Domain allowlist; proxy auditing

    Plugin-based interception only covers known paths. It is a supplementary measure and cannot replace the control points above.

    3. Three Layers of Defense

    The defense consists of three layers, each effective independently. If one layer fails, the other two can still intercept the leak.

    The first layer is the model context. Before data enters the model, replace emails and account identifiers with placeholders. No account information should appear in system prompts.

    The second layer is request construction. Request headers are generated by code according to a whitelist. The model can only fill in allowed fields, and every value must be validated.

    The third layer is the outbound network. All outgoing requests must pass through a proxy. If the target domain is not on the allowlist, the request is rejected outright, and a redacted audit log is recorded.

    Among these three layers, regex-based redaction only recognizes standard-format emails. Encoded variants or unconventional spellings may slip through, which is why the egress proxy layer is indispensable.

    4. Implementation Code

    Example environment: Python 3.11, requests 2.32. The code is for illustration only; verify it fully in a test environment before deployment, and replace the domains and User-Agent.

    Context redaction module redact_guard.py:

    1. import re
    2. EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
    3. def mask_emails(text: str) -> str:
    4. """Replace email addresses in text with a placeholder."""
    5. return EMAIL_RE.sub("[REDACTED_EMAIL]", text)
    6. def sanitize_messages(messages: list[dict]) -> list[dict]:
    7. """Redact messages before they enter model context, without mutating the originals."""
    8. return [{**m, "content": mask_emails(m["content"])} for m in messages]

    Request construction and egress control module safe_http.py:

    1. import logging
    2. from urllib.parse import urlparse
    3. import requests
    4. from redact_guard import EMAIL_RE, mask_emails
    5. ALLOWED_UA = "docs-bot/1.0 (+https://example.org/bot)"
    6. ALLOWED_HEADERS = {"Accept", "Accept-Language"}
    7. ALLOWED_HOSTS = {"api.example.org", "data.example.gov.cn"}
    8. log = logging.getLogger("egress")
    9. def build_headers(requested: dict[str, str] | None = None) -> dict[str, str]:
    10. headers = {"User-Agent": ALLOWED_UA}
    11. for key, value in (requested or {}).items():
    12. if key not in ALLOWED_HEADERS:
    13. raise ValueError(f"Header not in whitelist: {key}")
    14. if EMAIL_RE.search(value):
    15. raise ValueError(f"Header value contains an email, rejected: {key}")
    16. headers[key] = value
    17. return headers
    18. def safe_get(url: str, requested: dict[str, str] | None = None,
    19. timeout: float = 10.0) -> requests.Response:
    20. host = urlparse(url).hostname or ""
    21. if host not in ALLOWED_HOSTS:
    22. raise PermissionError(f"Outbound domain not authorized: {host}")
    23. headers = build_headers(requested)
    24. # Audit logs record only the domain and redacted headers, not the full URL or query parameters.
    25. log.info("egress host=%s headers=%s",
    26. host, {k: mask_emails(v) for k, v in headers.items()})
    27. # Outbound traffic goes through a proxy: specify the proxy via HTTPS_PROXY in the deployment environment.
    28. resp = requests.get(url, headers=headers, timeout=timeout)
    29. resp.raise_for_status()
    30. return resp

    Code notes: build_headers rejects all headers not on the whitelist.