Post

The token says who you are. OpenFGA says what you can see.

TL;DR: My Keycloak lab could say what kind of thing a user may do. It couldn’t say whether they may see this document. I added sharing with OpenFGA: a document can be private to its owner, who shares it with a person or a department. OpenFGA stores only who owns what and who it was shared with. Who belongs where stays in Keycloak, and travels with every check from the token. This post covers that split, three things that went wrong without an error, and a delete that took three rounds of review to get right.

In September I wrote that my API makes its own authorization decisions, and ended with a rule of thumb: if your policies change faster than your deploys, or users share things with each other, Keycloak’s Authorization Services earns its round-trip.

Then I added sharing, and didn’t use Authorization Services.

That rule was half right. Sharing is what makes a per-document model worth having. It didn’t have to be Keycloak’s.

So how do you add per-document sharing to an API behind Keycloak? Keep membership in Keycloak and relationships in OpenFGA. OpenFGA stores who owns a document and who it was shared with. The caller’s tenant and departments travel with every check as contextual tuples, built from the validated token, so there’s no second copy of membership to keep in step.

As before, it’s a lab: I’ve run it on my machine and in CI against a real Keycloak and a real OpenFGA, and nowhere else.

Keycloak sends the token to the API, which asks OpenFGA with the caller's membership added; OpenFGA stores only owners and shares

Roles can’t answer “this document”

The lab’s demo app, DocVault, is a multi-tenant document store. Until now, everyone in a tenant saw every document of it, and the token decided everything else:

QuestionAnswered byFrom
Which tenant are you in?the APIthe token’s groups path
What kind of thing may you do?.NET policiesthe token’s roles
Was the sign-in strong enough?the step-up policythe token’s acr
May you see this document?OpenFGAstored relationships, plus memberships from the token

The last row is new, and it’s a different kind of question. “May alice edit documents?” depends on alice. “May alice see the Q4 plan?” depends on the Q4 plan: who owns it, and who it was shared with. A token can’t carry that, because it would have to list every document alice may see.

There are two easy ways to get this wrong, and they mirror each other. Put roles into the authorization service, and a role now has two places to change. Put relationships into the token, and the token grows with every share. Each question should be answered once, by the part that owns it.

The model

OpenFGA is an open-source authorization service modelled on Google’s Zanzibar. You write a model of types and relations, store relationships as tuples (user:alice owner document:q4-plan), and ask it questions (can user:alice can_view document:q4-plan?). This is DocVault’s whole model:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
type user

type tenant
  relations
    define member: [user]

type department          # id: <tenant>/<department>, e.g. acme/legal
  relations
    define member: [user]

