Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@ All notable changes to this project are documented here. The format follows

### Added

- Telnyx adapter (Messaging API v2) with Ed25519 webhook verification.
- Vonage adapter (SMS API) with signed webhook verification for `md5hash` and
HMAC methods.
- `Smswire::ProviderContract`, a shipped Minitest suite every adapter passes;
the provider generator now writes a test that runs it.
- `Noticed::DeliveryMethods::Smswire` for `deliver_by :smswire`, loaded when
Noticed is present.
- Webhook endpoints accept both status and inbound events, for providers that
post everything to one URL.

- Messenger previews at `<mount>/previews` with a phone frame, encoding,
segment count, remaining characters, and the characters that force UCS-2.
- Development inbox at `<mount>/inbox` listing deliveries and inbound
Expand Down
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ if (rails_version = ENV["RAILS_VERSION"])
end

gem "sqlite3", (ENV["RAILS_VERSION"] == "7.1") ? "~> 1.4" : ">= 2.1"
gem "noticed", "~> 3.1"
gem "rake", "~> 13.0"
gem "minitest", "~> 5.25"
gem "webmock", "~> 3.23"
Expand Down
28 changes: 24 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ templates for SMS, a provider-agnostic message object, a delivery pipeline
with typed outcomes, retries with a transient-versus-permanent error
taxonomy, and test helpers. Persisted deliveries with status callbacks,
consent and STOP / HELP / START handling, quiet hours, previews, and a
[Noticed](https://github.com/excid3/noticed) delivery adapter follow in later
phases of the [specification](docs/SPEC.md).
[Noticed](https://github.com/excid3/noticed) delivery method are included.
See the [specification](docs/SPEC.md) for the full design.

**Status:** pre-release. Phases 1 to 4 of the spec are implemented; the
**Status:** pre-release. Phases 1 to 5 of the spec are implemented; the
published `0.0.1.pre` gem only reserves the name.

## Requirements
Expand Down Expand Up @@ -167,14 +167,34 @@ Smswire.register_interceptor(
| Name | Use |
|---|---|
| `:twilio` | Twilio Programmable Messaging over REST, no SDK |
| `:telnyx` | Telnyx Messaging API v2; `api_key`, `public_key` for webhooks |
| `:vonage` | Vonage SMS API; `api_key`, `api_secret`, `signature_secret` |
| `:log` | Writes messages to the logger; development default |
| `:test` | Records messages in memory; test default |
| `:null` | Accepts and discards |

Generate your own with `bin/rails generate smswire:provider Acme`, or
Each adapter passes `Smswire::ProviderContract`, a test suite shipped in the
gem. Generate your own with `bin/rails generate smswire:provider Acme`, which
writes an adapter and a test that runs the contract against it, or
subclass `Smswire::Providers::Base` and call
`Smswire::Providers.register(:acme, "AcmeProvider")`.

### Noticed

```ruby
class OrderShippedNotifier < Noticed::Event
deliver_by :smswire do |config|
config.messenger = "OrderMessenger"
config.action = :shipped # called with the recipient by default
end
end
```

The messenger gets the event params plus `notification`, `record`, and
`recipient`, so consent, quiet hours, deduplication, retries, and status
tracking all apply. Each delivery stores the Noticed notification and event
ids in its metadata.

### Testing

```ruby
Expand Down
26 changes: 4 additions & 22 deletions app/controllers/smswire/inbound_messages_controller.rb
Original file line number Diff line number Diff line change
@@ -1,27 +1,9 @@
module Smswire
# Receives inbound messages at POST <mount>/inbound/:provider, records
# them once per provider message id, and handles compliance keywords.
# Apps can build two-way messaging with an observer that implements
# +sms_received(inbound_message)+.
class InboundMessagesController < ActionController::Base
skip_forgery_protection

# POST <mount>/inbound/:provider. Apps can build two-way messaging with
# an observer that implements +sms_received(inbound_message)+.
class InboundMessagesController < WebhooksController
def create
provider = Providers.resolve(params[:provider])
return head(:not_found) unless provider.capabilities.include?(:inbound)

if Smswire.config.verify_callback_signatures
provider.verify_signature!(request, url: Callbacks.request_url(request))
end

InboundHandler.call(provider.parse_inbound(request), provider: provider.name)

body, content_type = provider.inbound_response
body ? render(plain: body, content_type:) : head(:no_content)
rescue ConfigurationError
head :not_found
rescue SignatureError
head :forbidden
handle_inbound || handle_status || head(:no_content)
end
end
end
41 changes: 3 additions & 38 deletions app/controllers/smswire/status_callbacks_controller.rb
Original file line number Diff line number Diff line change
@@ -1,43 +1,8 @@
module Smswire
# Receives provider delivery status callbacks at
# POST <mount>/status/:provider. Always answers 2xx for well-formed,
# signed requests so providers do not retry, even when the delivery is
# unknown.
class StatusCallbacksController < ActionController::Base
skip_forgery_protection

# POST <mount>/status/:provider
class StatusCallbacksController < WebhooksController
def create
provider = Providers.resolve(params[:provider])
return head(:not_found) unless provider.capabilities.include?(:status_callbacks)

if Smswire.config.verify_callback_signatures
provider.verify_signature!(request, url: Callbacks.request_url(request))
end

update = provider.parse_status_callback(request)
payload = {provider: provider.name, provider_id: update.provider_id, status: update.status,
error_code: update.error_code}
ActiveSupport::Notifications.instrument("status_update.smswire", payload) do
delivery = Delivery.apply_status_update(update, provider: provider.name, delivery_id: params[:delivery_id])
payload[:delivery_id] = delivery&.id
payload[:delivery_status] = delivery&.status
notify_observers(delivery, update) if delivery
end

head :no_content
rescue ConfigurationError
head :not_found
rescue SignatureError
head :forbidden
end

private

def notify_observers(delivery, update)
Smswire.config.observers.each do |observer|
observer = observer.is_a?(String) ? observer.constantize : observer
observer.sms_status_updated(delivery, update) if observer.respond_to?(:sms_status_updated)
end
handle_status || handle_inbound || head(:no_content)
end
end
end
49 changes: 49 additions & 0 deletions app/controllers/smswire/webhooks_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
module Smswire
# Shared provider webhook handling. Each endpoint tries its own kind of
# event first and falls back to the other, so a provider that posts every
# event to one URL (Telnyx messaging profiles do) is handled either way.
# Signed, well-formed requests always get a 2xx so providers do not retry.
class WebhooksController < ActionController::Base
skip_forgery_protection

before_action :load_provider
before_action :verify_signature

private

def load_provider
@provider = Providers.resolve(params[:provider])
head(:not_found) unless (@provider.capabilities & %i[status_callbacks inbound]).any?
rescue ConfigurationError
head :not_found
end

def verify_signature
return unless Smswire.config.verify_callback_signatures

@provider.verify_signature!(request, url: Callbacks.request_url(request))
rescue SignatureError => error
Smswire.logger.warn("[Smswire] Rejected #{@provider.name} webhook: #{error.message}")
head :forbidden
end

def handle_status
return false unless @provider.capabilities.include?(:status_callbacks)

update = @provider.parse_status_callback(request) or return false
StatusHandler.call(update, provider: @provider.name, delivery_id: params[:delivery_id])
head :no_content
true
end

def handle_inbound
return false unless @provider.capabilities.include?(:inbound)

inbound = @provider.parse_inbound(request) or return false
InboundHandler.call(inbound, provider: @provider.name)
body, content_type = @provider.inbound_response
body ? render(plain: body, content_type:) : head(:no_content)
true
end
end
end
44 changes: 39 additions & 5 deletions docs/SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,33 @@ Later: `sinch`, `bandwidth`, `aws_sns`, `plivo`, `messagebird`.
All adapters use Net::HTTP (or a tiny shared client as in Noticed). No
provider SDKs are runtime dependencies. Bodies are never logged.

Adapter notes:

- **Twilio** signs webhooks with HMAC-SHA1 over the URL and sorted POST
parameters. Messaging services map to `MessagingServiceSid`.
- **Telnyx** signs webhooks with Ed25519 over `<timestamp>|<raw body>`,
verified against the account public key, with a five-minute timestamp
tolerance. Messaging services map to `messaging_profile_id`. A messaging
profile can post every event to one URL, so both webhook endpoints accept
both event kinds. Telnyx takes no validity period here, so it is ignored.
- **Vonage** (SMS API) signs webhooks with sorted `&key=value` pairs using the
configured `signature_secret` and `signature_method` (`md5hash`, Vonage's
default, or an HMAC). Its send error 7, "number barred," also covers blocks
other than opt-outs, so it maps to `:unroutable` and never records an
opt-out. Long messages are billed as several parts with separate ids; the
receipt keeps the first, so receipts for later parts are acknowledged but
not matched. The API does not name a price currency.

**Contract suite.** `Smswire::ProviderContract` is a Minitest module shipped
in the gem. An adapter's test includes it and defines hooks that stub the
provider for each outcome (`success`, `invalid_number`, `opted_out`,
`authentication`, `throttled`, `server_error`, `timeout`) and build signed
status and inbound requests. The suite checks receipts, the normalized status
vocabulary, the error taxonomy and reasons, a full pipeline send, and, for
declared capabilities, callback parsing and signature rejection. An adapter
whose provider cannot report opt-outs at send time says so with
`contract_reports_opt_outs?` rather than guessing.

### 6.5 Persistence

Three tables, installed by `rails g smswire:install`.
Expand Down Expand Up @@ -441,9 +468,13 @@ end
```

The adapter builds the message through the messenger, so templates, consent,
quiet hours, persistence, and status tracking all apply. The resulting
`Smswire::Delivery` id is written back to the Noticed notification via
`error_handler`-style callbacks so the two records can be joined.
quiet hours, persistence, and status tracking all apply. It always uses
`deliver_later`, so Smswire's retry policy applies even though Noticed's own
delivery jobs do not retry. The messenger receives the event params plus
`notification`, `record`, and `recipient`, and the default action argument is
the recipient. Each `Smswire::Delivery` records `noticed_notification_id` and
`noticed_event_id` in its metadata, which joins the two records without a
schema dependency between the gems.

### 6.10 Generators

Expand All @@ -452,8 +483,9 @@ quiet hours, persistence, and status tracking all apply. The resulting
- `rails g smswire:messenger Order shipped delivered` — class, templates,
preview, test.
- `rails g smswire:provider Acme` — adapter skeleton in `app/sms_providers`,
a WebMock test, and a registration line in the initializer. The shared
adapter contract suite arrives in Phase 5.
a test that runs `Smswire::ProviderContract` against it with WebMock stubs,
and a registration line in the initializer. The generated pair passes the
contract as generated.

## 7. Configuration surface

Expand Down Expand Up @@ -594,6 +626,8 @@ next. No phase includes a calendar estimate.
- `Noticed::DeliveryMethods::Smswire`.
- Accept: the same dummy-app messenger passes the contract suite against all
three real adapters (WebMock) and delivers through a Noticed notifier.
- Status: implemented. Webhook endpoints share one controller, so a provider
that sends every event to one URL is routed by event kind.

### Phase 6: Release

Expand Down
30 changes: 23 additions & 7 deletions lib/generators/smswire/provider/templates/provider.rb.tt
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,48 @@
# Raise Smswire::TransientError for network failures and 5xx responses,
# Smswire::ThrottledError (with retry_after) for rate limiting, and
# Smswire::PermanentError (with a reason) when retrying cannot help.
# test/sms_providers/<%= file_name %>_provider_test.rb runs the shared
# Smswire::ProviderContract against this class.
class <%= provider_class %> < Smswire::Providers::Base
API_URL = "https://api.example.com/messages".freeze

# Replace with the provider's error codes.
PERMANENT_REASONS = {
"invalid_number" => :invalid_number,
"opted_out" => :opted_out
}.freeze

def deliver(message)
response = Smswire::HTTP.post_form(API_URL, [
["to", message.to],
["from", message.from.to_s],
["body", message.body.to_s]
], headers: {"Authorization" => "Bearer #{options.fetch(:api_key)}"}, provider: name)

status = response.code.to_i
json = Smswire::HTTP.parse_json(response.body)
case response.code.to_i
code = json.dig("error", "code")&.to_s
error_options = {provider: name, provider_code: code, http_status: status, raw: json}

case status
when 200..299
receipt(provider_id: json["id"], status: :accepted, segments: message.segments, raw: json)
when 401, 403
raise Smswire::PermanentError.new("<%= class_name %> authentication failed", reason: :authentication, **error_options)
when 429
raise Smswire::ThrottledError.new("<%= class_name %> rate limited", retry_after: response["Retry-After"]&.to_i, provider: name)
raise Smswire::ThrottledError.new("<%= class_name %> rate limited", retry_after: response["Retry-After"]&.to_i, **error_options)
when 500..599
raise Smswire::TransientError.new("<%= class_name %> #{response.code}", provider: name, http_status: response.code.to_i)
raise Smswire::TransientError.new("<%= class_name %> #{status}", **error_options)
else
raise Smswire::PermanentError.new("<%= class_name %> #{response.code}: #{json["error"]}",
reason: :rejected, provider: name, http_status: response.code.to_i, raw: json)
raise Smswire::PermanentError.new("<%= class_name %> #{status}: #{code}",
reason: PERMANENT_REASONS.fetch(code, :rejected), **error_options)
end
end

# Add :status_callbacks and :inbound here once verify_signature!,
# parse_status_callback, and parse_inbound are implemented.
# Add :status_callbacks and :inbound once verify_signature!,
# parse_status_callback, and parse_inbound are implemented; the contract
# then also checks them through contract_status_request and
# contract_inbound_request.
def capabilities
Set.new
end
Expand Down
36 changes: 20 additions & 16 deletions lib/generators/smswire/provider/templates/test.rb.tt
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,28 @@ require "test_helper"
require "webmock/minitest"

class <%= provider_class %>Test < ActiveSupport::TestCase
setup do
@provider = <%= provider_class %>.new({api_key: "test-key"}, name: :<%= file_name %>)
@message = Smswire::Message.new(to: "+15555550100", from: "+15555550199", body: "Hello")
end
include Smswire::TestHelper
include Smswire::ProviderContract

test "delivers and returns a receipt" do
stub_request(:post, <%= provider_class %>::API_URL).to_return(status: 200, body: {id: "msg_1"}.to_json)
receipt = @provider.deliver(@message)
assert_equal "msg_1", receipt.provider_id
end
def contract_provider_name = :<%= file_name %>

test "5xx responses are transient" do
stub_request(:post, <%= provider_class %>::API_URL).to_return(status: 503)
assert_raises(Smswire::TransientError) { @provider.deliver(@message) }
end
def contract_provider_options = {api_key: "test-key"}

test "4xx responses are permanent" do
stub_request(:post, <%= provider_class %>::API_URL).to_return(status: 400, body: {error: "invalid"}.to_json)
assert_raises(Smswire::PermanentError) { @provider.deliver(@message) }
# Stub the provider API for each contract outcome. Update the error
# payloads to the provider's real responses.
def stub_contract_send(outcome, message)
stub = stub_request(:post, <%= provider_class %>::API_URL)
error = ->(status, code) { stub.to_return(status:, body: {error: {code:}}.to_json) }
case outcome
when :success
stub.with(body: hash_including("to" => message.to, "body" => message.body))
.to_return(status: 200, body: {id: "msg_1"}.to_json)
when :invalid_number then error.call(400, "invalid_number")
when :opted_out then error.call(400, "opted_out")
when :authentication then stub.to_return(status: 401)
when :throttled then stub.to_return(status: 429)
when :server_error then stub.to_return(status: 503)
when :timeout then stub.to_timeout
end
end
end
1 change: 1 addition & 0 deletions lib/smswire.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"#{__dir__}/generators",
"#{__dir__}/smswire/errors.rb",
"#{__dir__}/smswire/engine.rb",
"#{__dir__}/smswire/noticed_delivery_method.rb",
"#{__dir__}/smswire/rspec.rb"
)
loader.setup
Expand Down
2 changes: 1 addition & 1 deletion lib/smswire/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def text(to:, body: nil, from: nil, **options)
body: BodyFormatter.call(content),
media_urls: settings[:media_urls],
category: settings[:category],
metadata: settings[:metadata],
metadata: (settings[:metadata] || {}).merge(params.fetch(:smswire_metadata, {})),
validity_period: settings[:validity_period],
idempotency_key: settings[:idempotency_key],
consent_scope: settings[:consent_scope] || sender.consent_scope,
Expand Down
Loading
Loading