Sigra.APIToken.ScopeRegistry (Sigra v1.20.0)

Copy Markdown View Source

Scope validation and registry for API tokens.

Scopes follow a resource:action format (e.g., "profile:read", "sessions:write") and are validated against a registry of built-in and custom scopes.

Built-in Scopes

  • profile:read
  • profile:write
  • sessions:read
  • sessions:write
  • api_tokens:read
  • api_tokens:write
  • mfa:read
  • mfa:write

Custom Scopes

Register custom scopes via the :api_token config:

Sigra.Config.new!(
  repo: MyApp.Repo,
  user_schema: MyApp.User,
  api_token: [custom_scopes: ["billing:read", "billing:write"]]
)

Wildcard

The special scope "*" grants access to all resources and actions.

Summary

Functions

Returns all registered scopes (built-in + custom).

Returns true if the scope string is valid format.

Validates a list of scopes against the registry.

Functions

all_scopes(config)

(since 0.7.0)
@spec all_scopes(Sigra.Config.t()) :: [String.t()]

Returns all registered scopes (built-in + custom).

Examples

iex> config = Sigra.Config.new!(repo: R, user_schema: U)
iex> "profile:read" in Sigra.APIToken.ScopeRegistry.all_scopes(config)
true

valid_format?(scope)

(since 0.7.0)
@spec valid_format?(String.t()) :: boolean()

Returns true if the scope string is valid format.

Valid formats:

  • "resource:action" where both parts are lowercase letters and underscores
  • "*" wildcard scope

Examples

iex> Sigra.APIToken.ScopeRegistry.valid_format?("profile:read")
true

iex> Sigra.APIToken.ScopeRegistry.valid_format?("PROFILE:READ")
false

iex> Sigra.APIToken.ScopeRegistry.valid_format?("*")
true

validate_scopes(config, scopes)

(since 0.7.0)
@spec validate_scopes(Sigra.Config.t(), [String.t()]) ::
  :ok
  | {:error,
     :scopes_required
     | {:invalid_format, [String.t()]}
     | {:unregistered_scopes, [String.t()]}}

Validates a list of scopes against the registry.

Returns :ok if all scopes are valid format and registered, or an error tuple describing the issue.

Examples

iex> config = Sigra.Config.new!(repo: R, user_schema: U)
iex> Sigra.APIToken.ScopeRegistry.validate_scopes(config, ["profile:read"])
:ok

iex> Sigra.APIToken.ScopeRegistry.validate_scopes(config, [])
{:error, :scopes_required}