Lesson 8

Defend the HTTP Server

ตั้ง transport_security ของ http_server.py ให้รับแค่ Host 127.0.0.1:8765 ที่ไม่มี Origin เรียก API ปลายทางด้วย credential ของ server เอง เขียน pytest แล้วทำให้ Fail เพื่อพิสูจน์ว่าจับได้ ปิดท้ายด้วย checklist ก่อนติดตั้งและก่อนเปิด server

บทนี้ปิดช่องของบท HTTP Attacks แล้วส่ง request ชุดเดิมซ้ำครับ

ทุกคำสั่งรันในโฟลเดอร์ cafe-mcp และต้องมี tokens.env จากบท Require a Token

What to Defend

AttackChangeWhat Stops It
DNS rebindingTRANSPORT_SECURITY ใน auth.py ส่งให้ http_server.pyserver ตอบ 421 หรือ 403 และ pytest
Token passthroughpos.pypytest ที่ตรวจ header ที่ส่งออก

Write the Code

  • TRANSPORT_SECURITY ใน auth.py และ http_server.py
  • pos.py
  • script try_*.py สองตัวสำหรับรันโดยไม่ต้องมี AI
  • pytest สองไฟล์

1. Transport Security

เพิ่ม TRANSPORT_SECURITY ใน auth.py ต่อจาก AUTH_SETTINGS พร้อม import

auth.py
from mcp.server.transport_security import TransportSecuritySettings

# Only Host 127.0.0.1:8765 passes, and a request that carries any Origin header is refused.
TRANSPORT_SECURITY = TransportSecuritySettings(
    enable_dns_rebinding_protection=True,
    allowed_hosts=["127.0.0.1:8765"],
    allowed_origins=[],
)

แล้วส่งให้ entry point

http_server.py
from auth import TRANSPORT_SECURITY
from cafe_server import mcp

mcp.run(transport="streamable-http", host="127.0.0.1", port=8765, transport_security=TRANSPORT_SECURITY)
  • ค่าเริ่มต้นของ SDK รับ 127.0.0.1, localhost และ [::1] ทุก port ค่าใหม่รับ Host เดียวคือ 127.0.0.1:8765 ตรงกับ RESOURCE_URL
  • request ที่ไม่มี header Origin ผ่าน ส่วนที่มี Origin แต่ไม่อยู่ในรายการได้ 403 พอ allowed_origins=[] ทุก request ที่มี Origin ก็ได้ 403 curl กับ client ของ SDK ไม่ส่ง Origin แต่เบราว์เซอร์ส่งทุกครั้งที่ข้าม origin
  • เก็บค่าไว้ใน auth.py เพราะ try_bind_fixed.py ต้อง import และ http_server.py เรียก mcp.run ทันทีที่ถูก import

2. pos.py

โค้ดฝั่งที่ถูกของ Token Passthrough เขียนเป็นไฟล์แยกให้ทดสอบได้ ไม่ได้ลงทะเบียนเป็น tool ของ cafe

pos.py
import os
from datetime import date

import httpx2

from auth import require_scope


async def fetch_sales(day: str, http: httpx2.AsyncClient) -> str:
    """Calls the POS API with this server's own credential, never with the caller's token."""
    require_scope("orders:read")
    day = date.fromisoformat(day).isoformat()
    response = await http.get(
        f"https://pos.example.com/sales/{day}",
        headers={"Authorization": f"Bearer {os.environ['POS_API_TOKEN']}"},
    )
    response.raise_for_status()
    return response.text
  • require_scope ตรวจสิทธิ์ของผู้เรียกจาก token ที่ SDK ตรวจแล้ว ส่วน Authorization ที่ส่งออกไปใช้ POS_API_TOKEN ที่ API ปลายทางออกให้ server
  • date.fromisoformat บังคับให้ day เป็นวันที่ก่อนเข้า URL ค่าอย่าง ../admin ไม่ถึง API
  • import httpx2 เพราะ SDK 2.3.0 ใช้ตัวนี้ ใน virtual environment ไม่มี httpx
  • แทน pos.example.com กับ POS_API_TOKEN ด้วย API ที่ server ของเราเรียกจริง pytest ใช้ httpx2.MockTransport เลยไม่มี request ออกนอกเครื่อง

