Documentation
¶
Index ¶
- Variables
- func Compact(entitlements []string) []string
- func Dominates(held, requested string) bool
- func EncodeResourceName(name string) (string, error)
- func IsCanonicalResourceName(s string) bool
- func ValidateEntitlement(s string) error
- func ValidateRequirement(s string) error
- func VerifyAttenuation(held, requested []string) (offender string, ok bool)
- type Binding
- type Entitlements
- type EntitlementsChecker
- func (ec *EntitlementsChecker) BindRequirements(reqs ParsedRequirements, b Binding) (ParsedRequirements, error)
- func (ec *EntitlementsChecker) CalculateResourceRequirements(resource string, resourceName string, requirements Requirements, ...) (Requirements, error)
- func (ec *EntitlementsChecker) ParseEntitlements(entitlements Entitlements) ParsedEntitlements
- func (ec *EntitlementsChecker) ParseRequirements(requirements Requirements) ParsedRequirements
- func (ec *EntitlementsChecker) VerifyEntitlements(entitlements Entitlements, requirements Requirements) (result bool)
- func (ec *EntitlementsChecker) VerifyParsedEntitlements(entitlements ParsedEntitlements, requirements ParsedRequirements) (result bool)
- func (ec *EntitlementsChecker) VerifyResourceEntitlements(resource string, resourceName string, entitlements Entitlements, ...) (bool, error)
- func (ec *EntitlementsChecker) VerifyResourceParsedEntitlements(resource string, resourceName string, parsedEntitlements ParsedEntitlements, ...) (bool, error)
- func (ec *EntitlementsChecker) WildcardRequirements(reqs Requirements) []string
- func (ec *EntitlementsChecker) WithBaseEntitlements(patterns []string) *EntitlementsChecker
- func (ec *EntitlementsChecker) WithLogger(log logr.Logger) *EntitlementsChecker
- func (ec *EntitlementsChecker) WithStrictRequirements(strict bool) *EntitlementsChecker
- type InvalidEntitlementError
- type InvalidEntitlementReason
- type ParsedEntitlements
- type ParsedRequirements
- type Requirements
Constants ¶
This section is empty.
Variables ¶
var ErrInvalidBoundValue = errors.New("entitlements: bound value must not be empty, a wildcard, or contain ':'")
ErrInvalidBoundValue is returned by BindRequirements when a Binding maps a placeholder to "", "*", or a value containing ':'. "" and "*" are the wildcard spelling, not a concrete resourceName: binding one would silently widen the requirement to the whole resource class. A ':' would re-split the bound pattern into the wrong shape when re-parsed — Rust and Python rebuild the pattern as a string and are exposed to that hazard, while Go and TypeScript construct it directly and are not; rejecting the colon in all four ports is what keeps their results identical. A binder that could not resolve a value must fail like an unbound placeholder rather than widen the gate or diverge across ports.
var ErrInvalidEntitlement = errors.New("entitlements: invalid entitlement")
ErrInvalidEntitlement is matched (via errors.Is) by every error ValidateEntitlement returns. Use errors.As with *InvalidEntitlementError to read the reason.
var ErrInvalidResourceName = errors.New("entitlements: resource name must be non-empty, well-formed UTF-8")
ErrInvalidResourceName is returned by EncodeResourceName for a name that has no canonical encoding: the empty name, which would encode to the wildcard spelling, and a string that is not well-formed UTF-8, which would let two distinct names share one encoding and so one grant.
var ErrUnboundPlaceholder = errors.New("entitlements: unbound placeholder in requirement")
ErrUnboundPlaceholder is returned by BindRequirements when a requirement declares a {placeholder} that the supplied Binding does not resolve. An unbound placeholder is an error, never a pass.
var ErrWildcardRequirement = errors.New("entitlements: wildcard resourceName is not allowed in a requirement")
ErrWildcardRequirement is returned by BindRequirements under strict mode when a requirement's resourceName is a wildcard ("*" or empty, which includes the short and medium syntaxes). Wildcards are meaningful only on the held side; as a requirement the spelling is ambiguous. Use a {placeholder} for the resource being addressed, or an opaque scope for a context-less capability.
Functions ¶
func Compact ¶ added in v0.3.0
Compact returns the subset of entitlements with every entry removed that is strictly dominated by another entry, or that is an exact / equivalent-form duplicate (e.g. "pages:read", "pages::read", "pages:*:read" collapse to the first-seen one). The result grants exactly the same authority as the input; surviving entries keep their original strings and their first-seen order.
It is defined purely in terms of Dominates, so its notion of "broader than" can never drift from attenuation. Opaque and malformed scopes collapse only by exact equality. Compaction is intended for preparing an entitlement array (e.g. before minting a narrowed token); it does not consult the checker's anonymous/base patterns or the intern cache.
func Dominates ¶ added in v0.2.1
Dominates reports whether the held entitlement is equal to or BROADER than the requested one under the kdex-entitlements grammar. This is the predicate for attenuation (minting a token that carries a subset of the caller's authority). Unlike request-time matching (entitlementMatches), a wildcard resourceName is honored ONLY on the held side: a specific grant cannot dominate a wildcard request, so a mint can never broaden authority.
Opaque scopes (no ':') dominate only by exact match.
func EncodeResourceName ¶ added in v0.7.0
EncodeResourceName returns the canonical encoding of a resourceName or context name (SPEC.md, Encoding): each must-encode byte of the name's UTF-8 form becomes %XX with upper-case hex, and every other byte, including '/', '@' and '*', stays raw. A name that is exactly "*" encodes as "%2A", so a literal can never become a wildcard. The empty name and a string that is not well-formed UTF-8 have no encoding: they return ErrInvalidResourceName.
The library never decodes a name: matching compares bytes, so every writer of a grant or requirement must produce this form.
func IsCanonicalResourceName ¶ added in v0.7.0
IsCanonicalResourceName reports whether s is exactly what EncodeResourceName produces for some name: it percent-decodes cleanly to a non-empty, well-formed UTF-8 name and re-encodes to itself. A wildcard ("*" or "") is not a name, so it is not canonical; "%2A" is.
func ValidateEntitlement ¶ added in v0.5.0
ValidateEntitlement reports whether s is a well-formed HELD entitlement: an opaque scope (no ':'), <resource>:<verb>, <resource>:<resourceName>:<verb>, or the contextual form. It returns nil, or an *InvalidEntitlementError naming the first failed check in this order: empty; a control (Cc) or White_Space character, or invalid UTF-8; more than 3 segments and not contextual; an invalid context; an empty resource; an empty verb; a {placeholder} resourceName or context name; a non-canonical name in a contextual form. An empty resourceName stays legal ("apitokens::mint"), as do wildcards and the verb "all". Strings of at most 3 segments get no new rejections in 0.7.0.
Verification deliberately parses leniently (see parsePattern): a malformed string becomes an opaque scope or a pattern that never matches. This is the strict counterpart for a writer that accepts entitlements from a person or from configuration and must reject them before they are stored. It is pure and checker-independent.
A held {placeholder} is rejected because it is literal text on the held side: it grants nothing a caller can address, and against a caller that skipped BindRequirements it would literally match the unbound requirement.
func ValidateRequirement ¶ added in v0.6.0
ValidateRequirement is ValidateEntitlement for a REQUIREMENT string: the same checks, in the same order, with the same reason codes, except that a {placeholder} resourceName is legal -- on the requirement side it is the hole BindRequirements fills. Use it to check a requirement declared in configuration (an OpenAPI security block or extension) before relying on it.
func VerifyAttenuation ¶ added in v0.2.1
VerifyAttenuation returns ("", true) when every requested entitlement is dominated by at least one held entitlement. Otherwise it returns the first requested entitlement that no held entitlement dominates, and false.
Types ¶
type Binding ¶ added in v0.4.0
Binding maps a requirement placeholder key to the concrete resourceName it stands for, e.g. {"vector_store_id": "vs_abc"}.
type Entitlements ¶
Entitlements is a map where keys are security schemes (e.g., "bearer", "oauth2") and values are slices of entitlement strings. Entitlement strings can be in long, medium, short, or opaque forms.
type EntitlementsChecker ¶
type EntitlementsChecker struct {
// contains filtered or unexported fields
}
EntitlementsChecker handles the verification of user entitlements against security requirements. It supports exact matches and wildcard patterns for resource names and verbs.
Pattern Forms:
- Long Form: <resource>:<resourceName>:<verb>
- Medium Form: <resource>::<verb> (means <resource>:*:<verb>)
- Short Form: <resource>:<verb> (means <resource>:*:<verb>)
- Opaque Form: <resource> (not a wildcard, only matches exactly)
- Contextual Form: <ctxResource>:<ctxName>@<resource>:<resourceName>:<verb> (scoped to the object the resource lives in; chains allowed)
Opaque form is intended to support JWT claims and other forms of requirements like HTTP Headers.
Contextual form scopes a grant to its parent object, e.g. vector_stores:vs_x@tags:*:read reads every tag in store vs_x. A grant with no context applies in every context; a contextual grant never satisfies a requirement with no context. Releases before 0.7.0 parse a contextual string as opaque, so it fails closed there. See SPEC.md, Contexts.
Encoding: A resourceName or context name must not contain a raw ':', since it would be misinterpreted by the pattern splitting logic. The library never decodes or case-folds a name - matching compares bytes - so every writer of a grant or requirement must produce the canonical form: use EncodeResourceName, and IsCanonicalResourceName to check one. See SPEC.md, Encoding.
Examples:
- pages:/foo:read - read access to page "foo" (explicit resource name)
- pages:*:read - read access to all pages (explicit wildcard)
- pages::read - read access to all pages (implicit wildcard)
- pages:read - read access to all pages (short form)
- pages:/foo:all - all access to page "foo" (explicit resource name)
- pages:*:all - all access to all pages (explicit wildcard)
- pages::all - all access to all pages (implicit wildcard)
- pages:all - all access to all pages (short form)
- email - exact match only (opaque form)
func NewEntitlementsChecker ¶
func NewEntitlementsChecker( anonymousEntitlements []string, defaultScheme string, grantReadyByDefault bool, ) *EntitlementsChecker
NewEntitlementsChecker creates a new entitlements checker with the specified settings. anonymousEntitlements is a list of patterns granted only to callers whose entitlements map is empty (no schemes present, or every scheme's list empty). Authenticated callers do not receive these patterns; use WithBaseEntitlements for patterns that should apply to every caller. defaultScheme is the fallback security scheme used when none is specified. grantReadyByDefault determines if the identity requirement is automatically satisfied.
func (*EntitlementsChecker) BindRequirements ¶ added in v0.4.0
func (ec *EntitlementsChecker) BindRequirements(reqs ParsedRequirements, b Binding) (ParsedRequirements, error)
BindRequirements substitutes every {placeholder} resourceName in reqs with its value from b and returns the rewritten requirements. Requirement sets containing no placeholder are returned unchanged.
Returns ErrUnboundPlaceholder if any placeholder has no entry in b — an unbound placeholder is a configuration error, never a pass. Keys in b that match no placeholder are ignored, so a caller may pass a superset (e.g. every path value it resolved) without knowing the requirement.
Returns ErrInvalidBoundValue if a placeholder is bound to "", "*", or a value containing ':'. "" and "*" are the wildcard spelling of a resourceName, not a concrete value: binding one would silently widen the requirement to the whole resource class. A ':' is rejected because this method constructs the bound pattern directly (see the comment below), but Rust and Python have no pre-parsed type and must re-emit the bound pattern as a string that verify then re-parses — there, a value containing ':' re-splits into the wrong shape and the pattern silently becomes opaque. Rejecting the colon here, in every port, is what keeps all four producing identical results instead of fixing only the two that happen to rebuild the string. A binder that could not resolve a value must fail like an unbound placeholder rather than widen the gate or diverge across ports.
Under WithStrictRequirements, also returns ErrWildcardRequirement if any requirement in reqs — placeholder or not — has a wildcard resourceName ("" or "*", including the short/medium syntaxes). This check runs before the placeholder no-op above, so a wildcard-only requirement set (no placeholder at all) is still rejected rather than passed through unchanged.
func (*EntitlementsChecker) CalculateResourceRequirements ¶
func (ec *EntitlementsChecker) CalculateResourceRequirements( resource string, resourceName string, requirements Requirements, verbs ...string, ) (Requirements, error)
CalculateResourceRequirements calculates the requirements for a resource instance. It returns a copy of the requirements with an identity requirement added for the specific resource. The optional verbs parameter allows specifying the verb for the identity requirement (defaults to "read").
func (*EntitlementsChecker) ParseEntitlements ¶
func (ec *EntitlementsChecker) ParseEntitlements(entitlements Entitlements) ParsedEntitlements
ParseEntitlements converts a raw Entitlements map into ParsedEntitlements for efficient reuse in multiple verification calls.
func (*EntitlementsChecker) ParseRequirements ¶
func (ec *EntitlementsChecker) ParseRequirements(requirements Requirements) ParsedRequirements
ParseRequirements converts raw Requirements into ParsedRequirements for efficient reuse in multiple verification calls.
func (*EntitlementsChecker) VerifyEntitlements ¶
func (ec *EntitlementsChecker) VerifyEntitlements( entitlements Entitlements, requirements Requirements, ) (result bool)
VerifyEntitlements checks if the user's entitlements satisfy the given security requirements. It returns true if any of the alternative requirement sets (OR'd) is fully satisfied.
func (*EntitlementsChecker) VerifyParsedEntitlements ¶
func (ec *EntitlementsChecker) VerifyParsedEntitlements( entitlements ParsedEntitlements, requirements ParsedRequirements, ) (result bool)
VerifyParsedEntitlements is a high-performance check that uses pre-parsed entitlements and requirements. It is intended for scenarios where the same entitlements or requirements are checked repeatedly.
func (*EntitlementsChecker) VerifyResourceEntitlements ¶
func (ec *EntitlementsChecker) VerifyResourceEntitlements( resource string, resourceName string, entitlements Entitlements, requirements Requirements, verbs ...string, ) (bool, error)
VerifyResourceEntitlements checks if the user's entitlements satisfy the security requirements for a specific resource instance. It automatically adds an identity requirement for the resource. The optional verbs parameter allows specifying the verb for the identity requirement (defaults to "read").
func (*EntitlementsChecker) VerifyResourceParsedEntitlements ¶
func (ec *EntitlementsChecker) VerifyResourceParsedEntitlements( resource string, resourceName string, parsedEntitlements ParsedEntitlements, parsedRequirements ParsedRequirements, verbs ...string, ) (bool, error)
VerifyResourceParsedEntitlements is a high-performance check for a specific resource instance using pre-parsed entitlements and requirements.
Under WithStrictRequirements, a resourceName of "*" makes the identity requirement this method builds illegal by spelling, so it is denied regardless of grants — see WithStrictRequirements for the full explanation.
func (*EntitlementsChecker) WildcardRequirements ¶ added in v0.4.0
func (ec *EntitlementsChecker) WildcardRequirements(reqs Requirements) []string
WildcardRequirements returns the requirement strings whose resourceName is a wildcard ("*", empty, or the short/medium syntaxes) — the spellings strict mode rejects outright. Results are de-duplicated and in first-seen order.
It is a migration inventory, not a complete strict-mode pre-flight: strict also rejects an unbound placeholder at verification time, which this query does not report (a placeholder is the migration's destination, not a target). An empty result means no requirement still uses a wildcard spelling.
It is a pure query so a caller may log, count, or fail in its own idiom. Use it to inventory what remains to migrate before enabling WithStrictRequirements.
func (*EntitlementsChecker) WithBaseEntitlements ¶ added in v0.2.0
func (ec *EntitlementsChecker) WithBaseEntitlements(patterns []string) *EntitlementsChecker
WithBaseEntitlements sets the base entitlements: patterns that apply to every caller (authenticated or anonymous) under the default scheme. Unlike anonymousEntitlements (which apply only when the caller's entitlements map is empty), base entitlements form a floor of grants that every request receives.
Replaces any previously set base entitlements. Intended for use during checker construction; not safe for concurrent mutation with verify calls in flight.
func (*EntitlementsChecker) WithLogger ¶
func (ec *EntitlementsChecker) WithLogger(log logr.Logger) *EntitlementsChecker
WithLogger attaches a logger to the EntitlementsChecker for debugging purposes.
func (*EntitlementsChecker) WithStrictRequirements ¶ added in v0.4.0
func (ec *EntitlementsChecker) WithStrictRequirements(strict bool) *EntitlementsChecker
WithStrictRequirements rejects wildcard resourceNames on the requirement side. It never affects entitlements, where wildcards remain meaningful.
When enabled, BindRequirements returns ErrWildcardRequirement for such a requirement (the loud path), and verification treats both a wildcard requirement and an unbound placeholder as unsatisfiable (a fail-closed backstop for callers that skip BindRequirements).
Defaults to false; a future major version will default it to true. Intended for use during checker construction; not safe for concurrent mutation with verify calls in flight.
VerifyResourceEntitlements and VerifyResourceParsedEntitlements build their identity requirement from the caller-supplied resourceName (as "<resource>:<resourceName>:<verb>"). They already reject an empty resourceName outright, but "*" passes that guard; under strict, "*" makes the identity a wildcard requirement — illegal by spelling — so the check denies unconditionally, regardless of the caller's grants, including a genuine wildcard grant like "pages::all". Callers must pass a concrete resourceName. There is deliberately no requirement spelling for "holds authority over the whole class"; use an opaque capability scope for that.
type InvalidEntitlementError ¶ added in v0.5.0
type InvalidEntitlementError struct {
Entitlement string
Reason InvalidEntitlementReason
}
InvalidEntitlementError is returned by ValidateEntitlement. It carries the offending string and the reason code, and matches ErrInvalidEntitlement.
func (*InvalidEntitlementError) Error ¶ added in v0.5.0
func (e *InvalidEntitlementError) Error() string
func (*InvalidEntitlementError) Unwrap ¶ added in v0.5.0
func (e *InvalidEntitlementError) Unwrap() error
type InvalidEntitlementReason ¶ added in v0.5.0
type InvalidEntitlementReason string
InvalidEntitlementReason is a stable, cross-port code naming why ValidateEntitlement rejected a string. The values are a contract (SPEC.md, Validation) — callers may put them in a 400 body — so never change one.
const ( // InvalidEntitlementEmpty: the string is empty. InvalidEntitlementEmpty InvalidEntitlementReason = "empty" // InvalidEntitlementCharacter: the string contains a control character // (Unicode Cc) or a White_Space character, or is not valid UTF-8. InvalidEntitlementCharacter InvalidEntitlementReason = "invalid_character" // InvalidEntitlementTooManySegments: more than 3 ':'-separated segments, // and not the contextual form. InvalidEntitlementTooManySegments InvalidEntitlementReason = "too_many_segments" // InvalidEntitlementInvalidContext: a contextual form whose outermost // context resource is empty or contains '@', whose context name is empty, // or whose intermediate context resource is empty. InvalidEntitlementInvalidContext InvalidEntitlementReason = "invalid_context" // InvalidEntitlementEmptyResource: a structured form with an empty resource. InvalidEntitlementEmptyResource InvalidEntitlementReason = "empty_resource" // InvalidEntitlementEmptyVerb: a structured form with an empty verb. InvalidEntitlementEmptyVerb InvalidEntitlementReason = "empty_verb" // InvalidEntitlementPlaceholder: the resourceName, or a context name, is a // {placeholder}. InvalidEntitlementPlaceholder InvalidEntitlementReason = "placeholder" // InvalidEntitlementNonCanonicalEncoding: a name in a contextual form is // not canonically encoded (see EncodeResourceName). InvalidEntitlementNonCanonicalEncoding InvalidEntitlementReason = "non_canonical_encoding" )
type ParsedEntitlements ¶
type ParsedEntitlements struct {
// contains filtered or unexported fields
}
ParsedEntitlements represents a set of user entitlements that have been pre-parsed into internal patterns for high-performance verification.
type ParsedRequirements ¶
type ParsedRequirements struct {
// contains filtered or unexported fields
}
ParsedRequirements represents a set of security requirements that have been pre-parsed into internal patterns for high-performance verification.
type Requirements ¶
Requirements is a slice of maps representing alternative security requirement sets. Each map in the slice represents an alternative set of requirements (OR'd). Within each map, all schemes and their associated scopes must be satisfied (AND'd).