typesystem

package
v1.11.5 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2026 License: Apache-2.0 Imports: 25 Imported by: 5

Documentation

Overview

Package typesystem contains code to manipulate authorization models.

Index

Constants

View Source
const (
	// SchemaVersion1_0 for the authorization models.
	SchemaVersion1_0 string = "1.0"

	// SchemaVersion1_1 for the authorization models.
	SchemaVersion1_1 string = "1.1"

	// SchemaVersion1_2 for the authorization models.
	SchemaVersion1_2 string = "1.2"
)

Variables

View Source
var (
	// ErrModelNotFound is returned when an authorization model is not found.
	ErrModelNotFound = errors.New("authorization model not found")

	// ErrDuplicateTypes is returned when an authorization model contains duplicate types.
	ErrDuplicateTypes = errors.New("an authorization model cannot contain duplicate types")

	// ErrInvalidSchemaVersion is returned for an invalid schema version in the authorization model.
	ErrInvalidSchemaVersion = errors.New("invalid schema version")

	// ErrInvalidModel is returned when encountering an invalid authorization model.
	ErrInvalidModel = errors.New("invalid authorization model encountered")

	// ErrRelationUndefined is returned when encountering an undefined relation in the authorization model.
	ErrRelationUndefined = errors.New("undefined relation")

	// ErrObjectTypeUndefined is returned when encountering an undefined object type in the authorization model.
	ErrObjectTypeUndefined = errors.New("undefined object type")

	// ErrInvalidUsersetRewrite is returned for an invalid userset rewrite definition.
	ErrInvalidUsersetRewrite = errors.New("invalid userset rewrite definition")

	// ErrReservedKeywords is returned when using reserved keywords "self" and "this".
	ErrReservedKeywords = errors.New("self and this are reserved keywords")

	// ErrCycle is returned when a cycle is detected in an authorization model.
	// This occurs if an objectType and relation in the model define a rewrite
	// rule that is self-referencing through computed relationships.
	ErrCycle = errors.New("an authorization model cannot contain a cycle")

	// ErrNoEntrypoints is returned when a particular objectType and relation in an authorization
	// model are not accessible via a direct edge, for example from another objectType.
	ErrNoEntrypoints = errors.New("no entrypoints defined")

	// ErrNoEntryPointsLoop is returned when an authorization model contains a cycle
	// because at least one objectType and relation returned ErrNoEntrypoints.
	ErrNoEntryPointsLoop = errors.New("potential loop")

	// ErrNoConditionForRelation is returned when no condition is defined for a relation in the authorization model.
	ErrNoConditionForRelation = errors.New("no condition defined for relation")

	// ErrInvalidRelation is returned when a model failed due to invalid relation.
	ErrInvalidRelation = errors.New("invalid relation")
)

Functions

func AssignableRelationError

func AssignableRelationError(objectType, relation string) error

AssignableRelationError returns an error for an assignable relation with no relation types defined.

func ComputedUserset added in v0.2.4

func ComputedUserset(relation string) *openfgav1.Userset

ComputedUserset creates an Userset representing a computed userset based on the specified relation.

func ConditionedRelationReference added in v1.3.8

func ConditionedRelationReference(rel *openfgav1.RelationReference, condition string) *openfgav1.RelationReference

ConditionedRelationReference assigns a condition to a given RelationReference and returns the modified RelationReference.

func ContextWithTypesystem added in v0.3.5

func ContextWithTypesystem(parent context.Context, typesys *TypeSystem) context.Context

ContextWithTypesystem creates a copy of the parent context with the provided TypeSystem.

func Difference added in v0.2.4

func Difference(base *openfgav1.Userset, sub *openfgav1.Userset) *openfgav1.Userset

Difference creates new Userset representing the difference between two Usersets 'base' and 'sub'.

func DirectRelationReference added in v0.3.0

func DirectRelationReference(objectType, relation string) *openfgav1.RelationReference

DirectRelationReference creates a direct RelationReference for the given object type and relation.

