Skip to main content

Global filters

A global filter adds a condition to every query of a model. It follows the model into joins, Include, Has, subqueries and bulk writes. ant builds it when the query runs, so it can read values from the request's context.

Declare a filter​

b.Filter takes a name and a function from the context to a condition. This model filters by tenant and hides secret documents:

type Doc struct {
ID int64
TenantID int64
Secret bool
Title string
}

func (Doc) Configure(b *ant.ModelBuilder[Doc]) {
b.Filter("tenant", func(ctx context.Context) ant.Cond {
tenant, ok := ctx.Value(tenantKey{}).(int64)
if !ok {
return ant.FailedCond(errors.New("no tenant in context"))
}

return ant.Eq(&Docs.TenantID, tenant)
})

b.Filter("public", func(context.Context) ant.Cond {
return ant.Eq(&Docs.Secret, false)
})
}

type tenantKey struct{}

var Docs = ant.Fields[Doc]()

ant.FailedCond fails the query with your error. Use it when the context has no tenant, since a filter that returned no condition would show every tenant's rows.

Query as a tenant​

one := context.WithValue(ctx, tenantKey{}, int64(1))

docs, err := db.Docs.Where(ant.Like(&Docs.Title, "A%")).All(one)
// SELECT ... FROM "docs"
// WHERE "docs"."title" LIKE $1 AND "docs"."tenant_id" = $2 AND "docs"."secret" = $3
// -- $1 = "A%", $2 = 1, $3 = false
func tenantMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tenant := tenantOf(r)

next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), tenantKey{}, tenant)))
})
}

Filters apply to writes​

Bulk updates and deletes get the same conditions:

n, err := db.Docs.Where(ant.Eq(&Docs.Title, "x")).Delete(one)
// DELETE FROM "docs"
// WHERE "docs"."title" = $1 AND "docs"."tenant_id" = $2 AND "docs"."secret" = $3

Switch filters off​

IgnoreFilters switches off the named filters for one query, or all of them when you name none. Include queries keep their own filters.

withSecrets, err := db.Docs.IgnoreFilters("public").All(one)
// SELECT ... FROM "docs" WHERE "docs"."tenant_id" = $1

everything, err := db.Docs.IgnoreFilters().All(ctx)
// SELECT ... FROM "docs"

Search for IgnoreFilters in code review: it is how rows leak across tenants.

A convenience, not a security boundary

ant.Raw and IgnoreFilters bypass filters. For a harder boundary, PostgreSQL's row-level security enforces the same rule in the database. See multi-tenancy.

See the SQL with a context​

ToSQL has no context, so it shows a query without filters. ToSQLContext runs the filters:

text, args, err := db.Docs.Query().ToSQLContext(one)