access

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT, MIT Imports: 26 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

access

Go library for role-based access control (RBAC) with domain-partitioned permission management. The release's default roles travel with the release, in a role file embedded in the application binary; custom roles and role memberships live in typed tables owned by this library. Permission checks are answered by an immutable in-memory snapshot compiled from both — lock-free, allocation-free, and never touching the database on the request path.

Overview

Manages user permissions and roles across multiple domains or tenants. Supports PostgreSQL and Google Cloud Spanner as persistence backends through the postgresstore and spannerstore subpackages.

Features

  • Role-based access control (RBAC)
  • Multi-tenant support with structural global and every-domain scopes
  • Resource- and field-level permissions (employees, employees.name, employees.*)
  • Compiled in-memory snapshot evaluation with near-realtime change propagation
  • User, role, and permission management APIs
  • HTTP handlers for REST endpoints
  • Default roles shipped in the application binary, with a deploy-time policy check

Installation

go get github.com/impulseframework/impulse/access

Core Concepts

  • Scope: Where a request is — the global partition (accesstypes.GlobalScope()) or one tenant domain (accesstypes.DomainScope(domain)). Permission checks, permission digests and the foothold question take a Scope, because a request is in exactly one partition. Global-ness is structural: no domain string means "global", so any tenant name is legal data (a tenant literally named "global" is an ordinary tenant). Scopes are opaque labels to access — the application owns its tenant list, and checks fail closed on unknown tenants.
  • PolicyScope: Where policy is held — a role membership, a custom role and its grants live in the global partition (accesstypes.GlobalPolicyScope()), in one tenant domain (accesstypes.DomainPolicyScope(domain)), or in every tenant domain (accesstypes.EveryDomainPolicyScope()). The policy store and the user manager take a PolicyScope. A membership held in every domain reaches every tenant, including a tenant the store holds no other row in, so a tenant created at run time needs nothing written for its every-domain members. Every domain is not a place a request can be in, so nothing converts a PolicyScope into a Scope, and passing a PolicyScope to a check fails to compile. Scope.PolicyScope() converts the other way, and PolicyScope.Covers(scope) answers whether policy held somewhere applies in a partition.
  • User: Individual with assigned roles
  • Role: Named collection of permissions, of one of two kinds. A default role is declared in the release's role file (see Default Roles): a global default is held in the global partition, a domain default in every tenant domain, and the store holds no row for either. A custom role is created at run time through the user manager and held where it was created; its identity is (policy scope, role).
  • Permission: Action that can be performed (List, Read, Create, Update, Delete, ...)
  • Resource: What a permission applies to. A resource name has at most one dot: employees is a parent resource, employees.name is one field on it, and employees.* grants all fields by implication (covering fields that don't exist yet). An endpoint grant (employees) gives no field visibility, and field grants don't grant the endpoint — that separation is the point of field-level control.

Policy Stores

Each store owns six tables named {Prefix}{Store}{Roles|UserRoles|RoleGrants|Groups|GroupMembers|GroupRoles} — defaults yield AccessRoles, AccessUserRoles, AccessRoleGrants, AccessGroups, AccessGroupMembers, AccessGroupRoles. Applications with several independent permission stores in one database give each a store name (WithStore("AdminPortal") → AccessAdminPortalRoles, ...); separate tables make cross-store leakage structurally impossible.

The tables hold what is written at run time: custom roles, their grants, role memberships, and the groups of people with their members and the roles they hold. The release's default roles have no rows. Each row records where it is held in its own columns, never in a distinguished domain value: Kind is global, domain or every and is checked in the database, DomainId carries the tenant's id on a domain row and is empty otherwise, and Axis is the empty string on every row today. Any tenant name is therefore ordinary data.

The access.Store interface the two subpackages implement is sealed: only this module's stores satisfy it. The stores are thin; validation, change signaling and snapshot compilation live in the access package, one code path for every store. Both stores keep the same contract:

  • Roles holds custom roles only, each with the description it was created with.
  • UserRoles stands alone. A membership names its role by name alone, since a default role has no row to reference, so InsertUserRole writes by role name; the access package checks that the name resolves before it writes. An index led by the user ({Prefix}{Store}UserRolesByUserID) serves ListUserMemberships, which lists every membership a user holds wherever it is held.
  • RoleGrants belongs to its custom role: interleaved in Roles on Spanner and a foreign key on PostgreSQL, both with cascading delete. A grant needs its role's row, and deleting a custom role deletes its grants.
  • DeleteRole refuses while memberships held in that scope that have not ended still name the role, checked in the same transaction as the delete, and takes the ended ones with the role.
  • A membership, a place in a group and a group's role each carry the period they count in, in two nullable columns, StartsAt and EndsAt (see Periods). An insert gives the row its period: it writes the row where the key is free, and where it is taken it replaces the period and leaves the rest of the row as it was. No row is written when a period begins or ends. The listings of what a person or a group holds return the rows that count at the database's present; ReadPolicy returns every row with its period.
  • Groups holds the groups of people, each under an id the access package generates, with where it is kept (Kind is global or domain, checked in the database: no group is kept in every domain), its name and its description. A unique index ({Prefix}{Store}GroupsByName) holds a name to one group where the group is kept.
  • GroupMembers holds the people in each group and GroupRoles the roles each group holds, a role named by name alone as a membership names it. Both reference their group (a foreign key in both stores), so DeleteGroup refuses a group that still has a member or holds a role that has not ended, checked in the same transaction as the delete, takes the ended ones with the group, and the database stands behind the check. An index led by the user ({Prefix}{Store}GroupMembersByUserId) serves the groups a person is in, and one led by where a role is held ({Prefix}{Store}GroupRolesByScope) serves the group roles held in one tenant.
  • ReadPolicy reads the custom roles, their grants, the memberships, and the groups with their members and roles, with one consistent view of the store, for the snapshot to compile.
  • Inserting an existing row and deleting an absent one are no-ops, and list results are sorted.

The library never runs DDL — applications own their schema lifecycle. DDL() returns the canonical schema rendered with the configured names; copy it into your migration file. The library's own test suites execute exactly these statements, so the shipped DDL is the tested DDL.

PostgreSQL
import "github.com/impulseframework/impulse/access/postgresstore"

// Rides the application's existing pgx pool.
store, err := postgresstore.New(pool /* *pgxpool.Pool */)

// Or a named store with a custom prefix:
store, err := postgresstore.New(pool, postgresstore.WithStore("AdminPortal"))

// Schema for your migration file:
for _, stmt := range store.DDL() { ... }
Google Cloud Spanner
import "github.com/impulseframework/impulse/access/spannerstore"

store, err := spannerstore.New(client /* *spanner.Client */)

// Or a named store:
store, err := spannerstore.New(client, spannerstore.WithStore("AdminPortal"))

Quick Start

package main

import (
    "context"
    "log"

    "github.com/impulseframework/impulse/access"
    "github.com/impulseframework/impulse/access/postgresstore"
    "github.com/impulseframework/impulse/accesstypes"
    "github.com/jackc/pgx/v5/pgxpool"
)

func main() {
    ctx := context.Background()

    pool, _ := pgxpool.New(ctx, "postgresql://user:pass@localhost/db")

    store, err := postgresstore.New(pool)
    if err != nil {
        log.Fatal(err)
    }

    // An application that ships default roles adds
    // access.WithDefaultRoles(collection, roles.File); see Default Roles.
    client, err := access.New(store)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    mgr := client.UserManager()

    // Where the request is, and where the policy for it is held.
    tenant1 := accesstypes.DomainScope("tenant1")
    tenant1Policy := tenant1.PolicyScope()

    // Create a custom role, saying what it is for, and grant permissions
    mgr.AddRole(ctx, tenant1Policy, "Administrator", "Administers the tenant.")
    mgr.AddRolePermissionResources(ctx, tenant1Policy, "Administrator", "Read", "documents", "documents.*")

    // Assign role to user
    mgr.AddUserRoles(ctx, tenant1Policy, "john.doe", "Administrator")

    // Check permissions: one Decision per resource, from one policy snapshot.
    env := accesstypes.NewEnvironment() // per-request decision context
    decisions, err := client.CheckUserResources(ctx, env, "john.doe", tenant1, "Read", "documents", "documents.title")
    if err != nil {
        log.Fatal(err)
    }
    if denied := decisions.DeniedResources(); len(denied) > 0 {
        // deny: shape your own Forbidden response
    }
}

Policy Snapshot, Freshness, and Lifecycle

Permission checks are served from an immutable in-memory snapshot: lock-free, allocation-free, and never touching the database on the request path. Policy changes propagate between instances in near-realtime through a change signal the application supplies (see Change signal below), with a background heartbeat as the correctness backstop: it re-reads the policy store (default every 1m) and swaps in a new snapshot only when the content changed, so cross-instance staleness is bounded by the heartbeat interval even if the signal breaks. Writes made through this client are visible to its own checks immediately.

The snapshot compiles the release's default roles from the role file beside the store's rows, in three parts: the global partition; the policy held in every domain, which is the domain default roles, the custom roles held in every domain and the memberships held in every domain; and, for each domain the store holds rows in, what that domain's rows add on top of the every-domain part. A check in a tenant the store holds no rows for is answered from the every-domain part alone, so a membership held in every domain reaches that tenant, and a thousand tenants share one compiled copy of the defaults.

client, err := access.New(store,
    // The release's default roles: the role file embedded in the binary,
    // validated against what the release declares (see Default Roles). The
    // collection also lets a load skip and report a stored grant naming a
    // permission, resource or field this release does not have, instead of
    // carrying it. An application with no role file passes
    // access.WithPermissionCollection(router.Collection()) for that check.
    access.WithDefaultRoles(router.Collection(), roles.File),
    // Recommended: propagate changes between instances in near-realtime over
    // the application's signal channel (see Change signal).
    access.WithChangeSignal(policySignal),
    // Optional: tune the heartbeat backstop (default 1m).
    access.WithHeartbeatInterval(30*time.Second),
    // Optional: replace the hook that receives background reload/signal
    // failures and the findings a load reports. The default writes each one
    // to the standard log; while reloads fail, checks keep serving the last
    // good snapshot.
    access.WithReloadErrorHandler(func(err error) { alert(err) }),
)

// Readiness: block until the first policy snapshot has loaded.
if err := client.WaitReady(ctx); err != nil { ... }

// Shutdown: stop background reloading (checks keep serving the last snapshot).
defer client.Close()

A grant the running release cannot use — a condition that does not parse, a row-referencing condition on a scope-wide grant, or, with the collection from WithDefaultRoles or WithPermissionCollection, a permission, resource or field the release does not declare — does not stop the load: it is left out of the snapshot and reported to the reload-error hook as a *access.SkippedGrant. The permission it would grant is denied, the rest of the policy loads, and the instance becomes ready. That is what makes a stored grant safe to outlive the release that wrote it: after a rollback, or after a release removes a field, the grant is denied and reported, and everything else keeps working.

A load reports two more findings the same way. A custom role whose name a default role of the running release has, in the same kind of scope, is a *access.ShadowedRole: the default wins, the custom role's grants are skipped, and its members hold the default role's grants; rename or delete the custom role to clear it. Memberships naming a role that is neither a default role nor a custom role in their scope are an *access.OrphanedMembership: the members hold nothing from it, as happens when a release retires a default role and its memberships remain. Each finding reaches the hook once per compiled snapshot, and CheckPolicy returns the same findings to the deploy (see Default Roles).

A custom role's grant set changes through ChangeRoleGrants, one store write for the removals and the additions together, so a reader never sees a role with neither its old grant nor its new one.

Change signal

The engine announces on the change signal after every successful policy write and watches it for the hints other instances announce. A hint only nudges the background loop to re-read the policy store: the signal carries no policy, so a lost or duplicated hint costs latency and nothing else. Announce failures and watch errors reach the reload-error hook and never fail the write. Close waits for an announcement still in flight, bounded by a few seconds, so a write made right before it (a migrate command's seed) is heard by the other instances before the application closes the channel.

The application supplies the signal as an adapter over its one signal channel, through access.ChangeSignalFunc(announce, watch). announce publishes the policy kind on the channel. watch subscribes to the policy kind, hands every signal to the onChange the engine passes, and blocks until its context ends; that is the Watch contract, and it keeps the subscription open for the life of the client, its stop running when watch returns. Whenever watch returns early (a subscription that ended), the engine re-invokes it after a delay, so a watch that returns on connection loss is enough.

The heartbeat is the backstop. With or without a signal, the engine re-reads the policy store every heartbeat interval (default 1m, WithHeartbeatInterval) and swaps in a new snapshot only when the content changed, so cross-instance staleness is bounded by that interval while the signal is broken or absent. Correctness never depends on the signal.

An application built on the resource package has the channel already: its live.Service (package github.com/impulseframework/impulse/resource/live) carries Signal(ctx, kind) and Subscribe(kind, onSignal) (stop, err) over the signal kinds the resource package declares, and resource.KindPolicy is the policy kind. The adapter over it, where svc is the application's live.Service:

policySignal := access.ChangeSignalFunc(
    func(ctx context.Context) error {
        return svc.Signal(ctx, resource.KindPolicy)
    },
    func(ctx context.Context, onChange func()) error {
        stop, err := svc.Subscribe(resource.KindPolicy, onChange)
        if err != nil {
            return err
        }
        defer stop()
        <-ctx.Done()

        return nil
    },
)

client, err := access.New(store, access.WithChangeSignal(policySignal))

Any channel that publishes a kind to every instance's subscribers adapts the same way.

API Usage

Permission Checking

The base name / Resources suffix pairing is the API's naming standard: the base method checks a permission held scope-wide (attached to no resource); the Resources variant checks specific resources.

The checks — for users and for roles alike — are the request-path seams and are ABAC-ready: they take the per-request decision context (accesstypes.Environment, immediately after ctx) and answer with Decisions (Denied / Granted / Conditional). CheckUserResources returns one Decision per resource, all from a single policy snapshot; Decisions.DeniedResources() lists what was denied — empty means everything passed. One permission per call; batch as many resources as you like. CheckUser returns the Decision for a permission held scope-wide. A grant may carry a condition — opaque expression text on its store row (Condition, empty = unconditional, and part of the row's identity) — and a resource covered only by conditional grants answers Conditional; any unconditional cover answers Granted outright. A role may hold several grants on one resource for one permission, each under its own condition, stored as one row per condition, so the engine sees them exactly as it would from separate roles. Grouping is the engine's job: within one CheckUserResources call, a Conditional decision's ConditionGroup.Resources lists every checked resource sharing that covering-grant set, the same group appearing in each member's Decision — deduplicate by sorted-Resources equality. Conditions never attach to scope-wide grants (there is no row for them to see — rejected at snapshot load; interim — this narrows to row-referencing conditions once the condition package classifies row-free, with environment/subject-only conditions folding at check time), so CheckUser never answers Conditional. Nothing authors conditions yet (the expression language is undesigned), so in practice every Decision is Granted or Denied and an empty Environment is the normal argument.

The role checks are the same seams evaluated against a role's effective grants — its own and, transitively, every role it inherits — with no member involved: CheckRole and CheckRoleResources answer exactly what CheckUser and CheckUserResources answer a user holding only that role. They serve sessions that operate as a role (an administrator working a partner portal under a role chosen for the session — the session library's impersonated sessions) as well as policy introspection. A role has no identity of its own: a subject term in a row condition is bound by the resource layer to the session's effective identity at render time, and a scope-wide condition that needs a subject is a check error, as it is for a user. RoleHasGrants and RolePermissionDigest are the role twins of the user foothold and digest questions.

env := accesstypes.NewEnvironment()

decisions, err := client.CheckUserResources(ctx, env, user, scope, "Read", "documents", "documents.title", "images")
decision, err := client.CheckUser(ctx, env, user, scope, "ExportReports") // scope-wide

decisions, err = client.CheckRoleResources(ctx, env, role, scope, "Update", "documents")
decision, err = client.CheckRole(ctx, env, role, scope, "ExportReports")

A request binds its principal once: client.ForUser(user) returns a *UserChecker and client.ForRole(role) a *RoleChecker, each carrying Check, PermissionDigest and HasGrants over the bound subject — the canonical implementations of the resource package's UserPermissions and RolePermissions seams. Only the UserChecker has User(): a role is not anyone, and the session's effective identity is the resource layer's to supply.

UserHasGrants, and HasGrants on a UserChecker, answer the foothold question: whether a user holds at least one grant in a scope. An application that hides which tenants exist answers a caller with no foothold in a domain exactly as if the domain did not exist. A tenant picker filters the application's own tenant list by it; access holds no tenant list, so it never enumerates domains. A membership that resolves to no grants is not a foothold, and a membership held in every domain is a foothold in each tenant.

checker := client.ForUser(user)

var visible []accesstypes.Domain
for _, tenant := range tenants { // the application's own tenant list
    ok, err := checker.HasGrants(ctx, accesstypes.DomainScope(tenant))
    if err != nil {
        return err
    }
    if ok {
        visible = append(visible, tenant)
    }
}

There is no tenant validation on the check path: an unknown tenant scope holds no grants, so everything comes back denied (fail closed). If your API wants to answer 400 for an invalid tenant rather than 403, validate the tenant in your own guard — your application owns the tenant table.

User Management
mgr := client.UserManager()

// Where policy is held: one tenant domain, every tenant domain, or the
// global partition (accesstypes.GlobalPolicyScope()).
tenant1 := accesstypes.DomainPolicyScope("tenant1")
tenant2 := accesstypes.DomainPolicyScope("tenant2")
everyDomain := accesstypes.EveryDomainPolicyScope()

mgr.AddUserRoles(ctx, tenant1, "john.doe", "Administrator", "Editor")
mgr.DeleteUserRoles(ctx, tenant1, "john.doe", "Editor")

// Held in every domain: john.doe is a Viewer in every tenant, including one
// created after this call.
mgr.AddUserRoles(ctx, everyDomain, "john.doe", "Viewer")

// Memberships as stored, keyed by where each is held: with no scopes, every
// membership the user holds; with scopes, the memberships held in each.
roles, err := mgr.UserRoles(ctx, "john.doe")
roles, err = mgr.UserRoles(ctx, "john.doe", tenant1, tenant2)

// Effective permissions are answered where a request is, from the snapshot.
// Access holds no tenant list of its own, so at least one scope is required.
permissions, err := mgr.UserPermissions(ctx, "john.doe", accesstypes.DomainScope("tenant1"))

UserRoles reports what the user holds where each role is held, so a membership held in every domain is one entry under EveryDomainPolicyScope(), never one per tenant. It is the user's own memberships and the roles of every group the user is in (see Groups), each role once in each place: it is what a sign-in decides a person by, so a person who holds a role through a group alone is somebody. UserPermissions reports what the user holds in each scope from the roles held there and in every domain, default and custom roles alike.

Groups

A group of people holds roles the way a person does, and a person in a group holds the group's roles wherever the group holds them, until they leave the group or the group loses the role.

mgr := client.UserManager()

// A group is kept for the whole application or in one tenant domain. The id
// is generated; the name is one group's where the group is kept.
watch, err := mgr.AddGroup(ctx, accesstypes.DomainPolicyScope("tenant1"), "Night watch", "The people on the night shift.")
auditors, err := mgr.AddGroup(ctx, accesstypes.GlobalPolicyScope(), "Auditors", "Reads every tenant's books.")

mgr.AddGroupRoles(ctx, watch, accesstypes.DomainPolicyScope("tenant1"), "Editor")
mgr.AddGroupRoles(ctx, auditors, accesstypes.EveryDomainPolicyScope(), "Viewer")
mgr.AddGroupUsers(ctx, watch, "john.doe", "jane.roe")

// Emptied, a group is deleted.
mgr.DeleteGroupUsers(ctx, watch, "john.doe", "jane.roe")
mgr.DeleteGroupRoles(ctx, watch, accesstypes.DomainPolicyScope("tenant1"), "Editor")
mgr.DeleteGroup(ctx, watch)
  • A check costs what it did: the snapshot folds each group's roles into its members when it compiles, so a person in a group is checked exactly as a person who holds the role themselves. A role held both ways is held once, and losing one way leaves the other
  • A group kept in one tenant domain is managed there and holds roles in that domain alone: AddGroupRoles and GroupRole refuse a role anywhere else. A group kept for the whole application holds roles in the global partition, in one domain or in every domain
  • No group holds the Super Administrator role, so a group is no way around the rule that only a super administrator makes another: the writes refuse it
  • DeleteGroup refuses a group that still has a member or holds a role. Nobody loses a role because a group was deleted: each person is removed and each role taken by an act of its own
  • DeleteRole refuses a custom role a group holds, as it refuses one a person holds: a role deleted from under a group would leave the group's row behind, and a role of the name made again would at once be held by everyone in the group. Take the role away from the group first
  • RoleUsers lists who holds a role in a scope: the people who hold it by a membership of their own and the people who hold it through a group, each once. RoleHolders says how each holds it, their own membership, the groups, or both. Removing a person's own membership (DeleteUserRoles, DeleteRoleUsers) leaves what they hold through a group: that goes when they leave the group or the group loses the role
  • A row the rules refuse (written past this package) gives nobody a role: the snapshot leaves it out and CheckPolicy reports it (SkippedGroupRole)
  • Groups, UserGroups, GroupUsers and GroupRoles read what the store holds; GroupRole, with NewGroupRoleKey and GroupMemberKey, is for a caller that writes the rows in a transaction of its own and then calls Controller.PolicyChanged, as Membership is for a person's own role
Periods

A role assignment may carry a period, a start and an end, and counts only inside it: a role taken for a task goes away by itself, and nobody has to remember to remove it.

mgr := client.UserManager()
tenant1 := accesstypes.DomainPolicyScope("tenant1")

// Until Friday noon, from now: no start is from the moment the role is given.
friday := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
period, err := accesstypes.NewPeriod(nil, &friday)
mgr.AssignUserRole(ctx, tenant1, "john.doe", "Editor", period)

// Assigning again replaces the period; with none, the role stands until it is removed.
mgr.AddUserRoles(ctx, tenant1, "john.doe", "Editor")

// A person's place in a group and a group's role take a period the same way.
mgr.AssignGroupUser(ctx, watch, "jane.roe", period)
mgr.AssignGroupRole(ctx, watch, tenant1, "Editor", period)
  • Each end of a period is optional: no start is from the moment the assignment is given, and no end is until it is removed. The start is the first instant the assignment counts and the end the first it does not. A period that ends at or before its start is refused
  • It holds at the moment, and nothing is written when a period begins or ends. A check reads the assignments that count at its instant, the Environment's now, which is the one a grant's condition folds with, and the engine's own clock where the Environment carries none. UserRoles, which a sign-in decides a person by, RoleUsers, GroupUsers, GroupRoles and UserGroups leave out an assignment outside its period while its row still stands, read at the database's present
  • A check still costs what it did. The snapshot holds the assignments that count in a window of time, from the latest start or end before its instant until the earliest after it, and the first check past the window compiles the next one from the records it already holds, with no store read. A store whose assignments carry no period compiles one snapshot for all time
  • A person holds a group's role while their place in the group and the group's role both count
  • Changing a period is assigning again: AssignUserRole, AssignGroupUser and AssignGroupRole give the period handed, and the Add methods give none. Ending an assignment now is removing it
  • The Super Administrator role takes no end, and no start either (ValidatePeriod): there is always a super administrator, and a period could leave none
  • An assignment that has ended stands in nobody's way: DeleteRole and DeleteGroup take the ended ones with what they delete, and refuse one whose period has not begun as they refuse one that counts
  • Nothing here removes an ended row on a schedule. The identity library removes a person's ended assignments at their next sign-in; until then the row counts for nothing
  • A caller that writes an assignment's row in a transaction of its own asks ValidatePeriod before it writes, as it asks Membership or GroupRole for the key
Role Management
// A custom role's name follows the grammar every role name does (letters and
// digits starting with a capital letter), and it is created with a
// description: one or two plain sentences saying what it is for. A name
// outside the grammar, or a role without a description, is refused.
mgr.AddRole(ctx, tenant1, "Moderator", "Reviews and removes the tenant's posts.")
deleted, err := mgr.DeleteRole(ctx, tenant1, "Moderator") // scoped to tenant1

roles, err := mgr.Roles(ctx, tenant1) // []access.RoleInfo: each role's name and description
role, exists, err := mgr.ResolveRole(ctx, tenant1, "administrator") // "Administrator": the spelling the store holds, matched without regard to case

users, err := mgr.RoleUsers(ctx, tenant1, "Administrator")     // who holds it, themselves or through a group
holders, err := mgr.RoleHolders(ctx, tenant1, "Administrator") // []access.RoleHolder: each with how they hold it
mgr.AddRoleUsers(ctx, tenant1, "Administrator", "user1", "user2")
mgr.DeleteRoleUsers(ctx, tenant1, "Administrator", "user1")

// A custom role held in every domain exists in each tenant.
mgr.AddRole(ctx, everyDomain, "Auditor", "Reads every tenant's records without changing them.")
users, err = mgr.RoleUsers(ctx, everyDomain, "Auditor")

// Global-scope roles live in their own partition.
mgr.AddRole(ctx, accesstypes.GlobalPolicyScope(), "SystemAdmin", "Administers the application itself.")

Roles lists the roles that exist in a scope, each as its name and description (RoleInfo): the release's default roles of the scope's kind, described by the role file, and the custom roles held there, and, for one domain, the custom roles held in every domain too, described as AddRole was told. A name is listed once however many places hold it. ResolveRole finds the role a scope holds under a name, matched without regard to case, and returns it in the spelling the store holds: in one domain a domain default role, a custom role held in that domain, or a custom role held in every domain. The exact spelling wins when it exists; otherwise the one role that matches case-insensitively, and two such roles with no exact match is an error. It is how a name from outside the application, a directory's group (a Google group is an email address, so its name is lowercase), finds the role the role file spelled. A custom role held in one domain alone cannot be assigned in every domain.

No two roles in a scope differ only in case: the role file is refused at New when it declares such a pair, and AddRole refuses a custom role whose name matches an existing role of the scope without regard to case, so a resolution is never ambiguous. AddRole also holds a custom role's name to the one grammar every role name follows — letters and digits starting with a capital letter, such as Administrator or TenantAdministrator (see Default Roles) — and refuses a name outside it with the same words the role file is refused with.

A default role's name is taken: AddRole refuses it, and DeleteRole refuses to delete a default role. DeleteRole also refuses while users hold the role in that scope. A custom role held in every domain is changed where it is held, through EveryDomainPolicyScope(), not through one domain.

Permission Management
// Resource- and field-specific permissions
mgr.AddRolePermissionResources(ctx, tenant1, "Editor", "Read", "documents", "documents.*")
mgr.DeleteRolePermissionResources(ctx, tenant1, "Editor", "Read", "documents.*")

// A scope-wide permission (not tied to any resource) is granted through the
// base-name method — there is no resource value that means it.
mgr.AddRolePermission(ctx, tenant1, "Administrator", "CreateUsers")
mgr.DeleteRolePermission(ctx, tenant1, "Administrator", "CreateUsers")

// What the role holds where a request is, from the snapshot, inheritance
// folded: the file's grants for a default role, the store's for a custom one.
permissions, err := mgr.RolePermissions(ctx, accesstypes.DomainScope("tenant1"), "Administrator")

// The role's resource grants as held, with the conditions each is granted under.
grants, err := mgr.RoleGrants(ctx, tenant1, "Administrator")

Grant writes enforce the resource shape fail-closed: at most one dot, both segments non-empty (a.b.c, .name, and employees. are rejected at declaration time). The grant methods change custom roles only: a default role's grants are the release's, so a call naming one is refused; copy its grants into a custom role under another name to change them.

HTTP Handlers

logHandler := func(handler func(w http.ResponseWriter, r *http.Request) error) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        if err := handler(w, r); err != nil {
            // Handle error
        }
    }
}

handlers := client.Handlers(logHandler)

r := chi.NewRouter()
r.Get("/domains/{domain}/roles", handlers.Roles())
r.Post("/domains/{domain}/roles", handlers.AddRole())
r.Delete("/domains/{domain}/roles/{role}", handlers.DeleteRole())
r.Get("/domains/{domain}/roles/{role}/permissions", handlers.RolePermissions())
r.Get("/domains/{domain}/roles/{role}/users", handlers.RoleUsers())
r.Post("/domains/{domain}/roles/{role}/users", handlers.AddRoleUsers())
r.Delete("/domains/{domain}/roles/{role}/users", handlers.DeleteRoleUsers())

// Memberships held in every tenant domain have no domain to name.
r.Get("/every-domain/roles/{role}/users", handlers.RoleUsersEveryDomain())
r.Post("/every-domain/roles/{role}/users", handlers.AddRoleUsersEveryDomain())
r.Delete("/every-domain/roles/{role}/users", handlers.DeleteRoleUsersEveryDomain())

The handlers read the {domain} and {role} path parameters from a chi router; the paths are the application's choice. The {domain} forms address roles and memberships held in one tenant domain. AddRoleUsersEveryDomain, DeleteRoleUsersEveryDomain and RoleUsersEveryDomain address memberships held in every tenant domain. No handler addresses the global partition. Roles lists the domain's default roles and the custom roles held there or in every domain, each as {"name": ..., "description": ...}; AddRole takes roleName and description in its body and refuses a role without a description; and RolePermissions answers what a role holds in the domain, read as the scope of a request, for default and custom roles alike.

Default Roles

Default roles are policy that travels with the release. They are authored as a role file, JSON in the RoleConfig shape (see JSON Configuration), embedded in the application binary and handed to New through WithDefaultRoles. New parses the file and validates it against the collection the release declares: a file that does not parse, names a role outside the grammar, leaves a role without a description, declares a role twice or at both scopes, grants what the collection does not declare, or carries a condition the vocabulary refuses fails New, so a release whose default roles are wrong does not start.

Every role name follows one grammar, a default role's in the file and a custom role's given to AddRole alike: letters and digits starting with a capital letter, such as Administrator or TenantAdministrator — no underscore, hyphen, space or dot. The scope is never part of the name: a role is declared under its scope key, so Administrator_Global is refused where Administrator under global is meant. Every role carries a description, one or two plain sentences saying what the role is for, the way a cloud provider describes its roles; Roles returns it beside the name.

The store holds no row for a default role. A global default role is held in the global partition and a domain default role in every tenant domain. A membership names a default role by name alone, the snapshot compiles its grants from the file, and the user manager, with the HTTP handlers over it, lists it beside the custom roles, refuses to create, change or delete it, and answers its grants from the file. Nothing copies the file into the store, so a deploy has no step to run per tenant and a rollback has no step of its own: the running binary's file is the default policy.

Usage

Embed the role file in a package of the application:

// Package roles holds the release's default roles.
package roles

import (
    _ "embed"

    "github.com/impulseframework/impulse/access"
)

// File is the release's role file.
//
//go:embed roles.json
var File access.RoleFile

Hand it to New with the collection it validates against:

client, err := access.New(store,
    access.WithDefaultRoles(router.Collection(), roles.File),
    access.WithChangeSignal(policySignal), // see Change signal
)
if err != nil {
    return err // includes a role file that does not parse or does not validate
}

WithDefaultRoles also gives the client the collection WithPermissionCollection would, so an application with a role file passes only WithDefaultRoles.

The deploy's migrate step calls CheckPolicy. It reads the store once and returns the role file's warnings (see Warnings) beside what the store holds that this release cannot use as written: a grant the load would skip (*access.SkippedGrant), a custom role a default of the same name shadows (*access.ShadowedRole), and memberships naming a role nothing defines (*access.OrphanedMembership). It writes nothing; a store that cannot be read is the error.

func checkPolicy(ctx context.Context, client *access.Client) error {
    warnings, err := client.CheckPolicy(ctx)
    if err != nil {
        return err
    }
    for _, w := range warnings {
        fmt.Printf("Warning: %s\n", w)
    }

    return nil
}

Every warning prints as one line. A consumer that wants the fields switches on the kind: access.GrantWarning, access.RequiredFieldWarning and access.ConcealingKeyWarning come from the role file, and *access.SkippedGrant, *access.ShadowedRole and *access.OrphanedMembership from the store.

Behavior
  • A global default role is held in the global partition; a domain default role is held in every tenant domain, including a tenant created after the release started, with nothing written for it
  • A membership names a default role by name alone: a global default is assigned in the global partition, a domain default in one domain or in every domain
  • Roles and ResolveRole include the default roles of the scope's kind, Roles with the file's description, and RolePermissions and RoleGrants answer a default role's grants from the file
  • AddRole refuses a default role's name, DeleteRole refuses a default role, and the grant methods refuse to change one; copy its grants into a custom role under another name to change them
  • A role whose file entry has no grants exists and holds nothing until a grant is authored
  • Validates resources, permissions, and conditions against the collection before the client starts, and refuses a grant on a resource whose scope is not its role's
  • Prevents update permissions on immutable resources
  • Warns, without rejecting, when a role holds a conditional Delete, Update, or targeted Execute on a row it can neither Read nor List, a Create on a resource without a field every create must be given, or a conditional List on a concealing field the resource sorts or filters by (see Warnings)
  • A release that introduces a default role under a custom role's name shadows the custom role, and a release that retires a default role leaves its memberships holding nothing; both are reported, and the store is left as it is
The Super Administrator Role

Beside the role file's roles, every client defines one role of the framework's own: SuperAdministrator (accesstypes.SuperAdministrator), the way back in when everything else is broken. It is in no role file and needs none; a client built without a role file defines it too.

  • The name is reserved in any case: a role file that defines a role of that name, global or domain, does not validate (RoleFile.Parse, ValidateRoles and New refuse it, so impulse check and the release's start do), and AddRole refuses it as a custom role anywhere
  • It is held in the global partition alone: AddUserRoles, AddRoleUsers and Membership refuse a membership of it in one tenant or in every tenant
  • Roles lists it among the global roles with the framework's description, and it holds nothing of its own unless the client is built with access.WithSuperAdministratorMethods(methods...): the methods that give and take the auth's roles, which the auth's generated management names (<auth>identity.SuperAdministratorMethods()). The role then holds Execute on each, under no condition, whatever the role file grants anybody, so a super administrator gives and takes any role of the auth for any person. With a collection, New refuses a method the release does not declare at the global scope with Execute. Client.SuperAdministratorMethods answers what the client was built with, and the identity library refuses an engine built without the methods its auth names
  • Client.UserIsSuperAdministrator and UserChecker.SuperAdministrator answer whether a person holds it, from the snapshot, by the one test of who is a super administrator (accesstypes.RoleCollection.HoldsSuperAdministrator): the question a session's reach into a tenant asks of its actor, and the sign-in policy's first rule asks of the person signing in. A super administrator's session enters every tenant whatever the tenant's sign-in settings say. The one other person a tenant's sign-in settings do not keep out is that tenant's own administrator, in that tenant alone (see A Tenant's Administrators)
  • Who may hold it is the identity library's rule, not this one's, where the application gives the roles: only a holder makes or removes another, a holder's account disabled or enabled included, or changes how another signs in, and the last holder who can sign in keeps the role and the account. Giving the role ends nothing the person holds: their sessions, tokens and remembered browsers stand
  • In an auth whose roles come from its directory, the directory decides who is a super administrator: the session library's role synchronization gives the role to a person the directory names for it and takes it from one it no longer names, the last holder's included, as it does every role. UserManager.ResolveRole finds the role in the global partition alone, so the synchronization writes it nowhere the store would refuse it, and nobody is seeded as one
  • No group holds it (see Groups): it is given to one person at a time, so the rule on who makes another super administrator has no way around it
  • It takes no end and no start (see Periods): AssignUserRole and ValidatePeriod refuse any period on it, since there is always a super administrator and a period could leave none
A Tenant's Administrators

An application names the roles whose holders administer a tenant with access.WithTenantAdministratorRoles(roles...), and the engine answers who administers which tenant. It is the question a tenant's sign-in settings ask before they keep a person out: a tenant that admits its people through its directory only still admits its own administrators with a password and a second factor, so a tenant whose directory has a problem can be mended by the people who run it (the session library's signin.TenantDeclaration.AdmitsAdministrator is the decision, and its README says what the person signs in with).

  • A person administers a tenant when they hold one of the named roles in the tenant itself, inside its period (see Periods): by a membership of their own in the tenant's domain, or through a group kept in that tenant, which is written in the tenant, its people and its roles alike
  • A role held in every tenant does not count, and neither does one a group kept for the whole application holds in the tenant: both are how the application's own people are seated everywhere, and a tenant's sign-in settings shut those people out with everyone else
  • Client.UserAdministersTenant and UserChecker.AdministersTenant answer for one person and one tenant from the snapshot, on every request, so the answer follows a role taken away or a period that ended at the next request. UserManager.TenantsAdministered answers every tenant a person administers from the store, which is what the sign-in decision reads. Both come to one statement of where a role must be held to count
  • Client.TenantAdministratorRoles answers what the client was built with. A client built without the option answers that nobody administers any tenant, and a generated auth package passes the role file's tenant administrator roles (AdministratorRoles())

Note: CheckPolicy writes nothing, so it is safe to run on every deploy and from any tool. A rollback's binary carries its own role file, and what the store holds that the older release cannot use is reported the same way.

Warnings

A Delete, an Update, and an Execute on a method with a @target row locate the row first and answer NotFound when it is absent, then evaluate the grant's condition and answer Forbidden when it fails. A read hides a row its condition does not select behind the same NotFound. So a role holding a conditional write on a row it can neither Read nor List learns, from the response code alone, that a row exists in its tenant, without changing it. The role file may carry such a grant, and the release enforces it as written; CheckPolicy returns one warning for it, which the migrate step prints as one line:

Warning: role Paymaster: Delete on Missions is granted under "state = 'open'" without Read or List on Missions: a Forbidden answer tells the caller a Missions row exists where a read would answer NotFound. Grant Read or List on Missions in this role or in a role assigned with it, or accept the disclosure; a Read whose condition is narrower than this one leaks the same way.

The check is per role. A reader role meant to be assigned alongside the writer role does not silence it, because the role file holds no assignments; the line tells the role's author which role to change. Unconditional writes are not flagged: they reveal existence only by succeeding, which is what the grant permits. The check is a heuristic. Holding Read does not close the channel when the Read condition is narrower than the write's.

The second warning is about a create that can never be completed. A create writes the fields the caller's Create grants name and no others, and the commit refuses a row whose NOT NULL column nothing filled. The generated collection names, for each resource, the fields a create must be given by the client: the column takes no NULL, no column default and no default_create_fn fills it, it is no key and no field the server owns, and a grant names it for Create. A role that holds Create on a resource, and none of whose Create grants there covers one of those fields, creates no row by itself: the page draws the create form from the grant, the person fills in everything they may, and the commit answers 409 with nothing they can act on.

Warning: role FlightLead: Create on Sorties is granted without launchedAt, which every create of Sorties must be given (the column takes no NULL and nothing fills it for the client): a create under this role alone is refused at commit, whatever the person submits. Grant Create on the field, give the column a default, or accept this warning where the same people hold another role that grants it.

The check reads every Create grant the role holds on the resource, whatever condition each is under, so it says that no create can succeed, never that some cannot. It is per role, like the first: two roles the same person holds can cover the field between them, which a role file cannot say, so the line is a warning and the release starts.

The third warning is about cost, not disclosure. A sort or filter on a conditionally visible field runs over the visible projection, CASE WHEN <condition> THEN column END, so a masked cell is NULL wherever the query looks at it and nothing about a hidden value leaks through order or match. No index serves that expression: every such page sorts the tenant's whole partition. The query drops the CASE when the row filter has already proven the field's condition on every surviving row, which is the case when every field the role lists on the resource is granted under a condition that implies the field's own; it keeps the CASE when the role lists another field unconditionally, or under a condition the field's condition does not cover. The warning is raised exactly there, for a field the resource orders by (@order, so every page pays) or admits as a sort or filter key (an indexed or allow_filter field, so a page sorted or filtered by it pays), and only where the field's masked cells conceal. The resource package's masking:"positional" struct tag declares the other behavior: the cell stays hidden but the query runs on the real column, the index serves the page, and where the hidden values fall is disclosed; the generated collection leaves such a field out of the check.

Warning: role Archivist: List on Missions.fee is granted under "state = 'completed'", and fee is a sort or filter key of Missions whose masked cells conceal; this role also lists Missions fields under "state IN ('completed', 'failed', 'stood_down')", which the field's condition does not cover, so the row filter does not prove the field's condition and a page this role sorts or filters by fee orders on CASE WHEN <condition> THEN column END, which no index serves: it sorts the tenant's whole partition. Grant fee unconditionally in this role, tag the field masking:"positional" and disclose where its hidden values fall, or accept the cost for a table that never pages at volume.

The covering test admits implication on one attribute under a closed rule set: a condition covers another that spells it the same way, an equality or IN list whose values all sit inside its own IN list, a != or NOT IN whose values include all of its own, and a conjunction any one of whose terms it covers; every other shape (another attribute, a range, a subject set, 1 against 1.0) must be spelled the same. So the archivist's row fields, granted on the closed states, are silent, because her completed grant implies them (state = 'completed' is one of state IN ('completed', 'failed', 'stood_down')); her fee, granted on completed alone, is the one warning above, because the closed-states grant admits rows the fee's condition does not select.

Both warnings are about the role file's roles. A custom role's grants are written at run time through the user manager, and these two checks do not run on them.

ValidateRoles runs the validation New runs on the role file and returns its warnings as []access.Warning, with no store and no client involved, so a project test or a tool gets the answer the release's start would:

config, err := roles.File.Parse()
if err != nil {
    return err
}
warnings, err := access.ValidateRoles(router.Collection(), config)
if err != nil {
    return err // the refusals that would fail New
}
for _, w := range warnings {
    fmt.Println(w)
}
Several Sites, One Policy Store

A deployment whose sites each generate their own collection over one schema shares one policy store: a login is one identity and a role is one set of powers across the application. UnionCollection presents the sites' collections as one registry for WithDefaultRoles: the registries merge, the subject namespace is the union of the sites' declarations, and every other question about a resource is answered by the first collection registering it. A resource several sites serve must be declared identically in each; UnionCollection refuses collections that disagree on a shared resource's permissions (fields included), scope, immutability, computed marking, or method target.

collection, err := access.UnionCollection(consolerouter.Collection(), portalrouter.Collection())
if err != nil {
    return err
}

client, err := access.New(store, access.WithDefaultRoles(collection, roles.File))
JSON Configuration
{
  "roles": {
    "global": [],
    "domain": [
      {
        "name": "Editor",
        "description": "Writes and edits the documents of the tenant.",
        "permissions": {
          "List":   [{"resource": "Documents", "fields": ["title", "author"]}],
          "Read":   [{"resource": "Documents", "fields": ["title", "author", "body"]}],
          "Create": [{"resource": "Documents", "fields": ["title", "body"]}],
          "Update": [{"resource": "Documents", "fields": ["title", "body"], "condition": "author = subject"}]
        }
      },
      {
        "name": "Viewer",
        "description": "Reads the documents of the tenant.",
        "permissions": {
          "List": [{"resource": "Documents", "fields": ["title", "author"]}],
          "Read": [{"resource": "Documents", "fields": ["title", "author", "body"]}]
        }
      }
    ]
  }
}

Each role is declared under exactly one scope key, with a name in the grammar (letters and digits starting with a capital letter; the scope is never part of the name) and a description saying what it is for. A global role carries grants on global-scoped resources and is held in the global partition; a domain role carries grants on domain-scoped resources and is held in every tenant domain. A job function that needs both kinds of powers is two roles assigned to one user. Each grant names a base resource, the fields it covers as their wire tags, and an optional condition; a role may carry several grants on one resource for one permission, each under its own condition.

The file is decoded strictly: a key the shape does not declare is an error, since a misspelled key would otherwise silently drop the roles under it. RoleFile.Parse decodes it and checks its shape the way New does — the name grammar, the descriptions, each grant's grammar and condition syntax — with no permission collection, for a test or a tool that wants the RoleConfig or the refusals a release's start would give before it looks at the collection. ValidateRoles then checks what the file grants against the collection.

License

See LICENSE file.


Created and maintained by the CCC team.

Documentation

Overview

Package access implements tools to manage access to resources.

Package access is a generated GoMock package.

Index

Constants

View Source
const DefaultTablePrefix = "Access"

DefaultTablePrefix leads a policy store's table names when no prefix is given, which keeps every access table contiguous in a sorted listing.

Variables

This section is empty.

Functions

func AdministersTenant added in v0.5.0

func AdministersTenant(administrators []accesstypes.Role, scope accesstypes.PolicyScope, role accesstypes.Role, kept *accesstypes.PolicyScope) (accesstypes.Domain, bool)

AdministersTenant reports the tenant a role makes its holder an administrator of, held where scope says: by a membership of the person's own (kept is nil) or by a group of people kept where kept says. A role counts when it is one of administrators and is held in the tenant itself:

  • a membership of the person's own in the tenant's domain;
  • a role a group kept in that tenant holds there. A tenant's own group is written in the tenant, its people and its roles alike, so it gives nobody what a membership in the tenant would not, and a tenant that keeps its administrators in a group has administrators.

A role held in every tenant does not count, and neither does one a group kept for the whole application holds in the tenant: both are how the application's own people are seated everywhere, and a tenant's sign-in settings shut those people out with everyone else.

It is exported for a caller that judges a change to who holds a role before the engine reads it, the generated user management while a tenant is directory only, so that what it guards and what the engine counts are one statement.

func GroupScope added in v0.5.0

func GroupScope(kind, axis, domain string) (accesstypes.PolicyScope, error)

GroupScope answers where a group is kept from the columns of its row, as a caller that read the row in a transaction of its own holds them. Columns no store writes for a group are refused.

func ValidatePeriod added in v0.5.0

func ValidatePeriod(role accesstypes.Role, period accesstypes.Period) error

ValidatePeriod refuses a period an assignment of role cannot carry: one that ends at or before its start, which would never count, and any period on the Super Administrator role. There is always a super administrator, and an end could leave none; a start could too, since the rule that keeps the last one counts who holds the role, and a holder whose period has not begun is nobody's way back in. It is the one statement of the rule, asked by every write of a person's role here and by a caller that writes the row in a transaction of its own (UserManager.Membership).

Types

type ChangeSignal

type ChangeSignal interface {
	// Announce broadcasts that policy may have changed. The Client calls it
	// after successful policy writes; failures are reported through the
	// reload error handler and never fail the write.
	Announce(ctx context.Context) error

	// Watch delivers received hints by invoking onChange, blocking until ctx
	// ends or the subscription fails. If Watch returns early the Client
	// re-invokes it after a delay, so implementations may either reconnect
	// internally or simply return on connection loss.
	Watch(ctx context.Context, onChange func()) error
}

ChangeSignal is the engine's seam for propagating policy-change hints between instances. The Client announces after every successful policy write and watches for the hints other instances announce; a hint only nudges the background loop to re-read the policy store. Correctness never depends on it: the heartbeat re-reads the policy store on a fixed interval regardless, so a broken signal only costs propagation latency, never accuracy.

The application supplies the implementation as an adapter over its one signal channel, through ChangeSignalFunc.

func ChangeSignalFunc

func ChangeSignalFunc(announce func(ctx context.Context) error, watch func(ctx context.Context, onChange func()) error) ChangeSignal

ChangeSignalFunc builds a ChangeSignal from the two functions an application writes over its signal channel, so wiring the engine to the channel is one line instead of a type. announce publishes the policy kind on the channel. watch subscribes to the policy kind, hands every signal to onChange, and blocks until ctx ends, which is what the Watch contract asks: the engine re-invokes watch after a delay whenever it returns, and the subscription's stop runs when watch returns.

Over the resource package's live service, where svc is the application's live.Service and resource.KindPolicy is the policy kind:

policySignal := access.ChangeSignalFunc(
	func(ctx context.Context) error {
		return svc.Signal(ctx, resource.KindPolicy)
	},
	func(ctx context.Context, onChange func()) error {
		stop, err := svc.Subscribe(resource.KindPolicy, onChange)
		if err != nil {
			return err
		}
		defer stop()
		<-ctx.Done()

		return nil
	},
)
client, err := access.New(store, access.WithChangeSignal(policySignal))

Both functions must be set; a nil one panics here, at construction, rather than at the first policy write or the first watch.

type Client

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

Client is the main access control client for permission checking and user management.

func New

func New(store Store, opts ...Option) (*Client, error)

New creates a new Client over a policy store built by one of the store subpackages (spannerstore, postgresstore).

Permission checks are answered by the snapshot engine, compiled in-memory from the release's default roles (WithDefaultRoles) and the policy store, and kept fresh by a background heartbeat plus an optional push hint (see WithChangeSignal). All policy writes (user management) go through the same store and refresh the snapshot immediately on this instance.

The store's values — domains, users, resources — are opaque labels to access: referential validity belongs to the callers that write them, and checks fail closed on anything unknown. Where a request is — a tenant domain or the global partition — is an accesstypes.Scope; where policy is held — the global partition, one domain or every domain — is an accesstypes.PolicyScope; neither is ever a distinguished value.

New fails when the role file does not parse or does not validate against the collection: a release whose default roles are wrong does not start.

func (*Client) CheckPolicy

func (c *Client) CheckPolicy(ctx context.Context) ([]Warning, error)

CheckPolicy reads the policy store once and reports everything a deploy should hear about before the release takes traffic: the shapes the role file carries that are legal and probably not what the author wanted (GrantWarning, ConcealingKeyWarning), and what the store holds that this release cannot use as written — a grant it would skip (*SkippedGrant), a custom role a default of the same name shadows (*ShadowedRole), memberships naming a role nothing defines (*OrphanedMembership). It writes nothing: the default roles are the release's and the store holds no row for them, so there is nothing to reconcile. A migrate step calls it and prints each warning on its own line; a store that cannot be read is the error.

func (*Client) CheckRole

CheckRole returns the Decision for whether role holds perm scope-wide — attached to no resource — within scope: what CheckUser answers a member holding only that role, minus the membership lookup. It is the scope-wide check for a session operating as a role principal, and an introspection tool for policy tooling.

The Environment and scope semantics are CheckUser's. A role has no identity of its own, so the folding facts carry the request's instant and nothing else; a scope-wide condition that needs a subject is a check error here exactly as it is for a user.

func (*Client) CheckRoleResources

func (c *Client) CheckRoleResources(
	ctx context.Context, env accesstypes.Environment, role accesstypes.Role, scope accesstypes.Scope, perm accesstypes.Permission, resources ...accesstypes.Resource,
) (accesstypes.Decisions, error)

CheckRoleResources returns the Decision for each resource for whether role holds perm on it within scope — the role twin of CheckUserResources, with the same single-snapshot, Decision, grouping, Environment, and scope semantics. A Conditional decision's payload is what the database must still evaluate; a subject term in it is bound at render time to the session's effective identity by the resource layer, never here — a role has no identity of its own.

func (*Client) CheckUser

CheckUser returns the Decision for whether user holds perm scope-wide — attached to no resource — within scope.

The Environment is the per-request decision context (sampled once per request). The engine folds condition facts against it at check time; a condition referencing an attribute the Environment does not carry is a check error, never a silent allow or deny. The answer here is always Granted or Denied: a scope-wide grant carries only row-free conditions (row-referencing ones are rejected at snapshot load — no row exists for them to see), and row-free conditions fold to a definite answer. A condition folding leaves unsettled — a subject-attribute reference, which is data only the database can compare — is a check error too: there is no place to evaluate it on this path.

There is no scope validation: an unknown tenant simply holds no grants, so the check fails closed. Callers wanting to distinguish "invalid tenant" from "no permission" validate the tenant in their own guard, against the source that owns tenants.

func (*Client) CheckUserResources

func (c *Client) CheckUserResources(
	ctx context.Context, env accesstypes.Environment, user accesstypes.User, scope accesstypes.Scope, perm accesstypes.Permission, resources ...accesstypes.Resource,
) (accesstypes.Decisions, error)

CheckUserResources returns the Decision for each resource for whether user holds perm on it within scope — all answered from a single policy snapshot, so a revocation can never land between two answers of the same call. A resource is either a parent name ("employees") or a single field on a parent ("employees.name"). Per resource: Denied when no grant covers it, Granted when at least one unconditional grant covers it (conditions on other grants are moot), Conditional when only conditional grants cover it.

Condition facts fold before the Decisions build: each covering set's any-of combination is evaluated against the environment's instant and the user's identity, so a set folding TRUE answers Granted, one folding FALSE answers Denied, and a Conditional decision carries only what the database must still evaluate — the engine folds facts, and never renders SQL. A condition referencing an attribute the Environment does not carry is a check error, never a silent allow or deny.

Grouping is the engine's job — only the engine owns grant-set identity: a Conditional decision carries one ConditionGroup whose Resources lists every resource checked in this call sharing that covering-grant set, and the same group value appears in each member's Decision, so callers deduplicate by sorted-Resources equality. The distinct groups are exactly a write check's boolean list — OR across a group's grants inside its Condition, AND across groups computed by the caller — and a denial names the failing group's Resources. See CheckUser for the Environment and scope semantics.

func (*Client) Close

func (c *Client) Close() error

Close stops the Client's background policy reloading and change-signal watch, and waits for a change announcement still in flight (bounded by a few seconds), so a policy write made right before Close reaches the other instances before the application closes the channel the signal rides on. Permission checks keep answering from the last loaded snapshot.

func (*Client) ForRole

func (c *Client) ForRole(role accesstypes.Role) *RoleChecker

ForRole returns the request-bound permission checker for role — the canonical implementation of the resource package's RolePermissions seam, for sessions operating as a role principal. See RoleChecker.

func (*Client) ForUser

func (c *Client) ForUser(user accesstypes.User) *UserChecker

ForUser returns the request-bound permission checker for user — the canonical implementation of the resource package's UserPermissions seam. See UserChecker.

func (*Client) Handlers

func (c *Client) Handlers(logHandler LogHandler) Handlers

Handlers returns the Handlers for enforcing access control

func (*Client) PolicyChanged added in v0.3.0

func (c *Client) PolicyChanged()

PolicyChanged tells the engine that policy rows were committed outside its own write path: an application wrote a membership inside a transaction of its own and committed it. The next check on this instance reloads the policy before it answers, as after the manager's own writes, the background loop is nudged, and the other instances are hinted through the change signal. Called when nothing changed, it costs one read of the policy store.

func (*Client) RoleHasGrants

func (c *Client) RoleHasGrants(ctx context.Context, role accesstypes.Role, scope accesstypes.Scope) (bool, error)

RoleHasGrants reports whether role holds at least one grant in scope, own or inherited, answered from the in-memory policy snapshot — the foothold question UserHasGrants answers for a user, asked for a session operating as the role: concealed tenancy answers a role with no grants in a domain exactly as if the domain did not exist. A role that exists but resolves to no grants has no foothold; a domain default role has one in every domain.

func (*Client) RolePermissionDigest

func (c *Client) RolePermissionDigest(ctx context.Context, role accesstypes.Role, scope accesstypes.Scope) (accesstypes.PermissionDigest, error)

RolePermissionDigest returns role's structural grant enumeration within scope — the frontend digest payload for a session operating as the role, with UserPermissionDigest's semantics: granted or conditional per resource and permission, denied targets absent, nothing folded, scope-wide grants not enumerated.

func (*Client) SuperAdministratorMethods added in v0.5.0

func (c *Client) SuperAdministratorMethods() []accesstypes.Resource

SuperAdministratorMethods returns the methods the client lets a super administrator execute whatever the role file grants anybody: the ones it was built with (WithSuperAdministratorMethods), none without the option. The identity library holds the engine it is handed to the methods its auth's generated management names (identity.New), so an application that built the engine without them does not start.

func (*Client) TenantAdministratorRoles added in v0.5.0

func (c *Client) TenantAdministratorRoles() []accesstypes.Role

TenantAdministratorRoles returns the roles the client was told administer a tenant (WithTenantAdministratorRoles), none without the option. An auth's generated identity client reads them here and hands them to the tenant's list of its people, so the sign-in, the session's reach and the list are answered over one set of names.

func (*Client) UserAdministersTenant added in v0.5.0

func (c *Client) UserAdministersTenant(ctx context.Context, user accesstypes.User, domain accesstypes.Domain) (bool, error)

UserAdministersTenant reports whether user administers the tenant: they hold one of the roles the application names as a tenant's administrator's (WithTenantAdministratorRoles) in the tenant itself, inside its period, by a membership of their own in the tenant's domain or through a group kept in that tenant. A role held in every tenant, or through a group kept for the whole application, administers no tenant in this sense. It is answered from the in-memory policy snapshot like the checks (safe inside transactions; no store read), and is the question a session's reach into a tenant asks of the session's actor where the tenant admits its people through its directory only: the tenant's own administrators keep a way in. A Client built without the option answers false for everyone.

func (*Client) UserHasGrants

func (c *Client) UserHasGrants(ctx context.Context, user accesstypes.User, scope accesstypes.Scope) (bool, error)

UserHasGrants reports whether user holds at least one grant in scope, answered from the in-memory policy snapshot (safe inside transactions; no store read). It is the visibility question concealed tenancy asks: an application hiding tenant existence answers a caller with no grants in a domain exactly as if the domain did not exist, while a caller with any foothold proceeds to ordinary permission checks. It is also the predicate a tenant picker filters the application's own tenant list by — access holds no tenant list, so it never enumerates domains. Role membership that resolves to no grants is not a foothold; a membership held in every domain is a foothold in each.

func (*Client) UserIsSuperAdministrator added in v0.5.0

func (c *Client) UserIsSuperAdministrator(ctx context.Context, user accesstypes.User) (bool, error)

UserIsSuperAdministrator reports whether user holds the Super Administrator role (accesstypes.SuperAdministrator), answered from the in-memory policy snapshot like the checks (safe inside transactions; no store read). It is the question a session's reach into a tenant asks of the session's actor: a super administrator enters every tenant, whatever the tenant's sign-in settings say. The one other person a tenant's sign-in settings do not keep out is that tenant's own administrator (UserAdministersTenant), in that tenant alone.

func (*Client) UserManager

func (c *Client) UserManager() UserManager

UserManager returns the UserManager for managing users, roles, and permissions.

func (*Client) UserPermissionDigest

func (c *Client) UserPermissionDigest(ctx context.Context, user accesstypes.User, scope accesstypes.Scope) (accesstypes.PermissionDigest, error)

UserPermissionDigest returns user's structural grant enumeration within scope: every resource and field the user's grants reach, each mapping permission → granted (an unconditional cover exists) or conditional (only conditional grants cover it), with denied targets absent — fail-closed by construction. It is the payload of the frontend's per-scope permission digest and is advisory only; enforcement stays with the Check seams.

Unlike the Check seams the digest never folds: it reports grant structure with no environment instant and no row data, so a payload is stable for the life of a policy snapshot and caches cleanly per scope. Scope-wide grants attach to no resource and are not enumerated. See CheckUser for the scope semantics — an unknown tenant simply holds no grants, so its digest is empty.

func (*Client) WaitReady

func (c *Client) WaitReady(ctx context.Context) error

WaitReady blocks until the first policy snapshot has loaded (or ctx expires). Wire it into readiness probes so instances receive traffic only once permission checks can be answered.

type ConcealingKeyWarning

type ConcealingKeyWarning struct {
	// Role holds the grant; Scope is the scope the role is declared at.
	Role  accesstypes.Role
	Scope accesstypes.PermissionScope

	// Resource is the listed resource and Field the concealing key on it, as
	// its wire tag.
	Resource accesstypes.Resource
	Field    accesstypes.Tag

	// Conditions are the conditions the role's List grants cover the field
	// under, sorted; the field's visible projection is their OR.
	Conditions []string

	// DefaultOrder marks a field of the resource's declared order: every page
	// this role lists pays, not only a page a request sorts or filters by the
	// field.
	DefaultOrder bool

	// Why the CASE stands. Unconditional: the role lists other fields of the
	// resource with no condition, so the row filter proves nothing. Uncovered:
	// the conditions, one disjunct each in canonical text, the role lists other
	// fields under and the field's own conditions do not imply
	// (condition.Implies), so the row filter admits rows the field's condition
	// does not select.
	Unconditional bool
	Uncovered     []string
}

ConcealingKeyWarning is one conditional List grant the role file carries as written but flags: it covers a field the resource orders by or admits as a sort or filter key, the field's masked cells conceal, and the role's other List grants on the resource leave the field's condition standing in the query, so a page this role orders or filters by the field sorts the tenant's whole partition.

func (ConcealingKeyWarning) String

func (w ConcealingKeyWarning) String() string

String renders the warning as one line: the grant, why its condition stays in the query, what that costs, and the three ways out.

type Controller

type Controller interface {
	// CheckUser returns the Decision for whether user holds perm scope-wide
	// (attached to no resource) within scope. env is the request's decision
	// context; the check folds environment-referencing conditions against it
	// and fails loudly when a referenced attribute is absent.
	CheckUser(
		ctx context.Context, env accesstypes.Environment, user accesstypes.User, scope accesstypes.Scope, perm accesstypes.Permission,
	) (accesstypes.Decision, error)

	// CheckUserResources returns the Decision for each resource for whether
	// user holds perm on it within scope, all answered from one policy
	// snapshot. env is the request's decision context; the check folds
	// environment-referencing conditions against it and fails loudly when a
	// referenced attribute is absent.
	CheckUserResources(
		ctx context.Context, env accesstypes.Environment, user accesstypes.User, scope accesstypes.Scope, perm accesstypes.Permission, resources ...accesstypes.Resource,
	) (accesstypes.Decisions, error)

	// CheckRole returns the Decision for whether role holds perm scope-wide
	// within scope: what CheckUser answers a member holding only that role,
	// minus the membership lookup. env is the request's decision context;
	// the check folds environment-referencing conditions against it and
	// fails loudly when a referenced attribute is absent.
	CheckRole(
		ctx context.Context, env accesstypes.Environment, role accesstypes.Role, scope accesstypes.Scope, perm accesstypes.Permission,
	) (accesstypes.Decision, error)

	// CheckRoleResources returns the Decision for each resource for whether
	// role holds perm on it within scope, all answered from one policy
	// snapshot — the role twin of CheckUserResources, with the same
	// Environment, grouping, and fail-closed semantics.
	CheckRoleResources(
		ctx context.Context, env accesstypes.Environment, role accesstypes.Role, scope accesstypes.Scope, perm accesstypes.Permission, resources ...accesstypes.Resource,
	) (accesstypes.Decisions, error)

	// UserHasGrants reports whether user holds at least one grant in scope,
	// answered from the in-memory policy snapshot — the visibility question
	// concealed tenancy asks and the predicate a tenant picker filters the
	// application's tenant list by (see Client.UserHasGrants).
	UserHasGrants(ctx context.Context, user accesstypes.User, scope accesstypes.Scope) (bool, error)

	// UserIsSuperAdministrator reports whether user holds the Super
	// Administrator role, answered from the in-memory policy snapshot: the
	// question a session's reach into a tenant asks of the session's actor
	// (see Client.UserIsSuperAdministrator).
	UserIsSuperAdministrator(ctx context.Context, user accesstypes.User) (bool, error)

	// UserAdministersTenant reports whether user administers the tenant: they
	// hold one of the application's tenant administrator roles in the tenant
	// itself, inside its period, answered from the in-memory policy snapshot:
	// the question a session's reach into a directory-only tenant asks of
	// the session's actor (see Client.UserAdministersTenant).
	UserAdministersTenant(ctx context.Context, user accesstypes.User, domain accesstypes.Domain) (bool, error)

	// TenantAdministratorRoles returns the roles whose holders administer a
	// tenant, as the engine was told them (WithTenantAdministratorRoles), none
	// where it was told none: the names UserAdministersTenant and
	// UserManager.TenantsAdministered answer by, for whatever else must agree
	// with them, such as a tenant's list of its people.
	TenantAdministratorRoles() []accesstypes.Role

	// UserPermissionDigest returns user's structural grant enumeration within
	// scope — the frontend digest payload: resource → permission → granted or
	// conditional, denied targets absent, nothing folded (see
	// Client.UserPermissionDigest).
	UserPermissionDigest(ctx context.Context, user accesstypes.User, scope accesstypes.Scope) (accesstypes.PermissionDigest, error)

	// ForUser returns the request-bound permission checker for user, whose
	// method set structurally satisfies the resource package's UserPermissions
	// seam. Test doubles implement it in one line over NewUserChecker.
	ForUser(user accesstypes.User) *UserChecker

	// RoleHasGrants reports whether role holds at least one grant in scope —
	// the foothold a session operating as the role has there (see
	// Client.RoleHasGrants).
	RoleHasGrants(ctx context.Context, role accesstypes.Role, scope accesstypes.Scope) (bool, error)

	// RolePermissionDigest returns role's structural grant enumeration within
	// scope — the frontend digest payload for a session operating as the role
	// (see Client.RolePermissionDigest).
	RolePermissionDigest(ctx context.Context, role accesstypes.Role, scope accesstypes.Scope) (accesstypes.PermissionDigest, error)

	// ForRole returns the request-bound permission checker for role, whose
	// method set structurally satisfies the resource package's
	// RolePermissions seam. Test doubles implement it in one line over
	// NewRoleChecker.
	ForRole(role accesstypes.Role) *RoleChecker

	// UserManager returns the UserManager for managing users, roles, and permissions.
	UserManager() UserManager

	// PolicyChanged tells the engine that policy rows were committed outside
	// its own write path: an application wrote a membership inside a
	// transaction of its own (see UserManager.Membership) and committed it.
	// The next check reloads the policy before it answers (see
	// Client.PolicyChanged).
	PolicyChanged()

	// Handlers returns HTTP handlers for access management with validation and logging.
	Handlers(handler LogHandler) Handlers
}

Controller is the main interface for access control operations.

type Grant

type Grant struct {
	// Resource is the base resource name. A dotted field resource is legal
	// only as a bare mechanical grant (no Fields, no Condition) — fields
	// belong in Fields, and conditions are authored per grant, never per
	// field (the pairing invariant).
	Resource accesstypes.Resource `json:"resource"`

	// Fields is the field set the grant covers, spelled as the fields' wire
	// tags; each expands to a Resource.field grant row.
	Fields []accesstypes.Tag `json:"fields,omitempty"`

	// Condition is the grant's limiting condition in the condition expression
	// language; empty is unconditional. One condition scopes exactly this
	// grant's field set.
	Condition string `json:"condition,omitempty"`
}

Grant is one authored unit of a role's configuration: a permission (the map key above) on one resource, covering a field set, optionally limited by one condition. It expands into the base and field grant rows, all carrying the same condition — the construction invariant the check seams and the read gate lean on: a conditional base decision's payload is always exactly the union its field decisions deliver.

A role may carry several grants on one resource for one permission, each with a different condition: the condition is part of a grant's identity, so each grant's rows stand beside the others' and the engine sees them exactly as it would had they arrived through separate roles (any unconditional cover settles a decision as Granted). Two grants with the same condition are one grant written twice and are rejected.

type GrantRow

type GrantRow struct {
	Permission accesstypes.Permission
	Resource   accesstypes.Resource
	Condition  string
}

GrantRow is one grant as the store holds it: Permission on Resource — a bare resource name, or Resource.field for one field — limited by Condition, "" being unconditional. AddRoleGrants takes rows; the role file's authored Grants expand into the same shape.

type GrantWarning

type GrantWarning struct {
	// Role holds the grant; Scope is the scope the role is declared at.
	Role  accesstypes.Role
	Scope accesstypes.PermissionScope

	// Permission and Resource name the grant: the row resource for Delete and
	// Update, the method for Execute.
	Permission accesstypes.Permission
	Resource   accesstypes.Resource

	// Row is the row resource whose existence the response code reveals: the
	// grant's own resource, or the method's @target.
	Row accesstypes.Resource

	// Condition is the grant's condition text.
	Condition string
}

GrantWarning is one grant the role file carries as written but flags: a conditional Delete, Update, or targeted Execute in a role that holds neither Read nor List on the row resource the grant checks.

func (GrantWarning) String

func (w GrantWarning) String() string

String renders the warning as one line: what is granted, what the answer reveals, and what closes it.

type GroupInfo added in v0.5.0

type GroupInfo struct {
	ID          accesstypes.Group
	Scope       accesstypes.PolicyScope
	Name        string
	Description string
}

GroupInfo is one group of people as UserManager lists it: the id the store names it by, where it is kept (the global partition or one tenant domain), and the name and the description people read it by.

type GroupMemberKey added in v0.5.0

type GroupMemberKey struct {
	Group accesstypes.Group
	User  accesstypes.User
}

GroupMemberKey is the key of one row of the group members table (<Prefix><Store>GroupMembers): the group, by its id, and the person as the engine names them.

type GroupRoleKey added in v0.5.0

type GroupRoleKey struct {
	Group  accesstypes.Group
	Kind   string
	Axis   string
	Domain string
	Role   accesstypes.Role
}

GroupRoleKey is the key of one row of the group roles table (<Prefix><Store>GroupRoles), its columns in key order: the group, by its id, where the role is held, in the stores' encoding of the scope, and the role in the spelling the store holds it.

func NewGroupRoleKey added in v0.5.0

func NewGroupRoleKey(group accesstypes.Group, scope accesstypes.PolicyScope, role accesstypes.Role) GroupRoleKey

NewGroupRoleKey spells the role a group holds in scope as the store's row key. It checks nothing: it is the form for reading a row or deleting one. A row to be written comes from UserManager.GroupRole, which holds it to the rule first.

func (*GroupRoleKey) Scope added in v0.5.0

func (k *GroupRoleKey) Scope() (accesstypes.PolicyScope, error)

Scope answers where the key's role is held.

type GroupRow added in v0.5.0

type GroupRow struct {
	Kind        string
	Axis        string
	Domain      string
	Name        string
	Description string
}

GroupRow is the row of a group to be created (<Prefix><Store>Groups) less its id, which whoever writes the row generates: where the group is kept, in the stores' encoding of a scope, and its name and description as the rules leave them.

func NewGroup added in v0.5.0

func NewGroup(scope accesstypes.PolicyScope, name, description string) (GroupRow, error)

NewGroup holds a group to be created to its rules and answers its row, for a caller that writes it inside a transaction of its own instead of through UserManager.AddGroup. A group is kept for the whole application or in one tenant, never in every tenant; its name is one to 128 characters with no control character, kept as given less the space around it; and it carries a description, one or two plain sentences saying who is in it. That the name is free where the group is kept is the store's to hold: the table's unique index refuses a second group of the name there.

type HandlerClient

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

HandlerClient implements Handlers for access management.

func (*HandlerClient) AddRole

func (a *HandlerClient) AddRole() http.HandlerFunc

AddRole is the handler to add a custom role held in the domain. The request carries the role's name and its description, one or two plain sentences saying what the role is for; the manager refuses a role without one.

Permissions Required: AddRole

func (*HandlerClient) AddRoleUsers

func (a *HandlerClient) AddRoleUsers() http.HandlerFunc

AddRoleUsers is the handler to assign a role to a list of users, the memberships held in the domain

Permissions Required: AddRoleUsers

func (*HandlerClient) AddRoleUsersEveryDomain

func (a *HandlerClient) AddRoleUsersEveryDomain() http.HandlerFunc

AddRoleUsersEveryDomain is the handler to assign a role to a list of users, the memberships held in every tenant domain

Permissions Required: AddRoleUsers

func (*HandlerClient) DeleteRole

func (a *HandlerClient) DeleteRole() http.HandlerFunc

DeleteRole is the handler to delete a custom role held in the domain

Permissions Required: DeleteRole

func (*HandlerClient) DeleteRoleUsers

func (a *HandlerClient) DeleteRoleUsers() http.HandlerFunc

DeleteRoleUsers is the handler to delete a list of users from a given role, the memberships held in the domain

Permissions Required: DeleteRoleUsers

func (*HandlerClient) DeleteRoleUsersEveryDomain

func (a *HandlerClient) DeleteRoleUsersEveryDomain() http.HandlerFunc

DeleteRoleUsersEveryDomain is the handler to delete a list of users from a given role, the memberships held in every tenant domain

Permissions Required: DeleteRoleUsers

func (*HandlerClient) RolePermissions

func (a *HandlerClient) RolePermissions() http.HandlerFunc

RolePermissions is the handler to the list of permissions a given role holds in the domain, default and custom roles alike

Permissions Required: ListRolePermissions

func (*HandlerClient) RoleUsers

func (a *HandlerClient) RoleUsers() http.HandlerFunc

RoleUsers is the handler to the list of users for a given role, the memberships held in the domain

Permissions Required: ListRoleUsers

func (*HandlerClient) RoleUsersEveryDomain

func (a *HandlerClient) RoleUsersEveryDomain() http.HandlerFunc

RoleUsersEveryDomain is the handler to the list of users for a given role, the memberships held in every tenant domain

Permissions Required: ListRoleUsers

func (*HandlerClient) Roles

func (a *HandlerClient) Roles() http.HandlerFunc

Roles is the handler to get the list of roles that exist in a given domain, each with its name and description: the release's domain default roles and the custom roles held there or in every domain

Permissions Required: ListRoles

type Handlers

type Handlers interface {
	AddRole() http.HandlerFunc
	AddRoleUsers() http.HandlerFunc
	AddRoleUsersEveryDomain() http.HandlerFunc
	DeleteRole() http.HandlerFunc
	DeleteRoleUsers() http.HandlerFunc
	DeleteRoleUsersEveryDomain() http.HandlerFunc
	RolePermissions() http.HandlerFunc
	Roles() http.HandlerFunc
	RoleUsers() http.HandlerFunc
	RoleUsersEveryDomain() http.HandlerFunc
}

Handlers provides HTTP handlers for managing roles and their members. The {domain} forms address memberships and roles held in one tenant domain; the EveryDomain forms address memberships held in every tenant domain, which have no domain to name.

type LogHandler

type LogHandler func(handler func(w http.ResponseWriter, r *http.Request) error) http.HandlerFunc

LogHandler wraps handlers with logging. Converts error-returning handler to http.HandlerFunc.

type MembershipKey added in v0.3.0

type MembershipKey struct {
	Kind   string
	Axis   string
	Domain string
	Role   accesstypes.Role
	User   accesstypes.User
}

MembershipKey is the key of one row of the memberships table (<Prefix><Store>UserRoles), its columns in key order. Kind, Axis and Domain spell the scope the membership is held in (the stores' encoding, which the table's CHECK constraint holds the kind to), Role is the role in the spelling the store holds it, and User is the person as the engine names them.

func NewMembershipKey added in v0.3.0

func NewMembershipKey(scope accesstypes.PolicyScope, user accesstypes.User, role accesstypes.Role) MembershipKey

NewMembershipKey spells the membership of user in role, held in scope, as the store's row key. It checks nothing: it is the form for reading a row or deleting one, which the manager's DeleteUserRoles does whether or not the role still exists. A row to be written comes from UserManager.Membership, which holds it to the rule first.

type MockController

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

MockController is a mock of Controller interface.

func NewMockController

func NewMockController(ctrl *gomock.Controller) *MockController

NewMockController creates a new mock instance.

func (*MockController) CheckRole

CheckRole mocks base method.

func (*MockController) CheckRoleResources

CheckRoleResources mocks base method.

func (*MockController) CheckUser

CheckUser mocks base method.

func (*MockController) CheckUserResources

CheckUserResources mocks base method.

func (*MockController) EXPECT

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockController) ForRole

func (m *MockController) ForRole(role accesstypes.Role) *RoleChecker

ForRole mocks base method.

func (*MockController) ForUser

func (m *MockController) ForUser(user accesstypes.User) *UserChecker

ForUser mocks base method.

func (*MockController) Handlers

func (m *MockController) Handlers(handler LogHandler) Handlers

Handlers mocks base method.

func (*MockController) PolicyChanged added in v0.3.0

func (m *MockController) PolicyChanged()

PolicyChanged mocks base method.

func (*MockController) RoleHasGrants

func (m *MockController) RoleHasGrants(ctx context.Context, role accesstypes.Role, scope accesstypes.Scope) (bool, error)

RoleHasGrants mocks base method.

func (*MockController) RolePermissionDigest

func (m *MockController) RolePermissionDigest(ctx context.Context, role accesstypes.Role, scope accesstypes.Scope) (accesstypes.PermissionDigest, error)

RolePermissionDigest mocks base method.

func (*MockController) TenantAdministratorRoles added in v0.5.0

func (m *MockController) TenantAdministratorRoles() []accesstypes.Role

TenantAdministratorRoles mocks base method.

func (*MockController) UserAdministersTenant added in v0.5.0

func (m *MockController) UserAdministersTenant(ctx context.Context, user accesstypes.User, domain accesstypes.Domain) (bool, error)

