The authz package
Centralized authorization in Grit and how to use it.
The last lesson fixed one IDOR by hand. Doing that in every handler is how the second one gets forgotten, so Grit puts the answer in one package: internal/authz. This lesson is a tour of what is in it and, more usefully, which of the four questions each part answers.
Authorization is four different questions
Most arguments about access control are really people answering different questions with the same word. Separate them and the package stops looking like a grab bag:
- May this user touch widgets at all? That is a permission, it comes from the route's middleware, and it never looks at a row.
- Is this their row? That is ownership, and it is a column.
- Is this row in a state where that is allowed? A draft may be edited and a published post may not. That is a policy, and it needs the row and the user together.
- Can this admin grant a permission they do not hold? That is the ceiling, and forgetting it is how a junior admin promotes themselves.
A rule that cannot be expressed as one of those four is usually two rules wearing a coat. Split it before you write it.
Ownership: MustOwn and the 404
The ownership helpers load the row and check the owner in one call. Note the status code:
func (h *NoteHandler) Update(c *gin.Context) {var note models.Note// Loads by id AND checks the owner. On any failure it has already// written the response, so the handler just returns.if err := authz.MustOwn(c, h.DB, ¬e, c.Param("id")); err != nil {return}// From here the row is theirs. Ordinary handler code.}
MustOwn answers a failure with 404, not 403. That is deliberate, and it is the part people change back without thinking. A 403 says "this row exists and is not yours", which is a yes/no oracle: an attacker walks the id space and learns exactly which records exist before they ever break in. A 404 says nothing. Same code, same user experience for the legitimate caller, and no free map of your database.
The variants exist because admin screens call the same endpoints:
MustOwn, strict ownership.MustOwnUnlessAdmin, the same check with an ADMIN bypass. Without it an administrator opening the admin panel sees only the rows they personally created, which reads as a bug and gets fixed by removing the check entirely.ScopeOwned(ctx, query, column), for lists. It adds the owner filter to a query rather than checking one row.
ScopeOwned returns q.Where(...), a statement clause. That matters: a clause is carried into Find, Scan and Rows alike. Scoping implemented as a GORM callback instead is easy to get wrong, because Scan does not go through the query callback.
Permissions: the catalogue, not a string
Permissions are generated into a catalogue rather than typed as strings at each call site, because a typo in a permission string fails open: Can(db, user, "psots.delete") is simply false for everyone, including the people who should be denied loudly.
authz.Catalog() // every module and its permissionsauthz.Keys() // every permission key, flatauthz.Can(db, userID, "posts.delete")// does this user hold itauthz.Granted(grants, "posts.delete")// against a list you already loadedauthz.Expand(grants) // wildcards resolved to concrete keys
Policies: the rule that needs the row
Neither a permission nor an owner column can say "a post may be edited while it is a draft and not after it is published". That is a policy: a named ability with a rule that receives the actor and the record.
authz.Define("post.edit", func(ctx context.Context, record any) authz.Decision {post, ok := record.(*models.Post)if !ok {return authz.Deny("not a post")}if post.Status == "published" {return authz.Deny("a published post is not editable")}if !authz.Owns(ctx, post) {return authz.Deny("not yours")}return authz.Allow()})
Then authz.Allows(ctx, "post.edit", &post) at the call site, or Inspect when you want the reason to put in the response. The reason is worth having: "forbidden" teaches a user nothing, and "a published post is not editable" stops a support ticket.
The ceiling: the one people forget
An admin screen that lets somebody assign permissions must stop them assigning permissions they do not themselves hold. Otherwise the lowest-privileged admin account is a route to the highest, in two clicks and with a full audit trail showing it was allowed.
// Everything in requested that the caller does not hold.if over := authz.CannotGrant(c, requested); len(over) > 0 {respond.Fail(c, respond.CodeForbidden,"You cannot grant: "+strings.Join(over, ", "))return}
Privilege escalation almost never looks like an attack in the logs. It looks like an administrator using an administration screen exactly as designed, which is why the check has to be in the code rather than in the reviewer's head.
Which to reach for
Can they use this endpoint at all? permission, in the route middlewareIs this their row? MustOwn / ScopeOwnedIs the row in a state that allows a policy: authz.Define + Allowsit, or does the rule involve boththe user and the record?Are they handing out power they authz.CannotGrantdo not have?
Try it
Take one endpoint in your project that lists rows and one that updates a single row.
One. Put ScopeOwned on the list and MustOwn on the update.
Two. Sign in as a second user and request the first user's row by id. Write down the status code you get.
Three. Change MustOwn to return 403 instead, repeat, and explain in one sentence what an attacker now learns that they did not before.
Quick check
Spot a typo? Have an idea?
Help us improve this lesson. One click opens a GitHub issue with the lesson URL pre-filled, suggest clearer wording, report a bug, or request more depth. The course keeps improving thanks to learners like you.
Suggest an improvement on GitHub