@vantreeseba/graphql-casl
v1.12.0
Published
GraphQL middleware plugin for defining CASL permission rules on resolvers, with optional argument scoping and an envelop/Yoga integration.
Maintainers
Readme
@vantreeseba/graphql-casl
Permission rules for GraphQL resolvers, built on CASL and
graphql-middleware. Declare a rule per type or field
in one PermissionsMap; each runs before its resolver, or on what the resolver loaded, and an error
replaces what the caller may not see.
CASL has to know what an object is before it can pick a rule for it, which is the hard part of binding it
to a data source: plain rows carry no type name. GraphQL already gives every object one, in __typename.
So the subjects here are your schema's types. They come from your own generated resolver types, nothing is
listed by hand, and a misspelled type, field or condition is a compile error. You can also start with no
generated types at all and have the map checked when the server starts.
Rules guard resolvers, so they are defense in depth: ownership enforced in the data layer holds on paths a resolver rule cannot see.
Install
npm install @vantreeseba/graphql-casl @casl/ability graphql graphql-middlewareESM only. /envelop also needs @envelop/core and @envelop/on-resolve.
Quick start
A todo API where callers may read only their own todos. It needs npm install @graphql-tools/schema. Save
it as quick-start.ts in a package with "type": "module" and run node quick-start.ts.
import { makeExecutableSchema } from '@graphql-tools/schema';
import {
Actions,
accept,
applyPermissions,
createCan,
createGraphQLAbility,
createTyped,
deny,
type PermissionsMap,
} from '@vantreeseba/graphql-casl';
import { graphql } from 'graphql';
type Todo = { id: string; ownerId: string; title: string };
type Context = { userId?: string };
const todos: Todo[] = [
{ id: 't1', ownerId: 'alice', title: 'buy milk' },
{ id: 't2', ownerId: 'bob', title: 'walk dog' },
];
const baseSchema = makeExecutableSchema({
typeDefs: /* GraphQL */ `
type Query {
todo(id: ID!): Todo
health: String
}
type Todo {
id: ID!
title: String
}
`,
resolvers: {
Query: {
todo: (_parent: unknown, args: { id: string }) => todos.find((todo) => todo.id === args.id),
health: () => 'ok',
},
},
});
// Derive this from generated types in a real app: SubjectMap<Resolvers, ResolversTypes>.
type AppSubjectMap = { Todo: Todo };
const typed = createTyped<AppSubjectMap>();
// 1. What each caller may do.
function abilitiesFor(userId: string | undefined) {
const { can, build } = createGraphQLAbility<AppSubjectMap>();
if (userId) {
can(Actions.read, 'Todo', { ownerId: userId }); // only your own
}
return build(); // no rules: everything is denied
}
// 2. Bind abilities and the auth check to the context.
const canUser = createCan<Context, AppSubjectMap>(
async (ctx) => abilitiesFor(ctx.userId),
(ctx) => ctx.userId != null,
typed,
);
// 3. Say which rule guards which field.
const permissions: PermissionsMap = {
Query: {
todo: canUser.onResult(Actions.read, 'Todo'), // checks the record that was loaded
health: accept, // public
},
Todo: accept, // reached only through a guarded field
};
// 4. Guard the schema. Fields the map does not name are denied.
const schema = applyPermissions(baseSchema, permissions, { fallbackRule: deny });
const run = (source: string, contextValue: Context) => graphql({ schema, source, contextValue });
console.log(await run('{ health todo(id: "t1") { title } }', { userId: 'alice' })); // both
console.log(await run('{ health todo(id: "t2") { title } }', { userId: 'alice' })); // todo: Forbidden
console.log(await run('{ health todo(id: "t1") { title } }', {})); // todo: Not authenticatedDocumentation
- Install and generate the types, or start without them
- Quick start
- Abilities, subjects and conditions
- The permissions map: kinds of rule, IDOR, precedence
- Apply the map to a schema: coverage, responses, errors
- Entry points:
/scoping,/envelop,/apollo - Common mistakes
- Every export, as
llms.txt - API reference
- Coming from
graphql-shield - Changelog
- Companion package:
@vantreeseba/graphql-casl-codegengenerates the subject bindings
Guides
One page per topic, in rough order of how often it comes up.
| Guide | Use it when |
| --- | --- |
| Post-execution rules | The condition belongs to the record the resolver loads, not to the client's arguments |
| Field-level rules | A single field of a type needs its own rule |
| Field permissions from the ability | The ability already lists fields (can('read', 'User', ['id'])) and you don't want to restate them |
| Combining rules | A field needs more than one check — and / or / not / chain / race / wrap |
| Caching a rule's answer | An async rule runs once per field per object and should run once per request, or once per row |
| Granting a parent's decision to its fields | A list already authorized its rows and the type rule re-checks them once per field |
| Error control | Forbidden isn't enough: you need codes, filtering, or a look at what actually broke |
| Wildcards | One rule should cover a whole type, or one field across every type |
| Rules on interfaces | One rule should cover every type implementing an interface, new ones included |
| Row-level filtering | A list should return fewer rows rather than be denied outright |
| Scoping generated resolvers | The resolver is generated and you can only reach its arguments |
| Validating arguments | The arguments need checking the SDL cannot express — blank strings, ranges, one field against another |
| Using the map without graphql-middleware | You're building your own integration |
| Enforcing the map through envelop | Yoga, Apollo 4+, a gateway, or any schema you don't own |
| Delegating to an external policy engine | Permissions are relationship-derived — OpenFGA, Cerbos, OPA, Oso |
| Persisting rules | Rules live in a database rather than in code |
| Testing your permissions | You want the rules covered, including the argument-forging case |
License
MIT © Benjamin Van Treese
