server

package
v1.11.1 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2025 License: Apache-2.0 Imports: 46 Imported by: 11

Documentation

Overview

Package server contains the endpoint handlers.

Index

Examples

Constants

View Source
const (
	AuthorizationModelIDHeader = "Openfga-Authorization-Model-Id"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type OpenFGAServiceV1Option added in v1.3.0

type OpenFGAServiceV1Option func(s *Server)

func WithAccessControlParams added in v1.7.0

func WithAccessControlParams(enabled bool, storeID string, modelID string, authnMethod string) OpenFGAServiceV1Option

WithAccessControlParams sets enabled, the storeID, and modelID for the access control feature.

func WithAuthorizationModelCacheSize added in v1.5.4

func WithAuthorizationModelCacheSize(maxAuthorizationModelCacheSize int) OpenFGAServiceV1Option

WithAuthorizationModelCacheSize sets the maximum number of authorization models that will be cached in memory.

func WithCacheControllerEnabled added in v1.7.0

func WithCacheControllerEnabled(enabled bool) OpenFGAServiceV1Option

WithCacheControllerEnabled enables cache invalidation of different cache entities.

func WithCacheControllerTTL added in v1.7.0

func WithCacheControllerTTL(ttl time.Duration) OpenFGAServiceV1Option

WithCacheControllerTTL sets the frequency for the controller to execute.

func WithChangelogHorizonOffset added in v1.3.0

func WithChangelogHorizonOffset(offset int) OpenFGAServiceV1Option

WithChangelogHorizonOffset sets an offset (in minutes) from the current time. Changes that occur after this offset will not be included in the response of ReadChanges API. If your datastore is eventually consistent or if you have a database with replication delay, we recommend setting this (e.g. 1 minute).

func WithCheckCacheLimit added in v1.8.1

func WithCheckCacheLimit(limit uint32) OpenFGAServiceV1Option

WithCheckCacheLimit sets the check cache size limit (in items).

func WithCheckDatabaseThrottle added in v1.8.13

func WithCheckDatabaseThrottle(threshold int, duration time.Duration) OpenFGAServiceV1Option

func WithCheckIteratorCacheEnabled added in v1.7.0

func WithCheckIteratorCacheEnabled(enabled bool) OpenFGAServiceV1Option

WithCheckIteratorCacheEnabled enables caching of iterators produced within Check for subsequent requests.

func WithCheckIteratorCacheMaxResults added in v1.7.0

func WithCheckIteratorCacheMaxResults(limit uint32) OpenFGAServiceV1Option

WithCheckIteratorCacheMaxResults sets the limit of an iterator size to cache (in items) Needs WithCheckIteratorCacheEnabled set to true.

func WithCheckIteratorCacheTTL added in v1.8.1

func WithCheckIteratorCacheTTL(ttl time.Duration) OpenFGAServiceV1Option

WithCheckIteratorCacheTTL sets the TTL of iterator caches. Needs WithCheckIteratorCacheEnabled set to true.

func WithCheckQueryCacheEnabled added in v1.3.1

func WithCheckQueryCacheEnabled(enabled bool) OpenFGAServiceV1Option

WithCheckQueryCacheEnabled enables caching of Check results for the Check and List objects APIs. This cache is shared for all requests. See also WithCheckCacheLimit and WithCheckQueryCacheTTL.

func WithCheckQueryCacheTTL added in v1.3.1

func WithCheckQueryCacheTTL(ttl time.Duration) OpenFGAServiceV1Option

WithCheckQueryCacheTTL sets the TTL of cached checks and list objects partial results Needs WithCheckQueryCacheEnabled set to true.

func WithContext added in v1.5.8

func WithContext(ctx context.Context) OpenFGAServiceV1Option

WithContext passes the server context to allow for graceful shutdowns.

func WithContextPropagationToDatastore added in v1.8.0

func WithContextPropagationToDatastore(enable bool) OpenFGAServiceV1Option

WithContextPropagationToDatastore determines whether the request context is propagated to the datastore. When enabled, the datastore receives cancellation signals when an API request is cancelled. When disabled, datastore operations continue even if the original request context is cancelled. Disabling context propagation is normally desirable to avoid unnecessary database connection churn. If not specified, the default value is false (separate storage and request contexts).

func WithContinuationTokenSerializer added in v1.8.0

func WithContinuationTokenSerializer(ds encoder.ContinuationTokenSerializer) OpenFGAServiceV1Option

func WithDatastore added in v1.3.0

WithDatastore passes a datastore to the Server. You must call storage.OpenFGADatastore.Close on it after you have stopped using it.

func WithDispatchThrottlingCheckResolverEnabled added in v1.5.1

func WithDispatchThrottlingCheckResolverEnabled(enabled bool) OpenFGAServiceV1Option

WithDispatchThrottlingCheckResolverEnabled sets whether dispatch throttling is enabled for Check requests. Enabling this feature will prioritize dispatched requests requiring less than the configured dispatch threshold over requests whose dispatch count exceeds the configured threshold.

func WithDispatchThrottlingCheckResolverFrequency added in v1.5.1

func WithDispatchThrottlingCheckResolverFrequency(frequency time.Duration) OpenFGAServiceV1Option

WithDispatchThrottlingCheckResolverFrequency defines how frequent dispatch throttling will be evaluated for Check requests. Frequency controls how frequently throttled dispatch requests are evaluated to determine whether it can be processed. This value should not be too small (i.e., in the ns ranges) as i) there are limitation in timer resolution and ii) very small value will result in a higher frequency of processing dispatches, which diminishes the value of the throttling.

