Parent: #565
Child ticket: #748
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-rrrpzzxsqrlm
for you to fetch changes up to 8c9a87be9d6b281a010fd66477251e01676e9f7f:
Accept OAuth credentials during registration (2026-10-21 09:45:25 -0600)
Amolith (2):
Separate registration validation from storage
Accept OAuth credentials during registration
sgx-bwmsgsv2.rb | 110 ++++++++++++++++++++++±-------
test/test_component.rb | 200 ++++++++++++++++++++++++++++++++++++++++++++++++++++++±
2 files changed, 278 insertions(+), 32 deletions(-)
diff --git a/sgx-bwmsgsv2.rb b/sgx-bwmsgsv2.rb
index 9bdbdb7..2db99c8 100755
--- a/sgx-bwmsgsv2.rb
+++ b/sgx-bwmsgsv2.rb
@@ -715,9 +715,9 @@ module SGXbwmsgsv2
true
end
- def self.check_then_register(i, *creds)
+ def self.check_then_register(i, creds)
@registration_repo
- .put(i.from, BandwidthCredentials.new(creds))
+ .put(i.from, creds)
.catch_only(RegistrationRepo::Conflict) { |e|
EMPromise.reject([:cancel, 'conflict', e.message])
}.then {
@@ -727,17 +727,81 @@ module SGXbwmsgsv2
def self.creds_from_registration_query(i)
if i.query.find_first("./ns:x", ns: "jabber:x:data")
+ client_id = i.form.field("client_id")&.value
+ client_secret = i.form.field("client_secret")&.value
+ if client_id.to_s.empty? && client_secret.to_s.empty?
+ client_id = client_secret = nil
+ end
[
i.form.field("nick")&.value,
i.form.field("username")&.value,
i.form.field("password")&.value,
- i.form.field("phone")&.value
+ i.form.field("phone")&.value,
+ client_id,
+ client_secret
]
else
[i.nick, i.username, i.password, i.phone]
end
end
+ def self.validate_registration(creds)
+ if creds.client_id || creds.client_secret
+ validate_oauth_registration(creds).then {
+ validate_basic_registration(creds)
+ }
+ else
+ validate_basic_registration(creds)
+ end
+ end
+
+ def self.validate_basic_registration(creds)
+ if [creds.account_id, creds.username, creds.password].any? { |v|
+ v.to_s.empty?
+ }
+ return EMPromise.reject([
+ :modify, 'bad-request', 'Missing registration fields'
+ ])
+ end
+
+ # TODO: find a way to verify the telephone number, too.
+ call_catapult(
+ creds.username,
+ creds.password,
+ :get,
+ "api/v2/users/#{creds.account_id}/media",
+ nil,
+ {'Content-Type' => 'application/json'}
+ ).then { |response|
+ JSON.parse(response)
+ # TODO: confirm response is array - could be empty
+
+ LOG.debug("Registration verify response", response: response.to_s[0..999])
+ }
+ end
+
+ def self.validate_oauth_registration(creds)
+ EMPromise.resolve(nil).then {
+ response = creds.iris_client.create_connection.get(
+ "https://messaging.bandwidth.com/" \
+ "api/v2/users/#{creds.account_id}/media",
+ nil, {'Accept' => 'application/json'}
+ )
+ unless response.status == 200
+ raise BandwidthError.for(response.status, response.body)
+ end
+ unless JSON.parse(response.body).is_a?(Array)
+ next EMPromise.reject([:cancel, 'internal-server-error'])
+ end
+ }.catch_only(ArgumentError) { |e|
+ EMPromise.reject([:modify, 'bad-request', e.message])
+ }.catch_only(BandwidthIris::Errors::GenericError) { |e|
+ EMPromise.reject(BandwidthError.for(e.http_status, e.body.to_s))
+ }.catch_only(Faraday::Error, JSON::ParserError) {
+ EMPromise.reject([:cancel, 'internal-server-error'])
+ }
+ end
+
def self.process_registration(i)
EMPromise.resolve(nil).then {
if i.remove?
@@ -746,37 +810,18 @@ module SGXbwmsgsv2
EMPromise.reject(:done)
end
else
- creds_from_registration_query(i)
+ BandwidthCredentials.new(creds_from_registration_query(i))
end
- }.then { |user_id, api_token, api_secret, phone_num|
- if phone_num && phone_num[0] == '+'
- [user_id, api_token, api_secret, phone_num]
+ }.then { |creds|
+ if creds.tel && creds.tel[0] == '+'
+ creds
else
# TODO: add text re number not (yet) supported
EMPromise.reject([:cancel, 'item-not-found'])
end
- }.then { |user_id, api_token, api_secret, phone_num|
- # TODO: find way to verify #{phone_num}, too
- call_catapult(
- api_token,
- api_secret,
- :get,
- "api/v2/users/#{user_id}/media",
- nil,
- {'Content-Type' => 'application/json'}
- ).then { |response|
- JSON.parse(response)
- # TODO: confirm response is array - could be empty
-
- LOG.debug("Registration verify response", response: response.to_s[0..999])
-
- check_then_register(
- i,
- user_id,
- api_token,
- api_secret,
- phone_num
- )
+ }.then { |creds|
+ validate_registration(creds).then {
+ check_then_register(i, creds)
}
}.catch_only(BandwidthError) { |e|
EMPromise.reject(case e.code
@@ -825,6 +870,13 @@ module SGXbwmsgsv2
required: true, type: :"text-single",
label: 'Phone Number', var: 'phone',
value: existing_number.to_s
+ },
+ {
+ type: :"text-single", label: 'OAuth Client ID', var: 'client_id'
+ },
+ {
+ type: :"text-private",
+ label: 'OAuth Client Secret', var: 'client_secret'
}
]
orig.form.title = 'Register for '\
diff --git a/test/test_component.rb b/test/test_component.rb
index b999f71..4a0f049 100644
--- a/test/test_component.rb
+++ b/test/test_component.rb
@@ -338,13 +338,16 @@ class ComponentTest < Minitest::Test
em :test_ibr_bad_tel
def test_ibr_bad_creds
+ REDIS.rpush(
+ "catapult_cred-test@example.com", "stored-client", "stored-secret"
+ )
stub_request(
:get,
"https://messaging.bandwidth.com/api/v2/users/acct/media"
).with(basic_auth: ["user", "pw"]).to_return(status: 401)
iq = Blather::Stanza::Iq::IBR.new(:set, "component")
- iq.from = "newuser@example.com"
+ iq.from = "test@example.com"
iq.phone = "+15551234567"
iq.nick = "acct"
iq.username = "user"
@@ -358,6 +361,11 @@ class ComponentTest < Minitest::Test
error = stanza.find_first("error")
assert_equal "auth", error["type"]
assert_equal "not-authorized", xmpp_error_name(error)
+ assert_equal(
+ ["account", "user", "password", "+15550000000",
+ "stored-client", "stored-secret"],
+ REDIS.get("catapult_cred-test@example.com").sync
+ )
end
em :test_ibr_bad_creds
@@ -437,6 +445,9 @@ class ComponentTest < Minitest::Test
em :test_ibr_new
def test_ibr_update
+ REDIS.rpush(
+ "catapult_cred-test@example.com", "stored-client", "stored-secret"
+ )
stub_request(
:get,
"https://messaging.bandwidth.com/api/v2/users/acct/media"
@@ -455,7 +466,7 @@ class ComponentTest < Minitest::Test
stanza = Blather::XMPPNode.parse(written.first.to_xml)
refute stanza.error?
assert_equal(
- ["acct", "user", "pw", "+15550000009"],
+ ["acct", "user", "pw", "+15550000009", "stored-client", "stored-secret"],
REDIS.get("catapult_cred-test@example.com").sync
)
assert_equal "test@example.com", REDIS.get("catapult_jid-+15550000009").sync
@@ -574,9 +585,14 @@ class ComponentTest < Minitest::Test
assert stanza.result?
assert stanza.registered?
assert_equal(
- ["nick", "username", "password", "phone"],
+ ["nick", "username", "password", "phone", "client_id", "client_secret"],
stanza.form.fields.map(&:var)
)
+ assert_equal "text-private", stanza.form.field("client_secret").type.to_s
+ ["client_id", "client_secret"].each do |name|
+ assert_empty stanza.form.field(name).value.to_s
+ refute stanza.form.field(name).required?
+ end
assert stanza.instructions
assert stanza.nick
assert stanza.username
@@ -986,3 +1002,181 @@ class ComponentTest < Minitest::Test
end
em :test_error_handler
end
+
+class RegistrationOAuthTest < Minitest::Test
+ MEDIA = "https://messaging.bandwidth.com/api/v2/users/acct/media"
+ TOKEN = "https://api.bandwidth.com/api/v1/oauth2/token"
+ STORED = [
+ "account", "user", "password", "+15550000000", "old-client", "old-secret"
+ ].freeze
+ FIELDS = {
+ "nick" => "acct", "username" => "unvalidated-user",
+ "password" => "unvalidated-password", "phone" => "+15550000009",
+ "client_id" => "new-client", "client_secret" => "new-secret"
+ }.freeze
+
+ def setup
+ reset_stanzas!
+ reset_redis!
+ REDIS.set("catapult_cred-test@example.com", STORED.dup)
+ end
+
+ def test_oauth_validates_submitted_account_and_stores_both_pairs
+ stub_token
+ stub_request(:get, MEDIA).with(
+ basic_auth: ["unvalidated-user", "unvalidated-password"]
+ ).to_return(status: 200, body: "[]")
+ stub_request(:get, MEDIA).with(
+ headers: {
+ "Authorization" => "Bearer registration-token",
+ "Accept" => "application/json"
+ }
+ ).to_return(status: 200, body: "[]")
+ ["new@example.com", "test@example.com"].each do |jid|
+ # Give each registration its own number to avoid a mapping conflict.
+ phone = jid.start_with?("new") ? "+15550000008" : "+15550000009"
+ submit(FIELDS.merge("phone" => phone), jid: jid)
+ assert Blather::XMPPNode.parse(written.last.to_xml).result?
+ assert_equal(
+ ["acct", "unvalidated-user", "unvalidated-password", phone,
+ "new-client", "new-secret"],
+ REDIS.get("catapult_cred-#{jid}").sync
+ )
+ assert_equal jid, REDIS.get("catapult_jid-#{phone}").sync
+ end
+ assert_nil REDIS.get("catapult_jid-+15550000000").sync
+ end
+ em :test_oauth_validates_submitted_account_and_stores_both_pairs
+
+ def test_valid_oauth_does_not_approve_invalid_basic_credentials
+ stub_token
+ stub_request(:get, MEDIA).with(
+ headers: {"Authorization" => "Bearer registration-token"}
+ ).to_return(status: 200, body: "[]")
+ stub_request(:get, MEDIA).with(
+ basic_auth: ["unvalidated-user", "unvalidated-password"]
+ ).to_return(status: 401, body: '{"description":"Access denied"}')
+ ["new@example.com", "test@example.com"].each do |jid|
+ submit(FIELDS, jid: jid)
+ assert_rejected("not-authorized")
+ assert_nil REDIS.get("catapult_cred-new@example.com").sync
+ end
+ end
+ em :test_valid_oauth_does_not_approve_invalid_basic_credentials
+
+ def test_missing_fields_leave_registration_unchanged
+ stub_token
+ stub_request(:get, %r{\Ahttps://messaging.bandwidth.com/api/v2/users/(?:acct)?/media\z}).with(
+ headers: {"Authorization" => "Bearer registration-token"}
+ ).to_return(status: 200, body: "[]")
+ ["client_id", "client_secret", "nick", "username", "password"].each { |name|
+ [nil, ""].each do |value|
+ fields = FIELDS.merge(name => value)
+ fields.delete(name) if value.nil?
+ submit(fields)
+ assert_rejected("bad-request")
+ unless name.start_with?("client_")
+ submit(fields.reject { |field, _| field.start_with?("client_") })
+ assert_rejected("bad-request")
+ end
+ end
+ }
+ ["client_id", "client_secret"].each do |name|
+ submit(FIELDS.merge(name => nil))
+ assert_rejected("bad-request")
+ end
+ end
+ em :test_missing_fields_leave_registration_unchanged
+
+ def test_blank_oauth_uses_basic_and_preserves_stored_oauth
+ ids = [{}, {"client_id" => nil}, {"client_id" => ""}]
+ secrets = [{}, {"client_secret" => nil}, {"client_secret" => ""}]
+ ids.product(secrets, [200, 401]).each do |id, secret, status|
+ reset_redis!
+ REDIS.set("catapult_cred-test@example.com", STORED.dup)
+ WebMock.reset!
+ stub_request(:get, MEDIA).with(
+ basic_auth: ["unvalidated-user", "unvalidated-password"]
+ ).to_return(status: status, body: "[]")
+ fields = FIELDS.reject { |name, _| name.start_with?("client_") }
+ submit(fields.merge(id).merge(secret))
+ if status == 200
+ assert Blather::XMPPNode.parse(written.last.to_xml).result?
+ assert_equal(
+ ["acct", "unvalidated-user", "unvalidated-password",
+ "+15550000009", "old-client", "old-secret"],
+ REDIS.get("catapult_cred-test@example.com").sync
+ )
+ assert_equal "test@example.com",
+ REDIS.get("catapult_jid-+15550000009").sync
+ assert_nil REDIS.get("catapult_jid-+15550000000").sync
+ else
+ assert_rejected("not-authorized")
+ end
+ assert_not_requested :post, TOKEN
+ end
+ end
+ em :test_blank_oauth_uses_basic_and_preserves_stored_oauth
+
+ def test_oauth_failures_never_fall_back_or_change_registration
+ [[TOKEN, 401, "not-authorized"], [TOKEN, 404, "item-not-found"],
+ [MEDIA, 401, "not-authorized"], [MEDIA, 403, "not-acceptable"],
+ [MEDIA, 404, "item-not-found"]].each do |url, status, condition|
+ WebMock.reset!
+ stub_token
+ stub_request(url == TOKEN ? :post : :get, url).to_return(
+ status: status, body: '{"description":"Access denied"}'
+ )
+ submit(FIELDS)
+ assert_rejected(condition)
+ end
+ end
+ em :test_oauth_failures_never_fall_back_or_change_registration
+
+ def test_invalid_media_response_or_transport_failure_does_not_save
+ ["not JSON", "{}", :timeout].each do |response|
+ WebMock.reset!
+ stub_token
+ request = stub_request(:get, MEDIA)
+ if response == :timeout
+ request.to_timeout
+ else
+ request.to_return(status: 200, body: response)
+ end
+ submit(FIELDS)
+ assert_rejected("internal-server-error")
+ end
+ end
+ em :test_invalid_media_response_or_transport_failure_does_not_save
+
+private
+
+ def stub_token
+ stub_request(:post, TOKEN).with(
+ basic_auth: ["new-client", "new-secret"],
+ body: {"grant_type" => "client_credentials"}
+ ).to_return(status: 200, body: {
+ access_token: "registration-token", expires_in: 3600
+ }.to_json)
+ end
+
+ def submit(fields, jid: "test@example.com")
+ reset_stanzas!
+ iq = Blather::Stanza::Iq::IBR.new(:set, "component")
+ iq.from = jid
+ form = Blather::Stanza::X.find_or_create(iq.query)
+ form.type = :submit
+ form.fields = fields.map { |name, value| {var: name, value: value} }
+ process_stanza(Blather::XMPPNode.parse(iq.to_xml))
+ assert_equal 1, written.length
+ end
+
+ def assert_rejected(condition)
+ stanza = Blather::XMPPNode.parse(written.last.to_xml)
+ assert stanza.error?
+ assert_equal condition, xmpp_error_name(stanza.find_first("error"))
+ assert_equal STORED, REDIS.get("catapult_cred-test@example.com").sync
+ assert_equal "test@example.com", REDIS.get("catapult_jid-+15550000000").sync
+ assert_nil REDIS.get("catapult_jid-+15550000009").sync
+ end
+end
You will be sad to learn that this is an extension code path that is never used in practise right now. sgx-jmp and the sgx protocol in general currently assumes we are using the non-form variant of IBR. So we either need to change that or use items from this list blather/lib/blather/stanza/iq/ibr.rb at develop · adhearsion/blather · GitHub
Is there any better call we can make these days just to check “does this token work” ?
I feel a bit like now that we have an object that represents the creds this could even be BandwidthCredentials.fromIbr(i) or similar
also need to get rid of the validation through /media so we can remove call_catapult
The following changes since commit b4823b8105fb1cb8508a0412fb9b3a64905c5f2b:
Merge branch ‘push-ywvlmwxoqmsv’ of https://knot.secluded.site/secluded.site/sgx-bwmsgsv2 (2026-11-04 15:50:05 -0500)
are available in the Git repository at:
https://knot.secluded.site/secluded.site/sgx-bwmsgsv2 push-mzmmszzzzxwn
for you to fetch changes up to 8b65dc7c31fa52127fbd806fc85bb59679e40956:
Register with OAuth credentials (2026-11-17 12:29:38 -0700)
Amolith (2):
Answer registration check failures with errors
Register with OAuth credentials
lib/bandwidth_credentials.rb | 40 ++++++++++++±----
lib/registration_repo.rb | 11 ±—
sgx-bwmsgsv2.rb | 142 ++++++++++++++++++±------------------------------------------
test/property/test_to_catapult.rb | 2 ±
test/test_bandwidth_credentials.rb | 123 ++++++++++++++++++++++++++++++±---------------------
test/test_bandwidth_message.rb | 6 ±-
test/test_bandwidth_tn_options.rb | 2 ±
test/test_component.rb | 270 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++±-----------------------------------------------------
test/test_registration_repo.rb | 112 +++++++++++±------------------------------------
9 files changed, 321 insertions(+), 387 deletions(-)
diff --git a/lib/bandwidth_credentials.rb b/lib/bandwidth_credentials.rb
index d5589db..c7352a1 100644
--- a/lib/bandwidth_credentials.rb
+++ b/lib/bandwidth_credentials.rb
@@ -4,13 +4,31 @@ require "ruby-bandwidth-iris"
require "bandwidth-sdk"
class BandwidthCredentials
- attr_reader :account_id, :username, :password, :tel
- # nil means omitted on writes; an empty string is an explicit replacement.
- attr_reader :client_id, :client_secret
+ # Indicates the account has migrated from Basic to OAuth.
+ OAUTH_PREFIX = "oauth:"
+
+ class IncompleteOAuth < ArgumentError; end
+
+ attr_reader :account_id, :tel
+
+ def self.from_ibr(iq)
+ account_id, client_id, client_secret, tel =
+ if iq.query.find_first("./ns:x", ns: "jabber:x:data")
+ ["nick", "username", "password", "phone"].map { |var|
+ iq.form.field(var)&.value
+ }
+ else
+ [iq.nick, iq.username, iq.password, iq.phone]
+ end
+ new([account_id, "#{OAUTH_PREFIX}#{client_id}", client_secret, tel])
+ end
def initialize(record)
- @account_id, @username, @password, @tel,
- @client_id, @client_secret = record
+ @account_id, @username, @password, @tel = record
+ end
+
+ def to_record
+ [@account_id, @username, @password, @tel]
end
def messages_api
@@ -33,16 +51,18 @@ class BandwidthCredentials
end
def authentication
- unless @client_id || @client_secret
+ unless @username.to_s.start_with?(OAUTH_PREFIX)
return {username: @username, password: @password}
end
+
+ client_id = @username.delete_prefix(OAUTH_PREFIX)
missing = []
- missing << "client_id" if @client_id.to_s.empty?
- missing << "client_secret" if @client_secret.to_s.empty?
+ missing << "client_id" if client_id.empty?
+ missing << "client_secret" if @password.to_s.empty?
unless missing.empty?
- raise ArgumentError, "Missing OAuth #{missing.join(' and ')}"
+ raise IncompleteOAuth, "Missing OAuth #{missing.join(' and ')}"
end
- {client_id: @client_id, client_secret: @client_secret}
+ {client_id: client_id, client_secret: @password}
end
end
diff --git a/lib/registration_repo.rb b/lib/registration_repo.rb
index 73c25bf..7127565 100644
--- a/lib/registration_repo.rb
+++ b/lib/registration_repo.rb
@@ -22,22 +22,13 @@ class RegistrationRepo
def put(jid, credentials)
tel = credentials.tel
+ record = credentials.to_record
EMPromise.all([
REDIS.lrange(cred_key(jid), 0, -1),
REDIS.get(jid_key(tel))
]).then { |(oldcreds, oldjid)|
oldtel = oldcreds[3]
- record = [
- credentials.account_id, credentials.username, credentials.password, tel,
- *oldcreds.drop(4)
- ]
- record[4] = credentials.client_id unless credentials.client_id.nil?
- unless credentials.client_secret.nil?
- # Redis lists cannot store nil; keep the secret in its original slot.
- record[4] ||= ""
- record[5] = credentials.client_secret
- end
next if record == oldcreds && jid.to_s == oldjid.to_s
if oldjid && oldjid.to_s != jid.to_s
diff --git a/sgx-bwmsgsv2.rb b/sgx-bwmsgsv2.rb
index 2e7cc55..c227e50 100755
--- a/sgx-bwmsgsv2.rb
+++ b/sgx-bwmsgsv2.rb
@@ -273,47 +273,6 @@ module SGXbwmsgsv2
true
end
- def self.call_catapult(
- token, secret, m, pth, body=nil,
- head={}, code=[200], respond_with=:body
- )
- LOG.debug "call_catapult", body
- # pth looks like one of:
- # "api/v2/users/#{user_id}/[endpoint_name]"
-
- url_prefix = ''
-
- # TODO: need to make a separate thing for voice.bw.c eventually
- if pth.start_with? 'api/v2/users'
- url_prefix = 'https://messaging.bandwidth.com/'
- end
-
- EM::HttpRequest.new(
- URI.parse(url_prefix + pth), tls: {verify_peer: true}
- ).public_send(
- "a#{m}",
- head: {
- 'Authorization' => [token, secret]
- }.merge(head),
- body: body
- ).then { |http|
- if code.include?(http.response_header.status)
- case respond_with
- when :body
- http.response
- when :headers
- http.response_header
- else
- http
- end
- else
- EMPromise.reject(
- BandwidthError.for(http.response_header.status, http.response)
- )
- end
- }
- end
-
def self.to_catapult_possible_oob(s, num_dest, credentials)
un = s.at("oob|x > oob|url", oob: "jabber:x:oob")
unless un
@@ -715,9 +674,9 @@ module SGXbwmsgsv2
true
end
- def self.check_then_register(i, *creds)
+ def self.save_registration(i, creds)
@registration_repo
- .put(i.from, BandwidthCredentials.new(creds))
+ .put(i.from, creds)
.catch_only(RegistrationRepo::Conflict) { |e|
EMPromise.reject([:cancel, 'conflict', e.message])
}.then {
@@ -725,19 +684,6 @@ module SGXbwmsgsv2
}
end
- def self.creds_from_registration_query(i)
- if i.query.find_first("./ns:x", ns: "jabber:x:data")
- [
- i.form.field("nick")&.value,
- i.form.field("username")&.value,
- i.form.field("password")&.value,
- i.form.field("phone")&.value
- ]
- else
- [i.nick, i.username, i.password, i.phone]
- end
- end
-
def self.process_registration(i)
EMPromise.resolve(nil).then {
if i.remove?
@@ -746,46 +692,43 @@ module SGXbwmsgsv2
EMPromise.reject(:done)
end
else
- creds_from_registration_query(i)
+ BandwidthCredentials.from_ibr(i)
end
- }.then { |user_id, api_token, api_secret, phone_num|
- if phone_num && phone_num[0] == '+'
- [user_id, api_token, api_secret, phone_num]
- else
+ }.then { |creds|
+ unless creds.tel&.start_with?('+')
# TODO: add text re number not (yet) supported
- EMPromise.reject([:cancel, 'item-not-found'])
+ next EMPromise.reject([:cancel, 'item-not-found'])
end
- }.then { |user_id, api_token, api_secret, phone_num|
- # TODO: find way to verify #{phone_num}, too
- call_catapult(
- api_token,
- api_secret,
- :get,
- "api/v2/users/#{user_id}/media",
- nil,
- {'Content-Type' => 'application/json'}
- ).then { |response|
- JSON.parse(response)
- # TODO: confirm response is array - could be empty
- LOG.debug("Registration verify response", response: response.to_s[0..999])
+ # TODO: find way to verify creds.tel, too
+ verify_registration(creds).then { save_registration(i, creds) }
+ }
+ end
- check_then_register(
- i,
- user_id,
- api_token,
- api_secret,
- phone_num
- )
- }
- }.catch_only(BandwidthError) { |e|
- EMPromise.reject(case e.code
- when 401
- [:auth, 'not-authorized', e.to_s]
- when 404
- [:cancel, 'item-not-found', e.to_s]
+ def self.verify_registration(creds)
+ EMPromise.resolve(nil).then {
+ BandwidthIris::Account.get(creds.iris_client)
+ }.catch { |e|
+ EMPromise.reject(case e
+ when BandwidthCredentials::IncompleteOAuth
+ [:modify, 'not-acceptable', e.message]
+ when URI::InvalidURIError
+ [:modify, 'not-acceptable', 'Invalid Account ID']
+ when BandwidthIris::Errors::GenericError
+ case e.http_status
+ when 401, 403 then [:auth, 'not-authorized', e.reason]
+ when 404 then [:cancel, 'item-not-found', e.reason]
+ when 429, 500..599 then [:wait, 'service-unavailable', e.reason]
+ else [:modify, 'not-acceptable', e.reason]
+ end
+ when REXML::ParseException
+ # Iris parses error bodies as XML before checking the status, so a
+ # proxy's HTML or plain-text error page ends up here.
+ [:wait, 'service-unavailable']
else
- [:modify, 'not-acceptable', e.to_s]
+ LOG.error("Registration check failed", error: e)
+ Sentry.capture_exception(e)
+ [:wait, 'internal-server-error']
end)
}
end
@@ -793,12 +736,11 @@ module SGXbwmsgsv2
def self.registration_form(orig, existing_number=nil)
orig.registered = !!existing_number
- # TODO: update "User Id" x2 below (to "accountId"?), and others?
- orig.instructions = "Enter the information from your Account "\
- "page as well as the Phone Number\nin your "\
+ orig.instructions = "Enter your Account ID, the Client ID and "\
+ "Client Secret of an API credential, and the Phone Number\nin your "\
"account you want to use (ie. '+12345678901')"\
- ".\nUser Id is nick, API Token is username, "\
- "API Secret is password, Phone Number is phone"\
+ ".\nAccount ID is nick, Client ID is username, "\
+ "Client Secret is password, Phone Number is phone"\
".\n\nThe source code for this gateway is at "\
"https://gitlab.com/soprani.ca/sgx-bwmsgsv2 ."\
"\nCopyright (C) 2017-2020 Denver Gingerich "\
@@ -811,15 +753,15 @@ module SGXbwmsgsv2
orig.form.fields = [
{
required: true, type: :"text-single",
- label: 'User Id', var: 'nick'
+ label: 'Account ID', var: 'nick'
},
{
required: true, type: :"text-single",
- label: 'API Token', var: 'username'
+ label: 'Client ID', var: 'username'
},
{
required: true, type: :"text-private",
- label: 'API Secret', var: 'password'
+ label: 'Client Secret', var: 'password'
},
{
required: true, type: :"text-single",
@@ -829,8 +771,8 @@ module SGXbwmsgsv2
]
orig.form.title = 'Register for '\
'Soprani.ca Gateway to XMPP - Bandwidth API V2'
- orig.form.instructions = "Enter the details from your Account "\
- "page as well as the Phone Number\nin your "\
+ orig.form.instructions = "Enter your Account ID, the Client ID and "\
+ "Client Secret of an API credential, and the Phone Number\nin your "\
"account you want to use (ie. '+12345678901')"\
".\n\nThe source code for this gateway is at "\
"https://gitlab.com/soprani.ca/sgx-bwmsgsv2 ."\
diff --git a/test/property/test_to_catapult.rb b/test/property/test_to_catapult.rb
index a5dc8b1..d8aac40 100644
--- a/test/property/test_to_catapult.rb
+++ b/test/property/test_to_catapult.rb
@@ -25,7 +25,7 @@ class ToCatapultPropertyTest < Minitest::Test
WebMock.reset!
if oauth
REDIS.set("catapult_cred-test@example.com", [
- "account", "user", "password", "+15550000000", "client", "secret"
+ "account", "oauth:client", "secret", "+15550000000"
])
end
token = stub_request(
diff --git a/test/test_bandwidth_credentials.rb b/test/test_bandwidth_credentials.rb
index b34e44e..e801974 100644
--- a/test/test_bandwidth_credentials.rb
+++ b/test/test_bandwidth_credentials.rb
@@ -4,22 +4,8 @@ require "test_helper"
require "bandwidth_credentials"
class BandwidthCredentialsTest < Minitest::Test
- def test_basic_credentials_are_unchanged
- record = [
- "account", "oauth:example", "oauth:password", "+15551234567"
- ].freeze
- credentials = BandwidthCredentials.new(record)
-
- assert_equal "account", credentials.account_id
- assert_equal "oauth:example", credentials.username
- assert_equal "oauth:password", credentials.password
- assert_equal "+15551234567", credentials.tel
+ def assert_iris_options(credentials, expected)
client = Object.new
- expected = {
- account_id: "account",
- username: "oauth:example",
- password: "oauth:password"
- }
BandwidthIris::Client.stub :new, lambda { |**options|
assert_equal expected, options
client
@@ -28,45 +14,80 @@ class BandwidthCredentialsTest < Minitest::Test
end
end
- def test_appended_oauth_credentials_are_preferred_without_modification
- record = [
- "account", "basic-user", "basic-secret", "+15551234567",
- "oauth:client", "oauth:secret"
- ].freeze
- credentials = BandwidthCredentials.new(record)
-
- assert_equal "account", credentials.account_id
- assert_equal "basic-user", credentials.username
- assert_equal "basic-secret", credentials.password
- assert_equal "+15551234567", credentials.tel
- client = Object.new
- expected = {
- account_id: "account",
- client_id: "oauth:client",
- client_secret: "oauth:secret"
- }
- BandwidthIris::Client.stub :new, lambda { |**options|
- assert_equal expected, options
- client
- } do
- assert_same client, credentials.iris_client
- end
- end
-
- def test_incomplete_or_empty_oauth_credentials_do_not_fall_back
- {
- ["client"] => "Missing OAuth client_secret",
- ["client", ""] => "Missing OAuth client_secret",
- ["", "secret"] => "Missing OAuth client_id",
- ["", ""] => "Missing OAuth client_id and client_secret"
- }.each do |oauth, message|
+ def test_unprefixed_records_use_basic
+ [[], ["client", "client-secret"]].each do |appended|
credentials = BandwidthCredentials.new(
- ["account", "basic-user", "basic-secret", "+15551234567"] + oauth
+ ["account", "user", "pass:oauth:", "+15551234567"] + appended
)
- assert_equal "basic-user", credentials.username
- assert_equal "basic-secret", credentials.password
- error = assert_raises(ArgumentError) { credentials.iris_client }
+
+ assert_equal "account", credentials.account_id
+ assert_equal "+15551234567", credentials.tel
+ assert_iris_options(
+ credentials,
+ {account_id: "account", username: "user", password: "pass:oauth:"}
+ )
+ end
+ end
+
+ def test_prefixed_records_use_oauth_without_the_prefix
+ record = ["account", "oauth:client", "oauth:secret", "+15551234567"].freeze
+ credentials = BandwidthCredentials.new(record)
+
+ assert_equal "account", credentials.account_id
+ assert_equal "+15551234567", credentials.tel
+ assert_equal record, credentials.to_record
+ assert_iris_options(
+ credentials,
+ {
+ account_id: "account", client_id: "client",
+ client_secret: "oauth:secret"
+ }
+ )
+ end
+
+ def test_incomplete_oauth_does_not_fall_back
+ {
+ ["oauth:client", nil] => "Missing OAuth client_secret",
+ ["oauth:client", ""] => "Missing OAuth client_secret",
+ ["oauth:", "secret"] => "Missing OAuth client_id",
+ ["oauth:", nil] => "Missing OAuth client_id and client_secret"
+ }.each do |(username, password), message|
+ credentials = BandwidthCredentials.new(
+ ["account", username, password, "+15551234567"]
+ )
+ error = assert_raises(BandwidthCredentials::IncompleteOAuth) {
+ credentials.iris_client
+ }
assert_equal message, error.message
end
end
+
+ def test_from_ibr_reads_oauth_from_plain_fields
+ iq = Blather::Stanza::Iq::IBR.new(:set, "component")
+ iq.nick = "account"
+ iq.username = "client"
+ iq.password = "secret"
+ iq.phone = "+15551234567"
+
+ assert_equal(
+ ["account", "oauth:client", "secret", "+15551234567"],
+ BandwidthCredentials.from_ibr(iq).to_record
+ )
+ end
+
+ def test_from_ibr_reads_oauth_from_form_fields
+ iq = Blather::Stanza::Iq::IBR.new(:set, "component")
+ iq.username = "plain-client"
+ Blather::Stanza::X.find_or_create(iq.query).fields = [
+ {var: "nick", value: "account"},
+ {var: "username", value: "client"},
+ {var: "password", value: "secret"},
+ {var: "phone", value: "+15551234567"}
+ ]
+
+ assert_equal(
+ ["account", "oauth:client", "secret", "+15551234567"],
+ BandwidthCredentials.from_ibr(iq).to_record
+ )
+ end
end
diff --git a/test/test_bandwidth_message.rb b/test/test_bandwidth_message.rb
index 4c301a4..3a8625a 100644
--- a/test/test_bandwidth_message.rb
+++ b/test/test_bandwidth_message.rb
@@ -86,7 +86,7 @@ class BandwidthMessageTest < Minitest::Test
def test_oauth_reuses_token_within_one_transport_instance
message = BandwidthMessage.new(
"account", BandwidthCredentials.new(
- ["account", "user", "password", nil, "client", "secret"]
+ ["account", "oauth:client", "secret", nil]
).messages_api
)
token = stub_request(
@@ -108,7 +108,7 @@ class BandwidthMessageTest < Minitest::Test
def test_short_lived_tokens_are_used_once_per_submission
message = BandwidthMessage.new(
"account", BandwidthCredentials.new(
- ["account", "user", "password", nil, "client", "secret"]
+ ["account", "oauth:client", "secret", nil]
).messages_api
)
token = stub_request(
@@ -139,7 +139,7 @@ class BandwidthMessageTest < Minitest::Test
].each do |response, exception|
message = BandwidthMessage.new(
"account", BandwidthCredentials.new(
- ["account", "user", "password", nil, "client", "secret"]
+ ["account", "oauth:client", "secret", nil]
).messages_api
)
token = stub_request(
diff --git a/test/test_bandwidth_tn_options.rb b/test/test_bandwidth_tn_options.rb
index 00808be..b56947e 100644
--- a/test/test_bandwidth_tn_options.rb
+++ b/test/test_bandwidth_tn_options.rb
@@ -11,7 +11,7 @@ class BandwidthTNOptionsTest < Minitest::Test
ORDERS = "#{API}/accounts/account_id/tnoptions"
TOKEN_URL = "https://api.bandwidth.com/api/v1/oauth2/token"
OAUTH_RECORD = [
- "account_id", "token", "secret", "+15551234567", "client", "client-secret"
+ "account_id", "oauth:client", "client-secret", "+15551234567"
].freeze
OAUTH_CREDS = BandwidthCredentials.new(OAUTH_RECORD).freeze
diff --git a/test/test_component.rb b/test/test_component.rb
index 1f2b5f8..a322681 100644
--- a/test/test_component.rb
+++ b/test/test_component.rb
@@ -325,98 +325,138 @@ class ComponentTest < Minitest::Test
end
em :test_ibr_bad_tel
- def test_ibr_bad_creds
- stub_request(
- :get,
- "https://messaging.bandwidth.com/api/v2/users/acct/media"
- ).with(basic_auth: ["user", "pw"]).to_return(status: 401)
+ IRIS_ACCOUNT_URL = "https://dashboard.bandwidth.com/v1.0/accounts/acct"
+ TOKEN_URL = "https://api.bandwidth.com/api/v1/oauth2/token"
+ def stub_registration_token(status: 200)
+ stub_request(:post, TOKEN_URL).with(
+ basic_auth: ["client", "secret"]
+ ).to_return(
+ status: status,
+ body: JSON.dump(access_token: "registration-token", expires_in: 3600)
+ )
+ end
+
+ def stub_registration_account(status: 200)
+ stub_registration_token
+ stub_request(:get, IRIS_ACCOUNT_URL).with(
+ headers: {"Authorization" => "Bearer registration-token"}
+ ).to_return(
+ status: status,
+ body: "<AccountResponse><Account><AccountId>acct</AccountId>" \
+ "</Account></AccountResponse>"
+ )
+ end
+
+ def registration_iq(from, phone, client_secret: "secret")
iq = Blather::Stanza::Iq::IBR.new(:set, "component")
- iq.from = "newuser@example.com"
- iq.phone = "+15551234567"
+ iq.from = from
+ iq.phone = phone
iq.nick = "acct"
- iq.username = "user"
- iq.password = "pw"
- process_stanza(iq)
+ iq.username = "client"
+ iq.password = client_secret
+ iq
+ end
+ def assert_registration_error(type, name)
assert_equal 1, written.length
-
stanza = Blather::XMPPNode.parse(written.first.to_xml)
assert stanza.error?
error = stanza.find_first("error")
- assert_equal "auth", error["type"]
- assert_equal "not-authorized", xmpp_error_name(error)
+ assert_equal type, error["type"]
+ assert_equal name, xmpp_error_name(error)
+ error
+ end
+
+ def test_ibr_bad_creds
+ stub_registration_token(status: 401)
+ process_stanza(registration_iq("newuser@example.com", "+15551234567"))
+
+ assert_registration_error "auth", "not-authorized"
+ assert_not_requested :get, IRIS_ACCOUNT_URL
+ refute REDIS.get("catapult_cred-newuser@example.com").sync
end
em :test_ibr_bad_creds
- def test_ibr_number_not_found
- stub_request(
- :get,
- "https://messaging.bandwidth.com/api/v2/users/acct/media"
- ).with(basic_auth: ["user", "pw"]).to_return(status: 404)
+ def test_ibr_creds_for_another_account
+ stub_registration_account(status: 403)
+ process_stanza(registration_iq("newuser@example.com", "+15551234567"))
- iq = Blather::Stanza::Iq::IBR.new(:set, "component")
- iq.from = "newuser@example.com"
- iq.phone = "+15551234567"
- iq.nick = "acct"
- iq.username = "user"
- iq.password = "pw"
- process_stanza(iq)
-
- assert_equal 1, written.length
-
- stanza = Blather::XMPPNode.parse(written.first.to_xml)
- assert stanza.error?
- error = stanza.find_first("error")
- assert_equal "cancel", error["type"]
- assert_equal "item-not-found", xmpp_error_name(error)
+ assert_registration_error "auth", "not-authorized"
+ refute REDIS.get("catapult_cred-newuser@example.com").sync
end
- em :test_ibr_number_not_found
+ em :test_ibr_creds_for_another_account
+
+ def test_ibr_incomplete_creds
+ process_stanza(
+ registration_iq("newuser@example.com", "+15551234567", client_secret: "")
+ )
+
+ error = assert_registration_error "modify", "not-acceptable"
+ assert_equal "Missing OAuth client_secret", xmpp_error_text(error)
+ assert_not_requested :post, TOKEN_URL
+ refute REDIS.get("catapult_cred-newuser@example.com").sync
+ end
+ em :test_ibr_incomplete_creds
+
+ def test_ibr_account_not_found
+ stub_registration_account(status: 404)
+ process_stanza(registration_iq("newuser@example.com", "+15551234567"))
+
+ assert_registration_error "cancel", "item-not-found"
+ end
+ em :test_ibr_account_not_found
def test_ibr_other_error
- stub_request(
- :get,
- "https://messaging.bandwidth.com/api/v2/users/acct/media"
- ).with(basic_auth: ["user", "pw"]).to_return(status: 400)
+ stub_registration_account(status: 400)
+ process_stanza(registration_iq("newuser@example.com", "+15551234567"))
- iq = Blather::Stanza::Iq::IBR.new(:set, "component")
- iq.from = "newuser@example.com"
- iq.phone = "+15551234567"
- iq.nick = "acct"
- iq.username = "user"
- iq.password = "pw"
- process_stanza(iq)
-
- assert_equal 1, written.length
-
- stanza = Blather::XMPPNode.parse(written.first.to_xml)
- assert stanza.error?
- error = stanza.find_first("error")
- assert_equal "modify", error["type"]
- assert_equal "not-acceptable", xmpp_error_name(error)
+ assert_registration_error "modify", "not-acceptable"
end
em :test_ibr_other_error
- def test_ibr_new
- stub_request(
- :get,
- "https://messaging.bandwidth.com/api/v2/users/acct/media"
- ).with(basic_auth: ["user", "pw"]).to_return(status: 200, body: "[]")
+ def test_ibr_check_failures_do_not_shut_down_the_gateway
+ {
+ {status: 503, body: "Service Unavailable"} => "service-unavailable",
+ {status: 503, body: "<Error/>"} => "service-unavailable",
+ {status: 429, body: "<Error/>"} => "service-unavailable",
+ nil => "internal-server-error"
+ }.each do |response, name|
+ reset_stanzas!
+ WebMock.reset!
+ stub_registration_token
+ account = stub_request(:get, IRIS_ACCOUNT_URL)
+ response ? account.to_return(**response) : account.to_timeout
+ process_stanza(registration_iq("newuser@example.com", "+15551234567"))
- iq = Blather::Stanza::Iq::IBR.new(:set, "component")
- iq.from = "test9@example.com"
- iq.phone = "+15550000009"
- iq.nick = "acct"
- iq.username = "user"
- iq.password = "pw"
+ assert_registration_error "wait", name
+ refute REDIS.get("catapult_cred-newuser@example.com").sync
+ end
+ end
+ em :test_ibr_check_failures_do_not_shut_down_the_gateway
+
+ def test_ibr_invalid_account_id
+ stub_registration_token
+ iq = registration_iq("newuser@example.com", "+15551234567")
+ iq.nick = "acct "
process_stanza(iq)
+ error = assert_registration_error "modify", "not-acceptable"
+ assert_equal "Invalid Account ID", xmpp_error_text(error)
+ end
+ em :test_ibr_invalid_account_id
+
+ def test_ibr_new
+ account = stub_registration_account
+ process_stanza(registration_iq("test9@example.com", "+15550000009"))
+
assert_equal 1, written.length
stanza = Blather::XMPPNode.parse(written.first.to_xml)
refute stanza.error?
+ assert_requested account
assert_equal(
- ["acct", "user", "pw", "+15550000009"],
+ ["acct", "oauth:client", "secret", "+15550000009"],
REDIS.get("catapult_cred-test9@example.com").sync
)
assert_equal "test9@example.com", REDIS.get("catapult_jid-+15550000009").sync
@@ -425,25 +465,15 @@ class ComponentTest < Minitest::Test
em :test_ibr_new
def test_ibr_update
- stub_request(
- :get,
- "https://messaging.bandwidth.com/api/v2/users/acct/media"
- ).with(basic_auth: ["user", "pw"]).to_return(status: 200, body: "[]")
-
- iq = Blather::Stanza::Iq::IBR.new(:set, "component")
- iq.from = "test@example.com"
- iq.phone = "+15550000009"
- iq.nick = "acct"
- iq.username = "user"
- iq.password = "pw"
- process_stanza(iq)
+ stub_registration_account
+ process_stanza(registration_iq("test@example.com", "+15550000009"))
assert_equal 1, written.length
stanza = Blather::XMPPNode.parse(written.first.to_xml)
refute stanza.error?
assert_equal(
- ["acct", "user", "pw", "+15550000009"],
+ ["acct", "oauth:client", "secret", "+15550000009"],
REDIS.get("catapult_cred-test@example.com").sync
)
assert_equal "test@example.com", REDIS.get("catapult_jid-+15550000009").sync
@@ -452,26 +482,10 @@ class ComponentTest < Minitest::Test
em :test_ibr_update
def test_ibr_conflict
- stub_request(
- :get,
- "https://messaging.bandwidth.com/api/v2/users/acct/media"
- ).with(basic_auth: ["user", "pw"]).to_return(status: 200, body: "[]")
+ stub_registration_account
+ process_stanza(registration_iq("test2@example.com", "+15550000000"))
- iq = Blather::Stanza::Iq::IBR.new(:set, "component")
- iq.from = "test2@example.com"
- iq.phone = "+15550000000"
- iq.nick = "acct"
- iq.username = "user"
- iq.password = "pw"
- process_stanza(iq)
-
- assert_equal 1, written.length
-
- stanza = Blather::XMPPNode.parse(written.first.to_xml)
- assert stanza.error?
- error = stanza.find_first("error")
- assert_equal "cancel", error["type"]
- assert_equal "conflict", xmpp_error_name(error)
+ error = assert_registration_error "cancel", "conflict"
assert_equal(
"Another user exists for +15550000000",
xmpp_error_text(error)
@@ -495,10 +509,7 @@ class ComponentTest < Minitest::Test
em :test_ibr_remove
def test_ibr_form
- stub_request(
- :get,
- "https://messaging.bandwidth.com/api/v2/users/acct/media"
- ).with(basic_auth: ["user", "pw"]).to_return(status: 200, body: "[]")
+ stub_registration_account
iq = Blather::Stanza::Iq::IBR.new(:set, "component")
iq.from = "formuser@example.com"
@@ -510,11 +521,11 @@ class ComponentTest < Minitest::Test
},
{
var: "username",
- value: "user"
+ value: "client"
},
{
var: "password",
- value: "pw"
+ value: "secret"
},
{
var: "phone",
@@ -524,7 +535,7 @@ class ComponentTest < Minitest::Test
process_stanza(iq)
assert_equal(
- ["acct", "user", "pw", "+15551234567"],
+ ["acct", "oauth:client", "secret", "+15551234567"],
REDIS.get("catapult_cred-formuser@example.com").sync
)
@@ -562,8 +573,11 @@ class ComponentTest < Minitest::Test
assert stanza.result?
assert stanza.registered?
assert_equal(
- ["nick", "username", "password", "phone"],
- stanza.form.fields.map(&:var)
+ [
+ ["nick", "Account ID"], ["username", "Client ID"],
+ ["password", "Client Secret"], ["phone", "Phone Number"]
+ ],
+ stanza.form.fields.map { |field| [field.var, field.label] }
)
assert stanza.instructions
assert stanza.nick
@@ -574,8 +588,8 @@ class ComponentTest < Minitest::Test
end
em :test_ibr_get_form_registered
- def test_ibr_get_form_uses_tel_from_extended_registration
- creds = ["account", "user", "password", "+15550000000", "client", "client-secret"]
+ def test_ibr_get_form_uses_tel_from_oauth_registration
+ creds = ["account", "oauth:client", "client-secret", "+15550000000"]
REDIS.set("catapult_cred-test@example.com", creds)
iq = Blather::Stanza::Iq::IBR.new(:get, "component")
iq.from = "test@example.com"
@@ -588,7 +602,7 @@ class ComponentTest < Minitest::Test
assert_equal "+15550000000", stanza.form.field("phone").value
refute_includes stanza.to_xml, "client-secret"
end
- em :test_ibr_get_form_uses_tel_from_extended_registration
+ em :test_ibr_get_form_uses_tel_from_oauth_registration
def test_port_out_pin
iq = Blather::Stanza::Iq::Command.new(:set, 'component').tap do |iq|
@@ -640,7 +654,9 @@ class ComponentTest < Minitest::Test
em :test_port_out_pin
def test_port_out_pin_with_incomplete_oauth_returns_error_without_panic
- REDIS.rpush("catapult_cred-test@example.com", "client")
+ REDIS.set("catapult_cred-test@example.com", [
+ "account", "oauth:client", "", "+15550000000"
+ ])
iq = Blather::Stanza::Iq::Command.new(:set, "component")
iq.from = "test@example.com/resource"
iq.node = "set-port-out-pin"
@@ -771,9 +787,9 @@ class ComponentTest < Minitest::Test
end
em :test_outbound_message_emits_to_stream
- def test_outbound_sms_uses_oauth_from_extended_registration
+ def test_outbound_sms_uses_oauth_from_oauth_registration
creds = [
- "account", "user", "password", "+15550000000", "client", "client-secret"
+ "account", "oauth:client", "client-secret", "+15550000000"
]
token = stub_request(
:post, "https://api.bandwidth.com/api/v1/oauth2/token"
@@ -802,16 +818,17 @@ class ComponentTest < Minitest::Test
assert_equal 1, entries.length
assert_equal "+15550000000", entries.first[:fields]["from"]
end
- em :test_outbound_sms_uses_oauth_from_extended_registration
+ em :test_outbound_sms_uses_oauth_from_oauth_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|
+ ["oauth:client", nil], ["oauth:", "secret"], ["oauth:client", ""],
+ ["oauth:", ""]
+ ].product([1, 481]).each do |(client_id, client_secret), length|
reset_stanzas!
REDIS.set(
"catapult_cred-test@example.com",
- ["account", "user", "password", "+15550000000"] + oauth
+ ["account", client_id, client_secret, "+15550000000"]
)
message = build_outbound_message("a" * length, "+15551234567")
message.from = "test@example.com/resource"
@@ -846,7 +863,7 @@ class ComponentTest < Minitest::Test
WebMock.reset!
REDIS.set("catapult_mm4_flag-+15550000000", "1")
REDIS.set("catapult_cred-test@example.com", [
- "account", "user", "password", "+15550000000", "client", "secret"
+ "account", "oauth:client", "secret", "+15550000000"
])
url = "https://example.com/photo.jpg"
body = "look #{url}"
@@ -880,7 +897,7 @@ class ComponentTest < Minitest::Test
} do
destination = group ? ["+15551234567", "+15557654321"] : "+15551234567"
credentials = BandwidthCredentials.new(
- ["account", "user", "password", "+15550000000", "client", "secret"]
+ ["account", "oauth:client", "secret", "+15550000000"]
)
SGXbwmsgsv2.to_catapult_possible_oob(message, destination, credentials).sync
end
@@ -934,8 +951,11 @@ class ComponentTest < Minitest::Test
reset_stanzas!
reset_redis!
WebMock.reset!
- credentials = ["account", "user", "password", "+15550000000"]
- credentials += ["client", "secret"] if oauth
+ credentials = if oauth
+ ["account", "oauth:client", "secret", "+15550000000"]
+ else
+ ["account", "user", "password", "+15550000000"]
+ end
REDIS.set("catapult_cred-test@example.com", credentials)
stub_request(:head, media_url).with { |r|
!r.headers.key?("Authorization")
@@ -962,7 +982,7 @@ class ComponentTest < Minitest::Test
def test_token_rejection_returns_one_xmpp_error
REDIS.set("catapult_cred-test@example.com", [
- "account", "user", "password", "+15550000000", "client", "secret"
+ "account", "oauth:client", "secret", "+15550000000"
])
token = stub_request(
:post, "https://api.bandwidth.com/api/v1/oauth2/token"
@@ -1005,7 +1025,7 @@ 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"
+ "account", "oauth:incomplete-client", "", "+15550000000"
])
message_time = Time.utc(2026, 5, 19, 16, 0, 0)
@@ -1074,13 +1094,13 @@ class ComponentTest < Minitest::Test
end
em :test_passthrough_message_emits_to_stream
- def test_passthrough_uses_tel_from_extended_registration
+ def test_passthrough_uses_tel_from_oauth_registration
REDIS.set("catapult_jid-+15559999999", "other@example.com")
REDIS.set("catapult_cred-other@example.com", [
"other-account", "other-user", "other-password", "+15559999999"
])
creds = [
- "account", "user", "password", "+15550000000", "incomplete-client"
+ "account", "oauth:incomplete-client", "", "+15550000000"
]
message = Blather::Stanza::Message.new("+15559999999@component", "hello")
message.from = "test@example.com/resource"
@@ -1095,7 +1115,7 @@ class ComponentTest < Minitest::Test
assert_equal "+15550000000", entries.first[:fields]["owner"]
assert_equal "+15550000000", entries.first[:fields]["from"]
end
- em :test_passthrough_uses_tel_from_extended_registration
+ em :test_passthrough_uses_tel_from_oauth_registration
def test_sentry_captures_handler_exception
captured_exceptions = []
diff --git a/test/test_registration_repo.rb b/test/test_registration_repo.rb
index eae5b3f..61b5452 100644
--- a/test/test_registration_repo.rb
+++ b/test/test_registration_repo.rb
@@ -4,7 +4,7 @@ require "test_helper"
class RegistrationRepoTest < Minitest::Test
BASIC = ["account", "user", "password", "+15550000000"].freeze
- OAUTH = ["client", "client-secret"].freeze
+ OAUTH = ["account", "oauth:client", "client-secret", "+15550000000"].freeze
JID = "test@example.com"
def setup
@@ -18,7 +18,7 @@ class RegistrationRepoTest < Minitest::Test
repo.delete(jid).sync
assert_equal "HERE", REDIS.get("catapult_jid-").sync
- credentials = BandwidthCredentials.new(BASIC.take(3) + ["+15550000009"])
+ credentials = BandwidthCredentials.new(OAUTH.take(3) + ["+15550000009"])
repo.put(jid, credentials).sync
credentials = repo.find(jid).sync
assert_instance_of BandwidthCredentials, credentials
@@ -30,117 +30,57 @@ class RegistrationRepoTest < Minitest::Test
end
em :test_missing_registration_can_be_created_and_deleted
- def test_updates_preserve_oauth_and_telephone_mapping
- [[], OAUTH, ["client"]].each do |oauth|
- ["other-account", "other-user", "other-password", "+15550000009"].each_with_index do |value, index|
+ def test_updates_replace_the_whole_record_and_telephone_mapping
+ appended = BASIC + ["client", "client-secret"]
+ [BASIC, OAUTH, appended].each do |stored|
+ [OAUTH, OAUTH.take(3) + ["+15550000009"]].each do |updated|
reset_redis!
- REDIS.set("catapult_cred-#{JID}", BASIC + oauth)
- updated = BASIC.dup
- updated[index] = value
+ REDIS.set("catapult_cred-#{JID}", stored.dup)
RegistrationRepo.new.put(JID, BandwidthCredentials.new(updated)).sync
- assert_equal updated + oauth, REDIS.get("catapult_cred-#{JID}").sync
+ assert_equal updated, REDIS.get("catapult_cred-#{JID}").sync
assert_equal JID, REDIS.get("catapult_jid-#{updated[3]}").sync
- assert_nil REDIS.get("catapult_jid-#{BASIC[3]}").sync if index == 3
+ if updated[3] != stored[3]
+ assert_nil REDIS.get("catapult_jid-#{stored[3]}").sync
+ end
end
end
end
- em :test_updates_preserve_oauth_and_telephone_mapping
+ em :test_updates_replace_the_whole_record_and_telephone_mapping
- def test_unchanged_registration_preserves_oauth_without_writing
- REDIS.set("catapult_cred-#{JID}", BASIC + OAUTH)
+ def test_unchanged_registration_is_not_rewritten
+ REDIS.set("catapult_cred-#{JID}", OAUTH.dup)
REDIS.stub(:multi, -> { flunk "Unchanged registration must not be rewritten" }) do
- RegistrationRepo.new.put(JID, BandwidthCredentials.new(BASIC)).sync
+ RegistrationRepo.new.put(JID, BandwidthCredentials.new(OAUTH)).sync
end
- assert_equal BASIC + OAUTH, REDIS.get("catapult_cred-#{JID}").sync
+ assert_equal OAUTH, REDIS.get("catapult_cred-#{JID}").sync
end
- em :test_unchanged_registration_preserves_oauth_without_writing
-
- def test_supplied_oauth_fields_replace_only_their_stored_values
- {
- ["new-client", "new-secret"] => ["new-client", "new-secret"],
- ["new-client"] => ["new-client", "client-secret"],
- [nil, "new-secret"] => ["client", "new-secret"],
- [""] => ["", "client-secret"],
- [nil, ""] => ["client", ""],
- ["", ""] => ["", ""]
- }.each do |supplied, expected|
- REDIS.set("catapult_cred-#{JID}", BASIC + OAUTH)
- credentials = BandwidthCredentials.new(BASIC + supplied)
- RegistrationRepo.new.put(JID, credentials).sync
-
- assert_equal BASIC + expected, REDIS.get("catapult_cred-#{JID}").sync
- assert_equal JID, REDIS.get("catapult_jid-#{BASIC[3]}").sync
- REDIS.stub(:multi, lambda { flunk "Repeated OAuth update" }) do
- RegistrationRepo.new.put(JID, credentials).sync
- end
- end
- end
- em :test_supplied_oauth_fields_replace_only_their_stored_values
-
- def test_oauth_fields_can_be_added_to_basic_or_missing_registrations
- [[], BASIC].each do |stored|
- {
- ["new-client", "new-secret"] => ["new-client", "new-secret"],
- ["new-client"] => ["new-client"],
- [nil, "new-secret"] => ["", "new-secret"],
- ["", ""] => ["", ""]
- }.each do |supplied, expected|
- reset_redis!
- REDIS.del("catapult_cred-#{JID}", "catapult_jid-#{BASIC[3]}")
- REDIS.rpush("catapult_cred-#{JID}", *stored) unless stored.empty?
- credentials = BandwidthCredentials.new(BASIC + supplied)
- RegistrationRepo.new.put(JID, credentials).sync
-
- assert_equal BASIC + expected, REDIS.get("catapult_cred-#{JID}").sync
- assert_equal JID, REDIS.get("catapult_jid-#{BASIC[3]}").sync
- end
- end
- end
- em :test_oauth_fields_can_be_added_to_basic_or_missing_registrations
+ em :test_unchanged_registration_is_not_rewritten
def test_conflicting_update_preserves_both_records
- REDIS.set("catapult_cred-#{JID}", BASIC + OAUTH)
REDIS.set("catapult_jid-+15550000009", "other@example.com")
- credentials = BandwidthCredentials.new(
- BASIC.take(3) + ["+15550000009", "new-client", "new-secret"]
- )
+ credentials = BandwidthCredentials.new(OAUTH.take(3) + ["+15550000009"])
assert_raises(RegistrationRepo::Conflict) do
RegistrationRepo.new.put(JID, credentials).sync
end
- assert_equal BASIC + OAUTH, REDIS.get("catapult_cred-#{JID}").sync
+ assert_equal BASIC, REDIS.get("catapult_cred-#{JID}").sync
assert_equal "other@example.com", REDIS.get("catapult_jid-+15550000009").sync
end
em :test_conflicting_update_preserves_both_records
- def test_full_reader_and_deletion_use_original_tel
- [[], OAUTH, ["client"]].each do |oauth|
- REDIS.set("catapult_cred-#{JID}", BASIC + oauth)
- REDIS.set("catapult_jid-#{BASIC[3]}", JID)
+ def test_reader_and_deletion_use_original_tel
+ [BASIC, OAUTH].each do |stored|
+ REDIS.set("catapult_cred-#{JID}", stored.dup)
+ REDIS.set("catapult_jid-#{stored[3]}", JID)
credentials = RegistrationRepo.new.find(JID).sync
assert_instance_of BandwidthCredentials, credentials
- assert_equal "account", credentials.account_id
- assert_equal "user", credentials.username
- assert_equal "password", credentials.password
- assert_equal "+15550000000", credentials.tel
+ assert_equal stored, credentials.to_record
RegistrationRepo.new.delete(JID).sync
assert_nil REDIS.get("catapult_cred-#{JID}").sync
- assert_nil REDIS.get("catapult_jid-#{BASIC[3]}").sync
+ assert_nil REDIS.get("catapult_jid-#{stored[3]}").sync
end
end
- em :test_full_reader_and_deletion_use_original_tel
-
- def test_deletion_uses_tel_from_extended_registration
- REDIS.set("catapult_cred-#{JID}", BASIC + OAUTH)
- REDIS.set("catapult_jid-#{BASIC[3]}", JID)
- REDIS.set("catapult_jid-#{OAUTH[1]}", "other@example.com")
- RegistrationRepo.new.delete(JID).sync
-
- assert_nil REDIS.get("catapult_cred-#{JID}").sync
- assert_nil REDIS.get("catapult_jid-#{BASIC[3]}").sync
- assert_equal "other@example.com", REDIS.get("catapult_jid-#{OAUTH[1]}").sync
- end
- em :test_deletion_uses_tel_from_extended_registration
+ em :test_reader_and_deletion_use_original_tel
end