UserAdministersTenant mocks base method.

func (*MockController) UserHasGrants

func (m *MockController) UserHasGrants(ctx context.Context, user accesstypes.User, scope accesstypes.Scope) (bool, error)

UserHasGrants mocks base method.

func (*MockController) UserIsSuperAdministrator added in v0.5.0

func (m *MockController) UserIsSuperAdministrator(ctx context.Context, user accesstypes.User) (bool, error)

UserIsSuperAdministrator mocks base method.

func (*MockController) UserManager

func (m *MockController) UserManager() UserManager

UserManager mocks base method.

func (*MockController) UserPermissionDigest

func (m *MockController) UserPermissionDigest(ctx context.Context, user accesstypes.User, scope accesstypes.Scope) (accesstypes.PermissionDigest, error)

UserPermissionDigest mocks base method.

type MockControllerMockRecorder

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

MockControllerMockRecorder is the mock recorder for MockController.

func (*MockControllerMockRecorder) CheckRole

func (mr *MockControllerMockRecorder) CheckRole(ctx, env, role, scope, perm any) *gomock.Call

CheckRole indicates an expected call of CheckRole.

func (*MockControllerMockRecorder) CheckRoleResources

func (mr *MockControllerMockRecorder) CheckRoleResources(ctx, env, role, scope, perm any, resources ...any) *gomock.Call

CheckRoleResources indicates an expected call of CheckRoleResources.

func (*MockControllerMockRecorder) CheckUser

func (mr *MockControllerMockRecorder) CheckUser(ctx, env, user, scope, perm any) *gomock.Call

CheckUser indicates an expected call of CheckUser.

func (*MockControllerMockRecorder) CheckUserResources

func (mr *MockControllerMockRecorder) CheckUserResources(ctx, env, user, scope, perm any, resources ...any) *gomock.Call

CheckUserResources indicates an expected call of CheckUserResources.

func (*MockControllerMockRecorder) ForRole

func (mr *MockControllerMockRecorder) ForRole(role any) *gomock.Call

ForRole indicates an expected call of ForRole.

func (*MockControllerMockRecorder) ForUser

func (mr *MockControllerMockRecorder) ForUser(user any) *gomock.Call

ForUser indicates an expected call of ForUser.

func (*MockControllerMockRecorder) Handlers

func (mr *MockControllerMockRecorder) Handlers(handler any) *gomock.Call

Handlers indicates an expected call of Handlers.

func (*MockControllerMockRecorder) PolicyChanged added in v0.3.0

func (mr *MockControllerMockRecorder) PolicyChanged() *gomock.Call

PolicyChanged indicates an expected call of PolicyChanged.

func (*MockControllerMockRecorder) RoleHasGrants

func (mr *MockControllerMockRecorder) RoleHasGrants(ctx, role, scope any) *gomock.Call

RoleHasGrants indicates an expected call of RoleHasGrants.

func (*MockControllerMockRecorder) RolePermissionDigest

func (mr *MockControllerMockRecorder) RolePermissionDigest(ctx, role, scope any) *gomock.Call

RolePermissionDigest indicates an expected call of RolePermissionDigest.

func (*MockControllerMockRecorder) TenantAdministratorRoles added in v0.5.0

func (mr *MockControllerMockRecorder) TenantAdministratorRoles() *gomock.Call

TenantAdministratorRoles indicates an expected call of TenantAdministratorRoles.

func (*MockControllerMockRecorder) UserAdministersTenant added in v0.5.0

func (mr *MockControllerMockRecorder) UserAdministersTenant(ctx, user, domain any) *gomock.Call

UserAdministersTenant indicates an expected call of UserAdministersTenant.

func (*MockControllerMockRecorder) UserHasGrants

func (mr *MockControllerMockRecorder) UserHasGrants(ctx, user, scope any) *gomock.Call

UserHasGrants indicates an expected call of UserHasGrants.

func (*MockControllerMockRecorder) UserIsSuperAdministrator added in v0.5.0

func (mr *MockControllerMockRecorder) UserIsSuperAdministrator(ctx, user any) *gomock.Call

UserIsSuperAdministrator indicates an expected call of UserIsSuperAdministrator.

func (*MockControllerMockRecorder) UserManager

func (mr *MockControllerMockRecorder) UserManager() *gomock.Call

UserManager indicates an expected call of UserManager.

func (*MockControllerMockRecorder) UserPermissionDigest

func (mr *MockControllerMockRecorder) UserPermissionDigest(ctx, user, scope any) *gomock.Call

UserPermissionDigest indicates an expected call of UserPermissionDigest.

type MockUserManager

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

MockUserManager is a mock of UserManager interface.

func NewMockUserManager

func NewMockUserManager(ctrl *gomock.Controller) *MockUserManager

NewMockUserManager creates a new mock instance.

func (*MockUserManager) AddGroup added in v0.5.0

func (m *MockUserManager) AddGroup(ctx context.Context, scope accesstypes.PolicyScope, name, description string) (accesstypes.Group, error)

AddGroup mocks base method.

func (*MockUserManager) AddGroupRoles added in v0.5.0

func (m *MockUserManager) AddGroupRoles(ctx context.Context, group accesstypes.Group, scope accesstypes.PolicyScope, roles ...accesstypes.Role) error

AddGroupRoles mocks base method.

func (*MockUserManager) AddGroupUsers added in v0.5.0

func (m *MockUserManager) AddGroupUsers(ctx context.Context, group accesstypes.Group, users ...accesstypes.User) error

AddGroupUsers mocks base method.

func (*MockUserManager) AddRole

func (m *MockUserManager) AddRole(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, description string) error

AddRole mocks base method.

func (*MockUserManager) AddRoleGrant

func (m *MockUserManager) AddRoleGrant(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, permission accesstypes.Permission, resource accesstypes.Resource, condition string) error

AddRoleGrant mocks base method.

func (*MockUserManager) AddRoleGrants

func (m *MockUserManager) AddRoleGrants(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, grants ...GrantRow) error

AddRoleGrants mocks base method.

func (*MockUserManager) AddRolePermission

func (m *MockUserManager) AddRolePermission(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, permission accesstypes.Permission) error

AddRolePermission mocks base method.

func (*MockUserManager) AddRolePermissionResources

func (m *MockUserManager) AddRolePermissionResources(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, permission accesstypes.Permission, resources ...accesstypes.Resource) error

AddRolePermissionResources mocks base method.

func (*MockUserManager) AddRoleUsers

func (m *MockUserManager) AddRoleUsers(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, users ...accesstypes.User) error

AddRoleUsers mocks base method.

func (*MockUserManager) AddUserRoles

func (m *MockUserManager) AddUserRoles(ctx context.Context, scope accesstypes.PolicyScope, user accesstypes.User, roles ...accesstypes.Role) error

AddUserRoles mocks base method.

func (*MockUserManager) AssignGroupRole added in v0.5.0

func (m *MockUserManager) AssignGroupRole(ctx context.Context, group accesstypes.Group, scope accesstypes.PolicyScope, role accesstypes.Role, period accesstypes.Period) error

AssignGroupRole mocks base method.

func (*MockUserManager) AssignGroupUser added in v0.5.0

func (m *MockUserManager) AssignGroupUser(ctx context.Context, group accesstypes.Group, user accesstypes.User, period accesstypes.Period) error

AssignGroupUser mocks base method.

func (*MockUserManager) AssignUserRole added in v0.5.0

func (m *MockUserManager) AssignUserRole(ctx context.Context, scope accesstypes.PolicyScope, user accesstypes.User, role accesstypes.Role, period accesstypes.Period) error

AssignUserRole mocks base method.

func (*MockUserManager) ChangeRoleGrants

func (m *MockUserManager) ChangeRoleGrants(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, removals, additions []GrantRow) error

ChangeRoleGrants mocks base method.

func (*MockUserManager) DeleteAllRolePermissions

func (m *MockUserManager) DeleteAllRolePermissions(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role) error

DeleteAllRolePermissions mocks base method.

func (*MockUserManager) DeleteGroup added in v0.5.0

func (m *MockUserManager) DeleteGroup(ctx context.Context, group accesstypes.Group) error

DeleteGroup mocks base method.

func (*MockUserManager) DeleteGroupRoles added in v0.5.0

func (m *MockUserManager) DeleteGroupRoles(ctx context.Context, group accesstypes.Group, scope accesstypes.PolicyScope, roles ...accesstypes.Role) error

DeleteGroupRoles mocks base method.

func (*MockUserManager) DeleteGroupUsers added in v0.5.0

func (m *MockUserManager) DeleteGroupUsers(ctx context.Context, group accesstypes.Group, users ...accesstypes.User) error

DeleteGroupUsers mocks base method.

func (*MockUserManager) DeleteRole

func (m *MockUserManager) DeleteRole(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role) (bool, error)

DeleteRole mocks base method.

func (*MockUserManager) DeleteRoleGrant

func (m *MockUserManager) DeleteRoleGrant(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, permission accesstypes.Permission, resource accesstypes.Resource, condition string) error

DeleteRoleGrant mocks base method.

func (*MockUserManager) DeleteRolePermission

func (m *MockUserManager) DeleteRolePermission(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, permission accesstypes.Permission) error

DeleteRolePermission mocks base method.

func (*MockUserManager) DeleteRolePermissionResources

func (m *MockUserManager) DeleteRolePermissionResources(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, permission accesstypes.Permission, resources ...accesstypes.Resource) error

DeleteRolePermissionResources mocks base method.

func (*MockUserManager) DeleteRoleUsers

func (m *MockUserManager) DeleteRoleUsers(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, users ...accesstypes.User) error

DeleteRoleUsers mocks base method.

func (*MockUserManager) DeleteUserRoles

func (m *MockUserManager) DeleteUserRoles(ctx context.Context, scope accesstypes.PolicyScope, user accesstypes.User, roles ...accesstypes.Role) error

DeleteUserRoles mocks base method.

func (*MockUserManager) DescribeGroup added in v0.5.0

func (m *MockUserManager) DescribeGroup(ctx context.Context, group accesstypes.Group, description string) error

DescribeGroup mocks base method.

func (*MockUserManager) EXPECT

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockUserManager) GroupRole added in v0.5.0

func (m *MockUserManager) GroupRole(ctx context.Context, group accesstypes.Group, kept, scope accesstypes.PolicyScope, role accesstypes.Role, held RoleReader) (GroupRoleKey, error)

GroupRole mocks base method.

func (*MockUserManager) GroupRoles added in v0.5.0

GroupRoles mocks base method.

func (*MockUserManager) GroupUsers added in v0.5.0

func (m *MockUserManager) GroupUsers(ctx context.Context, group accesstypes.Group) ([]accesstypes.User, error)

GroupUsers mocks base method.

func (*MockUserManager) Groups added in v0.5.0

Groups mocks base method.

func (*MockUserManager) Membership added in v0.3.0

Membership mocks base method.

func (*MockUserManager) ResolveRole

func (m *MockUserManager) ResolveRole(ctx context.Context, scope accesstypes.PolicyScope, name string) (accesstypes.Role, bool, error)

ResolveRole mocks base method.

func (*MockUserManager) RoleGrants

RoleGrants mocks base method.

func (*MockUserManager) RoleHolders added in v0.5.0

func (m *MockUserManager) RoleHolders(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role) ([]RoleHolder, error)

RoleHolders mocks base method.

func (*MockUserManager) RolePermissions

RolePermissions mocks base method.

func (*MockUserManager) RoleUsers

RoleUsers mocks base method.

func (*MockUserManager) Roles

Roles mocks base method.

func (*MockUserManager) TenantsAdministered added in v0.5.0

func (m *MockUserManager) TenantsAdministered(ctx context.Context, user accesstypes.User) ([]accesstypes.Domain, error)

TenantsAdministered mocks base method.

func (*MockUserManager) UserGroups added in v0.5.0

func (m *MockUserManager) UserGroups(ctx context.Context, user accesstypes.User) ([]GroupInfo, error)

UserGroups mocks base method.

func (*MockUserManager) UserPermissions

UserPermissions mocks base method.

func (*MockUserManager) UserRoles

UserRoles mocks base method.

type MockUserManagerMockRecorder

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

MockUserManagerMockRecorder is the mock recorder for MockUserManager.

func (*MockUserManagerMockRecorder) AddGroup added in v0.5.0

func (mr *MockUserManagerMockRecorder) AddGroup(ctx, scope, name, description any) *gomock.Call

AddGroup indicates an expected call of AddGroup.

func (*MockUserManagerMockRecorder) AddGroupRoles added in v0.5.0

func (mr *MockUserManagerMockRecorder) AddGroupRoles(ctx, group, scope any, roles ...any) *gomock.Call

AddGroupRoles indicates an expected call of AddGroupRoles.

func (*MockUserManagerMockRecorder) AddGroupUsers added in v0.5.0

func (mr *MockUserManagerMockRecorder) AddGroupUsers(ctx, group any, users ...any) *gomock.Call

AddGroupUsers indicates an expected call of AddGroupUsers.

func (*MockUserManagerMockRecorder) AddRole

func (mr *MockUserManagerMockRecorder) AddRole(ctx, scope, role, description any) *gomock.Call

AddRole indicates an expected call of AddRole.

func (*MockUserManagerMockRecorder) AddRoleGrant

func (mr *MockUserManagerMockRecorder) AddRoleGrant(ctx, scope, role, permission, resource, condition any) *gomock.Call

AddRoleGrant indicates an expected call of AddRoleGrant.

func (*MockUserManagerMockRecorder) AddRoleGrants

func (mr *MockUserManagerMockRecorder) AddRoleGrants(ctx, scope, role any, grants ...any) *gomock.Call

AddRoleGrants indicates an expected call of AddRoleGrants.

func (*MockUserManagerMockRecorder) AddRolePermission

func (mr *MockUserManagerMockRecorder) AddRolePermission(ctx, scope, role, permission any) *gomock.Call

AddRolePermission indicates an expected call of AddRolePermission.

func (*MockUserManagerMockRecorder) AddRolePermissionResources

func (mr *MockUserManagerMockRecorder) AddRolePermissionResources(ctx, scope, role, permission any, resources ...any) *gomock.Call

AddRolePermissionResources indicates an expected call of AddRolePermissionResources.

func (*MockUserManagerMockRecorder) AddRoleUsers

func (mr *MockUserManagerMockRecorder) AddRoleUsers(ctx, scope, role any, users ...any) *gomock.Call

AddRoleUsers indicates an expected call of AddRoleUsers.

func (*MockUserManagerMockRecorder) AddUserRoles

func (mr *MockUserManagerMockRecorder) AddUserRoles(ctx, scope, user any, roles ...any) *gomock.Call

AddUserRoles indicates an expected call of AddUserRoles.

func (*MockUserManagerMockRecorder) AssignGroupRole added in v0.5.0

func (mr *MockUserManagerMockRecorder) AssignGroupRole(ctx, group, scope, role, period any) *gomock.Call

AssignGroupRole indicates an expected call of AssignGroupRole.

func (*MockUserManagerMockRecorder) AssignGroupUser added in v0.5.0

func (mr *MockUserManagerMockRecorder) AssignGroupUser(ctx, group, user, period any) *gomock.Call

AssignGroupUser indicates an expected call of AssignGroupUser.

func (*MockUserManagerMockRecorder) AssignUserRole added in v0.5.0

func (mr *MockUserManagerMockRecorder) AssignUserRole(ctx, scope, user, role, period any) *gomock.Call

AssignUserRole indicates an expected call of AssignUserRole.

func (*MockUserManagerMockRecorder) ChangeRoleGrants

func (mr *MockUserManagerMockRecorder) ChangeRoleGrants(ctx, scope, role, removals, additions any) *gomock.Call

ChangeRoleGrants indicates an expected call of ChangeRoleGrants.

func (*MockUserManagerMockRecorder) DeleteAllRolePermissions

func (mr *MockUserManagerMockRecorder) DeleteAllRolePermissions(ctx, scope, role any) *gomock.Call

DeleteAllRolePermissions indicates an expected call of DeleteAllRolePermissions.

func (*MockUserManagerMockRecorder) DeleteGroup added in v0.5.0