func GetRelationReferenceAsString added in v0.4.0

func GetRelationReferenceAsString(rr *openfgav1.RelationReference) string

GetRelationReferenceAsString returns team#member, or team:*, or an empty string if the input is nil.

func Intersection added in v0.2.4

func Intersection(children ...*openfgav1.Userset) *openfgav1.Userset

Intersection creates a new Userset representing the intersection of the provided Usersets.

func InvalidRelationTypeError

func InvalidRelationTypeError(objectType, relation, relatedObjectType, relatedRelation string) error

InvalidRelationTypeError returns an error for an invalid relation type in a relation definition.

func IsSchemaVersionSupported added in v1.1.0

func IsSchemaVersionSupported(version string) bool

IsSchemaVersionSupported checks if the provided schema version is supported.

func NonAssignableRelationError

func NonAssignableRelationError(objectType, relation string) error

NonAssignableRelationError returns an error for a non-assignable relation with a relation type defined.

func RelationEquals added in v1.6.0

func RewriteContainsSelf added in v0.2.5

func RewriteContainsSelf(rewrite *openfgav1.Userset) bool

RewriteContainsSelf returns true if the provided userset rewrite is defined by one or more self referencing definitions.

func This added in v0.2.4

func This() *openfgav1.Userset

This creates an Userset representing the special "this" userset.

func TupleToUserset added in v0.2.4

func TupleToUserset(tupleset, computedUserset string) *openfgav1.Userset

TupleToUserset creates an Userset based on the provided tupleset and computed userset.

func Union added in v0.2.4

func Union(children ...*openfgav1.Userset) *openfgav1.Userset

Union creates an Userset representing the union of the provided children Usersets.

func WalkUsersetRewrite added in v0.3.2

func WalkUsersetRewrite(rewrite *openfgav1.Userset, handler WalkUsersetRewriteHandler) (interface{}, error)

WalkUsersetRewrite recursively walks the provided userset rewrite and invokes the provided WalkUsersetRewriteHandler to each node in the userset rewrite tree until the first non-nil response is encountered.

func WildcardRelationReference added in v0.3.0

func WildcardRelationReference(objectType string) *openfgav1.RelationReference

WildcardRelationReference creates a RelationReference for a wildcard relation of the given object type.

Types

type ExclusionEdges added in v1.10.0

type ExclusionEdges struct {
	BaseEdge     *graph.WeightedAuthorizationModelEdge // base edge to apply list objects
	ExcludedEdge *graph.WeightedAuthorizationModelEdge // excluded edge to apply exclusion
}

func GetEdgesForExclusion added in v1.9.0

func GetEdgesForExclusion(
	edges []*graph.WeightedAuthorizationModelEdge,
	sourceType string,
) (ExclusionEdges, error)

GetEdgesForExclusion returns the base edges (i.e., edge A in "A but not B") and excluded edge (edge B in "A but not B") based on weighted graph for exclusion.

type IntersectionEdges added in v1.9.0

type IntersectionEdges struct {
	LowestEdge   *graph.WeightedAuthorizationModelEdge   // lowest edge to apply list objects
	SiblingEdges []*graph.WeightedAuthorizationModelEdge // the rest of the edges to apply intersection
}

func GetEdgesForIntersection added in v1.9.0

func GetEdgesForIntersection(edges []*graph.WeightedAuthorizationModelEdge, sourceType string) (IntersectionEdges, error)

GetEdgesForIntersection returns the lowest weighted edge and its siblings edges for intersection based via the weighted graph. If the direct edges have equal weight as its sibling edges, it will choose the direct edges as preference. If any of the children are not connected, it will return empty IntersectionEdges.

type InvalidRelationError

type InvalidRelationError struct {
	ObjectType string
	Relation   string
	Cause      error
}

InvalidRelationError represents an error indicating an invalid relation definition.

func (*InvalidRelationError) Error added in v0.2.5

func (e *InvalidRelationError) Error() string

Error implements the error interface for InvalidRelationError.

func (*InvalidRelationError) Unwrap added in v0.2.5

