diff --git a/CHANGELOG.md b/CHANGELOG.md index 350dee5..1e3276c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 `/previews` with a phone frame, encoding, segment count, remaining characters, and the characters that force UCS-2. - Development inbox at `/inbox` listing deliveries and inbound diff --git a/Gemfile b/Gemfile index 80fa44e..4f6b824 100644 --- a/Gemfile +++ b/Gemfile @@ -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" diff --git a/README.md b/README.md index 5b12a4f..4c7d27c 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 diff --git a/app/controllers/smswire/inbound_messages_controller.rb b/app/controllers/smswire/inbound_messages_controller.rb index 02a7bc6..bbe596e 100644 --- a/app/controllers/smswire/inbound_messages_controller.rb +++ b/app/controllers/smswire/inbound_messages_controller.rb @@ -1,27 +1,9 @@ module Smswire - # Receives inbound messages at POST /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 /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 diff --git a/app/controllers/smswire/status_callbacks_controller.rb b/app/controllers/smswire/status_callbacks_controller.rb index 9098421..7ab278d 100644 --- a/app/controllers/smswire/status_callbacks_controller.rb +++ b/app/controllers/smswire/status_callbacks_controller.rb @@ -1,43 +1,8 @@ module Smswire - # Receives provider delivery status callbacks at - # POST /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 /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 diff --git a/app/controllers/smswire/webhooks_controller.rb b/app/controllers/smswire/webhooks_controller.rb new file mode 100644 index 0000000..3dc16f0 --- /dev/null +++ b/app/controllers/smswire/webhooks_controller.rb @@ -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 diff --git a/docs/SPEC.md b/docs/SPEC.md index 507b075..d5ba349 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -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 `|`, + 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`. @@ -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 @@ -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 @@ -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 diff --git a/lib/generators/smswire/provider/templates/provider.rb.tt b/lib/generators/smswire/provider/templates/provider.rb.tt index b2b93dc..469a0cb 100644 --- a/lib/generators/smswire/provider/templates/provider.rb.tt +++ b/lib/generators/smswire/provider/templates/provider.rb.tt @@ -4,9 +4,17 @@ # 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], @@ -14,22 +22,30 @@ class <%= provider_class %> < Smswire::Providers::Base ["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 diff --git a/lib/generators/smswire/provider/templates/test.rb.tt b/lib/generators/smswire/provider/templates/test.rb.tt index 2827b59..687a2f8 100644 --- a/lib/generators/smswire/provider/templates/test.rb.tt +++ b/lib/generators/smswire/provider/templates/test.rb.tt @@ -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 diff --git a/lib/smswire.rb b/lib/smswire.rb index 5180334..b48a270 100644 --- a/lib/smswire.rb +++ b/lib/smswire.rb @@ -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 diff --git a/lib/smswire/base.rb b/lib/smswire/base.rb index 6da55e4..edce9c7 100644 --- a/lib/smswire/base.rb +++ b/lib/smswire/base.rb @@ -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, diff --git a/lib/smswire/engine.rb b/lib/smswire/engine.rb index aabdb20..7c84019 100644 --- a/lib/smswire/engine.rb +++ b/lib/smswire/engine.rb @@ -33,6 +33,10 @@ class Engine < ::Rails::Engine Smswire.config.logger ||= ::Rails.logger end + config.after_initialize do + require_relative "noticed_delivery_method" if defined?(::Noticed::DeliveryMethod) + end + initializer "smswire.log_subscriber" do Smswire::LogSubscriber.attach_to :smswire end diff --git a/lib/smswire/http.rb b/lib/smswire/http.rb index 111aba8..b026153 100644 --- a/lib/smswire/http.rb +++ b/lib/smswire/http.rb @@ -29,6 +29,20 @@ def post_form(url, pairs, basic_auth: nil, headers: {}, open_timeout: 5, read_ti raise TransientError.new("#{error.class}: #{error.message}", provider:) end + def post_json(url, payload, headers: {}, open_timeout: 5, read_timeout: 15, provider: nil) + uri = URI(url) + request = Net::HTTP::Post.new(uri, {"User-Agent" => "smswire/#{Smswire::VERSION}", + "Accept" => "application/json"}.merge(headers)) + request.content_type = "application/json" + request.body = JSON.generate(payload) + + Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout:, read_timeout:) do |http| + http.request(request) + end + rescue *NETWORK_ERRORS => error + raise TransientError.new("#{error.class}: #{error.message}", provider:) + end + def parse_json(body) JSON.parse(body.to_s) rescue JSON::ParserError diff --git a/lib/smswire/noticed_delivery_method.rb b/lib/smswire/noticed_delivery_method.rb new file mode 100644 index 0000000..f7d3d90 --- /dev/null +++ b/lib/smswire/noticed_delivery_method.rb @@ -0,0 +1,52 @@ +# Loaded by Smswire::Engine when Noticed is present. +module Noticed + module DeliveryMethods + # Sends a Noticed notification through a Smswire messenger, so + # templates, consent, quiet hours, deduplication, persistence, retries, + # and status tracking all apply. + # + # class OrderShippedNotifier < Noticed::Event + # deliver_by :smswire do |config| + # config.messenger = "OrderMessenger" + # config.action = :shipped + # # Optional: + # # config.args = -> { [recipient] } # default + # # config.kwargs = -> { {} } + # # config.params = -> { {order: record} } # default: the event params + # # config.wait, config.queue, config.priority # for Smswire::DeliveryJob + # end + # end + # + # The messenger receives the event params plus +notification+, +record+, + # and +recipient+. Each Smswire::Delivery records the Noticed + # notification and event ids in its metadata. + class Smswire < DeliveryMethod + required_options :messenger, :action + + def deliver + messenger = fetch_constant(:messenger) + action = evaluate_option(:action).to_sym + args = evaluate_option(:args) || [recipient] + kwargs = evaluate_option(:kwargs) || {} + + ::Smswire::MessageDelivery.new(messenger, action, args: Array(args), kwargs:, params: messenger_params) + .deliver_later(**job_options) + end + + private + + def messenger_params + base = evaluate_option(:params) || event.params || {} + base.to_h.symbolize_keys.merge( + notification:, record: event.record, recipient:, + smswire_metadata: {"noticed_notification_id" => notification.id, "noticed_event_id" => event.id} + ) + end + + def job_options + {wait: evaluate_option(:wait), wait_until: evaluate_option(:wait_until), + queue: evaluate_option(:queue), priority: evaluate_option(:priority)}.compact + end + end + end +end diff --git a/lib/smswire/provider_contract.rb b/lib/smswire/provider_contract.rb new file mode 100644 index 0000000..a95d58c --- /dev/null +++ b/lib/smswire/provider_contract.rb @@ -0,0 +1,158 @@ +require "rack/mock" +require "action_dispatch" + +module Smswire + # Minitest contract every provider adapter must pass. Include it in a + # test case that also has Smswire::TestHelper and WebMock, and define the + # hooks below. Tests for optional capabilities run only when the adapter + # declares them. + # + # class AcmeProviderContractTest < ActiveSupport::TestCase + # include Smswire::TestHelper + # include Smswire::ProviderContract + # + # def contract_provider_name = :acme + # def contract_provider_options = {api_key: "test"} + # def stub_contract_send(outcome, message) = ... # WebMock stub; see OUTCOMES + # def contract_status_request(provider_id:, status:, signed: true) = ... # with :status_callbacks + # def contract_inbound_request(from:, to:, body:, signed: true) = ... # with :inbound + # end + # + # +stub_contract_send+ must stub the provider API for +outcome+ and return + # the WebMock stub. For :success it should also match the message's + # recipient and body. +status+ is :delivered or :undelivered. Define + # +contract_reports_opt_outs?+ as false when the provider cannot report an + # opt-out when sending. Request + # hooks return an ActionDispatch::Request, built with +contract_request+. + module ProviderContract + OUTCOMES = %i[success invalid_number opted_out authentication throttled server_error timeout].freeze + STATUSES = %i[queued accepted sent delivered undelivered failed read].freeze + CAPABILITIES = %i[mms status_callbacks inbound messaging_services scheduling].freeze + + # Return false when the provider has no send-time error that + # specifically means the recipient opted out. The suite then skips the + # :opted_out outcome rather than accept a guess. + def contract_reports_opt_outs? = true + + # The message the suite sends. Override to use one of your messengers. + def contract_message + Message.new(to: "+14155552671", from: "+15005550006", body: "Smswire contract check", messenger: "ContractMessenger", + action: "check") + end + + def contract_provider + Providers.lookup(contract_provider_name).new(contract_provider_options, name: contract_provider_name) + end + + def contract_request(url, body: nil, params: nil, headers: {}) + env = Rack::MockRequest.env_for(url, :method => "POST", :input => body || Rack::Utils.build_query(params || {}), + "CONTENT_TYPE" => body ? "application/json" : "application/x-www-form-urlencoded") + headers.each { |key, value| env["HTTP_#{key.upcase.tr("-", "_")}"] = value } + ActionDispatch::Request.new(env) + end + + def test_contract_declares_known_capabilities + assert_empty contract_provider.capabilities.to_a - CAPABILITIES + end + + def test_contract_delivers_and_returns_a_receipt + message = contract_message + stub = stub_contract_send(:success, message) + receipt = contract_provider.deliver(message) + + assert_requested stub + assert_equal contract_provider_name, receipt.provider + assert receipt.provider_id.present?, "receipt needs the provider message id" + assert_includes STATUSES, receipt.status + assert(receipt.segments.nil? || receipt.segments.positive?) + end + + def test_contract_delivers_through_the_pipeline + message = contract_message + stub_contract_send(:success, message) + providers = Smswire.config.providers.merge(contract_provider_name => contract_provider_options) + result = contract_with_config(default_provider: contract_provider_name, providers:) do + message.provider = contract_provider_name + Pipeline.call(message) + end + + assert result.accepted?, "expected accepted, got #{result.status} #{result.error&.message}" + if Smswire.config.persist_deliveries + assert_equal result.provider_id, result.delivery.reload.provider_id + assert_equal contract_provider_name.to_s, result.delivery.provider + end + end + + def test_contract_maps_permanent_errors_to_reasons + expected = {invalid_number: :invalid_number, opted_out: :opted_out, authentication: :authentication} + expected.delete(:opted_out) unless contract_reports_opt_outs? + expected.each do |outcome, reason| + message = contract_message + stub_contract_send(outcome, message) + error = assert_raises(PermanentError, "#{outcome} should be permanent") { contract_provider.deliver(message) } + assert_equal reason, error.reason, "#{outcome} should map to #{reason}" + assert_equal contract_provider_name, error.provider + WebMock.reset! + end + end + + def test_contract_raises_retryable_errors + {throttled: ThrottledError, server_error: TransientError, timeout: TransientError}.each do |outcome, klass| + message = contract_message + stub_contract_send(outcome, message) + assert_raises(klass, "#{outcome} should raise #{klass}") { contract_provider.deliver(message) } + WebMock.reset! + end + end + + def test_contract_parses_and_verifies_status_callbacks + skip "no :status_callbacks capability" unless contract_provider.capabilities.include?(:status_callbacks) + + %i[delivered undelivered].each do |status| + request = contract_status_request(provider_id: "contract-#{status}", status:) + contract_provider.verify_signature!(request, url: request.original_url) + update = contract_provider.parse_status_callback(request) + assert_equal "contract-#{status}", update.provider_id + assert_equal status, update.status + end + + forged = contract_status_request(provider_id: "contract-forged", status: :delivered, signed: false) + assert_raises(SignatureError) { contract_provider.verify_signature!(forged, url: forged.original_url) } + end + + def test_contract_parses_and_verifies_inbound_messages + skip "no :inbound capability" unless contract_provider.capabilities.include?(:inbound) + + request = contract_inbound_request(from: "+14155552671", to: "+15005550006", body: "STOP") + contract_provider.verify_signature!(request, url: request.original_url) + inbound = contract_provider.parse_inbound(request) + assert inbound.provider_id.present? + assert_equal ["+14155552671", "+15005550006", "STOP"], [inbound.from, inbound.to, inbound.body] + if contract_provider.capabilities.include?(:status_callbacks) + assert_nil contract_provider.parse_status_callback(request), "inbound messages must not parse as status updates" + end + + forged = contract_inbound_request(from: "+14155552671", to: "+15005550006", body: "STOP", signed: false) + assert_raises(SignatureError) { contract_provider.verify_signature!(forged, url: forged.original_url) } + end + + def test_contract_status_callbacks_are_not_inbound_messages + capabilities = contract_provider.capabilities + skip "needs both :status_callbacks and :inbound" unless capabilities.superset?(Set[:status_callbacks, :inbound]) + + request = contract_status_request(provider_id: "contract-status", status: :delivered) + assert_nil contract_provider.parse_inbound(request) + end + + private + + def contract_with_config(**overrides) + config = Smswire.config + previous = overrides.keys.to_h { |key| [key, config.public_send(key)] } + overrides.each { |key, value| config.public_send(:"#{key}=", value) } + yield + ensure + previous&.each { |key, value| config.public_send(:"#{key}=", value) } + end + end +end diff --git a/lib/smswire/providers.rb b/lib/smswire/providers.rb index 08bd36e..725f743 100644 --- a/lib/smswire/providers.rb +++ b/lib/smswire/providers.rb @@ -4,7 +4,9 @@ module Providers test: "Smswire::Providers::Test", log: "Smswire::Providers::Log", null: "Smswire::Providers::Null", - twilio: "Smswire::Providers::Twilio" + twilio: "Smswire::Providers::Twilio", + telnyx: "Smswire::Providers::Telnyx", + vonage: "Smswire::Providers::Vonage" } class << self diff --git a/lib/smswire/providers/telnyx.rb b/lib/smswire/providers/telnyx.rb new file mode 100644 index 0000000..a9a131d --- /dev/null +++ b/lib/smswire/providers/telnyx.rb @@ -0,0 +1,172 @@ +require "base64" +require "bigdecimal" +require "json" +require "openssl" + +module Smswire + module Providers + # Telnyx Messaging API v2 over REST. No SDK dependency. + # + # Smswire.config.providers[:telnyx] = { + # api_key: "KEY...", + # public_key: "base64 key from Mission Control > Keys & Credentials", + # messaging_profile_id: "..." # optional default; senders may set messaging_service + # } + # + # A sender's +messaging_service+ is sent as +messaging_profile_id+. + # Credentials fall back to Rails.application.credentials.telnyx. + # Telnyx does not accept a validity period here, so it is ignored. + class Telnyx < Base + API_URL = "https://api.telnyx.com/v2/messages".freeze + SIGNATURE_TOLERANCE = 300 + ED25519_SPKI_PREFIX = ["302a300506032b6570032100"].pack("H*").freeze + + PERMANENT_REASONS = { + "40300" => :opted_out, # Blocked: recipient replied STOP + "40310" => :invalid_number, # Invalid 'to' address + "40012" => :invalid_number, # Invalid destination number + "40001" => :unroutable, # Not routable (landline or non-SMS) + "40305" => :rejected, # Invalid 'from' address + "40013" => :rejected, # Invalid source number + "40311" => :authentication, # Invalid profile secret + "40313" => :authentication # Missing profile secret + }.freeze + TRANSIENT_CODES = %w[40006 40008].freeze # Recipient unavailable, undeliverable + THROTTLED_CODES = %w[40002 40011 40016 40018].freeze # Spam throttle and carrier throughput limits + + STATUSES = { + "queued" => :queued, "sending" => :accepted, "sent" => :sent, "delivered" => :delivered, + "delivery_unconfirmed" => :sent, "sending_failed" => :failed, "delivery_failed" => :undelivered, + "expired" => :undelivered + }.freeze + + def deliver(message) + response = HTTP.post_json(API_URL, payload_for(message), + headers: {"Authorization" => "Bearer #{credential(:api_key)}"}, provider: name) + handle(response) + end + + def capabilities + Set[:mms, :status_callbacks, :inbound, :messaging_services] + end + + def payload_for(message) + profile = message.messaging_service || options[:messaging_profile_id] + if message.from.blank? && profile.blank? + raise ConfigurationError, "Telnyx requires a from number or messaging_profile_id" + end + + { + to: message.to, + from: message.from.presence, + messaging_profile_id: profile.presence, + text: message.body.presence, + media_urls: message.media_urls.presence, + webhook_url: message.status_callback_url || options[:webhook_url] + }.compact + end + + # Ed25519 over "|", checked against the + # account public key, rejecting timestamps older than five minutes. + def verify_signature!(request, url: nil) + signature = request.headers["telnyx-signature-ed25519"].to_s + timestamp = request.headers["telnyx-timestamp"].to_s + raise SignatureError, "Missing Telnyx signature headers" if signature.empty? || timestamp.empty? + raise SignatureError, "Stale Telnyx timestamp" if (Time.now.to_i - timestamp.to_i).abs > SIGNATURE_TOLERANCE + + verified = public_key.verify(nil, Base64.decode64(signature), "#{timestamp}|#{request.raw_post}") + raise SignatureError, "Invalid Telnyx signature" unless verified + rescue OpenSSL::PKey::PKeyError, ArgumentError + raise SignatureError, "Invalid Telnyx signature" + end + + def parse_status_callback(request) + event_type, payload = event(request) + return nil unless %w[message.sent message.finalized].include?(event_type) + + recipient = Array(payload["to"]).first || {} + error = Array(payload["errors"]).first || {} + StatusUpdate.new( + provider_id: payload["id"], + status: STATUSES.fetch(recipient["status"].to_s, :accepted), + error_code: error["code"]&.to_s, + error_message: error["title"] || error["detail"], + raw: payload + ) + end + + def parse_inbound(request) + event_type, payload = event(request) + return nil unless event_type == "message.received" + + Inbound.new( + provider_id: payload["id"], + from: payload.dig("from", "phone_number"), + to: Array(payload["to"]).first&.dig("phone_number"), + body: payload["text"].to_s, + messaging_service: payload["messaging_profile_id"], + raw: payload + ) + end + + private + + def handle(response) + status = response.code.to_i + json = HTTP.parse_json(response.body) + return success(json["data"] || {}) if status.between?(200, 299) + + error = Array(json["errors"]).first || {} + code = error["code"]&.to_s + detail = "Telnyx #{status}#{" (#{code})" if code}: #{error["title"] || error["detail"] || response.message}" + error_options = {provider: name, provider_code: code, http_status: status, raw: json} + + if status == 429 || THROTTLED_CODES.include?(code) + retry_after = response["Retry-After"]&.to_i + raise ThrottledError.new(detail, retry_after: retry_after&.positive? ? retry_after : nil, **error_options) + elsif status >= 500 || TRANSIENT_CODES.include?(code) + raise TransientError.new(detail, **error_options) + elsif status == 401 || (status == 403 && code.nil?) + raise PermanentError.new(detail, reason: :authentication, **error_options) + else + raise PermanentError.new(detail, reason: PERMANENT_REASONS.fetch(code, :rejected), **error_options) + end + end + + def success(data) + recipient = Array(data["to"]).first || {} + cost = data["cost"] || {} + receipt( + provider_id: data["id"], + status: STATUSES.fetch(recipient["status"].to_s, :queued), + segments: data["parts"]&.to_i, + price_amount: (BigDecimal(cost["amount"].to_s) if cost["amount"].present?), + price_currency: cost["currency"], + raw: data + ) + end + + def event(request) + data = JSON.parse(request.raw_post.to_s)["data"] || {} + [data["event_type"], data["payload"] || {}] + rescue JSON::ParserError + [nil, {}] + end + + def public_key + @public_key ||= OpenSSL::PKey.read(ED25519_SPKI_PREFIX + Base64.decode64(credential(:public_key))) + end + + def credential(key) + value = options[key] || rails_credentials&.dig(key) + raise ConfigurationError, "Missing Telnyx #{key}" if value.blank? + value + end + + def rails_credentials + return unless defined?(::Rails) && ::Rails.respond_to?(:application) && ::Rails.application + ::Rails.application.credentials.telnyx&.to_h&.symbolize_keys + end + end + end +end diff --git a/lib/smswire/providers/twilio.rb b/lib/smswire/providers/twilio.rb index dc5d2a0..27e9059 100644 --- a/lib/smswire/providers/twilio.rb +++ b/lib/smswire/providers/twilio.rb @@ -72,9 +72,12 @@ def verify_signature!(request, url:) def parse_status_callback(request) params = request.request_parameters + raw_status = (params["MessageStatus"] || params["SmsStatus"]).to_s + return nil if raw_status.empty? || raw_status == "received" + StatusUpdate.new( provider_id: params["MessageSid"] || params["SmsSid"], - status: STATUSES.fetch((params["MessageStatus"] || params["SmsStatus"]).to_s, :accepted), + status: STATUSES.fetch(raw_status, :accepted), error_code: params["ErrorCode"].presence, error_message: params["ErrorMessage"].presence, raw: params.to_h @@ -83,6 +86,8 @@ def parse_status_callback(request) def parse_inbound(request) params = request.request_parameters + return nil unless params.key?("Body") && params["From"].present? + Inbound.new( provider_id: params["MessageSid"] || params["SmsSid"], from: params["From"], diff --git a/lib/smswire/providers/vonage.rb b/lib/smswire/providers/vonage.rb new file mode 100644 index 0000000..d00cbe0 --- /dev/null +++ b/lib/smswire/providers/vonage.rb @@ -0,0 +1,186 @@ +require "bigdecimal" +require "digest/md5" +require "openssl" + +module Smswire + module Providers + # Vonage SMS API over REST. No SDK dependency. + # + # Smswire.config.providers[:vonage] = { + # api_key: "...", api_secret: "...", + # signature_secret: "...", # required to verify webhooks + # signature_method: "sha256" # md5hash (Vonage's default), md5, sha1, sha256, or sha512 + # } + # + # Set the dashboard webhook method to POST. Long messages are billed as + # several parts; the receipt keeps the first part's message id, so + # delivery receipts for later parts are acknowledged but not matched. + # Prices are recorded in the account currency, which the API does not name. + # Credentials fall back to Rails.application.credentials.vonage. + class Vonage < Base + API_URL = "https://rest.nexmo.com/sms/json".freeze + SIGNATURE_METHODS = %w[md5hash md5 sha1 sha256 sha512].freeze + SIGNATURE_TOLERANCE = 300 + + # Send response status codes. + PERMANENT_REASONS = { + "4" => :authentication, # Invalid credentials + "14" => :authentication, # Invalid signature + "32" => :authentication, # Signature and API secret disallowed + "6" => :invalid_number, # Invalid message (unrecognized number prefix) + "33" => :invalid_number, # Number de-activated + "7" => :unroutable, # Number barred; may include opt-outs but is not specific to them + "29" => :unroutable # Non-whitelisted destination (demo account) + }.freeze + THROTTLED_CODES = %w[1].freeze + TRANSIENT_CODES = %w[5].freeze + + # Delivery receipt statuses. + STATUSES = { + "accepted" => :accepted, "buffered" => :sent, "delivered" => :delivered, "expired" => :undelivered, + "failed" => :undelivered, "rejected" => :failed, "unknown" => :sent + }.freeze + + def deliver(message) + response = HTTP.post_form(API_URL, form_for(message), provider: name) + handle(response) + end + + def capabilities + Set[:status_callbacks, :inbound] + end + + def form_for(message) + raise ConfigurationError, "Vonage requires a from number or sender id" if message.from.blank? + + pairs = [ + ["api_key", credential(:api_key)], ["api_secret", credential(:api_secret)], + ["to", message.to.delete_prefix("+")], ["from", message.from.delete_prefix("+")], + ["text", message.body.to_s], ["type", (message.encoding == :ucs2) ? "unicode" : "text"] + ] + pairs << ["ttl", (message.validity_period.to_i * 1000).to_s] if message.validity_period + if (callback = message.status_callback_url || options[:callback]) + pairs << ["status-report-req", "1"] << ["callback", callback] + end + pairs + end + + # Vonage signs webhook parameters as sorted "&key=value" pairs with + # "&" and "=" in values replaced by "_", then hashes with the + # signature secret. Timestamps older than five minutes are rejected. + def verify_signature!(request, url: nil) + params = request.request_parameters.to_h.transform_keys(&:to_s) + signature = params.delete("sig").to_s + raise SignatureError, "Missing Vonage sig parameter" if signature.empty? + if params["timestamp"].present? && (Time.now.to_i - params["timestamp"].to_i).abs > SIGNATURE_TOLERANCE + raise SignatureError, "Stale Vonage timestamp" + end + + expected = self.class.signature(params, secret: signature_secret, method: signature_method) + return if ActiveSupport::SecurityUtils.secure_compare(expected.downcase, signature.downcase) + + raise SignatureError, "Invalid Vonage signature" + end + + def self.signature(params, secret:, method:) + data = params.sort.map { |key, value| "&#{key}=#{value.to_s.tr("&=", "__")}" }.join + if method == "md5hash" + Digest::MD5.hexdigest("#{data}#{secret}") + else + OpenSSL::HMAC.hexdigest(method, secret, data).upcase + end + end + + def parse_status_callback(request) + params = request.request_parameters + return nil if params["status"].blank? + + err_code = params["err-code"].to_s + StatusUpdate.new( + provider_id: params["messageId"], + status: STATUSES.fetch(params["status"].to_s, :sent), + error_code: (err_code unless err_code.empty? || err_code == "0"), + raw: params.to_h + ) + end + + def parse_inbound(request) + params = request.request_parameters + return nil unless params.key?("text") && params["msisdn"].present? + + Inbound.new( + provider_id: params["messageId"], + from: international(params["msisdn"]), + to: international(params["to"]), + body: params["text"].to_s, + raw: params.to_h + ) + end + + private + + def handle(response) + status = response.code.to_i + json = HTTP.parse_json(response.body) + raise TransientError.new("Vonage #{status}", provider: name, http_status: status) if status >= 500 + if status == 429 + raise ThrottledError.new("Vonage 429", provider: name, http_status: status) + end + + parts = Array(json["messages"]) + failed = parts.find { |part| part["status"].to_s != "0" } + return success(parts) if status.between?(200, 299) && parts.any? && failed.nil? + + code = failed&.dig("status")&.to_s + detail = "Vonage #{status}#{" (#{code})" if code}: #{failed&.dig("error-text") || response.message}" + error_options = {provider: name, provider_code: code, http_status: status, raw: json} + if THROTTLED_CODES.include?(code) + raise ThrottledError.new(detail, **error_options) + elsif TRANSIENT_CODES.include?(code) + raise TransientError.new(detail, **error_options) + else + raise PermanentError.new(detail, reason: PERMANENT_REASONS.fetch(code, :rejected), **error_options) + end + end + + def success(parts) + prices = parts.filter_map { |part| part["message-price"].presence } + receipt( + provider_id: parts.first["message-id"], + status: :accepted, + segments: parts.size, + price_amount: (prices.sum { |price| BigDecimal(price.to_s) } if prices.any?), + raw: {"messages" => parts} + ) + end + + def international(number) + number = number.to_s + number.match?(/\A\d+\z/) ? "+#{number}" : number + end + + def signature_secret + credential(:signature_secret) + rescue ConfigurationError + raise SignatureError, "Set providers[:vonage][:signature_secret] to verify Vonage webhooks" + end + + def signature_method + method = (options[:signature_method] || rails_credentials&.dig(:signature_method) || "md5hash").to_s + raise ConfigurationError, "Unknown Vonage signature_method #{method}" unless SIGNATURE_METHODS.include?(method) + method + end + + def credential(key) + value = options[key] || rails_credentials&.dig(key) + raise ConfigurationError, "Missing Vonage #{key}" if value.blank? + value + end + + def rails_credentials + return unless defined?(::Rails) && ::Rails.respond_to?(:application) && ::Rails.application + ::Rails.application.credentials.vonage&.to_h&.symbolize_keys + end + end + end +end diff --git a/lib/smswire/status_handler.rb b/lib/smswire/status_handler.rb new file mode 100644 index 0000000..4c41940 --- /dev/null +++ b/lib/smswire/status_handler.rb @@ -0,0 +1,25 @@ +module Smswire + # Applies a parsed provider status update to its delivery and notifies + # observers. Shared by the webhook endpoints. + module StatusHandler + module_function + + def call(update, provider:, delivery_id: nil) + payload = {provider:, 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:, delivery_id:) + payload[:delivery_id] = delivery&.id + payload[:delivery_status] = delivery&.status + notify_observers(delivery, update) if delivery + delivery + end + end + + 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 + end + end +end diff --git a/test/dummy/app/messengers/order_messenger.rb b/test/dummy/app/messengers/order_messenger.rb index d175d07..a246a96 100644 --- a/test/dummy/app/messengers/order_messenger.rb +++ b/test/dummy/app/messengers/order_messenger.rb @@ -21,6 +21,11 @@ def literal(phone, body) text to: phone, body: end + # Called by OrderShippedNotifier through Noticed. + def notify_shipped(customer) + text to: customer, body: "Hi #{customer.name}, order #{params[:order_number]} has shipped." + end + def deal(phone, body) text to: phone, body:, category: :marketing end diff --git a/test/dummy/app/models/customer.rb b/test/dummy/app/models/customer.rb new file mode 100644 index 0000000..82e5b42 --- /dev/null +++ b/test/dummy/app/models/customer.rb @@ -0,0 +1,3 @@ +class Customer < ActiveRecord::Base + has_many :notifications, as: :recipient, dependent: :destroy, class_name: "Noticed::Notification" +end diff --git a/test/dummy/app/notifiers/order_shipped_notifier.rb b/test/dummy/app/notifiers/order_shipped_notifier.rb new file mode 100644 index 0000000..6dbfebc --- /dev/null +++ b/test/dummy/app/notifiers/order_shipped_notifier.rb @@ -0,0 +1,8 @@ +class OrderShippedNotifier < Noticed::Event + required_params :order_number + + deliver_by :smswire do |config| + config.messenger = "OrderMessenger" + config.action = :notify_shipped + end +end diff --git a/test/dummy/config/application.rb b/test/dummy/config/application.rb index 41fdecc..d113cb3 100644 --- a/test/dummy/config/application.rb +++ b/test/dummy/config/application.rb @@ -2,6 +2,7 @@ require "active_job/railtie" require "active_record/railtie" require "action_controller/railtie" +require "noticed" require "smswire" module Dummy diff --git a/test/generators_test.rb b/test/generators_test.rb index fea0806..1773be6 100644 --- a/test/generators_test.rb +++ b/test/generators_test.rb @@ -57,6 +57,28 @@ class MessengerGeneratorTest < Rails::Generators::TestCase end class ProviderGeneratorTest < Rails::Generators::TestCase + ROOT = File.expand_path("../tmp/generators/provider-contract", __dir__) + + # Generate an adapter once and load it with its test, so the generated + # code runs the provider contract as part of this suite. + def self.load_generated_contract! + return if defined?(::ContractcoProviderTest) + + FileUtils.rm_rf(ROOT) + FileUtils.mkdir_p(File.join(ROOT, "config/initializers")) + File.write(File.join(ROOT, "config/initializers/smswire.rb"), "") + original_stdout, $stdout = $stdout, StringIO.new + begin + Smswire::Generators::ProviderGenerator.new(%w[Contractco], {}, destination_root: ROOT).invoke_all + ensure + $stdout = original_stdout + end + require File.join(ROOT, "app/sms_providers/contractco_provider.rb") + Smswire::Providers.register(:contractco, "ContractcoProvider") + require File.join(ROOT, "test/sms_providers/contractco_provider_test.rb") + ::ContractcoProviderTest.include(DatabaseReset) + end + tests Smswire::Generators::ProviderGenerator destination File.expand_path("../tmp/generators/provider", __dir__) @@ -107,3 +129,5 @@ def self.generate! assert WelcomeMessenger.greet("+14155552671").deliver_now.accepted? end end + +ProviderGeneratorTest.load_generated_contract! diff --git a/test/noticed_test.rb b/test/noticed_test.rb new file mode 100644 index 0000000..7da06f3 --- /dev/null +++ b/test/noticed_test.rb @@ -0,0 +1,64 @@ +require "test_helper" + +# Phase 5 acceptance: a Noticed notifier delivers through a Smswire messenger. +class NoticedTest < Smswire::TestCase + setup do + @customer = Customer.create!(name: "Ada", phone_number: "(415) 555-2671") + end + + test "the delivery method is registered with Noticed" do + assert_equal Noticed::DeliveryMethods::Smswire, OrderShippedNotifier.delivery_methods[:smswire].constant + assert_equal %i[messenger action], Noticed::DeliveryMethods::Smswire.required_option_names + end + + test "a notifier delivers through the messenger pipeline" do + perform_enqueued_jobs do + OrderShippedNotifier.with(order_number: "R5").deliver(@customer) + end + + notification = Noticed::Notification.sole + delivery = Smswire::Delivery.sole + assert_equal "Hi Ada, order R5 has shipped.", delivery.body + assert_equal ["+14155552671", "OrderMessenger", "notify_shipped", "accepted"], + [delivery.to_number, delivery.messenger, delivery.action, delivery.status] + assert_equal @customer, delivery.recipient + assert_equal({"noticed_notification_id" => notification.id, "noticed_event_id" => notification.event_id}, delivery.metadata) + end + + test "consent still applies to Noticed deliveries" do + Smswire::Consent.opt_out!(@customer.phone_number, source: :api) + perform_enqueued_jobs do + OrderShippedNotifier.with(order_number: "R6").deliver(@customer) + end + assert_equal 1, Noticed::Notification.count + assert_equal 0, Smswire::Delivery.count + assert_empty sms_deliveries + end + + test "custom args, params, and job options" do + notifier = Class.new(Noticed::Event) do + def self.name = "CustomShippedNotifier" + + deliver_by :smswire do |config| + config.messenger = OrderMessenger + config.action = :delivery_window + config.args = -> { [recipient.phone_number] } + config.kwargs = -> { {window: "9-11am"} } + config.params = -> { {order_number: "R7"} } + config.queue = :sms + end + end + Object.const_set(:CustomShippedNotifier, notifier) + + perform_enqueued_jobs(only: [Noticed::EventJob, Noticed::DeliveryMethods::Smswire]) do + notifier.with(order_number: "ignored").deliver(@customer) + end + assert_enqueued_sms(OrderMessenger, :delivery_window, args: ["(415) 555-2671"], kwargs: {window: "9-11am"}) + assert_equal "sms", enqueued_jobs.last[:queue] + + perform_enqueued_jobs + assert_equal "Order R7 arrives 9-11am", Smswire::Delivery.sole.body + ensure + Object.send(:remove_const, :CustomShippedNotifier) if Object.const_defined?(:CustomShippedNotifier) + end +end diff --git a/test/provider_contract_test.rb b/test/provider_contract_test.rb new file mode 100644 index 0000000..9d758c6 --- /dev/null +++ b/test/provider_contract_test.rb @@ -0,0 +1,147 @@ +require "test_helper" +require "base64" + +# Phase 5 acceptance: the same dummy-app messenger passes the provider +# contract against every bundled adapter. +module DummyContractMessage + def contract_message + customer = Struct.new(:name, :phone_number).new("Ada", "+14155552671") + OrderMessenger.with(order_number: "R100").shipped(customer).message.tap { |message| message.to = "+14155552671" } + end + + def expected_body = "Hi Ada!\nOrder R100 has shipped.\n\nTrack it: http://shop.example/orders/R100" +end + +class TwilioContractTest < Smswire::TestCase + include Smswire::ProviderContract + include DummyContractMessage + + URL = "https://api.twilio.com/2010-04-01/Accounts/ACtest/Messages.json" + + def contract_provider_name = :twilio + + def contract_provider_options = {account_sid: "ACtest", auth_token: "secret"} + + def stub_contract_send(outcome, message) + stub = stub_request(:post, URL) + case outcome + when :success + stub.with(body: hash_including("To" => message.to, "Body" => expected_body)) + .to_return(status: 201, body: {sid: "SMcontract", status: "queued", num_segments: "1"}.to_json) + when :invalid_number then stub.to_return(status: 400, body: {code: 21211}.to_json) + when :opted_out then stub.to_return(status: 400, body: {code: 21610}.to_json) + when :authentication then stub.to_return(status: 401, body: {code: 20003}.to_json) + when :throttled then stub.to_return(status: 429, body: {code: 20429}.to_json) + when :server_error then stub.to_return(status: 503) + when :timeout then stub.to_timeout + end + end + + def twilio_request(params, signed:) + url = "https://app.example/smswire/callbacks" + data = url + params.sort.map { |key, value| "#{key}#{value}" }.join + signature = signed ? Base64.strict_encode64(OpenSSL::HMAC.digest("SHA1", "secret", data)) : "forged" + contract_request(url, params:, headers: {"X-Twilio-Signature" => signature}) + end + + def contract_status_request(provider_id:, status:, signed: true) + twilio_request({"MessageSid" => provider_id, "MessageStatus" => status.to_s}, signed:) + end + + def contract_inbound_request(from:, to:, body:, signed: true) + twilio_request({"MessageSid" => "SMinbound", "From" => from, "To" => to, "Body" => body, "SmsStatus" => "received"}, signed:) + end +end + +class TelnyxContractTest < Smswire::TestCase + include Smswire::ProviderContract + include DummyContractMessage + + KEY = OpenSSL::PKey.generate_key("ED25519") + PUBLIC_KEY = Base64.strict_encode64(KEY.public_to_der[-32..]) + + def contract_provider_name = :telnyx + + def contract_provider_options = {api_key: "KEYtest", public_key: PUBLIC_KEY} + + def stub_contract_send(outcome, message) + stub = stub_request(:post, Smswire::Providers::Telnyx::API_URL) + error = ->(status, code) { stub.to_return(status:, body: {errors: [{code:, title: "error"}]}.to_json) } + case outcome + when :success + stub.with(headers: {"Authorization" => "Bearer KEYtest"}, + body: hash_including("to" => message.to, "from" => "+15005550006", "text" => expected_body)) + .to_return(status: 200, body: {data: {id: "tx-contract", to: [{phone_number: message.to, status: "queued"}], + parts: 1, cost: {amount: "0.0040", currency: "USD"}}}.to_json) + when :invalid_number then error.call(422, "40310") + when :opted_out then error.call(422, "40300") + when :authentication then error.call(401, "10009") + when :throttled then error.call(429, "10011") + when :server_error then error.call(503, "10007") + when :timeout then stub.to_timeout + end + end + + def telnyx_request(data, signed:) + body = {data:}.to_json + timestamp = Time.now.to_i.to_s + signature = Base64.strict_encode64(KEY.sign(nil, "#{timestamp}|#{signed ? body : "#{body} "}")) + contract_request("https://app.example/smswire/inbound/telnyx", body:, + headers: {"telnyx-signature-ed25519" => signature, "telnyx-timestamp" => timestamp}) + end + + def contract_status_request(provider_id:, status:, signed: true) + native = {delivered: "delivered", undelivered: "delivery_failed"}.fetch(status) + telnyx_request({event_type: "message.finalized", payload: {id: provider_id, to: [{phone_number: "+14155552671", status: native}]}}, signed:) + end + + def contract_inbound_request(from:, to:, body:, signed: true) + telnyx_request({event_type: "message.received", payload: {id: "tx-inbound", from: {phone_number: from}, + to: [{phone_number: to}], text: body}}, signed:) + end +end + +class VonageContractTest < Smswire::TestCase + include Smswire::ProviderContract + include DummyContractMessage + + def contract_provider_name = :vonage + + def contract_provider_options = {api_key: "key", api_secret: "secret", signature_secret: "sigsecret", signature_method: "sha256"} + + def stub_contract_send(outcome, message) + stub = stub_request(:post, Smswire::Providers::Vonage::API_URL) + part = ->(status) { stub.to_return(status: 200, body: {"message-count" => "1", "messages" => [{"status" => status, "error-text" => "error"}]}.to_json) } + case outcome + when :success + stub.with(body: hash_including("to" => message.to.delete_prefix("+"), "text" => expected_body, "type" => "text")) + .to_return(status: 200, body: {"message-count" => "1", "messages" => [{"to" => "14155552671", "message-id" => "vg-contract", + "status" => "0", "message-price" => "0.0333"}]}.to_json) + when :invalid_number then part.call("6") + when :authentication then part.call("4") + when :throttled then part.call("1") + when :server_error then stub.to_return(status: 500) + when :timeout then stub.to_timeout + end + end + + # Vonage's "number barred" code also covers blocks other than opt-outs. + def contract_reports_opt_outs? = false + + def vonage_request(params, signed:) + params = params.merge("timestamp" => Time.now.to_i.to_s) + sig = Smswire::Providers::Vonage.signature(params, secret: "sigsecret", method: "sha256") + contract_request("https://app.example/smswire/inbound/vonage", params: params.merge("sig" => signed ? sig : "0" * 64)) + end + + def contract_status_request(provider_id:, status:, signed: true) + native = {delivered: "delivered", undelivered: "failed"}.fetch(status) + vonage_request({"messageId" => provider_id, "msisdn" => "14155552671", "to" => "15005550006", "status" => native, + "err-code" => (status == :delivered) ? "0" : "2"}, signed:) + end + + def contract_inbound_request(from:, to:, body:, signed: true) + vonage_request({"messageId" => "vg-inbound", "msisdn" => from.delete_prefix("+"), "to" => to.delete_prefix("+"), + "text" => body, "type" => "text"}, signed:) + end +end diff --git a/test/telnyx_test.rb b/test/telnyx_test.rb new file mode 100644 index 0000000..7365ab5 --- /dev/null +++ b/test/telnyx_test.rb @@ -0,0 +1,71 @@ +require "test_helper" +require "base64" + +class TelnyxTest < Smswire::IntegrationTest + KEY = OpenSSL::PKey.generate_key("ED25519") + OPTIONS = {api_key: "KEYtest", public_key: Base64.strict_encode64(KEY.public_to_der[-32..])}.freeze + + def with_telnyx(&) + with_config(providers: Smswire.config.providers.merge(telnyx: OPTIONS), &) + end + + def provider = Smswire::Providers::Telnyx.new(OPTIONS, name: :telnyx) + + def post_event(path, data, timestamp: Time.now.to_i) + body = {data:}.to_json + signature = Base64.strict_encode64(KEY.sign(nil, "#{timestamp}|#{body}")) + post path, params: body, headers: {"Content-Type" => "application/json", "telnyx-signature-ed25519" => signature, + "telnyx-timestamp" => timestamp.to_s} + end + + test "sends the profile id, media, and per-message webhook url" do + message = Smswire::Message.new(to: "+14155552671", body: "Look", messaging_service: "profile-1", media_urls: ["https://a.example/1.png"]) + message.status_callback_url = "https://app.example/smswire/status/telnyx?delivery_id=7" + assert_equal({to: "+14155552671", messaging_profile_id: "profile-1", text: "Look", media_urls: ["https://a.example/1.png"], + webhook_url: "https://app.example/smswire/status/telnyx?delivery_id=7"}, provider.payload_for(message)) + assert_raises(Smswire::ConfigurationError) { provider.payload_for(Smswire::Message.new(to: "+14155552671", body: "x")) } + end + + test "carrier throughput and temporary failures are retryable" do + {"40011" => Smswire::ThrottledError, "40006" => Smswire::TransientError}.each do |code, klass| + stub_request(:post, Smswire::Providers::Telnyx::API_URL).to_return(status: 422, body: {errors: [{code:}]}.to_json) + assert_raises(klass) { provider.deliver(Smswire::Message.new(to: "+14155552671", from: "+15005550006", body: "x")) } + end + end + + test "a profile webhook pointed at one URL handles both inbound and status events" do + stub_request(:post, Smswire::Providers::Telnyx::API_URL).to_return(status: 200, + body: {data: {id: "tx-1", to: [{status: "queued"}], parts: 1}}.to_json) + result = with_telnyx do + with_config(default_provider: :telnyx) { OrderMessenger.literal("+14155552671", "Shipped").deliver_now } + end + assert_equal "queued", result.delivery.status + + with_telnyx do + post_event "/smswire/inbound/telnyx", {event_type: "message.finalized", payload: {id: "tx-1", to: [{status: "delivered"}]}} + assert_response :no_content + assert_equal "delivered", result.delivery.reload.status + + post_event "/smswire/status/telnyx", {event_type: "message.received", + payload: {id: "tx-in", from: {phone_number: "+14155552671"}, to: [{phone_number: "+15005550006"}], text: "HELP"}} + assert_response :no_content + end + assert_equal "help", Smswire::InboundMessage.sole.keyword + end + + test "unrelated events are acknowledged" do + with_telnyx { post_event "/smswire/inbound/telnyx", {event_type: "number_order.complete", payload: {}} } + assert_response :no_content + end + + test "stale or tampered events are refused" do + with_telnyx do + post_event "/smswire/status/telnyx", {event_type: "message.finalized", payload: {id: "x"}}, timestamp: Time.now.to_i - 3600 + assert_response :forbidden + post "/smswire/status/telnyx", params: {data: {}}.to_json, + headers: {"Content-Type" => "application/json", "telnyx-signature-ed25519" => Base64.strict_encode64("x" * 64), + "telnyx-timestamp" => Time.now.to_i.to_s} + assert_response :forbidden + end + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb index dfd8df6..b3a9cef 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -10,7 +10,17 @@ require_relative "dummy/config/environment" ActiveRecord::Migration.verbose = false -ActiveRecord::MigrationContext.new(File.expand_path("../db/migrate", __dir__)).migrate +ActiveRecord::MigrationContext.new([ + File.expand_path("../db/migrate", __dir__), + Noticed::Engine.root.join("db/migrate").to_s +]).migrate +ActiveRecord::Schema.define do + create_table :customers, force: true do |t| + t.string :name + t.string :phone_number + t.string :time_zone + end +end require "minitest/autorun" require "webmock/minitest" @@ -42,7 +52,8 @@ def twilio_success(sid: "SM123", status: "queued", segments: "1") # Every test starts with empty Smswire tables. module DatabaseReset def before_setup - [Smswire::Delivery, Smswire::Consent, Smswire::InboundMessage].each(&:delete_all) + [Smswire::Delivery, Smswire::Consent, Smswire::InboundMessage, Noticed::Notification, Noticed::Event, Customer] + .each(&:delete_all) super end end diff --git a/test/vonage_test.rb b/test/vonage_test.rb new file mode 100644 index 0000000..cb4c8d9 --- /dev/null +++ b/test/vonage_test.rb @@ -0,0 +1,91 @@ +require "test_helper" + +class VonageTest < Smswire::IntegrationTest + OPTIONS = {api_key: "key", api_secret: "secret", signature_secret: "sigsecret", signature_method: "sha256"}.freeze + + def with_vonage(**options, &) + with_config(providers: Smswire.config.providers.merge(vonage: OPTIONS.merge(options)), &) + end + + def provider(**options) = Smswire::Providers::Vonage.new(OPTIONS.merge(options), name: :vonage) + + def signed(params, method: "sha256") + params = params.merge("timestamp" => Time.now.to_i.to_s) + params.merge("sig" => Smswire::Providers::Vonage.signature(params, secret: "sigsecret", method:)) + end + + test "signatures match the Vonage SDK algorithm" do + params = {"api_key" => "abc123", "to" => "447900000000", "from" => "447900000001", "text" => "Hello & =World", "timestamp" => "1385047698"} + data = "&api_key=abc123&from=447900000001&text=Hello _ _World×tamp=1385047698&to=447900000000" + assert_equal OpenSSL::HMAC.hexdigest("sha256", "s", data).upcase, Smswire::Providers::Vonage.signature(params, secret: "s", method: "sha256") + assert_equal Digest::MD5.hexdigest("#{data}s"), Smswire::Providers::Vonage.signature(params, secret: "s", method: "md5hash") + end + + test "sends unicode, sender, ttl, and callback parameters" do + message = Smswire::Message.new(to: "+14155552671", from: "AcmeCo", body: "Café ☕", validity_period: 600) + message.status_callback_url = "https://app.example/smswire/status/vonage?delivery_id=1" + params = provider.form_for(message).to_h + assert_equal ["14155552671", "AcmeCo", "unicode", "600000", "1"], params.values_at("to", "from", "type", "ttl", "status-report-req") + assert_equal "https://app.example/smswire/status/vonage?delivery_id=1", params["callback"] + end + + test "multipart sends keep the first id and total the price" do + stub_request(:post, Smswire::Providers::Vonage::API_URL).to_return(status: 200, body: { + "message-count" => "2", + "messages" => [{"message-id" => "part-1", "status" => "0", "message-price" => "0.0333"}, + {"message-id" => "part-2", "status" => "0", "message-price" => "0.0333"}] + }.to_json) + receipt = provider.deliver(Smswire::Message.new(to: "+14155552671", from: "+15005550006", body: "x" * 200)) + assert_equal ["part-1", 2, BigDecimal("0.0666")], [receipt.provider_id, receipt.segments, receipt.price_amount] + assert_nil receipt.price_currency + end + + test "number barred is unroutable, not an opt-out" do + stub_request(:post, Smswire::Providers::Vonage::API_URL).to_return(status: 200, body: {"messages" => [{"status" => "7"}]}.to_json) + error = assert_raises(Smswire::PermanentError) { provider.deliver(Smswire::Message.new(to: "+14155552671", from: "+15005550006", body: "x")) } + assert_equal [:unroutable, "7"], [error.reason, error.provider_code] + refute error.opted_out? + end + + test "delivery receipts and inbound replies arrive through the webhooks" do + stub_request(:post, Smswire::Providers::Vonage::API_URL).to_return(status: 200, + body: {"messages" => [{"message-id" => "vg-1", "status" => "0"}]}.to_json) + result = with_vonage do + with_config(default_provider: :vonage) { OrderMessenger.literal("+14155552671", "Shipped").deliver_now } + end + assert_equal "accepted", result.delivery.status + + with_vonage do + post "/smswire/status/vonage", params: signed({"messageId" => "vg-1", "msisdn" => "14155552671", "status" => "delivered", "err-code" => "0"}) + assert_response :no_content + assert_equal "delivered", result.delivery.reload.status + + post "/smswire/inbound/vonage", params: signed({"messageId" => "vg-in", "msisdn" => "14155552671", "to" => "15005550006", "text" => "STOP"}) + assert_response :no_content + end + assert_equal "opted_out", Smswire::Consent.status_for("+14155552671") + assert_equal "+15005550006", Smswire::InboundMessage.sole.to_number + end + + test "stale timestamps, bad signatures, and a missing secret are refused" do + with_vonage do + stale = {"messageId" => "x", "status" => "delivered", "timestamp" => (Time.now.to_i - 3600).to_s} + post "/smswire/status/vonage", params: stale.merge("sig" => Smswire::Providers::Vonage.signature(stale, secret: "sigsecret", method: "sha256")) + assert_response :forbidden + post "/smswire/status/vonage", params: {"messageId" => "x", "status" => "delivered", "sig" => "bad"} + assert_response :forbidden + end + with_vonage(signature_secret: nil) do + post "/smswire/status/vonage", params: signed({"messageId" => "x", "status" => "delivered"}) + assert_response :forbidden + end + end + + test "md5hash signatures are accepted" do + with_vonage(signature_method: "md5hash") do + post "/smswire/inbound/vonage", params: signed({"messageId" => "vg-md5", "msisdn" => "14155552671", "to" => "15005550006", "text" => "hi"}, method: "md5hash") + end + assert_response :no_content + assert_equal 1, Smswire::InboundMessage.count + end +end