Skip to content

fix(bedrock): discard stale payload hashes when resigning - #45634

Open
micahmills88 wants to merge 6 commits into
BerriAI:mainfrom
micahmills88:fix_bedrock_resign_payload_hash
Open

micahmills88 wants to merge 6 commits into
BerriAI:mainfrom
micahmills88:fix_bedrock_resign_payload_hash

Conversation

@micahmills88

@micahmills88 micahmills88 commented Oct 9, 2026 •

Copy link
Copy Markdown

Bedrock retries now discard a previous payload hash before signing a changed request body. This prevents an old hash from invalidating the retry signature. The refreshed proxy proof and regression results are below, with live AWS validation still outstanding

Details

TLDR

Problem this solves:

  • Bedrock retries can retain the previous body's payload hash

How it solves it:

  • Exclude computed headers before signing and prevent stale hash restoration

User Flow

Before: the reported Bedrock workflow can fail authentication

  1. Send a Bedrock Anthropic Messages request with thinking history and an existing payload-hash header
  2. Bedrock rejects a thinking signature, triggering a retry with stripped thinking blocks
  3. The retry carries the old body's hash and may fail with SignatureDoesNotMatch

Expected after the fix; live AWS confirmation is pending

  1. Send the same Bedrock Anthropic Messages request
  2. Bedrock rejects a thinking signature, triggering the same body-changing retry
  3. The retry signs the current body without replaying the old hash

Relevant issues

Related: issue #27513 and merged re-signing fix #32371. This addresses the remaining payload-hash case

Implementation

When native Anthropic Messages retry handling removes rejected thinking blocks, it signs the changed body using the previous attempt's headers. A supplied x-amz-content-sha256 survives both the pre-sign filter and post-sign copy-back. Botocore uses that stale digest in its canonical request. The fix includes the payload hash in SIGV4_COMPUTED_HEADERS and excludes computed headers before signing. Existing restoration exclusions then prevent the stale hash from being reintroduced

Pre-Submission checklist

  • I have added meaningful tests
  • The focused test files covering my change pass locally
  • My PR passes all required CI/CD checks
  • My PR solves one specific problem
  • Every automated review on the latest commit has finished and its findings are addressed

Screenshots / Proof of Fix

A real local proxy receives POST /v1/messages from curl and sends HTTP requests to a controlled Bedrock peer. A calibration request captures the initial body digest, which is then supplied through the public extra_headers request option. The peer accepts the first signature and returns a rejected-thinking HTTP 400. The production retry strips the thinking block, changes the body, and signs again. No retry or signing code is patched

The peer independently recomputes SHA-256 and the SigV4 HMAC using Python's standard library. It rejects mixed credential generations, mismatched payload hashes, and incorrect signatures with HTTP 403. Both before and after use the same peer. This is controlled HTTP integration proof with synthetic credentials and responses. It does not establish live AWS acceptance, IRSA behavior, or production failure frequency

Shared setup uses Python 3.12, curl, and the locked proxy dependencies. Save the script below as proxy_proof.py outside the checkouts. It starts a local proxy and HTTP peer on temporary loopback ports, generates a local master key, runs curl, saves the response and peer observations, and stops its own processes. It makes no live provider calls

Complete HTTP reproduction harness
"""Controlled HTTP integration proof. All credentials and responses are synthetic."""
import argparse
import hashlib
import hmac
import json
import os
import secrets
import shutil
from pathlib import Path
import socket
import subprocess
import sys
import threading
import time
from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import quote, urlsplit

import httpx


def digest(data):
    return hashlib.sha256(data).hexdigest()


def mac(key, value):
    return hmac.new(key, value.encode(), hashlib.sha256).digest()