func WithDispatchThrottlingCheckResolverMaxThreshold added in v1.5.4

func WithDispatchThrottlingCheckResolverMaxThreshold(maxThreshold uint32) OpenFGAServiceV1Option

WithDispatchThrottlingCheckResolverMaxThreshold define the maximum threshold values allowed It will ensure checkDispatchThrottlingMaxThreshold will never be smaller than threshold.

func WithDispatchThrottlingCheckResolverThreshold added in v1.5.1

func WithDispatchThrottlingCheckResolverThreshold(defaultThreshold uint32) OpenFGAServiceV1Option

WithDispatchThrottlingCheckResolverThreshold define the number of dispatches to be throttled. In addition, it will update checkDispatchThrottlingMaxThreshold if required.

func WithExperimentals added in v1.3.0

func WithExperimentals(experimentals ...string) OpenFGAServiceV1Option

func WithFeatureFlagClient added in v1.10.4

func WithFeatureFlagClient(client featureflags.Client) OpenFGAServiceV1Option

func WithListObjectsDatabaseThrottle added in v1.8.13

func WithListObjectsDatabaseThrottle(threshold int, duration time.Duration) OpenFGAServiceV1Option

func WithListObjectsDeadline added in v1.3.0

func WithListObjectsDeadline(deadline time.Duration) OpenFGAServiceV1Option

WithListObjectsDeadline affect the ListObjects API and Streamed ListObjects API only. It sets the maximum amount of time that the server will spend gathering results.

func WithListObjectsDispatchThrottlingEnabled added in v1.5.4

func WithListObjectsDispatchThrottlingEnabled(enabled bool) OpenFGAServiceV1Option

WithListObjectsDispatchThrottlingEnabled sets whether dispatch throttling is enabled for List Objects requests. Enabling this feature will prioritize dispatched requests requiring less than the configured dispatch threshold over requests whose dispatch count exceeds the configured threshold.

func WithListObjectsDispatchThrottlingFrequency added in v1.5.4

func WithListObjectsDispatchThrottlingFrequency(frequency time.Duration) OpenFGAServiceV1Option

WithListObjectsDispatchThrottlingFrequency defines how frequent dispatch throttling will be evaluated for List Objects requests. Frequency controls how frequently throttled dispatch requests are evaluated to determine whether it can be processed. This value should not be too small (i.e., in the ns ranges) as i) there are limitation in timer resolution and ii) very small value will result in a higher frequency of processing dispatches, which diminishes the value of the throttling.

