rules

package
v0.9.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 12 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package rules checks and compiles a collection's rules (the `rules:` section of its collection.yaml): expr-lang expressions deciding, per operation, whether a caller may act on a whole document. Read rules also become backend-neutral storage filters. It knows nothing about HTTP or MongoDB.

Index

Constants

This section is empty.

Variables

Ops lists the operations in a fixed order.

Functions

func ChangedFields added in v0.8.5

func ChangedFields(before, after map[string]any) []string

ChangedFields lists the top-level user fields whose values differ between two versions of a document: what `changed()` returns in a rule, and what an event carries as `changed`.

Types

type Op

type Op string

Op is an operation a rule can allow.

const (
	Read   Op = "read"
	Create Op = "create"
	Update Op = "update"
	Delete Op = "delete"
	// Restore and Purge are the operations of a collection that soft-deletes
	// (collection.yaml): restore decides who may read the deleted documents
	// and bring them back, purge who may remove them for good. Neither is
	// covered by `write`: they are denied unless declared.
	Restore Op = "restore"
	Purge   Op = "purge"
	// Invoke is a function's invoke rule (function.yaml): it decides who
	// may call the function and sees only `user`.
	Invoke Op = "invoke"
	// Config is the read rule of a path of the realm's app configuration
	// (_realm/config/rules.yaml): it sees `user` and `now`, with no document.
	Config Op = "config"
	// Reveal is the `reveal:` of an encrypted field: whether a caller who may read a document
	// sees the field's value or null. It sees `document` (the whole plaintext) and `user`, and is
	// evaluated per document, in memory.
	Reveal Op = "reveal"
	// Trigger is the `when:` of a collection's trigger (collection.yaml): it sees the
	// document before and after a change, `changed()`, `now` (the change's time) and the
	// app configuration — and no caller, because an event has none.
	Trigger Op = "trigger"
)

type OrgsEnv added in v0.8.3

type OrgsEnv = map[string]*UserOrg

OrgsEnv is the memberships by organization id.

type Rule

type Rule struct {
	Op     Op
	Key    string // the rules key it came from: the op, or "write"
	Source string
	// contains filtered or unexported fields
}

Rule is one compiled rule.

func CompileConfig added in v0.8.2

func CompileConfig(src string, roles, consents []string) (*Rule, error)

CompileConfig compiles and checks the read rule of a path of the app configuration. It may use `user`, `now`, hasRole with the realm's roles and hasConsent with its consents; there is no document.

func CompileInvoke

func CompileInvoke(src string, roles []string, configLeaf func(string) bool) (*Rule, error)

CompileInvoke compiles and checks a function's invoke rule. It may use `user`, hasRole with the realm's roles and appConfig with the values configLeaf says exist (nil when the realm declares no app configuration); there is no document.

func CompileReveal added in v0.9.1

func CompileReveal(src string, schema Schema) (*Rule, error)

CompileReveal compiles and checks the `reveal:` of an encrypted field. It may use `document`, `user`, `now`, hasRole and the organization helpers like an update rule, but not `data`.

func CompileTrigger added in v0.8.5

func CompileTrigger(src string, schema Schema) (*Rule, error)

CompileTrigger compiles and checks the `when:` of a trigger. It may use `document` (after the change), `before` (before it), `changed()`, `now` and appConfig; `user`, `data` and the helpers that need a caller are errors, because an event has none.

func (*Rule) Allow

func (r *Rule) Allow(v Values) (bool, error)

Allow evaluates the rule. An evaluation error (for example comparing values of different types) is returned, and must be treated as a denial.

func (*Rule) AlwaysFalse added in v0.8.2

func (r *Rule) AlwaysFalse() bool

AlwaysFalse reports whether the rule is literally `false`: nobody is ever allowed.

func (*Rule) AlwaysTrue added in v0.8.2

func (r *Rule) AlwaysTrue() bool

AlwaysTrue reports whether the rule is literally `true`: it allows everyone, with or without a session, so what it guards can be cached publicly.

func (*Rule) CanAllowAnonymous added in v0.8.2

func (r *Rule) CanAllowAnonymous() bool

CanAllowAnonymous reports whether the rule may be true for a caller without credentials: false only when it is false whatever the document holds, such as `user != nil`, `hasRole(user, 'admin')` or `hasConsent(user, 'terms')`. It reads the rule's syntax tree with three values; `document` and `now` are unknown.

func (*Rule) Filter

func (r *Rule) Filter(v Values) (storage.Filter, error)

Filter turns a read rule into a storage filter for the given caller. The result is simplified: Const(true) allows every document, Const(false) none, whatever they contain.

func (*Rule) Fires added in v0.8.5

func (r *Rule) Fires(before, after map[string]any, at time.Time, config map[string]any) (bool, error)

Fires evaluates a trigger's `when:` for one change. before and after are the documents in API shape, nil when there is none (a created document has no before, a removed one no after); at is the change's cluster time and config the app configuration, for appConfig.

A missing document reads as an empty one, so `before.status != 'paid'` is true for a creation (it came from nothing). The exception is a removal: a condition that names `document` never matches it, whatever it says, because the document is gone; conditions meant for removals read `before`.

func (*Rule) References added in v0.8.5

func (r *Rule) References(name string) bool

References reports whether the rule's source names the variable (`document`, `before`).

