Repository navigation
Releases
v0.7.0
AshBilling v0.7.0
Highlights
- Subscription Quantity & Item Synchronization: Added protected nullable
quantity(:integer,min: 0) andprovider_subscription_item_id(:string) attributes toAshBilling.Subscription.WebhookSyncandAshBilling.reconcile_subscription/2extract, persist, compare, and CAS-guard both attributes for single-item subscriptions with fail-closed validation (nilpreserved when absent/null,0preserved as zero seats, negative/malformed values fail closed with{:error, :invalid_quantity}). - Diagnostics Engine & Doctor CLI (
AshBilling.Diagnostics,mix ash_billing.doctor): ExtendedAshBilling.check_configuration/1(backwards-compatible) with layered structural, read-only PostgreSQL schema/migration/index checks (0.6.0&0.7.0),WebhookEventprivacy verification, multitenancy/Repo checks, HTTP timeout guidance, optional read-only Stripe probes, and explicitconfiguration_validvsproduction_readyreporting in text and--json. - Reconciliation CLI (
AshBilling.Reconciler,mix ash_billing.reconcile): Read-only--dry-rundefault, mandatory--execute --confirmfor writes, fail-closed selection filter validation, stable keyset streaming batch pagination, bounded concurrency, global cross-worker rate limiting, and strict Ash actor/policy, multitenant, and database-level Stripe Connect isolation. - Low-Cardinality Telemetry & Dashboard Guide: Instrumented
[:ash_billing, :reconcile, ...],[:ash_billing, :reverify, ...],[:ash_billing, :deduplication, :acquire | :complete | :release],[:ash_billing, :postgres, :contention], and[:ash_billing, :reconciler, :batch]with low-cardinality metadata and drift detection, plus aTelemetry.Metricsdashboard guide. - Runnable SaaS Reference Application (
examples/saas_example): Full runnable Phoenix + Ash + AshPostgres SaaS app with Docker Compose (PostgreSQL 16), migrations, guarded demo seeds, PBKDF2 auth + actor freshness, Stripe Checkout/Portal/plan swap/quantity update/cancel/resume/reconciliation, transactionalFOR UPDATEseat enforcement,Subscribed&HasPricepolicies, HMAC-verified webhooks with PostgreSQL deduplication,mix ash_billing.doctor/mix ash_billing.reconcile, and CI test coverage.
Upgrading from 0.6.0
Requires adding nullable quantity and provider_subscription_item_id columns to your subscription table. See Upgrading to 0.7 and Diagnostics, Recovery CLI & Observability.
v0.6.0
Added & Changed
- Durable Reconciliation Checkpoints (
last_reconciled_at): Added nullable protected attributelast_reconciled_at(:utc_datetime_usec) toAshBilling.Subscription. See Upgrading to 0.6 for the required database migration. - PostgreSQL Shared-Clock Checkpointing:
AshBilling.reconcile_subscription/2queries PostgreSQLclock_timestamp()under canonicalCustomer -> SubscriptionFOR UPDATElocks, omits fabricated local timestamps ("created" => nil), and persistslast_reconciled_atmonotonically and atomically in the same transaction as reconciled state. - Post-Reconciliation Financial Verification: When
last_reconciled_atis present,AshBilling.WebhookSyncevaluates critical synchronized financial attributes (status,price_id,current_period_end,trial_ends_at,cancel_at_period_end,cancel_at) before applying non-terminal or delayed terminal webhooks. Safe fast paths (duplicates,event.created < last_event_created_at, or identical snapshots with no financial diff) skip provider calls, while any financial difference triggers live provider re-verification underFOR UPDATEregardless ofevent.createdage, failing closed on provider or PostgreSQL errors with no ETS state. - 0.5.x Upgrade Cursor Healing & Operational Guidance:
AshBilling.reconcile_subscription/2now automatically clears ahead/futurelast_event_created_atvalues (> PostgreSQL clock_timestamp()) tonilatomically alongside persistinglast_reconciled_at(and supportsreset_event_cursor?: truefor shared app+DB forward clock skew), preventing synthetic0.5.xreconciliation timestamps from causingexisting_event_newer?/2to ignore legitimate Stripe webhooks. Documented explicitquantitypersistence scope and HTTP timeout /FOR UPDATElock hold / PostgreSQL pool sizing recommendations in Upgrading to 0.6.
v0.5.3
What's Changed
- Reconciliation Concurrency & Lock Error Propagation:
AshBilling.reconcile_subscription/2enters the transaction lock boundary and acquires canonicalCustomer -> SubscriptionFOR UPDATErow locks before callingAshBilling.get_subscription/2, propagating lookup and lock-acquisition errors cleanly without invoking the provider while preservingv0.5.2synthetic timestamp semantics and zero breaking API or schema changes. - Billing Invariants Documentation: Added
Billing invariantssection todocumentation/topics/webhooks-and-resilience.md. - Canary CI: Added PostgreSQL 16 service and failure classification (
INFRASTRUCTURE_FAILUREvsCOMPATIBILITY_FAILURE) to.github/workflows/canary.yml.
Full Changelog: v0.5.2...v0.5.3
AshBilling 0.5.2
Security & Reliability Hardening
- Subscription Quantity Updates (AB-01, AB-02): Added optional
update_quantity/3callback toAshBilling.Providerbehaviour and implemented it inAshBilling.Providers.Stripe. Quantity updates now POST onlyitems[0][id]anditems[0][quantity], omittingitems[0][price]. This prevents unintended plan switches, avoids race conditions where a concurrent plan change would be clobbered by a quantity update, and avoids unnecessary GET requests whensubscription_item_idis supplied withoutprice_id. An optional:price_idcan be passed as an optimistic assertion against the active plan, returning{:error, {:price_mismatch, actual}}if stale. Emits[:ash_billing, :update_quantity]telemetry span. - Subscription Reconciliation API (AB-09): Added
AshBilling.reconcile_subscription/2to safely fetch live provider state and synchronize updates directly into PostgreSQL inside advisory locks and transaction boundaries. Inactive and canceled subscriptions are updated to prevent stale entitlements when webhooks are lost. - URL Path Sanitization & Traversal Prevention (AB-03): Added percent-encoding via
URI.encode(..., &URI.char_unreserved?/1)for all dynamicsubscription_idpath segments inAshBilling.Providers.Stripe(get_subscription,cancel_subscription,resume_subscription,swap_plan,update_quantity). Validates subscription IDs early and returns{:error, :invalid_subscription_id}on blank, whitespace-only, or non-binary input without making remote requests. - Webhook Error Normalization (AB-04): Normalized verification error handling in
AshBilling.Plug. Signed non-JSON payloads now return a clean 400 response with{"error": "invalid_payload"}instead of raisingProtocol.UndefinedErroronJason.DecodeError. - Pre-Authentication Information Disclosure Prevention (AB-05): Redacted internal repository module names from the 503 response body when the pre-authentication transaction boundary fails in
AshBilling.Plug. Details are logged viaLogger.error/1while external callers receive a sanitized{"error": "transaction_boundary", "message": "Service temporarily unavailable"}. - Public API Contract Robustness (AB-06): Added fallback clause to
AshBilling.create_customer/2returning{:error, :invalid_customer}for non-map / non-struct inputs (nil,"", numbers, lists), replacingFunctionClauseError. - Documentation & Telemetry Consistency (AB-07): Documented
[:ash_billing, :swap_plan]and[:ash_billing, :update_quantity]telemetry spans inREADME.md. UpdatedSECURITY.mdsupported versions to explicitly list0.5.x.
AshBilling 0.5.1
Security
- Resolved Hex advisory on retired
ash_sql 0.8.4(Ecto query cache issue) by upgradingash_sqlto0.8.7(andnimble_optionsto1.2.0). Verified withmix hex.audit(0 advisories).
Added
AshBilling.Checks.HasPrice: added support for specifying multiple allowed price IDs as a list (e.g.price: ["price_monthly", "price_annual"]). Authorizes when the active subscription'sprice_idmatches any element in the list. Enforces fail-closed semantics on empty lists, blank strings, or invalid non-binary elements.
Fixed
- Public error contracts in
AshBilling:AshBilling.create_portal_session/2: Returns{:error, :missing_return_url}when:return_urlis missing, blank, or non-binary, avoidingKeyError.AshBilling.get_subscription/2,cancel_subscription/2,resume_subscription/2: Return{:error, :invalid_subscription_id}when givennil,"", or unsupported structures, preventingFunctionClauseErrorand unneeded Stripe API requests.
AshBilling 0.5.0
AshBilling 0.5.0 hardens Stripe subscription mutations, Customer identity and PostgreSQL webhook consistency.
Changes
- Preserve seat quantities when changing plans; reject ambiguous or incomplete item selection.
- Require an established Customer before recurring Checkout and protect resource ownership references.
- Validate required persistence and retain the remote Customer ID when a later local write fails.
- Reject unsupported nonterminal multi-item subscriptions instead of storing a partial entitlement model.
- Roll back supported shared-Repo PostgreSQL processing on sync/handler failures and keep leases retryable.
Upgrading
This release changes public contracts from 0.4.x. Recurring Checkout requires a Customer, handlers must return explicit success/error tuples, and raw lease errors propagate directly. No new schema migration is introduced.
Read the 0.5 upgrade guide. Unsupported snapshots retain the last supported entitlements pending application remediation. External effects still require consumer idempotency or an outbox.
{:ash_billing, "~> 0.5.0"}Validation
389 library tests pass with 91.98% coverage, plus 13 offline convergence tests and seven launcher safety tests. The release tree passes the three supported CI combinations. Real Stripe Test Mode checks cover paid Checkout, quantity preservation, lifecycle operations and signed webhooks, including official HTTPS resends. Fault injection and arranged event reordering are separately classified local simulations.
v0.4.1
AshBilling v0.4.1
Fixed
AshBilling.Checks.HasPricenow fails closed when:priceis missing,nil, empty, or whitespace-only.- Invalid or missing
:priceoptions are rejected at compile time during Ash policy definition viainit/1with a descriptiveSpark.Error.DslError. - Added dynamic policy compilation regression tests and comprehensive authorization policy tests.
Documentation
- Clarified that
AshBilling.WebhookEventis an internal deduplication resource and its actions must not be exposed to untrusted clients via public APIs (AshJsonApi,AshGraphql, etc.). - Documented explicit
AshPostgres.DataLayersetup and shared Repo pool requirements for distributed webhook deduplication. - Clarified that distributed cross-node concurrency guarantees (
pg_try_advisory_xact_lockandFOR UPDATE NOWAIT) apply to PostgreSQL. Non-Postgres data layers rely on local node locks. - Updated installation, upgrade, and security documentation for the published 0.4.x series.
Upgrade Notes
- Applications using
HasPricewithout a valid:pricemust supply an explicit price or switch toAshBilling.Checks.Subscribedfor general active subscription checks. - No database migrations are required when upgrading from v0.4.0.
v0.4.0 - Enterprise Security, Webhook Deduplication & Multi-Tenant Isolation
Highlights in v0.4.0 (2026-10-30)
Security & Hardening
- Strict Attribute Protection: Explicit protection against mass assignment on billing attributes (
stripe_customer_id,stripe_subscription_id,stripe_price_id,billing_deleted_at). Wildcard accepts likeaccept: :*no longer expose billing identifiers to untrusted callers. - Stripe Serialization (
Ash.CiString): Fixed form parameter serializer to properly convert case-insensitive string values (Ash.CiString) to binary strings instead of failing or treating them as map structures. - Connect Scope & Account Validation: Enforces exact match of account ID and Stripe mode (live vs. test) across all provider operations.
Resilience & Concurrency
- PostgreSQL Webhook Deduplication: Atomic lease acquisition with TTL and commit lifecycle. Concurrent duplicate deliveries safely converge: the winning process executes inside a shared transaction while parallel arrivals receive HTTP 503 for controlled Stripe retries.
- Transaction Rollback Protection: Unpersisted or failed local database operations release webhook leases cleanly, preventing ghost subscriptions and ensuring Stripe delivers retries.
- Out-of-Order Delivery Protection: Webhooks arriving out-of-order for terminated or transitioned subscriptions are safely ignored.
Developer Experience & Upgrading
- Added comprehensive upgrade guide:
documentation/topics/upgrading-to-0.4.md. - Updated DSL references and regenerated documentation.
- CI pipeline enriched with dependency auditing, strict documentation checks (
--warnings-as-errors), and packaging validation (mix hex.build).
Upgrade Guide: Please consult Upgrading to 0.4.0 for breaking changes and schema migrations.
v0.3.1 - Support Ash.CiString and Custom Structs in Stripe Payloads
Highlights in v0.3.1
Fixed
- Support
Ash.CiStringand Custom Structs in Stripe Payloads:- Automatically coerces
Ash.CiStringvalues (commonly used byAshAuthenticationfor:emailfields) to binary strings inAshBilling.Providers.Stripe.to_form_params/2. - Safely serializes structs implementing
String.Charsor unwraps them to maps, preventingProtocol.UndefinedErrorwhen invokingAshBilling.create_customer/2orAshBilling.create_checkout_session/2.
- Automatically coerces
For full details, see CHANGELOG.md.
v0.3.0 - Tenant-Scoped Uniqueness, Atomic Terminal Guards, and Integrity Hardening
Highlights in v0.3.0
Database Uniqueness & Concurrency Protection
- Tenant-Scoped Unique Index: Uniqueness constraint on
provider_subscription_idscoped by resource and tenant (tenant_id), backed by a PostgreSQL unique index. - Atomic Terminal State Guards: Prevents obsolete webhook events from modifying or resurrecting terminal subscriptions (
:canceled,:incomplete_expired).
Security & Developer Experience
- Customer Identity Association: Enforced atomic customer identity checks. Contradictory customer mappings produce safe retryable errors.
- Credential Redaction: Automatic redaction of API keys and webhook secrets from diagnostics and exceptions.
- Igniter Installer Improvements: Automated domain/resource registration and endpoint raw-body preservation.
- Plug Raw Body Preservation:
AshBilling.Plug.read_body/2captures raw webhook payload bytes for signature verification.
For full migration instructions and diagnostic SQL, refer to CHANGELOG.md.