func WithListObjectsDispatchThrottlingMaxThreshold added in v1.5.4

func WithListObjectsDispatchThrottlingMaxThreshold(maxThreshold uint32) OpenFGAServiceV1Option

WithListObjectsDispatchThrottlingMaxThreshold define the maximum threshold values allowed It will ensure listObjectsDispatchThrottlingMaxThreshold will never be smaller than threshold.

func WithListObjectsDispatchThrottlingThreshold added in v1.5.4

func WithListObjectsDispatchThrottlingThreshold(threshold uint32) OpenFGAServiceV1Option

WithListObjectsDispatchThrottlingThreshold define the number of dispatches to be throttled for List Objects requests.

func WithListObjectsIteratorCacheEnabled added in v1.8.10

func WithListObjectsIteratorCacheEnabled(enabled bool) OpenFGAServiceV1Option

WithListObjectsIteratorCacheEnabled enables caching of iterators produced within Check for subsequent requests.

func WithListObjectsIteratorCacheMaxResults added in v1.8.10

func WithListObjectsIteratorCacheMaxResults(limit uint32) OpenFGAServiceV1Option

WithListObjectsIteratorCacheMaxResults sets the limit of an iterator size to cache (in items) Needs WithListObjectsIteratorCacheEnabled set to true.

func WithListObjectsIteratorCacheTTL added in v1.8.10

func WithListObjectsIteratorCacheTTL(ttl time.Duration) OpenFGAServiceV1Option

WithListObjectsIteratorCacheTTL sets the TTL of iterator caches. Needs WithListObjectsCheckIteratorCacheEnabled set to true.

func WithListObjectsMaxResults added in v1.3.0

func WithListObjectsMaxResults(limit uint32) OpenFGAServiceV1Option

WithListObjectsMaxResults affects the ListObjects API only. It sets the maximum number of results that this API will return.

func WithListUsersDatabaseThrottle added in v1.8.13

func WithListUsersDatabaseThrottle(threshold int, duration time.Duration) OpenFGAServiceV1Option

func WithListUsersDeadline added in v1.5.4

func WithListUsersDeadline(deadline time.Duration) OpenFGAServiceV1Option

WithListUsersDeadline affect the ListUsers API only. It sets the maximum amount of time that the server will spend gathering results.

func WithListUsersDispatchThrottlingEnabled added in v1.5.8

func WithListUsersDispatchThrottlingEnabled(enabled bool) OpenFGAServiceV1Option

WithListUsersDispatchThrottlingEnabled sets whether dispatch throttling is enabled for ListUsers requests. Enabling this feature will prioritize dispatched requests requiring less than the configured dispatch threshold over requests whose dispatch count exceeds the configured threshold.

func WithListUsersDispatchThrottlingFrequency added in v1.5.8

func WithListUsersDispatchThrottlingFrequency(frequency time.Duration) OpenFGAServiceV1Option

WithListUsersDispatchThrottlingFrequency defines how frequent dispatch throttling will be evaluated for ListUsers requests. Frequency controls how frequently throttled dispatch requests are evaluated to determine whether it can be processed. This value should not be too small (i.e., in the ns ranges) as i) there are limitation in timer resolution and ii) very small value will result in a higher frequency of processing dispatches, which diminishes the value of the throttling.

func WithListUsersDispatchThrottlingMaxThreshold added in v1.5.8

func WithListUsersDispatchThrottlingMaxThreshold(maxThreshold uint32) OpenFGAServiceV1Option

WithListUsersDispatchThrottlingMaxThreshold define the maximum threshold values allowed It will ensure listUsersDispatchThrottlingMaxThreshold will never be smaller than threshold.

func WithListUsersDispatchThrottlingThreshold added in v1.5.8

func WithListUsersDispatchThrottlingThreshold(threshold uint32) OpenFGAServiceV1Option

