Guides
Permissions
On this page
One common challenge of implementing an API is enforcing permissions. For example, users may only be allowed to read or modify some data, based on their role, on whether they own the data, or on other factors.
Three approaches work well with Gratos:
- Viewer context: pass the user into the data layer, and enforce permissions there.
- Permission directives: annotate fields with the permissions they require, with GraphQL directives, and enforce them in the GraphQL layer.
- Permission tokens with derived contexts: use TypeScript types and Gratos' derived contexts to enforce permissions in a type-safe way.
Viewer context
When you can, enforce permissions as close to the data source as possible, not in the GraphQL layer. Your privacy rules then apply however the data is accessed, through GraphQL or any other way.
One highly effective pattern is an object that represents the user making the request (often called "ViewerContext" or "VC"). Every database fetch that requires permissions takes one of these objects as an argument, and enforces the permissions at that layer: it uses the object's properties to determine whether the data can be read or updated, and throws an error if not. Derived contexts make it easy to get such an object.
/**
* This object can be derived from the request/cookies/etc.
* @gqlContext */
type VC = {
role: Role;
userId: string | null;
};
/** @gqlQueryField */
export function getUserById(vc: VC, userId: string): User {
return queryForUser(vc, userId);
}
// Separate function somewhere in your data layer
function queryForUser(vc: VC, userId: string): User {
if (vc.role !== "ADMIN" && vc.userId !== userId) {
throw new Error("You do not have permission to access this user.");
}
return db.queryUserById(userId);
}
/** @gqlType */
type User = {
/** @gqlField */
name: string;
};
type Role = "ADMIN" | "USER";
declare const db: { queryUserById(userId: string): User };type Query {
getUserById(userId: String!): User
}
type User {
name: String
}The VC object can also be passed through model constructors, so that you don't pass it explicitly through every field resolver:
/** @gqlType */
class User {
private vc: VC;
constructor(vc: VC /* ... other fields */) {
this.vc = vc;
}
/** @gqlField */
post(): Post {
return new Post(this.vc);
}
}
/** @gqlType */
class Post {
private vc: VC;
constructor(vc: VC /* ... other fields */) {
this.vc = vc;
}
/** @gqlField */
title(): string {
return readPostTitle(this.vc);
}
}
/** @gqlContext */
type VC = { userId: string | null };
declare function readPostTitle(vc: VC): string;type Post {
title: String
}
type User {
post: Post
}Permission directives
If you do enforce permissions in the GraphQL layer, one approach is to annotate fields with the permissions they require, using directives, and to wrap the fields' resolvers with permission checks.
The permission requirements are then visible in your generated GraphQL schema. Clients may find it useful to know which permissions a field requires, but sometimes permissions are not meant to be public knowledge, so consider whether this suits your use case.
Schema directives are not exposed through GraphQL introspection, so clients that read the schema that way do not see them.
Each restricted field is annotated like this:
/**
* @gqlQueryField
* @gqlAnnotate assert(is: ADMIN)
*/
export function getAllUsers(): User[] {
return db.queryAllUsers();
}
/** @gqlType */
type User = {
/** @gqlField */
name: string;
};
declare const db: { queryAllUsers(): User[] };"""Indicates that a field require the specified roles to access."""
directive @assert(is: Role!) on FIELD_DEFINITION
enum Role {
ADMIN
GUEST
USER
}
type Query {
getAllUsers: [User!] @assert(is: ADMIN)
}
type User {
name: String
}The directive, the role enum and the context, with the function that checks the directive:
import { GraphQLError } from "graphql";
/** @gqlContext */
export type Ctx = {
role: Role;
};
/** @gqlEnum */
export type Role = "ADMIN" | "USER" | "GUEST";
/**
* Indicates that a field require the specified roles to access.
* @gqlDirective assert on FIELD_DEFINITION
*/
export function requiresRole(args: { is: Role }, context: Ctx): void {
if (args.is !== context.role) {
// Using `GraphQLError` here ensures `maskErrors()` does not mask the error.
throw new GraphQLError("You do not have permission to access this field.");
}
}Then, once the schema is created, wrap each field annotated with the directive in a function that first checks the permission. Gratos writes each field's directives in its extensions, under grats.directives (see Directive annotations):
import { defaultFieldResolver, GraphQLObjectType } from "graphql";
import type { GraphQLSchema } from "graphql";
import { requiresRole } from "./directives.ts";
import type { Ctx, Role } from "./directives.ts";
/** A directive annotation, as Gratos writes it in a field's `extensions`. */
type Annotation = { name: string; args: { is: Role } };
// Wraps the `resolve` function of every field annotated with `@assert`.
export function applyRolePermissions(schema: GraphQLSchema): GraphQLSchema {
for (const type of Object.values(schema.getTypeMap())) {
if (!(type instanceof GraphQLObjectType)) {
continue;
}
for (const field of Object.values(type.getFields())) {
const annotations = field.extensions.grats as { directives?: Annotation[] } | undefined;
const assert = annotations?.directives?.find((directive) => directive.name === "assert");
if (assert === undefined) {
continue;
}
const originalResolve = field.resolve ?? defaultFieldResolver;
field.resolve = (source, args, context: Ctx, info) => {
requiresRole(assert.args, context);
return originalResolve(source, args, context, info);
};
}
}
return schema;
}Apply it to the schema before you pass it to your server, and before effectSchema if your resolvers return Effects.
Permission tokens with derived contexts
Gratos' derived contexts can implement a "permission tokens" pattern, in which a permission token is a special object that represents that its bearer has a given permission.
Assert tokens
A derived context type can make a field throw when the user lacks the required permissions. Gratos calls the derived context function as part of the field's execution, so if it throws, the field fails with that error, and access is refused.
The AssertAdminToken type, its derived context function, and a field restricted by it:
/**
* The main GraphQL context object, derived from the request/cookies.
* @gqlContext
*/
type Ctx = {
isAdmin: boolean;
};
// Use "branded types" to ensure nobody else can construct an AdminToken.
// https://egghead.io/blog/using-branded-types-in-typescript
type AdminToken = "AdminToken" & { __brand: "AdminToken" };
type AssertAdminToken = AdminToken;
/**
* @gqlContext
*/
export function adminCheck(ctx: Ctx): AssertAdminToken {
if (!ctx.isAdmin) {
throw new Error("You do not have permission to access this field");
}
return "AdminToken" as AdminToken;
}
/**
* This field will throw for any user that is not an admin. This is enabled
* simply by adding an argument typed as `AssertAdminToken`, even if it's
* unused.
*
* @gqlQueryField */
export function someField(_admin: AssertAdminToken): string {
return "You must be an admin!";
}type Query {
"""
This field will throw for any user that is not an admin. This is enabled
simply by adding an argument typed as `AssertAdminToken`, even if it's
unused.
"""
someField: String
}Maybe tokens
Permission tokens can also be used like the viewer context above: the permission token is a required parameter deep in the data layer.
Define a "maybe" derived context type, which is either the permission token, or null when the user lacks the required permissions. The field resolver then decides how to handle a user who lacks them, and the permission check is still always performed before the data layer is reached.
The two token approaches can also be combined!
/** @gqlContext */
type Ctx = {
isAdmin: boolean;
};
type AdminToken = "AdminToken" & { __brand: "AdminToken" };
type MaybeAdminToken = AdminToken | null;
/**
* @gqlContext
*/
export function maybeAdminToken(ctx: Ctx): MaybeAdminToken {
if (ctx.isAdmin) {
return "AdminToken" as AdminToken;
}
return null;
}
/** @gqlQueryField */
export function someField(admin: MaybeAdminToken): string | null {
// TypeScript ensures we somehow handle the case where `admin` is null before
// calling into the data layer.
if (admin == null) {
return null;
}
return someDataLayerFunction(admin);
}
function someDataLayerFunction(admin: AdminToken) {
return "Here is your data";
}type Query {
someField: String
}