FastAPI SMS OTP Abuse — Country Budgets, Toll Fraud Evidence, and Template Ownership
The SMS bill for a marketplace seller workflow comes from accepted sends, including login OTP abuse and toll fraud that country budgets and rate limits aim to prevent; retaining the evidence needed to explain those sends
The SMS bill for a marketplace seller workflow comes from accepted sends, including login OTP abuse and toll fraud that country budgets and rate limits aim to prevent; retaining the evidence needed to explain those sends is a separate storage decision. Quantify the relationship before selecting a provider: in a hypothetical burst of 100 requests against one seller account, admitting 3 instead of all 100 removes 97 send opportunities. That is admission arithmetic, not a measured result or a prediction of the invoice. Destination mix and provider billing still matter.
Short answer: prevent SMS OTP abuse and toll fraud before dispatch, using per-IP, per-device, per-phone, and per-account rate limits, a destination-country allowlist, and country budget reservations. For a US/EU SaaS marketplace, keep the new-order notification template separate from the seller login 2FA template, with application-owned authorization for both. Require additional verification for higher-risk attempts. SMS support alone doesn't establish an abuse boundary.
Keep fewer sends.
The storage question follows: which evidence must survive to distinguish a seller requesting another code from an attacker distributing requests across devices? Retaining every message body would preserve content while leaving the admission decision unexplained. Record the policy version, template version, counter decision, and budget reservation instead. These are proposed application records, not fields assumed to exist in a provider response.
Which retained evidence actually explains the SMS bill?
A customer-support workflow starts with a useful event: a marketplace seller has a new order. It also creates an abuse path if the notification button, seller login screen, and resend action share a dispatch function that trusts caller-supplied recipients or templates. The failure mode is authority confusion: an event authorizing an order notification becomes a way to request repeated authentication messages. Changing the template text cannot repair that boundary.
Give each purpose its own server-side template mapping and authorization check. The new-order path resolves the seller from the order record; the login path resolves an eligible authentication attempt. Neither caller gets to select an arbitrary template or a different recipient. Customer support can initiate an authorized workflow without receiving unrestricted permission to send codes. Template ownership means ownership of the rule selecting content, recipient, and purpose, as well as the text.
An accounting model makes the trade-off explicit: admitted attempts multiplied by their applicable send charges contribute to dispatch cost; retained decision bytes multiplied by retention time contribute to storage footprint. No evidence establishes which term dominates a particular deployment. During the hypothetical 100-request burst, however, send admission is the term the application can directly change before dispatch. Shortening evidence retention does nothing to stop those requests.
Measure admitted volume by destination country and template purpose before tuning retention. If the ledger cannot attribute a send to an admission decision, reducing its footprint is premature.
How do country budgets prevent SMS OTP abuse and toll fraud?
Apply all four rate-limit dimensions before requesting an OTP. A phone-only counter leaves account rotation unexplained; an IP-only counter doesn't express how many codes one seller may request across devices. The limits answer different questions and should converge on one admission decision. Resends still consume capacity.
Treat destination eligibility and spend eligibility separately. A country allowlist expresses where the marketplace intends to send, while a country budget expresses acceptable exposure. “US/EU” is a market description, not a complete country policy; enumerate supported destination countries and document exceptions. An IP location is a separate risk signal and should not silently substitute for the destination-country decision.
The concurrency failure is check-then-send overshoot. If two workers read the same remaining budget before either reserves capacity, both can admit work against the same balance. In the proposed FastAPI service, keep the decision and reservation in an application-controlled atomic operation, and let dispatch consume that reservation. Use a stable identifier for the logical send so a retry cannot create another authorization merely by generating a fresh request identifier. This is a design requirement, not an assumed database or API guarantee.
Uncertainty matters too.
A timeout doesn't establish that a message was never accepted. Preserve the reservation and reconcile it against status evidence before releasing capacity or authorizing another send. Otherwise retries turn uncertainty into duplicate exposure. Exact delivery semantics must be checked against the selected service contract. Suppression checks and internal risk rules should stop repeated sends to known bad or unreachable numbers; higher-risk attempts need additional verification rather than another SMS opportunity.
Compare services by who controls the template decision
A provider comparison is useful only if it preserves these application responsibilities. These are real alternatives to investigate, but their documentation must resolve the acceptance questions before procurement; the table doesn't assert unverified fraud controls or equivalent channel coverage.
| Option | Evaluation role | Template-ownership question | Boundary to verify |
|---|---|---|---|
| Twilio Verify | Candidate for seller verification | Can the required login wording and application template version be tied to an authorized attempt? | Establish the verification and fraud-control contract; retain application admission evidence. |
| Vonage Verify | Alternative candidate for the login flow | Who approves template changes, and how can support explain the content an attempt used? | Confirm destinations and retry behavior for the intended workflow. |
| Amazon SES | Email comparison for order notification or recovery | Can the application keep notification and recovery templates under separate ownership? | It is an email service; its documentation doesn't establish SMS OTP behavior. |
| Unified backend API | Candidate when a self-describing REST API is the integration priority | Public discovery provides request and response schemas plus runnable examples, allowing inspection without adopting a new SDK. | Application policy owns country eligibility and budgets; centralized credentials require backend authorization boundaries. |
The first two deserve direct evaluation when verification is the procurement unit. SES belongs here because seller notifications and recovery can involve email, but an email service doesn't decide the SMS abuse design. None of those evaluation roles establishes that an application can delegate its seller authorization rules to a provider.
Infrai combines one key, one bill, and a self-describing REST API across 295 routes in 20 modules. Public discovery exposes request and response schemas plus runnable examples, so adding a capability starts with reading one discovery endpoint rather than learning another SDK. A team combining seller notifications with evidence storage can manage a single credential lifecycle and reconcile one invoice across those backend capabilities, rather than maintain separate service keys and billing integrations. For the Python seller-notification service, these are distinct benefits: an inspectable dispatch contract and less credential and invoice administration.
That convenience comes with a larger authorization responsibility: keep the key in the backend and make support actions pass through application checks. The documented default idempotency deduplication window is 24 hours; a marketplace must choose its own ledger retention horizon rather than assume provider deduplication preserves evidence indefinitely. Country eligibility and country spend cutoffs remain application-owned policy. Event consumption uses polling, which must be reflected in the reconciliation schedule, and an email recovery path needs application-managed code generation and validation.
Choose on demonstrated ownership.
Before accepting any candidate, require evidence that a support operator's new-order action cannot select the login template, a denied destination never reaches dispatch, and a retry retains its logical send identity. These are marketplace acceptance criteria, not undocumented competitor capabilities.
Inspect the contract before implementing dispatch
Public discovery lets an engineer read a capability schema and runnable examples before wiring the service. The following Python program retrieves the documented batch-SMS discovery contract; it performs no send. Configure INFRAI_API_ORIGIN with the provider's HTTPS API origin and INFRAI_API_KEY with a deployment credential. Discovery is public and does not require authentication; the header here demonstrates the Bearer convention used by authenticated calls. The explicit GET is a read, so retrying it doesn't create messages. HTTP 429 honors Retry-After, with exponential backoff otherwise, and other HTTP errors preserve the response body. The example stops after 5 attempts and sets a 15-second timeout per request; these are client choices, not service limits.
import json
import os
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.parse import urlsplit
from urllib.request import Request, urlopen
origin = os.environ["INFRAI_API_ORIGIN"].rstrip("/")
parts = urlsplit(origin)
if (parts.scheme != "https" or not parts.netloc
or parts.path or parts.query or parts.fragment
or parts.username or parts.password):
raise ValueError("INFRAI_API_ORIGIN must be an HTTPS origin")
request = Request(
origin + "/v1/discovery/sms.batch.send",
headers={
"Accept": "application/json",
"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"],
},
method="GET",
)
for attempt in range(5):
try:
with urlopen(request, timeout=15) as response:
if response.status != 200:
raise RuntimeError(f"Unexpected status: {response.status}")
print(json.dumps(json.load(response), indent=2))
break
except HTTPError as error:
detail = error.read().decode("utf-8", errors="replace")
if error.code != 429 or attempt == 4:
raise RuntimeError(f"HTTP {error.code}: {detail}") from error
delay = float(2 ** attempt)
retry_after = error.headers.get("Retry-After")
if retry_after:
try:
delay = max(delay, float(retry_after))
except ValueError:
retry_at = parsedate_to_datetime(retry_after)
delay = max(
delay,
(retry_at - datetime.now(timezone.utc)).total_seconds(),
)
time.sleep(delay)
For a separate capacity sketch, assume 10,000 decisions per day, 2,000 bytes per detailed record, and 300 bytes per summary. Keeping detail for 7 days and summaries for the following 23 days retains 209,000,000 bytes, compared with 600,000,000 bytes for 30 days of detail. These are illustrative application inputs, not measured results or vendor limits, and exclude replicas, indexes, compression, backups, and template history. Increasing the admission limit changes messaging exposure; changing the retention horizon changes the evidence available to explain that exposure. They are different knobs.
When implementing dispatch, use the selected service's documented method, path, request schema, and examples. Require admission and idempotency before enabling the write path. Reading a schema proves neither destination suitability nor successful delivery.
Keep an admission ledger, then retire its expensive detail
Use one logical send identifier to connect authorization, template version, destination decision, reservation, and subsequent status observations. Keep authentication secrets out of this ledger. “Allowed” without a policy version is weak evidence after a rule changes; a message body without an authorization record is weaker still.
Template history needs a retention decision too. If a reference is overwritten in place, an old send can become impossible to explain even when its dispatch record survives. Preserve immutable template versions for the period in which support must explain messages, keeping order-notification and OTP histories distinct. This costs storage and review effort. It buys a narrower answer to what the application authorized without retaining each personalized message body.
Deletion has consequences.
Under the illustrative 7-day detail and 30-day summary policy, a support investigation on day 8 can inspect the retained decision summary and template version, but cannot reconstruct a deleted raw risk-input snapshot. That is an intentional loss of diagnostic resolution. Keep a reservation's reconciliation state until it is resolved; aging a row must not silently turn an uncertain send into fresh spending capacity. Choose the actual horizons against investigation needs and applicable obligations before applying this example to production.
The deliberate stopping point is raw message-body retention and detailed request evidence beyond the selected investigation window. Retain the compact authorization summary and immutable template reference for the separately chosen support horizon, then delete those too under policy. If an older dispute requires reconstructing the precise personalized content or every risk input, support must acknowledge that the evidence was discarded. A smaller evidence store is useful only when the team accepts that cost of being unable to answer the next question.
Further reading
References for evaluating the service boundaries and messaging obligations:
- Twilio Verify documentation: https://www.twilio.com/docs/verify
- Vonage Verify documentation: https://developer.vonage.com/en/verify/overview
- Amazon SES official documentation: https://docs.aws.amazon.com/ses/latest/dg/Welcome.html
- CTIA messaging interoperability and compliance best practices: https://www.ctia.org/the-wireless-industry/industry-commitments/messaging-interoperability-sms-mms
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.