Security

Roles & Permissions

Grit guards routes by permission, not by role name. Roles are named bags of permissions you edit at runtime, so adding a role never means editing routes and redeploying.

The shape of a permission

A permission key is <resource>.<action>, where the action is one of create, view, edit or delete:

products.create
users.delete
uploads.view

Grants may use wildcards:

* every permission (superuser)
products.* every action on products
*.view view on every resource

Roles hold grants

Three roles are seeded on first migrate: ADMIN (holds *), EDITOR (content) and USER (no administrative permissions). Seeding is idempotent and never overwrites grants you have edited.

Grants are stored as authored. If a role holds products.* and you later add a new action to that resource, the role picks it up automatically — nothing to re-grant.

Guarding a route

RequireRole accepts role names, permissions (prefixed perm:), or both. Access is granted if any argument matches:

internal/routes/routes.go
// Permission-based (preferred)
staff.DELETE("/products/:id",
middleware.RequireRole("perm:products.delete"),
productHandler.Delete)
// Mixed: an ADMIN passes, and so does any role granted users.edit.
staff.PUT("/users/:id",
middleware.RequireRole("ADMIN", "perm:users.edit"),
userHandler.Update)
// Role-only still works. Nothing existing had to change.
admin.Use(middleware.RequireRole("ADMIN"))

Staff routes: how a custom role reaches the admin API

routes.go has two groups for the admin API, and which one a route is on decides who can reach it:

  • staff admits anyone who holds at least one permission, and every route on it names the permission it needs. Users, roles, the audit log, jobs, backups, blogs and the dashboards live here, so a role granted users.view can list users and nothing more.
  • admin requires the ADMIN role and nothing less. Routes that name no permission stay here (SSO connections, form sharing, writing settings, changing feature flags), and so does anything a plugin adds, so a route that forgets its permission fails closed.

Generated resources follow the same split. Reading and writing a record is on the protected group; delete and bulk are on the staff group and ask for <resource>.delete, so a role can be allowed to delete products without being made an admin.

internal/routes/product_routes.go
m.Staff.DELETE("/products/:id", middleware.RequireRole("ADMIN", "perm:products.delete"), h.Delete)
m.Staff.POST("/products/bulk", middleware.RequireRole("ADMIN", "perm:products.delete"), h.Bulk)

Before v3.220.0 there was only the admin group. Every route on it sat behind the ADMIN role, so the perm: guards on them never ran, and a custom role was refused by every admin endpoint whatever it was granted. The admin panel showed an EDITOR pages the API then refused.

Inside a handler, use authz.Can for conditional logic:

if authz.Can(h.DB, userID, "products.delete") {
// show the destructive action
}

Generated resources register themselves

grit generate resource Product adds products.create|view|edit|delete to the catalog automatically, so a new resource is grantable immediately. grit remove resource takes them back out. Hand-written permissions belong in coreModules() in internal/authz/permissions.go; machine-written entries live in generatedModules() between the marker comments.

Policies: a rule about one row

A permission answers "may this role touch this resource at all", and it is checked before the handler runs. It cannot answer anything that depends on the record: editable while it is a draft, approvable by anyone but the person who raised it, deletable only once archived. Those are policies, and they live in internal/policies.

grit generate resource Invoice writes internal/policies/invoice.go with the three abilities the service checks, every one commented out. A rule you do not write is not a rule that denies, so a project that ignores the package behaves exactly as it did before it had one.

internal/policies/invoice.go
func registerInvoices() {
authz.Define("invoices.update", func(actor authz.Actor, record any) authz.Decision {
item, ok := record.(*models.Invoice)
if !ok {
// Another model reached this rule, which is a wiring mistake
// rather than a refusal. Let the ability meant for it decide.
return authz.Allow()
}
if item.Status == "paid" {
return authz.Deny("This invoice is paid, so it is corrected with a credit note rather than edited")
}
return authz.Allow()
})
}

The three abilities are <resource>.read, <resource>.update and <resource>.delete. The service consults them around the row it loaded, so they hold on every path into that row: the REST handler, a background job, a CLI command and a test all go through the same service method. The reason a rule gives is the message the client receives, with a 403.

An ADMIN is not exempt by default. That is deliberate: these rules are about the state of a record rather than the rank of a user, and "this invoice is already paid" is as true for an administrator as for anybody else. authz.Before adds an exemption for the abilities that want one.