def verify(method, path, headers, body):
    try:
        parts = dict(part.strip().split("=", 1) for part in headers["authorization"].removeprefix("AWS4-HMAC-SHA256 ").split(","))
        access, date, region, service, terminal = parts["Credential"].split("/")
        generation = access.removeprefix("proof-access-")
        token_ok = headers.get("x-amz-security-token") == f"proof-token-{generation}"
        body_hash = digest(body)
        hash_ok = headers.get("x-amz-content-sha256", body_hash) == body_hash
        names = parts["SignedHeaders"]
        canonical_headers = "".join(f"{name}:{' '.join(headers[name].split())}\n" for name in names.split(";"))
        url = urlsplit(path)
        canonical = "\n".join((method, quote(url.path, safe="/-_.~"), url.query, canonical_headers, names, body_hash))
        scope = "/".join((date, region, service, terminal))
        to_sign = "\n".join(("AWS4-HMAC-SHA256", headers["x-amz-date"], scope, digest(canonical.encode())))
        key = ("AWS4proof-secret-" + generation).encode()
        for value in (date, region, service, terminal):
            key = mac(key, value)
        signature_ok = hmac.compare_digest(mac(key, to_sign).hex(), parts["Signature"])
        return {"access": access, "token": headers.get("x-amz-security-token"), "token_ok": token_ok, "payload_hash_ok": hash_ok, "signature_ok": signature_ok, "body_sha256": body_hash}
    except (KeyError, ValueError):
        return {"token_ok": False, "payload_hash_ok": False, "signature_ok": False}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--repo", required=True)
    parser.add_argument("--case", choices=("rotation", "payload"), required=True)
    parser.add_argument("--expect", choices=("fail", "pass"), required=True)
    parser.add_argument("--output", required=True)
    args = parser.parse_args()
    output = Path(args.output).resolve()
    output.parent.mkdir(parents=True, exist_ok=True)
    state = {"generation": 0, "attempts": [], "calibration": args.case == "payload"}

    class Peer(BaseHTTPRequestHandler):
        def log_message(self, *_):
            pass

        def reply(self, status, value, error=None):
            content = json.dumps(value).encode()
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(content)))
            if error:
                self.send_header("x-amzn-errortype", error)
            self.end_headers()
            self.wfile.write(content)

        def do_GET(self):
            if self.path != "/credentials":
                self.reply(404, {})
                return
            state["generation"] += 1
            n = state["generation"]
            self.reply(200, {"AccessKeyId": f"proof-access-{n}", "SecretAccessKey": f"proof-secret-{n}", "Token": f"proof-token-{n}", "Expiration": (datetime.now(timezone.utc) + timedelta(seconds=60)).isoformat()})

        def do_POST(self):
            body = self.rfile.read(int(self.headers.get("Content-Length", "0")))
            result = verify("POST", self.path, self.headers, body)
            result["path"] = self.path
            result["body"] = json.loads(body)
            state["attempts"].append(result)
            if not all(result[k] for k in ("token_ok", "payload_hash_ok", "signature_ok")):
                self.reply(403, {"message": "SignatureDoesNotMatch: controlled peer rejected inconsistent signing"}, "SignatureDoesNotMatch")
                return
            messages = result["body"].get("messages", [])
            has_thinking = any(isinstance(m.get("content"), list) and any(c.get("type") == "thinking" for c in m["content"]) for m in messages)
            if args.case == "payload" and not state["calibration"] and has_thinking:
                self.reply(400, {"message": "messages.1.content.0: Invalid `signature` in `thinking` block"})
                return
            self.reply(200, {"id": "msg_controlled_peer", "type": "message", "role": "assistant", "model": "anthropic.claude-sonnet-4-6", "content": [{"type": "text", "text": "controlled peer accepted signature"}], "stop_reason": "end_turn", "stop_sequence": None, "usage": {"input_tokens": 10, "output_tokens": 5}})

    peer = ThreadingHTTPServer(("127.0.0.1", 0), Peer)
    threading.Thread(target=peer.serve_forever, daemon=True).start()
    peer_url = f"http://127.0.0.1:{peer.server_port}"
    with socket.socket() as listener:
        listener.bind(("127.0.0.1", 0))
        proxy_port = listener.getsockname()[1]
    proxy_url = f"http://127.0.0.1:{proxy_port}"
    params = {"model": "bedrock/anthropic.claude-sonnet-4-6", "aws_region_name": "us-east-1", "aws_bedrock_runtime_endpoint": peer_url}
    if args.case == "payload":
        params.update(aws_access_key_id="proof-access-static", aws_secret_access_key="proof-secret-static", aws_session_token="proof-token-static")
    master_key = "sk-" + secrets.token_hex(24)
    config = {"model_list": [{"model_name": "sigv4-proof", "litellm_params": params}], "general_settings": {"master_key": master_key}, "litellm_settings": {"telemetry": False}, "router_settings": {"num_retries": 0, "disable_cooldowns": True}}
    config_path = output.with_suffix(".config.json")
    config_path.write_text(json.dumps(config, indent=2))
    env = {k: v for k, v in os.environ.items() if k.upper() in {"PATH", "SYSTEMROOT", "WINDIR", "TEMP", "TMP", "COMSPEC", "LOCALAPPDATA", "APPDATA", "USERPROFILE"}}
    env.update(PYTHONPATH=str(Path(args.repo).resolve()), PYTHONUTF8="1", PYTHON_DOTENV_DISABLED="1", LITELLM_LOCAL_MODEL_COST_MAP="True", AWS_EC2_METADATA_DISABLED="true", AWS_CONFIG_FILE=str(output.with_suffix(".empty")), AWS_SHARED_CREDENTIALS_FILE=str(output.with_suffix(".empty")), CUSTOM_TIKTOKEN_CACHE_DIR=os.environ.get("CUSTOM_TIKTOKEN_CACHE_DIR", str(output.parent / "tiktoken")), NO_PROXY="127.0.0.1,localhost", DO_NOT_TRACK="1")
    if args.case == "rotation":
        env["AWS_CONTAINER_CREDENTIALS_FULL_URI"] = peer_url + "/credentials"
    body = {"model": "sigv4-proof", "max_tokens": 100, "messages": [{"role": "user", "content": "hi"}]}
    if args.case == "payload":
        body["messages"] += [{"role": "assistant", "content": [{"type": "thinking", "thinking": "x", "signature": ""}, {"type": "text", "text": "ok"}]}, {"role": "user", "content": "continue"}]
    log = output.with_suffix(".proxy.log").open("w", encoding="utf-8")
    process = subprocess.Popen([sys.executable, "-m", "litellm.proxy.proxy_cli", "--config", str(config_path), "--host", "127.0.0.1", "--port", str(proxy_port)], cwd=args.repo, env=env, stdout=log, stderr=subprocess.STDOUT)
    try:
        with httpx.Client(timeout=30, trust_env=False, headers={"Authorization": "Bearer " + master_key}) as client:
            for _ in range(90):
                if process.poll() is not None:
                    raise RuntimeError(f"Proxy exited {process.returncode}, see {log.name}")
                try:
                    if client.get(proxy_url + "/health/liveliness").status_code == 200:
                        break
                except httpx.TransportError:
                    pass
                time.sleep(1)
            else:
                raise RuntimeError("Proxy startup timed out")
            if args.case == "payload":
                calibration = client.post(proxy_url + "/v1/messages", json=body)
                if calibration.status_code != 200 or len(state["attempts"]) != 1:
                    raise RuntimeError(f"Calibration failed {calibration.status_code}: {calibration.text[:1500]}, attempts={state['attempts']}")
                body["extra_headers"] = {"x-amz-content-sha256": state["attempts"][0]["body_sha256"]}
                state["attempts"] = []
                state["calibration"] = False
            request_path = output.with_suffix(".request.json")
            request_path.write_text(json.dumps(body, indent=2))
            curl_binary = shutil.which("curl.exe") or shutil.which("curl")
            assert curl_binary is not None, "curl must be installed"
            curl = [curl_binary, "--silent", "--show-error", "--max-time", "40", "-w", "\n%{http_code}", "-H", "Authorization: Bearer " + master_key, "-H", "Content-Type: application/json", "-H", "anthropic-version: 2023-06-01", "--data-binary", "@" + str(request_path), proxy_url + "/v1/messages"]
            run = subprocess.run(curl, capture_output=True, text=True, timeout=45, check=True)
            response_body, response_status = run.stdout.rsplit("\n", 1)
            report = {"commit": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=args.repo, text=True).strip(), "case": args.case, "curl_command": subprocess.list2cmdline(curl).replace(master_key, "${LITELLM_MASTER_KEY}"), "response_status": int(response_status), "response": json.loads(response_body), "credential_fetches": state["generation"], "attempts": state["attempts"]}
            output.write_text(json.dumps(report, indent=2), encoding="utf-8")
            print(json.dumps({k: report[k] for k in ("commit", "case", "response_status", "credential_fetches", "attempts")}, indent=2), flush=True)
            assert report["response_status"] == (200 if args.expect == "pass" else 403)
            assert len(state["attempts"]) == (1 if args.case == "rotation" else 2)
            if args.case == "payload":
                assert state["attempts"][0]["body_sha256"] != state["attempts"][1]["body_sha256"]
                assert state["attempts"][0]["signature_ok"]
    finally:
        process.terminate()
        try:
            process.wait(timeout=10)
        except subprocess.TimeoutExpired:
            process.kill()
            process.wait()
        log.close()
        peer.shutdown()
        peer.server_close()


