Ectomancer.Authorization (Ectomancer v1.2.1)

Copy Markdown View Source

Authorization system for Ectomancer tools.

Supports three authorization strategies:

  1. Inline function - Simple authorization with a function

    authorize fn actor, action ->
      actor.role == :admin or action in [:list, :get]
    end
  2. Policy module - Complex authorization with a policy module

    authorize with: MyApp.Policies.UserPolicy
  3. No authorization - Public access

    authorize :none

Cascade Authorization

Authorization can be defined at three levels (from broadest to specific):

  1. Global (in use Ectomancer)
  2. Schema (in expose/2)
  3. Action (in expose/2 with action-specific rules)

When multiple levels are defined, they cascade:

  • All levels must pass for authorization to succeed
  • If any level fails, the tool returns an unauthorized error

Summary

Functions

Checks authorization for a tool execution.

Checks if authorization is configured.

Functions

check(actor, action, opts)

@spec check(any(), atom(), keyword()) :: :ok | {:error, String.t()}

Checks authorization for a tool execution.

Parameters

  • actor - The current actor (from frame.assigns[:ectomancer_actor])
  • action - The action being performed (e.g., :list, :get, :create)
  • opts - Authorization options
    • :handler - The authorization handler (function, module, or :none)
    • :schema - The schema module (for context)
    • :parent_auth - Parent authorization config for cascading

Returns

  • :ok - Authorization passed
  • {:ok, :scoped, scope_fn} - Authorization passed with row-level scope
  • {:error, reason} - Authorization failed with reason

The scope_fn is a function that takes an Ecto query and returns a scoped query:

fn query ->
  from(u in query, where: u.org_id == ^actor.org_id)
end

When a scope is returned, it is automatically applied to all CRUD queries (list, get, update, destroy) for that tool call.

enabled?(opts)

@spec enabled?(keyword()) :: boolean()

Checks if authorization is configured.