Secrets, sign-ins and the addresses a program opens
Where an agent's credentials should live, how to sign in as the owner with OAuth and the narrowest permissions, how to state an exception to a safety rule honestly, and how to open addresses other people typed without server-side request forgery.
- List the kinds of credential a personal agent holds, say where each one lives, and say who else holds a copy.
- Explain, step by step, how a program signs in to a service as its owner without a key being copied, and implement the return to the local machine.
- Ask a service for only the permissions the program means to use, and check that the request on the wire says the same.
- State a deliberate exception to a safety rule so that a reader can check every condition of it.
- Explain server-side request forgery and guard a program that opens addresses somebody else typed.
- Week
- 7 of 14
- Before it
- Chapter 8 and Chapter 9; Definitions 1, 2, 4 and 6 and Property 2 of the model.
- Read first
- [RFC 9700]; [OWASP 2021].
- Laboratory
- 2: a gate, and a proof that it mediates
- Problem set
- 3
10.1The problem: keys, sign-ins and addresses the program does not choose
An agent acts on its owner's accounts, so it must hold something that opens them. The plain way is a key pasted into a settings file. A key copied by hand can land in the wrong place, does not say whose it is, and usually opens more than the program needs.
Consider two requests on one afternoon. The owner says: connect the firm's customer database, so that you can look people up. Then the owner sends a link to a pitch deck and nothing else. The first needs a credential that acts as the owner, and only as far as the owner intends. The second makes the program connect to an address chosen by whoever wrote the link, which on a server can lead somewhere only the program can reach. This chapter is about holding credentials narrowly and opening addresses carefully.
10.2The kinds of credential, and where each lives
- Credential
- Anything that lets its holder act as someone at a service: a password, a key, a token, a session cookie, or a link that grants access by itself.
- API key
- A long-lived secret issued by a vendor to a program, sent with every request. It identifies the account that pays, not the person being served.
- Access token
- A short-lived credential issued after a person approves a program at a service. It carries a list of permissions.
- Refresh token
- A longer-lived credential used only to obtain a new access token when the old one expires, without asking the person again.
- Scope
- The list of permissions a program asks for, and a token carries, such as "read posts" or "send direct messages".
The program's rule for every one of them is the same: no credential is ever placed in anything the model reads. The settings module says so at its head (odysseus/config.py): "Secrets live only here and in the process environment. They are never placed in anything the model reads." The table shows where each kind actually lives.
| Credential | Where it lives | Who else holds something that opens the account |
|---|---|---|
| Vendor keys: the chat bot's token, the model, search, the connector service, the browser service, text recognition, tracing | The .env file locally (ignored by git, never put into the server image) or the host's secret store on a server | Each vendor, for its own key |
| Access and refresh tokens for a service with its own server (the firm's database, meeting notes, X, DocSend) | One file per service in the data folder, <name>.json | The service, which can withdraw them |
| Access to the owner's mail and calendar | The connector service; the program holds only its key | The connector service |
| Sign-ins to websites for the browser | A saved browser profile at the browser vendor | The browser vendor; the program holds no password |
| The live-view link to a running browser | Sent once, to the owner's own chat | Anyone who obtains the link, for as long as the browser runs |
| A program's identity at a service that will not let programs register themselves (X) | An identifier from the owner's own developer app, in the settings | The owner's developer account |
The data folder holds tokens, mail text and the conversation in the clear; inside a folder that a file-syncing service copies, all of it is copied too, so the program warns at start-up when that is so. Two nets catch credentials that reach the model by accident: memory refuses text shaped like a card number or an access key, and tracing strips keys. Both are patterns and will miss things.
10.3Signing in as the owner without copying a key
The idea
A service that speaks the Model Context Protocol (Chapter 13) can use the same exchange a website uses for "sign in with". The program asks for access; the owner approves in a browser where they are already signed in; the service hands the program two tokens, one to act with and one to renew it. Nothing is copied by hand, and the program acts with exactly the permissions the owner approved.
- OAuth authorisation code flow
- A standard exchange in which a person approves a program at a service, the service sends the person's browser back to the program with a one-time code, and the program trades that code for tokens.
- Redirect address (return address)
- Where the service sends the browser after approval. For a program on the owner's own machine it is an address on that machine,
http://127.0.0.1:<port>/callback. - Proof key (PKCE)
- A random secret the program makes before the sign-in. The link carries only a scrambled form of it; the program must present the original when it trades the code. Only the program that made the link can do that.
Why the proof key matters, in plain words: the one-time code travels through the browser inside an ordinary web address, which other software on the machine might see. A program with no secret of its own (this one registers with token_endpoint_auth_method="none") could have its code stolen and traded. The proof key makes a stolen code useless.
The code
The tokens are kept by a small class that the protocol library calls to read and write them. From odysseus/attio.py:
def _write(self, key: str, value: dict[str, Any]) -> None:
data = self._read()
data[key] = value
self.path.parent.mkdir(parents=True, exist_ok=True)
tmp = self.path.with_suffix(".tmp")
tmp.write_text(json.dumps(data), encoding="utf-8")
tmp.replace(self.path)
def signed_in(self) -> bool:
return bool(self._read().get("tokens"))
The file is written to a temporary file and put in place in one step, so a crash mid-write cannot leave a half-written token file. It also holds the program's registration (its client identifier and registered return address), which matters for the port below.
Step 6 needs something on the owner's machine to receive the browser. From the same file:
async def wait_for_callback(timeout_s: float = 600, port: int | None = None) -> tuple[str, str | None, str | None]:
"""Listen once on this machine for the browser coming back from the service. Returns (code, state, issuer)."""
done = asyncio.get_running_loop().create_future()
async def serve(reader, writer) -> None:
line = (await reader.readline()).decode("latin-1")
query = parse_qs(urlsplit(line.split(" ")[1] if " " in line else "").query)
ok = bool(query.get("code"))
body = b"Connected. You can close this tab." if ok else b"The service did not send a code. Nothing was connected."
writer.write(b"HTTP/1.1 200 OK\r\n..." + body) # headers shortened here
await writer.drain()
writer.close()
if ok and not done.done():
done.set_result((query["code"][0], (query.get("state") or [None])[0], (query.get("iss") or [None])[0]))
server = await asyncio.start_server(serve, "127.0.0.1", port or CALLBACK_PORT)
try:
return await asyncio.wait_for(done, timeout_s)
finally:
server.close()
It is the smallest possible web server: it reads one request line, takes the code, gives a plain answer and closes. It listens on 127.0.0.1 only, so no other machine can reach it, for at most ten minutes. The state value is handed back to the sign-in library with the code. In the standard, its purpose is to tie the browser's return to the sign-in this program started (this book's explanation, not something tested here).
The cost of returning to the local machine
Step 5 sends the browser to the owner's own machine. So the sign-in completes only in a browser on the machine where the program runs. From a phone it cannot complete. On a server in a data centre it needs a public return address, a page of the program's own, which Chapter 16 describes. Verified: the first sign-in ran once, and later calls used the stored token without a second sign-in. Not tested: renewal after the first token expires, and what happens when the owner withdraws access at the service.
A sign-in that quietly stopped being renewed
A sign-in with a service is two tokens: a short-lived one that is presented with each request, and a longer-lived one used only to get a new short-lived one. The owner connected a service from the chat; it worked; and some hours later it reported that the sign-in had lapsed. The owner connected it again. It lapsed again.
Nothing had been withdrawn. The program saved the tokens and not the moment they were issued. The library that signs in keeps that moment only in memory, so after a restart it had a token and not its age, took it to be good for ever, and went on presenting it. When the service refused it, the library tried to renew, did not know where the service's token address was (it learns that during a sign-in, not from disk), guessed, was refused again, threw the sign-in away and asked for a new one, which nobody was there to give. Every connection was good for exactly the life of its first token: two hours for two services, six for a third, a day for the firm's database. Two other services had run out in the same way without anyone noticing, because nothing had asked them anything since.
The repair is in the program, by the standard steps. The moment of issue is saved. Before a session is opened with a token that has run out, the program reads where the token address is from the service's own published description and exchanges the renewal token for a new pair. One renewal runs at a time, because a renewal token is good for one use and two sessions opening together would spend it twice.
The renewal token is the most valuable thing in the file, so where it may be sent is decided by code and not by what a description says: only to an https address on the same site as the server the owner connected. A description naming an address anywhere else is refused, and nothing is posted. Verified: on the real services, three sign-ins that had run out were renewed without the owner; six unit tests, among them the refusal and the single renewal (tests/test_renewal.py). Not tested: a service whose renewal token itself expires, where the owner must sign in again and should be told why.
Every check of these connections had been made within minutes of connecting, which is the one stretch of time in which the fault cannot show.
10.4Asking only for what the program will use
An agent that reads what strangers write should hold no permission it does not use, because a misled model can only misuse permissions that exist. For the firm's database, X and DocSend the program's configuration states the permissions to ask for. For the other services (the meeting notes, the data vendors, any server connected by address) it states none: the link asks for whatever the server advertises, and the chat message says so, so that the owner can read the provider's approval page before approving. Even where the permissions are stated, stating them turned out not to be enough.
The owner asked how to give the assistant control of a partner's X account, so that it could surface opportunities. The answer was not to: finding opportunities needs reading (the timeline, lists, bookmarks, follows, search) and no permission to post, reply or message. The configuration listed seven reading permissions. The first sign-in link the program produced asked X for every permission X offers, including posting, sending direct messages and changing billing. The sign-in library had replaced the configured list with the server's full list of what it supports, because the protocol tells a client to ask for what the server advertises. Both were behaving as designed, and together they turned "read only" into "everything".
It was caught because the link was read before it was opened. No approval was given on it and no token was saved.
The repair is to rewrite the link after the library builds it and before the owner sees it. From odysseus/attio.py:
def pin_scope(link: str, scope: str | None) -> str:
"""The sign-in link, asking for exactly the permissions this program was told to ask for and no others."""
if not scope:
return link
parts = urlsplit(link)
query = [(k, v) for k, v in ((k, v[0]) for k, v in parse_qs(parts.query, keep_blank_values=True).items()) if k != "scope"]
return urlunsplit(parts._replace(query=urlencode(query + [("scope", scope)])))
Every parameter survives except scope, which is replaced, not added to. The library reaches the owner only through the function that calls pin_scope, so every link passes through it; for a service with no configured permissions it is passed on unchanged. The chat message lists the permissions asked for above the link; where a service's entry names none, it says the service chooses and asks the owner to read its page.
Verified: X's approval page then listed only reading, and the token X returned carries the seven reading permissions and no others. A second service showed the same pattern from the other side: DocSend's sign-in, left alone, asks to write files, data rooms and contacts as well as to read. Only the four reading permissions are asked for, and the approval page the owner saw listed only viewing. A third case went the other way on purpose: DocSend's sign-in for uploading a file asked to "Edit your DocSend content and settings" and "Send emails or other notifications on your behalf". Work stopped and the owner was asked; they approved it for one test upload, and the token was used once and deleted.
The narrow permissions have a second use. X and DocSend are marked in the program as connections that can only read, and every tool they offer then runs without asking (Chapter 8). That rests entirely on the token carrying only reading permissions and on the tools hidden by name; were a service to grant more than was asked and offer a writing tool not hidden by name, nothing in the program would stop that tool from running unasked.
A configuration states what the program intends. Only the link, and better still the token that comes back, shows what was actually requested and granted.
10.5The port a sign-in returns to
A fixed return port failed in practice: a DocSend sign-in could not use it because another program on the machine held it. A free port per sign-in is half the answer. From odysseus/connect.py and odysseus/attio.py:
def free_port() -> int:
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return int(s.getsockname()[1])
def _return_port(tokens: FileTokens, port: int | None) -> int:
"""Where this sign-in comes back to. A service remembers the address a program registered with, so a program that
has registered before must come back to that same port; a first sign-in may use any free one."""
try:
raw = (tokens._read().get("client") or {}).get("redirect_uris") or []
known = urlsplit(str(raw[0])).port if raw else None
except Exception:
known = None
return known or port or CALLBACK_PORT
The other half is that a service compares the return address on each sign-in with the one the program registered. A program that registered on port 8765 must come back on port 8765, not on whatever port is free today. So the port is chosen per sign-in only the first time, and remembered per service from the registration in its token file. Asking the operating system for port 0 is how a program obtains a port nobody holds.
10.6Websites: the owner signs in by hand
Many sites offer programs no sign-in exchange, so the agent uses a browser (Chapter 14). A vault of passwords the model cannot read is the obvious design. It was not needed.
- Cookie
- A small piece of data a site stores in a browser after sign-in, so that the browser is recognised on later visits without the password being typed again.
- Browser profile
- A browser's saved state: its cookies and other stored data. Loading the same profile into a new browser makes it start out signed in wherever the old one was.
- Live view
- A web link through which a person can see and operate a browser running elsewhere.
The owner sends /browser. The program asks the browser vendor for a browser loaded with the owner's profile and replies with a live-view link. The owner opens it, signs in to the sites they want, typing their own passwords into the sites' own pages and completing any second step themselves, then sends /browser done. Stopping the browser saves the sign-ins to the profile. Later runs load it. The program never sees a password and stores none, so there is nothing a model could be tricked into revealing.
The sign-ins live with the vendor, another third party holding something that opens the owner's accounts. The live-view link is itself a key: the vendor's documentation says to treat it as a credential. The program sends it only to the owner's chat, says so, and the browser closes after twenty minutes. And sign-ins wear out; a later run may find itself at a sign-in page, and nothing detects this in advance.
10.7A narrow exception, stated as one
Chapter 9 removes sign-in codes and account links from mail before any model sees it, so that a misled model can never be used to take over an account. One errand meets that rule head on. A deck shared through DocSend often asks for the viewer's address and then verifies it: DocSend's help pages say a message is sent with a link, valid for an hour, which "must be clicked from the same device" that opened the document. The owner asked for the assistant to do this with their address (Chapter 22).
The rule stands. The exception is that code, not a model, reads one kind of link, under four conditions, all checked in code:
- the message's From line names an address at docsend.com (a line anyone can forge, so the protection rests on conditions 2 to 4);
- the link points at docsend.com;
- the message arrived after this run began;
- the run was begun by the owner typing a DocSend link in their own message.
The link goes to the browsing agent and nowhere else. It is not shown to the conversation's model and not written to the log. What it unlocks is one document, for viewing. From odysseus/deckview.py:
def verification_link(message: dict[str, Any]) -> str | None:
"""The link in a message from DocSend that verifies an address. None unless the sender and the link are both DocSend's."""
sender = str(message.get("sender") or message.get("from") or "").lower()
m = re.search(r"@([a-z0-9.-]+)", sender)
domain = m.group(1).rstrip(">") if m else ""
if not (domain == HOST or domain.endswith("." + HOST)):
return None
found = []
for s in _strings(message):
for raw in _URL.findall(s.replace("&", "&")):
u = _unwrapped(raw.rstrip(".,"))
host = (urlsplit(u).hostname or "").lower() if u else ""
if u and host in (HOST, "www." + HOST) and len(urlsplit(u).path) > 1 and not any(x in u.lower() for x in _NOT_IT) and u not in found:
found.append(u) # a page on docsend.com itself: not its picture server, not its front page
found.sort(key=lambda u: 0 if re.search(r"verif|confirm|auth|token|redirect", u, re.I) else 1)
return found[0] if found else None
Conditions 1 and 2 are here. The domain test is exact or a true subdomain, so docsend.com.evil.example fails. Condition 1 is weaker than it looks: the domain is taken after the first "@" in the From text, so a display name such as "help@docsend.com" <x@attacker.example> passes, and no proof of the sender (no authentication result) is checked at all. Condition 2 still holds for such a message, so the most it can do is send the browser to an address on docsend.com of the attacker's choosing. Condition 3 is in the loop that waits for the mail, which skips any message with no readable time, and any stamped more than ten seconds before the run began (the mail service's clock and the machine's are not the same clock). Condition 4 is in the conversation: the viewer is started only from a DocSend link in the owner's own message, never from one inside mail, a file or a page.
Two things the browsing agent is told not to do, and the program stops when it reports meeting them: accept an agreement (some links ask for a confidentiality agreement first, which is a contract the owner makes), or try a passcode. These are instructions to another company's model, not checks in code; a browsing agent that ignored them could accept an agreement, and nothing in the program would prevent it. The sender is told who looked, by address, as if the owner had opened the link, and the owner is told in the reply that their address was given.
A well-stated exception names the rule it departs from and says the rule stands; lists every condition, each checkable in code, and says how strong each check really is; says who reads the secret (code), where it goes (one browser) and where it never goes (the model, the log); says what it unlocks and what it will not do, and which of those limits code enforces; and sits in the module's header, where a reader meets it before the code.
A link that hides its destination
The first real verification message defeated condition 2. DocSend's emails do not link to docsend.com. Every link goes through its mail provider's click counter, an address on the provider's own domain with the real address written, encoded, inside it. A rule that accepts only links pointing at docsend.com rejected all of them. From odysseus/deckview.py:
def _unwrapped(url: str) -> str | None:
parts = urlsplit(url)
host = (parts.hostname or "").lower()
if host == HOST or host.endswith("." + HOST):
return url
for piece in parts.path.split("/"):
inner = unquote(piece)
inner = inner if inner.startswith("https://") else "https://" + inner
inside = (urlsplit(inner).hostname or "").lower()
if "%" in piece and (inside == HOST or inside.endswith("." + HOST)):
return inner
return None
The inner address is taken out and used directly. The browser is still only given an address on docsend.com, and the counter, which could send the browser anywhere, is never visited. A counter whose inner address leads elsewhere is refused. Relaxing condition 2 to "any link in a DocSend message" would have been easier, and would have let the counter send the browser anywhere.
10.8Opening an address somebody typed
Many decks arrive as a link to a PDF or to a shared Drive, Slides or Dropbox file. Code fetches those. That makes the program, for the first time, connect to an address that is not in its settings.
- Server-side request forgery (SSRF)
- Making a server fetch an address of the attacker's choosing, so that the request comes from inside: from the machine itself or its private network, which the attacker cannot reach directly. Classic targets are the machine's own administration pages and a cloud provider's page of credentials at a fixed private address.
On a cloud machine a program can usually reach a metadata address that hands out the machine's own credentials to anyone asking from inside. Send the assistant a link to it, and the answer comes back in the reply.
Check 2 is the subtle one. The naive version looks the name up, sees a public address, then connects, and the connection looks the name up again. An attacker who controls the name's answers can give a public address to the check and a private one to the connection. This is a race between the time of checking and the time of use. The program closes it by doing the check inside the resolver that the connection itself uses. From odysseus/links.py:
def _public(ip: str) -> bool:
try:
return ipaddress.ip_address(ip.split("%")[0]).is_global
except ValueError:
return False
class PublicOnly(AbstractResolver):
"""Resolves a name and keeps only public addresses. Used for the connection itself, so the check cannot be raced."""
async def resolve(self, host: str, port: int = 0, family: int = socket.AF_INET) -> list[dict[str, Any]]:
found = [a for a in await self._inner.resolve(host, port, family) if self._allow(str(a["host"]))]
if not found:
self.refused = True # the library wraps this error and loses its words, so the refusal is kept here
raise OSError(f"{host} is not a public address")
return found
is_global rejects loopback, private ranges, link-local addresses (including the cloud metadata address 169.254.169.254) and unparseable text. A literal address in the link is checked before connecting; a name is checked when resolved. Redirects are not followed by the library: each one is taken by hand and checked like the first address, so a public page cannot send the program inwards.
The remaining two checks are in the reading loop of Fetcher._fetch. The size is counted as bytes arrive, not taken from the server's stated length, which may lie. And the file is judged a PDF by finding %PDF in its first kilobyte. A shared link that is not really shared returns a sign-in page with a 200 status and a plausible name; judged by its first bytes, it is reported as "not a PDF but a web page; it may need a sign-in".
One more rule sits above all four: only a link in the owner's own typed message is fetched. A link inside mail, a file or a web page never is.
Worked example: three links
- The owner sends
https://drive.google.com/file/d/<id>/viewwith no message.targetrewrites it to Drive's public download address for that file. The fetch passes https; Drive's name resolves to public addresses; a redirect to Drive's content host is checked and followed; the body begins%PDF; it is under 20 MB. The file is read exactly as if it had been sent. (This path is traced through the code; a real Drive link has not been tried.) - The owner pastes
https://169.254.169.254/latest/meta-data.pdf, perhaps copied from a hostile message. The address is a literal;_checkfinds it is not global and refuses before any connection: "the link leads to a private address, which I do not open". - A page at a public address answers with a redirect to
https://10.0.0.5/secret.pdf. The redirect is taken by hand, checked like the first address, and refused as private. (A redirect to anhttpaddress would be refused one step earlier, as not secure.) The test does the same with a server run inside it, over http, which the test permits so that the private-address check is reached.
The same checks elsewhere
Connecting a server from the chat (/connect with an address) requires https and an address whose name resolves only to public addresses. public_host in odysseus/connect.py makes that lookup before the session opens, and the protocol library's client then looks the name up again, so this check, unlike the link fetcher's, can in principle be raced: the two lookups are moments apart. The wider gap is closed: the check is made every time a session to such a server is opened, not only when it is connected, so a name that is later pointed at a private address is refused from then on (_checked in odysseus/mcpapp.py). A reading of the code found it had been made only once, at connecting. Pinning the connection to the address that was checked, as the link fetcher does, is left as an exercise. The sign-in then follows wherever the server says it lives, and that second address is not checked. One more fault was found in use: the chat app made a preview of a sign-in link, meaning its servers fetched it. The bot's messages now carry no link previews.
10.9The theory
This chapter's claims are about authority. In the terms of the model they bound the effects of calls in A(T), which Property 2 leaves open, and add one argument about time.
Credentials outside the context. By Definition 1 every tool input is drawn from M(c). If no credential is part of any item of the history, a model can put one into a call only by guessing it, whatever it was told. The settings module keeps vendor keys and token files on code paths that append nothing to the history; a property of the code's structure, stated in config.py and not tested as a whole. Where outside material can carry a credential, a code or reset link in mail, hide_secrets removes it before the item is appended: a pattern, with the misses the chapter names, and not applied to files.
A token is a row of the access matrix. Write Σ for the permissions a token carries and Eff(Σ) for the effects the service will perform with it. Whatever the model does, calls made with the token have effects in Eff(Σ). The gate decides which calls happen unasked; the scope decides which can happen at all. Least privilege is Σ = Σneed, the permissions the program's tools use.
For X and DocSend every offered tool counts as a read, so G(τ, x, T) = allow unless x carries a recognised detail. By Property 2 the effects a taken-over model can cause there unasked are those of the tools not hidden by name, under Σgranted. The gate is sound there for change and destroy if and only if every such call only reads. It is not sound for send in the strict sense of Definition 2, whatever the scope: every call's inputs reach the service, which is why a call carrying a recognised detail asks.
Argument and hypothesis. The program controls one link of the chain C → Σreq → Σgranted, where C is the configured list: pin_scope replaces the link's scope, so Σreq = C whenever C is set. It does not control the grant. A service that grants more than was asked breaks the condition silently. One that later offers a writing tool not hidden by name breaks it too: the changed listing is noticed between runs (mcpapp.pin_listing), written to the journal and counted as outside material read, but the new tool still runs unasked. The case note is a composition failure: a library and a protocol, each correct, made Σreq the server's whole advertised set.
For X this was checked once, from the returned token: seven reading permissions and no others. That measures one grant, not the service.
Checking an address at the moment of use. A server-side request forgery succeeds when a check and the use it guards read different values. Model a fetch as connections to peer addresses p₁, …, pₙ, one per hop, n ≤ 6.
Every pᵢ is either a literal in the address, refused before connecting unless global, or an element of the list PublicOnly.resolve returns, which holds only global addresses. The check filters the very list the connection uses, so a name that answers differently from one lookup to the next gains nothing: there is one read, not two. Redirects re-enter the loop and are checked like the first address.
Hypotheses. The client library takes every peer address from the resolver it is given (no proxy from the environment, no name cache); is_global matches what the operator means by inside; and no global address leads inward. The last fails for a machine with a public address of its own, where a service listening on every interface is reached with the check's approval.
/connect lacks this property: public_host and the protocol library each look the name up, so check and use are two reads. Checking at every opening shrinks the window from the life of a connection to one opening and does not close it, and the address the sign-in later follows is not checked. The renewal token has a property of the first kind: code posts it only to an https address on the site the owner connected, whatever a description says. So is the DocSend exception: code reads the link and hands it only to a browser, only for an address on docsend.com; against a forger the bound rests on conditions 2 to 4.
| Claim in this chapter | Kind | How it is known |
|---|---|---|
| No stored credential enters a model's context | Property, by construction | Stated in config.py; not tested as a whole |
| The sign-in link asks for exactly the configured permissions | Property | pin_scope; tests/test_attio.py |
| X's token carries only reading permissions | Measurement | One grant, read once |
| A fetched link reaches only global addresses | Property, under three hypotheses | Argued from links.py; tests/test_links.py |
| A server connected by address is public when used | Not guaranteed | Two lookups; checked at each opening |
| The verification procedure reads a real document | Measurement | 7 good runs of 8 |
10.10How to test it
Tests here must show a boundary from outside: what the link asks for, which address is refused, which message is ignored.
tests/test_attio.py: the token file round-trips and says whether anyone is signed in; a wide scope in a sign-in link is replaced, not added to, while the state, proof-key challenge and return address survive.tests/test_connect.py: a program that registered before comes back to the same port; an http address, a private address and a taken name are refused before anything is opened; a sign-in nobody approves saves nothing and does not restart; only the owner's typed command connects.tests/test_links.py: private, loopback, link-local and metadata addresses are not public; a name resolving to this machine is refused when connecting; a PDF is fetched through a redirect, while a web page, a large file, a forbidden page and a redirect to a private address are each refused with a reason; a stranger's link is not fetched.tests/test_deckview.py: the verification link is taken only from DocSend and only when it points at DocSend; a look-alike sender and a link elsewhere are refused; the link is found inside a click counter shaped like the real one, the counter itself is never returned, and a counter leading elsewhere is refused.
The port collision, the click counter and the over-wide scope were all found live; no stand-in written before the real service was seen could have shown them.
Verified live: the sign-in to the firm's database ran once and its token was reused; X's approval page listed only reading and its token carried only the seven reading permissions; DocSend was signed in to with reading permissions only; nine connects and disconnects in a row from the chat each ended with the assistant back; a public PDF was fetched from a real site and three dead links were refused with the site's own answer; the verification procedure read a real DocSend document, with seven good runs of eight, four with verification, the one failure coinciding with the browser service's credit running out.
Verified by unit tests: everything in the list above.
Not tested: token renewal and withdrawal; a sign-in for a server nobody here has seen; a server that mislabels its tools; any real Google Drive, Slides or Dropbox link; a link that is not shared; a real page asking for an agreement or a passcode; signing in from a phone, which by design cannot complete. The browser vendor holds the website sign-ins and the connector service holds mail access; how well either protects them is their claim, not something checked here.
Known weaknesses in the code. The verification procedure's sender check reads an unauthenticated From line; its refusal of agreements and passcodes is an instruction to another company's model; most services' sign-ins ask for whatever the server advertises; and the check that a server connected by address is public is made by a lookup separate from the connection's own.
10.11Where this sits in the literature
Asking only for the permissions a program uses is least privilege, one of the principles [Saltzer and Schroeder 1975] set out for any protection mechanism. Fail-safe defaults, another, is what the fetcher follows when an address it cannot parse counts as not public. [Lampson 1971] gave the vocabulary for stating the result: an access matrix of subjects, objects and rights, whose rows are capability lists. A token is one such row, restricted to one service, and the chapter's table of credentials adds a column the matrix does not have: who else holds a copy.
[Hardy 1988] described a privileged program tricked into misusing its own authority for a caller, and an agent holding its owner's mail and file credentials is such a deputy by construction. Narrow scopes shrink the authority the deputy can misuse; they do not tell it whose request it is serving. That second half is the gate's work (Chapter 8), and this chapter only bounds what is at stake when the gate allows a call.
The sign-in follows [RFC 6749], the authorisation code grant with access and refresh tokens and scopes, and depends on [RFC 7636], which binds the code to the client that asked for it. The chapter's account of why a stolen code is useless is that binding, and a program with no client secret relies on it entirely. [RFC 9700] gathers current practice into a checklist that includes redirect matching, the proof key and token lifetime. The program's evidence on that list is thin. The return address is matched by the service, and the program only keeps it stable; the state value is handed to the library and its use was not tested; and token lifetime was the source of the renewal fault, found in use and not by checking against the list. Here the published practice is stronger than this program: it is written from many deployments' failures, where this chapter's repairs were found one at a time. [RFC 6819] catalogues threats to OAuth deployments and is the reference for an agent holding long-lived refresh tokens. This program keeps them in the clear in its data folder and warns when the folder is synced; a threat model in that style would ask who else can read the folder, which the chapter does not answer.
[OWASP 2021] lists the usual defences against request forgery: allow-lists, blocking internal ranges and disabling redirects. The fetcher blocks internal ranges at the moment of connection and, instead of disabling redirects, takes each one by hand and checks it. It has no allow-list for links the owner types, since any public site may host a deck. The attachment fetch reads from the mail connector's storage and could have one; it uses the same fetcher, with none.
[MCP security practices] names the attacks particular to a tool-protocol client, among them token passthrough, request forgery during sign-in discovery and scope minimisation. The program minimises scope only where permissions are configured, and leaves the address the sign-in follows unchecked, which is the forgery that document describes. On both points the published guidance asks for more than this program does.
What is not settled is least privilege for a program whose needs are chosen at run time. The principle assumes the program knows what it will use. An agent's needs are decided by a model from what it is asked. A scope wide enough for any request is the over-wide grant of the case note; a scope per task means a consent page per task, which moves the approval fatigue of Chapter 8 onto the service's pages. None of the works cited here says how to grant for that.
- Every credential has a home: vendor keys in the environment, service tokens in one file each in the data folder, which the program warns about if it is synced, mail access at the connector, website sign-ins in the browser vendor's profile. None is ever put where the model reads.
- Signing in as the owner uses the authorisation code flow with a proof key and a return to
127.0.0.1; tokens never pass through the browser or the chat. - Ask only for the permissions the program uses, and verify on the wire: a library may widen the request, so where permissions are configured the link is rewritten and the returned token checked. Where none are configured, the service chooses and the owner is told to read its page.
- Choose a free return port for a first sign-in, and reuse the registered one ever after, because the service remembers it.
- For websites, the owner signs in by hand in a live browser; no password passes through the program, at the price of a vendor holding the sign-ins.
- An exception to a safety rule is stated with the rule, every checked condition, who reads the secret, where it goes, and what it unlocks.
- A program that opens addresses somebody typed needs four checks: https only, public addresses checked at the moment of connecting, limits counted while reading, and the file judged by its first bytes.
Review
- Explain what an attacker who sees the one-time code in step 5 of the sign-in can and cannot do, and which part of the exchange decides that.
- Why is the return port remembered per service rather than chosen afresh each time? What error would the owner see if it were not?
- Write a test for
Fetcherin which a name resolves to a public address on the first lookup and to127.0.0.1on the second. Show that the program refuses, and explain why a check before connecting would not. - The waiting loop in
deckview.pyskips a message with no readable time stamp, and one stamped more than ten seconds before the run began. Why ten seconds and not zero? What could go wrong if undated messages were accepted, and which of the four conditions would still hold? - Change
/connectso that the server's address is checked by the same lookup the session uses, aslinks.pydoes. What has to change in how the session is opened? - Rewrite a second exception in this program, or one you design, in the form this chapter gives: rule, conditions, reader, destination, what it unlocks, what it will not do.
Analysis
- Prove the property "a fetched link connects only to global addresses" from
links.py, stating each hypothesis about the client library where you use it. Then, in a simulated deployment you describe, give a link the check accepts that still reaches a service on the program's own machine or network. Say whether your example refutes the property or only its purpose, and write the test that would catch it. /connectchecks a name with one lookup and the session then makes another. Model a name server that answers each lookup independently, with a private address with probability p and a public one otherwise, and no caching anywhere. (a) For one opening, what is the probability that the check passes and the session reaches a private address, and which p maximises it? (b) The check is repeated at each opening. With that p, what is the probability that at least one of 10 openings reaches a private address? (c) What is the answer to (a) for a server that answers the first lookup of each opening publicly and the second privately? (d) What are the answers to (a) and (c) for the link fetcher, and which step of the argument gives them?- State, as a derivation from Property 2, the condition under which the gate is sound for change and destroy at a connection marked as one that can only read, and say why no scope makes it sound for send. For each of the following, say whether the condition fails, whether the program could detect it at sign-in or only at each call, and the cheapest detection you can design: (a) the service grants a writing permission that was not asked for; (b) the service later adds a writing tool not on the hidden list (the program already notices a changed listing; say what it then does and whether that is enough); (c) a permission named for reading whose calls also notify the author of what was read.
- The exception for DocSend claims that, whatever the model does, the verification link is handed only to a browser and only for an address on docsend.com. Prove this from
verification_linkand_unwrapped. Then give two hypotheses about the world under which the exception unlocks more than "one document, for viewing" although every checked condition holds, and say for each whether code in this program could close it.
Design
- The assistant is to run on one rented server for a household of three invented people at
larch.example, each with their own mail, chat and tokens. Design where each credential lives and who can read it, how a sign-in returns to the server, and what one person's conversation, taken over by planted text, can do with another person's credentials. State what is guaranteed by code and what is given up. - A new requirement: when the owner asks what a link inside an email says, the program should fetch it. Today only links the owner types are fetched. Design the change. Say which of the four checks still hold, what effect class under Definition 2 a fetch of an address chosen by a stranger has (an address can carry data in its path and query), how the fingerprint check of Chapter 9 should apply to it, and what is guaranteed and what is given up.
Reading
- Read [RFC 9700]. In about four hundred words: what it claims; why it matters for this chapter's decisions to rely on the sign-in library for the proof key and the state value, and to pin the scope by rewriting the link; where you were not convinced that its advice fits a program running on its owner's laptop; and what you would check or build next in this program.
- Read [OWASP 2021]. In about four hundred words: what it claims; why it matters for this chapter's decisions to check addresses inside the resolver the connection uses and to take redirects by hand instead of refusing them; where you were not convinced; and what you would measure or build next, including whether the attachment fetch should have an allow-list.
Open
- (Hard, open.) Design a return address for a program running on a server, so that the owner can approve a sign-in from a phone. What new credential does your design create, who could steal it, and how would you test it without a real service?
- Design a scheme in which an agent holds, at each moment, only the permissions the current task has used or been approved to use, at services that grant permissions only at sign-in. Progress would be a property of the form "no token held at the end of a task carries a permission the task did not use", argued from code, together with a measurement of the consent pages per week the scheme costs the owner compared with one sign-in per service.