func (e *InvalidRelationError) Unwrap() error

Unwrap returns the underlying cause of the error.

type InvalidTypeError added in v0.3.5

type InvalidTypeError struct {
	ObjectType string
	Cause      error
}

InvalidTypeError represents an error indicating an invalid object type.

func (*InvalidTypeError) Error added in v0.3.5

func (e *InvalidTypeError) Error() string

Error implements the error interface for InvalidTypeError.

func (*InvalidTypeError) Unwrap added in v0.3.5

func (e *InvalidTypeError) Unwrap() error

Unwrap returns the underlying cause of the error.

type ObjectTypeUndefinedError added in v0.2.5

type ObjectTypeUndefinedError struct {
	ObjectType string
	Err        error
}

ObjectTypeUndefinedError represents an error indicating an undefined object type.

func (*ObjectTypeUndefinedError) Error added in v0.2.5

func (e *ObjectTypeUndefinedError) Error() string

Error implements the error interface for ObjectTypeUndefinedError.

func (*ObjectTypeUndefinedError) Unwrap added in v0.2.5

func (e *ObjectTypeUndefinedError) Unwrap() error

Unwrap returns the underlying cause of the error.

type RelationConditionError added in v1.3.8

type RelationConditionError struct {
	Condition string
	Relation  string
	Err       error
}

RelationConditionError represents an error indicating an undefined condition for a relation.

func (*RelationConditionError) Error added in v1.3.8

func (e *RelationConditionError) Error() string

Error implements the error interface for RelationConditionError.

func (*RelationConditionError) Unwrap added in v1.3.8

func (e *RelationConditionError) Unwrap() error

Unwrap returns the underlying cause of the error.

type RelationUndefinedError added in v0.2.5

type RelationUndefinedError struct {
	ObjectType string
	Relation   string
	Err        error
}

RelationUndefinedError represents an error indicating an undefined relation.

func (*RelationUndefinedError) Error added in v0.2.5

func (e *RelationUndefinedError) Error() string

Error implements the error interface for RelationUndefinedError.

func (*RelationUndefinedError) Unwrap added in v0.2.5

func (e *RelationUndefinedError) Unwrap() error

Unwrap returns the underlying cause of the error.

type TypeSystem

type TypeSystem struct {
	// contains filtered or unexported fields
}

TypeSystem is a wrapper over an openfgav1.AuthorizationModel.

func New

New creates a *TypeSystem from an *openfgav1.AuthorizationModel. It assumes that the input model is valid. If you need to run validations, use NewAndValidate.

func NewAndValidate added in v0.4.0

func NewAndValidate(ctx context.Context, model *openfgav1.AuthorizationModel) (*TypeSystem, error)

NewAndValidate is like New but also validates the model according to the following rules:

  1. Checks that the *TypeSystem have a valid schema version.
  2. For every rewrite the relations in the rewrite must: a) Be valid relations on the same type in the *TypeSystem (in cases of computedUserset) b) Be valid relations on another existing type (in cases of tupleToUserset)
  3. Do not allow duplicate types or duplicate relations (only need to check types as relations are in a map so cannot contain duplicates)

If the *TypeSystem has a v1.1 schema version (with types on relations), then additionally validate the *TypeSystem according to the following rules:

  1. Every type restriction on a relation must be a valid type: a) For a type (e.g. user) this means checking that this type is in the *TypeSystem b) For a type#relation this means checking that this type with this relation is in the *TypeSystem
  2. Check that a relation is assignable if and only if it has a non-zero list of types

func TypesystemFromContext added in v0.3.5

func TypesystemFromContext(ctx context.Context) (*TypeSystem, bool)

TypesystemFromContext returns the TypeSystem from the provided context (if any).

func (*TypeSystem) CacheEntityType added in v1.8.12

func (t *TypeSystem) CacheEntityType() string

func (*TypeSystem) ConstructExclusionUserset added in v1.10.0