func (*Rule) UsesConfig added in v0.8.2

func (r *Rule) UsesConfig() bool

UsesConfig reports whether the rule reads the app configuration.

func (*Rule) UsesNow added in v0.8.2

func (r *Rule) UsesNow() bool

UsesNow reports whether the rule depends on the time of the request.

func (*Rule) UsesOrgs added in v0.8.3

func (r *Rule) UsesOrgs() bool

UsesOrgs reports whether the rule reads the caller's memberships: a helper or `user.orgs`.

type Schema

type Schema struct {
	// DocumentField reports whether a dot path exists on stored documents
	// (schema fields plus id and _meta fields).
	DocumentField func(path string) bool
	// DataField reports whether a dot path exists in request bodies.
	DataField func(path string) bool
	// ScalarField reports whether a document path holds a single value:
	// declared with types that don't include "array", and not reached
	// through an array. Read rules may only compare such fields, because
	// MongoDB compares arrays element by element.
	ScalarField func(path string) bool
	// ArrayField reports whether a document path is declared as an array
	// (and not reached through another array), for `value in document.path`.
	ArrayField func(path string) bool
	// DateField reports whether a path is stored as a date (x-backd-store:
	// date): its value is a time in rules, comparable with `now`. May be nil.
	DateField func(path string) bool
	// EncryptedField reports whether a document path is stored encrypted: a read rule, which is
	// applied inside the query, can't compare it. May be nil.
	EncryptedField func(path string) bool
	// SearchableField reports whether an encrypted path has a blind index: a read rule may then
	// compare it with == or `in`, nothing else. May be nil.
	SearchableField func(path string) bool
	// Roles are the role names declared in realm.yaml.
	Roles []string
	// Consents are the consent names declared in realm.yaml, for hasConsent.
	Consents []string
	// ConfigLeaf reports whether a dot path is a value of the realm's app
	// configuration, for appConfig; nil when the realm declares none.
	ConfigLeaf func(path string) bool
	// OrgRoles are the organization roles declared in realm.yaml, for hasOrgRole; nil when
	// the realm doesn't enable organizations.
	OrgRoles []string
	// InOrgs says the collection's documents can belong to an organization, so rules may name
	// document._meta.org (and data._meta.org on create).
	InOrgs bool
	// TeamRoles are the team roles declared in realm.yaml, for hasTeamRole.
	TeamRoles []string
	// InTeams says the collection's documents can belong to a team, so rules may name
	// document._meta.team (and data._meta.team on create).
	InTeams bool
}

Schema describes what the rules of one collection may refer to.

type Set

type Set struct {
	File string
	// contains filtered or unexported fields
}

Set is a collection's compiled rules. A nil rule denies the operation.

func Parse

func Parse(doc map[string]string, schema Schema) (*Set, []error)

Parse compiles and checks the `rules:` section of a collection's collection.yaml: a mapping of operation (read, create, update, delete, restore, purge, or write for the three that change a document) to an expression.

func (*Set) For

func (s *Set) For(op Op) *Rule

For returns the rule of op, or nil if none allows it.

func (*Set) UsesConfig added in v0.8.2

func (s *Set) UsesConfig() bool

UsesConfig reports whether any rule of the set reads the app configuration.

func (*Set) UsesOrgs added in v0.8.3

func (s *Set) UsesOrgs() bool

UsesOrgs reports whether any rule of the set reads memberships.

type User

type User struct {
	ID            string   `expr:"id"`
	Email         string   `expr:"email"`
	EmailVerified bool     `expr:"email_verified"`
	Roles         []string `expr:"roles"`
	// MFA says the session used a second factor; Methods are how it was created: the
	// first factor and, with MFA, "totp" or "recovery". API keys are ["key"].
	MFA     bool     `expr:"mfa"`
	Methods []string `expr:"methods"`
	// Consents maps each consent the user holds to the version they accepted.
	Consents map[string]string `expr:"consents"`
	// Orgs are the memberships that count, by organization id (design/organizations.md §6):
	// filled in only for a rule that uses them.
	Orgs map[string]*UserOrg `expr:"orgs"`
}

User is the signed-in user as rules see it; nil for anonymous callers.

type UserOrg added in v0.8.3

type UserOrg struct {
	Roles []string `expr:"roles"`
	Teams []string `expr:"teams"`
	// TeamRoles are the team roles held in force, by team id.
	TeamRoles map[string][]string `expr:"team_roles"`
	Claims    map[string]any      `expr:"claims"`
}

UserOrg is one membership that counts: the roles the caller holds in the organization (direct, default and through teams), the teams, the team roles held within them and the organization's claims.

type Values

type Values struct {
	User     *User          // nil for anonymous callers
	Document map[string]any // stored document (read, update, delete)
	Data     map[string]any // incoming document (create, update)
	Now      time.Time
	// Orgs are the caller's memberships that count, for the organization helpers; only filled
	// in when a rule reads them (Rule.UsesOrgs).
	Orgs map[string]*UserOrg
	// Before is the document before the change, and Event says this is a trigger's `when:`:
	// `changed()` then compares Before with Document (the document after).
	Before map[string]any
	Event  bool
	// Config is the app configuration, by dot path of each value, for appConfig();
	// only filled in when a rule reads it.
	Config map[string]any
}

Values are what a rule is evaluated with.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL