FGA API Reference
Application-facing access checks, authorized pages, entity-backed resources, and grants.
This page documents the application-facing FGA surface. The recommended path is SqlOSDbContext<TContext> plus ISqlOSResourceEntity for protected domain rows, explicit subject provisioning, and explicit role grants. Public schema/bootstrap implementation classes are not intended as normal application extension points.
The core authorization service. Injected via DI as ISqlOSFgaAuthService.
Check if a subject has access to a specific resource with a given permission. Walks up the resource hierarchy from the target resource to the root, looking for grants whose role includes the required permission.
var access = await authService.CheckAccessAsync(subjectId, "CHAIN_VIEW", "chain-1");
if (!access.Allowed)
return Results.Json(new { error = "Permission denied" }, statusCode: 403);Parameters
| Name | Type | Description |
|---|---|---|
subjectId | string | The subject (user, agent, etc.) to check access for. |
permissionKey | string | The permission key to check (e.g., "CHAIN_VIEW"). |
resourceId | string | The resource ID to check access on. |
Returns
Task<SqlOSFgaAccessCheckResult>
| Field | Type | Description |
|---|---|---|
Allowed | bool | Whether the subject has the permission on the resource. |
Trace | List<SqlOSFgaAccessTrace>? | Step-by-step trace of how the decision was made. |
Error | string? | Error message if the check failed unexpectedly. |
Check whether a subject has a permission on the configured FGA root resource. Use it for an intentionally global capability granted at root; it does not scan for the permission on arbitrary descendants.
var canEdit = await authService.HasCapabilityAsync(subjectId, "CHAIN_EDIT");
if (!canEdit)
return Results.Json(new { error = "Permission denied" }, statusCode: 403);Parameters
| Name | Type | Description |
|---|---|---|
subjectId | string | The subject to check. |
permissionKey | string | The permission key to check. |
Returns
Task<bool> — the result of CheckAccessAsync(subjectId, permissionKey, RootResourceId).
There are two ways, and only two: a page of a query with ToPageAsync, and one resource with CheckAccessAsync (or AuthorizedDetailAsync, built on it). SqlOS has no authorized count, Any, join, or unpaged list: each of those costs every row the caller can see. BuildFilterAsync was removed for that reason: a filter kept .Where(filter).OrderBy(...).Take(20) compiling and correct while it read the table for a caller who sees little of it.
Point checks, traces, and pages apply the same lifecycle rules automatically. Inactive users and groups, expired service accounts, inactive target resources, and resources below an inactive ancestor are denied even when a matching grant remains stored. Applications do not need to revoke every grant when deactivating one of these records, and should not add a separate display-only lifecycle filter around authorization queries.
Provision typed subjects with the SDK helpers rather than inserting only a bare SqlOSFgaSubject: authorization fails closed when a user, group, agent, or service_account subject is missing its corresponding typed lifecycle row.
Rebuild the entries of every page order in the context's model (the primary key and every index of each protected entity) from the application tables and the resource graph.
await authService.RebuildPageOrdersAsync(cancellationToken);For each order: delete all entries, then insert them in one statement, inside one transaction per order. The cost is the table's rows times the tree depth. SqlOSDbContext<TContext> keeps entries current for every write that goes through SaveChanges; call this after writes that bypass EF Core (bulk loads, raw SQL, ExecuteUpdate/ExecuteDelete) and for recovery. Until then, rows those writes inserted are missing from pages and rows they changed page at their old position; a row the caller may not see is never returned. It runs without a command timeout; the cancellation token stops it. Run it while the application is not writing to those tables: a save during a rebuild waits for it, or makes it fail with a deadlock or duplicate key, and running it again fixes that.
Returns
Task — completes when every page order has been rebuilt.
Produce a detailed, structured trace of a resource access decision. Shows every step of the hierarchy walk and which grants matched or didn't. Useful for debugging authorization issues.
var trace = await authService.TraceResourceAccessAsync(
subjectId, "chain-1", "CHAIN_VIEW");
// trace contains the full decision pathParameters
| Name | Type | Description |
|---|---|---|
subjectId | string | The subject to trace access for. |
resourceId | string | The target resource. |
permissionKey | string | The permission to trace. |
Returns
Task<SqlOSFgaResourceAccessTrace> — structured trace of the full decision.
Canonical SDK helpers for resource lifecycle, subject provisioning, and role grants. Available via using SqlOS.Extensions.
For protected application rows, implement ISqlOSResourceEntity and let SqlOSDbContext<TContext> synchronize SqlOSFgaResource rows during SaveChanges / SaveChangesAsync.
public sealed class Workspace : ISqlOSResourceEntity
{
public Guid Id { get; set; }
public string ResourceId { get; set; } = "";
public string OrganizationId { get; set; } = "";
public string Name { get; set; } = "";
public string ResourceTypeId => "workspace";
public string ResourceName => Name;
public string ParentResourceId => $"org::{OrganizationId}";
public string? ResourceDescription => null;
public bool ResourceIsActive => true;
}Manual resource APIs remain available for resources that are not backed by domain entities:
| Method | Use |
|---|---|
CreateResourceAsync(...) | Strict create with a generated resource ID. |
CreateResourceWithIdAsync(...) | Strict create with an explicit stable resource ID. |
ProvisionResourceWithIdAsync(...) | Idempotent create/update for explicit non-entity resources. |
DeleteResourceAsync(...) | Delete one resource and its direct grants without cascading child resources. |
Subjects are provisioned explicitly. Grants never create subjects implicitly.
| Method | Use |
|---|---|
ProvisionUserSubjectAsync(...) | Idempotently provision a user FGA subject and typed user row. |
ProvisionAgentSubjectAsync(...) | Idempotently provision an agent FGA subject and typed agent row. |
ProvisionServiceAccountSubjectAsync(...) | Idempotently provision a service-account FGA subject and typed service-account row. |
GrantRoleAsync(...) | Idempotently grant a role by key or ID to an existing subject/resource. |
RevokeRoleAsync(...) | Remove a role grant by key or ID if it exists. |
Lower-level/read-side FGA convenience extensions. Available via using SqlOS.Fga.Extensions.
CreateResource(...) is a lower-level/manual lifecycle helper kept for manual FGA samples and existing code. Do not use it as the normal protected-entity creation path. For protected application rows, prefer ISqlOSResourceEntity plus SqlOSDbContext<TContext>.
// Manual lifecycle sample only.
var resourceId = context.CreateResource("retail_root", request.Name, "chain");Read the page of a query that a subject may see (SqlOS.Fga.Extensions).
var page = await db.Products
.AsNoTracking()
.Where(p => p.Name.Contains(term))
.OrderBy(p => p.Price)
.ToPageAsync(subjectId, "product.view", pageSize: 20, cursor: request.Cursor, cancellationToken);
return Results.Ok(page.ToResponse(p => new ProductDto(p)));public static Task<SqlOSCursorPage<T>> ToPageAsync<T>(
this IQueryable<T> query,
string subjectId,
string permissionKey,
int pageSize,
string? cursor = null,
CancellationToken cancellationToken = default)
where T : class, IHasResourceId| Name | Type | Description |
|---|---|---|
query | IQueryable<T> | A query that starts from a DbSet of a context deriving from SqlOSDbContext<TContext>, with optional Where, Include/ThenInclude, tracking, TagWith, IgnoreQueryFilters and AsSplitQuery, ending with one OrderBy/OrderByDescending and any number of ThenBy/ThenByDescending in the same direction over mapped scalar properties. The primary key is appended to the order. |
subjectId | string | The caller. Its active group memberships are included. |
permissionKey | string | The permission each row's resource must grant. |
pageSize | int | 1 to 1,000. |
cursor | string? | The previous page's NextCursor, or null for the first page. |
Returns Task<SqlOSCursorPage<T>>, the visible rows after cursor in the query's order. An order an index of the table covers costs about a page for any caller; one no index covers reads the query in order and checks each row, for every caller, and logs a warning naming the index to add.
Behavior
NextCursor, a logged warning, and no page queries.SqlOSFgaPage_{Table}_{Columns} in SqlOS's FGA schema, added to the EF model so the next migration creates it). The query's order columns with the key appended must equal an index's columns exactly, in sequence; direction is free, and an index that ends with the key is the same order as one without it. An index that contains ResourceId, or whose columns are exactly a foreign key's, is a lookup and gets no copy. A nullable order column, a string without a maximum length, an unsupported type, a composite primary key, an entity without a mapped ResourceId, and an owned, view-mapped, TPT or TPC entity get no copy either; the model builds, and startup logs one warning per skip with the fix.SqlOS.Fga category.The cursor rule. Pass NextCursor back as it came. Don't write your own position filter (.Where(x => x.CreatedAt < lastSeen), keyset libraries, since= versions): ToPageAsync seeks under each of the caller's nodes from the cursor, and a hand-written position is just another filter there, so every page walks the caller's rows from the start of the order. For a change feed, the cursor is the sync token the client stores.
Exceptions
| Exception | When |
|---|---|
ArgumentOutOfRangeException | pageSize is outside 1 to 1,000. |
ArgumentException | The query does not start from a DbSet of a context deriving from SqlOSDbContext<TContext>; no OrderBy; mixed directions; an order over anything but a mapped non-nullable scalar property; Select, Skip, Take, Distinct, GroupBy, Join, SelectMany, Union or Concat in the chain; a cursor issued for another list (ParamName is "cursor"). |
SqlOSCursorException | The cursor is not one this list issued. |
The page ToPageAsync returns (SqlOS.Pagination).
| Member | Type | Description |
|---|---|---|
Data | IReadOnlyList<T> | The page's rows, in the query's order. |
PageSize | int | The requested page size. |
NextCursor | string? | The cursor of the next page; null on the last page. |
HasNextPage | bool | NextCursor != null. |
ToResponse(selector) | object | { data, pageSize, nextCursor, hasNextPage } with each row projected. |
Fetch a single entity by predicate, check authorization, and return the appropriate HTTP result in one call. Replaces the pattern of fetch → check → map → return.
return await authService.AuthorizedDetailAsync(
context.Chains.Include(c => c.Locations),
c => c.Id == id,
subjectId,
"CHAIN_VIEW",
chain => new ChainDetailDto
{
Id = chain.Id,
Name = chain.Name,
LocationCount = chain.Locations.Count
});Parameters
| Name | Type | Description |
|---|---|---|
authService | ISqlOSFgaAuthService | The auth service (called as extension method). |
query | IQueryable<TEntity> | The queryable to fetch from (can include .Include()). |
predicate | Expression<Func<TEntity, bool>> | Filter to find the single entity (e.g., c => c.Id == id). |
subjectId | string | The subject to authorize. |
permissionKey | string | The permission to check on the entity's resource. |
selector | Func<TEntity, TDto> | Maps the entity to a DTO for the response body. |
Type constraint: TEntity : class, IHasResourceId
Returns
Task<IResult> — one of:
| Condition | HTTP Result |
|---|---|
| Entity not found | 404 Not Found |
| Access denied | 403 { "error": "Permission denied" } |
| Access granted | 200 with the mapped DTO |
Recommended resource lifecycle contract for protected application rows. It extends IHasResourceId and gives SqlOSDbContext<TContext> enough metadata to create, update, and delete backing FGA resources during EF saves.
public interface ISqlOSResourceEntity : IHasResourceId
{
string ResourceTypeId { get; }
string ResourceName { get; }
string? ParentResourceId { get; }
string? ResourceDescription { get; }
bool ResourceIsActive { get; }
}Lower-level contract that exposes an entity's FGA resource ID. Required for ToPageAsync and AuthorizedDetailAsync; SqlOS keeps a page order for the primary key and every index of an entity that implements it. ISqlOSResourceEntity extends this interface and is the recommended contract for normal protected domain rows.
public interface IHasResourceId
{
string ResourceId { get; }
}Lower-level implementation
public class Chain : IHasResourceId
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public string ResourceId { get; set; } = "";
public string Name { get; set; } = "";
}public class SqlOSFgaAccessCheckResult
{
public bool Allowed { get; set; }
public List<SqlOSFgaAccessTrace>? Trace { get; set; }
public string? Error { get; set; }
}public class SqlOSFgaAccessTrace
{
public string Step { get; set; }
public string Detail { get; set; }
public string? ResourceId { get; set; }
public string? ResourceName { get; set; }
public string? GrantId { get; set; }
public string? RoleName { get; set; }
public string? SubjectName { get; set; }
}public class SqlOSFgaResource
{
public string Id { get; set; }
public string ParentId { get; set; }
public string Name { get; set; }
public string ResourceTypeId { get; set; }
public bool IsActive { get; set; }
}public class SqlOSFgaGrant
{
public string Id { get; set; }
public string SubjectId { get; set; }
public string ResourceId { get; set; }
public string RoleId { get; set; }
public string? Description { get; set; }
}public class SqlOSFgaSubject
{
public string Id { get; set; }
public string SubjectTypeId { get; set; }
public string DisplayName { get; set; }
public string? OrganizationId { get; set; }
public string? ExternalRef { get; set; }
}