if __name__ == "__main__":
    main()

Before (61da6fc)

  1. Run python proxy_proof.py --repo ../before --case payload --expect fail --output ./proof/payload-before.json with that checkout at the named commit
  2. The harness sends this request to its real proxy. The temporary port, request path and local master key are normalized here
curl --silent --show-error --max-time 40 -w '\n%{http_code}' \
  -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
  -H "Content-Type: application/json" \
  -H "anthropic-version: 2023-06-01" \
  --data-binary @request.json http://127.0.0.1:$PROXY_PORT/v1/messages
  1. Observe HTTP 403 and this response
{
  "type": "error",
  "error": {
    "type": "permission_error",
    "message": "litellm.PermissionDeniedError: BedrockException - {\"message\": \"SignatureDoesNotMatch: controlled peer rejected inconsistent signing\"}\n\nLiteLLM: model group 'sigv4-proof' failed with the error above. No fallback was attempted."
  }
}
  1. The independent peer records
{
  "response_status": 403,
  "credential_fetches": 0,
  "attempts": [
    {
      "access": "proof-access-static",
      "token": "proof-token-static",
      "token_ok": true,
      "payload_hash_ok": true,
      "signature_ok": true,
      "body_sha256": "221e7780cda3fe0d7e5bcf1b906f9b185e565d18d470567e915a5f72e9fc781f"
    },
    {
      "access": "proof-access-static",
      "token": "proof-token-static",
      "token_ok": true,
      "payload_hash_ok": false,
      "signature_ok": false,
      "body_sha256": "7d4a3aca416f27f603e43c55e4219bf2b7f5b0f4b9c42af530afaa6ea9496159"
    }
  ]
}

