Authorization in Go: policies answer 403, row rules answer 404
Authorization asks two questions that look like one. "May this user edit invoices" is about the user. "May this user edit invoice 8821" is about the relationship between a user and a row. Answering only the first is the most common serious vulnerability in web applications, and it is exploited by changing a number in a URL.
This is how to answer both in Go: where each check belongs, which status code each failure returns, and why that choice is a security decision rather than a stylistic one.
18 min read. Commands and output last run against Grit v3.560.0.
What you will have at the end
A permission check that is declared on the route and a scope that is part of the query.
A defensible rule for 401, 403 and 404, including the case where 403 leaks information you were trying to protect.
A way to find the write paths that were built without the rule.
Two questions, two mechanisms
"May this user delete invoices?" a property of the user→ a permission, checked on the route, before the handler runs→ failure is 403 Forbidden"May this user delete invoice 8821?" a property of the pair→ a scope in the query, or a policy that sees the row→ failure is 404 Not Found
The first is cheap: it needs the token and nothing else, so it belongs in middleware and never reaches your handler. The second needs the row, so it cannot happen before the handler, and that is exactly why it gets skipped.
The vulnerability, concretely
// The route is guarded. The user genuinely has invoice.write.invoices.PATCH("/:id", middleware.Require(authz.InvoiceWrite), h.Update)// And the handler is wide open.func (h *InvoiceHandler) Update(c *gin.Context) {var inv models.Invoiceif err := h.db.First(&inv, c.Param("id")).Error; err != nil {respond.NotFound(c)return}// ... applies the change to whoever's invoice that was}
Nothing here is a mistake in isolation. The middleware correctly answered the question it was asked. The handler correctly loaded the record it was given. Nobody asked whether the two belong together.
The exploit needs no tooling: increment the id. This class, insecure direct object reference, is consistently near the top of the OWASP list, and it survives code review because the dangerous version and the safe version differ by one clause.
Scope in the query, so the mistake fails closed
There are two shapes, and the difference is what happens when somebody forgets.
// Shape A: fetch, then check.inv, err := repo.ByID(ctx, id)if inv.OrganisationID != orgID {return ErrForbidden}// Forget the second statement and the row is returned. The code still// compiles, the tests still pass, and the bug is invisible.// Shape B: the scope is an argument.inv, err := repo.ByID(ctx, orgID, id)// Forget the argument and it does not compile.
Prefer B everywhere. Not because developers are careless, but because over a few years and several people, the version that fails closed is the one that is still correct.
// Every method takes the scope. There is no unscoped variant to reach// for in a hurry, which is the point: the safe path must also be the// convenient one.func (r *InvoiceRepo) ByID(ctx context.Context, orgID, id uint) (*models.Invoice, error) {var inv models.Invoiceerr := r.db.WithContext(ctx).Where("id = ? AND organisation_id = ?", id, orgID).First(&inv).Errorif errors.Is(err, gorm.ErrRecordNotFound) {return nil, ErrNotFound // deliberately not ErrForbidden}if err != nil {return nil, fmt.Errorf("load invoice %d: %w", id, err)}return &inv, nil}
A GORM scope keeps it from being retyped
A small named scope makes the rule one token, which raises the chance it is applied and makes an audit a grep for a single identifier.
func OwnedBy(orgID uint) func(*gorm.DB) *gorm.DB {return func(db *gorm.DB) *gorm.DB {return db.Where("organisation_id = ?", orgID)}}r.db.Scopes(OwnedBy(orgID)).Find(&invoices)
403 or 404, and why it is not a style question
A 403 says: this exists, and you may not have it. For a row outside somebody's scope that sentence gives away the first half for free.
GET /api/invoices/8820 → 404 no such invoiceGET /api/invoices/8821 → 403 there IS an invoice 8821GET /api/invoices/8822 → 404An attacker now knows exactly which ids are real, how many customers youhave, and roughly how fast you are growing. None of that required asingle successful request.
The rule, stated plainly:
- 401 when there is no valid credential. Sign in.
- 403 when the identity is known and the kind of action is not allowed. "Viewers cannot delete." Safe to admit: it is a property of the role, not of the data.
- 404 when the record is outside the caller's scope. The honest answer is that there is no such invoice as far as you are concerned, and it is also the answer that reveals nothing.
A useful consequence: if the scope lives in the query, you get this for free. The row does not come back, the repository returns ErrNotFound, and the handler answers 404 without anybody writing a rule about information disclosure.
The timing says it too
Returning the same status is not enough if the two paths take measurably different time. A scoped query that returns nothing in two milliseconds, against a path that loads the row and then runs a policy in thirty, is an oracle for anybody with a stopwatch. It matters most on authentication; it is worth knowing about here.
When the rule needs the row
Some rules are not expressible as a scope, because they depend on the record's state or on the relationship between it and the user.
// A policy takes both sides and returns a decision. Keep them in one// package, name them for the action, and test them directly: they are// the most security-relevant functions in the codebase and the cheapest// to test, because they take two structs and return a bool.func CanVoid(u *models.User, inv *models.Invoice) Decision {switch {case inv.OrganisationID != u.OrganisationID:// Not theirs at all. Say nothing about it.return Deny404case inv.Status == models.InvoicePaid:// Theirs, and the rule refuses. Explaining this is useful and// leaks nothing they did not already know.return DenyReason("a paid invoice cannot be voided")case !authz.Can(u.Role, authz.InvoiceVoid):return Deny403default:return Allow}}
The three outcomes matter. A policy that returns a boolean forces the caller to invent a status code, and the caller will choose 403, which is the leaking answer. Returning the decision keeps the information choice next to the rule that knows what is sensitive.
Postgres row-level security, as a second layer
RLS moves the scope into the database, so even a query that forgot the clause returns nothing. It is a genuine defence in depth and it is not a replacement for the application rule.
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;CREATE POLICY org_isolation ON invoicesUSING (organisation_id = current_setting('app.org_id')::bigint);
The cost is real. Every connection must set app.org_id, which means every checkout from the pool, and a connection that is reused without setting it sees nothing or sees the wrong tenant. Background jobs, migrations and admin tooling each need a deliberate answer. Worth it when a cross-tenant leak would end the business; too much machinery when it would not.
The write paths nobody checked
Getting the single-record handler right is the easy part. The failure that actually happens is a second way into the same table, built later, by somebody solving a different problem.
- Bulk edit. A list of ids and a patch. If the ids are not filtered by the scope, it is an unscoped write with a convenient batch interface.
- CSV export. Frequently written against a reporting query that somebody composed separately.
- Import. Rows arrive with ids or with foreign keys, and an unchecked foreign key attaches your record to another tenant's parent.
- Search. Often hits a separate index that was populated without the tenant column.
- Background jobs. They run with no request and therefore no user, so every scope has to be passed explicitly in the payload, and it is easy to pass none.
- The admin panel. Usually allowed to cross tenants on purpose, which means the permission check there is doing all the work.
A comment claiming the scope is applied is not the scope
One bulk-edit endpoint in this project went eight months unscoped behind a comment saying it reused the list query's filtering. It did not. When you add a new way into a table, the question is not whether the code works but whether it carries the same rule, and the only way to answer it is to read the query.
Test the refusals, and make one fail
A test suite that only covers the allowed path proves nothing about authorization. The cases worth writing are the ones nobody would report if they silently worked.
func TestInvoiceScoping(t *testing.T) {a := seedOrg(t, "org-a")b := seedOrg(t, "org-b")inv := seedInvoice(t, b) // belongs to the OTHER organisationfor _, tc := range []struct {name, method, path stringwant int}{{"read", "GET", "/api/invoices/" + inv.ID, http.StatusNotFound},{"update", "PATCH", "/api/invoices/" + inv.ID, http.StatusNotFound},{"delete", "DELETE", "/api/invoices/" + inv.ID, http.StatusNotFound},{"void", "POST", "/api/invoices/" + inv.ID + "/void", http.StatusNotFound},} {t.Run(tc.name, func(t *testing.T) {res := request(t, tc.method, tc.path, as(a.Owner))// 404 and not 403: a 403 would confirm the invoice exists.require.Equal(t, tc.want, res.Code)})}}func TestListNeverLeaksAnotherOrg(t *testing.T) {a, b := seedOrg(t, "a"), seedOrg(t, "b")seedInvoices(t, b, 20)res := request(t, "GET", "/api/invoices?page_size=100", as(a.Owner))require.Equal(t, http.StatusOK, res.Code)require.Empty(t, decodeList(t, res), "org A must see none of org B's rows")}
Then do the thing that actually validates the test: remove the scope from the repository and confirm these go red. A test that cannot fail is a test that is not testing, and authorization tests are unusually prone to passing for the wrong reason, because an empty result and a correctly-denied result look identical.
How a generated project enforces it
Scoping is a property of the resource rather than something each endpoint remembers:
$grit generate resource Invoice --fields "number:string,total:money" --owned-by organisation
That puts the scope in every generated query, including the list, the detail, the bulk actions and the export, and returns 404 rather than 403 for an out-of-scope row. Per-resource policies live in internal/policies for the rules that need the record.
There is also --confidential, for a resource an administrator must not read either, which is a stricter thing than ownership and deliberately cannot be granted by the role system.
grit doctor reads the static route table in internal/access and reports a route with no guard, which catches the endpoint added in a hurry. The authorization reference covers the generated rules.
Frequently asked questions
- Is 404 instead of 403 not just security through obscurity?
- No, because it does not replace a control, it removes a disclosure. The access control is the scope in the query and is unchanged either way. What differs is whether the response confirms that a given id exists, which is information an attacker can accumulate across thousands of requests. Returning 404 costs nothing and tells them nothing.
- Should I use UUIDs instead of sequential ids?
- They stop enumeration, which is worth something, and they are not authorization: a UUID that leaks through a shared link, a log or a referrer is still a valid id. Use them to avoid publishing your growth rate in every URL, and scope every query regardless.
- Row-level security or application-level scoping?
- Application scoping always, because it is where the logic is readable and testable. RLS in addition when a cross-tenant leak would be catastrophic, as a second layer that catches the query somebody wrote without the clause. The cost is that every connection must carry the tenant setting, and every job, migration and admin tool needs a deliberate answer to that.
- Where should the check live: middleware, handler or service?
- Permissions in middleware, because they need only the token and should never reach your code. Scope in the repository, because it has to be in the query. Policies in the service, because they need the loaded record and the business rules around it. The anti-pattern is scattering all three through handlers, where no one place answers what the policy is.
Next steps
- Roles and permissions explainedThe first half of the problem, in plain terms.
- Multi-tenant SaaS in GoWhere the scope comes from, and the three ways to isolate tenants.
- Authorization referenceGenerated scoping, policies, confidential resources and the route table.
- The OWASP Top 10 in GoThis is the first risk on the list. Here are the other nine.
