AGENT SKILL

consolidator

AVFL consolidator. Merges, cross-checks, deduplicates, and scores validator findings.

License 许可
Apache-2.0
最近更新
2026-11-09
Stars
★ 0
Forks
0

01 前言 Front Matter

name
security-harden-proxy
description
Use when building a service or sidecar that calls an authenticated upstream API (Bearer token, API key) and relays results, to prevent the credential or full URL from leaking into logs or client responses

02 资源文件 1

03 SKILL.md 正文

Secret-Safe Upstream Proxy

A service that authenticates to an upstream and returns aggregated/proxied data can leak the token through exception text, error responses, or logs. Build it so the secret never escapes.

  1. Keep the token in one place — read it once from the environment; never embed it in returned data, never echo the constructed URL (which may carry it as a query param) back to the client.

  2. Wrap every upstream call and sever the exception chain — HTTP-client exceptions stringify to text that includes the request URL (urllib.error.HTTPError holds the URL, status, and response headers; requests errors embed the full URL). If the key rides in the URL (?api_key=…), echoing str(exc) to the client, or calling log.exception(...)/logging the traceback, writes the credential into responses and logs. Keep every credential-bearing object — the token, the credentialed URL, and the response/request (HTTP response objects keep the full URL and often the authenticated request) — inside a helper, and raise a clean error from a caller that holds none of them, after the except block, so it carries no reference to the original exception:

    def _fetch(path, accept):                  # the only frame that holds token, url, resp
        token = os.environ["UPSTREAM_TOKEN"]
        url = f"{BASE}{path}?api_key={token}"
        with _get(url, accept) as resp:
            return parse(resp)                 # all response processing stays in this frame
    
    def fetch(path, accept):                   # no secret-bearing locals in this frame
        failed = False
        try:
            return _fetch(path, accept)
        except Exception:
            failed = True                      # keep nothing from the original exception
        if failed:
            raise RuntimeError("upstream request failed")   # __context__ and __cause__ are None
    

    Scrubbing names in the raising frame (del url, token) is not enough on its own: a failure while processing the response leaves resp bound, and any later-added local reopens the leak. The helper boundary covers every such object at once.

    raise … from None inside the except is not enough: it only sets __suppress_context__, which hides the original exception from standard traceback output and from error reporters that honor suppression (Sentry, traceback), but the credentialed exception stays reachable on __context__ for custom handlers, debug middleware, and error reporters that walk the exception object graph directly. A cleared chain also does not cover traceback locals: the replacement exception's __traceback__ still contains this frame, and Sentry/debug middleware serialize each frame's locals — so url, token and resp leak unless the raise comes from a frame that never held them (the helper above). Also turn local capture off or scrub the token in the reporter (Sentry include_local_variables=False, or a before_send/EventScrubber denylist) — a caller further up the stack that holds the token would leak it.

  3. Return a generic error to clients — on failure, send a fixed status + opaque message (e.g. 502 "upstream error"); never include the exception text, URL, or headers in the HTTP response body.

  4. Override the log formatter to log message-only — ensure the access/error logger prints just the human message, not the request line or headers, and route it to stdout for container capture.

  5. Stream and cap untrusted payloads — when the upstream returns a large/unbounded body, iterate it line-by-line and abort past a byte cap rather than buffering the whole response, keeping memory bounded regardless of upstream size.

  6. Keep it internal-only — bind the service to the private network/IP, never expose it through the reverse proxy, since it holds a privileged credential.

  7. Add a review/test that asserts no leak — a unit test that forces an upstream failure and asserts the token string does not appear in the raised message or response, and that the raised error has __context__ is None and __cause__ is None (or, walking the whole chain, that no exception in it stringifies to text containing the token) — plus a check that serializing every frame's f_locals along exc.__traceback__ (the shape Sentry/debug middleware capture) contains no credential, e.g. "".join(traceback.TracebackException.from_exception(exc, capture_locals=True).format()). Force both failures: the request itself failing, and response processing failing after a successful request (the case that leaves resp bound). Run the assertion inside a test function — module-level frames capture every global and give false positives.

04 同仓库更多 Skills