After (36e7cd3)

  1. Run python proxy_proof.py --repo ../after --case payload --expect pass --output ./proof/payload-after.json with that checkout at the named commit
  2. The harness sends this request to its real proxy. The temporary port, request path and local master key are normalized here
curl --silent --show-error --max-time 40 -w '\n%{http_code}' \
  -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
  -H "Content-Type: application/json" \
  -H "anthropic-version: 2023-06-01" \
  --data-binary @request.json http://127.0.0.1:$PROXY_PORT/v1/messages
  1. Observe HTTP 200 and this response
{
  "id": "msg_controlled_peer",
  "type": "message",
  "role": "assistant",
  "model": "sigv4-proof",
  "content": [
    {
      "type": "text",
      "text": "controlled peer accepted signature"
    }
  ],
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 10,
    "output_tokens": 5
  }
}
  1. The independent peer records
{
  "response_status": 200,
  "credential_fetches": 0,
  "attempts": [
    {
      "access": "proof-access-static",
      "token": "proof-token-static",
      "token_ok": true,
      "payload_hash_ok": true,
      "signature_ok": true,
      "body_sha256": "221e7780cda3fe0d7e5bcf1b906f9b185e565d18d470567e915a5f72e9fc781f"
    },
    {
      "access": "proof-access-static",
      "token": "proof-token-static",
      "token_ok": true,
      "payload_hash_ok": true,
      "signature_ok": true,
      "body_sha256": "7d4a3aca416f27f603e43c55e4219bf2b7f5b0f4b9c42af530afaa6ea9496159"
    }
  ]
}

Regression validation

The focused checks were rerun at 36e7cd35782a7c2b7c34ab74cd4e40f73ffcacd3 on November 2 with refreshed locked dependencies

uv run --no-sync pytest tests/unit/llms/bedrock/test_base_aws_llm.py tests/unit/llms/custom_httpx/test_llm_http_handler.py -k 'sigv4_resign_uses_current_body_hash or anthropic_invalid_thinking_signature_retry_resigns_bedrock_request' -q --tb=short --timeout=30

Result: 15 passed, 520 deselected, 5 warnings in 6.54s

The current main signer fails ten hash-present cases while five absent-hash controls pass. Removing either pre-sign filtering or copy-back protection recreates all ten failures