3. Scripts

try_defended_client.py เป็น client ของ SDK ที่แนบ token ของ staff ไว้เช็กว่า client ปกติยังต่อได้

try_defended_client.py
# DEMO: an MCP client over HTTP, with the token header, against the hardened http_server.py.
import asyncio
import os

import httpx2
from mcp import Client
from mcp.client.streamable_http import streamable_http_client


async def main() -> None:
    headers = {"Authorization": f"Bearer {os.environ['CAFE_STAFF_TOKEN']}"}
    async with httpx2.AsyncClient(headers=headers) as http:
        async with Client(streamable_http_client("http://127.0.0.1:8765/mcp", http_client=http)) as client:
            print("tools:", [tool.name for tool in (await client.list_tools()).tools])
            menu = await client.call_tool("list_menu", {"max_price_thb": 50})
            print("list_menu is_error:", menu.is_error)


asyncio.run(main())

try_bind_fixed.py ทำแบบ try_bind.py ที่ 0.0.0.0 เทียบกันระหว่างไม่ส่งกับส่ง TRANSPORT_SECURITY

try_bind_fixed.py
# DEMO: a server bound to 0.0.0.0 with and without explicit transport_security. No network needed.
from mcp.server.mcpserver import MCPServer
from starlette.testclient import TestClient

from auth import TRANSPORT_SECURITY

