Sigra.MFA.Trust (Sigra v1.20.0)

Copy Markdown View Source

Trust cookie HMAC signing, verification, and mass revocation.

"Trust this browser" allows users to skip MFA on recognized browsers. The trust cookie is an HMAC-signed payload containing the user_id, trust_epoch, and issued timestamp. Verification checks the HMAC signature, user_id match, epoch match, and TTL.

Security Properties

  • HMAC-signed via Plug.Crypto.sign/4 using the app's secret_key_base (D-46)
  • Cookie payload: {user_id, trust_epoch, issued_at} (D-52)
  • Mass revocation via mfa_trust_epoch increment on user record (D-48)
  • HttpOnly, Secure, SameSite=Lax cookie options (D-54)
  • Verified against current user_id to prevent cross-user cookie reuse (Pitfall 6)

Summary

Functions

Returns the trust cookie name.

cookie_opts() deprecated

Removed: use cookie_opts/1 with a %Sigra.Config{} so :cookie_domain is honored.

Returns remember-me cookie options honoring :cookie_domain from the given config.

Revokes all trusted browsers for a user by incrementing mfa_trust_epoch.

Signs a trust cookie for the given user and epoch.

Verifies a trust cookie against the current user and epoch.

Functions

revoke_all(repo, user_schema, user_id)

(since 0.6.0)
@spec revoke_all(module(), module(), term()) :: {non_neg_integer(), nil}

Revokes all trusted browsers for a user by incrementing mfa_trust_epoch.

Uses update_all for atomic increment. All existing trust cookies become invalid because their epoch no longer matches.

Parameters

  • repo - The Ecto repo module
  • user_schema - The generated user Ecto schema module
  • user_id - The user's ID

sign(secret_key_base, user_id, trust_epoch, trust_ttl)

(since 0.6.0)
@spec sign(String.t(), term(), non_neg_integer(), pos_integer()) :: binary()

Signs a trust cookie for the given user and epoch.

Returns a binary cookie value signed with HMAC via Plug.Crypto.sign/4.

Parameters

  • secret_key_base - The host app's secret key base
  • user_id - The authenticated user's ID
  • trust_epoch - The user's current mfa_trust_epoch value
  • trust_ttl - Trust cookie TTL in seconds

verify(secret_key_base, cookie, current_user_id, current_trust_epoch, trust_ttl)

(since 0.6.0)
@spec verify(String.t(), binary(), term(), non_neg_integer(), pos_integer()) ::
  {:ok, term()} | {:error, :invalid}

Verifies a trust cookie against the current user and epoch.

Returns {:ok, user_id} if valid, {:error, :invalid} otherwise. Checks: HMAC signature, TTL, user_id match, and trust_epoch match.

Parameters

  • secret_key_base - The host app's secret key base
  • cookie - The trust cookie value to verify
  • current_user_id - The currently authenticated user's ID
  • current_trust_epoch - The user's current mfa_trust_epoch value
  • trust_ttl - Trust cookie TTL in seconds