The complete Bedrock base, Invoke, HTTP handler and Mantle Messages test files pass in a fresh Python 3.12 Linux container, 670 passed, 52 warnings in 47.99s. Scoped Ruff with the production and test configurations, production formatting and git diff --check against main pass. Full repository gates and current-tip coverage are left to hosted CI

The Linux environment uses the native bridge from main's unit workflow. Its artifact digest was verified, and the Rust sources, build configuration and model catalog are identical to main on this PR. This follows CI's shared bridge setup

Type

Bug Fix

Caveats

Medium

  • Live Bedrock/Mantle and IRSA deployment validation remain unavailable
  • The HTTP proof supplies the first hash through extra_headers. The reported stock code location that initially creates this header remains untraced. No live AWS call was made

Final Attestation

  • The tests check the right things, including edge cases and regressions in the respective real-world use cases

Review status and validation scope

Merged main 61da6fcb4dc02cd58e39cb8c57ab3c99bea39a4f on November 2. The signing fix and focused scope are unchanged. Dependency declarations, lockfiles and OSV exemptions match main

Fresh current-tip CI and automated reviews remain pending. Upstream's November 2 OSV scan passes with temporary filelock and MSAL exemptions. These are upstream's exemptions, and the dependency-upgrade PR #49204 remains unmerged. Earlier CI, coverage and review results do not count as approvals of this tip

The proxy/curl proof above was rerun at this merge base and exact tip. It uses a single proxy worker, synthetic credentials and an independent HTTP peer. Redis is omitted because the reproduction exercises standalone request signing. Live AWS acceptance, IRSA behavior and production failure frequency remain untested. Maintainer acceptance of this evidence or additional live validation remains outstanding

@CLAassistant

CLAassistant commented Oct 9, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@codspeed

codspeed Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 1 benchmark is dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 35 untouched benchmarks


Comparing micahmills88:fix_bedrock_resign_payload_hash (210b37b) with main (72f1ac4)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (dddbaa8) during the generation of this report, so 72f1ac4 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@codecov

codecov Bot commented Oct 9, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@micahmills88

Copy link
Copy Markdown
Author

@greptileai review this draft

@greptile-apps

greptile-apps Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[High impact] The code appears safe to merge; no actionable issue was found

Summary

The PR prevents old payload hashes from affecting Bedrock requests when a retry changes the body

  • Bedrock retries sign the changed body without reusing its old payload hash.

micahmills88 explicitly records that live AWS and IRSA validation are unavailable and requests maintainer validation. micahmills88 also acknowledges pending CI and broader test gates; CI must rerun on the latest revision. These acknowledged limits were not treated as completed checks. No tests were executed during this review

Reviews (1) · Last reviewed commit: "test(bedrock): expect computed headers t..." · Reviewed by Greptile

Copy link
Copy Markdown
Author

@greptileai please review the updated draft after merging main, including the refreshed regression evidence and explanation of the controlled reproduction trigger

@micahmills88
micahmills88 marked this pull request as ready for review October 12, 2026 18:02

Copy link
Copy Markdown
Author

bugbot run

Please review the current Bedrock signing fix, focused regression coverage, and documented validation limits after merging main

Copy link
Copy Markdown
Author

Please rerun mcp-server. Its unrelated cold schema-validation test timed out. The GitHub integration cannot rerun upstream jobs, returning 403

@micahmills88
micahmills88 force-pushed the fix_bedrock_resign_payload_hash branch from a421c9e to 2a12aa1 Compare October 12, 2026 18:04

Copy link
Copy Markdown
Author

@greptileai please review the current tip. CLA identity is corrected, code is unchanged, and fresh CI replaces the unrelated timeout

@cursor cursor 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.

Stale Bugbot comment from a previous run.

Copy link
Copy Markdown
Author

@greptileai added real proxy HTTP proof and the complete harness. The controlled retry returns 403 before and 200 after, with independently verified signatures

Copy link
Copy Markdown
Author

bugbot run

Please confirm the current commit after the CLA email correction. The previously reviewed code tree is unchanged

Copy link
Copy Markdown
Author

The fresh mcp-server run hit the same cold schema-validation timeout. Requested upstream rerun assistance on #45633, whose identical tree previously passed

@cursor cursor 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.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 2a12aa1. Configure here.

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.

2 participants