Bulk actions and the editable grid ask per row. A policy that refuses twelve of the selected rows refuses the whole action rather than applying nine of them, because a bulk action that reports twelve and changed nine is worse than one that says no and names what it would not touch.

Before v3.451.0, no rule ran

policies.Register() had no call site. The package was generated, documented and injected into correctly, and nothing ever called the function that defines the rules, so every rule anybody wrote was registered into a map that stayed empty. grit upgrade adds the call. If you wrote a rule before that version, upgrade and then check it actually refuses what you expect, because until now it did not.

Managing roles

The admin panel has a Roles & permissions screen under System (/system/roles): create roles, tick permissions in a tree with a CRUD matrix, copy permissions from an existing role, and see how many users hold each one.

Built-in roles can have their permissions edited, but they cannot be renamed or deleted — routes and the upgrade path resolve them by name. This is enforced by the API, not just hidden in the UI.

In the frontend

The API returns the caller's permissions already expanded, so the client never re-implements wildcard matching:

const { can, isSuper } = usePermissions()
{can("products.delete") && <DeleteButton />}
{can("products.*") && <ProductsMenu />}
Hiding UI is not access control

can() is a convenience for hiding buttons and nav items. It is not a security boundary — anyone can call your API directly. Always guard the route as well.

The panel is not sent to a stranger

The same point, one layer out. Every admin page needs a session, and until v3.459.0 that was decided in the browser: the page arrived, React mounted, asked /api/auth/me who you were, and on a 401 replaced the route with the login. Correct, and it meant the panel was downloaded and run for somebody who had never signed in.

A generated project gates it before that. A Next.js admin app has apps/admin/proxy.ts; a panel inside a web app is covered by that app's proxy.ts, which carries the same check as adminGate; a Vite admin does it in its router's beforeLoad.

// apps/admin/proxy.ts: the pages a signed-out visitor may reach.
const PUBLIC_PATHS = [
"/login", "/sign-up", "/forgot-password",
"/reset-password", "/verify-email", "/magic-link", "/callback",
];
// Everything else needs one of two cookies, and neither holds a secret:
// grit_admin_session written on the admin's origin after a sign-in
// grit_signed_in set by the API, when the API shares this host

The matcher denies by default, so a page you add later, with grit generate or a plugin, is gated the day it lands. Add a page a visitor must reach without signing in and add its path to PUBLIC_PATHS, or it will redirect to the login.

The gate is not access control either

Those cookies are markers. Anyone can write one from the console, and what it buys them is the HTML of a panel whose every request the API refuses. The gate decides what gets sent; the API decides what is allowed. Do not put a check here and nowhere else.

Upgrading an existing app

Nothing breaks, by construction:

  • every existing RequireRole("ADMIN") call site keeps working — the signature did not change
  • if a user has no role assignment yet, grants resolve from the legacy users.role string, so admins do not lose access
  • changing a user's role in the admin keeps the assignment in step, so the dropdown still takes effect

Adopt permissions route by route: add a perm: argument alongside the role name, then drop the role name once every caller has a role that grants it.

A project scaffolded before v3.220.0 has no staff group, and grit upgrade does not restructure routes.go, so it says so instead. Its generated deletes stay ADMIN-only until you add the group. To add it, create the group beside the admin one, move each route you want grantable onto it with the permission it needs, and hand it to generated resources:

internal/routes/routes.go
staff := v1.Group("")
staff.Use(middleware.APIKeyOrAuth(db, middleware.Auth(db, authService)))
staff.Use(middleware.RequireStaff())
{
staff.GET("/users", middleware.RequireRole("ADMIN", "perm:users.view"), userHandler.List)
}
mountResources(&Mount{
// ...
Admin: admin,
Staff: staff,
})

grit upgrade does not rewrite internal/middleware/auth.go or internal/routes/resources.go either. Copy RequireStaff and RequirePermissionFor from a new project into the first, and add Staff *gin.RouterGroup to the Mount in the second. Regenerate a resource afterwards and its delete and bulk routes move to the staff group.

Multiple roles per user

Assignment is many-to-many. The admin's user form edits a single primary role; assign several with:

PUT /api/users/:id/roles
{ "role_ids": ["...", "..."] }

A user's grants are the union of every role they hold.