Configures an Ash resource as an outbound webhook destination, including its enable/disable state and references to signing secrets.
use Ash.Resource,
data_layer: AshSqlite.DataLayer,
extensions: [AshHooks.Endpoint]
# Map a declared :active boolean instead of injecting :status.
endpoint do
status_attribute :active
enabled_values [true]
disabled_value false
endThe extension injects url, status (:enabled | :disabled), and four
secret references (secret_ref required,
previous_secret_ref / legacy_secret_ref / legacy_previous_secret_ref
for rotation and the legacy envelope). All four are
AshHooks.Endpoint.SecretRef. The type rejects secret-shaped literals
(whsec_ / whsk_ / whpk_ prefixed material) at cast, on every write
path including consumer-defined actions: secrets live behind consumer
callbacks; store references to those secrets in the endpoint rows.
With key_lifecycle :on, a standard previous key signs only before its
previous_secret_retired_at, even if the retirement sweep is delayed.
A roll inside an active overlap returns {:error, :overlap_active};
use expire_previous_secret/2 before rolling again immediately. An ended
window permits rolling before the sweep. default_overlap_seconds
configures the overlap (86,400 seconds when unset), and optional
max_overlap_seconds caps both rolling and retirement scheduling from now.
A stored previous reference without a retirement time is an undated state:
it keeps signing, the sweep skips it, and roll_secret/2 refuses it with
{:error, :previous_secret_undated}. Resolve it with
schedule_previous_retirement/3 or expire_previous_secret/2. No retirement
date is inferred when lifecycle tracking is adopted. Without lifecycle
tracking, previous keys keep signing until their references are removed.
With legacy_key_lifecycle :on (requires key_lifecycle :on), the legacy
slot follows the same lifecycle. Migrate its five nullable timestamps:
legacy_secret_created_at, legacy_secret_first_used_at,
legacy_previous_secret_created_at, legacy_previous_secret_first_used_at,
and legacy_previous_secret_retired_at. The actions
:mark_legacy_current_secret_used and :mark_legacy_previous_secret_used
record first use with the same reference fence. The lifecycle helpers
accept slot: :standard | :legacy, defaulting to :standard, and operate
only on the selected slot. Overlap defaults and caps apply to both slots.
An empty legacy incumbent installs the new key without a previous key.
With the legacy option off, no legacy timestamps or actions are injected.
With status_attribute set, the extension uses that attribute instead of
injecting status. The dispatcher skips endpoints whose
mapped value is outside enabled_values, and the 410 auto-disable flips
the mapped attribute to disabled_value. The mapped attribute must be
declared by the consumer (fail-closed at compile).
The dispatcher skips non-enabled endpoints entirely (no delivery row). URL casting checks the scheme, metadata hostnames, and literal IP addresses on every write path. Send-time validation resolves hostnames and rejects nonpublic addresses; the HTTP adapter pins the validated connection address.
Govern read access to target URLs and secret references with your own resource policies. The package does not inject read policies.
Policy obligation: protect the injected :disable action wherever you
expose it to application callers. The 410 rule uses it as a system write
(authorize?: false). A permissive resource policy can otherwise allow
callers to disable endpoints. See AshHooks.OutboundDelivery for the
delivery ledger's action policy requirements.
The lifecycle helpers perform system writes (authorize?: false) after
checking tenancy. Authorize application callers before exposing rolling,
retirement scheduling, or immediate retirement to them.
With custodian Module, declare key_registry Resource and
key_lifecycle :on. The registry uses AshHooks.KeyRegistry, the same
transactional AshPostgres or AshSqlite data layer and repository for writes,
with matching attribute tenancy.
Migrate nullable :term columns secret_kind and previous_secret_kind;
with legacy lifecycle also migrate legacy_secret_kind and
legacy_previous_secret_kind. Each kind marks only its adjacent reference
as custody-owned. A null kind leaves the slot under its host byte resolver.
Host create and update actions refuse direct kind input. Direct reference
writes require a byte resolver and never mark the slot as custody-owned.
Signing reads the custodian from this resource and derives its canonical
tenant inside the database transaction that reads the owner. Current and
previous kinds may differ. Declare secret_resolver {module, function} for unmarked byte slots;
delivery and worker resolvers are also supported. Without a resolver, an
occupied unmarked slot fails permanently as key_kind_mismatch.
Sender HMAC kinds are refused as kind_not_allowed before custody is called.
An unsupported tenant attribute type requires custody_tenant_key {m, f, a}.
The MFA receives the cast tenant value followed by its arguments and must
return equal UTF-8 binaries for tenants the database treats as equal. This
equality contract belongs to the host. Compilation refuses an unsupported
type without the option.
With config :ash_hooks, key_material: :custody_only, endpoint and worker
secret_resolver, inbound secret and previous_secret sources, and provider
webhook_signing_secret/1 and /2 implementations are refused at compile time.
The setting is off by default; direct byte signing APIs remain supported.
Rolling moves kinds with their references. Expiration and ended-window
displacement retire custody references in the owner's transaction; the
separately scheduled registry sweep destroys them after commit. See
AshHooks.KeyRegistry and the migration instructions in UPGRADING.md.
Create custody endpoints with create_with_key/3, roll with material: or
generate: kind, recover a lost disclosure with reissue_secret/2, and
migrate existing byte slots with adopt_keys/2. These issuing operations
refuse enclosing transactions before issuing anything. Storage runs outside
transactions; owner changes and registry attachment commit together. A failed
attempt retires its own issues, and the registry sweep recovers crashed issues.
Without secret_resolver, ordinary create actions refuse direct references.
Custody owners also receive the reserved read_custody_owner system action.
It has no action filter, preparation or pagination; the resource's own
base_filter still applies. Lifecycle retirement reads the persisted owner
after the write and retains references held in any slot. A refusal before
a write leaves an enclosing host transaction usable. A failure after a
package write rolls back that write and its registry retirement together.
Summary
Functions
Adopts the occupied standard current and previous byte slots through the
resource's secret_resolver without changing lifecycle timestamps. Legacy
slots are also adopted when legacy_key_lifecycle :on supplies their kind
columns. Otherwise legacy slots remain host byte references and keep signing
through secret_resolver. Kind-marked slots remain unchanged, making adoption
resumable and idempotent. Original host byte references remain host-owned
and never enter the registry.
The resolved auto-disable policy for an endpoint resource, or nil when
the resource declares no auto_disable section: a map with
:failure_window_seconds, :failure_share, :min_attempts,
:warning_share, :warning_min_attempts, and :warning_interval_seconds
(defaults applied).
Creates an endpoint with its current custody key. Requires custodian and
key_registry. Supply exactly one of generate: kind or material: wire_key.
Standard slots generate {:standard_webhooks, :v1} or
{:standard_webhooks, :v1a}. Material uses the signing API's wire encoding.
Removes native keys from an optional-native custody endpoint, atomically
retiring every custody-owned slot for durable registry disposal. Host signing
attributes remain on the row. Pass the explicit :tenant; authorize callers
before invoking this system operation. No key material is disclosed.
Issues and attaches a native key to a host-only custody endpoint. Requires
native_signing :optional. Options: :slot (:standard or :legacy),
:generate or :material, and explicit :tenant. Returns the endpoint and
one-time disclosure for generated keys. An occupied slot is refused.
Whether an endpoint row is deliverable under its configured status
source: the injected status attribute (default) or the consumer-owned
status_attribute mapping (enabled_values / disabled_value). The
dispatcher's skip decision and the send path's dead-letter decision
both route through here, so exactly one switch governs delivery.
Retires one endpoint's selected previous signing key at once: the old reference leaves the row and its retirement timestamp records the actual retirement time, including early removal. A row with no previous key is returned unchanged. This also resolves an undated previous reference without assigning it an overlap window.
The scheduled retirement sweep: expires every endpoint whose selected
previous key's overlap window has ended (retirement time at or before now).
Schedule it alongside your retention sweeps. Signing already omits dated
previous keys at their deadline. Undated previous references are skipped;
resolve them with schedule_previous_retirement/3 or
expire_previous_secret/2. Returns {:ok, retired_count}.
Replaces the selected current custody key with a generated key of the same
kind and returns {:ok, endpoint, disclosure}. Options: :slot (:standard
or :legacy), :tenant, and :now. A byte slot returns :byte_slot;
a kind that cannot be generated returns :kind_not_allowed before issuance.
Rolls the selected signing slot with an overlap window. The incumbent
reference moves to that slot's previous reference and the new reference
takes its place. Both keys sign before the previous key's retirement time;
at that instant, signing stops using the previous key independently of
expire_previous_secrets/2, which removes expired references.
Sets the selected previous key's retirement time, including for an undated previous reference adopted with lifecycle tracking. The key signs only before that time; the sweep can remove its reference afterward.
The endpoint lifecycle statuses: :disabled is the durable circuit
breaker the 410 rule and operators flip.
Functions
Adopts the occupied standard current and previous byte slots through the
resource's secret_resolver without changing lifecycle timestamps. Legacy
slots are also adopted when legacy_key_lifecycle :on supplies their kind
columns. Otherwise legacy slots remain host byte references and keep signing
through secret_resolver. Kind-marked slots remain unchanged, making adoption
resumable and idempotent. Original host byte references remain host-owned
and never enter the registry.
Options: :tenant, :now, and :tenant_aware_secrets (pass the tenant as
the resolver's second argument). An undated previous key returns
:previous_secret_undated; schedule or expire it first. A concurrent roll
returns :rolled_underneath and retires this attempt's issued references.
Returns {:ok, endpoint}; refuses enclosing transactions with
:inside_transaction. Authorize callers before this system operation.
The resolved auto-disable policy for an endpoint resource, or nil when
the resource declares no auto_disable section: a map with
:failure_window_seconds, :failure_share, :min_attempts,
:warning_share, :warning_min_attempts, and :warning_interval_seconds
(defaults applied).
@spec create_with_key(module(), map(), keyword()) :: {:ok, struct()} | {:ok, struct(), binary()} | {:error, term()}
Creates an endpoint with its current custody key. Requires custodian and
key_registry. Supply exactly one of generate: kind or material: wire_key.
Standard slots generate {:standard_webhooks, :v1} or
{:standard_webhooks, :v1a}. Material uses the signing API's wire encoding.
Generation returns {:ok, endpoint, disclosure}: a whsec_ secret for v1,
or the whpk_ public half for v1a. Import returns {:ok, endpoint}.
Disclosure is returned once and is never persisted or emitted as telemetry.
Options: :action (the resource's primary create action by default), :tenant
and :now. Authorize the caller before this system operation.
Issuance refuses enclosing transactions with :inside_transaction. A timed
out issue returns :key_issue_expired; an owner that did not persist every
issued reference in its intended slot returns :owner_mismatch. Failed
attempts retire their issued references for the registry sweep.
Removes native keys from an optional-native custody endpoint, atomically
retiring every custody-owned slot for durable registry disposal. Host signing
attributes remain on the row. Pass the explicit :tenant; authorize callers
before invoking this system operation. No key material is disclosed.
Issues and attaches a native key to a host-only custody endpoint. Requires
native_signing :optional. Options: :slot (:standard or :legacy),
:generate or :material, and explicit :tenant. Returns the endpoint and
one-time disclosure for generated keys. An occupied slot is refused.
Whether an endpoint row is deliverable under its configured status
source: the injected status attribute (default) or the consumer-owned
status_attribute mapping (enabled_values / disabled_value). The
dispatcher's skip decision and the send path's dead-letter decision
both route through here, so exactly one switch governs delivery.
Retires one endpoint's selected previous signing key at once: the old reference leaves the row and its retirement timestamp records the actual retirement time, including early removal. A row with no previous key is returned unchanged. This also resolves an undated previous reference without assigning it an overlap window.
:slot selects :standard (default) or :legacy (requires
legacy_key_lifecycle :on). :now supplies the application clock (default UTC now).
:tenant applies to the gated write (required on multitenant
resources; the tenancy pre-flight runs before it).
@spec expire_previous_secrets(module(), keyword()) :: {:ok, non_neg_integer()} | {:error, term()}
The scheduled retirement sweep: expires every endpoint whose selected
previous key's overlap window has ended (retirement time at or before now).
Schedule it alongside your retention sweeps. Signing already omits dated
previous keys at their deadline. Undated previous references are skipped;
resolve them with schedule_previous_retirement/3 or
expire_previous_secret/2. Returns {:ok, retired_count}.
Options: :slot (:standard by default, or :legacy with
legacy_key_lifecycle :on), :now (the application clock), and :tenant (required on
multitenant resources).
Replaces the selected current custody key with a generated key of the same
kind and returns {:ok, endpoint, disclosure}. Options: :slot (:standard
or :legacy), :tenant, and :now. A byte slot returns :byte_slot;
a kind that cannot be generated returns :kind_not_allowed before issuance.
The replaced key stops signing at once. A counterparty holding only that
key is cut off immediately. The separate previous key and its retirement
time stay unchanged, and only that previous key keeps working through its
existing window. This operation ignores the overlap gate and recovers a
committed generation whose one-time disclosure was lost. It refuses an
enclosing transaction with :inside_transaction. Authorize callers first.
@spec roll_secret(struct(), keyword()) :: {:ok, struct()} | {:ok, struct(), binary()} | {:error, term()}
Rolls the selected signing slot with an overlap window. The incumbent
reference moves to that slot's previous reference and the new reference
takes its place. Both keys sign before the previous key's retirement time;
at that instant, signing stops using the previous key independently of
expire_previous_secrets/2, which removes expired references.
A dated previous key still inside its window refuses the roll with
{:error, :overlap_active}. Call expire_previous_secret/2 before rolling
again immediately, or wait for the window to end. An ended but unswept
window does not block rolling.
An undated previous reference refuses the roll with
{:error, :previous_secret_undated}. Schedule its retirement with
schedule_previous_retirement/3 or remove it with expire_previous_secret/2
before rolling.
{:ok, rolled} =
AshHooks.Endpoint.roll_secret(endpoint,
# your store already holds the new secret under this reference
new_secret_ref: "signing-key-2026-11",
overlap_seconds: 24 * 3_600
)Byte endpoints take :new_secret_ref (a fresh store reference; rolling
onto the selected incumbent or previous reference is {:error, :same_reference}).
Custody endpoints take exactly one of material: (decoded from the signing
API's wire encoding) or generate: kind. With a declared secret_resolver,
a custody endpoint may also select the byte new_secret_ref: path. Without
it, that path returns :secret_resolver_required. Missing or conflicting
custody inputs return :key_input_required.
Standard slots generate {:standard_webhooks, :v1} or
{:standard_webhooks, :v1a}; legacy slots generate {:legacy_hmac, :sha256}.
Other kinds return :kind_not_allowed before issuing anything. All generation
uses 32 cryptographically random bytes. Generation returns
{:ok, endpoint, disclosure}: a whsec_ secret for v1, a whpk_ public half
for v1a, or the exact raw key bytes for legacy. Import and byte rolls return
{:ok, endpoint}. Never persist, log, or emit the one-time disclosure.
Custody issuance refuses enclosing transactions with :inside_transaction;
an issue lost to the registry sweep returns :key_issue_expired.
Other options:
:slot (:standard by default, or :legacy with legacy_key_lifecycle :on),
:overlap_seconds
(a non-negative integer, defaulting to the resource's
default_overlap_seconds or 86,400 when unset), :now (the application
clock), :tenant. A negative or non-integer overlap returns
{:error, :invalid_overlap}. Zero stops the old key signing at the roll
instant. Above the resource's optional max_overlap_seconds, rolling
returns {:error, {:overlap_exceeds_max, max}}. Emits
[:ash_hooks, :endpoint, :roll] with the endpoint id. The row carries
references and lifecycle timestamps only, never secret material. The
gated write fences concurrent rolls
({:error, :rolled_underneath} when the incumbent moved first); a
resource without key_lifecycle :on fails with a named error.
@spec schedule_previous_retirement(struct(), term(), keyword()) :: {:ok, struct()} | {:error, term()}
Sets the selected previous key's retirement time, including for an undated previous reference adopted with lifecycle tracking. The key signs only before that time; the sweep can remove its reference afterward.
at must be a DateTime at or after the application clock. A past time
returns {:error, :retirement_in_past}, an invalid value returns
{:error, :invalid_retirement_time}, and an endpoint without a previous
reference returns {:error, :no_previous_secret}. The atomic write checks
that the previous reference is still the one supplied; a concurrent change
returns {:error, :previous_secret_changed}.
If the resource declares max_overlap_seconds, a retirement time beyond
that many seconds from now returns {:error, {:overlap_exceeds_max, max}}.
Options: :slot (:standard by default, or :legacy with
legacy_key_lifecycle :on), :now (the application clock, default UTC now),
and :tenant
(required on multitenant resources). Requires key_lifecycle :on.
Authorize the caller before invoking this system write.
@spec statuses() :: [atom()]
The endpoint lifecycle statuses: :disabled is the durable circuit
breaker the 410 rule and operators flip.