func (mr *MockUserManagerMockRecorder) DeleteGroup(ctx, group any) *gomock.Call

DeleteGroup indicates an expected call of DeleteGroup.

func (*MockUserManagerMockRecorder) DeleteGroupRoles added in v0.5.0

func (mr *MockUserManagerMockRecorder) DeleteGroupRoles(ctx, group, scope any, roles ...any) *gomock.Call

DeleteGroupRoles indicates an expected call of DeleteGroupRoles.

func (*MockUserManagerMockRecorder) DeleteGroupUsers added in v0.5.0

func (mr *MockUserManagerMockRecorder) DeleteGroupUsers(ctx, group any, users ...any) *gomock.Call

DeleteGroupUsers indicates an expected call of DeleteGroupUsers.

func (*MockUserManagerMockRecorder) DeleteRole

func (mr *MockUserManagerMockRecorder) DeleteRole(ctx, scope, role any) *gomock.Call

DeleteRole indicates an expected call of DeleteRole.

func (*MockUserManagerMockRecorder) DeleteRoleGrant

func (mr *MockUserManagerMockRecorder) DeleteRoleGrant(ctx, scope, role, permission, resource, condition any) *gomock.Call

DeleteRoleGrant indicates an expected call of DeleteRoleGrant.

func (*MockUserManagerMockRecorder) DeleteRolePermission

func (mr *MockUserManagerMockRecorder) DeleteRolePermission(ctx, scope, role, permission any) *gomock.Call

DeleteRolePermission indicates an expected call of DeleteRolePermission.

func (*MockUserManagerMockRecorder) DeleteRolePermissionResources

func (mr *MockUserManagerMockRecorder) DeleteRolePermissionResources(ctx, scope, role, permission any, resources ...any) *gomock.Call

DeleteRolePermissionResources indicates an expected call of DeleteRolePermissionResources.

func (*MockUserManagerMockRecorder) DeleteRoleUsers

func (mr *MockUserManagerMockRecorder) DeleteRoleUsers(ctx, scope, role any, users ...any) *gomock.Call

DeleteRoleUsers indicates an expected call of DeleteRoleUsers.

func (*MockUserManagerMockRecorder) DeleteUserRoles

func (mr *MockUserManagerMockRecorder) DeleteUserRoles(ctx, scope, user any, roles ...any) *gomock.Call

DeleteUserRoles indicates an expected call of DeleteUserRoles.

func (*MockUserManagerMockRecorder) DescribeGroup added in v0.5.0

func (mr *MockUserManagerMockRecorder) DescribeGroup(ctx, group, description any) *gomock.Call

DescribeGroup indicates an expected call of DescribeGroup.

func (*MockUserManagerMockRecorder) GroupRole added in v0.5.0

func (mr *MockUserManagerMockRecorder) GroupRole(ctx, group, kept, scope, role, held any) *gomock.Call

GroupRole indicates an expected call of GroupRole.

func (*MockUserManagerMockRecorder) GroupRoles added in v0.5.0

func (mr *MockUserManagerMockRecorder) GroupRoles(ctx, group any) *gomock.Call

GroupRoles indicates an expected call of GroupRoles.

func (*MockUserManagerMockRecorder) GroupUsers added in v0.5.0

func (mr *MockUserManagerMockRecorder) GroupUsers(ctx, group any) *gomock.Call

GroupUsers indicates an expected call of GroupUsers.

func (*MockUserManagerMockRecorder) Groups added in v0.5.0

func (mr *MockUserManagerMockRecorder) Groups(ctx, scope any) *gomock.Call

Groups indicates an expected call of Groups.

func (*MockUserManagerMockRecorder) Membership added in v0.3.0

func (mr *MockUserManagerMockRecorder) Membership(ctx, scope, user, role, held any) *gomock.Call

Membership indicates an expected call of Membership.

func (*MockUserManagerMockRecorder) ResolveRole

func (mr *MockUserManagerMockRecorder) ResolveRole(ctx, scope, name any) *gomock.Call

ResolveRole indicates an expected call of ResolveRole.

func (*MockUserManagerMockRecorder) RoleGrants

func (mr *MockUserManagerMockRecorder) RoleGrants(ctx, scope, role any) *gomock.Call

RoleGrants indicates an expected call of RoleGrants.

func (*MockUserManagerMockRecorder) RoleHolders added in v0.5.0

func (mr *MockUserManagerMockRecorder) RoleHolders(ctx, scope, role any) *gomock.Call

RoleHolders indicates an expected call of RoleHolders.

func (*MockUserManagerMockRecorder) RolePermissions

func (mr *MockUserManagerMockRecorder) RolePermissions(ctx, scope, role any) *gomock.Call

RolePermissions indicates an expected call of RolePermissions.

func (*MockUserManagerMockRecorder) RoleUsers

func (mr *MockUserManagerMockRecorder) RoleUsers(ctx, scope, role any) *gomock.Call

RoleUsers indicates an expected call of RoleUsers.

func (*MockUserManagerMockRecorder) Roles

func (mr *MockUserManagerMockRecorder) Roles(ctx, scope any) *gomock.Call

Roles indicates an expected call of Roles.

func (*MockUserManagerMockRecorder) TenantsAdministered added in v0.5.0

func (mr *MockUserManagerMockRecorder) TenantsAdministered(ctx, user any) *gomock.Call

TenantsAdministered indicates an expected call of TenantsAdministered.

func (*MockUserManagerMockRecorder) UserGroups added in v0.5.0

func (mr *MockUserManagerMockRecorder) UserGroups(ctx, user any) *gomock.Call

UserGroups indicates an expected call of UserGroups.

func (*MockUserManagerMockRecorder) UserPermissions

func (mr *MockUserManagerMockRecorder) UserPermissions(ctx, user any, scopes ...any) *gomock.Call

UserPermissions indicates an expected call of UserPermissions.

func (*MockUserManagerMockRecorder) UserRoles

func (mr *MockUserManagerMockRecorder) UserRoles(ctx, user any, scopes ...any) *gomock.Call

UserRoles indicates an expected call of UserRoles.

type Option

type Option func(*clientOptions)

Option configures optional Client behavior.

func WithChangeSignal

func WithChangeSignal(s ChangeSignal) Option

WithChangeSignal wires a push hint that propagates policy changes between instances in near-realtime. This is the intended configuration: the application adapts its one signal channel through ChangeSignalFunc. Without it, changes propagate within one heartbeat interval.

func WithDefaultRoles

func WithDefaultRoles(collection PermissionCollection, file RoleFile) Option

WithDefaultRoles gives the Client the release's default roles: the role file embedded in the application binary, validated against the collection the release declares. The default roles are policy that travels with the release — the store holds no row for them: the snapshot compiles them from the file, a global role held in the global partition and a domain role held in every tenant domain, a membership names one by name alone, and the management surface lists them beside the store's custom roles, refuses to create, change or delete them, and answers their grants from the file.

New parses and validates the file: a file that does not parse, declares a role twice or at both scopes, grants what the collection does not declare, or carries a condition the vocabulary refuses fails New, so the release does not start. The shapes the file may carry but probably should not (see Warning) do not fail it; Client.CheckPolicy returns them for the deploy's migrate step to print. The collection must not be nil.

func WithHeartbeatInterval

func WithHeartbeatInterval(d time.Duration) Option

WithHeartbeatInterval overrides how often the policy store is re-read for changes (default 1m). It bounds cross-instance staleness when no ChangeSignal is configured, and otherwise backstops a broken signal. Non-positive values keep the default.

func WithPermissionCollection

func WithPermissionCollection(c PermissionCollection) Option

WithPermissionCollection tells the Client what the running release declares: its permissions, resources and fields. A stored grant naming one the release does not declare (after a rollback, or once a release drops a resource) is then left out of the snapshot and reported as a SkippedGrant instead of being carried as a grant nothing can check. Without it, names are not checked; conditions are checked either way. WithDefaultRoles sets the collection too, so an application with a role file does not need this.

func WithReloadErrorHandler

func WithReloadErrorHandler(f func(error)) Option

WithReloadErrorHandler replaces the hook that receives background failures (policy reloads and change-signal announce/watch errors) and what a load found in the store that this release cannot use as written: a grant it skipped (*SkippedGrant), a custom role a default shadows (*ShadowedRole), memberships naming a role nothing defines (*OrphanedMembership). While reloads fail the Client keeps serving the last good policy snapshot, so this hook is where persistent staleness and the findings become visible. The default writes each one to the standard log; wire alerting here when the log is not enough.

func WithSuperAdministratorMethods added in v0.5.0

func WithSuperAdministratorMethods(methods ...accesstypes.Resource) Option