func (t *TypeSystem) ConstructExclusionUserset(node *graph.WeightedAuthorizationModelNode, sourceUserType string) (*openfgav1.Userset, error)

func (*TypeSystem) ConstructIntersectionUserset added in v1.10.0

func (t *TypeSystem) ConstructIntersectionUserset(node *graph.WeightedAuthorizationModelNode, sourceUserType string) (*openfgav1.Userset, error)

func (*TypeSystem) ConstructUnionUserset added in v1.10.0

func (t *TypeSystem) ConstructUnionUserset(node *graph.WeightedAuthorizationModelNode, sourceUserType string) (*openfgav1.Userset, error)

func (*TypeSystem) ConstructUserset added in v1.9.0

func (t *TypeSystem) ConstructUserset(currentEdge *graph.WeightedAuthorizationModelEdge, sourceUserType string) (*openfgav1.Userset, error)

ConstructUserset returns the openfgav1.Userset to run CheckRewrite against list objects candidate when model has intersection / exclusion.

func (*TypeSystem) DirectlyRelatedUsersets added in v1.3.1

func (t *TypeSystem) DirectlyRelatedUsersets(objectType, relation string) ([]*openfgav1.RelationReference, error)

DirectlyRelatedUsersets returns a list of the directly user related types that are usersets.

func (*TypeSystem) GetAllRelations added in v1.5.1

func (t *TypeSystem) GetAllRelations() map[string]map[string]*openfgav1.Relation

GetAllRelations returns a map [objectType] => [relationName] => relation.

func (*TypeSystem) GetAuthorizationModelID added in v0.3.0

func (t *TypeSystem) GetAuthorizationModelID() string

GetAuthorizationModelID returns the ID for the authorization model this TypeSystem was constructed for.

func (*TypeSystem) GetCondition added in v1.3.8

func (t *TypeSystem) GetCondition(name string) (*condition.EvaluableCondition, bool)

GetCondition searches for an EvaluableCondition in the TypeSystem by its name.

func (*TypeSystem) GetConditions added in v1.3.8

func (t *TypeSystem) GetConditions() map[string]*condition.EvaluableCondition

GetConditions retrieves a map of condition names to their corresponding EvaluableCondition instances within the TypeSystem.

func (*TypeSystem) GetConnectedEdges added in v1.10.0

func (t *TypeSystem) GetConnectedEdges(targetTypeRelation string, sourceType string) ([]*graph.WeightedAuthorizationModelEdge, error)

GetConnectedEdges returns all edges which have a path to the source type.

func (*TypeSystem) GetDirectlyRelatedUserTypes added in v0.2.4

func (t *TypeSystem) GetDirectlyRelatedUserTypes(objectType, relation string) ([]*openfgav1.RelationReference, error)

GetDirectlyRelatedUserTypes fetches user types directly related to a specified objectType-relation pair.

func (*TypeSystem) GetEdgesFromNode added in v1.9.2

func (t *TypeSystem) GetEdgesFromNode(
	node *graph.WeightedAuthorizationModelNode,
	sourceType string,
) ([]*graph.WeightedAuthorizationModelEdge, error)

GetEdgesFromNode first checks if the node can reach the source type, then returns all the from edges for the node.

func (*TypeSystem) GetInternalEdges added in v1.10.3

GetInternalEdges returns a slice with all the edges linked to a grouping logical node, otherwise the slice contains the original edge.

func (*TypeSystem) GetNode added in v1.9.0

func (t *TypeSystem) GetNode(uniqueID string) (*graph.WeightedAuthorizationModelNode, bool)

func (*TypeSystem) GetRelation

func (t *TypeSystem) GetRelation(objectType, relation string) (*openfgav1.Relation, error)

GetRelation retrieves a specific Relation from the TypeSystem based on the provided objectType and relation strings. It can return ErrObjectTypeUndefined and ErrRelationUndefined.

func (*TypeSystem) GetRelations

func (t *TypeSystem) GetRelations(objectType string) (map[string]*openfgav1.Relation, error)

GetRelations returns all relations in the TypeSystem for a given type.

