Documentation
¶
Overview ¶
Package authz decides what an authenticated caller may do.
It holds two mechanisms that are deliberately independent, because they answer different questions and a deployment may want either alone:
- Per-resource access, in this file. An ACL names an owner, some viewers and some contributors; RoleOf resolves a caller to a Role against it; Allows says which actions a role may take. Authorize is the two composed.
- Service-wide grants, in rules.go. A set of named Rules maps identity patterns, SPIFFE path segments, certificate fields and OIDC claims onto the Admin bit and the right to proxy — replacing the exact-match identity lists that scale no better than the token table purser exists to retire. The set is a union with no deny rules, so its meaning does not depend on its order.
The vocabulary is the consuming service's ¶
purser supplies the mechanism and stays out of the nouns. There is no "session" here, and no daemon: an ACL guards a *resource*, whatever the service calls it, and the actions are the four verbs plus the scope-wide one. A service maps its own vocabulary onto them and keeps its own names in its own audit records:
// in the consuming service
type Action int // session.read, session.write, …
func Authorize(c purser.Caller, a Action, acl authz.ACL) bool {
return authz.Authorize(c, a.authzAction(), acl)
}
That indirection is the point. Role names and ACL shapes are policy the service owns; what purser owns is that the matrix is enforced the same way everywhere, and that a caller with no identity is nobody.
Deny by default ¶
Every path through this package that does not recognise its input denies: an unknown Action — except to RoleAdmin, which is defined as everything, including verbs added after this binary was built — a Role outside the ones defined here, a caller whose Identity is empty or is the anonymous one purser hands an unauthenticated request. A matcher assembled from configuration that never got set closes the door rather than opening it — including MatchAll with no matchers, which is why this package supplies no way to spell "everyone" at all.
The package is stdlib-only, so a consumer that only wants the authorization matrix links nothing else.
Index ¶
- func Allows(role Role, action Action) bool
- func Authorize(c purser.Caller, action Action, acl ACL) bool
- func WithRules(a authn.Authenticator, rules *Rules) (authn.Authenticator, error)
- type ACL
- type Action
- type Matcher
- func MatchAll(matchers ...Matcher) Matcher
- func MatchAnyOf(matchers ...Matcher) Matcher
- func MatchEmailDomain(domain string) Matcher
- func MatchIdentity(identities ...string) Matcher
- func MatchLabel(key string, values ...string) Matcher
- func MatchNot(m Matcher) Matcher
- func MatchPathPrefix(key string, segments ...string) Matcher
- func MatchPathSegments(key string, segments ...string) Matcher
- type Role
- type Rule
- type Rules
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Allows ¶
Allows reports whether role may take action:
| Action | Admin | Owner | Contributor | Viewer | None | |------------|-------|-------|-------------|--------|------| | List | ✓ | ✓ | ✓ | ✓ | ✓ | | Read | ✓ | ✓ | ✓ | ✓ | | | Write | ✓ | ✓ | ✓ | | | | Admin | ✓ | ✓ | | | | | ScopeAdmin | ✓ | | | | |
It is exported for the service that resolves roles some other way — from a group membership service, or a role already recorded on the resource — and wants the same matrix applied to the result. That is also why the range check below is not redundant: a Role reaching this function need not have come from RoleOf. A service persisting roles as integers and reading one back from a newer peer, a corrupted row, or an off-by-one in its own mapping table would otherwise find that any value above RoleAdmin satisfies every >= comparison here and authorizes everything short of the scope.
func Authorize ¶
Authorize reports whether c may perform action against the resource guarded by acl. It is Allows(acl.RoleOf(c), action), which is the whole of the decision for a service that keeps its ACLs in this shape.
func WithRules ¶
func WithRules(a authn.Authenticator, rules *Rules) (authn.Authenticator, error)
WithRules returns an Authenticator that applies rules to every Caller a resolves. It is what connects a rule set to a running surface: without it, Rules is data nothing consults.
auth, err := bearer.New(bearer.Options{Users: users})
rules, err := authz.NewRules(
authz.Rule{
Name: "platform-admins",
Match: authz.MatchLabel("group", "platform-oncall"),
Admin: true,
},
authz.Rule{
Name: "chat-bridge",
Match: authz.MatchIdentity("sa:slack-bot"),
Proxy: true,
},
)
auth, err := authz.WithRules(auth, rules)
caller, err := httpmw.NewCaller(httpmw.CallerOptions{Authenticator: auth, Enforce: true})
Three things it does, and one it deliberately does not:
- A successful Authenticate has its Caller passed through Rules.Apply, so the Admin bit reflects policy rather than whatever the credential itself carried.
- CanProxyAs is the union of the rules and whatever the wrapped authenticator already permitted, so a deployment moving from bearer.Options.ProxyIdentities to rules can run both during the migration and lose nobody.
- An asserted identity resolved through authn.IdentityLookup gets the same treatment, so proxying to an identity does not silently hand it a different set of grants than authenticating as it.
- It never grants anything to a caller nothing authenticated. Two things enforce that, because one of them is not enough. Rules themselves refuse the zero Caller and purser.AnonymousIdentity; and WithRules refuses outright an authenticator that reports purser.AuthSourceAnonymous, since applying policy to an authenticator that verifies nothing means granting the Admin bit to requests that presented no credential — authn.Anonymous resolves every one of them to a Caller that is not zero and would otherwise be matched like any other.
Preserving the optional interfaces ¶
authn's optional extensions are discovered by type assertion, so a decorator that implements too few of them silently downgrades the surface — and one that implements too many does the same. Both directions have teeth here: a wrapper that dropped authn.IdentityLookup would make httpmw take every asserted identity at face value instead of resolving it against the table, and a wrapper that added it to an authenticator with no table would make httpmw reject every assertion as unprovisioned.
So the returned value implements exactly the extensions a implements, plus authn.AuthenticatorWithProxy, which rules may grant on their own — and which reads the same as not implementing it when neither the rules nor a permit anyone to proxy.
Types ¶
type ACL ¶
type ACL struct {
// Owner is the identity with full control of the resource.
Owner string
// Viewers may read.
Viewers []string
// Contributors may read and write, but may not change this ACL.
Contributors []string
}
ACL is who may do what to one resource.
The zero value grants nothing to anyone but an Admin caller. That is the safe reading of a resource created before the service had an authorization story, or of a struct somebody forgot to populate: such a resource is administrator-only until an owner is assigned, rather than everyone's.
Membership is exact identity equality, not pattern matching. A caller named in several lists gets the most capable role, so widening an entry can never narrow access.
func (ACL) RoleOf ¶
RoleOf resolves c's role against acl.
A caller with no identity is RoleNone whatever the ACL says. This is the case worth stating: a zero purser.Caller has an empty Identity, an ACL that was never populated has an empty Owner, and comparing them for equality would make a half-initialized struct grant ownership of a resource to a request that never authenticated. The same reasoning applies to the Admin bit — a Caller carrying Admin with no identity did not come from an authenticator, since authn.Authenticator forbids returning an identity-less Caller alongside a nil error, so it is treated as the accident it is.
type Action ¶
type Action int
Action is a verb a caller may attempt against a resource. The set is small on purpose: finer scoping — per-field, per-sub-resource — is the consuming service's, layered on top of these.
const ( // ActionList is enumerating the resources of a collection. It is // always permitted, including to a caller with no identity: the // handler is expected to filter the result to what the caller may // actually read. Hiding the existence of unreadable resources is // what keeps a listing from leaking activity patterns, and a // listing that 403s tells the caller the collection exists. ActionList Action = iota // ActionRead is reading a resource's state. ActionRead // ActionWrite is mutating a resource's state. ActionWrite // ActionAdmin is mutating the resource itself rather than its // state — changing its ACL, deleting it. ActionAdmin // ActionScopeAdmin is anything not bound to a single resource: // service-wide configuration, a peer registry, global metrics. No // ACL can grant it, because no ACL describes that scope; only an // Admin caller may take it. ActionScopeAdmin )
type Matcher ¶
Matcher reports whether a Caller has some property. It is the unit a Rule is built from.
It is a function type, so a consumer with a predicate purser cannot anticipate simply writes one:
var afterHours authz.Matcher = func(c purser.Caller) bool { … }
A Matcher must not mutate the Caller it is given, and in particular must not write to its Labels: the map is shared with the request's own Caller and with every other matcher in the list.
func MatchAll ¶
MatchAll matches a caller every matcher matches. With no matchers, or with any nil matcher among them, it matches nobody.
That empty case is the opposite of mtls.MatchCertAll's, deliberately. An admission matcher is an *additional* restriction on a peer the TLS stack already verified, so an empty conjunction there removes a constraint and admits what verification already allowed. Here the conjunction is the entire predicate of a grant, so an empty one would *be* the grant — MatchAll(cfg.Matchers...) over a configuration section nobody filled in would hand the Admin bit to every caller. The rule of this package is that unset configuration closes the door, and it does not get an exception for the case that would silently open it widest.
A rule that genuinely applies to every caller therefore has no spelling in this package. Write the predicate in the consuming service, where it is visible in the source and turns up in a review:
Match: func(purser.Caller) bool { return true }
func MatchAnyOf ¶
MatchAnyOf matches a caller any matcher matches. With no matchers, or only nil ones, it matches nobody — an empty disjunction offers no way in, and neither does an empty conjunction here. See MatchAll.
func MatchEmailDomain ¶
MatchEmailDomain matches a caller whose Identity is an email address in domain — the shape an OIDC token or an email-SAN client certificate produces.
The match is anchored on the last "@", which is the difference between "@example.com" and every attacker-registered domain ending in those characters. An empty domain, or one containing "@", matches nobody.
The domain is compared case-insensitively — DNS labels are — but only over ASCII. strings.EqualFold applies Unicode simple folding, under which "ſlack.com" (U+017F) equals "slack.com" and "slacK.com" (U+212A, the Kelvin sign) equals "slack.com": separately registrable IDN domains that would satisfy a rule naming neither. Folding only A–Z keeps the comparison to what DNS actually treats as equal. A non-ASCII domain therefore matches only its exact bytes; configure such a domain in punycode, the form a certificate or an OIDC claim carries anyway.
The local part is not examined at all. Only the domain is folded, so this matcher is deliberately wider than MatchIdentity in a way that matters when the two are combined — see MatchNot.
func MatchIdentity ¶
MatchIdentity matches a caller whose Identity is exactly one of identities. This is the degenerate rule — the exact-match list core-agent configures today, expressible unchanged.
The comparison is byte for byte, with no case folding and no normalization, the same discipline ACL membership uses. An identity is an opaque string minted by an authenticator, and purser is not the layer that knows whether "Alice@example.com" and "alice@example.com" are one person — canonicalizing it is the authenticator's job, at the point where the credential's own rules are known. The consequence is stated on MatchNot, where it has teeth.
With no identities, or only empty ones, it matches nobody: a list that came back empty from configuration must not read as "anyone".
func MatchLabel ¶
MatchLabel matches a caller carrying key with any of values.
Labels are where the credential's structure lives: the SPIFFE trust domain and path (mtls.LabelTrustDomain, mtls.LabelPath), the issuing CA and serial (mtls.LabelIssuerDN, mtls.LabelSerial), and an OIDC token's residual claims. The key is an argument rather than a constant declared here because this package is stdlib-only and the packages that set those labels are not — a second spelling of "spiffe.path" living here is exactly the drift that would make a rule silently stop matching.
An empty key, no values, or only empty values match nobody. The empty value is the sharp one: purser.Caller.Label returns "" for a label that is absent, so a rule written as MatchLabel("group", cfg.Group) with Group unset would otherwise match every caller that has no group at all.
func MatchNot ¶
MatchNot matches a caller m does not match. A nil m matches nobody, the same as everywhere else in this package: an exception that was never configured must not inflate into a blanket grant, which is what the logically pure reading — not(nobody) is everyone — would make of it. Only a nil is recognisable that way. MatchNot(MatchAll()) is an empty conjunction negated, and a closure that matches nobody cannot be told from one that deliberately matches nobody today, so it does mean everyone. Build the exception's matcher directly rather than through a combinator over a slice that may be empty.
It exists so that an exception can be written into the rule that grants — "everyone in this namespace except the batch account" — rather than by ordering a deny rule ahead of an allow rule. Rules are a union and have no deny, which is what makes their order irrelevant and their meaning independent of how a configuration file happened to be assembled.
An exception must be as wide as the grant it sits inside ¶
The matchers here do not all compare the same way: MatchEmailDomain folds the case of the domain, MatchIdentity and ACL membership are byte-exact. An exception written in a narrower comparison than the grant leaves a gap, and the gap is the account the exception names:
// evadable: "Mallory@example.com" is granted and not excepted
MatchAll(
MatchEmailDomain("example.com"),
MatchNot(MatchIdentity("mallory@example.com")),
)
Whether that is reachable depends on whether the identity's own spelling is pinned — an authenticator that canonicalizes what it mints leaves nothing to evade, and one that copies an OIDC claim through unchanged may not. Where it is not pinned, except on the property the grant is written in (the label, the path prefix, the domain) rather than on an identity string, or write the exception's own comparison as a Matcher of your own.
func MatchPathPrefix ¶
MatchPathPrefix matches a caller whose label named by key is those segments or lies beneath them: MatchPathPrefix(mtls.LabelPath, "ns", "prod") matches /ns/prod and /ns/prod/sa/api, and does not match /ns/production.
The prefix is anchored on a segment boundary, which is the whole difference between "the prod namespace" and "any namespace whose name starts with prod". As with MatchPathSegments, an invalid or empty segment list matches nobody.
func MatchPathSegments ¶
MatchPathSegments matches a caller whose label named by key is exactly the slash-joined segments — MatchPathSegments(mtls.LabelPath, "ns", "prod", "sa", "api") matches the caller whose SPIFFE ID path is /ns/prod/sa/api, in any trust domain.
Pair it with MatchLabel(mtls.LabelTrustDomain, td) inside MatchAll to pin the trust domain too. A path is only unique within one.
Segments are passed separately rather than as one "/ns/prod/sa/api" string so that a segment interpolated from configuration cannot smuggle a separator in and widen the rule. An empty segment, a segment containing "/", or no segments at all yield a matcher that matches nobody.
type Role ¶
type Role int
Role is what a caller is to one resource. The constants are ordered from least to most capable and that ordering is part of the API: Allows compares with >=, and so may a consumer.
A role is not a group and not a claim. It is derived per resource, from an ACL, by RoleOf — except RoleAdmin, which comes from purser.Caller.Admin and therefore from policy (see Rules), never from a credential's own assertion.
const ( // RoleNone is a caller the ACL does not name. It may still list. RoleNone Role = iota // RoleViewer may read. RoleViewer // RoleContributor may read and write. RoleContributor // RoleOwner may read, write, and administer the resource. The owner // need not be a person: a synthetic identity such as // "channel:#incident-response" is the shape a shared resource takes. RoleOwner // RoleAdmin sees and does everything, on every resource in every // scope. It is the caller's Admin bit, not an ACL entry. RoleAdmin )
type Rule ¶
type Rule struct {
// Name identifies the rule in diagnostics and audit records —
// Rules.Matching returns these. It is required and must be unique
// within a rule set: a grant that cannot be named in a log line is
// a grant nobody can trace back to the configuration that made it.
Name string
// Match selects the callers this rule applies to. Required; nil is
// refused by NewRules rather than read as "everyone" or "nobody".
// No matcher in this package matches every caller — see MatchAll.
Match Matcher
// Admin grants purser.Caller.Admin — the see-everything role,
// authz.RoleAdmin against every ACL.
Admin bool
// Proxy grants the right to act on behalf of other identities via
// the asserted-caller header. See WithRules, which is what connects
// this to an authenticator, and authn.AuthenticatorWithProxy for
// what the capability means.
Proxy bool
}
Rule grants a capability to every caller its Matcher matches.
A rule can only grant. There is no deny, and so no precedence to get wrong: the effect of a rule list is the union of the rules that match, and reordering the list cannot change a decision. An exception is expressed inside the matcher with MatchNot, where it is visible in the rule that grants rather than in the distance between two rules.
type Rules ¶
type Rules struct {
// contains filtered or unexported fields
}
Rules is an evaluated rule set. It is safe for concurrent use and immutable after NewRules; a nil *Rules grants nothing, so a service that has not configured any can pass one around without a nil check.
func NewRules ¶
NewRules validates and freezes a rule set.
It refuses a rule with no Name, a duplicate Name, a nil Match, or one that grants nothing. Each is a rule that either cannot be traced or cannot do anything, and every one of them is far more likely to be a half-finished configuration than an intent — so it fails at startup rather than at the first request that needed it.
The rules are copied, so a caller may reuse or modify its slice.
func (*Rules) Apply ¶
Apply returns c with the grants its matching rules confer — today, the Admin bit.
It never demotes. A caller that already arrived with Admin keeps it, because rules compose with whatever set it rather than overruling them: a deployment migrating from an authenticator's own admin list to rules runs both for a release, and a rule set that had not been written yet must not quietly strip an operator's access.
A caller nothing authenticated gets nothing — see evaluate for what that means and why the check is not simply IsZero.
Labels are read, by any rule that matches on one, and the map is not copied: the returned Caller shares the argument's. Call purser.Caller.Clone if you need to detach it.
func (*Rules) CanProxyAs ¶
CanProxyAs reports whether c is granted the right to assert other identities. It is false for a caller nothing authenticated, whatever the rules say, which is the contract authn.AuthenticatorWithProxy states.
func (*Rules) Len ¶
Len reports how many rules the set holds. Useful to a surface logging its configuration at startup.