Provider conformance kits
An application that adds its own payment gateway, mail transport or video
service implements the same trait as Rullst’s built-in adapters. Since
13.0.0-alpha.5 each of those crates ships a conformance kit: a test suite,
behind the Cargo feature conformance, that runs the contract the built-in
adapters follow against your implementation and returns a structured report.
Passing it shows, in your own test suite, that the adapter refuses forged
notifications, header injection or impossible grants the way the built-in ones
do. No network is needed: the kits run against the adapter’s offline mode
(empty or mock_* credentials) or a local fixture you control.
| Crate | Trait | Kit | Built-in adapters it passes |
|---|---|---|---|
rullst-capital | BillingProvider | conformance::check_billing_provider | Stripe (mock and signed-webhook modes), InfinitePay (offline fixtures and the local Checkout API fixture) |
rullst-mail | MailDriver | conformance::check_mail_driver | Resend, AWS SES, SendPulse, SMTP (offline mock) |
rullst-media | VideoProvider | conformance::check_video_provider | Bunny Stream (offline mode, complete and upload-only) |
Enable the feature in your development dependencies only, with the same exact version as the rest of your Rullst crates:
[dev-dependencies]
rullst-capital = { version = "=13.0.0-rc.1", features = ["conformance"] }
Reading a report
Every kit returns a ConformanceReport with one ConformanceCase per case, in
a fixed order. A case is Passed, Failed or Skipped (the harness did not
supply a fixture the case needs, or the capability does not apply), and its
detail() names every failed expectation, the reason for a skip, or what a
passed case could not exercise. passed() is true when no case failed;
assert_passed() fails a test with the whole report:
conformance of examplepay: 9 passed, 1 failed, 0 skipped
ok mode.declared
ok checkout.inputs_validated
ok checkout.server_side_amount
ok checkout.notification_url
ok offline.deterministic
ok notification.forged_refused
ok notification.replay_idempotent
ok confirmation.required
FAILED confirmation.amount_currency_bound: a source payment of a higher amount is never paid
ok errors.typed_no_panic
Each case runs under catch_unwind, so a panicking adapter fails that case
with panicked: <message> and the run continues. The kits themselves never
panic, except assert_passed. Case identifiers are stable within 13.x; a
later 13.x release may add cases, so read the report rather than counting
cases.
Billing providers
check_billing_provider(&provider, &harness) takes your BillingProvider and
a BillingHarness, which supplies what only the implementer knows:
one_off_request(): a server-sideOneOffCheckoutRequestthe provider accepts (its currency and minimum amount), orNonewhen it has no one-off checkout; the kit then expectsUnsupportedOperation.authentic_delivery(request): an authentic webhook delivery, signed for theRealandMockverification modes, or the unsigned body naming the request forConfirmedAtSource. The kit derives forgeries from it: the body without its headers, every header value zeroed and, inRealmode, the authentic headers on a tampered body. Amock_*signature is not bound to the body, so the tamper check does not apply inMockmode.set_source_payment(request, payment): makes the provider’s source of truth (its API, or the local fake standing in for it) report aSourcePayment. When the harness cannot simulate it, the kit notes the paths it could not exercise; offline fixtures that never report paid still pass.
| Case | What a conforming provider does |
|---|---|
mode.declared | webhook_verification_mode() returns a mode |
checkout.inputs_validated | plan checkout refuses blank e-mail addresses and plans |
checkout.server_side_amount | the one-off checkout is bound to the server-side request (request_digest) and names the provider |
checkout.notification_url | a request with a per-checkout notification_url (13.0.0-alpha.6) gets a checkout that reports it sent (OneOffCheckout::notification_url), or UnsupportedOperation; it is never ignored |
offline.deterministic | the same checkout input gives the same result |
notification.forged_refused | handle_webhook refuses invented, stripped, zeroed and tampered deliveries, and every body of a provider that confirms at the source |
notification.replay_idempotent | reading the same authentic delivery twice gives the same event or notification |
confirmation.required | nothing is paid until the source confirms it; a confirmed payment with the request’s amount and currency is paid, twice the same, and bound to the request |
confirmation.amount_currency_bound | a source payment of a lower or higher amount, another currency or another order reference is never paid |
errors.typed_no_panic | empty, non-UTF-8 and 3 MiB bodies and empty identifiers return a CapitalError |
Rejecting a replayed delivery is the webhook middleware’s job
(verify_webhook_with_state and its replay store), not the provider’s, so the
kit checks that a replay gives the same answer.
Worked example: an application-owned provider
ExamplePay is a fictitious gateway: it signs each webhook with an HMAC of the
body and reports payments through its API. The adapter keeps the protocol
rules (signature, request binding, amount comparison) and takes the API as a
generic ExamplePayApi, so production code passes an HTTP client and the
test passes a local fake. The code is included from
rullst-capital/tests/conformance_example.rs,
which CI runs:
/// ExamplePay's HTTP API as the adapter needs it. Production code implements
/// it with an HTTP client; tests use a local fake.
pub trait ExamplePayApi: Send + Sync {
/// Creates a payment link for the server-side request; returns its URL.
fn create_link(
&self,
request: &OneOffCheckoutRequest,
) -> impl Future<Output = Result<String, CapitalError>> + Send;
/// The charged amount and currency of the order's payment, `None` until
/// the buyer pays.
fn payment(
&self,
reference: &str,
) -> impl Future<Output = Result<Option<(u64, String)>, CapitalError>> + Send;
}
/// Adapter for the fictitious ExamplePay gateway. Webhooks carry
/// `examplepay-signature: <hex HMAC-SHA256 of the body>`.
pub struct ExamplePay<A> {
webhook_secret: String,
api: A,
}
impl<A: ExamplePayApi> ExamplePay<A> {
pub fn new(webhook_secret: impl Into<String>, api: A) -> Self {
Self {
webhook_secret: webhook_secret.into(),
api,
}
}
}
fn unsupported(what: &str) -> CapitalError {
CapitalError::UnsupportedOperation(format!("ExamplePay has no {what}"))
}
#[async_trait]
impl<A: ExamplePayApi> BillingProvider for ExamplePay<A> {
fn name(&self) -> &'static str {
"examplepay"
}
fn webhook_verification_mode(&self) -> Result<WebhookVerificationMode, CapitalError> {
if self.webhook_secret.trim().is_empty() {
return Err(CapitalError::ConfigurationError(
"ExamplePay webhook secret is empty".into(),
));
}
Ok(WebhookVerificationMode::Real)
}
async fn create_checkout_session(
&self,
customer_email: &str,
plan_id: &str,
_redirect_url: &str,
) -> Result<String, CapitalError> {
if customer_email.trim().is_empty() || plan_id.trim().is_empty() {
return Err(CapitalError::ConfigurationError(
"an e-mail address and a plan are required".into(),
));
}
Err(unsupported("plans; use create_one_off_checkout"))
}
async fn create_one_off_checkout(
&self,
request: &OneOffCheckoutRequest,
) -> Result<OneOffCheckout, CapitalError> {
// ExamplePay notifies one endpoint per account: refuse a per-checkout
// notification URL instead of ignoring it.
if request.notification_url().is_some() {
return Err(unsupported("per-checkout notification URL"));
}
let url = self.api.create_link(request).await?;
// Binds the returned URL to the server-side request and checks it.
OneOffCheckout::from_verified_provider_response(self.name(), request, url)?
.with_session_id(request.reference())
}
async fn confirm_one_off_payment(
&self,
request: &OneOffCheckoutRequest,
notification: &PaymentNotification,
) -> Result<OneOffPayment, CapitalError> {
if notification.reference() != request.reference() {
return Err(CapitalError::InvalidCharge(
"the notification names another order".into(),
));
}
match self.api.payment(request.reference()).await? {
// `paid` refuses an amount or currency other than the request's.
Some((amount, currency)) => {
OneOffPayment::paid(self.name(), request, amount, amount, ¤cy)
}
None => Ok(OneOffPayment::unpaid(self.name(), request)),
}
}
fn handle_webhook(
&self,
payload: &[u8],
headers: &HashMap<String, String>,
) -> Result<WebhookEvent, CapitalError> {
self.webhook_verification_mode()?;
let invalid = || CapitalError::InvalidSignature("ExamplePay signature".into());
let signature = headers.get("examplepay-signature").ok_or_else(invalid)?;
let tag = hex::decode(signature).map_err(|_| invalid())?;
let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(self.webhook_secret.as_bytes())
.map_err(|_| invalid())?;
mac.update(payload);
// Constant-time comparison of the whole body's MAC.
mac.verify_slice(&tag).map_err(|_| invalid())?;
let body: Value = serde_json::from_slice(payload)
.map_err(|_| CapitalError::PayloadParseError("ExamplePay event".into()))?;
let field = |name: &str| body[name].as_str().unwrap_or_default().to_owned();
Ok(WebhookEvent::new(
field("subscription_id"),
field("customer_id"),
field("customer_email"),
field("plan_id"),
SubscriptionStatus::parse_status(&field("status")),
))
}
async fn create_customer_portal(&self, _: &str, _: &str) -> Result<String, CapitalError> {
Err(unsupported("customer portal"))
}
async fn cancel_subscription(&self, _: &str) -> Result<(), CapitalError> {
Err(unsupported("subscriptions"))
}
async fn pause_subscription(&self, _: &str) -> Result<(), CapitalError> {
Err(unsupported("subscriptions"))
}
async fn report_usage(&self, _: &str, _: &str, _: u64) -> Result<(), CapitalError> {
Err(unsupported("metered usage"))
}
async fn apply_coupon(&self, _: &str, _: &str) -> Result<(), CapitalError> {
Err(unsupported("coupons"))
}
async fn extend_trial(&self, _: &str, _: i64) -> Result<(), CapitalError> {
Err(unsupported("trials"))
}
}
The harness shares the fake API’s payment with the provider, so the kit can make the “source” report a payment of any amount and check that only the request’s amount and currency count:
/// The local stand-in for ExamplePay's API: deterministic links and a
/// payment the test controls.
#[derive(Clone)]
struct LocalApi {
payment: Arc<Mutex<SourcePayment>>,
}
impl ExamplePayApi for LocalApi {
async fn create_link(&self, request: &OneOffCheckoutRequest) -> Result<String, CapitalError> {
Ok(format!(
"https://pay.example.invalid/checkout/{}",
request.reference()
))
}
async fn payment(&self, _: &str) -> Result<Option<(u64, String)>, CapitalError> {
let payment = self.payment.lock().unwrap();
Ok(payment
.is_paid()
.then(|| (payment.amount_minor(), payment.currency().to_owned())))
}
}
const SECRET: &str = "examplepay_webhook_secret";
struct Harness {
api: LocalApi,
}
impl BillingHarness for Harness {
fn one_off_request(&self) -> Option<OneOffCheckoutRequest> {
OneOffCheckoutRequest::new(
"order-42",
4_900,
"usd",
"Rust workshop seat",
"https://shop.example/paid",
"https://shop.example/cart",
)
.ok()
}
fn authentic_delivery(&self, _: Option<&OneOffCheckoutRequest>) -> Option<WebhookDelivery> {
let body = r#"{"subscription_id":"sub_1","customer_id":"cus_1","plan_id":"plan_1","status":"active"}"#;
let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(SECRET.as_bytes()).ok()?;
mac.update(body.as_bytes());
let signature = hex::encode(mac.finalize().into_bytes());
Some(WebhookDelivery::new(body).with_header("examplepay-signature", signature))
}
fn set_source_payment(&self, _: &OneOffCheckoutRequest, payment: &SourcePayment) -> bool {
*self.api.payment.lock().unwrap() = payment.clone();
true
}
}
#[tokio::test]
async fn examplepay_passes_the_billing_conformance_kit() {
let api = LocalApi {
payment: Arc::new(Mutex::new(SourcePayment::unpaid())),
};
let provider = ExamplePay::new(SECRET, api.clone());
let report = check_billing_provider(&provider, &Harness { api }).await;
println!("{report}");
report.assert_passed();
}
Run it with cargo test -p rullst-capital --features conformance --test conformance_example. Points the kit enforced while the adapter was written:
OneOffCheckout::from_verified_provider_responsebinds the gateway’s URL to the server-side request; building it from another request failscheckout.server_side_amount.OneOffPayment::paidrefuses a charged amount or currency other than the request’s, so the adapter passes the provider’s figures to it instead of comparing them itself.hmac::verifychecks the exact body bytes; trimming or re-serializing the body before verifying failsnotification.forged_refused.- Operations the gateway does not offer return
UnsupportedOperation, which satisfieserrors.typed_no_panic; fabricating success would not. - ExamplePay notifies one endpoint per account, so it refuses a request with a
notification_urlwithUnsupportedOperation. Ignoring the URL failscheckout.notification_url; an adapter that sends it callsOneOffCheckout::with_notification_url_sent.
For a gateway whose webhooks are unsigned, declare
WebhookVerificationMode::ConfirmedAtSource, implement
parse_payment_notification, return the unsigned body from
authentic_delivery, and confirm with the gateway’s API; the InfinitePay
fixture test in rullst-capital/src/conformance/tests.rs shows the harness.
Writing your own payment provider covers the rest
of the adapter and the webhook middleware.
Mail transports
check_mail_driver(name, &driver, &capture) sends messages through your
MailDriver configured for its offline mode. The DeliveryCapture returns
what that mode captured instead of sending; the kit tells its own messages
apart by subject, so a capture shared with other tests works. The built-in
drivers record into the shared OfflineMailMock, read with
OfflineMockCapture::new("resend") (or aws_ses, sendpulse, smtp).
| Case | What a conforming driver does |
|---|---|
delivery.accepted | a valid message is delivered once through send, send_with_delivery_id and send_for_tenant, with its recipient |
headers.crlf_refused | CR or LF in the subject, recipient, sender or Reply-To is a ValidationError and nothing is delivered |
attachments.limits_enforced | 33 attachments, one over 20 MiB, two over 25 MiB together, a CR/LF or path filename are refused; one small attachment is delivered intact |
suppression.respected | behind a SuppressionGuard, a suppressed recipient gets SuppressedRecipient on every path and nothing is delivered; another recipient is delivered |
offline.deterministic | the same message sent twice is captured twice, identically |
errors.typed_no_panic | empty or invalid recipients, a subject over 2 KiB, a malformed delivery ID or tenant ID are a ValidationError and nothing is delivered |
A transport passes the refusal cases by running DeliveryPipeline::prepare (or
prepare_for_tenant) before anything else, as
Writing your own mail transport shows. For that
guide’s AcmeMailDriver, whose offline fixture keeps messages in
offline_outbox(), the capture is three lines:
struct Outbox(OfflineOutbox);
impl DeliveryCapture for Outbox {
fn captured(&self) -> Result<Vec<Message>, MailError> {
Ok(self.0.lock().map_err(|_| MailError::DriverError("outbox".into()))?.clone())
}
}
let driver = AcmeMailDriver::try_new("mock_acmemail")?;
let capture = Outbox(driver.offline_outbox());
check_mail_driver("acmemail", &driver, &capture).await.assert_passed();
Video providers
check_video_provider(name, &provider, expectations) creates, renames and
deletes videos, so run it against the offline mode or a disposable library.
VideoExpectations::new(now) expects upload grants, playback grants and
listing, checked against the trusted UTC second now;
without_upload(), without_playback() and without_listing() declare a
capability absent, which the provider must then refuse with
MediaError::Unsupported. Bunny’s upload-only credentials pass with
without_playback().
| Case | What a conforming provider does |
|---|---|
binding.stable | binding() returns the same binding every time |
create.marker_validated | create and find_created refuse a malformed marker with InvalidInput |
lifecycle.create_get_update_delete | a created video awaits its upload, is found by marker and ID, renamed, deleted, and deleting it again succeeds; updating it then is NotFound |
upload.grant | the grant names the video, library and mode, expires after its TTL, is signed, uses HTTPS and refuses a zero or 136-year TTL and clocks at or before 1970; a declared upload binds its type and length or is Unsupported |
playback.grant | each kind is granted (expiring after its TTL, over HTTPS, refusing a zero TTL) or Unsupported; at least one kind is granted, or none without playback |
list.bounded | a page echoes its number and size, holds at most per_page videos and a total at least that many |
offline.deterministic | in ProviderMode::Offline, the same grant and listing requests give the same answers (skipped in other modes) |
errors.typed_no_panic | an unknown video reads as None, deletes successfully and updates as NotFound; impossible clocks are refused |
Worked example: an application-owned video provider
An adapter creates its own grants with UploadGrant::new and
PlaybackGrant::new (since 13.0.0-alpha.5). Both take the adapter’s
ProviderBinding, whose library and mode the grant records, and validate
their input: the endpoint or URL is an absolute https:// URL of at most
2 KiB without credentials, fragment, spaces or control characters (plain
http:// only in ProviderMode::ProtocolFixture), the upload signature is
1 to 4096 visible ASCII characters, and the expiry is a UTC second between
1970 and 9999; anything else is MediaError::InvalidInput.
UploadGrant::with_declaration adds the content type and length a declared
upload binds. Both keep the URL or signature out of Debug. For list,
ListedVideo::new (a 1 to 1024-byte title and a duration of at most a week,
with optional with_created_at and an HTTPS with_thumbnail_url) and
VideoPage::new(&query, items, total) build the page; the page echoes the
query’s number and size and refuses more than per_page items or a total
lower than their number.
ExampleVideo is a fictitious service that signs its own upload and HLS
URLs and lists its library. The code is included from
rullst-media/tests/conformance_example.rs,
which CI runs:
/// Longest upload grant, in seconds.
const MAX_UPLOAD_TTL: u32 = 3_600;
/// Longest playback grant, in seconds.
const MAX_PLAYBACK_TTL: u32 = 900;
/// Adapter for the fictitious ExampleVideo service, here with its offline
/// library kept in memory. ExampleVideo signs its own upload and HLS URLs and
/// lists its library.
pub struct ExampleVideo {
binding: ProviderBinding,
videos: Mutex<BTreeMap<VideoId, RemoteVideo>>,
}
impl ExampleVideo {
pub fn offline(library: LibraryId) -> Result<Self, MediaError> {
Ok(Self {
binding: ProviderBinding::new(
library,
ProviderMode::Offline,
Reference::new("example-video")?,
),
videos: Mutex::new(BTreeMap::new()),
})
}
/// ExampleVideo's identifier for a creation marker (`rullst-video-` and
/// 32 lower-case hex digits): the digits as a GUID.
fn id_for(marker: &str) -> Result<VideoId, MediaError> {
let hex = marker
.strip_prefix("rullst-video-")
.filter(|hex| hex.len() == 32)
.filter(|hex| {
hex.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
})
.ok_or(MediaError::InvalidInput)?;
let (a, b, c, d, e) = (
&hex[..8],
&hex[8..12],
&hex[12..16],
&hex[16..20],
&hex[20..],
);
VideoId::new(format!("{a}-{b}-{c}-{d}-{e}"))
}
fn expiry(now: i64, ttl: u32, max_ttl: u32) -> Result<i64, MediaError> {
if ttl == 0 || ttl > max_ttl {
return Err(MediaError::InvalidInput);
}
if now <= 0 {
return Err(MediaError::Clock);
}
now.checked_add(i64::from(ttl)).ok_or(MediaError::Clock)
}
/// Stands in for ExampleVideo's signature: a real adapter computes it
/// with the service's key (an HMAC over the purpose, video and expiry).
fn token(purpose: &str, video: &VideoId, expires_at: i64) -> String {
format!("{purpose}.{}.{expires_at}", video.as_str())
}
fn videos(
&self,
) -> Result<std::sync::MutexGuard<'_, BTreeMap<VideoId, RemoteVideo>>, MediaError> {
self.videos.lock().map_err(|_| MediaError::Storage)
}
}
impl VideoProvider for ExampleVideo {
fn binding(&self) -> ProviderBinding {
self.binding.clone()
}
async fn create(&self, marker: &str) -> Result<RemoteVideo, MediaError> {
let video = RemoteVideo::new(
Self::id_for(marker)?,
self.binding.library,
marker.to_owned(),
String::new(),
Processing::AwaitingUpload,
0,
false,
);
self.videos()?.insert(video.id.clone(), video.clone());
Ok(video)
}
async fn find_created(&self, marker: &str) -> Result<Option<RemoteVideo>, MediaError> {
Self::id_for(marker)?;
Ok(self
.videos()?
.values()
.find(|video| video.title == marker)
.cloned())
}
async fn get(&self, video: &VideoId) -> Result<Option<RemoteVideo>, MediaError> {
Ok(self.videos()?.get(video).cloned())
}
async fn update(&self, video: &VideoId, metadata: &Metadata) -> Result<(), MediaError> {
let mut videos = self.videos()?;
let stored = videos.get_mut(video).ok_or(MediaError::NotFound)?;
stored.title = metadata.title().to_owned();
stored.description = metadata.description().to_owned();
Ok(())
}
async fn delete(&self, video: &VideoId) -> Result<(), MediaError> {
self.videos()?.remove(video);
Ok(())
}
fn upload(&self, video: &VideoId, now: i64, ttl: u32) -> Result<UploadGrant, MediaError> {
let expires_at = Self::expiry(now, ttl, MAX_UPLOAD_TTL)?;
UploadGrant::new(
&self.binding,
video.clone(),
UploadProtocol::Tus,
"https://upload.example-video.invalid/tus",
Self::token("upload", video, expires_at),
expires_at,
)
}
fn playback(
&self,
video: &VideoId,
now: i64,
ttl: u32,
kind: PlaybackKind,
) -> Result<PlaybackGrant, MediaError> {
// ExampleVideo serves HLS only.
if kind != PlaybackKind::Hls {
return Err(MediaError::Unsupported);
}
let expires_at = Self::expiry(now, ttl, MAX_PLAYBACK_TTL)?;
let token = Self::token("play", video, expires_at);
let url = format!(
"https://cdn.example-video.invalid/{}/playlist.m3u8?expires={expires_at}&token={token}",
video.as_str()
);
PlaybackGrant::new(&self.binding, url, expires_at)
}
async fn list(&self, query: &ListQuery) -> Result<VideoPage, MediaError> {
let term = query.search().map(str::to_lowercase);
let mut matches = Vec::new();
for video in self.videos()?.values() {
if term
.as_ref()
.is_none_or(|term| video.title.to_lowercase().contains(term))
{
let listed = ListedVideo::new(
video.id.clone(),
&video.title,
video.length_seconds,
video.processing,
)?;
matches.push(listed);
}
}
// ExampleVideo keeps no upload dates, so both orders list by title.
matches.sort_by(|a, b| a.title.cmp(&b.title));
let total = matches.len() as u64;
let skip = (query.page() as usize - 1) * query.per_page() as usize;
let items = matches
.into_iter()
.skip(skip)
.take(query.per_page() as usize)
.collect();
VideoPage::new(query, items, total)
}
}
ExampleVideo grants only HLS playback, so every other kind returns
Unsupported, which the playback.grant case accepts. The test expects every
capability:
#[tokio::test]
async fn example_video_passes_the_video_conformance_kit() {
let provider = ExampleVideo::offline(LibraryId::new(7).unwrap()).unwrap();
// Upload grants, HLS playback and listing, checked at this UTC second.
let expect = VideoExpectations::new(1_793_534_400);
let report = check_video_provider("example-video", &provider, expect).await;
println!("{report}");
report.assert_passed();
}
A wrapper that adds instrumentation or policy around BunnyStream or the S3
adapter passes the kit the same way. It must forward list and
upload_declared explicitly: their default implementations return
Unsupported, which list.bounded reports.