didww-v3 6.2.1 → 7.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/.github/workflows/tests.yml +8 -6
- data/.rubocop.yml +0 -110
- data/CHANGELOG.md +61 -0
- data/FILTERS.md +36 -12
- data/Gemfile +0 -2
- data/README.md +427 -56
- data/didww-v3.gemspec +11 -8
- data/docs/resource_relationships.md +35 -15
- data/examples/README.md +54 -61
- data/examples/capacity_pools.rb +28 -10
- data/examples/countries.rb +1 -1
- data/examples/did_groups.rb +1 -1
- data/examples/did_reservations.rb +35 -37
- data/examples/did_sms_routing.rb +91 -0
- data/examples/did_trunk_assignment.rb +106 -80
- data/examples/emergency_calling_services.rb +3 -3
- data/examples/emergency_requirements.rb +3 -3
- data/examples/emergency_scenario.rb +11 -11
- data/examples/emergency_verifications.rb +7 -5
- data/examples/exports.rb +1 -1
- data/examples/exports_sms.rb +72 -0
- data/examples/identity_address_proofs.rb +118 -0
- data/examples/includes.rb +65 -0
- data/examples/orders.rb +8 -6
- data/examples/orders_all_item_types.rb +63 -125
- data/examples/orders_emergency.rb +3 -3
- data/examples/{orders_by_sku.rb → orders_sku.rb} +12 -10
- data/examples/prices_download.rb +45 -0
- data/examples/prices_lookup.rb +43 -0
- data/examples/regions.rb +1 -1
- data/examples/sample.pdf +14 -0
- data/examples/sender_id_verifications.rb +63 -0
- data/examples/shared_capacity_groups.rb +44 -35
- data/examples/sms_trunk_groups.rb +71 -0
- data/examples/sms_trunks.rb +84 -0
- data/examples/test_readme.rb +1216 -0
- data/examples/trunks.rb +115 -0
- data/examples/upload_file.rb +44 -0
- data/examples/voice_in_trunk_groups.rb +57 -33
- data/examples/voice_in_trunk_sip_registration.rb +4 -1
- data/examples/voice_out_trunks.rb +11 -1
- data/examples/webhook.rb +51 -0
- data/lib/didww/auth/bearer_middleware.rb +74 -0
- data/lib/didww/auth/memory_store.rb +40 -0
- data/lib/didww/auth/token.rb +45 -0
- data/lib/didww/auth/token_provider.rb +215 -0
- data/lib/didww/base_middleware.rb +7 -8
- data/lib/didww/callback/request_validator.rb +2 -1
- data/lib/didww/client.rb +122 -13
- data/lib/didww/complex_objects/authentication_methods/generic.rb +6 -0
- data/lib/didww/complex_objects/configurations/base.rb +0 -18
- data/lib/didww/complex_objects/configurations/pstn_configuration.rb +0 -4
- data/lib/didww/complex_objects/configurations/sip_configuration.rb +86 -38
- data/lib/didww/complex_objects/emergency_order_item.rb +1 -1
- data/lib/didww/complex_objects/export_filters.rb +72 -6
- data/lib/didww/complex_objects/generic_order_item.rb +15 -0
- data/lib/didww/complex_objects/sms_trunk_configuration.rb +33 -0
- data/lib/didww/complex_objects/sms_trunk_configurations/base.rb +26 -0
- data/lib/didww/complex_objects/sms_trunk_configurations/generic.rb +32 -0
- data/lib/didww/complex_objects/sms_trunk_configurations/http_in.rb +75 -0
- data/lib/didww/complex_objects/sms_trunk_configurations/http_out.rb +35 -0
- data/lib/didww/complex_objects/sms_trunk_configurations/smpp_esme.rb +37 -0
- data/lib/didww/complex_objects/sms_trunk_configurations/smpp_smsc.rb +56 -0
- data/lib/didww/complex_objects/sms_trunk_configurations/sms_to_email.rb +27 -0
- data/lib/didww/errors.rb +103 -0
- data/lib/didww/http.rb +34 -0
- data/lib/didww/prices/lookup_result.rb +37 -0
- data/lib/didww/prices/price.rb +56 -0
- data/lib/didww/prices/price_file.rb +51 -0
- data/lib/didww/prices/service.rb +248 -0
- data/lib/didww/prices/sms_in_price.rb +43 -0
- data/lib/didww/prices/sms_out_price.rb +52 -0
- data/lib/didww/prices/voice_in_price.rb +48 -0
- data/lib/didww/prices/voice_out_price.rb +88 -0
- data/lib/didww/prices.rb +82 -0
- data/lib/didww/resource/address_requirement.rb +13 -3
- data/lib/didww/resource/base.rb +5 -2
- data/lib/didww/resource/concerns/number_types.rb +24 -0
- data/lib/didww/resource/did.rb +42 -3
- data/lib/didww/resource/did_group.rb +12 -1
- data/lib/didww/resource/emergency_calling_service.rb +10 -5
- data/lib/didww/resource/emergency_requirement.rb +27 -14
- data/lib/didww/resource/encrypted_file.rb +19 -6
- data/lib/didww/resource/export.rb +59 -12
- data/lib/didww/resource/identity.rb +9 -4
- data/lib/didww/resource/order.rb +1 -0
- data/lib/didww/resource/proof_type.rb +1 -1
- data/lib/didww/resource/sender_id_verification.rb +114 -0
- data/lib/didww/resource/sms_trunk.rb +76 -0
- data/lib/didww/resource/sms_trunk_group.rb +31 -0
- data/lib/didww/resource/sms_trunk_regenerate_credential.rb +16 -0
- data/lib/didww/resource/voice_in_trunk.rb +24 -1
- data/lib/didww/resource/voice_out_trunk.rb +72 -0
- data/lib/didww/types/ip_addresses.rb +1 -1
- data/lib/didww/types/strings.rb +1 -1
- data/lib/didww/types.rb +3 -1
- data/lib/didww/version.rb +1 -1
- data/lib/didww.rb +7 -0
- metadata +62 -24
- data/examples/identities_and_proofs.rb +0 -67
- data/examples/voice_in_trunks.rb +0 -108
- data/lib/didww/resource/did_group_type.rb +0 -10
- data/lib/didww/resource/exclusive_relationship.rb +0 -54
- data/lib/didww/resource/pop.rb +0 -10
|
@@ -0,0 +1,1216 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
# Runs the code snippets of the gem's README.md against the sandbox, one check
|
|
3
|
+
# per snippet (a snippet of independent statements is split along its comments),
|
|
4
|
+
# and deletes what the checks create, also when a check fails; exports cannot be
|
|
5
|
+
# deleted and an order is canceled while it is pending. Prints
|
|
6
|
+
# "Results: N passed, M failed" and exits 1 when a check fails.
|
|
7
|
+
#
|
|
8
|
+
# Placeholders of the snippets ('YOUR_API_KEY', 'uuid', 'sms-trunk-uuid', ...)
|
|
9
|
+
# are replaced with DIDWW_API_KEY, with resources of the sandbox account or
|
|
10
|
+
# with resources the check creates; changed DIDs and verifications are restored.
|
|
11
|
+
# Snippets written for production run on the sandbox, except the production
|
|
12
|
+
# configuration: it runs on production, read-only, in a process of its own.
|
|
13
|
+
#
|
|
14
|
+
# Created records that DIDWW reviews are printed on lines starting with REVIEW.
|
|
15
|
+
#
|
|
16
|
+
# Optional, a check is skipped with the reason when it is missing:
|
|
17
|
+
# DIDWW_README_PRODUCTION_API_KEY a production API key for the production configuration,
|
|
18
|
+
# used with a read token for reads only
|
|
19
|
+
# DIDWW_README_PROXY_URL an HTTP(S) proxy for the proxy snippets, in place of proxy.example.com
|
|
20
|
+
# actionpack in the bundle, for the Rails webhook controller
|
|
21
|
+
#
|
|
22
|
+
# Usage: DIDWW_API_KEY=your_api_key ruby examples/test_readme.rb
|
|
23
|
+
|
|
24
|
+
require 'bundler/setup'
|
|
25
|
+
require 'didww'
|
|
26
|
+
require 'didww/callback/request_validator' # the Webhook Signature Validation snippet's require
|
|
27
|
+
require 'active_support/cache'
|
|
28
|
+
require 'fileutils'
|
|
29
|
+
require 'logger'
|
|
30
|
+
require 'open3'
|
|
31
|
+
require 'openssl'
|
|
32
|
+
require 'rbconfig'
|
|
33
|
+
require 'securerandom'
|
|
34
|
+
require 'tmpdir'
|
|
35
|
+
|
|
36
|
+
# ActionPack runs the README's Rails controller; without it that check is skipped
|
|
37
|
+
ACTION_PACK = begin
|
|
38
|
+
require 'action_controller'
|
|
39
|
+
require 'rack/mock'
|
|
40
|
+
true
|
|
41
|
+
rescue LoadError
|
|
42
|
+
false
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
API_KEY = ENV.fetch('DIDWW_API_KEY') { abort 'Please set DIDWW_API_KEY' }
|
|
46
|
+
PROXY_URL = ENV.fetch('DIDWW_README_PROXY_URL', nil).presence
|
|
47
|
+
SUFFIX = SecureRandom.hex(4)
|
|
48
|
+
SMS_CONFIGURATIONS = DIDWW::ComplexObject::SmsTrunkConfiguration
|
|
49
|
+
# Shared between checks: the DID the emergency verification check submitted
|
|
50
|
+
CREATED = {}
|
|
51
|
+
|
|
52
|
+
# Stand-in for the README's MyCustomMiddleware: counts the JSON:API requests.
|
|
53
|
+
class MyCustomMiddleware < Faraday::Middleware
|
|
54
|
+
@requests = 0
|
|
55
|
+
|
|
56
|
+
class << self
|
|
57
|
+
attr_accessor :requests
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def call(env)
|
|
61
|
+
self.class.requests += 1
|
|
62
|
+
@app.call(env)
|
|
63
|
+
end
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# The JSON:API connection is built by the first configure of the process, so
|
|
67
|
+
# the README's customize_connection block (Connection Customization) is applied
|
|
68
|
+
# here, on the sandbox instead of production. The other configure calls below
|
|
69
|
+
# change the API key and the mode only.
|
|
70
|
+
DIDWW::Client.configure do |config|
|
|
71
|
+
config.api_key = API_KEY
|
|
72
|
+
config.api_mode = :sandbox
|
|
73
|
+
config.customize_connection do |conn|
|
|
74
|
+
# conn is a JsonApiClient::Connection instance
|
|
75
|
+
conn.use MyCustomMiddleware
|
|
76
|
+
conn.faraday.options.timeout = 30
|
|
77
|
+
conn.faraday.options.open_timeout = 10
|
|
78
|
+
end
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# ─── Helpers ───────────────────────────────────────────────
|
|
82
|
+
|
|
83
|
+
class Skip < StandardError; end
|
|
84
|
+
|
|
85
|
+
RESULTS = { passed: 0, failed: 0, skipped: 0 }
|
|
86
|
+
FAILURES = []
|
|
87
|
+
|
|
88
|
+
def section(title)
|
|
89
|
+
puts "\n== #{title} =="
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
def check(name)
|
|
93
|
+
yield
|
|
94
|
+
RESULTS[:passed] += 1
|
|
95
|
+
puts " ✓ #{name}"
|
|
96
|
+
rescue Skip => e
|
|
97
|
+
RESULTS[:skipped] += 1
|
|
98
|
+
puts " - #{name}: skipped, #{e.message}"
|
|
99
|
+
rescue StandardError => e
|
|
100
|
+
RESULTS[:failed] += 1
|
|
101
|
+
FAILURES << "#{name}: #{e.class}: #{e.message}"
|
|
102
|
+
puts " ✗ #{name}: #{e.class}: #{e.message}"
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
# A snippet that is not run at all
|
|
106
|
+
def skipped(name, reason)
|
|
107
|
+
RESULTS[:skipped] += 1
|
|
108
|
+
puts " - #{name}: skipped, #{reason}"
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
def skip!(reason)
|
|
112
|
+
raise Skip, reason
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
def verify(condition, expectation)
|
|
116
|
+
raise "expected #{expectation}" unless condition
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
def saved!(resource)
|
|
120
|
+
raise "#{resource.class.name.demodulize} not saved: #{resource.errors.full_messages.join('; ')}" unless resource.save
|
|
121
|
+
|
|
122
|
+
resource
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
# Deletes what a check created; a failed delete is printed, not raised, so it
|
|
126
|
+
# does not hide the outcome of the check.
|
|
127
|
+
def destroy_all(*resources)
|
|
128
|
+
resources.compact.select(&:persisted?).each do |resource|
|
|
129
|
+
next if resource.destroy
|
|
130
|
+
|
|
131
|
+
puts " cleanup: #{resource.type} #{resource.id} not deleted: #{resource.errors.full_messages.join('; ')}"
|
|
132
|
+
rescue StandardError => e
|
|
133
|
+
puts " cleanup: #{resource.type} #{resource.id} not deleted: #{e.message}"
|
|
134
|
+
end
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
def first_did
|
|
138
|
+
DIDWW::Client.dids.page(1).per(1).all.first || skip!('no DIDs on the account')
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
# A SKU of a DID group with numbers in stock
|
|
142
|
+
def first_sku
|
|
143
|
+
group = DIDWW::Client.did_groups.where(is_available: true).includes(:stock_keeping_units).all
|
|
144
|
+
.find { |g| g.stock_keeping_units&.any? }
|
|
145
|
+
group&.stock_keeping_units&.first || skip!('no available DID group with stock keeping units')
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
def create_http_in_trunk(name)
|
|
149
|
+
saved!(DIDWW::Client.sms_trunks.new(
|
|
150
|
+
name: "#{name} #{SUFFIX}",
|
|
151
|
+
configuration: SMS_CONFIGURATIONS::HttpIn.new(
|
|
152
|
+
url: 'https://example.com/sms',
|
|
153
|
+
http_method: SMS_CONFIGURATIONS::HttpIn::HTTP_METHOD_GET
|
|
154
|
+
)
|
|
155
|
+
))
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
# Signs a callback the way DIDWW does, see examples/webhook.rb
|
|
159
|
+
def sign_callback(secret, url, payload)
|
|
160
|
+
uri = URI(url)
|
|
161
|
+
normalized_url = "#{uri.scheme}://#{uri.host}:#{uri.port}#{uri.path}"
|
|
162
|
+
normalized_url += "?#{uri.query}" if uri.query
|
|
163
|
+
OpenSSL::HMAC.hexdigest('SHA1', secret, normalized_url + payload.sort.flatten.join)
|
|
164
|
+
end
|
|
165
|
+
|
|
166
|
+
# Runs Ruby code in a new process of this bundle, for a snippet that has to be
|
|
167
|
+
# the first configure of its process. The process inherits DIDWW_API_KEY.
|
|
168
|
+
def run_ruby(code)
|
|
169
|
+
output, status = Open3.capture2e(RbConfig.ruby, '-rbundler/setup', '-e', code)
|
|
170
|
+
error = output.lines.find { |line| line.include?('Error') } || output.lines.last.to_s
|
|
171
|
+
[output, status.success?, error.strip]
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
# An emergency-capable DID of the country that no identity, emergency
|
|
175
|
+
# verification or emergency calling service is bound to yet (a verification
|
|
176
|
+
# binds its DIDs to the identity of its address); when the account has none,
|
|
177
|
+
# one is ordered and the order awaited.
|
|
178
|
+
def emergency_did_in(country)
|
|
179
|
+
candidates = DIDWW::Client.dids
|
|
180
|
+
.where('did_group.features': DIDWW::Resource::DidGroup::FEATURE_EMERGENCY,
|
|
181
|
+
emergency_enabled: false, terminated: false, 'country.id': country.id)
|
|
182
|
+
.includes(:identity, :emergency_verification, :emergency_calling_service)
|
|
183
|
+
.all
|
|
184
|
+
did = candidates.find { |d| d.identity.nil? && d.emergency_verification.nil? && d.emergency_calling_service.nil? }
|
|
185
|
+
return did if did
|
|
186
|
+
|
|
187
|
+
available = DIDWW::Client.available_dids
|
|
188
|
+
.where('did_group.features': DIDWW::Resource::DidGroup::FEATURE_EMERGENCY, 'country.id': country.id)
|
|
189
|
+
.includes('did_group.stock_keeping_units')
|
|
190
|
+
.page(1).per(1)
|
|
191
|
+
.all
|
|
192
|
+
.first
|
|
193
|
+
sku = available&.did_group&.stock_keeping_units&.first
|
|
194
|
+
return nil unless sku
|
|
195
|
+
|
|
196
|
+
order = saved!(DIDWW::Client.orders.new(
|
|
197
|
+
items: [DIDWW::ComplexObject::DidOrderItem.new(available_did_id: available.id, sku_id: sku.id)]
|
|
198
|
+
))
|
|
199
|
+
puts " ordered #{available.number} (order #{order.id})"
|
|
200
|
+
begin
|
|
201
|
+
24.times do # up to 120 s
|
|
202
|
+
break if order.completed?
|
|
203
|
+
|
|
204
|
+
sleep 5
|
|
205
|
+
order = DIDWW::Client.orders.find(order.id).first
|
|
206
|
+
end
|
|
207
|
+
ensure
|
|
208
|
+
# An order that did not complete is canceled, so it allocates no DID later
|
|
209
|
+
cancel_pending(order) unless order.completed?
|
|
210
|
+
end
|
|
211
|
+
raise "order #{order.id} did not complete (#{order.status})" unless order.completed?
|
|
212
|
+
|
|
213
|
+
DIDWW::Client.dids.where('order.id': order.id).all.first
|
|
214
|
+
end
|
|
215
|
+
|
|
216
|
+
# Cancels a pending order; a failure is printed, not raised
|
|
217
|
+
def cancel_pending(order)
|
|
218
|
+
return unless order.pending?
|
|
219
|
+
|
|
220
|
+
puts " cleanup: order #{order.id} not canceled: #{order.errors.full_messages.join('; ')}" unless order.destroy
|
|
221
|
+
rescue StandardError => e
|
|
222
|
+
puts " cleanup: order #{order.id} not canceled: #{e.message}"
|
|
223
|
+
end
|
|
224
|
+
|
|
225
|
+
# ─── Installation ──────────────────────────────────────────
|
|
226
|
+
|
|
227
|
+
section 'Installation'
|
|
228
|
+
|
|
229
|
+
check("Installation: gem 'didww-v3'") do
|
|
230
|
+
spec = Gem.loaded_specs['didww-v3']
|
|
231
|
+
verify(spec, 'the didww-v3 gem in the bundle')
|
|
232
|
+
puts " didww-v3 #{spec.version}"
|
|
233
|
+
end
|
|
234
|
+
|
|
235
|
+
# ─── Quick Start ───────────────────────────────────────────
|
|
236
|
+
|
|
237
|
+
section 'Quick Start'
|
|
238
|
+
|
|
239
|
+
check('Quick Start') do
|
|
240
|
+
DIDWW::Client.configure do |config|
|
|
241
|
+
config.api_key = API_KEY
|
|
242
|
+
config.api_mode = :sandbox
|
|
243
|
+
end
|
|
244
|
+
|
|
245
|
+
# Check balance
|
|
246
|
+
balance = DIDWW::Client.balance
|
|
247
|
+
puts " Balance: #{balance.total_balance}"
|
|
248
|
+
|
|
249
|
+
# List DID groups with stock keeping units
|
|
250
|
+
did_groups = DIDWW::Client.did_groups
|
|
251
|
+
.includes(:stock_keeping_units)
|
|
252
|
+
.where(area_name: 'Acapulco')
|
|
253
|
+
.all
|
|
254
|
+
|
|
255
|
+
puts " DID groups: #{did_groups.count}"
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
# ─── Configuration ─────────────────────────────────────────
|
|
259
|
+
|
|
260
|
+
section 'Configuration'
|
|
261
|
+
|
|
262
|
+
check('Configuration: sandbox') do
|
|
263
|
+
DIDWW::Client.configure do |config|
|
|
264
|
+
config.api_key = API_KEY
|
|
265
|
+
config.api_mode = :sandbox
|
|
266
|
+
end
|
|
267
|
+
verify(DIDWW::Client.api_mode == :sandbox, 'the sandbox mode')
|
|
268
|
+
puts " API #{DIDWW::Client.api_base_url}, token service #{DIDWW::Client.auth_base_url}"
|
|
269
|
+
end
|
|
270
|
+
|
|
271
|
+
check('Configuration: production (read-only)') do
|
|
272
|
+
unless ENV.fetch('DIDWW_README_PRODUCTION_API_KEY', '').present?
|
|
273
|
+
skip!('set DIDWW_README_PRODUCTION_API_KEY to run it on production, read-only')
|
|
274
|
+
end
|
|
275
|
+
|
|
276
|
+
# In a process of its own, so that this script's sandbox configuration is
|
|
277
|
+
# untouched. The key is read there from the environment and never printed;
|
|
278
|
+
# the read scope makes the API refuse any write. Only reads are sent: the
|
|
279
|
+
# token, the balance, the countries and one price lookup.
|
|
280
|
+
output, ok, error = run_ruby(<<~'RUBY')
|
|
281
|
+
require 'didww'
|
|
282
|
+
|
|
283
|
+
# Production
|
|
284
|
+
DIDWW::Client.configure do |config|
|
|
285
|
+
config.api_key = ENV.fetch('DIDWW_README_PRODUCTION_API_KEY')
|
|
286
|
+
config.api_mode = :production
|
|
287
|
+
config.scope = :read # not in the README: a read token, so nothing can be changed
|
|
288
|
+
end
|
|
289
|
+
unless DIDWW::Client.api_base_url == DIDWW::Client::BASE_URLS[:production] &&
|
|
290
|
+
DIDWW::Client.auth_base_url == DIDWW::Client::AUTH_URLS[:production] &&
|
|
291
|
+
DIDWW::Client.prices_base_url(:voice_in) == DIDWW::Client::PRICES_URLS[:voice_in][:production]
|
|
292
|
+
abort 'not the production hosts'
|
|
293
|
+
end
|
|
294
|
+
|
|
295
|
+
scopes = []
|
|
296
|
+
ActiveSupport::Notifications.subscribe('mint_token.didww') { |event| scopes << event.payload[:scope_granted] }
|
|
297
|
+
|
|
298
|
+
abort 'no balance' unless DIDWW::Client.balance
|
|
299
|
+
abort 'the token is not read-only' unless scopes.any? && scopes.all?('read')
|
|
300
|
+
puts 'token_scope=read'
|
|
301
|
+
puts 'balance=read'
|
|
302
|
+
puts "countries=#{DIDWW::Client.countries.all.size}"
|
|
303
|
+
begin
|
|
304
|
+
DIDWW::Client.voice_in_prices.lookup(number: '12125551234')
|
|
305
|
+
puts 'price_lookup=ok'
|
|
306
|
+
rescue DIDWW::Prices::PricePlanNotAssigned, DIDWW::Prices::PriceNotFound => e
|
|
307
|
+
puts "price_lookup=answered #{e.class.name.demodulize}"
|
|
308
|
+
end
|
|
309
|
+
RUBY
|
|
310
|
+
verify(ok, "the production reads to succeed, they failed with: #{error}")
|
|
311
|
+
countries = output[/^countries=(\d+)/, 1].to_i
|
|
312
|
+
price = output[/^price_lookup=(.+)$/, 1]
|
|
313
|
+
verify(output.include?('token_scope=read') && output.include?('balance=read') && countries.positive? && price,
|
|
314
|
+
'a read token, the balance, the countries and a price lookup answer')
|
|
315
|
+
puts " production: token minted (scope read), balance read, #{countries} countries, price lookup #{price}"
|
|
316
|
+
end
|
|
317
|
+
|
|
318
|
+
# Prints the proxy of every JSON:API request; added to the proxy snippets below
|
|
319
|
+
PROXY_PROBE = <<~'RUBY'
|
|
320
|
+
class ProxyProbe < Faraday::Middleware
|
|
321
|
+
def call(env)
|
|
322
|
+
puts "json_api_proxy=#{env.request.proxy&.uri}"
|
|
323
|
+
@app.call(env)
|
|
324
|
+
end
|
|
325
|
+
end
|
|
326
|
+
RUBY
|
|
327
|
+
|
|
328
|
+
check('Connection Customization: proxy') do
|
|
329
|
+
skip!('set DIDWW_README_PROXY_URL to an HTTP(S) proxy to run it') unless PROXY_URL
|
|
330
|
+
|
|
331
|
+
# The snippet on the sandbox, in a new process: the JSON:API connection is
|
|
332
|
+
# built by the first configure of a process
|
|
333
|
+
output, ok, error = run_ruby(<<~'RUBY' + PROXY_PROBE + <<~'PROBE')
|
|
334
|
+
require 'didww'
|
|
335
|
+
|
|
336
|
+
# Using a proxy
|
|
337
|
+
DIDWW::Client.configure do |config|
|
|
338
|
+
config.api_key = ENV.fetch('DIDWW_API_KEY')
|
|
339
|
+
config.api_mode = :sandbox
|
|
340
|
+
config.customize_connection do |conn|
|
|
341
|
+
# conn is a JsonApiClient::Connection instance
|
|
342
|
+
conn.faraday.proxy = ENV.fetch('DIDWW_README_PROXY_URL')
|
|
343
|
+
end
|
|
344
|
+
end
|
|
345
|
+
RUBY
|
|
346
|
+
DIDWW::Resource::Base.connection.use ProxyProbe
|
|
347
|
+
puts "balance=#{DIDWW::Client.balance.total_balance}"
|
|
348
|
+
PROBE
|
|
349
|
+
verify(ok, "the snippet to run, it failed with: #{error}")
|
|
350
|
+
verify(output.include?("json_api_proxy=#{PROXY_URL.chomp('/')}") && output.include?('balance='),
|
|
351
|
+
"the balance request sent through #{PROXY_URL}, got: #{output.strip}")
|
|
352
|
+
puts " balance read through #{PROXY_URL}"
|
|
353
|
+
end
|
|
354
|
+
|
|
355
|
+
check('Connection Customization: custom middleware and timeouts') do
|
|
356
|
+
# Applied by the configure at the top of this script
|
|
357
|
+
before = MyCustomMiddleware.requests
|
|
358
|
+
DIDWW::Client.balance
|
|
359
|
+
options = DIDWW::Resource::Base.connection.faraday.options
|
|
360
|
+
verify(MyCustomMiddleware.requests > before, 'MyCustomMiddleware to see the request')
|
|
361
|
+
verify(options.timeout == 30 && options.open_timeout == 10, 'timeout 30 and open_timeout 10')
|
|
362
|
+
end
|
|
363
|
+
|
|
364
|
+
check('Connection Customization: customize_faraday proxy') do
|
|
365
|
+
skip!('set DIDWW_README_PROXY_URL to an HTTP(S) proxy to run it') unless PROXY_URL
|
|
366
|
+
|
|
367
|
+
# The snippet on the sandbox, in a new process. Its first request mints the
|
|
368
|
+
# token over the token service connection, which customize_faraday sets up.
|
|
369
|
+
output, ok, error = run_ruby(<<~'RUBY' + PROXY_PROBE + <<~'PROBE')
|
|
370
|
+
require 'didww'
|
|
371
|
+
|
|
372
|
+
DIDWW::Client.configure do |config|
|
|
373
|
+
config.api_key = ENV.fetch('DIDWW_API_KEY')
|
|
374
|
+
config.api_mode = :sandbox
|
|
375
|
+
config.customize_connection { |conn| conn.faraday.proxy = ENV.fetch('DIDWW_README_PROXY_URL') }
|
|
376
|
+
config.customize_faraday do |faraday|
|
|
377
|
+
# faraday is a Faraday::Connection instance
|
|
378
|
+
faraday.proxy = ENV.fetch('DIDWW_README_PROXY_URL')
|
|
379
|
+
end
|
|
380
|
+
end
|
|
381
|
+
RUBY
|
|
382
|
+
DIDWW::Resource::Base.connection.use ProxyProbe
|
|
383
|
+
puts "token_service_proxy=#{DIDWW::Http.connection(DIDWW::Client.auth_base_url).proxy&.uri}"
|
|
384
|
+
puts "balance=#{DIDWW::Client.balance.total_balance}"
|
|
385
|
+
PROBE
|
|
386
|
+
verify(ok, "the snippet to run, it failed with: #{error}")
|
|
387
|
+
proxy = PROXY_URL.chomp('/')
|
|
388
|
+
verify(output.include?("token_service_proxy=#{proxy}") && output.include?("json_api_proxy=#{proxy}") &&
|
|
389
|
+
output.include?('balance='),
|
|
390
|
+
"the token and the balance requests sent through #{PROXY_URL}, got: #{output.strip}")
|
|
391
|
+
puts " token minted and balance read through #{PROXY_URL}"
|
|
392
|
+
end
|
|
393
|
+
|
|
394
|
+
check('API Version: with_api_version') do
|
|
395
|
+
countries = DIDWW::Client.with_api_version('2099-01-01') do
|
|
396
|
+
verify(DIDWW::Client.api_version == '2099-01-01', 'the overridden version inside the block')
|
|
397
|
+
DIDWW::Client.countries.all
|
|
398
|
+
end
|
|
399
|
+
puts " #{countries.size} countries with API version 2099-01-01"
|
|
400
|
+
verify(DIDWW::Client.api_version == DIDWW::Client::DEFAULT_API_VERSION, 'the default version after the block')
|
|
401
|
+
|
|
402
|
+
# Not a YYYY-MM-DD date, and earlier than DEFAULT_API_VERSION
|
|
403
|
+
rejected = ['2099-1-1', '2020-01-01'].all? do |version|
|
|
404
|
+
DIDWW::Client.with_api_version(version) { nil }
|
|
405
|
+
false
|
|
406
|
+
rescue ArgumentError
|
|
407
|
+
true
|
|
408
|
+
end
|
|
409
|
+
verify(rejected, 'ArgumentError for a malformed and for an earlier version')
|
|
410
|
+
rescue DIDWW::Auth::InvalidRequest => e
|
|
411
|
+
skip!("the token service does not grant the snippet's version 2099-01-01 (#{e.message})")
|
|
412
|
+
end
|
|
413
|
+
|
|
414
|
+
# ─── Authentication ────────────────────────────────────────
|
|
415
|
+
|
|
416
|
+
section 'Authentication'
|
|
417
|
+
|
|
418
|
+
check('Scope') do
|
|
419
|
+
DIDWW::Client.scope = :read # GET and HEAD only
|
|
420
|
+
puts " balance with a read token: #{DIDWW::Client.balance.total_balance}"
|
|
421
|
+
DIDWW::Client.scope = :full
|
|
422
|
+
DIDWW::Client.scope = nil # the default: scope is not sent, the token service grants full
|
|
423
|
+
ensure
|
|
424
|
+
DIDWW::Client.scope = nil
|
|
425
|
+
end
|
|
426
|
+
|
|
427
|
+
check('Token cache: an ActiveSupport::Cache store') do
|
|
428
|
+
original_store = DIDWW::Client.token_store
|
|
429
|
+
DIDWW::Client.token_store = ActiveSupport::Cache::MemoryStore.new # Rails.cache in the README
|
|
430
|
+
puts " balance with the token in an ActiveSupport::Cache::MemoryStore: #{DIDWW::Client.balance.total_balance}"
|
|
431
|
+
ensure
|
|
432
|
+
DIDWW::Client.token_store = original_store if original_store
|
|
433
|
+
end
|
|
434
|
+
|
|
435
|
+
check('Logging and instrumentation: mint_token.didww') do
|
|
436
|
+
original_store = DIDWW::Client.token_store
|
|
437
|
+
events = []
|
|
438
|
+
logger = Logger.new($stdout) # Rails.logger in the README
|
|
439
|
+
subscriber = ActiveSupport::Notifications.subscribe('mint_token.didww') do |event|
|
|
440
|
+
aud = event.payload[:aud].join(', ')
|
|
441
|
+
if event.payload[:exception]
|
|
442
|
+
logger.warn("DIDWW token mint for #{aud} failed after #{event.duration.round} ms: #{event.payload[:exception].first}")
|
|
443
|
+
else
|
|
444
|
+
logger.info("DIDWW token minted for #{aud} in #{event.duration.round} ms")
|
|
445
|
+
end
|
|
446
|
+
events << event
|
|
447
|
+
end
|
|
448
|
+
DIDWW::Client.token_store = DIDWW::Auth::MemoryStore.new # empty, so the next call mints a token
|
|
449
|
+
DIDWW::Client.balance
|
|
450
|
+
verify(events.any? { |e| Array(e.payload[:aud]).include?(DIDWW::Client::API_AUDIENCE) }, 'a mint_token.didww event for api.didww.com')
|
|
451
|
+
ensure
|
|
452
|
+
ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber
|
|
453
|
+
DIDWW::Client.token_store = original_store if original_store
|
|
454
|
+
end
|
|
455
|
+
|
|
456
|
+
# ─── Read-Only Resources ───────────────────────────────────
|
|
457
|
+
|
|
458
|
+
section 'Read-Only Resources'
|
|
459
|
+
|
|
460
|
+
check('Read-Only Resources: countries') do
|
|
461
|
+
countries = DIDWW::Client.countries.all
|
|
462
|
+
country = DIDWW::Client.countries.find(countries.first.id)
|
|
463
|
+
puts " #{countries.size} countries, found #{country.first.name}"
|
|
464
|
+
end
|
|
465
|
+
|
|
466
|
+
check('Read-Only Resources: regions, cities, areas') do
|
|
467
|
+
regions = DIDWW::Client.regions.all
|
|
468
|
+
cities = DIDWW::Client.cities.all
|
|
469
|
+
areas = DIDWW::Client.areas.all
|
|
470
|
+
puts " #{regions.size} regions, #{cities.size} cities, #{areas.size} areas"
|
|
471
|
+
end
|
|
472
|
+
|
|
473
|
+
check('Read-Only Resources: DID groups by number type') do
|
|
474
|
+
did_groups = DIDWW::Client.did_groups
|
|
475
|
+
.where(number_type: DIDWW::Resource::DidGroup::NUMBER_TYPE_TOLL_FREE)
|
|
476
|
+
.includes(:stock_keeping_units)
|
|
477
|
+
.all
|
|
478
|
+
did_groups.first(3).each do |group|
|
|
479
|
+
puts " #{group.prefix} number_type=#{group.number_type} is_demo=#{group.is_demo} SKUs=#{group.stock_keeping_units&.size}"
|
|
480
|
+
end
|
|
481
|
+
verify(did_groups.all? { |g| g.number_type == DIDWW::Resource::DidGroup::NUMBER_TYPE_TOLL_FREE }, 'toll_free DID groups only')
|
|
482
|
+
end
|
|
483
|
+
|
|
484
|
+
check('Read-Only Resources: available DIDs') do
|
|
485
|
+
available_dids = DIDWW::Client.available_dids
|
|
486
|
+
.includes('did_group.stock_keeping_units')
|
|
487
|
+
.all
|
|
488
|
+
puts " #{available_dids.size} available DIDs"
|
|
489
|
+
end
|
|
490
|
+
|
|
491
|
+
check('Read-Only Resources: public keys') do
|
|
492
|
+
public_keys = DIDWW::Client.public_keys.all
|
|
493
|
+
verify(public_keys.any?, 'public keys')
|
|
494
|
+
puts " #{public_keys.size} public keys"
|
|
495
|
+
end
|
|
496
|
+
|
|
497
|
+
check('Read-Only Resources: address requirements') do
|
|
498
|
+
requirements = DIDWW::Client.address_requirements.all
|
|
499
|
+
puts " #{requirements.size} address requirements"
|
|
500
|
+
end
|
|
501
|
+
|
|
502
|
+
check('Read-Only Resources: balance') do
|
|
503
|
+
balance = DIDWW::Client.balance
|
|
504
|
+
verify(balance, 'the balance')
|
|
505
|
+
puts " total balance #{balance.total_balance}"
|
|
506
|
+
end
|
|
507
|
+
|
|
508
|
+
# ─── DIDs ──────────────────────────────────────────────────
|
|
509
|
+
|
|
510
|
+
section 'DIDs'
|
|
511
|
+
|
|
512
|
+
check('DIDs: list and update') do
|
|
513
|
+
dids = DIDWW::Client.dids.all
|
|
514
|
+
skip!('no DIDs on the account') if dids.empty?
|
|
515
|
+
|
|
516
|
+
did = DIDWW::Client.dids.find(dids.first.id).first
|
|
517
|
+
original_description = did.description
|
|
518
|
+
original_capacity_limit = did.capacity_limit
|
|
519
|
+
begin
|
|
520
|
+
did.description = 'Updated'
|
|
521
|
+
did.capacity_limit = 20
|
|
522
|
+
saved!(did)
|
|
523
|
+
puts " #{did.number}: description=#{did.description} capacity_limit=#{did.capacity_limit}"
|
|
524
|
+
ensure
|
|
525
|
+
restore = DIDWW::Client.dids.find(did.id).first
|
|
526
|
+
restore.description = original_description
|
|
527
|
+
restore.capacity_limit = original_capacity_limit
|
|
528
|
+
saved!(restore)
|
|
529
|
+
end
|
|
530
|
+
end
|
|
531
|
+
|
|
532
|
+
check('DIDs: SMS routing') do
|
|
533
|
+
did = DIDWW::Client.dids.includes(:did_group, :sms_trunk, :sms_trunk_group).all
|
|
534
|
+
.find { |d| Array(d.did_group&.features).include?(DIDWW::Resource::DidGroup::FEATURE_IN_SMS) }
|
|
535
|
+
skip!('no DID with the sms_in feature') unless did
|
|
536
|
+
|
|
537
|
+
original_trunk = did.sms_trunk
|
|
538
|
+
original_group = did.sms_trunk_group
|
|
539
|
+
trunk = nil
|
|
540
|
+
group_member = nil
|
|
541
|
+
group = nil
|
|
542
|
+
routed = false
|
|
543
|
+
begin
|
|
544
|
+
trunk = create_http_in_trunk('README routing')
|
|
545
|
+
group_member = create_http_in_trunk('README routing group member')
|
|
546
|
+
# SMS trunks and SMS trunk groups share one name space
|
|
547
|
+
group = DIDWW::Client.sms_trunk_groups.new(name: "README routing group #{SUFFIX}")
|
|
548
|
+
group.relationships.sms_trunks = [group_member]
|
|
549
|
+
saved!(group)
|
|
550
|
+
|
|
551
|
+
did = DIDWW::Client.dids.find(did.id).first
|
|
552
|
+
did.sms_trunk = DIDWW::Resource::SmsTrunk.load(id: trunk.id)
|
|
553
|
+
routed = true
|
|
554
|
+
saved!(did) # sends sms_trunk and sms_trunk_group: null
|
|
555
|
+
|
|
556
|
+
did.sms_trunk_group = DIDWW::Resource::SmsTrunkGroup.load(id: group.id)
|
|
557
|
+
saved!(did) # sends sms_trunk_group and sms_trunk: null
|
|
558
|
+
|
|
559
|
+
routed_dids = DIDWW::Client.dids.where('sms_trunk.id': trunk.id).all
|
|
560
|
+
current = DIDWW::Client.dids.includes(:sms_trunk, :sms_trunk_group).find(did.id).first
|
|
561
|
+
verify(current.sms_trunk_group&.id == group.id && current.sms_trunk.nil?, 'the DID routed to the group only')
|
|
562
|
+
puts " #{did.number}: routed to the group, #{routed_dids.size} DID(s) left on the trunk"
|
|
563
|
+
ensure
|
|
564
|
+
begin
|
|
565
|
+
if routed
|
|
566
|
+
restore = DIDWW::Resource::Did.load(id: did.id)
|
|
567
|
+
if original_trunk
|
|
568
|
+
restore.sms_trunk = original_trunk
|
|
569
|
+
elsif original_group
|
|
570
|
+
restore.sms_trunk_group = original_group
|
|
571
|
+
else
|
|
572
|
+
restore.sms_trunk = nil
|
|
573
|
+
restore.sms_trunk_group = nil
|
|
574
|
+
end
|
|
575
|
+
saved!(restore)
|
|
576
|
+
end
|
|
577
|
+
ensure
|
|
578
|
+
# Deleting a group also deletes the trunks in it
|
|
579
|
+
group&.persisted? ? destroy_all(group, trunk) : destroy_all(group_member, trunk)
|
|
580
|
+
end
|
|
581
|
+
end
|
|
582
|
+
end
|
|
583
|
+
|
|
584
|
+
# ─── Voice In Trunks ───────────────────────────────────────
|
|
585
|
+
|
|
586
|
+
section 'Voice In Trunks'
|
|
587
|
+
|
|
588
|
+
check('Voice In Trunks: create a SIP trunk') do
|
|
589
|
+
trunk = DIDWW::Client.voice_in_trunks.new(
|
|
590
|
+
name: "My SIP Trunk #{SUFFIX}",
|
|
591
|
+
pop: DIDWW::Resource::VoiceInTrunk::POP_AMS,
|
|
592
|
+
configuration: DIDWW::ComplexObject::SipConfiguration.new(
|
|
593
|
+
username: '{DID}',
|
|
594
|
+
host: 'sip.example.com',
|
|
595
|
+
port: 5060,
|
|
596
|
+
codecs: [
|
|
597
|
+
DIDWW::ComplexObject::SipConfiguration::CODEC_PCMA,
|
|
598
|
+
DIDWW::ComplexObject::SipConfiguration::CODEC_PCMU,
|
|
599
|
+
DIDWW::ComplexObject::SipConfiguration::CODEC_TELEPHONE_EVENT
|
|
600
|
+
],
|
|
601
|
+
ice_mode: DIDWW::ComplexObject::SipConfiguration::ICE_MODE_ACCEPT
|
|
602
|
+
)
|
|
603
|
+
)
|
|
604
|
+
|
|
605
|
+
saved!(trunk)
|
|
606
|
+
verify(trunk.pop == DIDWW::Resource::VoiceInTrunk::POP_AMS, 'pop ams')
|
|
607
|
+
verify(trunk.configuration.codecs == %w[pcma pcmu telephone_event], 'the codecs in the given order')
|
|
608
|
+
puts " created SIP trunk #{trunk.id}"
|
|
609
|
+
ensure
|
|
610
|
+
destroy_all(trunk)
|
|
611
|
+
end
|
|
612
|
+
|
|
613
|
+
check('Voice In Trunks: SIP registration') do
|
|
614
|
+
trunk = DIDWW::Client.voice_in_trunks.new(
|
|
615
|
+
name: "Office (registered) #{SUFFIX}",
|
|
616
|
+
configuration: DIDWW::ComplexObject::SipConfiguration.new.tap do |c|
|
|
617
|
+
c.enabled_sip_registration = true
|
|
618
|
+
c.use_did_in_ruri = true
|
|
619
|
+
c.cnam_lookup = true
|
|
620
|
+
end
|
|
621
|
+
)
|
|
622
|
+
saved!(trunk)
|
|
623
|
+
verify(trunk.configuration.incoming_auth_username.present?, 'a server-generated incoming_auth_username')
|
|
624
|
+
puts ' created with SIP registration, credentials generated'
|
|
625
|
+
|
|
626
|
+
# Disable SIP registration by setting host
|
|
627
|
+
trunk.configuration = DIDWW::ComplexObject::SipConfiguration.new.tap do |c|
|
|
628
|
+
c.host = 'sip.example.com'
|
|
629
|
+
end
|
|
630
|
+
saved!(trunk)
|
|
631
|
+
fresh = DIDWW::Client.voice_in_trunks.find(trunk.id).first
|
|
632
|
+
verify(fresh.configuration.enabled_sip_registration == false, 'SIP registration disabled')
|
|
633
|
+
puts " disabled by setting host: host=#{fresh.configuration.host}"
|
|
634
|
+
ensure
|
|
635
|
+
destroy_all(trunk)
|
|
636
|
+
end
|
|
637
|
+
|
|
638
|
+
# ─── Voice Out Trunks ──────────────────────────────────────
|
|
639
|
+
|
|
640
|
+
section 'Voice Out Trunks'
|
|
641
|
+
|
|
642
|
+
check('Voice Out Trunks: create with credentials_and_ip') do
|
|
643
|
+
trunk = DIDWW::Client.voice_out_trunks.new(
|
|
644
|
+
name: "My Outbound Trunk #{SUFFIX}",
|
|
645
|
+
on_cli_mismatch_action: 'reject_call',
|
|
646
|
+
authentication_method: DIDWW::ComplexObject::AuthenticationMethod::CredentialsAndIp.new(
|
|
647
|
+
allowed_sip_ips: ['203.0.113.0/24']
|
|
648
|
+
),
|
|
649
|
+
codecs: [
|
|
650
|
+
DIDWW::Resource::VoiceOutTrunk::CODEC_OPUS,
|
|
651
|
+
DIDWW::Resource::VoiceOutTrunk::CODEC_PCMA,
|
|
652
|
+
DIDWW::Resource::VoiceOutTrunk::CODEC_TELEPHONE_EVENT
|
|
653
|
+
]
|
|
654
|
+
)
|
|
655
|
+
|
|
656
|
+
saved!(trunk)
|
|
657
|
+
verify(trunk.authentication_method.username.present?, 'a server-generated username')
|
|
658
|
+
verify(trunk.codecs == %w[opus pcma telephone_event], 'the codecs in the given order')
|
|
659
|
+
puts " created voice out trunk #{trunk.id}"
|
|
660
|
+
ensure
|
|
661
|
+
destroy_all(trunk)
|
|
662
|
+
end
|
|
663
|
+
|
|
664
|
+
# ─── SMS Trunks ────────────────────────────────────────────
|
|
665
|
+
|
|
666
|
+
section 'SMS Trunks'
|
|
667
|
+
|
|
668
|
+
check('SMS Trunks: create, update and list') do
|
|
669
|
+
configurations = DIDWW::ComplexObject::SmsTrunkConfiguration
|
|
670
|
+
|
|
671
|
+
trunk = DIDWW::Client.sms_trunks.new(
|
|
672
|
+
name: "Inbound webhook #{SUFFIX}",
|
|
673
|
+
configuration: configurations::HttpIn.new(
|
|
674
|
+
url: 'https://example.com/sms',
|
|
675
|
+
http_method: configurations::HttpIn::HTTP_METHOD_POST,
|
|
676
|
+
body_type: configurations::HttpIn::BODY_TYPE_JSON,
|
|
677
|
+
body: '{"text":"{SMS_TEXT}","from":"{SMS_SRC_ADDR}","to":"{SMS_DST_ADDR}"}'
|
|
678
|
+
)
|
|
679
|
+
)
|
|
680
|
+
saved!(trunk)
|
|
681
|
+
|
|
682
|
+
# On update the configuration type must stay the same; attributes left out keep their values.
|
|
683
|
+
trunk.configuration = configurations::HttpIn.new(url: 'https://example.com/sms/v2')
|
|
684
|
+
saved!(trunk)
|
|
685
|
+
verify(trunk.configuration.url == 'https://example.com/sms/v2', 'the updated url')
|
|
686
|
+
|
|
687
|
+
# List by configuration type, with the group
|
|
688
|
+
trunks = DIDWW::Client.sms_trunks.where('configuration.type': 'http_in,sms_to_email').includes(:sms_trunk_group).all
|
|
689
|
+
verify(trunks.any? { |t| t.id == trunk.id }, 'the created trunk in the list')
|
|
690
|
+
puts " #{trunks.size} http_in / sms_to_email trunks"
|
|
691
|
+
ensure
|
|
692
|
+
destroy_all(trunk)
|
|
693
|
+
end
|
|
694
|
+
|
|
695
|
+
check('SMS Trunks: regenerate credentials') do
|
|
696
|
+
# An smpp_esme trunk, whose system_id and password DIDWW generates
|
|
697
|
+
esme = saved!(DIDWW::Client.sms_trunks.new(
|
|
698
|
+
name: "README ESME #{SUFFIX}",
|
|
699
|
+
configuration: SMS_CONFIGURATIONS::SmppEsme.new(server_location: SMS_CONFIGURATIONS::SERVER_LOCATION_NYC)
|
|
700
|
+
))
|
|
701
|
+
old_password = DIDWW::Client.sms_trunks.find(esme.id).first.configuration.password
|
|
702
|
+
|
|
703
|
+
trunk = DIDWW::Client.sms_trunks.find(esme.id).first
|
|
704
|
+
verify(trunk.regenerate_credentials, 'POST /sms_trunk_regenerate_credentials to succeed')
|
|
705
|
+
trunk = DIDWW::Client.sms_trunks.find(trunk.id).first
|
|
706
|
+
verify(trunk.configuration.password.present? && trunk.configuration.password != old_password, 'a new password')
|
|
707
|
+
puts ' password regenerated'
|
|
708
|
+
ensure
|
|
709
|
+
destroy_all(esme)
|
|
710
|
+
end
|
|
711
|
+
|
|
712
|
+
# ─── SMS Trunk Groups ──────────────────────────────────────
|
|
713
|
+
|
|
714
|
+
section 'SMS Trunk Groups'
|
|
715
|
+
|
|
716
|
+
check('SMS Trunk Groups: create with a trunk') do
|
|
717
|
+
member = create_http_in_trunk('README group member')
|
|
718
|
+
|
|
719
|
+
group = DIDWW::Client.sms_trunk_groups.new(name: "Inbound SMS #{SUFFIX}")
|
|
720
|
+
group.relationships.sms_trunks = [DIDWW::Resource::SmsTrunk.load(id: member.id)]
|
|
721
|
+
saved!(group)
|
|
722
|
+
verify(group.sms_trunks_count == 1, 'sms_trunks_count 1')
|
|
723
|
+
puts " created SMS trunk group #{group.id} with #{group.sms_trunks_count} trunk"
|
|
724
|
+
ensure
|
|
725
|
+
# Deleting a group also deletes the trunks in it
|
|
726
|
+
group&.persisted? ? destroy_all(group) : destroy_all(member)
|
|
727
|
+
end
|
|
728
|
+
|
|
729
|
+
# ─── Sender ID Verifications ───────────────────────────────
|
|
730
|
+
|
|
731
|
+
section 'Sender ID Verifications'
|
|
732
|
+
|
|
733
|
+
check('Sender ID Verifications: route through an SMS trunk and unassign it') do
|
|
734
|
+
verifications = DIDWW::Client.sender_id_verifications
|
|
735
|
+
.where(status: DIDWW::Resource::SenderIdVerification::STATUS_ACTIVE)
|
|
736
|
+
.includes(:sms_trunk)
|
|
737
|
+
.all
|
|
738
|
+
verification = verifications.first
|
|
739
|
+
skip!('no active Sender ID verification; verifications are created outside the API') unless verification
|
|
740
|
+
sending_trunk = DIDWW::Client.sms_trunks.all.find(&:allow_out)
|
|
741
|
+
skip!('no http_out, smpp_esme or smpp_smsc trunk on the account') unless sending_trunk
|
|
742
|
+
|
|
743
|
+
original_trunk = verification.sms_trunk
|
|
744
|
+
begin
|
|
745
|
+
verification.sms_trunk = DIDWW::Resource::SmsTrunk.load(id: sending_trunk.id)
|
|
746
|
+
saved!(verification)
|
|
747
|
+
|
|
748
|
+
verification.sms_trunk = nil # outbound messages stop until a trunk is assigned again
|
|
749
|
+
saved!(verification)
|
|
750
|
+
puts " #{verification.reference}: routed through #{sending_trunk.name}, then unassigned"
|
|
751
|
+
ensure
|
|
752
|
+
restore = DIDWW::Resource::SenderIdVerification.load(id: verification.id)
|
|
753
|
+
restore.sms_trunk = original_trunk
|
|
754
|
+
saved!(restore)
|
|
755
|
+
end
|
|
756
|
+
end
|
|
757
|
+
|
|
758
|
+
# ─── Exports ───────────────────────────────────────────────
|
|
759
|
+
|
|
760
|
+
section 'Exports'
|
|
761
|
+
|
|
762
|
+
check('Exports: create an SMS-Out export') do
|
|
763
|
+
filters = {
|
|
764
|
+
from: '2026-10-01 00:00:00', # inclusive
|
|
765
|
+
to: '2026-10-02 00:00:00', # exclusive
|
|
766
|
+
service_type: DIDWW::ComplexObject::ExportFilters::SERVICE_TYPE_A2P
|
|
767
|
+
}
|
|
768
|
+
sending_trunk = DIDWW::Client.sms_trunks.all.find(&:allow_out)
|
|
769
|
+
filters[:sms_trunk_id] = [sending_trunk.id] if sending_trunk # sent as "sms_trunk.id"
|
|
770
|
+
|
|
771
|
+
export = DIDWW::Client.exports.new(
|
|
772
|
+
export_type: DIDWW::Resource::Export::EXPORT_TYPE_SMS_OUT,
|
|
773
|
+
filters: DIDWW::ComplexObject::ExportFilters.new(filters)
|
|
774
|
+
)
|
|
775
|
+
saved!(export)
|
|
776
|
+
puts " created export #{export.id} (#{export.status})#{' without the sms_trunk_id filter: no sending trunk' unless sending_trunk}"
|
|
777
|
+
end
|
|
778
|
+
|
|
779
|
+
check('Exports: download a completed export') do
|
|
780
|
+
export = DIDWW::Client.exports.where(status: DIDWW::Resource::Export::STATUS_COMPLETED).all.first
|
|
781
|
+
skip!('no completed export on the account yet') unless export
|
|
782
|
+
|
|
783
|
+
file = export.download # binary Tempfile with the gzipped CSV
|
|
784
|
+
csv = export.csv # StringIO with the decompressed CSV
|
|
785
|
+
begin
|
|
786
|
+
verify(file.size.positive?, 'a downloaded file')
|
|
787
|
+
puts " #{export.export_type} export #{export.id}: #{file.size} bytes, columns: #{csv.gets&.strip}"
|
|
788
|
+
ensure
|
|
789
|
+
file.close!
|
|
790
|
+
end
|
|
791
|
+
end
|
|
792
|
+
|
|
793
|
+
# ─── Orders ────────────────────────────────────────────────
|
|
794
|
+
|
|
795
|
+
section 'Orders'
|
|
796
|
+
|
|
797
|
+
check('Orders: order by SKU') do
|
|
798
|
+
sku = first_sku
|
|
799
|
+
order = DIDWW::Client.orders.new(
|
|
800
|
+
items: [
|
|
801
|
+
DIDWW::ComplexObject::DidOrderItem.new(sku_id: sku.id, qty: 2) # 'sku-uuid' in the README
|
|
802
|
+
]
|
|
803
|
+
)
|
|
804
|
+
|
|
805
|
+
# Checked before the order is sent: the item must keep its sku_id and qty
|
|
806
|
+
item = order.as_json_api.dig('attributes', 'items', 0, 'attributes') || {}
|
|
807
|
+
verify(item['sku_id'] == sku.id && item['qty'] == 2, "the Hash item to keep sku_id and qty, it is sent as #{item.to_h}")
|
|
808
|
+
saved!(order)
|
|
809
|
+
puts " order #{order.id}: #{order.status}"
|
|
810
|
+
ensure
|
|
811
|
+
begin
|
|
812
|
+
# cancel it
|
|
813
|
+
if order&.persisted? && order.pending? && !order.destroy
|
|
814
|
+
puts " cleanup: order #{order.id} not canceled: #{order.errors.full_messages.join('; ')}"
|
|
815
|
+
end
|
|
816
|
+
rescue StandardError => e
|
|
817
|
+
puts " cleanup: order #{order.id} not canceled: #{e.message}"
|
|
818
|
+
end
|
|
819
|
+
end
|
|
820
|
+
|
|
821
|
+
# ─── Emergency Services ────────────────────────────────────
|
|
822
|
+
|
|
823
|
+
section 'Emergency Services'
|
|
824
|
+
|
|
825
|
+
check('Emergency Services: requirements') do
|
|
826
|
+
# List emergency requirements with filters
|
|
827
|
+
requirements = DIDWW::Client.emergency_requirements
|
|
828
|
+
.includes(:country)
|
|
829
|
+
.all
|
|
830
|
+
country = requirements.first&.country
|
|
831
|
+
skip!('no emergency requirements') unless country
|
|
832
|
+
|
|
833
|
+
# Filter by country and number type
|
|
834
|
+
requirements = DIDWW::Client.emergency_requirements
|
|
835
|
+
.where('country.id': country.id, number_type: 'local')
|
|
836
|
+
.all
|
|
837
|
+
|
|
838
|
+
requirements.first(3).each do |req|
|
|
839
|
+
puts " #{req.identity_type} / #{req.address_area_level} / #{req.estimate_setup_time} / #{req.requirement_restriction_message}"
|
|
840
|
+
end
|
|
841
|
+
end
|
|
842
|
+
|
|
843
|
+
check('Emergency Services: create an emergency verification') do
|
|
844
|
+
# An address of the account and an emergency-capable DID in its country,
|
|
845
|
+
# as in examples/emergency_scenario.rb
|
|
846
|
+
addresses = DIDWW::Client.addresses.includes(:country).all.select(&:country)
|
|
847
|
+
skip!('no address on the account') if addresses.empty?
|
|
848
|
+
address = nil
|
|
849
|
+
did = nil
|
|
850
|
+
addresses.sort_by { |a| a.verified ? 0 : 1 }.each do |candidate|
|
|
851
|
+
did = emergency_did_in(candidate.country)
|
|
852
|
+
address = candidate
|
|
853
|
+
break if did
|
|
854
|
+
end
|
|
855
|
+
skip!("no emergency-capable DID can be ordered in #{addresses.map { |a| a.country.iso }.uniq.join(', ')}") unless did
|
|
856
|
+
CREATED[:emergency_did_id] = did.id
|
|
857
|
+
|
|
858
|
+
# Create an emergency verification. 'ecs-uuid' of the README is left out, as
|
|
859
|
+
# in examples/emergency_scenario.rb: a DID without an emergency calling
|
|
860
|
+
# service gets one with the verification.
|
|
861
|
+
verification = DIDWW::Client.emergency_verifications.new(
|
|
862
|
+
external_reference_id: "readme-#{SUFFIX}", # 'my-ref-123' in the README
|
|
863
|
+
relationships: {
|
|
864
|
+
address: DIDWW::Resource::Address.load(id: address.id),
|
|
865
|
+
dids: [DIDWW::Resource::Did.load(id: did.id)]
|
|
866
|
+
}
|
|
867
|
+
)
|
|
868
|
+
|
|
869
|
+
if verification.save
|
|
870
|
+
puts " Created: #{verification.id} (status: #{verification.status})"
|
|
871
|
+
else
|
|
872
|
+
puts " Errors: #{verification.errors.full_messages}"
|
|
873
|
+
end
|
|
874
|
+
verify(verification.persisted?, "the emergency verification to be created (#{verification.errors.full_messages.join('; ')})")
|
|
875
|
+
puts "REVIEW emergency_verification #{verification.id} #{verification.reference}"
|
|
876
|
+
end
|
|
877
|
+
|
|
878
|
+
check('Emergency Services: emergency calling services') do
|
|
879
|
+
services = DIDWW::Client.emergency_calling_services
|
|
880
|
+
.includes(:country, :dids)
|
|
881
|
+
.all
|
|
882
|
+
|
|
883
|
+
services.first(3).each do |svc|
|
|
884
|
+
puts " #{svc.name} — #{svc.status} (#{svc.number_type})"
|
|
885
|
+
end
|
|
886
|
+
puts " #{services.size} emergency calling services"
|
|
887
|
+
end
|
|
888
|
+
|
|
889
|
+
check('Emergency Services: cancel an emergency calling service') do
|
|
890
|
+
# A service that is not canceled, active first. Another service than the one
|
|
891
|
+
# of the DID submitted above is preferred; that one is the fallback, and
|
|
892
|
+
# canceling it on the sandbox also rejects the test verification.
|
|
893
|
+
# Read per status on the server: canceled services can fill the first pages.
|
|
894
|
+
ecs_class = DIDWW::Resource::EmergencyCallingService
|
|
895
|
+
services = (ecs_class::STATUSES - [ecs_class::STATUS_CANCELED]).flat_map do |status|
|
|
896
|
+
DIDWW::Client.emergency_calling_services.where(status: status).includes(:dids).page(1).per(10).all.to_a
|
|
897
|
+
end
|
|
898
|
+
service = services.min_by do |s|
|
|
899
|
+
[Array(s.dids).any? { |d| d.id == CREATED[:emergency_did_id] } ? 1 : 0,
|
|
900
|
+
s.status == DIDWW::Resource::EmergencyCallingService::STATUS_ACTIVE ? 0 : 1]
|
|
901
|
+
end
|
|
902
|
+
skip!('no emergency calling service that is not canceled') unless service
|
|
903
|
+
|
|
904
|
+
# Cancel (destroy) an emergency calling service
|
|
905
|
+
svc = DIDWW::Client.emergency_calling_services.find(service.id).first
|
|
906
|
+
verify(svc.destroy, "the cancel to succeed (#{svc.errors.full_messages.join('; ')})")
|
|
907
|
+
|
|
908
|
+
begin
|
|
909
|
+
after = DIDWW::Client.emergency_calling_services.find(service.id).first
|
|
910
|
+
verify(after.status == DIDWW::Resource::EmergencyCallingService::STATUS_CANCELED || after.canceled_at,
|
|
911
|
+
"the service to be canceled, it is #{after.status}")
|
|
912
|
+
puts " #{service.reference} (#{service.status}) canceled: status #{after.status}, canceled_at #{after.canceled_at}"
|
|
913
|
+
rescue JsonApiClient::Errors::NotFound
|
|
914
|
+
puts " #{service.reference} (#{service.status}) canceled and no longer listed"
|
|
915
|
+
end
|
|
916
|
+
end
|
|
917
|
+
|
|
918
|
+
# ─── DID History ───────────────────────────────────────────
|
|
919
|
+
|
|
920
|
+
section 'DID History'
|
|
921
|
+
|
|
922
|
+
check('DID History') do
|
|
923
|
+
# List recent DID history events (retained for the last 90 days)
|
|
924
|
+
events = DIDWW::Client.did_history.all
|
|
925
|
+
|
|
926
|
+
events.first(3).each do |event|
|
|
927
|
+
puts " #{event.created_at.iso8601} #{event.did_number} #{event.action} via #{event.method}"
|
|
928
|
+
end
|
|
929
|
+
|
|
930
|
+
# Filter by action
|
|
931
|
+
assigned = DIDWW::Client.did_history
|
|
932
|
+
.where(action: DIDWW::Resource::DidHistory::ACTION_ASSIGNED)
|
|
933
|
+
.all
|
|
934
|
+
|
|
935
|
+
# Filter by DID number
|
|
936
|
+
per_number = DIDWW::Client.did_history
|
|
937
|
+
.where(did_number: '12125551234')
|
|
938
|
+
.all
|
|
939
|
+
|
|
940
|
+
# Filter by date range
|
|
941
|
+
seven_days_ago = (Time.now - 7 * 24 * 60 * 60).iso8601
|
|
942
|
+
recent = DIDWW::Client.did_history
|
|
943
|
+
.where(created_at_gteq: seven_days_ago)
|
|
944
|
+
.all
|
|
945
|
+
puts " #{events.size} events, #{assigned.size} assigned, #{per_number.size} for 12125551234, #{recent.size} in 7 days"
|
|
946
|
+
end
|
|
947
|
+
|
|
948
|
+
# ─── Prices ────────────────────────────────────────────────
|
|
949
|
+
|
|
950
|
+
section 'Prices'
|
|
951
|
+
|
|
952
|
+
check('Prices: lookups') do
|
|
953
|
+
lookups = {
|
|
954
|
+
'Voice IN' => -> { DIDWW::Client.voice_in_prices.lookup(number: '18005550123', src_country_iso: 'US') },
|
|
955
|
+
'Voice OUT' => -> { DIDWW::Client.voice_out_prices.lookup(number: '493012345678') },
|
|
956
|
+
'SMS OUT A2P' => -> { DIDWW::Client.sms_out_a2p_prices.lookup(dst_number: '4915123456789') },
|
|
957
|
+
'SMS IN' => -> { DIDWW::Client.sms_in_prices.lookup(dst_country_iso: 'US') }
|
|
958
|
+
}
|
|
959
|
+
answered = lookups.count do |name, lookup|
|
|
960
|
+
result = lookup.call
|
|
961
|
+
price = result.first
|
|
962
|
+
detail = name == 'Voice OUT' ? "category #{price&.category}" : "#{result.total_records} price(s)"
|
|
963
|
+
puts " #{name}: #{detail}"
|
|
964
|
+
true
|
|
965
|
+
rescue DIDWW::Prices::PricePlanNotAssigned, DIDWW::Prices::PriceNotFound => e
|
|
966
|
+
puts " #{name}: #{e.class.name.demodulize} (#{e.message})"
|
|
967
|
+
false
|
|
968
|
+
end
|
|
969
|
+
skip!('no price plan or price for any of the lookups') if answered.zero?
|
|
970
|
+
end
|
|
971
|
+
|
|
972
|
+
check('Prices: price files') do
|
|
973
|
+
dir = Dir.mktmpdir('didww-readme')
|
|
974
|
+
begin
|
|
975
|
+
prices = DIDWW::Client.voice_out_prices
|
|
976
|
+
path = File.join(dir, 'voice_out_prices.csv.gz')
|
|
977
|
+
|
|
978
|
+
# Download unless the copy at the path is current
|
|
979
|
+
file = prices.fetch(path)
|
|
980
|
+
puts " fetch: modified=#{file.modified?} last_modified=#{file.last_modified} #{file.bytes_written} bytes"
|
|
981
|
+
|
|
982
|
+
# Read the rows
|
|
983
|
+
rows = 0
|
|
984
|
+
DIDWW::Prices.each_row(path) do |row|
|
|
985
|
+
rows += 1
|
|
986
|
+
puts " #{row['Prefix']}: #{row['Rate']}" if rows <= 2
|
|
987
|
+
end
|
|
988
|
+
verify(rows.positive?, 'rows in the price file')
|
|
989
|
+
|
|
990
|
+
# Lower-level calls
|
|
991
|
+
status = prices.head(if_modified_since: file.last_modified)
|
|
992
|
+
puts " head: not_modified=#{status.not_modified?} content_length=#{status.content_length} filename=#{status.filename}"
|
|
993
|
+
|
|
994
|
+
prices.download(to: File.join(dir, 'voice_out_prices_2.csv.gz'))
|
|
995
|
+
File.open(File.join(dir, 'copy.csv.gz'), 'wb') { |io| prices.download(to: io) }
|
|
996
|
+
verify(File.size(File.join(dir, 'copy.csv.gz')).positive?, 'a download into an IO')
|
|
997
|
+
rescue DIDWW::Prices::PricePlanNotAssigned => e
|
|
998
|
+
skip!("no Voice OUT price plan on the account (#{e.message})")
|
|
999
|
+
rescue DIDWW::Prices::ServiceUnavailable => e
|
|
1000
|
+
skip!("the price file is not available yet, retry in #{e.retry_after.inspect} s")
|
|
1001
|
+
ensure
|
|
1002
|
+
FileUtils.remove_entry(dir)
|
|
1003
|
+
end
|
|
1004
|
+
end
|
|
1005
|
+
|
|
1006
|
+
# ─── Error Handling ────────────────────────────────────────
|
|
1007
|
+
|
|
1008
|
+
section 'Error Handling'
|
|
1009
|
+
|
|
1010
|
+
check('Error Handling: validation errors') do
|
|
1011
|
+
# Validation errors (422 Unprocessable Entity)
|
|
1012
|
+
trunk = DIDWW::Client.voice_in_trunks.new(
|
|
1013
|
+
name: "README invalid #{SUFFIX}",
|
|
1014
|
+
ringing_timeout: 100, # more than the allowed 32 seconds
|
|
1015
|
+
configuration: DIDWW::ComplexObject::SipConfiguration.new(host: 'sip.example.com')
|
|
1016
|
+
)
|
|
1017
|
+
unless trunk.save
|
|
1018
|
+
trunk.errors.full_messages.each do |msg|
|
|
1019
|
+
puts " Validation error: #{msg}"
|
|
1020
|
+
end
|
|
1021
|
+
end
|
|
1022
|
+
verify(!trunk.persisted? && trunk.errors.any?, 'the trunk to be refused with validation errors')
|
|
1023
|
+
ensure
|
|
1024
|
+
destroy_all(trunk)
|
|
1025
|
+
end
|
|
1026
|
+
|
|
1027
|
+
check('Error Handling: HTTP errors') do
|
|
1028
|
+
rescued = nil
|
|
1029
|
+
# HTTP errors
|
|
1030
|
+
begin
|
|
1031
|
+
DIDWW::Client.dids.find(SecureRandom.uuid) # 'nonexistent-uuid' in the README
|
|
1032
|
+
rescue JsonApiClient::Errors::NotFound => e
|
|
1033
|
+
puts " Not found: #{e.message}"
|
|
1034
|
+
rescued = :not_found
|
|
1035
|
+
rescue JsonApiClient::Errors::NotAuthorized => e
|
|
1036
|
+
puts " Token refused twice: #{e.message}"
|
|
1037
|
+
rescue JsonApiClient::Errors::AccessDenied => e
|
|
1038
|
+
puts " Access denied (e.g. a write with a read token): #{e.message}"
|
|
1039
|
+
rescue JsonApiClient::Errors::TooManyRequests => e
|
|
1040
|
+
puts " Rate limited, retry in #{e.retry_after.inspect} s: #{e.message}"
|
|
1041
|
+
rescue JsonApiClient::Errors::ServerError => e
|
|
1042
|
+
puts " Server error: #{e.message}"
|
|
1043
|
+
rescue JsonApiClient::Errors::ConnectionError => e
|
|
1044
|
+
puts " Connection error: #{e.message}"
|
|
1045
|
+
rescue DIDWW::Auth::Error => e
|
|
1046
|
+
puts " No access token: #{e.message} (status #{e.status}, retry after #{e.retry_after.inspect})"
|
|
1047
|
+
end
|
|
1048
|
+
verify(rescued == :not_found, 'JsonApiClient::Errors::NotFound for an unknown DID')
|
|
1049
|
+
end
|
|
1050
|
+
|
|
1051
|
+
# ─── Dirty Tracking ────────────────────────────────────────
|
|
1052
|
+
|
|
1053
|
+
section 'Dirty Tracking'
|
|
1054
|
+
|
|
1055
|
+
check('Dirty Tracking: PATCH sends only the changed attributes') do
|
|
1056
|
+
did = DIDWW::Client.dids.find(first_did.id).first
|
|
1057
|
+
original_description = did.description
|
|
1058
|
+
begin
|
|
1059
|
+
# A value equal to the current one is not a change, so it must differ
|
|
1060
|
+
did.description = original_description == 'Updated' ? 'Updated again' : 'Updated'
|
|
1061
|
+
sent = did.as_json_api['attributes'].keys
|
|
1062
|
+
verify(sent == ['description'], "only description in the PATCH payload, got #{sent}")
|
|
1063
|
+
saved!(did)
|
|
1064
|
+
ensure
|
|
1065
|
+
restore = DIDWW::Client.dids.find(did.id).first
|
|
1066
|
+
restore.description = original_description
|
|
1067
|
+
saved!(restore)
|
|
1068
|
+
end
|
|
1069
|
+
end
|
|
1070
|
+
|
|
1071
|
+
# ─── Date and Datetime Fields ──────────────────────────────
|
|
1072
|
+
|
|
1073
|
+
section 'Date and Datetime Fields'
|
|
1074
|
+
|
|
1075
|
+
check('Date and Datetime Fields') do
|
|
1076
|
+
did = DIDWW::Client.dids.find(first_did.id).first
|
|
1077
|
+
verify(did.created_at.is_a?(Time), 'Did#created_at as a Time')
|
|
1078
|
+
verify(did.expires_at.nil? || did.expires_at.is_a?(Time), 'Did#expires_at as nil or a Time')
|
|
1079
|
+
puts " created_at=#{did.created_at} expires_at=#{did.expires_at.inspect}"
|
|
1080
|
+
|
|
1081
|
+
identity = DIDWW::Client.identities.page(1).per(1).all.first
|
|
1082
|
+
if identity
|
|
1083
|
+
identity = DIDWW::Client.identities.find(identity.id).first
|
|
1084
|
+
verify(identity.birth_date.nil? || identity.birth_date.is_a?(String), 'Identity#birth_date as nil or a String')
|
|
1085
|
+
puts " birth_date=#{identity.birth_date.inspect}"
|
|
1086
|
+
else
|
|
1087
|
+
puts ' no identity on the account, birth_date not checked'
|
|
1088
|
+
end
|
|
1089
|
+
end
|
|
1090
|
+
|
|
1091
|
+
# ─── Webhook Signature Validation ──────────────────────────
|
|
1092
|
+
|
|
1093
|
+
section 'Webhook Signature Validation'
|
|
1094
|
+
|
|
1095
|
+
check('Webhook Signature Validation') do
|
|
1096
|
+
# require 'didww/callback/request_validator' is at the top of this file
|
|
1097
|
+
validator = DIDWW::Callback::RequestValidator.new('YOUR_CALLBACK_SECRET')
|
|
1098
|
+
|
|
1099
|
+
request_url = 'https://example.com/webhooks/didww'
|
|
1100
|
+
payload_params = { 'id' => SecureRandom.uuid, 'type' => 'orders', 'status' => 'completed' }
|
|
1101
|
+
signature = sign_callback('YOUR_CALLBACK_SECRET', request_url, payload_params)
|
|
1102
|
+
|
|
1103
|
+
# In your webhook handler:
|
|
1104
|
+
valid = validator.validate(
|
|
1105
|
+
request_url, # full original URL
|
|
1106
|
+
payload_params, # Hash of payload key-value pairs
|
|
1107
|
+
signature # value of X-DIDWW-Signature header
|
|
1108
|
+
)
|
|
1109
|
+
verify(valid == true, 'a valid signature to validate')
|
|
1110
|
+
verify(validator.validate(request_url, payload_params.merge('status' => 'canceled'), signature) == false,
|
|
1111
|
+
'a tampered payload to fail')
|
|
1112
|
+
verify(DIDWW::Callback::RequestValidator::HEADER == 'X-DIDWW-Signature', 'the X-DIDWW-Signature header name')
|
|
1113
|
+
end
|
|
1114
|
+
|
|
1115
|
+
check('Webhook Signature Validation: the validator required on its own') do
|
|
1116
|
+
# The snippet's require, in a process that has not loaded the rest of the gem
|
|
1117
|
+
code = <<~RUBY
|
|
1118
|
+
require 'didww/callback/request_validator'
|
|
1119
|
+
validator = DIDWW::Callback::RequestValidator.new('YOUR_CALLBACK_SECRET')
|
|
1120
|
+
validator.validate('https://example.com/webhooks/didww', { 'id' => '1' }, 'signature')
|
|
1121
|
+
RUBY
|
|
1122
|
+
_output, ok, error = run_ruby(code)
|
|
1123
|
+
verify(ok, "the snippet to run with only that require, it failed with: #{error}")
|
|
1124
|
+
end
|
|
1125
|
+
|
|
1126
|
+
if ACTION_PACK
|
|
1127
|
+
# Stand-in for the ApplicationController of a Rails app, which protects from forgery
|
|
1128
|
+
class ApplicationController < ActionController::Base
|
|
1129
|
+
protect_from_forgery with: :exception
|
|
1130
|
+
end
|
|
1131
|
+
|
|
1132
|
+
# The README's controller
|
|
1133
|
+
class WebhooksController < ApplicationController
|
|
1134
|
+
skip_before_action :verify_authenticity_token
|
|
1135
|
+
|
|
1136
|
+
def create
|
|
1137
|
+
validator = DIDWW::Callback::RequestValidator.new('YOUR_CALLBACK_SECRET')
|
|
1138
|
+
signature = request.headers[DIDWW::Callback::RequestValidator::HEADER]
|
|
1139
|
+
params_hash = request.POST
|
|
1140
|
+
|
|
1141
|
+
if validator.validate(request.original_url, params_hash, signature)
|
|
1142
|
+
# Process the webhook
|
|
1143
|
+
head :ok
|
|
1144
|
+
else
|
|
1145
|
+
head :forbidden
|
|
1146
|
+
end
|
|
1147
|
+
end
|
|
1148
|
+
end
|
|
1149
|
+
end
|
|
1150
|
+
|
|
1151
|
+
check('Webhook Signature Validation: Rails example') do
|
|
1152
|
+
skip!('ActionPack is not installed; add actionpack to the bundle to run it') unless ACTION_PACK
|
|
1153
|
+
|
|
1154
|
+
url = 'https://example.com/webhooks/didww'
|
|
1155
|
+
payload = { 'id' => SecureRandom.uuid, 'type' => 'orders', 'status' => 'completed' }
|
|
1156
|
+
signature = sign_callback('YOUR_CALLBACK_SECRET', url, payload)
|
|
1157
|
+
callback = lambda do |params|
|
|
1158
|
+
env = Rack::MockRequest.env_for(url, method: 'POST', params: params, 'HTTP_X_DIDWW_SIGNATURE' => signature)
|
|
1159
|
+
WebhooksController.action(:create).call(env).first
|
|
1160
|
+
end
|
|
1161
|
+
|
|
1162
|
+
signed = callback.call(payload)
|
|
1163
|
+
tampered = callback.call(payload.merge('status' => 'canceled'))
|
|
1164
|
+
verify(signed == 200, "200 for a signed callback, got #{signed}")
|
|
1165
|
+
verify(tampered == 403, "403 for a tampered callback, got #{tampered}")
|
|
1166
|
+
puts " ActionPack #{ActionPack.version}: signed callback #{signed}, tampered callback #{tampered}"
|
|
1167
|
+
end
|
|
1168
|
+
|
|
1169
|
+
# ─── Enums ─────────────────────────────────────────────────
|
|
1170
|
+
|
|
1171
|
+
section 'Enums'
|
|
1172
|
+
|
|
1173
|
+
check('Enums: the documented constants') do
|
|
1174
|
+
names = %w[
|
|
1175
|
+
DIDWW::Resource::NumberTypes::NUMBER_TYPES
|
|
1176
|
+
DIDWW::Resource::VoiceInTrunk::POPS
|
|
1177
|
+
DIDWW::ComplexObject::ExportFilters::TRUNK_TYPES
|
|
1178
|
+
DIDWW::ComplexObject::ExportFilters::SERVICE_TYPES
|
|
1179
|
+
DIDWW::ComplexObject::SmsTrunkConfiguration::HttpIn::HTTP_METHODS
|
|
1180
|
+
DIDWW::ComplexObject::SmsTrunkConfiguration::HttpIn::BODY_TYPES
|
|
1181
|
+
DIDWW::ComplexObject::SmsTrunkConfiguration::SERVER_LOCATIONS
|
|
1182
|
+
DIDWW::Prices::VoiceOutPrice::CATEGORIES
|
|
1183
|
+
DIDWW::Resource::SenderIdVerification::STATUSES
|
|
1184
|
+
DIDWW::Resource::SenderIdVerification::SENDER_TYPES
|
|
1185
|
+
DIDWW::ComplexObject::SipConfiguration::CODECS
|
|
1186
|
+
DIDWW::ComplexObject::SipConfiguration::ICE_MODES
|
|
1187
|
+
DIDWW::ComplexObject::SipConfiguration::RTCP_MUX_MODES
|
|
1188
|
+
DIDWW::ComplexObject::SipConfiguration::RTCP_FEEDBACK_MODES
|
|
1189
|
+
DIDWW::ComplexObject::SipConfiguration::CODEC_PCMA
|
|
1190
|
+
DIDWW::ComplexObject::SipConfiguration::ICE_MODE_ACCEPT
|
|
1191
|
+
DIDWW::Resource::VoiceOutTrunk::CODECS
|
|
1192
|
+
DIDWW::Resource::VoiceOutTrunk::ICE_MODES
|
|
1193
|
+
DIDWW::Resource::VoiceOutTrunk::RTCP_MUX_MODES
|
|
1194
|
+
DIDWW::Resource::VoiceOutTrunk::RTCP_FEEDBACK_MODES
|
|
1195
|
+
]
|
|
1196
|
+
missing = names.reject do |name|
|
|
1197
|
+
Object.const_get(name)
|
|
1198
|
+
true
|
|
1199
|
+
rescue NameError
|
|
1200
|
+
false
|
|
1201
|
+
end
|
|
1202
|
+
verify(missing.empty?, "every constant to exist, missing: #{missing.join(', ')}")
|
|
1203
|
+
end
|
|
1204
|
+
|
|
1205
|
+
# ─── Summary ───────────────────────────────────────────────
|
|
1206
|
+
|
|
1207
|
+
puts "\n#{'=' * 50}"
|
|
1208
|
+
puts "Results: #{RESULTS[:passed]} passed, #{RESULTS[:failed]} failed"
|
|
1209
|
+
puts "Skipped: #{RESULTS[:skipped]}" if RESULTS[:skipped].positive?
|
|
1210
|
+
unless FAILURES.empty?
|
|
1211
|
+
puts "\nFailures:"
|
|
1212
|
+
FAILURES.each { |failure| puts " - #{failure}" }
|
|
1213
|
+
end
|
|
1214
|
+
puts '=' * 50
|
|
1215
|
+
|
|
1216
|
+
exit(RESULTS[:failed].positive? ? 1 : 0)
|