type document
  relations
    define tenant: [tenant]
    define owner: [user]
    define viewer: [user, department#member, tenant#member]
    define in_tenant: member from tenant
    define can_view: (owner or viewer) and in_tenant
    define can_share: owner and in_tenant
    define can_delete: owner and in_tenant

Three decisions are in those lines.

“Visible to the tenant” is just a share. A document everyone in Acme can see has tenant:acme#member as a viewer. A private document doesn’t have that tuple, and nothing else is different.

Every permission requires membership of the document’s tenant. A share to someone in another tenant exists and grants nothing. The API refuses to write one anyway, because it would switch on the day that person joined the tenant.

Roles aren’t in the model. Deleting a document needs doc.admin or being its owner. The API reads the role from the token, like every other role. Only the owner half is OpenFGA’s.

The model has its own tests, run on OpenFGA’s own engine: make test-model, 30 checks and 3 lists, in Docker, with no lab running. When I took and in_tenant out of can_view, two of them failed.

Membership comes from the token

OpenFGA could hold group membership too, as tuples, kept in step with Keycloak by a sync job. I didn’t want a sync job. Instead, the API sends the caller’s memberships with every check, as contextual tuples: tuples that exist for that one request and are never stored.

sequenceDiagram
    participant B as Browser (alice)
    participant K as Keycloak
    participant A as DocVault API
    participant F as OpenFGA
    B->>K: sign in
    K-->>B: token: sub, groups ["/acme/engineering"], roles
    B->>A: GET /documents
    Note over A: validate the token,<br/>tenant from the group path
    A->>A: the tenant's documents, from the store
    A->>F: can_view? one check per document<br/>+ alice member tenant:acme<br/>+ alice member department:acme/engineering
    F-->>A: allowed or not, per document
    A-->>B: the documents alice may see

The tuples come from one place in the code, built from the validated token’s sub and groups and nothing else:

1
2
user:<alice's id> member tenant:acme
user:<alice's id> member department:acme/engineering

There’s no second copy of membership to go stale. The lab has an LDAP directory, and its end-to-end check moves erin, a directory person, out of engineering. The document shared with engineering disappears from her list with her next token. Nobody told OpenFGA anything.

The price is trust. OpenFGA believes contextual tuples completely. I measured it: bob, from globex, with a share to an Acme document written straight into OpenFGA, is refused. The same check with “bob is a member of acme” added as a contextual tuple is allowed. That’s how it’s meant to work, and it means a contextual tuple built from anything a caller controls is a way in.

So there are two checks, and either one alone keeps bob out. The API checks the tenant itself, from the token, before it asks OpenFGA anything. And the model requires the tenant. The end-to-end check writes that share to bob past the API and confirms both: OpenFGA says no while he’s in globex, and the API shows him nothing.

Why not Keycloak’s Authorization Services

The realm already models DocVault’s documents in Authorization Services, so I compared the two for sharing specifically:

 Keycloak Authorization ServicesOpenFGA
Each documentregistered in Keycloak, through the Protection API, with the resource server’s secrettuples pointing at the API’s own document id
The document listKeycloak holds a copythe API keeps it
MembershipKeycloak’s ownKeycloak’s, sent with each check
A decisiona network call to Keycloaka network call to OpenFGA
Keycloak on the read pathyesno
Testing the policyasking Keycloak, with real users’ tokensa typed model, tested on its own engine

Neither is free. Both put a network call on the request path, and both are a service that can be down. What decided it for me was the first two rows: with OpenFGA, Keycloak doesn’t need to know a document exists.

Three things that went wrong without an error

The theme of this series is configuration that looks right and fails silently. OpenFGA, and the Terraform provider for it, had their share.

list-objects drops results and returns 200. It’s the call made for “which documents may alice see?”, and the API doesn’t use it. With the limit set to 2 and three visible documents, it returned two of them, with HTTP 200 and no flag or header saying there were more. The default limit is 1000. Instead, the API takes the tenant’s documents from its own store and asks about each one with batch-check, which takes at most 50 checks a call (more is refused, which is at least loud).

The check cache delays a revoke and a new share alike. With OPENFGA_CHECK_QUERY_CACHE_ENABLED on, a revoked share stayed allowed, and a new share stayed refused, until the cache entry expired after 10 seconds. The cache is off by default. The API sends HIGHER_CONSISTENCY with every check anyway, which skips it, so turning the cache on can’t make a revoke slow. With the cache on, the end-to-end check passes. With the cache on and HIGHER_CONSISTENCY removed, it fails at “carol sees it now”.

Terraform reports a model destroyed that OpenFGA keeps. The store and model are in Terraform, applied by the same make seed as the realm (the tuples aren’t: they change at run time, and the plan would never be empty again). Change the model and the plan shows a replacement, and the apply says “Destruction complete”. OpenFGA can’t delete a model. The old id still answers. The API is pinned to one model id, so a new model doesn’t change a running API’s decisions under it.

Failing closed, and saying so

If OpenFGA can’t answer, the API answers 503. Not 404 or 403, because those are decisions and none was made. Not an empty list, which reads as “you have no documents”. And never “allow”.

The end-to-end check freezes OpenFGA with docker compose pause and measures the 503 at about three seconds, the client’s timeout. There are no retries. The OpenFGA client is a few dozen lines over HTTP rather than the SDK, so there’s no retry loop or fallback between a failure and the 503 that I’d have to reason about.

A check that comes back as an error inside a batch isn’t a “no” either. Nothing was decided, so the whole request fails.

A share is an id, never a name

A share records the person’s Keycloak user id, never their username. A username can be renamed, and it can be reused: a leaver’s username given to a new starter would carry the leaver’s shares with it.

The end-to-end check renames erin in the directory. She signs in under her new name with the same user id, the share follows her, and the owner’s list of shares shows the new name.

Someone who leaves the tenant keeps their place in that list, marked as no longer in the tenant. The share grants them nothing while they’re elsewhere, because every permission needs the tenant. It would grant them access again if they came back, so the owner should see it and be able to remove it.

Turning a username into an id needs Keycloak’s Admin API. The API does that as a separate client that holds view-users and nothing else. Asking to share with someone in another tenant gets exactly the same 404 as asking for nobody, so a share request isn’t a way to find out who works at globex. At least, that was the plan.

What three rounds of review found

As with the earlier posts, I asked a second, independent Claude session to review the branch adversarially, with the code and not my conclusions. It found five problems in the first round. None was a way to see, share or delete a document someone shouldn’t, and each fix has a test that fails without it. Two of them are worth telling.

The 404 that told you who exists, by its timing

Both answers were the same 404, with the same body. They didn’t take the same time. Looking up someone from the directory took about 300 ms, because Keycloak reads their groups from LDAP. Looking up nobody took about 90 ms. So an owner could tell that a person exists in another tenant, by timing a share.

Every share to a person now takes at least one second, found or not. Measured afterwards, a directory person in globex, one in no group, a local user in globex and nobody all took about 1040 ms. The API logs a warning if a lookup is ever slower than the floor, so a directory that outgrows it gets noticed.

The delete that took three rounds

Deleting a document removes its tuples from OpenFGA first, then the document. A document nobody can see is one nobody can delete again, so a delete that fails halfway mustn’t leave one.

Round one. OpenFGA writes at most 100 tuples at a time, and each write is all or nothing. A widely shared document needs several writes. OpenFGA reads tuples back oldest first, so the first write took the document’s tenant and owner with it. If the second failed, the document was still in the store and nobody could see it. The fix: shares first, tenant and owner in a last write of their own.

Round two. That fix split every delete into two writes, even a small one that fit in one. And the tenant-wide visibility, tenant:acme#member, went out with the shares in the first write. If the second write failed, the owner could still see the document, but an administrator who saw it through the tenant could not. For a seeded document, which has no owner, that was everyone. Now a document that fits in one write is deleted in one, so a failure changes nothing. A larger one keeps the tenant-wide visibility for its last write.

Round three. Take a private document whose owner has left, and an administrator who sees it only through a share, to them or to their department. The first write took that share, so a failure after it left nobody able to see the document. The last write now also keeps whatever lets the person deleting it see it, taken from their token, so they can try again.

Each round’s fix was correct for the case it fixed, and each round found a case it didn’t. What finally made the question answerable was asking it the other way round: not “which tuples are important?”, but “after any failure, who can still see this document?”.

A last look at the fix found nothing more in the delete, only a weakness in my test for it. The API’s tests use a fake OpenFGA that answers checks from a table, so a retry that succeeds proves nothing about the model. The lab’s end-to-end check now writes the tuples a failed delete leaves into the real OpenFGA, and asks who can still see the document.

And two smaller ones

  • A department called . passed the name check, and Keycloak looked up /acme/. and found /acme, the tenant itself. A name could also end in a newline, because $ in a .NET regex matches before a final one. Names now start with a letter or digit and end with \z.
  • Deleting a classified document answered 403 to anyone who wasn’t an administrator, and 404 for a document that didn’t exist. The 403 confirmed that a document behind the step-up policy existed. It’s a 404 now, like any unknown id.

An assistant can share too

The lab’s MCP server has two new tools, share_document and unshare_document. They need a scope of their own, docvault:share, which a client asks for only when the tool is first used, so the consent screen shows “Let the assistant share your documents with people in your organisation” on a line of its own.

I kept it out of docvault:write on purpose. A share is how a document reaches people who couldn’t see it, which makes it the tool a prompt injection would most want. The scope, the API’s owner and tenant rules, and the audit record of who each share went to are what stand in the way. Inside the tenant, nothing tells a share the user meant from one a document asked for.

What this isn’t

  • On Azure. The Azure deployment runs no OpenFGA. There, every document is visible to its tenant, and a request for a private one is refused rather than quietly made tenant-wide.
  • Break glass. No administrator can see a private document. A regulated organisation will want an audited override.
  • Ownership transfer. A leaver’s private documents stay theirs.
  • Production authentication to OpenFGA. The API uses a preshared key over plain HTTP on loopback. In production I’d use client credentials, which OpenFGA supports, and TLS.
  • Durable. The lab’s document store is in memory, so documents vanish when the API stops. Their tuples stay in OpenFGA and grant nothing, since no document has those ids any more.

What I took away

  • Keep each question in the part that owns it. Membership in the identity provider, relationships in the authorization service, roles in the token.
  • Send membership with the check instead of syncing it. There’s nothing to go stale. But the service believes what you send, so build it from the validated token alone, and check the tenant twice.
  • Fail closed, and look like it. A 503 is honest. An empty list is a lie that looks like an answer.
  • Make “not found” indistinguishable in time as well as in body. Same status and same body weren’t enough.
  • Ask “who can still see it?” after every failure, not “which writes matter?”. It took me three rounds to ask it that way.

Try it

v1.5.0 of the lab is the version this post describes. It needs Docker, .NET 10 and Terraform:

1
2
3
4
5
git clone --branch v1.5.0 https://github.com/MagnusJohansson/keycloak-poc
cd keycloak-poc
make test-model                      # the model's own tests, in Docker
make up && make seed && make api     # Keycloak, the directory, OpenFGA, the realm, the API
make assert-fga                      # 45 checks against the real stack

Then make web in another shell, sign in as alice (password DocVaultLab!2026), create a private document and share it with carol.

The details are in the lab’s write-up.

Earlier in this series: Keycloak can make your authorization decisions. Mine doesn’t., An MCP server behind Keycloak and The assistant deleted a document. Who did that?


I wrote this post with Claude’s help, the same way I built the feature. A second, independent Claude session reviewed the change over three rounds. The decisions and the final check of every claim are mine.

This post is licensed under CC BY 4.0 by the author.