Parent: Migrate from Basic Auth to OAuth
The following changes since commit cc359838dae460ff1cac5612b3d00122f7513aa3:
Merge branch ‘push-rzzpsovmnsrs’ of https://knot.secluded.site/secluded.site/sgx-bwmsgsv2 (2026-10-14 12:22:02 -0500)
are available in the Git repository at:
https://knot.secluded.site/secluded.site/sgx-bwmsgsv2 push-ywvlmwxoqmsv
for you to fetch changes up to 667e87ab48147e0ab64724b5b8acf9123ff3343a:
Enable OAuth for outbound MMS (2026-11-02 14:52:47 -0700)
Amolith (6):
Carry credential object through
Switch to my BW SDK fork
Use the SDK for outbound messages
Limit media fallback to preparation failures
Enable OAuth for outbound SMS
Enable OAuth for outbound MMS
Gemfile | 2 ±
guix.scm | 11 +++±–
lib/bandwidth_credentials.rb | 14 +++±—
lib/bandwidth_message.rb | 44 +++++++++++++++++++++++++
sgx-bwmsgsv2.rb | 58 +++++++++++++++±----------------
test/property/test_to_catapult.rb | 24 +++++++++++±-
test/test_bandwidth_message.rb | 149 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
test/test_component.rb | 235 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++±----------------
8 files changed, 463 insertions(+), 74 deletions(-)
create mode 100644 lib/bandwidth_message.rb
create mode 100644 test/test_bandwidth_message.rb
diff --git a/Gemfile b/Gemfile
index 61b4e58..df0e428 100644
--- a/Gemfile
+++ b/Gemfile
@@ -57,4 +57,4 @@ group(:test) do
gem 'fakefs', require: false
end
-gem "bandwidth-sdk", "~> 17.1"
+gem "bandwidth-sdk", "~> 1.0", git: "https://github.com/Amolith/ruby-sdk", ref: "69ad1f59aa5979006e55d15bf7271a51dba5eb1b"
diff --git a/guix.scm b/guix.scm
index 4d2e716..a5610d5 100755
--- a/guix.scm
+++ b/guix.scm
@@ -41,12 +41,15 @@
(define ruby-bandwidth-sdk
(package (inherit ruby-package)
(name "ruby-bandwidth-sdk")
- (version "17.3.2")
+ (version (git-version "1.0.0" "0" "69ad1f59aa5979006e55d15bf7271a51dba5eb1b"))
(source
(origin
- (method url-fetch)
- (uri (rubygems-uri "bandwidth-sdk" version))
- (sha256 (base32 "0s9w5sl3k7ygrkxzchz50i0irpp8aghjh8lihqs1x3gs0d128akg"))))
+ (method git-fetch)
+ (uri (git-reference
+ (url "https://github.com/Amolith/ruby-sdk")
+ (commit "69ad1f59aa5979006e55d15bf7271a51dba5eb1b")))
+ (file-name (git-file-name name version))
+ (sha256 (base32 "1rkhcmsvi6rkw4wzcfw0vn6clv6znx4s2l0vqkifzx92s1whgamf"))))
(propagated-inputs
(list ruby-faraday ruby-faraday-multipart ruby-marcel ruby-ox))
(arguments (list #:ruby ruby #:tests? #f))
diff --git a/lib/bandwidth_credentials.rb b/lib/bandwidth_credentials.rb
index c7b0db6..6f15d79 100644
--- a/lib/bandwidth_credentials.rb
+++ b/lib/bandwidth_credentials.rb
@@ -13,10 +13,12 @@ class BandwidthCredentials
end
def iris_client
+ BandwidthIris::Client.new(account_id: @account_id, **authentication)
+ end
+
+ def authentication
unless @client_id || @client_secret
- return BandwidthIris::Client.new(
- account_id: @account_id, username: @username, password: @password
- )
+ return {username: @username, password: @password}
end
missing = []
missing << "client_id" if @client_id.to_s.empty?
@@ -25,10 +27,6 @@ class BandwidthCredentials
raise ArgumentError, "Missing OAuth #{missing.join(' and ')}"
end
- BandwidthIris::Client.new(
- account_id: @account_id,
- client_id: @client_id,
- client_secret: @client_secret
- )
+ {client_id: @client_id, client_secret: @client_secret}
end
end
diff --git a/lib/bandwidth_message.rb b/lib/bandwidth_message.rb
new file mode 100644
index 0000000..42a4217
--- /dev/null
+++ b/lib/bandwidth_message.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+require "json"
+require "bandwidth-sdk"
+require "em_promise"
+require "em-synchrony/em-http"
+require "faraday/em_synchrony"
+require_relative "bandwidth_error"
+Faraday.default_adapter = :em_synchrony
+
+class BandwidthMessage
+ def initialize(account_id, username: nil, password: nil,
+ client_id: nil, client_secret: nil)
+ @account_id = account_id
+ configuration = Bandwidth::Configuration.new do |config|
+ config.username = username
+ config.password = password
+ config.client_id = client_id
+ config.client_secret = client_secret
+ end
+ @api = Bandwidth::MessagesApi.new(Bandwidth::ApiClient.new(configuration))
+ end
+
+ def call(body)
+ EMPromise.resolve(nil).then { request(body) }
+ end
+
+private
+
+ def request(body)
+ response, status = @api.create_message_with_http_info(
+ @account_id, body, debug_return_type: "String"
+ )
+ unless [201, 202].include?(status)
+ raise BandwidthError.for(status, response)
+ end
+
+ JSON.parse(response)
+ rescue Bandwidth::ApiError => e
+ raise BandwidthError.for(e.code, e.response_body) if e.code
+
+ raise
+ end
+end
diff --git a/sgx-bwmsgsv2.rb b/sgx-bwmsgsv2.rb
index 9bdbdb7..3814e6b 100755
--- a/sgx-bwmsgsv2.rb
+++ b/sgx-bwmsgsv2.rb
@@ -54,6 +54,7 @@ EM::Hiredis.logger = LOG
require_relative 'lib/bandwidth_patch'
require_relative 'lib/bandwidth_error'
+require_relative 'lib/bandwidth_message'
require_relative 'lib/bandwidth_tn_options'
require_relative 'lib/message_event'
require_relative 'lib/registration_repo'
@@ -161,6 +162,8 @@ end
module SGXbwmsgsv2
extend Blather::DSL
+ class MediaFetchError < StandardError; end
+
@feature_flag_repo = MM4::FeatureFlagRepo.new
@registration_repo = RegistrationRepo.new
@client = SGXClient.new
@@ -311,13 +314,11 @@ module SGXbwmsgsv2
}
end
- def self.to_catapult_possible_oob(s, num_dest, user_id, token, secret,
- usern)
+ def self.to_catapult_possible_oob(s, num_dest, credentials)
un = s.at("oob|x > oob|url", oob: "jabber:x:oob")
unless un
LOG.debug "No OOB URL node, processing as normal"
- return to_catapult(s, nil, num_dest, user_id, token,
- secret, usern)
+ return to_catapult(s, nil, num_dest, credentials)
end
LOG.debug "Found OOB URL node, checking MMS eligibility"
@@ -327,32 +328,34 @@ module SGXbwmsgsv2
unless body.include?(un.text)
s.body = body.empty? ? un.text : "#{body}\n#{un.text}"
end
- return to_catapult(s, nil, num_dest, user_id, token, secret, usern)
+ return to_catapult(s, nil, num_dest, credentials)
end
- MMS::Media::Head.new(url: un.text).call.then { |media|
+ MMS::Media::Head.new(url: un.text).call.catch { |e|
+ LOG.error("Error inspecting MMS, falling back to sending link", error: e)
+ un.text
+ }.then { |media|
if media.is_a?(String)
unless body.include?(media)
s.body = body.empty? ? media : "#{body}\n#{media}"
end
- to_catapult(s, nil, num_dest, user_id, token, secret, usern)
+ to_catapult(s, nil, num_dest, credentials)
else
# some clients send URI in both body & <url/> so delete
s.body = body.sub(/\s*#{Regexp.escape(un.text)}\s*$/, '')
LOG.debug("OOB MMS details", url: un.text, body: body.to_s.strip)
- to_catapult(s, media, num_dest, user_id, token, secret, usern)
+ to_catapult(s, media, num_dest, credentials)
end
- }.catch { |e|
- LOG.error("Error sending MMS, falling back to sending link", error: e)
- unless body.include?(un.text)
- s.body = body.empty? ? un.text : "#{body}\n#{un.text}"
- end
- to_catapult(s, nil, num_dest, user_id, token, secret, usern)
+ }.catch_only(MediaFetchError) {
+ s.body = body.include?(un.text) ? body :
+ (body.empty? ? un.text : "#{body}\n#{un.text}")
+ to_catapult(s, nil, num_dest, credentials)
}
end
- def self.to_catapult(s, media, num_dest, user_id, token, secret, usern)
+ def self.to_catapult(s, media, num_dest, credentials)
+ usern = credentials.tel
body = s.respond_to?(:body) ? s.body.to_s : ''
media_url = media&.url
@@ -422,15 +425,9 @@ module SGXbwmsgsv2
)
))
via_http = lambda {
- call_catapult(
- token,
- secret,
- :post,
- "api/v2/users/#{user_id}/messages",
- catapult_body,
- {'Content-Type' => 'application/json'},
- [201, 202]
- ).then(&JSON.method(:parse))
+ BandwidthMessage.new(
+ credentials.account_id, **credentials.authentication
+ ).call(catapult_body)
}
via_mm4 = lambda {
@@ -438,7 +435,11 @@ module SGXbwmsgsv2
MMS::Media::Fetch.new(attachment: media).call :
EMPromise.resolve(nil)
- attachment.then { |fetched_media|
+ attachment.catch {
+ EMPromise.reject(MediaFetchError.new)
+ }.then { |fetched_media|
+ raise MediaFetchError if fetched_media.is_a?(String)
+
MM4::Message.new(
recipients: Array(num_dest),
sender: usern,
@@ -467,6 +468,8 @@ module SGXbwmsgsv2
media_urls: [media_url].compact
).emit(REDIS)
}.catch { |e|
+ next EMPromise.reject(e) if e.is_a?(MediaFetchError)
+
EMPromise.reject(
[:cancel, 'internal-server-error', e.message]
)
@@ -569,10 +572,7 @@ module SGXbwmsgsv2
if other_user and not other_user.start_with? 'u-'
pass_on_message(m, creds.tel, jid)
else
- to_catapult_possible_oob(
- m, num_dest,
- creds.account_id, creds.username, creds.password, creds.tel
- )
+ to_catapult_possible_oob(m, num_dest, creds)
end
}.catch { |e|
if e.is_a?(Array) && (e.length == 2 || e.length == 3)
diff --git a/test/property/test_to_catapult.rb b/test/property/test_to_catapult.rb
index 412c407..a5dc8b1 100644
--- a/test/property/test_to_catapult.rb
+++ b/test/property/test_to_catapult.rb
@@ -15,14 +15,31 @@ class ToCatapultPropertyTest < Minitest::Test
resource = maybe_http_escapable_string
status = choose(201, 202)
- [dest, message_body(nil_pct: 0, empty_pct: 0), stanza_id, resource, status]
- }.check { |dest, body, stanza_id, resource, status|
+ [
+ dest, message_body(nil_pct: 0, empty_pct: 0),
+ stanza_id, resource, status, boolean
+ ]
+ }.check { |dest, body, stanza_id, resource, status, oauth|
reset_stanzas!
reset_redis!
WebMock.reset!
+ if oauth
+ REDIS.set("catapult_cred-test@example.com", [
+ "account", "user", "password", "+15550000000", "client", "secret"
+ ])
+ end
+ token = stub_request(
+ :post, "https://api.bandwidth.com/api/v1/oauth2/token"
+ ).with(basic_auth: ["client", "secret"]).to_return(
+ body: JSON.dump(access_token: "sms-token", expires_in: 3600)
+ )
+ authorization = oauth ?
+ "Bearer sms-token" : "Basic dXNlcjpwYXNzd29yZA=="
bw_request_body = nil
- bw_req = stub_request(:post, BW_MESSAGES_URL).to_return { |request|
+ bw_req = stub_request(:post, BW_MESSAGES_URL).with(
+ headers: {"Authorization" => authorization}
+ ).to_return { |request|
bw_request_body = JSON.parse(request.body)
{
status: status,
@@ -43,6 +60,7 @@ class ToCatapultPropertyTest < Minitest::Test
"Tag should be HTTP-escaped (status=#{status})"
assert_requested bw_req
+ oauth ? assert_requested(token) : assert_not_requested(token)
written.each do |response|
stanza = Blather::XMPPNode.parse(response.to_xml)
diff --git a/test/test_bandwidth_message.rb b/test/test_bandwidth_message.rb
new file mode 100644
index 0000000..f585646
--- /dev/null
+++ b/test/test_bandwidth_message.rb
@@ -0,0 +1,149 @@
+# frozen_string_literal: true
+
+require "test_helper"
+require "bandwidth_message"
+
+class BandwidthMessageTest < Minitest::Test
+ def setup
+ @message = BandwidthMessage.new(
+ "account", username: "user", password: "password"
+ )
+ @body = JSON.dump(
+ from: "+15550000000", to: ["+15551234567"], text: "hello 世界",
+ applicationId: "application", tag: "id%20one resource%2Ftwo",
+ media: "https://example.com/photo.jpg"
+ )
+ end
+
+ def test_preserves_payload_and_accepts_only_created_or_accepted
+ [201, 202].each do |status|
+ request = stub_request(:post, BW_MESSAGES_URL).with(
+ basic_auth: ["user", "password"], body: @body,
+ headers: {"Content-Type" => "application/json"}
+ ).to_return(
+ status: status, body: '{"id":"message","time":"2026-10-26T12:34:56Z"}'
+ )
+ assert_equal(
+ {"id" => "message", "time" => "2026-10-26T12:34:56Z"},
+ @message.call(@body).sync
+ )
+ assert_requested request, times: 1
+ WebMock.reset!
+ end
+ end
+ em :test_preserves_payload_and_accepts_only_created_or_accepted
+
+ def test_rejects_unexpected_statuses_with_existing_http_errors
+ [200, 204, 400, 401, 403, 429, 500].each do |status|
+ request = stub_request(:post, BW_MESSAGES_URL).to_return(
+ status: status, body: 'not JSON'
+ )
+ error = assert_raises(BandwidthError) { @message.call(@body).sync }
+ assert_equal status, error.code
+ assert_equal "Error #{status}", error.message
+ assert_requested request, times: 1
+ WebMock.reset!
+ end
+ end
+ em :test_rejects_unexpected_statuses_with_existing_http_errors
+
+ def test_preserves_carrier_error_descriptions
+ stub_request(:post, BW_MESSAGES_URL).to_return(
+ status: 400,
+ body: JSON.dump(
+ description: "Invalid message", fieldErrors: [{description: "Bad to"}]
+ )
+ )
+ error = assert_raises(BandwidthError) { @message.call(@body).sync }
+ assert_equal "Invalid message Bad to", error.message
+ assert_instance_of Bandwidth::ApiError, error.cause
+ assert_equal 400, error.cause.code
+ assert_equal "Invalid message",
+ JSON.parse(error.cause.response_body)["description"]
+ end
+ em :test_preserves_carrier_error_descriptions
+
+ def test_preserves_transport_and_parsing_failures_without_retry
+ {timeout: Bandwidth::ApiError, json: JSON::ParserError,
+ error_fields: NoMethodError}.each do |failure, exception|
+ request = stub_request(:post, BW_MESSAGES_URL)
+ case failure
+ when :timeout then request.to_timeout
+ when :json then request.to_return(status: 201, body: 'private-response')
+ when :error_fields
+ request.to_return(
+ status: 400, body: JSON.dump(fieldErrors: "private-response")
+ )
+ end
+ assert_raises(exception) { @message.call(@body).sync }
+ assert_requested request, times: 1
+ WebMock.reset!
+ end
+ end
+ em :test_preserves_transport_and_parsing_failures_without_retry
+
+ def test_oauth_uses_bearer_and_reuses_the_transport_token
+ message = BandwidthMessage.new(
+ "account", client_id: "client", client_secret: "secret"
+ )
+ token = stub_request(
+ :post, "https://api.bandwidth.com/api/v1/oauth2/token"
+ ).with(
+ basic_auth: ["client", "secret"], body: "grant_type=client_credentials"
+ ).to_return(body: JSON.dump(access_token: "token", expires_in: 3600))
+ request = stub_request(:post, BW_MESSAGES_URL).with(
+ headers: {"Authorization" => "Bearer token"}, body: @body
+ ).to_return(status: 202, body: '{"id":"oauth-message"}')
+ 2.times do
+ assert_equal({"id" => "oauth-message"}, message.call(@body).sync)
+ end
+ assert_requested token, times: 1
+ assert_requested request, times: 2
+ end
+ em :test_oauth_uses_bearer_and_reuses_the_transport_token
+
+ def test_short_lived_tokens_are_used_once_per_submission
+ message = BandwidthMessage.new(
+ "account", client_id: "client", client_secret: "secret"
+ )
+ token = stub_request(
+ :post, "https://api.bandwidth.com/api/v1/oauth2/token"
+ ).to_return(
+ {body: JSON.dump(access_token: "first", expires_in: 60)},
+ {body: JSON.dump(access_token: "second", expires_in: 60)}
+ )
+ headers = []
+ request = stub_request(:post, BW_MESSAGES_URL).to_return { |sent|
+ headers << sent.headers.fetch("Authorization")
+ {status: 201, body: '{"id":"message"}'}
+ }
+ ["first", "second"].each do |value|
+ assert_equal({"id" => "message"}, message.call(@body).sync)
+ assert_equal "Bearer #{value}", headers.last
+ end
+ assert_requested request, times: 2
+ assert_requested token, times: 2
+ end
+ em :test_short_lived_tokens_are_used_once_per_submission
+
+ def test_oauth_failure_preserves_errors_and_never_submits_a_message
+ [
+ [{status: 401, body: "token-rejection"}, RuntimeError],
+ [{status: 200, body: "invalid-json"}, JSON::ParserError],
+ [:timeout, Bandwidth::ApiError]
+ ].each do |response, exception|
+ message = BandwidthMessage.new(
+ "account", client_id: "client", client_secret: "secret"
+ )
+ token = stub_request(
+ :post, "https://api.bandwidth.com/api/v1/oauth2/token"
+ )
+ response == :timeout ? token.to_timeout : token.to_return(response)
+ assert_raises(exception) { message.call(@body).sync }
+ assert_requested token, times: 1
+ assert_not_requested :post, BW_MESSAGES_URL
+ WebMock.reset!
+ end
+ end
+ em :test_oauth_failure_preserves_errors_and_never_submits_a_message
+end
diff --git a/test/test_component.rb b/test/test_component.rb
index b999f71..1f2b5f8 100644
--- a/test/test_component.rb
+++ b/test/test_component.rb
@@ -108,10 +108,7 @@ class ComponentTest < Minitest::Test
SGXbwmsgsv2.to_catapult_possible_oob(
message,
"+15551234567",
- "account",
- "user",
- "password",
- "+15550000000"
+ BandwidthCredentials.new(["account", "user", "password", "+15550000000"])
).sync
assert_requested media_req
@@ -170,10 +167,7 @@ class ComponentTest < Minitest::Test
SGXbwmsgsv2.to_catapult_possible_oob(
message,
"+15551234567",
- "account",
- "user",
- "password",
- "+15550000000"
+ BandwidthCredentials.new(["account", "user", "password", "+15550000000"])
).sync
end
@@ -210,10 +204,7 @@ class ComponentTest < Minitest::Test
SGXbwmsgsv2.to_catapult_possible_oob(
message,
"+15551234567",
- "account",
- "user",
- "password",
- "+15550000000"
+ BandwidthCredentials.new(["account", "user", "password", "+15550000000"])
).sync
assert_requested media_req
@@ -247,10 +238,7 @@ class ComponentTest < Minitest::Test
SGXbwmsgsv2.to_catapult_possible_oob(
message,
"+45555555555",
- "account",
- "user",
- "password",
- "+15550000000"
+ BandwidthCredentials.new(["account", "user", "password", "+15550000000"])
).sync
assert_requested bw_req
@@ -783,29 +771,215 @@ class ComponentTest < Minitest::Test
end
em :test_outbound_message_emits_to_stream
- def test_outbound_uses_basic_from_extended_registration
- creds = ["account", "user", "password", "+15550000000", "client", "client-secret"]
+ def test_outbound_sms_uses_oauth_from_extended_registration
+ creds = [
+ "account", "user", "password", "+15550000000", "client", "client-secret"
+ ]
+ token = stub_request(
+ :post, "https://api.bandwidth.com/api/v1/oauth2/token"
+ ).with(
+ basic_auth: ["client", "client-secret"]
+ ).to_return(body: JSON.dump(access_token: "sms-token", expires_in: 3600))
request = stub_request(
:post,
"https://messaging.bandwidth.com/api/v2/users/account/messages"
- ).with(basic_auth: ["user", "password"], body: hash_including(
- from: "+15550000000", to: "+15551234567", text: "hello"
- )).to_return(status: 201, body: JSON.dump(id: "bw-msg-123"))
+ ).with(
+ headers: {"Authorization" => "Bearer sms-token"},
+ body: hash_including(
+ from: "+15550000000", to: "+15551234567", text: "hello"
+ )
+ ).to_return(status: 201, body: JSON.dump(id: "bw-msg-123"))
message = Blather::Stanza::Message.new("+15551234567@component", "hello")
message.from = "test@example.com/resource"
- [creds, creds.take(5)].each do |record|
- REDIS.set("catapult_cred-test@example.com", record)
- process_stanza(message)
- end
+ REDIS.set("catapult_cred-test@example.com", creds)
+ process_stanza(message)
- assert_requested request, times: 2
+ assert_requested token, times: 1
+ assert_requested request, times: 1
assert_empty written
entries = REDIS.stream_entries("messages").sync
- assert_equal 2, entries.length
+ assert_equal 1, entries.length
assert_equal "+15550000000", entries.first[:fields]["from"]
end
- em :test_outbound_uses_basic_from_extended_registration
+ em :test_outbound_sms_uses_oauth_from_extended_registration
+
+ def test_http_messages_with_incomplete_oauth_never_send_or_fall_back
+ [
+ ["client"], [nil, "secret"], ["", "secret"], ["client", ""], ["", ""]
+ ].product([1, 481]).each do |oauth, length|
+ reset_stanzas!
+ REDIS.set(
+ "catapult_cred-test@example.com",
+ ["account", "user", "password", "+15550000000"] + oauth
+ )
+ message = build_outbound_message("a" * length, "+15551234567")
+ message.from = "test@example.com/resource"
+ process_stanza(message)
+ assert_equal 1, written.length
+ assert Blather::XMPPNode.parse(written.first.to_xml).error?
+ assert_empty REDIS.stream_entries("messages").sync
+ end
+ assert_not_requested :post, BW_MESSAGES_URL
+ assert_not_requested :post, "https://api.bandwidth.com/api/v1/oauth2/token"
+ end
+ em :test_http_messages_with_incomplete_oauth_never_send_or_fall_back
+
+ def test_oob_link_sms_failure_is_not_retried
+ media_url = "https://example.com/unsupported"
+ stub_request(:head, media_url).to_return(
+ headers: {"Content-Type" => "application/octet-stream"}
+ )
+ request = stub_request(:post, BW_MESSAGES_URL).to_timeout
+ process_stanza(build_oob_message("+15551234567", "look", media_url))
+ assert_requested request, times: 1
+ assert_equal 1, written.length
+ assert Blather::XMPPNode.parse(written.first.to_xml).error?
+ assert_empty REDIS.stream_entries("messages").sync
+ end
+ em :test_oob_link_sms_failure_is_not_retried
+
+ def test_mm4_fetch_failures_fall_back_before_submission
+ [:timeout, :mime, :size].product([false, true]).each do |failure, group|
+ reset_stanzas!
+ reset_redis!
+ WebMock.reset!
+ REDIS.set("catapult_mm4_flag-+15550000000", "1")
+ REDIS.set("catapult_cred-test@example.com", [
+ "account", "user", "password", "+15550000000", "client", "secret"
+ ])
+ url = "https://example.com/photo.jpg"
+ body = "look #{url}"
+ stub_request(:head, url).to_return(
+ headers: {"Content-Type" => "image/jpeg", "Content-Length" => "10"}
+ )
+ fetch = stub_request(:get, url)
+ case failure
+ when :timeout then fetch.to_timeout
+ when :mime then fetch.to_return(headers: {"Content-Type" => "text/html"})
+ when :size
+ fetch.to_return(headers: {
+ "Content-Type" => "image/jpeg", "Content-Length" => "1000001"
+ })
+ end
+ token = stub_request(
+ :post, "https://api.bandwidth.com/api/v1/oauth2/token"
+ ).to_return(body: JSON.dump(access_token: "token", expires_in: 3600))
+ post = stub_request(:post, BW_MESSAGES_URL).with(
+ headers: {"Authorization" => "Bearer token"},
+ body: hash_including(text: body)
+ ).to_return(status: 201, body: '{"id":"sms-fallback"}')
+ mm4 = Minitest::Mock.new
+ mm4.expect(:send, EMPromise.resolve({"id" => "group-fallback"})) if group
+ message = build_oob_message("+15551234567", body, url)
+ MM4::Message.stub :new, lambda { |**options|
+ assert group
+ assert_equal body, options[:body]
+ assert_empty options[:attachments]
+ mm4
+ } do
+ destination = group ? ["+15551234567", "+15557654321"] : "+15551234567"
+ credentials = BandwidthCredentials.new(
+ ["account", "user", "password", "+15550000000", "client", "secret"]
+ )
+ SGXbwmsgsv2.to_catapult_possible_oob(message, destination, credentials).sync
+ end
+ assert_requested fetch, times: 1
+ group ? assert_not_requested(post) : assert_requested(post, times: 1)
+ group ? assert_not_requested(token) : assert_requested(token, times: 1)
+ assert_mock mm4
+ entries = REDIS.stream_entries("messages").sync
+ assert_equal 1, entries.length
+ assert_equal body, entries.first[:fields]["body"]
+ assert_equal "[]", entries.first[:fields]["media_urls"]
+ end
+ end
+ em :test_mm4_fetch_failures_fall_back_before_submission
+
+ def test_mm4_submission_failure_does_not_fall_back
+ REDIS.set("catapult_mm4_flag-+15550000000", "1")
+ url = "https://example.com/photo.jpg"
+ [:head, :get].each do |method|
+ stub_request(method, url).to_return(
+ headers: {"Content-Type" => "image/jpeg", "Content-Length" => "4"},
+ body: "jpeg"
+ )
+ end
+ mm4 = Minitest::Mock.new
+ mm4.expect(:send, EMPromise.reject(IOError.new("SMTP failed")))
+ MM4::Message.stub :new, mm4 do
+ process_stanza(build_oob_message("+15551234567", "look", url))
+ end
+ assert_mock mm4
+ assert_not_requested :post, BW_MESSAGES_URL
+ assert_equal 1, written.length
+ assert_empty REDIS.stream_entries("messages").sync
+ end
+ em :test_mm4_submission_failure_does_not_fall_back
+
+ def test_http_message_authentication_follows_registration
+ media_url = "https://example.com/photo.jpg"
+ unsupported_url = "https://example.com/unsupported"
+ [
+ build_oob_message("+15551234567", "look", media_url),
+ build_oob_message("+45555555555", "look", media_url),
+ build_oob_message("+15551234567", "look", unsupported_url),
+ build_group_mms("hello", ["+15551234567"]),
+ build_group_mms("hello", ["+15551234567", "+15557654321"]),
+ build_outbound_message("a" * 480, "+15551234567"),
+ build_outbound_message("a" * 481, "+15551234567"),
+ build_outbound_message("界" * 210, "+15551234567"),
+ build_outbound_message("界" * 211, "+15551234567")
+ ].product([false, true]).each do |message, oauth|
+ reset_stanzas!
+ reset_redis!
+ WebMock.reset!
+ credentials = ["account", "user", "password", "+15550000000"]
+ credentials += ["client", "secret"] if oauth
+ REDIS.set("catapult_cred-test@example.com", credentials)
+ stub_request(:head, media_url).with { |r|
+ !r.headers.key?("Authorization")
+ }.to_return(
+ headers: {"Content-Type" => "image/jpeg", "Content-Length" => "500"}
+ )
+ stub_request(:head, unsupported_url).to_timeout
+ token = stub_request(
+ :post, "https://api.bandwidth.com/api/v1/oauth2/token"
+ ).to_return(body: JSON.dump(access_token: "sms-token", expires_in: 3600))
+ authorization = oauth ? "Bearer sms-token" : "Basic dXNlcjpwYXNzd29yZA=="
+ request = stub_request(:post, BW_MESSAGES_URL).with(
+ headers: {"Authorization" => authorization}
+ ).to_return(status: 201, body: '{"id":"message"}')
+ process_stanza(message)
+ assert_requested request, times: 1
+ oauth ? assert_requested(token) : assert_not_requested(token)
+ assert_not_requested :get, media_url
+ assert_empty written
+ assert_equal 1, REDIS.stream_entries("messages").sync.length
+ end
+ end
+ em :test_http_message_authentication_follows_registration
+
+ def test_token_rejection_returns_one_xmpp_error
+ REDIS.set("catapult_cred-test@example.com", [
+ "account", "user", "password", "+15550000000", "client", "secret"
+ ])
+ token = stub_request(
+ :post, "https://api.bandwidth.com/api/v1/oauth2/token"
+ ).to_return(status: 401, body: "private-token-response")
+ process_stanza(
+ build_oob_message("+45555555555", "hello", "https://example.com/file")
+ )
+ assert_requested token, times: 1
+ assert_not_requested :post, BW_MESSAGES_URL
+ assert_equal 1, written.length
+ error = Blather::XMPPNode.parse(written.first.to_xml).find_first("error")
+ assert_equal "internal-server-error", xmpp_error_name(error)
+ assert_equal "Failed to obtain access token: 401 private-token-response",
+ xmpp_error_text(error)
+ assert_empty REDIS.stream_entries("messages").sync
+ end
+ em :test_token_rejection_returns_one_xmpp_error
def test_outbound_when_destination_registration_is_missing_or_legacy
request = stub_request(:post, BW_MESSAGES_URL).with(
@@ -830,6 +1004,9 @@ class ComponentTest < Minitest::Test
def test_mm4_outbound_message_emits_to_stream
REDIS.set("catapult_mm4_flag-+15550000000", "1")
+ REDIS.set("catapult_cred-test@example.com", [
+ "account", "user", "password", "+15550000000", "incomplete-client"
+ ])
message_time = Time.utc(2026, 5, 19, 16, 0, 0)
@@ -903,7 +1080,7 @@ class ComponentTest < Minitest::Test
"other-account", "other-user", "other-password", "+15559999999"
])
creds = [
- "account", "user", "password", "+15550000000", "client", "client-secret"
+ "account", "user", "password", "+15550000000", "incomplete-client"
]
message = Blather::Stanza::Message.new("+15559999999@component", "hello")
message.from = "test@example.com/resource"
I think credentials could have a .messages_api helper just like it has for iris_client to contruct this properly configured for certain creds.
I think you delete everything that calls catapult_creds but don’t actually delete the method? So this kind of dead code could go away.
It looks pretty good overall: did it work when you tried it?
Sure, added.
The only place I see catapult_cred is the fetch_catapult_cred_for method and catapult_cred-<jid> Redis records. Do you mean call_catapult? Registration still uses that against /media to validate credentials.
Yep! I tested SMS and MMS from a Bandwidth number to not a Bandwidth number and received both.
Yes that’s what I meant. Ok, so we still need to get rid of that validate path to remove later. fine
new ticket for that or new commit in this branch?
maybe just a note over on the registration ticket?