BODY = {
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/list",
    "params": {"_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}}},
}
HEADERS = {
    "Content-Type": "application/json",
    "Accept": "application/json, text/event-stream",
    "MCP-Protocol-Version": "2026-07-28",
    "Mcp-Method": "tools/list",
}
FOREIGN = "http://evil.example.com:8765"
CASES = [
    ("0.0.0.0, no settings, foreign Host and Origin", None, FOREIGN, {"Origin": FOREIGN}),
    ("0.0.0.0, explicit settings, foreign Host and Origin", TRANSPORT_SECURITY, FOREIGN, {"Origin": FOREIGN}),
    ("0.0.0.0, explicit settings, Host 127.0.0.1:8765", TRANSPORT_SECURITY, "http://127.0.0.1:8765", {}),
]

for label, settings, base_url, extra_headers in CASES:
    app = MCPServer("probe").streamable_http_app(host="0.0.0.0", transport_security=settings)
    with TestClient(app, base_url=base_url) as http:
        print(f"{label} ->", http.post("/mcp", headers=HEADERS | extra_headers, json=BODY).status_code)

4. Tests

tests/test_transport_security.py
import runpy

import pytest
import uvicorn
from starlette.testclient import TestClient

BODY = {
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/list",
    "params": {"_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}}},
}


def served_config(monkeypatch) -> uvicorn.Config:
    """Runs http_server.py with uvicorn stubbed out and returns the config it would have served."""
    served = []

    async def capture(server, *args, **kwargs):
        served.append(server.config)

    monkeypatch.setattr(uvicorn.Server, "serve", capture)
    runpy.run_module("http_server")
    return served[0]


@pytest.mark.parametrize(
    "extra_headers, expected_status",
    [
        ({}, 200),
        ({"Host": "evil.example.com:8765"}, 421),
        ({"Origin": "https://evil.example.com"}, 403),
        ({"Host": "evil.example.com:8765", "Origin": "http://evil.example.com:8765"}, 421),
        ({"Origin": "http://localhost:3000"}, 403),
        ({"Host": "localhost:8765"}, 421),
    ],
    ids=["normal", "foreign-host", "foreign-origin", "foreign-host-and-origin", "localhost-origin", "localhost-host"],
)
def test_http_server_refuses_foreign_host_and_origin(monkeypatch, extra_headers, expected_status):
    monkeypatch.setenv("CAFE_VIEWER_TOKEN", "secret-for-viewer")
    headers = {
        "Authorization": "Bearer secret-for-viewer",
        "Content-Type": "application/json",
        "Accept": "application/json, text/event-stream",
        "MCP-Protocol-Version": "2026-07-28",
        "Mcp-Method": "tools/list",
        **extra_headers,
    }
    config = served_config(monkeypatch)
    assert (config.host, config.port) == ("127.0.0.1", 8765)
    with TestClient(config.app, base_url="http://127.0.0.1:8765") as http:
        assert http.post("/mcp", headers=headers, json=BODY).status_code == expected_status
tests/test_pos.py
import httpx2
import pytest
from mcp.server.auth.middleware.auth_context import auth_context_var
from mcp.server.auth.middleware.bearer_auth import AuthenticatedUser
from mcp.server.auth.provider import AccessToken
from mcp.server.mcpserver.exceptions import ToolError

from pos import fetch_sales


def mock_pos_api(requests: list[httpx2.Request]) -> httpx2.AsyncClient:
    def respond(request: httpx2.Request) -> httpx2.Response:
        requests.append(request)
        return httpx2.Response(200, text='{"total_thb": 225}')

    return httpx2.AsyncClient(transport=httpx2.MockTransport(respond))


@pytest.fixture(autouse=True)
def pos_credential(monkeypatch):
    monkeypatch.setenv("POS_API_TOKEN", "token-issued-to-this-server")
    yield
    auth_context_var.set(None)


async def test_downstream_call_carries_the_servers_credential_not_the_callers():
    auth_context_var.set(AuthenticatedUser(AccessToken(token="token-of-the-caller", client_id="viewer", scopes=["orders:read"])))
    requests: list[httpx2.Request] = []
    async with mock_pos_api(requests) as http:
        await fetch_sales("2026-11-24", http)
    assert requests[0].headers["Authorization"] == "Bearer token-issued-to-this-server"
    assert "token-of-the-caller" not in str(requests[0].headers)


async def test_caller_without_scope_never_reaches_the_downstream_api():
    auth_context_var.set(AuthenticatedUser(AccessToken(token="token-of-the-caller", client_id="guest", scopes=[])))
    requests: list[httpx2.Request] = []
    async with mock_pos_api(requests) as http:
        with pytest.raises(ToolError):
            await fetch_sales("2026-11-24", http)
    assert requests == []


async def test_day_must_be_a_date_before_it_reaches_the_url():
    requests: list[httpx2.Request] = []
    async with mock_pos_api(requests) as http:
        with pytest.raises(ValueError):
            await fetch_sales("../admin", http)
    assert requests == []
  • test_transport_security.py รัน http_server.py ด้วย runpy โดยแทน uvicorn.Server.serve ด้วยฟังก์ชันที่เก็บ config ไว้เฉย ๆ app ที่ได้เลยสร้างตามทางเดียวกับตอนรันจริง แค่ไม่เปิด port ถ้า http_server.py ลืมส่ง TRANSPORT_SECURITY เทสต์นี้ Fail
  • กรณี Host กับ Origin แปลกพร้อมกันคาดว่าได้ 421 ตามที่ SDK 2.3.0 ตอบ
  • test_pos.py ตรวจว่า header ที่ไปถึง API ปลายทางเป็น credential ของ server ผู้เรียกที่ไม่มี scope ไม่ทำให้เกิด request เลย และ day ที่ไม่ใช่วันที่ถูกปฏิเสธก่อนสร้าง URL

Re-run the Attacks

  • Host และ Origin ด้วย probe ชุดเดิม
  • bind ที่ 0.0.0.0 แบบส่ง settings

Host and Origin

รัน http_server.py ที่แก้แล้ว

bash
source tokens.env
uv run python http_server.py

ใน terminal ที่มี probe อยู่ (ถ้าปิดไปแล้ว ตั้งใหม่ตามบท HTTP Attacks) ส่งชุดเดิมซ้ำ แล้วเพิ่ม Host localhost:8765

bash
probe "$CAFE_STAFF_TOKEN" -H 'Origin: http://localhost:3000'
ผลลัพธ์จาก probe "$CAFE_STAFF_TOKEN" -H 'Origin: http://localhost:3000'
HTTP/1.1 403 Forbidden
Invalid Origin header
bash
probe "$CAFE_STAFF_TOKEN" -H 'Host: localhost:8765'
ผลลัพธ์จาก probe "$CAFE_STAFF_TOKEN" -H 'Host: localhost:8765'
HTTP/1.1 421 Misdirected Request
Invalid Host header
RequestBeforeNow
token ของ staff, Host 127.0.0.1:8765, ไม่มี Origin200200
Host: evil.example.com:8765421421
Origin: https://evil.example.com403403
Host และ Origin แปลกพร้อมกัน421421
Origin: http://localhost:3000200403
Host: localhost:8765ไม่ได้ส่ง421
token ว่าง401401

แถวที่เปลี่ยนคือ Origin ของ localhost port อื่น ที่เหลือ SDK ตอบแบบนี้อยู่แล้ว แต่ตอนนี้ไม่ได้พึ่งค่าเริ่มต้นของ SDK แล้ว

client ที่แนบ token ยังต่อได้

bash
uv run python try_defended_client.py
ผลลัพธ์จาก uv run python try_defended_client.py
tools: ['list_menu', 'create_order', 'cancel_order']
list_menu is_error: False

Bind to 0.0.0.0

bash
uv run python try_bind_fixed.py 2>/dev/null
ผลลัพธ์จาก uv run python try_bind_fixed.py 2>/dev/null
0.0.0.0, no settings, foreign Host and Origin -> 200
0.0.0.0, explicit settings, foreign Host and Origin -> 421
0.0.0.0, explicit settings, Host 127.0.0.1:8765 -> 200

ส่ง settings เองแล้ว bind ที่ทุก interface ก็ยังปฏิเสธ Host แปลกได้ แต่ http_server.py ยัง bind ที่ 127.0.0.1 ตามที่ spec แนะนำ ถ้าต้องเปิดให้เครื่องอื่นในเครือข่ายเรียก ต้องทำพร้อมกันสามอย่าง

  • ระบุ allowed_hosts เป็นชื่อที่ client ใช้เรียกจริง เช่น cafe.example.com และใส่ allowed_origins เฉพาะเมื่อมีเว็บแอปที่เรียก server ตรง ๆ
  • วาง reverse proxy ที่ทำ HTTPS ไว้ข้างหน้า เพราะ bearer token บน HTTP ธรรมดาถูกดักอ่านได้
  • คง token กับ scope ไว้ เพราะ Host กับ Origin กันได้แค่ request จากเบราว์เซอร์

Run the Tests

  • ชุดทดสอบทั้งหมด
  • ลบ transport_security ออกจาก http_server.py แล้วดูเทสต์ Fail
  • ให้ pos.py ส่ง token ของผู้เรียกแล้วดูเทสต์ Fail
bash
uv run pytest -q
ผลลัพธ์จาก uv run pytest -q
.................................                                        [100%]
33 passed in 0.20s

22 ตัวจากบท Limit Tools by Scope บวก 2 ตัวของ test_review_tools.py จากบท Defend Against Tool Attacks และ 9 ตัวของบทนี้

เทสต์ที่ไม่เคย Fail ยังพิสูจน์อะไรไม่ได้ ลบ , transport_security=TRANSPORT_SECURITY ออกจากบรรทัด mcp.run ใน http_server.py แล้วรัน

bash
uv run pytest tests/test_transport_security.py -v | grep -E 'PASSED|FAILED|passed|failed'
ผลลัพธ์จาก uv run pytest tests/test_transport_security.py -v | grep -E 'PASSED|FAILED|passed|failed'
tests/test_transport_security.py::test_http_server_refuses_foreign_host_and_origin[normal] PASSED [ 16%]
tests/test_transport_security.py::test_http_server_refuses_foreign_host_and_origin[foreign-host] PASSED [ 33%]
tests/test_transport_security.py::test_http_server_refuses_foreign_host_and_origin[foreign-origin] PASSED [ 50%]
tests/test_transport_security.py::test_http_server_refuses_foreign_host_and_origin[foreign-host-and-origin] PASSED [ 66%]
tests/test_transport_security.py::test_http_server_refuses_foreign_host_and_origin[localhost-origin] FAILED [ 83%]
tests/test_transport_security.py::test_http_server_refuses_foreign_host_and_origin[localhost-host] FAILED [100%]
FAILED tests/test_transport_security.py::test_http_server_refuses_foreign_host_and_origin[localhost-origin]
FAILED tests/test_transport_security.py::test_http_server_refuses_foreign_host_and_origin[localhost-host]
========================= 2 failed, 4 passed in 0.07s ==========================

สองตัวที่ Fail คือกรณี localhost ที่ค่าของเราแคบกว่าค่าเริ่มต้นของ SDK ใส่ transport_security=TRANSPORT_SECURITY คืนแล้วรันใหม่จะได้ 6 passed

ต่อไปทำให้ pos.py พัง เพิ่ม from mcp.server.auth.middleware.auth_context import get_access_token แล้วเปลี่ยนค่าใน Authorization จาก os.environ['POS_API_TOKEN'] เป็น get_access_token().token

bash
uv run pytest tests/test_pos.py -q | grep -E 'FAILED|passed|failed|AssertionError'
ผลลัพธ์จาก uv run pytest tests/test_pos.py -q | grep -E 'FAILED|passed|failed|AssertionError'
E       AssertionError: assert 'Bearer token-of-the-caller' == 'Bearer token...o-this-server'
tests/test_pos.py:31: AssertionError
FAILED tests/test_pos.py::test_downstream_call_carries_the_servers_credential_not_the_callers
1 failed, 2 passed in 0.04s

token ของผู้เรียกหลุดไปถึง API ปลายทาง เทสต์เลย Fail คืนโค้ดเดิมแล้วรัน uv run pytest -q ให้ได้ 33 passed

Try It in Claude Code

  • ต่อ cafe-auth กับ http_server.py ที่ตั้งค่าใหม่
  • ล้างสิ่งที่ลงทะเบียนไว้

Connect cafe-auth

allowed_origins=[] ปฏิเสธทุก request ที่มี Origin ถ้า Claude Code ส่ง Origin มา cafe-auth จะต่อไม่ได้ ลองดู

ถ้า http_server.py จากหัวข้อ Host and Origin ยังรันอยู่ ใช้ตัวนั้นต่อได้เลย (ถ้าปิดไปแล้ว เปิดใหม่จาก shell ที่ source tokens.env แล้ว) จากนั้นลงทะเบียน cafe-auth ใหม่ในอีก terminal (บท Limit Tools by Scope ถอดออกไปแล้ว)

bash
claude mcp add-json cafe-auth '{"type":"http","url":"http://127.0.0.1:8765/mcp","headers":{"Authorization":"Bearer ${CAFE_STAFF_TOKEN}"}}' --scope project

เปิด claude จาก shell ที่ source tokens.env แล้ว พิมพ์ /mcp แล้วเลือก cafe-auth

หน้า /mcp ของ Claude Code เลือก cafe-auth แสดง Status connected, Auth authenticated, Protocol 2026-07-28, URL http://127.0.0.1:8765/mcp และ Tools 3 tools

ขึ้น connected กับ authenticated ครบ 3 tools แปลว่า Claude Code ไม่ได้ส่ง Origin ที่ server ปฏิเสธ

Clean Up

bash
claude mcp remove --scope project cafe-auth

หยุด http_server.py (Ctrl+C)

Pitfalls

  • allowed_origins=[] ปฏิเสธเว็บ client ที่เรียก server ตรง ๆ จากเบราว์เซอร์ด้วย ถ้ามี client แบบนั้นให้ใส่ origin ของมันตรงตัว เช่น https://app.example.com ไม่ใช้ wildcard
  • allowed_hosts ต้องตรงกับ Host ที่ client ส่งรวม port เรียกผ่าน localhost:8765 ก็ได้ 421
  • ถ้า SDK รุ่นหน้าเปลี่ยนไปตรวจ Origin ก่อน Host กรณี foreign-host-and-origin จะ Fail ต้องแก้ค่าที่คาดเป็น 403
  • fetch_sales อ่าน POS_API_TOKEN ตอนเรียก ไม่ตั้งไว้จะได้ KeyError เก็บใน environment variable ของ server เหมือน CAFE_* ไม่เขียนลง .mcp.json ที่ commit
  • test_pos.py ตรวจแค่ header ที่ส่งออก ไม่ได้ตรวจว่า API ปลายทางรับ credential นั้น

Summary

http_server.py รับแค่ Host 127.0.0.1:8765 ที่ไม่มี Origin โดยไม่พึ่งค่าเริ่มต้นของ SDK แล้ว Origin: http://localhost:3000 เปลี่ยนจาก 200 เป็น 403 แต่ Claude Code ยังต่อได้ pos.py ส่ง credential ของ server เองให้ API ปลายทาง และ เทสต์ชุด 33 ตัว Fail เมื่อเราถอด guard ออก

ถึงตรงนี้เรามีครบทั้งสองฝั่ง ฝั่งติดตั้ง server ของคนอื่นกับฝั่งเปิด server ของเรา

WhenCheckLesson
ก่อนติดตั้ง server ของคนอื่นอ่านคำสั่งเต็มใน .mcp.json และอ่านโค้ดของ server ก่อนรันRun Tool Attacks, Defend Against Tool Attacks
ก่อนติดตั้ง server ของคนอื่นพิมพ์ description กับ schema เต็มด้วย review_tools.py review แล้วดู argument ที่เกินหน้าที่Defend Against Tool Attacks
ก่อนติดตั้ง server ของคนอื่นpin หลังอนุมัติ commit tools.lock.json แล้วรัน check ก่อนใช้งานDefend Against Tool Attacks
ก่อนติดตั้ง server ของคนอื่นรัน server แบบ stdio ใน sandbox ที่ปิด network และกันไฟล์ข้อมูลDefend Against Tool Attacks
ทุกครั้งที่เรียก toolอ่าน argument ในหน้าขออนุญาตก่อนกด YesRun Tool Attacks
ก่อนเปิด server ของเราทุก request ต้องมี token ที่ออกให้ server นี้Require a Token
ก่อนเปิด server ของเราtool ที่แก้ข้อมูลตรวจ scope ก่อนทำงานLimit Tools by Scope
ก่อนเปิด server ของเราbind ที่ 127.0.0.1 และระบุ allowed_hosts กับ allowed_origins เองบทนี้
ก่อนเปิด server ของเราเรียก API อื่นด้วย credential ของ server เองบทนี้
ก่อนเปิด server ของเรามีเทสต์ที่เคยทำให้ Fail ด้วยการถอด guardบทนี้, Limit Tools by Scope

ยังเหลือค่าที่ AI ส่งเข้ามาใน argument ถ้า tool เอาค่านั้นไปต่อเป็นคำสั่ง shell จะเกิดอะไรขึ้น? บทหน้า Shell Commands from Tool Input ลองดูครับ

References

Copyright © 2026