Metadata-Version: 2.5
Name: gatehouse-issuer
Version: 0.1.0
Summary: A token issuer for mcp-gatehouse and any JWT validator: short-lived, narrowly scoped ES256 access tokens, validated offline through a public JWKS.
Project-URL: Repository, https://github.com/nickgeorgeseo/gatehouse-issuer
Project-URL: Issues, https://github.com/nickgeorgeseo/gatehouse-issuer/issues
Author-email: Nick George <nick@nickgeorgeai.com>
License-Expression: MIT
License-File: LICENSE
Keywords: ai-agents,authorization,jwks,jwt,mcp,oauth,token-exchange
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: pyjwt[crypto]>=2.10.1
Provides-Extra: dev
Requires-Dist: anyio>=4; extra == 'dev'
Requires-Dist: httpx>=0.27; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff==0.9.6; extra == 'dev'
Provides-Extra: gatehouse
Requires-Dist: mcp-gatehouse<0.7,>=0.6; extra == 'gatehouse'
Provides-Extra: gcp-kms
Requires-Dist: google-auth[requests]>=2.29; extra == 'gcp-kms'
Provides-Extra: postgres
Requires-Dist: psycopg-pool>=3.2; extra == 'postgres'
Requires-Dist: psycopg[binary]>=3.2.1; extra == 'postgres'
Provides-Extra: server
Requires-Dist: anyio>=4.1; extra == 'server'
Requires-Dist: pyyaml>=6.0.1; extra == 'server'
Requires-Dist: starlette>=0.40; extra == 'server'
Requires-Dist: uvicorn>=0.31.1; extra == 'server'
Description-Content-Type: text/markdown

# gatehouse-issuer

