Your agent’s scheduling tool sends DELETE /shifts/shf_1 with a token that cannot delete. The API
answers 403 after a round trip, the model reads a bare status and tries again, and each retry
counts against a rate limit. The client already knew which scopes the token carried, and it could
have refused the call itself.
What you get
You will end up with a generated client that refuses calls its role may not make, and a rule table generated from the API document. This is for you if an agent or a batch job calls an API under a role.
Short answer
With sdkgen, add the rbac feature and construct the generated client with three options. Set
deny to true, pass the scopes the role’s token carries as permissions, and pass a rules table
generated from the scopes in your OpenAPI document. A call the role may not make throws
rbac_denied before any request is built. Keep the server’s own check: the local one is a hint
that saves a round trip, and the server still refuses what only it can judge.
You will need
Node 22 or later, Python for the Python twin, and an OpenAPI 3 document that declares one scope on
each operation. The generated Python package declares 3.8 as its floor. Verified 2026-11-19
against Node 22.23.5, Python 3.13.18, @voxgig/create-sdkgen 0.31.9, @voxgig/sdkgen 4.44.3, and
NSwag 14.8.0. The sample’s clients were generated once from api.json, a five-operation Roster
document, and committed, so every command runs offline.
The check runs at PrePoint, the first stage of an operation, which
choose the pipeline stage where an SDK behavior should run
explains.
Approaches compared
| Approach | When it fits | What it costs you | When to pick something else |
|---|---|---|---|
| Casbin, evaluated in the client | The server already enforces a Casbin model, and the client can load the same files | An enforcer, a model file, and a policy file shipped in every client, per language | Rules are one scope per operation, which a lookup table covers |
| Fern audiences or a custom fetcher | A role fixed per consumer, where a filtered SDK can leave the methods out | An Enterprise plan for audiences, and no run-time check unless you write a fetcher or wrapper | One client must serve several roles at run time |
| Hand-written allow-list interceptor | Any client whose fetch you can wrap, generated or not | Method and path parsed back into an operation, and a table kept in step by hand | The generator can hand you the operation name |
| NSwag method guard | An NSwag client, whose methods carry the document’s operation ids | A wrapper you own and test, because NSwag generates no permission check | You want the check generated into every language you ship |
| sdkgen rbac feature | An sdkgen client, where the TypeScript and Python targets take the same three options | One permission per operation, allow by default unless deny is set, and direct() outside it | A rule needs two scopes, or a fact about the record |
| Server-side authorization alone | Every API, because it is the one check a caller cannot remove | A round trip and a 403 for each call the client could have refused | Never drop it, because every other row sits on top of it |
Voxgig maintains sdkgen. It is one of six options here, not the recommendation.
Only the last row is a boundary. Casbin, or a policy that OPA compiles to WebAssembly, can evaluate the server’s own policy file in the client, at the price of shipping an engine with it. A lookup table, whether sdkgen’s or your own around NSwag, is cheaper and says less: one permission per operation. Fern removes methods at build time instead, which fits a role that never changes.
Generate the rule table from the document
A rule table typed by hand is a second copy of the server’s rules. The OpenAPI document holds the
first: each operation’s security entry lists the scopes it requires.1 rules.mjs joins that
to the generated client’s own map of entity operations to routes.
/** rbac rules keyed "<entity>.<op>", one for each operation the generated client can call. */
export function rulesFrom(document, sdkConfig = config) {
const rules = []
for (const [entity, { op }] of Object.entries(sdkConfig.entity)) {
for (const [name, { points }] of Object.entries(op)) {
const scopes = new Set(points.map((point) => scopeOf(document, point.method, point.orig)))
if (scopes.size !== 1) {
throw new Error(`${entity}.${name} reaches routes with different scopes: ${[...scopes].join(', ')}`)
}
rules.push([`${entity}.${name}`, [...scopes][0]])
}
}
// Code-point order, so the file is the same wherever it is generated.
return Object.fromEntries(rules.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
}
node rules.mjs
{
"shift.create": "shift:write",
"shift.list": "shift:read",
"shift.load": "shift:read",
"shift.remove": "shift:delete",
"shift.update": "shift:write"
}
That output is committed as rules.json. The script stops on a document it cannot express, such
as an operation with two scopes or with none. A table weaker than the document would look like a
check without being one.
Build one client per role
The feature takes three options: what the client holds, what each operation needs, and what to do when no rule matches.
return new RosterSDK({
base,
apikey: granted.token,
// direct() is not an entity operation, so rbac never sees it. Leaving it out of allow.op
// makes the client refuse it too.
allow: { op: 'create,update,load,list,remove' },
feature: {
// deny: true refuses an operation that has no rule, so a missing rule fails closed.
rbac: { active: true, deny: true, permissions: granted.scopes, rules },
},
})
permissions should be the scope the token response reported, which can be narrower than the
scope you asked for.2 The demo runs seven calls under three roles against a stand-in server
that enforces the document’s scopes and one more rule: a shift changes only at its own site.
node demo.mjs
role call local check server
viewer shift.list allowed 200
viewer shift.create denied, shift:write not called
scheduler shift.create allowed 201
scheduler shift.update shf_1 allowed 200
scheduler shift.update shf_2 allowed 403 shf_2 is rostered at site south
scheduler shift.remove shf_1 denied, shift:delete not called
admin shift.remove shf_1 allowed 204
7 calls, 5 requests reached the server
the two refusals a caller catches, by err.code
rbac_denied RosterSDK: create: Permission "shift:write" required for operation "create"
request_status RosterSDK: update: request: 403: Forbidden
Two calls stopped in the client, which is two requests the rate limit never counted. The fifth
line is the one to remember. The local check allowed the update and the server refused it, because
which site owns shf_2 is a fact about one record, and a rule table holds no records.3 The
stand-in’s second check is the part no client can copy:
// Object level: which record this is, which only the server can know.
const site = id === undefined ? body.site : shifts.get(id).site
if (req.method !== 'GET' && principal.site !== '*' && site !== principal.site) {
return send(403, { error: 'forbidden', reason: `${id ?? 'the new shift'} is rostered at site ${site}` })
}
Return err.code and err.message to the model as the tool result. It can then tell a call its
role never makes from one refused for this record. sdkgen’s
feature reference
draws the same line: client-side enforcement, and not a security boundary.
Regenerate the rules when the document changes
A rule table goes stale in two directions. drift.mjs changes two scopes in the server’s document
and calls with the rules as shipped.
node drift.mjs
rules.json as shipped, against a server whose document has changed
shift.create local: allowed server: 403 shift:publish
shift.remove local: denied, shift:delete server: not called
rules generated again from the changed document
shift.create local: denied, shift:publish server: not called
shift.remove local: allowed server: 204
The stale allow costs the round trip the check was there to save. The stale deny is worse,
because the client blocks a call the server would accept and the refusal appears in no server log.
A test compares rules.json with the document, so the file cannot fall behind unnoticed.
Run the same check in the Python client
The Python target takes the same options under the same names, and reads the same rules.json.
demo.py gives it a transport that records each request and answers from a script.
python3 demo.py
role call outcome transport
scheduler shift.update shf_1 ok called
scheduler shift.update shf_2 request_status, status 403 called
scheduler shift.remove shf_1 rbac_denied, status -1 not called
3 calls, 2 reached the transport
client._rbac {'allowed': 2, 'denied': 1, 'last': {'required': 'shift:delete', 'allowed': False, 'op': 'remove'}}
The codes match the TypeScript client’s: rbac_denied for the local refusal, and request_status
with status 403 for the server’s. client._rbac is the feature’s own count of both verdicts.
Check it worked
Fourteen Node tests and five Python cases hold the two claims: a denied role never reaches the transport, and an allowed role still gets the server’s 403.
node --test check.test.mjs
1..14
# tests 14
# suites 0
# pass 14
# fail 0
# cancelled 0
# skipped 0
# todo 0
python3 test_check.py
ok a_denied_role_never_reaches_the_transport
ok an_allowed_role_still_gets_the_servers_403
ok an_operation_with_no_rule_is_refused
ok direct_is_refused_by_allow_op
ok a_permission_nobody_was_granted_is_never_held
5 cases, 0 failures
A third Node test gives a viewer’s token to a client that grants itself *. The local check
passes, but the server answers 403.
Add the check to a Fern or NSwag client
Fern documents no run-time permission check. Its nearest mechanism works at build time: tag
operations with x-fern-audiences, list an audience under api.audiences in sdk-config.yml,
and the SDK is generated without the operations tagged only for other audiences. Fern’s
audiences page marks that as
an Enterprise feature.
A run-time check in a Fern SDK goes where its dynamic authentication guides put their logic. In
TypeScript,
allowCustomFetcher: true
gives the client a fetcher option that wraps every request. In Python, Fern’s
method override pattern
puts a wrapper class over the generated client, and that class has to override each method.
NSwag’s TypeScript generator documents no permission check either, and the client it wrote from
api.json contains none. NSwag 14.8.0 produced one Client class with a method per operation id,
so a guard keyed by method name refuses before a URL exists.
export function guard(client, scopes, held) {
const granted = new Set(held)
return new Proxy(client, {
get(target, name) {
const member = Reflect.get(target, name, target)
if (typeof member !== 'function') return member
return (...args) => {
const needs = scopes.get(name)
if (needs === undefined) return Promise.reject(new PermissionDenied(String(name), 'no rule'))
if (!granted.has(needs)) return Promise.reject(new PermissionDenied(name, needs))
return member.apply(target, args)
}
},
})
}
node nswag-demo.mjs
role call local check server
scheduler listShifts allowed 200
scheduler updateShift shf_2 allowed 403 shf_2 is rostered at site south
scheduler deleteShift shf_1 denied, shift:delete not called
3 calls, 2 requests reached the server
The scopes here come straight from the document by operation id, with no model in between.
NSwag’s documented seams are request-level instead: a transformOptions method on a base class or
an extended client class, which sees the request options and not the operation.
When it goes wrong
An operation with no rule goes through. deny defaults to false, and an unmatched operation is
then allowed. Set deny: true, and generate a rule for every operation.
A forbidden call reaches the server through direct(). rbac hooks entity operations only. Leave
direct out of allow.op, as roles.mjs does.
A client holding nothing passes a rule. In the 4.44.3 TypeScript target, a permission named like
an Object member, such as constructor, counts as held, because the lookup is a plain object.
The Python target does not do this. rules.mjs refuses such scope names.
When not to do this
Do not relax the server because the client checks. Anybody can build a client without the
feature, or with permissions: ['*'], and the server’s 403 is then the only refusal left.
Do not use sdkgen’s rbac for rules it cannot hold. It takes one permission per operation and knows no record, so “two scopes” or “only at your own site” belong to the server, or to a policy engine that both sides load.
Do not ship a run-time check when the role is fixed per consumer. Fern’s audiences generate that consumer’s SDK without the operations, so the method is not there to call.
Do not add a generator feature for one TypeScript client. NSwag’s single file and a guard of fifteen lines are less to carry than a rule table tied to a model, and the guard’s keys are the operation ids in your document.
Related how-tos
Last verified
Verified 2026-11-19 against Node 22.23.5, Python 3.13.18, @voxgig/create-sdkgen 0.31.9,
@voxgig/sdkgen 4.44.3, TypeScript 5.9.3, and NSwag 14.8.0. Every output block is what the
command preceding it printed. The scaffold, the generation, and the NSwag run are not repeated by
the page’s checks: generate.sh ran them once, and their output is committed under generated/.
NSwag 14.8.0 was run once on the .NET 10.0.15 runtime, with DOTNET_CLI_TELEMETRY_OPTOUT set.
Fern was not run; its options come from its documentation, in the current sdk-config.yml format.
Casbin and OPA were not run. The Python client ran against a scripted transport, not a server.
Footnotes
-
The OpenAPI Specification 3.0.3 lets a requirement name scopes only for the
oauth2andopenIdConnectscheme types, and says the array must be empty for every other type. An API key, by that text, has no scopes to generate a rule from. ↩︎ Back to text -
RFC 6749 says the authorization server may fully or partially ignore the scope requested by the client, and that the
scoperesponse parameter informs the client of what was issued. So the list to hand the client is the one in the response. ↩︎ Back to text -
The OWASP API Security Top 10 for 2023 files the two checks apart. Broken object level authorization is first on the list, and broken function level authorization is fifth. A rule table of operations and scopes is a function level check, so it addresses the fifth item and leaves the first where it was. ↩︎ Back to text