WithListUsersDispatchThrottlingThreshold define the number of dispatches to be throttled for ListUsers requests.

func WithListUsersMaxResults added in v1.5.4

func WithListUsersMaxResults(limit uint32) OpenFGAServiceV1Option

WithListUsersMaxResults affects the ListUsers API only. It sets the maximum number of results that this API will return. If it's zero, all results will be attempted to be returned.

func WithLogger added in v1.3.0

func WithLogger(l logger.Logger) OpenFGAServiceV1Option

func WithMaxAuthorizationModelSizeInBytes added in v1.3.3

func WithMaxAuthorizationModelSizeInBytes(size int) OpenFGAServiceV1Option

func WithMaxChecksPerBatchCheck added in v1.8.0

func WithMaxChecksPerBatchCheck(maxChecks uint32) OpenFGAServiceV1Option

WithMaxChecksPerBatchCheck defines the maximum number of checks allowed to be sent in a single BatchCheck request.

func WithMaxConcurrentChecksPerBatchCheck added in v1.8.0

func WithMaxConcurrentChecksPerBatchCheck(maxConcurrentChecks uint32) OpenFGAServiceV1Option

WithMaxConcurrentChecksPerBatchCheck defines the maximum number of checks allowed to be processed concurrently in a single batch request.

func WithMaxConcurrentReadsForCheck added in v1.3.0

func WithMaxConcurrentReadsForCheck(maxConcurrentReadsForCheck uint32) OpenFGAServiceV1Option

WithMaxConcurrentReadsForCheck sets a limit on the number of datastore reads that can be in flight for a given Check call. This number should be set depending on the RPS expected for Check and ListObjects APIs, the number of OpenFGA replicas running, and the number of connections the datastore allows. E.g. If Datastore.MaxOpenConns = 100 and assuming that each Check call takes 1 second and no traffic to ListObjects API: - One OpenFGA replica and expected traffic of 100 RPS => set it to 1. - One OpenFGA replica and expected traffic of 1 RPS => set it to 100. - Two OpenFGA replicas and expected traffic of 1 RPS => set it to 50.

func WithMaxConcurrentReadsForListObjects added in v1.3.0

func WithMaxConcurrentReadsForListObjects(maxConcurrentReads uint32) OpenFGAServiceV1Option

WithMaxConcurrentReadsForListObjects sets a limit on the number of datastore reads that can be in flight for a given ListObjects call. This number should be set depending on the RPS expected for Check and ListObjects APIs, the number of OpenFGA replicas running, and the number of connections the datastore allows. E.g. If Datastore.MaxOpenConns = 100 and assuming that each ListObjects call takes 1 second and no traffic to Check API: - One OpenFGA replica and expected traffic of 100 RPS => set it to 1. - One OpenFGA replica and expected traffic of 1 RPS => set it to 100. - Two OpenFGA replicas and expected traffic of 1 RPS => set it to 50.

func WithMaxConcurrentReadsForListUsers added in v1.5.4

func WithMaxConcurrentReadsForListUsers(maxConcurrentReadsForListUsers uint32) OpenFGAServiceV1Option

WithMaxConcurrentReadsForListUsers sets a limit on the number of datastore reads that can be in flight for a given ListUsers call. This number should be set depending on the RPS expected for all query APIs, the number of OpenFGA replicas running, and the number of connections the datastore allows. E.g. If Datastore.MaxOpenConns = 100 and assuming that each ListUsers call takes 1 second and no traffic to other query APIs: - One OpenFGA replica and expected traffic of 100 RPS => set it to 1. - One OpenFGA replica and expected traffic of 1 RPS => set it to 100. - Two OpenFGA replicas and expected traffic of 1 RPS => set it to 50.

func WithPlanner added in v1.10.0

func WithPlanner(planner *planner.Planner) OpenFGAServiceV1Option

func WithRequestDurationByDispatchCountHistogramBuckets added in v1.5.1