[![CI](https://github.com/nickgeorgeseo/gatehouse-issuer/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/nickgeorgeseo/gatehouse-issuer/actions/workflows/ci.yml)

**gatehouse-issuer hands out tokens.** A token is a pass. It says who
someone is and what they're allowed to do, and it stops working after a
few minutes.

Your apps and MCP servers check each pass themselves, without asking the
issuer. They can check a pass, but none of them can make one. Only the
issuer holds the key that makes them.

It's built for [mcp-gatehouse](https://github.com/nickgeorgeseo/mcp-gatehouse),
which runs inside your MCP server and decides each call: is this order the
caller's, and may it be cancelled? mcp-gatehouse reads who the caller is
from their pass. gatehouse-issuer is where that pass comes from. It also
works with anything else that checks JWTs (the standard kind of signed
token).

<picture>
  <source media="(prefers-reduced-motion: reduce)" srcset="https://raw.githubusercontent.com/nickgeorgeseo/gatehouse-issuer/main/docs/social/architecture.png">
  <img src="https://raw.githubusercontent.com/nickgeorgeseo/gatehouse-issuer/main/docs/social/simple.gif" alt="How gatehouse-issuer works: alice signs in to your app, whose token is good only at your agent backend. The agent backend trades it at the issuer for a token of its own: good only at one MCP server, limited to what alice and the agent both may do, and gone in 5 minutes. The MCP server checks it offline. The steps below walk through it.">
</picture>

## Why you'd want it

An AI agent working for a user needs to call tools. The easy way is to
hand the agent the user's own pass. But then one bad instruction hidden in
an email or a web page (a "prompt injection") can make the agent do
anything the user can do.

gatehouse-issuer gives the agent a pass of its own instead. That pass:

- works at one MCP server, and nowhere else;
- allows only what the user and the agent are **both** allowed to do;
- stops working after 5 minutes.

For risky actions, like cancelling an order, you can also require the
user's own say-so. The agent can't give it for them.

## How it works

1. **The user signs in to your app** with the sign-in you already use:
   Firebase, Auth0, Google, Keycloak, or any other OpenID Connect provider.
   Your app trades that sign-in at the issuer for a pass. The pass works
   only at your agent backend, and lasts 5 minutes. Your app also gets a
   refresh token, for getting the next pass, and keeps it to itself.
2. **Your app hands the agent backend that pass**, along with the task.
3. **The agent backend trades it** at the issuer for a pass of its own. It
   proves who it is by signing the request with its own private key.
4. **The agent calls the MCP server** with its own pass. The MCP server
   checks it with the issuer's public keys, without calling the issuer.

The user's pass is no use at the MCP server. It's turned away there,
because it was made for the agent backend.

There are two more ways to get a pass:

- **An MCP client signs the user in by itself.** Claude Code, Cursor and
  other MCP clients can do this. The user signs in, then sees a page asking
  whether to let the client in. The client's pass holds only what the user
  agreed to.
- **One of your services calls another.** It proves who it is with its own
  key, and gets a pass for itself, not for a user.

New words are explained in [Words used here](#words-used-here).

## Install

```bash
pip install "gatehouse-issuer[server]"      # the issuer
pip install gatehouse-issuer                # only the checker, for any Python service
pip install "gatehouse-issuer[gatehouse]"   # the checker, plus the mcp-gatehouse adapter
pip install "gatehouse-issuer[server,postgres,gcp-kms]"   # the issuer, with Postgres and Cloud KMS
```

It needs Python 3.10 or later.

For JavaScript or TypeScript, the checker is on npm:
`npm install gatehouse-issuer`. It makes the same checks in the same
order, gives the same reasons, and has no dependencies. See [`js/`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/js).

## Five-minute quickstart

You'll run the issuer on your computer, sign in a test user called alice,
check her pass, and put the issuer in front of an MCP server. Dev mode
uses a pretend sign-in provider, so there's nothing to sign up for.

**1. Make a config file.**

```bash
gatehouse-issuer init
```

This writes `issuer.yaml`. It sets up an issuer at `http://localhost:8000`,
the pretend sign-in provider, one app (`web`), one MCP server
(`http://localhost:9000/mcp`) and one user, alice. It never writes over a
file that's already there.

**2. Start the issuer.**

```bash
gatehouse-issuer serve --dev
```

It makes a signing key and keeps its data in `.gatehouse-issuer/dev/`.
Nothing in there is used outside dev mode. It prints one line for every
pass it hands out. It keeps running, so open a second terminal in the same
folder for the next steps.

Is port 8000 taken? Pick another port and use it everywhere you see 8000.
`gatehouse-issuer init --port 8765` writes it into the config, and `serve`
takes the same `--port`. The two must match, because the checkers fetch
the issuer's keys from the address in the config. `init` won't write over
your first `issuer.yaml`, so delete that first.

Every command reads the config you name with `--config`. Without it, a
command reads the file named in `$GATEHOUSE_ISSUER_CONFIG`, and without
that, `issuer.yaml`.

**3. Sign alice in.**

```bash
export ACCESS_TOKEN=$(gatehouse-issuer dev token alice@dev --dev)
```

The pretend provider signs alice in, and the issuer trades that for a
pass, the same way it would for your app. The command prints the pass and
nothing else. If the issuer isn't running, or something else is using its
port, it tells you.

<details>
<summary>What these commands did</summary>

`init` wrote this `issuer.yaml`:

```yaml
issuer: http://localhost:8000
upstream:
  dev: true                    # the fake IdP; only runs with --dev
audiences:
  - http://localhost:9000/mcp  # your MCP server
clients:
  web:
    type: public
    audiences: [http://localhost:9000/mcp]
groups:
  buyers: [buyer]
permission_sets:
  buyer: ["order.own.read", "-order.own.read.cost", "order.own.cancel"]
members:
  - id: alice
    sub_from_upstream: alice@dev
    groups: [buyers]
```

alice is in the group `buyers`. That group gets the permission set
`buyer`: read her own orders, but not what they cost, and cancel her own
orders.

`dev token` asked the pretend provider for an ID token, its proof that
alice signed in. (`dev id-token` prints one.) Then it traded that ID token
at the issuer's `/token`. This curl does the same:

```bash
ID_TOKEN=$(gatehouse-issuer dev id-token alice@dev --dev)
curl -s localhost:8000/token \
  -d grant_type=urn:ietf:params:oauth:grant-type:token-exchange \
  -d subject_token_type=urn:ietf:params:oauth:token-type:id_token \
  -d client_id=web -d resource=http://localhost:9000/mcp \
  --data-urlencode "subject_token=$ID_TOKEN"
```

The issuer answers with two tokens, and `dev token` keeps the access
token, the pass:

```json
{"access_token": "eyJ0eXAiOiJhdCtqd3Qi…", "token_type": "Bearer", "expires_in": 300,
 "issued_token_type": "urn:ietf:params:oauth:token-type:access_token", "refresh_token": "gir_…"}
```


The sign-in is real. The issuer keeps the session and the refresh token,
and prints its line. If your config has more than one app or MCP server,
`--client` and `--resource` pick which one.

</details>

**4. Check the pass.** Any service can do this with just the issuer's
address. It needs no secrets. Save this as `validate.py` and run
`python validate.py` in the same terminal:

```python
import os

from gatehouse_issuer import TokenValidator

validator = TokenValidator("http://localhost:8000", "http://localhost:9000/mcp", dev=True)
token = validator.verify(os.environ["ACCESS_TOKEN"])
print(token.subject, token.client_id, token.perms.allows("order.own.cancel"))   # alice web True
```


`dev=True` is there because a dev issuer marks every pass `"dev": true`,
and checkers turn those away unless they're in dev mode too.

The pass lasts 5 minutes. After that, `verify` raises
`InvalidToken("expired")`. Run step 3 again to get a new one.

**5. Put it in front of an MCP server.** First run
`pip install "gatehouse-issuer[gatehouse]"`.
Then save this as `server.py`. The orders stand in for your app's own
records:

```python
from dataclasses import dataclass
from typing import Annotated

from mcp.server.mcpserver import MCPServer
from mcp_gatehouse import AccessTier, AuditLog, ConditionalWrite, Gatehouse, Load, Policy, terminal_approver

from gatehouse_issuer.gatehouse import IssuerTokenVerifier, permits, redact


@dataclass
class Order:      # your app's own record
    id: str
    owner: str    # the member who owns it: the "own" in order.own.read
    status: str
    total: int
    cost: int     # what it cost you: buyers have -order.own.read.cost


ORDERS = {"4417": Order("4417", "alice", "open", 812, 530), "4420": Order("4420", "dana", "open", 99, 61)}


def load_order(order_id: str) -> Order | None:
    return ORDERS.get(order_id)


verifier = IssuerTokenVerifier("http://localhost:8000", "http://localhost:9000/mcp", dev=True)
mcp = MCPServer("orders", token_verifier=verifier, auth=verifier.auth_settings())
gatehouse = Gatehouse(mcp, policy=Policy(approver=terminal_approver),
                      audit=AuditLog(path="audit.jsonl"), consistency=ConditionalWrite())


@gatehouse.tool(tier=AccessTier.READ, authorize=permits("order", "read", owner="owner"))
def lookup_order(order_id: str, order: Annotated[Order, Load(load_order)]) -> dict:
    """Look up one of your orders."""
    return redact(order, None, "order", "read", owner="owner")   # drops cost


@gatehouse.tool(tier=AccessTier.DESTRUCTIVE, authorize=permits("order", "cancel", owner="owner"))
def cancel_order(order_id: str, order: Annotated[Order, Load(load_order)]) -> str:
    """Cancel one of your orders, once a person at this server's terminal says yes."""
    order.status = "cancelled"
    return f"{order.id} cancelled"


mcp.run(transport="streamable-http", port=9000)
```

Here's what each part does:

- `IssuerTokenVerifier` checks the pass on every call.
- `permits("order", "read", owner="owner")` lets a call through only if
  the pass allows reading this order. For `order.own.read`, the order's
  `owner` must be the caller.
- `redact(...)` takes out the fields the caller may not see, like `cost`.
- `cancel_order` is marked `DESTRUCTIVE`, so a person at the server's
  terminal must say yes before it runs.

Run it in a third terminal, with `python server.py`. Then, in the terminal
with `ACCESS_TOKEN`, save this as `call.py`. It calls the server as alice,
with her pass from step 3:

```python
import asyncio
import os

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

CALLS = [("lookup_order", "4417"), ("lookup_order", "4420"), ("cancel_order", "4420")]


async def main() -> None:
    headers = {"Authorization": f"Bearer {os.environ['ACCESS_TOKEN']}"}   # alice's token, from step 3
    async with httpx2.AsyncClient(headers=headers) as http:
        async with Client(streamable_http_client("http://localhost:9000/mcp", http_client=http)) as client:
            for tool, order_id in CALLS:
                result = await client.call_tool(tool, {"order_id": order_id})
                print(f"{tool} {order_id}:", result.content[0].text)


asyncio.run(main())
```

`python call.py` prints:

```
lookup_order 4417: {
  "id": "4417",
  "owner": "alice",
  "status": "open",
  "total": 812
}
lookup_order 4420: Error executing tool lookup_order: 'lookup_order' is not permitted for this caller.
cancel_order 4420: Error executing tool cancel_order: 'cancel_order' is not permitted for this caller.
```

alice can read her own order, but not its `cost`. Order 4420 is dana's, so
alice can't read it or cancel it. The caller is told only that it isn't
permitted. The server's `audit.jsonl` says who asked, through which app,
and why the answer was no:

```json
{"tool": "cancel_order", "outcome": "denied", "reason": "policy: has order.own.cancel; order 4420 belongs to someone else",
 "caller": {"client_id": "web", "subject": "alice", "issuer": "http://localhost:8000", "scopes": []}, …}
```

Now change `CALLS` to `[("cancel_order", "4417")]` and run `call.py`
again. alice may cancel her own order, so the server's terminal asks you
first. Say yes, and `call.py` prints `cancel_order 4417: 4417 cancelled`.
If nobody answers, mcp-gatehouse refuses it. If a call says the pass has
expired, run step 3 again.

## See an agent do it

In the quickstart, alice calls the server herself.
[`examples/order_desk_http`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/examples/order_desk_http) adds an agent
backend that works for her, in front of mcp-gatehouse's demo order desk.
Run it from a clone of this repo, in its top folder:

```bash
pip install -e ".[server,gatehouse]"
python -m examples.order_desk_http.run --approve yes
```

```
alice's own token, sent straight to the order desk: HTTP 401 (it was minted for the agent)

The order desk's audit log (mcp-gatehouse), one line per call:
  list_orders   ok      for 'alice' via 'support-bot'
  lookup_order  ok      for 'alice' via 'support-bot'
  add_note      ok      for 'alice' via 'support-bot'
  lookup_order  denied  for 'alice' via 'support-bot'  policy: has order.own.read; order 4420 belongs to someone else
  cancel_order  denied  for 'alice' via 'support-bot'  policy: no grant for order.own.cancel
  cancel_order  denied  for 'alice' via 'support-bot'  policy: token is pinned to order 4418; this is order 4417
  lookup_order  denied  for 'alice' via 'support-bot'  policy: no grant for order.own.read
  cancel_order  ok      for 'alice' via 'support-bot'

The issuer's audit log:
  token_issued    sub='alice' client='web'
  token_issued    sub='alice' client='web' pinned=[{"type": "order", "identifier": "4418", "actions": ["cancel"]}]
  token_exchanged sub='alice' client='support-bot' act='agent:support-bot' for client 'web' cut=["order.*.cancel"] (needs the user's pin)
  token_exchanged sub='alice' client='support-bot' act='agent:support-bot' for client 'web' pinned by agent=[{"type": "order", "identifier": "4417", "actions": ["cancel"]}] cut=["order.*.cancel"] (needs the user's pin)
  token_exchanged sub='alice' client='support-bot' act='agent:support-bot' for client 'web' pinned by user=[{"type": "order", "identifier": "4418", "actions": ["cancel"]}]
```


Reading it from the top:

- alice's own pass is turned away at the order desk with a 401, because it
  was made for the agent.
- The order desk's log says "for alice via support-bot". The issuer's line
  for the same pass also says support-bot acted for alice's session in the
  `web` app. The two logs share the pass's `jti` and `sid`, so you can
  match them up.
- The first `cancel_order` uses a pass the agent pinned to order 4417
  itself, as a tricked model might. It gets no cancel at all.
- The last three calls use the pass alice's app pinned to order 4418.
  Cancelling 4417 is refused, reading is refused (the pin allows only
  cancelling), and cancelling 4418 goes through.

## Agents

An agent backend gets the user's pass, made for the agent's own address.
It trades that pass for a new one for each task:

```python
from gatehouse_issuer.client import TokenClient, load_private_key

issuer = TokenClient("https://auth.example.com", client_id="support-bot",
                     private_key=load_private_key("support-bot.pem"))
token = issuer.exchange_for_agent(user_token, resource="https://mcp.example.com")
```

The agent's pass:

- works only at the MCP server it asked for (`aud`);
- names the agent, in `client_id` and in `act: {"sub": "agent:support-bot"}`;
- allows what the user may do, cut down to the agent's `ceiling`, and cut
  down again by any pin (below);
- belongs to the user's sign-in session, so once you revoke the user, the
  agent's next trade is refused;
- stops working when the user's pass does, or after 5 minutes, whichever
  comes first. It comes with no refresh token.

Before the issuer trades, it checks that:

- the request is signed with the agent's key;
- the user's pass is real, and was made for this agent;
- the user's pass doesn't already name an agent, so agents can't chain;
- the user's session is still open, and the user is still a member;
- the MCP server asked for is on the agent's `resources` list.

**Pins, and who sets them.** A pin narrows a pass to named records and
actions, like "cancel order 4418, and nothing else". It's written as
`authorization_details`:
`[{"type": "order", "identifier": "4418", "actions": ["cancel"]}]`. That
pin cuts the pass down to `order.*.cancel`, and `permits()` refuses every
order except 4418.

An agent can pin its own pass. That limits the harm if the pass leaks. But
when a model drives the agent, a pin the agent picks is whatever the model
decided, and a tricked model picks the wrong record. So for the actions
that matter, the user sets the pin, through your app:

```python
# In your app, when the user picks "cancel order 4418":
front_end = TokenClient("https://auth.example.com", client_id="web")
picked = front_end.refresh(refresh_token, resource="https://agent.example.com",
                           authorization_details=[{"type": "order", "identifier": "4418", "actions": ["cancel"]}])
# Keep picked.refresh_token. Hand picked.access_token to the agent, with the task.
```

Only your app holds the refresh token, so the agent can't make the user's
pin itself. The pin is on that one pass, not on the whole session. The
agent's pass keeps the pin. The agent may narrow it, but never widen it.

In the agent's config, `needs_user_pin` lists what the agent may do only
when the user pinned the pass:

```yaml
agents:
  support-bot:
    ceiling: ["order.own.read", "order.own.note", "order.own.cancel"]
    needs_user_pin: ["order.*.cancel"]   # cut, unless the user pinned the token
```

Without the user's pin, those actions are cut from the agent's pass,
whatever the agent pins itself. So it can still read orders and add
notes, but it can't cancel anything. The issuer's log says who pinned each
pass and what was cut. Cookie mode doesn't pin passes yet.

**The agent's key.** The agent proves who it is with a short JWT it signs
with its own private key (`private_key_jwt`). The issuer holds only the
public key.
`gatehouse-issuer client-key support-bot --out support-bot.pem` makes the
pair, and prints the public key to paste into the config.

**Actions only the user may take.** In a policy,
`permits(..., agents=False)` refuses every agent's pass outright.

## MCP clients sign in directly

Claude Code, Cursor and other MCP clients can sign a user in by
themselves. The MCP spec has the client find the issuer through the MCP
server's metadata, then sign the user in with OAuth (the authorization
code flow, with PKCE). `IssuerTokenVerifier.auth_settings()` already makes
the MCP SDK publish that metadata, pointing at the issuer. Give it the
scopes your server needs:

```python
mcp = MCPServer("orders", token_verifier=verifier, auth=verifier.auth_settings(scopes=["orders:read"]))
```

In the issuer's config, say how users sign in, what each OAuth scope may
allow, and which clients may sign in:

```yaml
upstream:
  oidc: https://login.example.com
  client_id: web-frontend
  login:                                  # /authorize sends users here
    client_id: gatehouse-issuer           # the issuer's own client at the provider
    private_key_file: upstream-login.pem  # private_key_jwt; or client_secret_file
scopes:                                   # a scope is a ceiling on the token's permissions
  orders:read: ["order.own.read"]
  orders:write: ["order.own.note"]
clients:
  desk-cli:
    type: public
    name: Order desk CLI
    audiences: [https://mcp.example.com/mcp]
    scopes: [orders:read, orders:write]
    redirect_uris: [http://127.0.0.1/callback]   # loopback: any port
client_metadata:                          # clients that bring a Client ID Metadata Document
  audiences: [https://mcp.example.com/mcp]       # off until you list one
```

Using Firebase? Then `/authorize` sends users to a sign-in page you host
(`login: {handoff: https://app.example.com/issuer-login.html}`).
[`examples/firebase_login`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/examples/firebase_login) is that page.

What the client's pass holds:

- **A client that isn't yours**, like an MCP client or a partner's app,
  gets the user's permissions cut down to the scopes the user agreed to,
  and to the client's own `ceiling` if it has one. Its pass also names it:
  `act: {"sub": "client:<client_id>"}`. So `permits(..., agents=False)`
  refuses it, just as it refuses an agent. The user sees a page that names
  the client, where it will send them back to, and what its passes could
  do. The answer is remembered for 30 days.
- **Your own app** (`first_party: true`) gets the user's full permissions,
  with no consent page and no `act`, the same as signing in through your
  app.

[`examples/mcp_client_login`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/examples/mcp_client_login) runs it end to
end with the MCP SDK's own OAuth client:

```bash
python -m examples.mcp_client_login.run
```

```
The MCP SDK's client opened /authorize with:
  client_id              desk-cli
  resource               http://127.0.0.1:53320/mcp
  scope                  orders:read
  code_challenge_method  S256

The order desk's audit log (mcp-gatehouse):
  list_orders   ok      for 'alice' via 'desk-cli'
  lookup_order  ok      for 'alice' via 'desk-cli'
  add_note      denied  for 'alice' via 'desk-cli'  policy: no grant for order.own.note
  cancel_order  denied  for 'alice' via 'desk-cli'  policy: no grant for order.own.cancel
```


To check that your MCP server and the issuer agree, run
`gatehouse-issuer check-resource https://mcp.example.com/mcp`. Among
other things, it checks the resource, the issuer, the audience, PKCE, and
that every scope has a ceiling.

## Services calling services

A service that isn't working for a user, like a nightly job, gets a pass
for itself. Give it a key with `gatehouse-issuer client-key billing --out billing.pem`,
and list it in the config as a `type: service` client:

```yaml
clients:
  billing:
    type: service
    audiences: [https://api.example.com]
    groups: [billing]          # what its passes allow
    jwk: {...}                 # the public key client-key printed
```

Then it asks for a pass with its key:

```python
from gatehouse_issuer.client import TokenClient, load_private_key

billing = TokenClient("https://auth.example.com", client_id="billing",
                      private_key=load_private_key("billing.pem"))
token = billing.client_credentials(resource="https://api.example.com")
```

The pass names the service itself as its `sub`, and comes with no refresh
token. [Reference](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/docs/reference.md) lists every setting a service client
takes.

## Permissions

A permission is written `[-]resource.scope.action[.field]`. For example:
`order.own.read` reads your own orders, `-order.own.read.cost` hides what
they cost, and `invoice.org.*` does anything with your org's invoices.

- **Scopes say whose records.** `own` is yours, `org` is your org's, and
  `any` is anyone's. Each one covers the ones inside it:
  `any` covers `org`, and `org` covers `own`. A pass can't know who owns a
  record, so `permits()` looks at the record your loader returned.
- **`*` matches more.** At the end, it matches everything below
  (`order.*` is everything on orders). In the middle, it matches one part.
  With no field, a permission covers every field.
- **A denial always wins.** A permission starting with `-` beats any
  grant, at its scope and every narrower one.
- **A call needs a grant for every field it touches.** Denied fields are
  left out of what `fields_allowed` and `redact` return.
- **One broken permission spoils the pass.** If one pattern doesn't parse,
  the whole pass is refused.

**A resource catalog** lists what permissions may name. Once it lists one
resource, any pattern that names a resource, action or field it doesn't
have is refused when the config loads. So a typo like
`-ordr.own.read.cost` can't quietly deny nothing. `*` still matches
anything. The issuer's own resources (`member`, `session`, `consent`,
`policy`, `key`) are always there:

```yaml
resources:
  order:
    scopes: [own, org, any]      # which apply; a table nobody owns has only any
    owner_field: owner_id        # what decides own, for permits(owner=...)
    org_field: org_id
    actions: [read, create, update, delete, cancel]
    fields: [id, status, total, cost, owner_id, org_id]
```

You don't have to write it by hand. `gatehouse-issuer policy schema app`
reads the tables of a database listed under `schema_sources:` and prints
them as resources. The admin portal does the same, with a preview.

The full rules are in [`spec/permissions.md`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/spec/permissions.md).
[`spec/vectors.json`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/spec/vectors.json) holds the test cases a version
in another language must pass (133 of them).

## Words used here

Two words mean one thing in a permission and another in OAuth: resource
and scope. The rest are this project's own.

| Word | What it means here |
|---|---|
| **token**, or **pass** | a signed JWT that says who someone is and what they may do. It works for a few minutes. |
| **member** | a person the issuer makes passes for. Each has an `id` (the `sub` in every pass), the account at the sign-in provider it comes from, groups, and maybe an `org`. Signing in isn't enough: a user must be a member, or join as one with `new_members`. |
| **upstream** | your sign-in provider: Firebase, Auth0, or any OpenID Connect provider. It says who signed in. The issuer decides what they get. |
| **audience**, or **resource** in a request | the service or MCP server a pass is for, by its URL. It's the pass's `aud`, asked for with `resource`. Every other service turns the pass away. |
| **resource** in a permission | the kind of record: `order` in `order.own.read`. It has nothing to do with the URL above. |
| **scope** in a permission | whose records: `own`, `org` or `any`. `order.own.read` reads the caller's own orders. |
| **OAuth scope** | a word a client asks for when it signs a user in, like `orders:read`. Each one maps to a ceiling. It has nothing to do with `own`, `org` and `any`. |
| **permission set**, **group** | a named list of permissions, and a named list of sets. A member gets all their groups' sets together, and denials still win. |
| **ceiling** | the most a pass may allow, set on an agent, a client or an OAuth scope. An agent's pass holds what the user may do, cut down to the agent's ceiling. |
| **pin** | `authorization_details` that narrow a pass to named records and actions: cancel order 4418, and nothing else. |
| **`act`** | the part of a pass that names who is acting for the user: an agent, or a client that isn't yours. `permits(..., agents=False)` refuses those passes. |
| **first-party** | your own app (`first_party: true`). It gets the member's full permissions, with no consent page and no `act`. |
| **session** | one sign-in. It covers the refresh tokens it moves through, and every agent pass traded from its passes. Revoking it stops its refreshes and trades at once. Passes already handed out stop working within 5 minutes. |
| **admission hook** | a function of yours that can turn a user away when they sign in and every time their pass is refreshed. |

## Standards it uses

Everything on the wire is a published standard, so any JWT library can
check the passes:

- the pass is a JWT access token (RFC 9068), checked with keys from a JWKS;
- the issuer describes itself with OAuth metadata (RFC 8414);
- MCP clients sign in with the authorization code flow and PKCE (OAuth
  2.1, RFC 7636), with `iss` in the response (RFC 9207), and identify
  themselves with Client ID Metadata Documents;
- agents trade passes with token exchange (RFC 8693), and every request
  names its server with a resource indicator (RFC 8707);
- agents and services prove who they are with `private_key_jwt`
  (RFC 7523);
- passes can be revoked (RFC 7009) and looked up (RFC 7662).

Two optional features need more than a JWT library: permission sets by
reference, and the revocation list. Both are signed or hash-pinned JSON,
described in [`spec/tokens.md`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/spec/tokens.md).

## Where to go next

| | |
|---|---|
| [Going to production](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/docs/production.md) | your sign-in provider, admission hooks, keys, Docker, Postgres, Cloud KMS, members and sign-up, strict mode, cookie mode |
| [Running it day to day](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/docs/admin.md) | policy in the store, the admin API, the admin portal, access requests |
| [Putting it inside your own app](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/docs/embedding.md) | the issuer running in your own process, with hooks and logging in code |
| [Reference](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/docs/reference.md) | every config setting and every endpoint |
| [SECURITY.md](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/SECURITY.md) | what's checked, what's trusted, and what to do if a key leaks |
| [`spec/`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/spec) | the pass format and the permission language, for a version in another language |
| [`docs/design.md`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/docs/design.md) | the design, and every decision made on it |

## Reviewing the code

The parts that keep a pass safe are about 3,000 of the package's 15,100
lines. Read [SECURITY.md](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/SECURITY.md) first, for what's checked and what's
trusted. Then read these:

| File | What it decides |
|---|---|
| [`validator.py`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/src/gatehouse_issuer/validator.py) | every check a service makes on a pass, in the order [`spec/tokens.md`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/spec/tokens.md) lists them |
| [`permissions.py`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/src/gatehouse_issuer/permissions.py) | the permission language: matching, denials, cutting one set down by another |
| [`gatehouse.py`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/src/gatehouse_issuer/gatehouse.py) | `permits()` and `redact()`: `own` and `org`, decided from the record your loader returned |
| [`server/issuer.py`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/src/gatehouse_issuer/server/issuer.py) | making a pass: what goes in it, how big it may get, and the answer `/token` sends |
| [`server/grants/exchange.py`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/src/gatehouse_issuer/server/grants/exchange.py), [`pins.py`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/src/gatehouse_issuer/server/grants/pins.py) | signing in, and an agent's trade: the audience, the ceiling, `act`, pins and `needs_user_pin` |
| [`server/grants/refresh.py`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/src/gatehouse_issuer/server/grants/refresh.py), `rotate_refresh` in [`server/store.py`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/src/gatehouse_issuer/server/store.py) | swapping refresh tokens, catching one used twice, and the short grace window |
| [`server/client_auth.py`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/src/gatehouse_issuer/server/client_auth.py) | `private_key_jwt`: how agents and services prove who they are |
| [`server/authorize/__init__.py`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/src/gatehouse_issuer/server/authorize/__init__.py), [`server/joining.py`](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/src/gatehouse_issuer/server/joining.py) | `/authorize` (PKCE, tying the sign-in to one browser, consent), and which member a sign-in is for |

[CONTRIBUTING.md](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/CONTRIBUTING.md#where-things-are) maps the rest.

## What it doesn't do

- **Dynamic client registration.** It isn't planned, because the MCP spec
  dropped it. MCP clients bring a Client ID Metadata Document, or you list
  them in the config.
- **AWS KMS or Vault Transit for keys.** Keys live in a file or in Google
  Cloud KMS. Others would plug into the same `KeyBackend` interface, when
  someone needs them.

## Contributing

[CONTRIBUTING.md](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/CONTRIBUTING.md) shows how to set up, run the tests and
the lint, and where things are.

## Who built this

[Nick George](https://nickgeorgeai.com), who also builds mcp-gatehouse.

## License

[MIT](https://github.com/nickgeorgeseo/gatehouse-issuer/blob/main/LICENSE)
