Bob Belderbos: How to enforce least privilege with httpx

Wait 5 sec.

This week I learned that httpx.Client takes an event_hooks argument. A request hook runs before each request goes out. If it raises, the request is never sent. That makes it a neat place to enforce a permission policy.This client for a helpdesk API may read tickets and archive them, nothing else. The example uses numeric ticket IDs.import jsonimport reimport httpxBASE_URL = httpx.URL("https://helpdesk.example.com")TICKET_PATH = re.compile(rb"/tickets/[0-9]+")class WriteRefused(Exception): passdef _is_archive(request: httpx.Request) -> bool: try: body = json.loads(request.content) except (ValueError, httpx.RequestNotRead): return False return isinstance(body, dict) and len(body) == 1 and body.get("archived") is Truedef _refuse_unless_read_or_archive(request: httpx.Request) -> None: url = request.url if (url.scheme, url.host, url.port) == (BASE_URL.scheme, BASE_URL.host, BASE_URL.port): path = url.raw_path.split(b"?", 1)[0] is_ticket = TICKET_PATH.fullmatch(path) is not None if request.method == "GET" and (path == b"/tickets" or is_ticket): return if request.method == "PATCH" and is_ticket and _is_archive(request): return raise WriteRefused(f"Refused {request.method} {url.path} on {url.host}")def make_client(transport: httpx.BaseTransport | None = None) -> httpx.Client: return httpx.Client( base_url=BASE_URL, transport=transport, event_hooks={"request": [_refuse_unless_read_or_archive]}, )We explicitly say what is allowed instead of blocking certain things, so anything we didn't think of is refused.On the helpdesk origin, GET passes for /tickets and individual tickets. PATCH passes only for an individual ticket with the JSON body {"archived": true}. All other write operations like POST and DELETE are refused, and so are {"archived": 1} and {"archived": true, "status": "closed"}, because the whole body has to match.The transport parameter of make_client is a good example of dependency injection and it helps with testing: pass httpx.MockTransport, which answers requests with a plain function instead of the network, and you can assert that a DELETE raises WriteRefused without a real server.This is the principle of least privilege, which Jim and I wrote about in the latest Scripter to Rust newsletter.Rust expresses a similar idea through its references: &T provides shared access, while &mut T provides exclusive, mutable access. The idea goes back all the way to Saltzer and Schroeder's The Protection of Information in Computer Systems paper from 1975:Every program and every user of the system should operate using the least set of privileges necessary to complete the job.The hook can't stop code that clears it or builds its own client, though. For that the helpdesk can go one step further: give the app an API key with only read and archive rights, and the server rejects a DELETE whoever sends it. The hook fails fast, in your own process, with a message that says exactly what was attempted.The same goes for AI agents. The common pattern is full access plus a prompt asking the agent to be careful. Flip the default: hand the agent a client that can only make the calls the task needs, and let everything else fail loudly.Don't prompt for least privilege. Enforce it in code.