func WithRequestDurationByDispatchCountHistogramBuckets(buckets []uint) OpenFGAServiceV1Option

WithRequestDurationByDispatchCountHistogramBuckets sets the buckets used in labelling the requestDurationByQueryAndDispatchHistogram.

func WithRequestDurationByQueryHistogramBuckets added in v1.3.1

func WithRequestDurationByQueryHistogramBuckets(buckets []uint) OpenFGAServiceV1Option

WithRequestDurationByQueryHistogramBuckets sets the buckets used in labelling the requestDurationByQueryAndDispatchHistogram.

func WithRequestTimeout added in v1.10.2

func WithRequestTimeout(timeout time.Duration) OpenFGAServiceV1Option

func WithResolveNodeBreadthLimit added in v1.3.0

func WithResolveNodeBreadthLimit(limit uint32) OpenFGAServiceV1Option

WithResolveNodeBreadthLimit sets a limit on the number of goroutines that can be created when evaluating a subtree of a Check, ListObjects or ListUsers call. Thinking of a Check request as a tree of evaluations, this option controls, on a given level of the tree, the maximum number of nodes that can be evaluated concurrently (the breadth). If your authorization models are very complex (e.g. one relation is a union of many relations, or one relation is deeply nested), or if you have lots of users for (object, relation) pairs, you should set this option to be a low number (e.g. 1000).

func WithResolveNodeLimit added in v1.3.0

func WithResolveNodeLimit(limit uint32) OpenFGAServiceV1Option

WithResolveNodeLimit sets a limit on the number of recursive calls that one Check, ListObjects or ListUsers call will allow. Thinking of a request as a tree of evaluations, this option controls how many levels we will evaluate before throwing an error that the authorization model is too complex.

func WithShadowCheckResolverTimeout added in v1.8.8

func WithShadowCheckResolverTimeout(threshold time.Duration) OpenFGAServiceV1Option

WithShadowCheckResolverTimeout is the amount of time to wait for the shadow Check evaluation response.

func WithShadowListObjectsQueryMaxDeltaItems added in v1.9.0

func WithShadowListObjectsQueryMaxDeltaItems(maxDeltaItems int) OpenFGAServiceV1Option

func WithShadowListObjectsQueryTimeout added in v1.9.0

func WithShadowListObjectsQueryTimeout(threshold time.Duration) OpenFGAServiceV1Option

WithShadowListObjectsQueryTimeout is the amount of time to wait for the shadow ListObjects evaluation response.

func WithSharedIteratorEnabled added in v1.8.12

func WithSharedIteratorEnabled(enabled bool) OpenFGAServiceV1Option

WithSharedIteratorEnabled enables iterator to be shared across different consumer.

func WithSharedIteratorLimit added in v1.8.12

func WithSharedIteratorLimit(limit uint32) OpenFGAServiceV1Option

WithSharedIteratorLimit sets the number of items that can be shared.

func WithSharedIteratorTTL added in v1.8.13

func WithSharedIteratorTTL(ttl time.Duration) OpenFGAServiceV1Option

func WithTokenEncoder added in v1.3.0

func WithTokenEncoder(encoder encoder.Encoder) OpenFGAServiceV1Option

func WithTransport added in v1.3.0

func WithTransport(t gateway.Transport) OpenFGAServiceV1Option

WithTransport sets the connection transport.

type Server

type Server struct {
	openfgav1.UnimplementedOpenFGAServiceServer

	AccessControl serverconfig.AccessControlConfig
	AuthnMethod   string
	// contains filtered or unexported fields
}

A Server implements the OpenFGA service backend as both a GRPC and HTTP server.

func MustNewServerWithOpts added in v1.3.0

func MustNewServerWithOpts(opts ...OpenFGAServiceV1Option) *Server

MustNewServerWithOpts see NewServerWithOpts.

func NewServerWithOpts added in v1.3.0

func NewServerWithOpts(opts ...OpenFGAServiceV1Option) (*Server, error)

