Identity, access and limits
Step 4 of 14. Work out who is asking and what they may do, carry that identity into retrieval and tools, and cap what any one caller can spend. A prompt asking the model to behave is never the security boundary.
Identity, access and limits in 60 seconds
- Identity: prove who is calling with company single sign-on and a signed token. Never trust a user ID or role sent in the request body.
- Access: check permissions when documents are retrieved and when actions run. The model may suggest an action, and the application decides whether it is allowed.
- Limits: cap request rate, tokens, concurrency, tool calls and team quota, so one caller or one runaway loop cannot eat shared capacity or budget.
- Carry identity inward: pass the verified identity to retrieval filters, tools and logs, using short-lived tokens with narrow scopes.
- Fail helpfully: when a limit is hit, say what happened and when to try again.
The problem it solves
In an ordinary web app, a mistake in access control exposes a page or a record. In an AI assistant the same mistake has more routes to leak. A restricted document can appear in a generated answer, a retrieved passage, a conversation summary or the arguments of a tool call. Securing the screen is not enough. Security has to follow the data wherever the assistant takes it.
Store Assist makes this concrete. A store colleague may read the scanner sync guide. Only a small group may read the regional store closure plan. A colleague may reset their own till PIN but not someone else's. Refunds over £150 need a store manager. The rules already exist in the company. This step is about making the assistant obey them without exception, and about making sure a single noisy caller cannot take the other 11,999 colleagues down with it.
Identity: who is calling
Authentication proves who the caller is. In a company setting, Store Assist should use the existing single sign-on system built on OpenID Connect. After sign-in, the application holds a verifiable token or session. Every later request is tied to that proof, not to a name typed into a form field.
Each request should carry or resolve to the following facts, all established on the server:
- The signed-in colleague's identity.
- Their department or role, such as sales assistant, shift lead or store manager.
- Their store, region or business unit, where it matters.
- The operation being requested.
- A conversation or request identifier, for tracing.
Authorisation: what the caller may do
Authentication says who the caller is. Authorisation says what they can reach. Suppose a colleague asks about store closures and the retrieval system finds the regional closure plan, which is highly relevant but restricted. If search ignores permissions, the plan can leak even though the model followed every instruction it was given.
- Enforce at retrieval: filter documents by what this caller may read before the model sees them.
- Enforce at action time: the service that performs an action checks the caller's rights again.
- Do not rely on a prompt: a line saying do not reveal confidential documents is a request, not a control. It can be argued around.
- Rule of thumb: the model proposes, and the application decides whether to allow it.
Take the request to reset a till PIN. The application should check that this colleague may request a reset and that the account in question belongs to them or to someone in their scope. Only then does the identity verification workflow start. The reply never claims the reset happened unless the workflow says so.
Carrying identity into retrieval
Document permissions have to reach the search layer. Each chunk in the index should carry the access metadata of its source document, such as allowed roles, stores or groups, and a classification label. The query then runs with the caller's identity attached.
| Approach | How it works | Strength | Weakness |
|---|---|---|---|
| Pre-filter | Apply the permission filter inside the search query, so restricted chunks are never candidates. | Nothing restricted is ever scored or returned. Result counts stay full. | Needs filter support in the index and well-kept metadata. Complex filters can slow search. |
| Post-filter | Search first, then drop results the caller may not see. | Simple to add to any index. | Can leave too few results after filtering, and risks leaking existence through counts or timing. |
| Per-group indexes | Separate index per sensitivity tier or audience. | Strong isolation for the most sensitive material. | More indexes to build, refresh and pay for. |
Pre-filtering is the better default for confidential material. Use post-filtering only as a second line of defence, never the only one. Metadata must stay in step with the source: if a document's permissions change on Monday, the index metadata should change within your freshness target, and the cached answers that used the old rules must go too. Step 6 covers the update flow.
Service identity, short-lived tokens and scopes
The assistant calls other services, such as inventory and ticketing. Those calls need their own identity story, otherwise the assistant becomes one all-powerful account.
- Service-to-service identity: each service proves itself to the next with its own credentials, so a log shows exactly which component made which call.
- Act on behalf of the caller: where a tool reads personal data, pass the colleague's identity along with the call, so the downstream service applies the colleague's rights and not the assistant's.
- Short-lived tokens: issue tokens that last minutes, not days. A leaked token then has a short window of use.
- Per-tool scopes: a stock lookup token can read stock and nothing else. A ticket tool token can create and read tickets, but not close them.
- Least privilege: grant each tool the narrowest access that covers its single job.
What an API gateway adds
A gateway is the single guarded doorway in front of your services. Depending on the design, it can validate tokens, cap request sizes, apply rate limits, route traffic, do basic request checks, write central access logs and block common web attacks. See API gateway.
A gateway does not replace authorisation inside the application. It is one more layer that makes controls consistent. For example, a sales assistant might get a modest quota per minute, while a support desk agent or a trusted internal service gets a different one. Set the numbers from measured traffic, provider limits and the experience you want colleagues to have.
Limits as cost control
One AI request can fan out into several model calls, many retrieved documents, tool calls and a long answer. A flat requests-per-minute limit does not capture that. Limit at several levels:
- Request rate: the number of requests a colleague or client may send per minute.
- Token budget: the input and output size one request may consume.
- Concurrency: the number of simultaneous requests one caller may have running.
- Tool limits: the cap on tool calls and retrievals inside a single workflow.
- Organisational quota: the allowance a store, region or business unit has for a period.
These guard against runaway loops, abuse and surprise bills. The gateway can reject a request before the AI workflow starts, and the application can apply finer limits once it knows the request type. The aim is not to be strict for its own sake. It is to make sure one colleague, a faulty integration or a looping workflow cannot take an unreasonable share of capacity.
Quota design and helpful errors
- Per store, not only per person: a store of 30 colleagues should not be starved because one handheld loops. A store quota with a smaller personal cap inside it balances fairness and protection.
- Per business unit: a monthly token allowance for each unit supports chargeback and makes spend visible.
- Reserve for urgent work: keep a share of capacity for incident and approval paths, so a flood of routine questions cannot block them.
- Soft then hard: warn at 80 percent of a quota, throttle gently, and only then block.
- Say what happened: return a clear message that names the limit, says when it resets and offers an alternative such as the store support desk. A bare error teaches colleagues to retry in a loop, which makes things worse.
Audit logs
Security needs evidence. Record, for each request, who asked, which store they were in, which request type it was, which documents were retrieved by identifier, which tools were called with which scope, which limits were hit and what the outcome was. Log identifiers rather than full text where you can, and apply the retention rules from the next step. Write audit logs to a store that application code can append to but not edit.
Store Assist, worked through
Set limits from the capacity numbers. The average is 3 questions per colleague per trading day. A busy colleague might ask 10 times that on a bad day, so a personal cap of 30 requests an hour is generous without being unlimited. A store of 30 colleagues at 3 questions a day sends about 90. A store quota of 600 requests a day gives plenty of room, and a runaway handheld cannot take more than the store's share.
Budget tokens too. A request is planned at 1,000 input and 250 output tokens. Capping input at 4,000 and output at 600 stops a pasted log from costing 4 times the plan. At the illustrative prices, a capped worst-case request costs 4,000 x £0.40 per million plus 600 x £1.60 per million, about £0.0026. Even 100 of those in an hour costs about 26p. A tool cap of 3 calls per workflow bounds fan-out and matches the three-tool flow used for concurrency planning.
Now the identity walk-through. A colleague asks, "How many holiday hours do I have left?" The token says who they are. The application calls the rota service with that identity and a read-only scope for personal rota data. The answer is for this colleague only, so it must not enter any shared cache. A second colleague asking the same words gets their own lookup.
import time
PERSONAL_PER_HOUR = 30 # requests per colleague per hour
STORE_PER_DAY = 600 # requests per store per trading day
MAX_INPUT_TOKENS = 4_000 # hard cap on prompt size
MAX_OUTPUT_TOKENS = 600 # hard cap on answer size
MAX_TOOL_CALLS = 3 # per workflow
TOKEN_TTL_S = 300 # tool tokens live five minutes
def handle(request, auth, limiter, search, tools, audit):
# 1. Identity comes from a validated token, never from the body.
who = auth.verify(request.headers["authorization"]) # raises if invalid
if who is None:
return {"status": 401, "message": "Please sign in again."}
# 2. Limits are checked before any model or tool work starts.
ok, retry_after = limiter.check(
keys=[("person", who.id, PERSONAL_PER_HOUR, 3600),
("store", who.store, STORE_PER_DAY, 86400)])
if not ok:
audit.write(who, "limit_hit", request.id)
return {"status": 429,
"message": f"You have reached your hourly limit. Try again in {retry_after} seconds, or contact the store support desk."}
if request.token_estimate > MAX_INPUT_TOKENS:
return {"status": 413, "message": "That message is too long. Please shorten it."}
# 3. Retrieval is pre-filtered by what this caller may read.
passages = search.query(request.text, top_k=5,
filter={"allowed_roles": who.role,
"allowed_stores": [who.store, "all"]})
# 4. Tools get a short-lived, narrowly scoped token on the caller's behalf.
tool_token = tools.issue_token(on_behalf_of=who.id,
scopes=["stock:read", "ticket:read"],
ttl_s=TOKEN_TTL_S)
audit.write(who, "request", request.id,
doc_ids=[p.id for p in passages])
return {"status": 200, "passages": passages, "tool_token": tool_token,
"max_output_tokens": MAX_OUTPUT_TOKENS,
"max_tool_calls": MAX_TOOL_CALLS}
auth, limiter, search, tools and audit are placeholders for your own components. The shape to copy is the order: identity, then limits, then filtered retrieval, then scoped tools, with a log entry at the end.
Design decisions
- Where permissions live: one policy service that retrieval and tools both call, so the same rule is not written twice and then drift apart.
- Metadata model: which attributes go on every chunk (roles, stores, classification, document owner, version), and who is allowed to set them.
- Filter strategy: pre-filter for confidential material, with a per-group index for the very highest classification.
- Token design: lifetime, audience and scope list for tool tokens, and how they are revoked.
- Quota hierarchy: personal inside store inside business unit, with a reserved share for incident and approval paths.
- Failure behaviour: if the policy service is unreachable, the assistant refuses restricted requests and says so. It does not guess.
- Audit storage: append-only, access controlled, with its own retention period.
Measuring it
- Permission leak tests: a labelled set of questions where the correct answer depends on role, run as each role. The target is zero restricted passages returned to the wrong role.
- Retrieval quality under filters: recall at k with filters on, compared with the unfiltered figure, to confirm security does not quietly ruin answers.
- Limit hit rate: the share of requests rejected, by limit type and by store, so you can tell tuning problems from abuse.
- Rejection experience: the share of colleagues who retry within 10 seconds after a limit message, which shows whether the message helps.
- Tokens per request: distribution against the planned 1,000 input and 250 output, with a watch on the tail.
When to use it, and how much of it
| Situation | Controls to apply | Why |
|---|---|---|
| Public or fully open content only | Sign-in, basic rate limits, audit of requests | Little to leak, but cost and abuse still need caps. |
| Content with role or store restrictions | Add document permission metadata and pre-filtered retrieval | A relevant document is not always one the caller may read. |
| Personal data such as rotas and holiday balances | Add on-behalf-of calls, per-user scopes and no shared caching | The answer belongs to one person only. |
| Actions that change records | Add per-tool scopes, action-time checks and approval rules | A wrong action is harder to undo than a wrong answer. |
| Several business units sharing the platform | Add unit-level quotas, chargeback and separate audit views | Spend and access need clear owners. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Security and usability | Tight limits protect capacity but can block a genuine busy colleague. | Start generous, watch hit rates, and give a clear route to the support desk. |
| Quality | Permission filters can remove useful passages, so answers may be thinner for some roles. | Measure recall under filters and fix metadata gaps. |
| Latency | Token checks and policy calls add a few milliseconds to every request. | Cache validated tokens briefly and keep the policy service close to the gateway. |
| Cost | Limits cap spend, but identity and audit systems cost money to run. | Treat them as part of the base platform and share them across features. |
What this means for your role
Common mistakes
Step checklist
- Sign-in uses company single sign-on, and every request is tied to a validated token.
- No role, user ID or store comes from the request body.
- Every chunk carries access metadata, and retrieval filters by it before ranking.
- A role-by-role test shows no restricted passage reaches the wrong role.
- Tools receive short-lived, scoped tokens issued on the caller's behalf.
- Personal and role-specific answers are excluded from shared caches.
- Limits exist for request rate, tokens, concurrency, tool calls and organisational quota.
- Limit messages name the limit, the reset time and an alternative.
- Audit logs record identity, retrieved document identifiers, tools and outcomes in an append-only store.
Further reading
- Security concepts: the wider foundations behind identity and access.
- Rate limiting: algorithms and trade-offs for the limits above.
- API gateway: where several of these controls sit.
- Guardrails and safety: content-level controls that sit beside access control.
- Gateway, cost and reliability: quotas and spend control for model providers.
Identity and limits decide who gets in and how much they can use. They do not decide whether the words going in and out are safe. Next: Step 5: Guardrails and privacy.