func (*TypeSystem) GetSchemaVersion

func (t *TypeSystem) GetSchemaVersion() string

GetSchemaVersion returns the schema version associated with the TypeSystem instance.

func (*TypeSystem) GetTypeDefinition

func (t *TypeSystem) GetTypeDefinition(objectType string) (*openfgav1.TypeDefinition, bool)

GetTypeDefinition searches for a TypeDefinition in the TypeSystem based on the given objectType string.

func (*TypeSystem) GetWeightedGraph added in v1.10.4

func (t *TypeSystem) GetWeightedGraph() *graph.WeightedAuthorizationModelGraph

func (*TypeSystem) HasCycle added in v1.3.2

func (t *TypeSystem) HasCycle(objectType, relationName string) (bool, error)

HasCycle runs a cycle detection test on the provided `objectType#relation` to see if the relation defines a rewrite rule that is self-referencing in any way (through computed relationships).

func (*TypeSystem) HasTypeInfo added in v0.2.5

func (t *TypeSystem) HasTypeInfo(objectType, relation string) (bool, error)

HasTypeInfo determines if a given objectType-relation pair has associated type information. It checks against the specific schema version and the existence of type information in the relation. Returns true if type information is present and an error if the relation is not found.

func (*TypeSystem) IsDirectlyAssignable

func (t *TypeSystem) IsDirectlyAssignable(relation *openfgav1.Relation) bool

func (*TypeSystem) IsDirectlyRelated added in v0.2.4

func (t *TypeSystem) IsDirectlyRelated(target *openfgav1.RelationReference, source *openfgav1.RelationReference) (bool, error)

IsDirectlyRelated determines whether the type of the target DirectRelationReference contains the source DirectRelationReference.

func (*TypeSystem) IsPubliclyAssignable added in v0.3.2

func (t *TypeSystem) IsPubliclyAssignable(target *openfgav1.RelationReference, objectType string) (bool, error)

IsPubliclyAssignable checks if the provided objectType is part of a typed wildcard type restriction on the target relation.

Example:

type user

type document
  relations
    define viewer: [user:*]

In the example above, the 'user' objectType is publicly assignable to the 'document#viewer' relation. If the input target is not a defined relation, it returns false and RelationUndefinedError.

func (*TypeSystem) IsTuplesetRelation added in v0.3.0

func (t *TypeSystem) IsTuplesetRelation(objectType, relation string) (bool, error)

IsTuplesetRelation returns a boolean indicating if the provided relation is defined under a TupleToUserset rewrite as a tupleset relation (i.e. the right hand side of a `X from Y`).

func (*TypeSystem) PathExists added in v1.8.1

func (t *TypeSystem) PathExists(user, relation, objectType string) (bool, error)

PathExists returns true if: - the `user` type is a subject e.g. `user`, and there is a path from `user` to `objectType#relation`, or there is a path from `user:*` to `objectType#relation` or - the `user` type is a userset e.g. `group#member`, and there is a path from `group#member` to `objectType#relation`.

func (*TypeSystem) PubliclyAssignableReferences added in v1.8.0

func (t *TypeSystem) PubliclyAssignableReferences(target *openfgav1.RelationReference, objectType string) (*openfgav1.RelationReference, error)

PubliclyAssignableReferences returns the publicly assignable references with the specified objectType.

func (*TypeSystem) RelationInvolvesExclusion added in v0.2.5

func (t *TypeSystem) RelationInvolvesExclusion(objectType, relation string) (bool, error)

RelationInvolvesExclusion returns true if the provided relation's userset rewrite is defined by one or more direct or indirect exclusions or any of the types related to the provided relation are defined by one or more direct or indirect exclusions.

func (*TypeSystem) RelationInvolvesIntersection added in v0.2.5

func (t *TypeSystem) RelationInvolvesIntersection(objectType, relation string) (bool, error)

RelationInvolvesIntersection returns true if the provided relation's userset rewrite is defined by one or more direct or indirect intersections or any of the types related to the provided relation are defined by one or more direct or indirect intersections.