NewServerWithOpts returns a new server. You must call Close on it after you are done using it.

Example
datastore := memory.New() // other supported datastores include Postgres, MySQL and SQLite
defer datastore.Close()

openfga, err := NewServerWithOpts(WithDatastore(datastore),
	WithCheckQueryCacheEnabled(true),
	// more options available
	WithFeatureFlagClient(featureflags.NewHardcodedBooleanClient(true)),
	WithShadowListObjectsQueryTimeout(17*time.Millisecond),
	WithShadowListObjectsQueryMaxDeltaItems(20),
)
if err != nil {
	panic(err)
}
defer openfga.Close()

// create store
store, err := openfga.CreateStore(context.Background(),
	&openfgav1.CreateStoreRequest{Name: "demo"})
if err != nil {
	panic(err)
}

model := parser.MustTransformDSLToProto(`
	model
		schema 1.1

	type user

	type document
		relations
			define reader: [user]`)

// write the model to the store
authorizationModel, err := openfga.WriteAuthorizationModel(context.Background(), &openfgav1.WriteAuthorizationModelRequest{
	StoreId:         store.GetId(),
	TypeDefinitions: model.GetTypeDefinitions(),
	Conditions:      model.GetConditions(),
	SchemaVersion:   model.GetSchemaVersion(),
})
if err != nil {
	panic(err)
}

// write tuples to the store
_, err = openfga.Write(context.Background(), &openfgav1.WriteRequest{
	StoreId: store.GetId(),
	Writes: &openfgav1.WriteRequestWrites{
		TupleKeys: []*openfgav1.TupleKey{
			{Object: "document:budget", Relation: "reader", User: "user:anne"},
		},
	},
	Deletes: nil,
})
if err != nil {
	panic(err)
}

// make an authorization check
checkResponse, err := openfga.Check(context.Background(), &openfgav1.CheckRequest{
	StoreId:              store.GetId(),
	AuthorizationModelId: authorizationModel.GetAuthorizationModelId(), // optional, but recommended for speed
	TupleKey: &openfgav1.CheckRequestTupleKey{
		User:     "user:anne",
		Relation: "reader",
		Object:   "document:budget",
	},
})
if err != nil {
	panic(err)
}
fmt.Println(checkResponse.GetAllowed())
Output:

true

func (*Server) BatchCheck added in v1.8.0

func (*Server) Check

func (*Server) Close added in v1.4.3

func (s *Server) Close()

Close releases the server resources.

func (*Server) CreateStore

func (*Server) DeleteStore

func (*Server) Expand

func (*Server) GetStore

func (*Server) IsAccessControlEnabled added in v1.7.0

func (s *Server) IsAccessControlEnabled() bool

IsAccessControlEnabled returns true if the access control feature is enabled.

func (*Server) IsReady

func (s *Server) IsReady(ctx context.Context) (bool, error)

IsReady reports whether the datastore is ready. Please see the implementation of [storage.OpenFGADatastore.IsReady] for your datastore.

func (*Server) ListObjects

func (*Server) ListStores

func (*Server) ListUsers added in v1.5.4

ListUsers returns all users (e.g. subjects) matching a specific user filter criteria that have a specific relation with some object.

func (*Server) Read

func (*Server) ReadChanges

func (*Server) Write

Directories

Path Synopsis
Package commands contains the code that handles each endpoint.
Package commands contains the code that handles each endpoint.
reverseexpand
Package reverseexpand contains the code that handles the ReverseExpand API
Package reverseexpand contains the code that handles the ReverseExpand API
Package config contains all knobs and defaults used to configure features of OpenFGA when running as a standalone server.
Package config contains all knobs and defaults used to configure features of OpenFGA when running as a standalone server.
Package errors contains custom error codes that are sent to clients.
Package errors contains custom error codes that are sent to clients.
Package health contains the service that check the health of an OpenFGA server.
Package health contains the service that check the health of an OpenFGA server.

Jump to

Keyboard shortcuts

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