WithSuperAdministratorMethods names the methods that give and take the auth's roles for the whole application: the role methods of the auth's generated management (its identity package's SuperAdministratorMethods). The Super Administrator role, which every Client defines (accesstypes.SuperAdministrator), holds Execute on each of them under no condition, whatever the role file grants anybody: a super administrator gives and takes any role of the auth for any person, in the global partition and in every tenant, so one who can sign in can take the power to fix what is broken. With a collection (WithDefaultRoles, WithPermissionCollection) New refuses a method the release does not declare at the global scope with Execute. Without the option the role is defined and holds nothing of its own.

func WithTenantAdministratorRoles added in v0.5.0

func WithTenantAdministratorRoles(roles ...accesstypes.Role) Option

WithTenantAdministratorRoles names the roles whose holders administer a tenant: the domain roles the auth's package names as an administrator's (the every-tenant list of its AdministratorRoles). A person who holds one of them in a tenant itself, by a membership of their own in the tenant's domain or through a group kept in that tenant, administers the tenant (Client.UserAdministersTenant, UserManager.TenantsAdministered), and a tenant that admits its people through its directory only still admits its own administrators with a password and a second factor: the sign-in rule and the session's reach into the tenant both ask this Client. A role held in every tenant, or through a group kept for the whole application, administers no tenant in this sense, so the application's own people are kept out of a directory-only tenant with everyone else. The names are not checked against the role file: a name no role carries administers nothing. Without the option nobody administers a tenant, and a directory-only tenant admits nobody by a password.

type OrphanedMembership

type OrphanedMembership struct {
	Scope accesstypes.PolicyScope
	Role  accesstypes.Role
	// Users are the members, sorted.
	Users []accesstypes.User
}

OrphanedMembership reports memberships in the policy store naming a role that is neither a default role of the running release nor a custom role in their scope: the members hold nothing from it. A retired default role leaves its memberships behind this way until the directory sync or an administrator removes them. One report per (scope, role) reaches the reload-error hook each time a snapshot compiles, and the deploy check lists it as a Warning.

func (*OrphanedMembership) Error

func (e *OrphanedMembership) Error() string

Error prints the role, where and by how many it is held, and that it grants nothing.

func (*OrphanedMembership) String

func (e *OrphanedMembership) String() string

String renders the finding as the one line the deploy check prints.

type PermissionCollection

type PermissionCollection interface {
	List() map[accesstypes.Permission][]accesstypes.Resource
	Scope(res accesstypes.Resource) accesstypes.PermissionScope
	IsResourceImmutable(scope accesstypes.PermissionScope, res accesstypes.Resource) bool

	// The condition vocabulary: attribute names with their comparison types,
	// and the application-wide subject namespace, each set or value with the
	// comparison type of the column it yields. Grant conditions validate
	// against these at deploy time; ok is false for a name the application
	// does not declare.
	AttributeComparisonType(scope accesstypes.PermissionScope, res accesstypes.Resource, name string) (accesstypes.AttributeType, bool)
	AttributeIsColumn(scope accesstypes.PermissionScope, res accesstypes.Resource, name string) bool
	// AttributeIsList reports whether an attribute reads a list column: a
	// condition that reads one is judged once for each item of the row's
	// list, so it reads one list, as the row holds it.
	AttributeIsList(scope accesstypes.PermissionScope, res accesstypes.Resource, name string) bool
	SubjectSetComparisonType(name string) (accesstypes.AttributeType, bool)
	SubjectValueComparisonType(name string) (accesstypes.AttributeType, bool)

	// IsComputedResource reports whether res is a computed resource: one whose
	// rows come from the application's Go function. The library judges a
	// condition against each row the function yields, in Go, so a grant's
	// condition reads the fields the resource declares (@attribute on the
	// field) and validates against them as a table's does against its
	// columns; the marker lets a refusal name that declaration.
	IsComputedResource(scope accesstypes.PermissionScope, res accesstypes.Resource) bool

	// MethodTarget reports the row resource an RPC method's @target field
	// addresses, and whether the method declares one. A targeted method's
	// generated handler locates that row inside its transaction, so its
	// Execute grants may carry row-referencing conditions — validated here
	// against the target resource's vocabulary; a method without a target
	// keeps the decode-time row-free rule.
	MethodTarget(scope accesstypes.PermissionScope, method accesstypes.Resource) (accesstypes.Resource, bool)

	// ConcealingKeys reports the fields of a listed resource that a list
	// orders or filters on and whose masked cells conceal: order is the
	// resource's declared default order, keys are the fields a request may
	// sort or filter by (indexed and allow_filter fields), each less the
	// fields declared masking:"positional", as wire tags. A conditional
	// grant on one of these puts the condition into the ORDER BY or the
	// WHERE, which no index serves (see ConcealingKeyWarning); the
	// collection decides which fields are positional, so this package never
	// learns the declaration itself. Both are empty for a resource with no
	// list.
	ConcealingKeys(scope accesstypes.PermissionScope, res accesstypes.Resource) (order, keys []accesstypes.Tag)

	// RequiredOnCreate reports the fields a create of a resource must be given
	// by the client, as wire tags, sorted: the column takes no NULL, nothing
	// but the client fills it (no column default, no function of the server's,
	// no key), and a grant names the field for Create. A create that leaves
	// one out is refused at commit, so a role that may create the resource and
	// may set none of its grants' fields for one of them creates no row by
	// itself (see RequiredFieldWarning). Empty for a resource every create of
	// which the server can complete, and for a field resource.
	RequiredOnCreate(scope accesstypes.PermissionScope, res accesstypes.Resource) []accesstypes.Tag
}

PermissionCollection is the set of permission-registry and condition-vocabulary operations the role file validates against. *resource.GeneratedCollection satisfies this interface.

func UnionCollection

func UnionCollection(collections ...PermissionCollection) (PermissionCollection, error)

UnionCollection presents several permission collections as one registry: the application-wide collection of a deployment whose sites each generate their own over one schema and share one policy store, so a role is one set of powers across every site. List merges the registries, the subject namespace is the union of the collections' declarations, and every other question about a resource is answered by the first collection (in argument order) that registers it; a resource no collection registers is answered by the first collection.

The first collection's answer is exact only when every collection registering a resource declares it identically, the shape the resource generator produces when the sites' structs describe one table the same way. UnionCollection refuses collections that disagree on a shared resource in anything it can read through the interface: the permissions registered on it (the field set rides along, since List registers a field resource per field), its scope, its immutability, its computed marking, its method target, its concealing keys, and the fields a create of it must carry. The attribute vocabulary a shared resource declares is not enumerable through the interface, so keeping it identical stays the declaring sites' business.

type PermissionsListFunc

type PermissionsListFunc func() []accesstypes.Permission

PermissionsListFunc returns available permissions.

type RequiredFieldWarning added in v0.4.0

type RequiredFieldWarning struct {
	// Role holds the grant; Scope is the scope the role is declared at.
	Role  accesstypes.Role
	Scope accesstypes.PermissionScope

	// Resource is the resource the role holds Create on.
	Resource accesstypes.Resource

	// Fields are the required fields none of the role's Create grants on the
	// resource covers, as wire tags, sorted.
	Fields []accesstypes.Tag
}

RequiredFieldWarning is one resource a role may create and, by itself, cannot: the role holds Create on the resource, and none of its Create grants there covers a field every create must be given by the client (PermissionCollection.RequiredOnCreate). A create under this role alone leaves the column unset and is refused at commit.

func (RequiredFieldWarning) String added in v0.4.0

func (w RequiredFieldWarning) String() string

String renders the warning as one line: what is granted, what it leaves out, what that does to a create, and the ways out.

type Role

type Role struct {
	// Name is the role's name, in the one grammar every role name follows,
	// custom roles created through AddRole included: letters and digits
	// starting with a capital letter, such as Administrator or
	// TenantAdministrator — no underscore, hyphen, space or dot. The scope is
	// never part of the name: a role is declared under its scope key, and a
	// global and a domain role never share a name.
	Name accesstypes.Role `json:"name"`

	// Description says what the role is for: one or two plain sentences,
	// the way a cloud provider describes its roles ("Reads and edits the
	// documents of the tenant."). Every role carries one; a file whose role
	// has none, or only whitespace, is refused. The listing returns it
	// beside the name, so a person choosing a role reads what it is for.
	Description string `json:"description"`

	Permissions map[accesstypes.Permission][]Grant `json:"permissions"`
}

Role is one default role as the file declares it: its name, what it is for, and the permissions it grants.

type RoleChecker

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

RoleChecker is the request-bound permission checker for one role: what a session operating as a role principal checks against, and the canonical implementation of the resource package's RolePermissions seam. Its method set is UserChecker's without User(): a role has no identity of its own. The session's effective identity — the actor who established it — is the resource layer's to supply where a row condition names the subject, so nothing here can be mistaken for a user.

A RoleChecker binds the role only. Scope and Environment arrive per check from the caller, so one value serves every check in a request.

func NewRoleChecker

func NewRoleChecker(checker RoleResourceChecker, role accesstypes.Role) *RoleChecker

NewRoleChecker returns a RoleChecker for role over checker. Applications use Client.ForRole (or Controller.ForRole); this constructor exists so test doubles implementing RoleResourceChecker can satisfy Controller.ForRole in one line.

func (*RoleChecker) Check

Check returns the Decision for perm on each of resources within scope for the bound role. It is a pure delegate to CheckRoleResources — see there for the Decision, grouping, Environment, and scope semantics.

func (*RoleChecker) HasGrants

func (r *RoleChecker) HasGrants(ctx context.Context, scope accesstypes.Scope) (bool, error)

HasGrants reports whether the bound role holds at least one grant in scope — the foothold a session operating as the role has there. It is a pure delegate to RoleHasGrants; see Client.RoleHasGrants for the foothold semantics.

func (*RoleChecker) PermissionDigest

func (r *RoleChecker) PermissionDigest(ctx context.Context, scope accesstypes.Scope) (accesstypes.PermissionDigest, error)

PermissionDigest returns the bound role's structural grant enumeration within scope — the frontend digest payload. It is a pure delegate to RolePermissionDigest; see Client.RolePermissionDigest for the non-folding semantics.

func (*RoleChecker) Role

func (r *RoleChecker) Role() accesstypes.Role

Role returns the bound role.

type RoleConfig

type RoleConfig struct {
	Roles ScopedRoles `json:"roles"`
}

RoleConfig contains the release's default roles, declared by scope.

type RoleFile

type RoleFile []byte

RoleFile is the bytes of a role file: the release's default roles, authored as JSON in the RoleConfig shape and embedded in the application binary (//go:embed roles.json). It is handed to New through WithDefaultRoles, which parses and validates it, so a release whose file is malformed or names what its collection does not declare does not start.

func (RoleFile) Parse

func (f RoleFile) Parse() (*RoleConfig, error)

Parse decodes the file into its configuration and checks its shape: the JSON shape is RoleConfig's, and a field the shape does not declare is an error, since a misspelled key would otherwise silently drop the roles under it; every role name is in the grammar (see Role) and declared once, every role carries a description, and every grant is well-formed with a condition that parses. Nothing here needs the permission collection, so a tool checks a role file with Parse alone and gets the refusals New would give before it looks at the collection; what the file grants is validated against the collection by New and ValidateRoles.

type RoleHolder added in v0.5.0

type RoleHolder struct {
	User   accesstypes.User
	Own    bool
	Groups []GroupInfo
}

RoleHolder is one person who holds a role in a scope now, as UserManager.RoleHolders lists them, with how they hold it: by a membership of their own held there (Own), through the groups they are in that hold the role there (Groups), or both. Removing the person's own membership leaves what they hold through a group, which goes when they leave the group or the group loses the role.

type RoleInfo

type RoleInfo struct {
	Name        accesstypes.Role `json:"name"`
	Description string           `json:"description"`
}

RoleInfo is one role as UserManager.Roles lists it: the name it is held under and the description saying what it is for — the role file's for a default role, the one AddRole was given for a custom role.

type RoleKey added in v0.3.0

type RoleKey struct {
	Kind   string
	Axis   string
	Domain string
	Role   accesstypes.Role
}

RoleKey is the key of one row of the roles table (<Prefix><Store>Roles), its columns in key order: where a custom role is held, in the stores' encoding of the scope, and the role in the spelling the store holds it.

type RoleReader added in v0.3.0

type RoleReader func(ctx context.Context, key RoleKey) (bool, error)

RoleReader reports whether the roles table holds the row of a key. The caller of UserManager.Membership supplies one over the transaction it writes the membership in (through the resource it declares over the roles table), so the role is read in the transaction that seats a person in it: a role deleted beside it fails one of the two.

type RoleResourceChecker

type RoleResourceChecker interface {
	CheckRoleResources(
		ctx context.Context, env accesstypes.Environment, role accesstypes.Role, scope accesstypes.Scope, perm accesstypes.Permission, resources ...accesstypes.Resource,
	) (accesstypes.Decisions, error)

	RolePermissionDigest(ctx context.Context, role accesstypes.Role, scope accesstypes.Scope) (accesstypes.PermissionDigest, error)

	RoleHasGrants(ctx context.Context, role accesstypes.Role, scope accesstypes.Scope) (bool, error)
}

RoleResourceChecker is the engine surface a RoleChecker delegates to: the check call that answers enforcement, and the digest and foothold calls that answer the frontend's advisory questions — the role twin of UserResourceChecker. *Client satisfies it; test doubles satisfy it with the role check they already script plus digest and foothold stubs.

type ScopedRoles

type ScopedRoles struct {
	Global []*Role `json:"global"`
	Domain []*Role `json:"domain"`
}

ScopedRoles declares every role at exactly one scope, structurally — each scope its own JSON key, mirroring how accesstypes.Scope and role assignments express the global partition. A role describes powers at one scope: a global role carries grants on global-scoped resources and is held in the global partition only; a domain role carries grants on domain-scoped resources and reaches every tenant domain. A grant whose resource's scope contradicts the role's declared scope fails validation — it would otherwise be held where the role's holders never look. A job function needing both kinds of powers is two roles assigned to one user, never one mixed role.

type ShadowedRole

type ShadowedRole struct {
	Scope accesstypes.PolicyScope
	Role  accesstypes.Role
}

ShadowedRole reports a custom role in the policy store whose name a default role of the running release has in the same kind of scope: a later release introduced a default role with the custom role's name. The default wins at load, so the custom role's grants are skipped and its members hold the default role's grants. One report per such role reaches the reload-error hook each time a snapshot compiles, and the deploy check lists it as a Warning. Rename or delete the custom role to clear it.

func (*ShadowedRole) Error

func (e *ShadowedRole) Error() string

Error prints the role and what the load did with it.

func (*ShadowedRole) String

func (e *ShadowedRole) String() string

String renders the finding as the one line the deploy check prints.

type SkippedGrant

type SkippedGrant struct {
	Scope accesstypes.PolicyScope
	// Subject is the grant's holder: "role Chief" or "user dana".
	Subject    string
	Permission accesstypes.Permission
	// Resource is the dotted resource name ("Widgets", "Widgets.price"); it is
	// empty for a scope-wide grant.
	Resource  accesstypes.Resource
	Condition string
	Reason    error
}

SkippedGrant reports a grant the policy store holds that the running release cannot use: its condition does not parse, a row-referencing condition sits on a scope-wide grant, or it names a permission, resource or field the release does not declare. The snapshot loaded without the grant, so the permission it would grant is denied and the rest of the policy is in force. One report per such grant reaches the reload-error hook (WithReloadErrorHandler) each time a snapshot compiles; the default hook writes it to the log. Test for it with errors.As. The deploy check (Client.CheckPolicy) lists the same grant as a Warning.

func (*SkippedGrant) Error

func (e *SkippedGrant) Error() string

Error prints the grant and the reason in one sentence.

func (*SkippedGrant) String

func (e *SkippedGrant) String() string

String renders the finding as the one line the deploy check prints.

func (*SkippedGrant) Unwrap

func (e *SkippedGrant) Unwrap() error

Unwrap returns the reason.

type SkippedGroupRole added in v0.5.0

type SkippedGroupRole struct {
	Group accesstypes.Group
	Scope accesstypes.PolicyScope
	Role  accesstypes.Role
	// Reason says why the group's members do not hold the role.
	Reason string
}

SkippedGroupRole reports a role the policy store holds for a group of people that the running release does not give the group's members: the group's own row is not there, the role is the Super Administrator role, which a person holds by a membership of their own alone, or the group is kept in one tenant and the role is held outside it. The snapshot loaded without the role, so nobody holds it through the group and the rest of the policy is in force. One report per such row reaches the reload-error hook (WithReloadErrorHandler) each time a snapshot compiles, and the deploy check (Client.CheckPolicy) lists it as a Warning. The management surface refuses to write such a row, so one is the mark of a row written by hand.

func (*SkippedGroupRole) Error added in v0.5.0

func (e *SkippedGroupRole) Error() string

Error prints the group, the role and why its members do not hold it.

func (*SkippedGroupRole) String added in v0.5.0

func (e *SkippedGroupRole) String() string

String renders the finding as the one line the deploy check prints.

type Store

type Store interface {
	// ReadPolicy returns the store's complete policy content as normalized
	// records for the snapshot compiler: the custom roles, their grants and
	// the memberships.
	ReadPolicy(ctx context.Context) (*policy.Records, error)

	// Membership. InsertUserRole gives the membership its period, replacing
	// the period of one that is there; the three listings return the
	// memberships that count now.
	InsertUserRole(ctx context.Context, scope accesstypes.PolicyScope, user accesstypes.User, role accesstypes.Role, period accesstypes.Period) error
	DeleteUserRole(ctx context.Context, scope accesstypes.PolicyScope, user accesstypes.User, role accesstypes.Role) error
	ListUserRoles(ctx context.Context, scope accesstypes.PolicyScope, user accesstypes.User) ([]accesstypes.Role, error)
	// ListUserMemberships returns every membership the user holds now,
	// wherever it is held, sorted by scope then role: the no-scope listing,
	// read through the user index.
	ListUserMemberships(ctx context.Context, user accesstypes.User) ([]policy.Membership, error)
	ListRoleUsers(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role) ([]accesstypes.User, error)

	// Roles. A role row carries the description its creator gave it, as
	// opaque text: InsertRole writes it with the row and, for a (scope, role)
	// that exists, is the documented no-op, so the stored description stays
	// as it is. ListRoles returns each role with its description, sorted by
	// name.
	InsertRole(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, description string) error
	ListRoles(ctx context.Context, scope accesstypes.PolicyScope) ([]policy.RoleRow, error)
	DeleteRole(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role) (bool, error)
	RoleExists(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role) (bool, error)

	// Grants. resource and field are stored as separate columns: field "" is
	// an endpoint grant, "*" an all-fields wildcard, anything else one field.
	// resource "" (with field "") is a scope-wide grant — the permission held
	// with no resource attachment; real resource names are validated non-empty
	// above this seam, so "" is structurally unreachable from data.
	// condition is the grant's condition as opaque expression text, "" when
	// unconditional, and is part of the row's identity: one (role,
	// permission, resource, field) holds one row per condition, so a role may
	// grant the same permission on one resource under several conditions.
	// InsertGrant is idempotent per row. DeleteGrant removes exactly one row;
	// DeleteGrants removes every condition's row for the (permission,
	// resource, field).
	InsertGrant(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, perm accesstypes.Permission, resource, field, condition string) error
	// InsertGrants adds the role's grant rows as one write per store round
	// trip instead of one per row: rows already present are left as they are
	// and the rest are inserted, so the call is idempotent like InsertGrant and
	// an overlap with existing rows is not an error. A row repeated in the
	// list is written once; an empty list is a no-op. Same parent-row
	// requirement as InsertGrant.
	InsertGrants(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, grants []policy.RoleGrant) error
	// ChangeGrants removes the role's removals and adds its additions as one
	// transaction: a reader sees the role's grants before the change or after
	// it, never between, and a failure leaves them as they were. Additions
	// already present are left as they are, as in InsertGrants; removals of
	// absent rows are no-ops; nothing to change is a no-op. Same parent-row
	// requirement as InsertGrant for the additions.
	ChangeGrants(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, removals, additions []policy.RoleGrant) error
	DeleteGrant(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, perm accesstypes.Permission, resource, field, condition string) error
	DeleteGrants(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, perm accesstypes.Permission, resource, field string) error
	ListRoleGrants(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role) ([]policy.RoleGrant, error)

	// Groups of people. A group is kept in the global partition or in one
	// domain, under the id its creator generated, and its name is held to one
	// group where it is kept (a unique index). InsertGroup is no idempotent
	// insert: an id or a name already taken there is an error, reported by
	// taken. SetGroupDescription and DeleteGroup report whether the group was
	// there; DeleteGroup refuses with an error while the group has a member or
	// a role that has not ended, checked in the delete's own transaction, and
	// takes the ended ones with the group. ListGroups returns the groups kept
	// in scope, sorted by name, and Group one by its id.
	InsertGroup(ctx context.Context, group *policy.GroupRow) (taken bool, err error)
	SetGroupDescription(ctx context.Context, group accesstypes.Group, description string) (bool, error)
	DeleteGroup(ctx context.Context, group accesstypes.Group) (bool, error)
	Group(ctx context.Context, group accesstypes.Group) (*policy.GroupRow, bool, error)
	ListGroups(ctx context.Context, scope accesstypes.PolicyScope) ([]policy.GroupRow, error)

	// A group's members. An insert gives the person's place its period, as a
	// membership's does, and deletes of absent rows are no-ops; the group's row
	// must exist for an insert. ListGroupMembers returns the people in the
	// group now, sorted by user, and ListUserGroups the groups the user is in
	// now, wherever each is kept, sorted by id, read through the index led by
	// the user.
	InsertGroupMember(ctx context.Context, group accesstypes.Group, user accesstypes.User, period accesstypes.Period) error
	DeleteGroupMember(ctx context.Context, group accesstypes.Group, user accesstypes.User) error
	ListGroupMembers(ctx context.Context, group accesstypes.Group) ([]accesstypes.User, error)
	ListUserGroups(ctx context.Context, user accesstypes.User) ([]policy.GroupRow, error)

	// The roles a group holds, each held where its scope says, as a
	// membership's is. An insert gives the role its period and deletes of
	// absent rows are no-ops; the group's row must exist for an insert, and
	// the role is named by name alone. ListGroupRoles returns the roles the
	// group holds now, sorted by scope then role. ListUserGroupRoles returns
	// every role held now by a group the user is in now, each with its group
	// and where the group is kept: what the person holds through groups, as
	// one read. ListRoleGroups returns the groups that hold role in scope now,
	// sorted by name then id: the groups a role is held through. DeleteRole
	// refuses, wrapping policy.ErrHeldByGroup, while a group's row of the role
	// in the scope has not ended, checked in the delete's own transaction, and
	// takes the ended ones with the role.
	InsertGroupRole(ctx context.Context, group accesstypes.Group, scope accesstypes.PolicyScope, role accesstypes.Role, period accesstypes.Period) error
	DeleteGroupRole(ctx context.Context, group accesstypes.Group, scope accesstypes.PolicyScope, role accesstypes.Role) error
	ListGroupRoles(ctx context.Context, group accesstypes.Group) ([]policy.Membership, error)
	ListUserGroupRoles(ctx context.Context, user accesstypes.User) ([]policy.GroupRole, error)
	ListRoleGroups(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role) ([]policy.GroupRow, error)
}

Store is the persistence seam for policy data: three typed tables (custom roles, user-role memberships, role grants) and the three of the groups of people (the groups, their members, the roles each group holds), each row held where its accesstypes.PolicyScope says — the global partition, one tenant domain or every tenant domain, persisted as the structural column triple (Kind, Axis, Domain) — plus one normalized read feeding the snapshot compiler. The release's default roles have no rows: the store holds only what is written at run time. Implementations are thin — each method is one SQL statement against one store's tables; everything smarter (validation, resource/field splitting, change signaling, snapshot compilation) lives in the access package, one shared code path for every store.

The interface is sealed by construction: ReadPolicy's signature references this module's internal/policy package, so only packages inside this module can implement it. Use the provided implementations:

spannerstore.New(client, opts...)   // Cloud Spanner
postgresstore.New(pool, opts...)    // PostgreSQL, rides the app's pgx pool

Store values hold bare names only — no marshal prefixes, no sentinel values. All values are opaque labels to the store: referential validity of domains, users, resources and role names belongs to the callers that write them. Where a row is held is stored structurally: the kind column names the global partition, one domain or every domain, never a distinguished domain value, so any domain string is ordinary tenant data. The axis column names the axis a domain belongs to and is the empty string for the default axis — the only axis a scope can name today, so every row carries "" and a later axis declaration changes no stored row. A row under any other axis fails the policy read rather than folding into the default.

Contracts every implementation provides:

  • Inserts are idempotent: re-inserting an existing row is a no-op, not an error. Deletes of absent rows are no-ops.
  • An assignment (a person's role, a person's place in a group, a group's role) carries the period it counts in, two nullable instants. Its insert gives the assignment that period: the row is written where the key is free, and where it is taken the period is replaced and the rest of the row left as it was, so assigning again is how a period changes and the same period again is a no-op. No row is written when a period begins or ends: the reads apply it. The listings of what a person or a group holds return the assignments that count at the database's present, so one outside its period is left out while its row is still there; ReadPolicy returns every row with its period, for the engine to apply at the instant of each check.
  • A membership names a role by name alone: InsertUserRole writes it whether or not a role row exists, since the role may be one of the release's defaults, which have no row. The access package checks that the name resolves before it writes.
  • DeleteRole is scoped to (scope, role): it cascades the role's grants, refuses with an error while memberships held in that scope that have not ended still name the role (checked in the same transaction as the delete), takes the ended ones with the role, and reports whether a row was actually deleted.
  • InsertGrant requires the (scope, role) row to exist (DB-enforced parent interleave or foreign key): a grant is a custom role's.
  • ChangeGrants applies a role's removals and additions in one transaction, so a grant whose condition changed (one row removed, one added) is never seen with neither row.
  • List results are sorted for deterministic output.
  • ReadPolicy reads roles, grants, memberships, groups and their members with snapshot consistency: the row sets observe the same store state.
  • A group's member and a group's role each require the group's row (DB-enforced foreign key), and DeleteGroup refuses a group that still has a member or a role that has not ended: a group goes once it is emptied, so no person loses a role by a group's deletion, and the ended members and roles, which give nobody anything, go with it.

type Tables added in v0.3.0

type Tables struct {
	Roles      string
	UserRoles  string
	RoleGrants string
	// UserRolesByUserID is the index on the memberships that leads with the user.
	UserRolesByUserID string
	// Groups are the groups of people, GroupMembers each person's place in one and
	// GroupRoles the roles a group holds.
	Groups       string
	GroupMembers string
	GroupRoles   string
	// GroupsByName is the unique index that holds a group's name to one group where the
	// group is kept, GroupMembersByUserID the index on the members that leads with the
	// user, and GroupRolesByScope the index on the groups' roles that leads with where a
	// role is held, as the memberships' key does.
	GroupsByName         string
	GroupMembersByUserID string
	GroupRolesByScope    string
}

Tables names the tables one policy store keeps: the custom roles, the memberships and the custom roles' grants, with the index the memberships are listed by user through, and the groups of people with their members and the roles each group holds.

func TablesWithPrefix added in v0.3.0

func TablesWithPrefix(prefix, store string) (Tables, error)

TablesWithPrefix answers the names of the policy store kept under prefix and store: {prefix}{store}Roles, {prefix}{store}UserRoles and {prefix}{store}RoleGrants, and {prefix}{store}Groups, {prefix}{store}GroupMembers and {prefix}{store}GroupRoles. It is the one rule both stores name their tables by, exported so whatever else names them (an application's migrations, the code generator declaring the management resources over them) cannot spell them another way. An application with several independent policy stores in one database gives each its own store name; the default is the empty name.

type UserChecker

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

UserChecker is the request-bound permission checker for one user: the canonical implementation of the resource package's UserPermissions seam. Its method set structurally satisfies that interface without either package importing the other; an application's per-request accessor is one line — return client.ForUser(user).

A UserChecker binds the user only. Scope and Environment arrive per check from the caller, so one value serves every check in a request.

func NewUserChecker

func NewUserChecker(checker UserResourceChecker, user accesstypes.User) *UserChecker

NewUserChecker returns a UserChecker for user over checker. Applications use Client.ForUser (or Controller.ForUser); this constructor exists so test doubles implementing UserResourceChecker can satisfy Controller.ForUser in one line.

func (*UserChecker) AdministersTenant added in v0.5.0

func (u *UserChecker) AdministersTenant(ctx context.Context, domain accesstypes.Domain) (bool, error)

AdministersTenant reports whether the bound user administers the tenant: the question the resource package asks of a session's actor before a directory-only tenant keeps a password session out. It is a pure delegate to UserAdministersTenant.

func (*UserChecker) Check

Check returns the Decision for perm on each of resources within scope for the bound user. It is a pure delegate to CheckUserResources — see there for the Decision, grouping, Environment, and scope semantics.

func (*UserChecker) HasGrants

func (u *UserChecker) HasGrants(ctx context.Context, scope accesstypes.Scope) (bool, error)

HasGrants reports whether the bound user holds at least one grant in scope — the foothold a tenant picker filters the application's tenant list by, and the visibility question concealed tenancy asks. It is a pure delegate to UserHasGrants; see Client.UserHasGrants for the foothold semantics.

func (*UserChecker) PermissionDigest

func (u *UserChecker) PermissionDigest(ctx context.Context, scope accesstypes.Scope) (accesstypes.PermissionDigest, error)

PermissionDigest returns the bound user's structural grant enumeration within scope — the frontend digest payload. It is a pure delegate to UserPermissionDigest; see Client.UserPermissionDigest for the non-folding semantics.

func (*UserChecker) SuperAdministrator added in v0.5.0

func (u *UserChecker) SuperAdministrator(ctx context.Context) (bool, error)

SuperAdministrator reports whether the bound user holds the Super Administrator role: the question the resource package asks of a session's actor before it holds the session to a tenant's sign-in settings. It is a pure delegate to UserIsSuperAdministrator.

func (*UserChecker) User

func (u *UserChecker) User() accesstypes.User

User returns the bound user.

type UserManager

type UserManager interface {
	// AddRoleUsers assigns role to users, the memberships held in scope.
	// Errors if role doesn't exist in scope: a default role of scope's kind
	// or a custom role held in scope — or, for one domain, in every domain.
	// A custom role held in one domain alone cannot be assigned in every
	// domain.
	AddRoleUsers(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, users ...accesstypes.User) error

	// AddUserRoles assigns roles to user, the memberships held in scope, each
	// with no period: it counts until it is removed, and a role the user held
	// for a period loses the period. Errors if any role doesn't exist in
	// scope, as AddRoleUsers defines it.
	AddUserRoles(ctx context.Context, scope accesstypes.PolicyScope, user accesstypes.User, roles ...accesstypes.Role) error

	// AssignUserRole gives user the role in scope for the period: the role
	// counts from the period's start, where it has one, until its end, where
	// it has one, with no row written in between. Assigning again is how a
	// period changes: the period handed replaces the one the assignment had.
	// Errors as AddUserRoles does, if the period ends at or before its start,
	// and if it puts an end or a start on the Super Administrator role, which
	// takes neither.
	AssignUserRole(ctx context.Context, scope accesstypes.PolicyScope, user accesstypes.User, role accesstypes.Role, period accesstypes.Period) error

	// DeleteRoleUsers removes users from role, the memberships held in scope.
	// Errors if role doesn't exist.
	DeleteRoleUsers(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, users ...accesstypes.User) error

	// DeleteUserRoles removes user's memberships of roles held in scope.
	DeleteUserRoles(ctx context.Context, scope accesstypes.PolicyScope, user accesstypes.User, roles ...accesstypes.Role) error

	// Membership answers the key of the row that says user holds role in
	// scope, for a caller that writes it inside a transaction of its own
	// instead of through AddUserRoles. Errors as AddUserRoles does: role
	// doesn't exist in scope, or user is empty. A custom role is read through
	// held, the caller's reader of the roles table over that transaction; a
	// default role needs no read. The caller commits the row and then calls
	// Controller.PolicyChanged. A row to remove needs no check and is spelled
	// by NewMembershipKey. A caller that writes the row with a period asks
	// ValidatePeriod first.
	Membership(ctx context.Context, scope accesstypes.PolicyScope, user accesstypes.User, role accesstypes.Role, held RoleReader) (MembershipKey, error)

	// UserRoles returns the roles user holds now, keyed by where each is held:
	// the memberships of their own and the roles of every group they are in,
	// each role listed once in each place, and none that is outside its
	// period, whether or not its row is still there. A membership held in every
	// domain is one entry under EveryDomainPolicyScope, never one per domain.
	// With no scopes it lists every place the user holds a role in; with
	// scopes, the roles held in each, an entry per scope asked. It is what a
	// sign-in decides a person by, so a person who holds a role through a
	// group alone is somebody. The Super Administrator role is listed only
	// where the user's own membership holds it: no group gives it.
	UserRoles(ctx context.Context, user accesstypes.User, scopes ...accesstypes.PolicyScope) (accesstypes.RoleCollection, error)

	// TenantsAdministered lists the tenants user administers now, sorted: the
	// tenant domains where they hold one of the application's tenant
	// administrator roles (WithTenantAdministratorRoles) in the tenant itself,
	// by a membership of their own in the tenant's domain or through a group
	// kept in that tenant, and none that is outside its period. A role held
	// in every tenant, or through a group kept for the whole application,
	// lists no tenant. It reads the store, as UserRoles does: it is what a
	// sign-in decides the administrators' way into a directory-only tenant
	// by, and Controller.UserAdministersTenant answers the same question of
	// one tenant at each request.
	TenantsAdministered(ctx context.Context, user accesstypes.User) ([]accesstypes.Domain, error)

	// AddGroup creates a group of people kept in scope, the global partition
	// or one tenant domain, and answers the id the store names it by. The
	// name is what people know the group by, held to one group where it is
	// kept, and the description says who is in it; both are refused when
	// empty. A group kept in every domain is refused.
	AddGroup(ctx context.Context, scope accesstypes.PolicyScope, name, description string) (accesstypes.Group, error)

	// DescribeGroup replaces the description of group. Errors if the group
	// does not exist or the description is empty.
	DescribeGroup(ctx context.Context, group accesstypes.Group, description string) error

	// DeleteGroup removes group. Errors if the group does not exist, or still
	// has a member or holds a role: a group goes once it is emptied. A member
	// or a role whose period has ended goes with it.
	DeleteGroup(ctx context.Context, group accesstypes.Group) error

	// Groups returns the groups kept in scope, sorted by name.
	Groups(ctx context.Context, scope accesstypes.PolicyScope) ([]GroupInfo, error)

	// UserGroups returns the groups user is in, wherever each is kept.
	UserGroups(ctx context.Context, user accesstypes.User) ([]GroupInfo, error)

	// AddGroupUsers puts users in group, each with no period: each then holds
	// the group's roles wherever the group holds them. Errors if the group
	// does not exist.
	AddGroupUsers(ctx context.Context, group accesstypes.Group, users ...accesstypes.User) error

	// AssignGroupUser puts user in group for the period, replacing the period
	// of a place that is there: the person holds the group's roles while their
	// place and the group's role both count. Errors as AddGroupUsers does, and
	// if the period ends at or before its start.
	AssignGroupUser(ctx context.Context, group accesstypes.Group, user accesstypes.User, period accesstypes.Period) error

	// DeleteGroupUsers takes users out of group.
	DeleteGroupUsers(ctx context.Context, group accesstypes.Group, users ...accesstypes.User) error

	// GroupUsers returns the people in group now.
	GroupUsers(ctx context.Context, group accesstypes.Group) ([]accesstypes.User, error)

	// AddGroupRoles gives group the roles, each held in scope, so every
	// person in the group holds them there. A group kept for the whole
	// application holds roles wherever a person can: globally, in one domain
	// or in every domain. A group kept in one domain holds roles in that
	// domain alone. No group holds the Super Administrator role. Errors if
	// the group does not exist or a role doesn't exist in scope, as
	// AddRoleUsers defines it. Each role is given with no period.
	AddGroupRoles(ctx context.Context, group accesstypes.Group, scope accesstypes.PolicyScope, roles ...accesstypes.Role) error

	// AssignGroupRole gives group the role in scope for the period, replacing
	// the period of one the group holds there. Errors as AddGroupRoles does,
	// and if the period ends at or before its start.
	AssignGroupRole(ctx context.Context, group accesstypes.Group, scope accesstypes.PolicyScope, role accesstypes.Role, period accesstypes.Period) error

	// DeleteGroupRoles takes the roles group holds in scope away from it.
	DeleteGroupRoles(ctx context.Context, group accesstypes.Group, scope accesstypes.PolicyScope, roles ...accesstypes.Role) error

	// GroupRoles returns the roles group holds now, keyed by where each is
	// held.
	GroupRoles(ctx context.Context, group accesstypes.Group) (accesstypes.RoleCollection, error)

	// GroupRole answers the key of the row that says group holds role in
	// scope, for a caller that writes it inside a transaction of its own
	// instead of through AddGroupRoles. kept is where the group is kept, read
	// by the caller with the group's row. Errors as AddGroupRoles does. A
	// custom role is read through held, as Membership reads it. The caller
	// commits the row and then calls Controller.PolicyChanged. A row to
	// remove needs no check and is spelled by NewGroupRoleKey.
	GroupRole(ctx context.Context, group accesstypes.Group, kept, scope accesstypes.PolicyScope, role accesstypes.Role, held RoleReader) (GroupRoleKey, error)

	// UserPermissions returns user's effective permissions in each scope —
	// what the user holds there, from memberships held in the scope and in
	// every domain, default and custom roles alike, answered from the policy
	// snapshot. At least one scope is required.
	UserPermissions(ctx context.Context, user accesstypes.User, scopes ...accesstypes.Scope) (accesstypes.UserPermissionCollection, error)

	// AddRole creates a custom role held in scope, with the description
	// saying what it is for: one or two plain sentences, refused when empty.
	// The name follows the one grammar every role name does, letters and
	// digits starting with a capital letter (see Role), and a name outside it
	// is refused. Errors if the role exists in scope, or its name is a
	// default role's.
	AddRole(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, description string) error

	// ResolveRole returns the role scope holds under name, matched without
	// regard to case, in the spelling the store holds it: a default role of
	// scope's kind, a custom role held in scope, or — for one domain — a
	// custom role held in every domain. The exact spelling wins when it
	// exists; otherwise the one role that matches case-insensitively. Two
	// such roles with no exact match is an error, never a guess. A
	// directory names roles without regard to case (a Google group is an
	// email address), so the name it asserts resolves here to the spelling
	// the role file or AddRole gave the role.
	ResolveRole(ctx context.Context, scope accesstypes.PolicyScope, name string) (accesstypes.Role, bool, error)

	// Roles returns the roles that exist in scope, sorted by name, each with
	// its description: the default roles of scope's kind, described by the
	// role file, and the custom roles held in scope, and in every domain for
	// one domain, described as AddRole was told. A name is listed once
	// however many places hold it: a default before a custom role it
	// shadows, the scope's own custom role before one held in every domain.
	Roles(ctx context.Context, scope accesstypes.PolicyScope) ([]RoleInfo, error)

	// DeleteRole removes a custom role held in scope with its grants. Returns
	// false with an error if the role has members in scope, if a group holds
	// it there, or if it is a default role. The delete is scoped to the given
	// scope.
	DeleteRole(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role) (bool, error)

	// AddRolePermission grants permission to role scope-wide: the permission is
	// held with no resource attachment. Errors if role is not a custom role
	// held in scope.
	AddRolePermission(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, permission accesstypes.Permission) error

	// DeleteRolePermission removes a scope-wide permission from role. Errors
	// if role is not a custom role held in scope.
	DeleteRolePermission(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, permission accesstypes.Permission) error

	// AddRolePermissionResources grants permission on resources to role.
	// Errors if role is not a custom role held in scope.
	AddRolePermissionResources(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, permission accesstypes.Permission, resources ...accesstypes.Resource) error

	// AddRoleGrant grants permission on one resource to role, limited by
	// condition ("" is unconditional). Errors if role is not a custom role
	// held in scope.
	AddRoleGrant(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, permission accesstypes.Permission, resource accesstypes.Resource, condition string) error

	// AddRoleGrants writes the grants to role as one store write rather than
	// one per grant; grants the role already holds are left as they are.
	// Errors if role is not a custom role held in scope or a grant names no
	// resource.
	AddRoleGrants(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, grants ...GrantRow) error

	// ChangeRoleGrants removes the removals from role and adds the additions
	// to it as one store write: a reader sees the role's grants before the
	// change or after it, never between, and a failure leaves them as they
	// were. Additions the role already holds are left as they are; removals
	// it does not hold are ignored. Errors if role is not a custom role held
	// in scope or a grant names no resource.
	ChangeRoleGrants(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, removals, additions []GrantRow) error

	// DeleteRolePermissionResources removes every grant of permission on the
	// resources from role, whatever their conditions. Errors if role is not
	// a custom role held in scope.
	DeleteRolePermissionResources(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, permission accesstypes.Permission, resources ...accesstypes.Resource) error

	// DeleteRoleGrant removes one grant: permission on resource under
	// condition ("" is the unconditional grant); other conditions on the
	// resource stay. Errors if role is not a custom role held in scope.
	DeleteRoleGrant(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role, permission accesstypes.Permission, resource accesstypes.Resource, condition string) error

	// DeleteAllRolePermissions removes all permissions from role, scope-wide
	// and resource-specific alike. Errors if role is not a custom role held
	// in scope.
	DeleteAllRolePermissions(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role) error

	// RoleUsers returns the users who hold role in scope now, each once,
	// sorted: by a membership of their own held there, and through a group
	// that holds the role there, as UserRoles lists what a person holds both
	// ways. A person listed through a group alone keeps the role when a
	// membership of their own is removed: it goes when they leave the group or
	// the group loses the role. RoleHolders says which way each holds it.
	RoleUsers(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role) ([]accesstypes.User, error)

	// RoleHolders returns who holds role in scope now, sorted by user, each
	// with how: by a membership of their own held there, through the groups
	// they are in that hold the role there, or both. No group gives the Super
	// Administrator role, so its holders hold it themselves.
	RoleHolders(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role) ([]RoleHolder, error)

	// RolePermissions returns the permissions role holds in scope — a place a
	// request is — and how each is granted (scope-wide, on resources, or
	// both), inheritance folded, answered from the policy snapshot: the
	// file's grants for a default role, the store's for a custom one. Errors
	// if role doesn't exist in scope.
	RolePermissions(ctx context.Context, scope accesstypes.Scope, role accesstypes.Role) (accesstypes.RolePermissionCollection, error)

	// RoleGrants returns the role's resource grants as held, keyed by
	// permission and resource, with the conditions each resource is granted
	// under (sorted; "" is the unconditional grant): the store's rows for a
	// custom role held in scope (or, for one domain, in every domain), the
	// file's grants for a default role. Scope-wide grants are not included.
	// Errors if role doesn't exist in scope.
	RoleGrants(ctx context.Context, scope accesstypes.PolicyScope, role accesstypes.Role) (map[accesstypes.Permission]map[accesstypes.Resource][]string, error)
}

UserManager manages role membership, custom roles and their grants. Where a membership, a role or a grant is held is an accesstypes.PolicyScope: the global partition, one tenant domain, or every tenant domain. Scopes are opaque partition labels: no method validates tenant existence — the application owns its tenant list and validates tenants at its own boundaries.

Roles are of two kinds. The release's default roles come from the role file (WithDefaultRoles): a global default is held in the global partition, a domain default in every tenant domain; they exist without a store row, a membership names them by name, their grants are the file's and are read here, never written. Custom roles are the store's: created, granted and deleted through this interface, held where they were created. A default role's name is taken: a custom role cannot be created under it, and a custom role that predates a default of the same name is shadowed by it (see ShadowedRole).

The base-name/Resources-suffix pairing is the API's naming standard: the base method addresses a permission held scope-wide (attached to no resource); the Resources variant addresses specific resources.

type UserResourceChecker

type UserResourceChecker interface {
	CheckUserResources(
		ctx context.Context, env accesstypes.Environment, user accesstypes.User, scope accesstypes.Scope, perm accesstypes.Permission, resources ...accesstypes.Resource,
	) (accesstypes.Decisions, error)

	UserPermissionDigest(ctx context.Context, user accesstypes.User, scope accesstypes.Scope) (accesstypes.PermissionDigest, error)

	UserHasGrants(ctx context.Context, user accesstypes.User, scope accesstypes.Scope) (bool, error)

	UserIsSuperAdministrator(ctx context.Context, user accesstypes.User) (bool, error)

	UserAdministersTenant(ctx context.Context, user accesstypes.User, domain accesstypes.Domain) (bool, error)
}

UserResourceChecker is the engine surface a UserChecker delegates to: the check call that answers enforcement, the digest and foothold calls that answer the frontend's advisory questions, and the questions of who is a super administrator and who administers a tenant. *Client satisfies it; test doubles that script permission checks satisfy it with the same check method they already fake plus digest, foothold, super administrator and tenant administrator stubs.

type Warning

type Warning interface {
	fmt.Stringer
	// contains filtered or unexported methods
}

Warning is one thing a deploy should hear about before the release takes traffic: a shape the role file carries as written but flags (GrantWarning, RequiredFieldWarning, ConcealingKeyWarning), or something the policy store holds that this release cannot use as written (SkippedGrant, ShadowedRole, OrphanedMembership). A consumer that ranges and prints sees one line each, and one that switches on the kind reads its fields.

func ValidateRoles

func ValidateRoles(store PermissionCollection, roleConfig *RoleConfig) ([]Warning, error)

ValidateRoles checks a role configuration the way New does before it accepts the file — role names and descriptions, grant grammar, every condition against the collection's vocabulary, each grant at its role's declared scope — and returns the warnings the configuration raises (see Warning), with no store client involved. A project test or a tool gets the answer the release's start would.

Directories

Path Synopsis
internal
policy
Package policy defines the normalized policy records that flow between a policy store and the snapshot compiler: a store reader turns rows into records; everything after (interning, bitsets, caches) is one shared code path in the access package.
Package policy defines the normalized policy records that flow between a policy store and the snapshot compiler: a store reader turns rows into records; everything after (interning, bitsets, caches) is one shared code path in the access package.
signaltest
Package signaltest is an in-memory signal channel with the shape of the application's one: Signal publishes a kind and Subscribe follows one.
Package signaltest is an in-memory signal channel with the shape of the application's one: Signal publishes a kind and Subscribe follows one.
storetest
Package storetest is the shared conformance suite for access.Store implementations.
Package storetest is the shared conformance suite for access.Store implementations.
Package mock contains the generated mocks for the project.
Package mock contains the generated mocks for the project.
mock_access
Package mock_access is a generated GoMock package.
Package mock_access is a generated GoMock package.
Package postgresstore implements access.Store over PostgreSQL, riding the application's existing connection pool.
Package postgresstore implements access.Store over PostgreSQL, riding the application's existing connection pool.
Package spannerstore implements access.Store over Cloud Spanner.
Package spannerstore implements access.Store over Cloud Spanner.

Jump to

Keyboard shortcuts

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