func (*TypeSystem) ResolveComputedRelation added in v1.6.2

func (t *TypeSystem) ResolveComputedRelation(objectType, relation string) (string, error)

ResolveComputedRelation traverses the typesystem until finding the final resolution of a computed relationship. Subsequent calls to this method are resolved from a cache.

func (*TypeSystem) TTUUseRecursiveResolver added in v1.9.3

func (t *TypeSystem) TTUUseRecursiveResolver(objectType, relation, userType string, ttu *openfgav1.TupleToUserset) bool

TTUUseRecursiveResolver returns true fast path can be applied to user/relation. For it to return true, all of these conditions: 1. Node[objectType#relation].weights[userType] = infinite 2. Node[objectType#relation].RecursiveRelation = objectType#relation 3. Node[objectType#relation].IsPartOfTupleCycle == false 4. Node[objectType#relation] has only 1 edge, and it's to an OR node 5. The OR node has one or more TTU edge with weight infinite for the terminal type and the computed relation for the TTU is the same 6. Any other edge coming out of the OR node that has a weight for terminal type, it should be weight 1 must be all true.

func (*TypeSystem) TTUUseWeight2Resolver added in v1.9.3

func (t *TypeSystem) TTUUseWeight2Resolver(objectType, relation, userType string, ttu *openfgav1.TupleToUserset) bool

func (*TypeSystem) UsersetUseRecursiveResolver added in v1.9.3

func (t *TypeSystem) UsersetUseRecursiveResolver(objectType, relation, userType string) bool

UsersetUseRecursiveResolver returns true if all these conditions apply: 1. Node[objectType#relation].weights[userType] = infinite 2. Any other direct type, userset or computed relation used in the relation needs to be weight = 1 for the usertype Example: type doc rel1 = [doc#rel1, user, user with cond, employee, doc#rel8] or ( (rel2 but not rel7) or rel8) rel2 = rel4 but not rel5 rel4 = [user] rel5 = [user] rel7 = [user] rel8 = [employee] calling UsersetUseRecursiveResolver(doc, rel1, user) should return TRUE calling UsersetUseRecursiveResolver(doc, rel1, employee) should return FALSE because there is a doc#rel8 that has weight = 2 for employee.

func (*TypeSystem) UsersetUseWeight2Resolver added in v1.9.3

func (t *TypeSystem) UsersetUseWeight2Resolver(objectType, relation, userType string, userset *openfgav1.RelationReference) bool

func (*TypeSystem) UsersetUseWeight2Resolvers added in v1.10.0

func (t *TypeSystem) UsersetUseWeight2Resolvers(objectType, relation, userType string, usersets []*openfgav1.RelationReference) bool

UsersetUseWeight2Resolvers TODO: Deprecate once userset refactor is complete.

type TypesystemResolverFunc added in v1.2.0

type TypesystemResolverFunc func(ctx context.Context, storeID, modelID string) (*TypeSystem, error)

func MemoizedTypesystemResolverFunc added in v1.2.0

func MemoizedTypesystemResolverFunc(datastore storage.AuthorizationModelReadBackend, maxSize int) (TypesystemResolverFunc, func(), error)

MemoizedTypesystemResolverFunc does several things.

If given a model ID: validates the model ID, and tries to fetch it from the cache. If not found in the cache, fetches from the datastore, validates it, stores in cache, and returns it.

If not given a model ID: fetches the latest model ID from the datastore, then sees if the model ID is in the cache. If it is, returns it. Else, validates it and returns it.

type WalkUsersetRewriteHandler added in v0.3.2

type WalkUsersetRewriteHandler func(rewrite *openfgav1.Userset) interface{}

WalkUsersetRewriteHandler is a userset rewrite handler that is applied to a node in a userset rewrite tree. Implementations of the WalkUsersetRewriteHandler should return a non-nil value when the traversal over the rewrite tree should terminate and nil if traversal should proceed to other nodes in the tree.

Jump to

Keyboard shortcuts

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