ap2_mandate_verifier 1.3.0 → 1.5.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/README.ja.md +24 -8
- data/README.md +24 -8
- data/SECURITY.md +4 -2
- data/docs/PAYMENT_ACCEPTANCE.md +88 -0
- data/docs/PAYMENT_POLICY.md +72 -0
- data/docs/PUBLIC_API.md +13 -3
- data/docs/RELEASE_130_CANDIDATE.md +2 -0
- data/docs/RELEASE_140_CANDIDATE.md +19 -0
- data/docs/RELEASE_150_CANDIDATE.md +21 -0
- data/docs/SELECTIVE_CHECKOUT.md +4 -2
- data/docs/SUPPORT_CONTRACT.md +5 -1
- data/examples/payment_acceptance.rb +77 -0
- data/examples/payment_policy.rb +101 -0
- data/lib/ap2_mandate_verifier/payment.rb +102 -54
- data/lib/ap2_mandate_verifier/payment_acceptance/sqlite_store.rb +316 -0
- data/lib/ap2_mandate_verifier/payment_acceptance.rb +263 -0
- data/lib/ap2_mandate_verifier/payment_policy.rb +115 -0
- data/lib/ap2_mandate_verifier/payment_receipt.rb +6 -5
- data/lib/ap2_mandate_verifier/selective_payment.rb +40 -31
- data/lib/ap2_mandate_verifier.rb +3 -0
- metadata +14 -4
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module AP2MandateVerifier
|
|
4
|
+
module PaymentAcceptance
|
|
5
|
+
# Optional local durable reference. Production adapters must preserve the
|
|
6
|
+
# same protected-authorization + claim transaction and CAS guarantees.
|
|
7
|
+
class SQLiteStore
|
|
8
|
+
DRIVER_VERSION = "2.10.2".freeze
|
|
9
|
+
RECEIPT_FIELDS = %w[trusted_public_key_pem expected_issuer expected_payment_id not_before not_after].freeze
|
|
10
|
+
SCHEMA = {
|
|
11
|
+
"ap2_store" => "CREATE TABLE ap2_store (identity TEXT NOT NULL)",
|
|
12
|
+
"ap2_approvals" => "CREATE TABLE ap2_approvals (operation_key TEXT PRIMARY KEY, tenant TEXT NOT NULL, merchant TEXT NOT NULL, approval TEXT NOT NULL, occurrence TEXT NOT NULL, scope TEXT NOT NULL, instruction TEXT NOT NULL, receipt_context TEXT NOT NULL, active INTEGER NOT NULL DEFAULT 1 CHECK(active IN (0,1)), UNIQUE(tenant,merchant,approval,occurrence))",
|
|
13
|
+
"ap2_attempts" => "CREATE TABLE ap2_attempts (operation_key TEXT PRIMARY KEY REFERENCES ap2_approvals(operation_key), tenant TEXT NOT NULL, merchant TEXT NOT NULL, closed_reference TEXT NOT NULL, fence TEXT NOT NULL, state TEXT NOT NULL CHECK(state IN ('reserved','processing','unknown','receipt_success','receipt_error')), record TEXT NOT NULL, UNIQUE(tenant,merchant,closed_reference))"
|
|
14
|
+
}.transform_values(&:freeze).freeze
|
|
15
|
+
def self.create(**arguments)
|
|
16
|
+
raise Unavailable unless arguments.keys == [:path]
|
|
17
|
+
path = arguments.fetch(:path)
|
|
18
|
+
dependencies!
|
|
19
|
+
checked = path!(path)
|
|
20
|
+
File.open(checked, File::WRONLY | File::CREAT | File::EXCL, 0o600) { |f| f.fsync }
|
|
21
|
+
value = allocate
|
|
22
|
+
value.send(:setup!, checked, true)
|
|
23
|
+
value
|
|
24
|
+
rescue StandardError, LoadError
|
|
25
|
+
raise Unavailable.new, cause: nil
|
|
26
|
+
end
|
|
27
|
+
def self.dependencies!
|
|
28
|
+
gem "sqlite3", "= #{DRIVER_VERSION}"
|
|
29
|
+
require "sqlite3"
|
|
30
|
+
raise Unavailable unless Gem.loaded_specs.fetch("sqlite3").version.to_s == DRIVER_VERSION
|
|
31
|
+
end
|
|
32
|
+
def self.path!(path)
|
|
33
|
+
checked = InputValidator.snapshot!(path, max_bytes: 4096)
|
|
34
|
+
raise Invalid if checked.empty? || checked == ":memory:" || checked.include?("\0") || checked.start_with?("file:")
|
|
35
|
+
checked
|
|
36
|
+
end
|
|
37
|
+
private_class_method :dependencies!, :path!
|
|
38
|
+
def initialize(**arguments)
|
|
39
|
+
raise Unavailable unless arguments.keys == [:path]
|
|
40
|
+
setup!(self.class.send(:path!, arguments.fetch(:path)), false)
|
|
41
|
+
rescue StandardError, LoadError
|
|
42
|
+
raise Unavailable.new, cause: nil
|
|
43
|
+
end
|
|
44
|
+
def inspect = "#<AP2MandateVerifier::PaymentAcceptance::SQLiteStore>"
|
|
45
|
+
def setup!(path, creating)
|
|
46
|
+
self.class.send(:dependencies!)
|
|
47
|
+
@path = path
|
|
48
|
+
@db = SQLite3::Database.new(@path, flags: SQLite3::Constants::Open::READWRITE)
|
|
49
|
+
@db.busy_timeout = 5000
|
|
50
|
+
unless creating
|
|
51
|
+
raise Unavailable unless @db.get_first_value("PRAGMA user_version") == 1 && @db.execute("PRAGMA quick_check") == [["ok"]]
|
|
52
|
+
expected = SCHEMA.map { |name,sql| ["table", name, name, sql] } +
|
|
53
|
+
[["index", "sqlite_autoindex_ap2_approvals_1", "ap2_approvals", nil],
|
|
54
|
+
["index", "sqlite_autoindex_ap2_approvals_2", "ap2_approvals", nil],
|
|
55
|
+
["index", "sqlite_autoindex_ap2_attempts_1", "ap2_attempts", nil],
|
|
56
|
+
["index", "sqlite_autoindex_ap2_attempts_2", "ap2_attempts", nil]]
|
|
57
|
+
actual = @db.execute("SELECT type,name,tbl_name,sql FROM sqlite_master ORDER BY type,name")
|
|
58
|
+
raise Unavailable unless actual == expected.sort_by { |row| row.first(2) }
|
|
59
|
+
identities = @db.execute("SELECT identity FROM ap2_store")
|
|
60
|
+
raise Unavailable unless identities.size == 1 && identities[0].size == 1
|
|
61
|
+
@store_id = identities[0][0]
|
|
62
|
+
raise Unavailable unless @store_id.instance_of?(String) && @store_id.match?(/\A[0-9a-f]{64}\z/)
|
|
63
|
+
end
|
|
64
|
+
@db.execute("PRAGMA journal_mode=DELETE")
|
|
65
|
+
@db.execute("PRAGMA synchronous=FULL")
|
|
66
|
+
@db.execute("PRAGMA foreign_keys=ON")
|
|
67
|
+
raise Unavailable unless @db.get_first_value("PRAGMA journal_mode") == "delete" &&
|
|
68
|
+
@db.get_first_value("PRAGMA synchronous") == 2 && @db.get_first_value("PRAGMA foreign_keys") == 1
|
|
69
|
+
if creating
|
|
70
|
+
require "securerandom"
|
|
71
|
+
@store_id = SecureRandom.hex(32)
|
|
72
|
+
@db.execute("BEGIN IMMEDIATE")
|
|
73
|
+
@db.execute(SCHEMA.fetch("ap2_store"))
|
|
74
|
+
@db.execute("INSERT INTO ap2_store(identity) VALUES (?)", [@store_id])
|
|
75
|
+
@db.execute(SCHEMA.fetch("ap2_approvals"))
|
|
76
|
+
@db.execute(SCHEMA.fetch("ap2_attempts"))
|
|
77
|
+
@db.execute("PRAGMA user_version=1")
|
|
78
|
+
@db.execute("COMMIT")
|
|
79
|
+
end
|
|
80
|
+
@mutex = Mutex.new
|
|
81
|
+
rescue StandardError, LoadError
|
|
82
|
+
@db&.close rescue nil
|
|
83
|
+
raise Unavailable.new, cause: nil
|
|
84
|
+
end
|
|
85
|
+
private :setup!
|
|
86
|
+
|
|
87
|
+
# Only a protected Host approval backend may enroll this immutable grant.
|
|
88
|
+
# A received ID/flag never enrolls or alters an approved occurrence.
|
|
89
|
+
def authorize!(tenant_id:, merchant_id:, operation_id:, approval_id:, occurrence_id:, order_id:,
|
|
90
|
+
mode:, profile_ref:, checkout:, payment:, receipt_context:)
|
|
91
|
+
scope = PaymentAcceptance.scope!({"tenant_id" => tenant_id, "merchant_id" => merchant_id,
|
|
92
|
+
"operation_id" => operation_id, "approval_id" => approval_id, "occurrence_id" => occurrence_id, "order_id" => order_id})
|
|
93
|
+
profile = PaymentAcceptance.profile!(mode, profile_ref)
|
|
94
|
+
cart = InputBuilder.send(:copy!, checkout)
|
|
95
|
+
raise Invalid unless cart["id"] == scope["order_id"] && cart.dig("merchant", "id") == scope["merchant_id"]
|
|
96
|
+
instruction = PaymentAcceptance.instruction!(mode, profile, cart, payment)
|
|
97
|
+
context = PaymentAcceptance.copy!(receipt_context).transform_keys(&:to_s)
|
|
98
|
+
raise Invalid unless context.keys.sort == RECEIPT_FIELDS.sort
|
|
99
|
+
RootSignature.public_jwk!(context["trusted_public_key_pem"])
|
|
100
|
+
%w[expected_issuer expected_payment_id].each { |f| CheckoutReceipt.send(:text!, context[f], 512) }
|
|
101
|
+
%w[not_before not_after].each { |f| CheckoutReceipt.send(:epoch!, context[f]) }
|
|
102
|
+
raise Invalid unless context["not_before"] <= context["not_after"]
|
|
103
|
+
row = [PaymentAcceptance.canonical(scope), instruction, PaymentAcceptance.canonical(context)]
|
|
104
|
+
transaction do
|
|
105
|
+
alias_key = @db.get_first_value("SELECT operation_key FROM ap2_approvals WHERE tenant=? AND merchant=? AND approval=? AND occurrence=?",
|
|
106
|
+
scope.values_at("tenant_id", "merchant_id", "approval_id", "occurrence_id"))
|
|
107
|
+
raise Conflict if alias_key && alias_key != PaymentAcceptance.key(scope)
|
|
108
|
+
old = @db.get_first_row("SELECT CASE WHEN length(CAST(scope AS BLOB))<=131072 THEN scope END,CASE WHEN length(CAST(instruction AS BLOB))<=131072 THEN instruction END,CASE WHEN length(CAST(receipt_context AS BLOB))<=8192 THEN receipt_context END FROM ap2_approvals WHERE operation_key=?", [PaymentAcceptance.key(scope)])
|
|
109
|
+
check_grant!(old) if old
|
|
110
|
+
raise Conflict if old && old != row
|
|
111
|
+
unless old
|
|
112
|
+
begin
|
|
113
|
+
@db.execute("INSERT INTO ap2_approvals(operation_key,tenant,merchant,approval,occurrence,scope,instruction,receipt_context) VALUES (?,?,?,?,?,?,?,?)",
|
|
114
|
+
[PaymentAcceptance.key(scope), *scope.values_at("tenant_id", "merchant_id", "approval_id", "occurrence_id"), *row])
|
|
115
|
+
rescue SQLite3::ConstraintException
|
|
116
|
+
raise Conflict
|
|
117
|
+
end
|
|
118
|
+
end
|
|
119
|
+
true
|
|
120
|
+
end
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
def reserve!(scope:, instruction:, record:)
|
|
124
|
+
transaction do
|
|
125
|
+
key = PaymentAcceptance.key(scope)
|
|
126
|
+
grant = @db.get_first_row("SELECT CASE WHEN length(CAST(scope AS BLOB))<=131072 THEN scope END,CASE WHEN length(CAST(instruction AS BLOB))<=131072 THEN instruction END,CASE WHEN length(CAST(receipt_context AS BLOB))<=8192 THEN receipt_context END,active FROM ap2_approvals WHERE operation_key=?", [key])
|
|
127
|
+
raise Invalid unless grant
|
|
128
|
+
check_grant!(grant)
|
|
129
|
+
raise Invalid unless grant[3] == 1
|
|
130
|
+
raise Conflict unless grant[0] == PaymentAcceptance.canonical(scope) && grant[1] == instruction
|
|
131
|
+
old = load_record(key)
|
|
132
|
+
if old
|
|
133
|
+
raise Conflict unless old["instruction"] == instruction
|
|
134
|
+
next PaymentAcceptance.result(old)
|
|
135
|
+
end
|
|
136
|
+
reused = @db.get_first_value("SELECT operation_key FROM ap2_attempts WHERE tenant=? AND merchant=? AND closed_reference=?",
|
|
137
|
+
[scope.fetch("tenant_id"), scope.fetch("merchant_id"), record.fetch("reference")])
|
|
138
|
+
raise Conflict if reused
|
|
139
|
+
require "securerandom"
|
|
140
|
+
fence = SecureRandom.hex(32)
|
|
141
|
+
value = record.merge("state" => "reserved", "processor_key" => SecureRandom.hex(32),
|
|
142
|
+
"receipt_context" => decode!(grant[2], 8192))
|
|
143
|
+
raise Invalid if JSON.generate(value).bytesize > 1_048_576
|
|
144
|
+
begin
|
|
145
|
+
@db.execute("INSERT INTO ap2_attempts(operation_key,tenant,merchant,closed_reference,fence,state,record) VALUES (?,?,?,?,?,?,?)",
|
|
146
|
+
[key, scope.fetch("tenant_id"), scope.fetch("merchant_id"), record.fetch("reference"), fence, "reserved", JSON.generate(value)])
|
|
147
|
+
rescue SQLite3::ConstraintException
|
|
148
|
+
raise Conflict
|
|
149
|
+
end
|
|
150
|
+
# Returned only after COMMIT succeeds. A commit error is unavailable,
|
|
151
|
+
# even if SQLite may have persisted the row; no capability is returned.
|
|
152
|
+
Result.send(:new, :reserved, value, Ticket.send(:new, @store_id + key, fence))
|
|
153
|
+
end
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
def start!(ticket:, verified_at:, instruction:, signed_wires:)
|
|
157
|
+
key, fence = ticket_parts!(ticket)
|
|
158
|
+
transaction do
|
|
159
|
+
row = @db.get_first_row("SELECT state,CASE WHEN length(CAST(record AS BLOB))<=1048576 THEN record ELSE NULL END FROM ap2_attempts WHERE operation_key=? AND fence=?", [key, fence])
|
|
160
|
+
raise Invalid unless row
|
|
161
|
+
next nil unless row[0] == "reserved"
|
|
162
|
+
record = decode!(row[1], 1_048_576)
|
|
163
|
+
raise Unavailable unless record["state"] == row[0]
|
|
164
|
+
grant = @db.get_first_row("SELECT active,CASE WHEN length(CAST(instruction AS BLOB))<=131072 THEN instruction END FROM ap2_approvals WHERE operation_key=?", [key])
|
|
165
|
+
raise Invalid unless grant && grant[0] == 1 && grant[1] == instruction &&
|
|
166
|
+
record["instruction"] == instruction && record["signed_wires"] == signed_wires
|
|
167
|
+
next nil unless verified_at >= record["accepted_at"] && verified_at < record["valid_until"]
|
|
168
|
+
record["state"] = "processing"
|
|
169
|
+
record["started_at"] = verified_at
|
|
170
|
+
@db.execute("UPDATE ap2_attempts SET state='processing',record=? WHERE operation_key=? AND fence=? AND state='reserved'", [JSON.generate(record), key, fence])
|
|
171
|
+
raise Unavailable unless @db.changes == 1
|
|
172
|
+
record
|
|
173
|
+
end
|
|
174
|
+
end
|
|
175
|
+
|
|
176
|
+
def ticket_record!(ticket:)
|
|
177
|
+
key, fence = ticket_parts!(ticket)
|
|
178
|
+
transaction do
|
|
179
|
+
row = @db.get_first_row("SELECT CASE WHEN length(CAST(record AS BLOB))<=1048576 THEN record ELSE NULL END FROM ap2_attempts WHERE operation_key=? AND fence=?", [key, fence])
|
|
180
|
+
raise Invalid unless row
|
|
181
|
+
decode!(row[0], 1_048_576)
|
|
182
|
+
end
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
def lookup_record!(scope:)
|
|
186
|
+
transaction do
|
|
187
|
+
record = load_record(PaymentAcceptance.key(scope))
|
|
188
|
+
raise Conflict if record && record["scope"] != scope
|
|
189
|
+
record
|
|
190
|
+
end
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
def unknown!(ticket:)
|
|
194
|
+
key, fence = ticket_parts!(ticket)
|
|
195
|
+
transaction do
|
|
196
|
+
record = load_record(key, fence)
|
|
197
|
+
raise Invalid unless record
|
|
198
|
+
if record["state"] == "processing"
|
|
199
|
+
record["state"] = "unknown"
|
|
200
|
+
save(key, record)
|
|
201
|
+
elsif record["state"] != "unknown"
|
|
202
|
+
raise Invalid
|
|
203
|
+
end
|
|
204
|
+
PaymentAcceptance.result(record)
|
|
205
|
+
end
|
|
206
|
+
end
|
|
207
|
+
|
|
208
|
+
def finish!(scope:, ticket:, receipt_jwt:, status:)
|
|
209
|
+
raise Invalid unless %w[receipt_success receipt_error].include?(status)
|
|
210
|
+
key = PaymentAcceptance.key(scope)
|
|
211
|
+
fence = ticket_parts!(ticket)[1] if ticket
|
|
212
|
+
raise Invalid if ticket && ticket_parts!(ticket)[0] != key
|
|
213
|
+
transaction do
|
|
214
|
+
record = load_record(key, fence)
|
|
215
|
+
raise Invalid unless record && record["scope"] == scope
|
|
216
|
+
if %w[receipt_success receipt_error].include?(record["state"])
|
|
217
|
+
raise Conflict unless record["receipt_jwt"] == receipt_jwt && record["state"] == status
|
|
218
|
+
else
|
|
219
|
+
raise Invalid unless %w[processing unknown].include?(record["state"])
|
|
220
|
+
record["state"], record["receipt_jwt"] = status, receipt_jwt
|
|
221
|
+
save(key, record)
|
|
222
|
+
end
|
|
223
|
+
PaymentAcceptance.result(record)
|
|
224
|
+
end
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
def close
|
|
228
|
+
@mutex.synchronize { @db.close }
|
|
229
|
+
rescue StandardError
|
|
230
|
+
raise Unavailable.new, cause: nil
|
|
231
|
+
end
|
|
232
|
+
|
|
233
|
+
def revoke!(**scope)
|
|
234
|
+
scope = PaymentAcceptance.scope_keywords!(scope)
|
|
235
|
+
transaction do
|
|
236
|
+
@db.execute("UPDATE ap2_approvals SET active=0 WHERE operation_key=? AND scope=?", [PaymentAcceptance.key(scope), PaymentAcceptance.canonical(scope)])
|
|
237
|
+
raise Invalid unless @db.changes == 1
|
|
238
|
+
true
|
|
239
|
+
end
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
private
|
|
243
|
+
def ticket_parts!(ticket)
|
|
244
|
+
raise Invalid unless ticket.instance_of?(Ticket)
|
|
245
|
+
key = ticket.send(:key)
|
|
246
|
+
raise Invalid unless key.start_with?(@store_id) && key.bytesize == 128
|
|
247
|
+
[key[64,64], ticket.send(:fence)]
|
|
248
|
+
end
|
|
249
|
+
def load_record(key, fence = nil)
|
|
250
|
+
sql = "SELECT state,CASE WHEN length(CAST(record AS BLOB))<=1048576 THEN record ELSE NULL END FROM ap2_attempts WHERE operation_key=?"
|
|
251
|
+
args = [key]
|
|
252
|
+
if fence
|
|
253
|
+
sql += " AND fence=?"; args << fence
|
|
254
|
+
end
|
|
255
|
+
row = @db.get_first_row(sql, args)
|
|
256
|
+
if row
|
|
257
|
+
record = decode!(row[1], 1_048_576)
|
|
258
|
+
raise Unavailable unless record["state"] == row[0]
|
|
259
|
+
record
|
|
260
|
+
end
|
|
261
|
+
end
|
|
262
|
+
def save(key, record)
|
|
263
|
+
raise Unavailable if JSON.generate(record).bytesize > 1_048_576
|
|
264
|
+
@db.execute("UPDATE ap2_attempts SET state=?,record=? WHERE operation_key=?", [record.fetch("state"), JSON.generate(record), key])
|
|
265
|
+
raise Unavailable unless @db.changes == 1
|
|
266
|
+
end
|
|
267
|
+
def check_grant!(row)
|
|
268
|
+
[131_072,131_072,8192].each_with_index { |limit,i| InputValidator.snapshot!(row[i], max_bytes: limit) }
|
|
269
|
+
end
|
|
270
|
+
def decode!(source, max)
|
|
271
|
+
wire = InputValidator.snapshot!(source, max_bytes: max)
|
|
272
|
+
InputValidator.send(:reject_extensions!, wire)
|
|
273
|
+
raise Unavailable unless JSON::VERSION == InputValidator::JSON_VERSION
|
|
274
|
+
JSON.parse(wire, create_additions: false, symbolize_names: false, max_nesting: 24,
|
|
275
|
+
allow_nan: false, allow_duplicate_key: false, allow_trailing_comma: false)
|
|
276
|
+
rescue StandardError
|
|
277
|
+
raise Unavailable.new, cause: nil
|
|
278
|
+
end
|
|
279
|
+
def transaction
|
|
280
|
+
@mutex.synchronize do
|
|
281
|
+
@db.execute("BEGIN IMMEDIATE")
|
|
282
|
+
begin
|
|
283
|
+
value = yield
|
|
284
|
+
@db.execute("COMMIT")
|
|
285
|
+
value
|
|
286
|
+
rescue StandardError
|
|
287
|
+
@db.execute("ROLLBACK") rescue nil
|
|
288
|
+
raise
|
|
289
|
+
end
|
|
290
|
+
end
|
|
291
|
+
rescue Invalid, Conflict
|
|
292
|
+
raise
|
|
293
|
+
rescue StandardError
|
|
294
|
+
raise Unavailable.new, cause: nil
|
|
295
|
+
end
|
|
296
|
+
|
|
297
|
+
%i[authorize! reserve! start! ticket_record! lookup_record! unknown! finish! close revoke!].each do |name|
|
|
298
|
+
implementation = instance_method(name)
|
|
299
|
+
required = implementation.parameters.filter_map { |kind, key| key if kind == :keyreq }.freeze
|
|
300
|
+
allowed = implementation.parameters.filter_map { |kind, key| key if %i[keyreq key].include?(kind) }.freeze
|
|
301
|
+
rest = implementation.parameters.any? { |kind,_| kind == :keyrest }
|
|
302
|
+
define_method(name) do |**arguments|
|
|
303
|
+
raise Invalid unless (required - arguments.keys).empty? && (rest || (arguments.keys - allowed).empty?)
|
|
304
|
+
implementation.bind_call(self, **arguments)
|
|
305
|
+
rescue Conflict
|
|
306
|
+
raise Conflict.new("payment acceptance conflict"), cause: nil
|
|
307
|
+
rescue Unavailable
|
|
308
|
+
raise Unavailable.new, cause: nil
|
|
309
|
+
rescue StandardError, LoadError
|
|
310
|
+
raise Invalid.new, cause: nil
|
|
311
|
+
end
|
|
312
|
+
public name
|
|
313
|
+
end
|
|
314
|
+
end
|
|
315
|
+
end
|
|
316
|
+
end
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module AP2MandateVerifier
|
|
4
|
+
# Application-side single-attempt coordination, not a PSP execution engine.
|
|
5
|
+
module PaymentAcceptance
|
|
6
|
+
SCOPE = %w[tenant_id merchant_id operation_id approval_id occurrence_id order_id].freeze
|
|
7
|
+
class Invalid < ArgumentError
|
|
8
|
+
def initialize = super("invalid payment acceptance information")
|
|
9
|
+
end
|
|
10
|
+
class Unavailable < StandardError
|
|
11
|
+
def initialize = super("payment acceptance storage unavailable")
|
|
12
|
+
end
|
|
13
|
+
class Conflict < StandardError; end
|
|
14
|
+
|
|
15
|
+
class Ticket
|
|
16
|
+
def initialize(key, fence)
|
|
17
|
+
@key, @fence = key.freeze, fence.freeze
|
|
18
|
+
freeze
|
|
19
|
+
end
|
|
20
|
+
def inspect = "#<AP2MandateVerifier::PaymentAcceptance::Ticket>"
|
|
21
|
+
private
|
|
22
|
+
attr_reader :key, :fence
|
|
23
|
+
private_class_method :new
|
|
24
|
+
end
|
|
25
|
+
class Result
|
|
26
|
+
attr_reader :status, :ticket, :closed_sd_jwt, :reference, :receipt_jwt, :processor_key, :signed_wires
|
|
27
|
+
def initialize(status, record = nil, ticket = nil)
|
|
28
|
+
@status, @ticket = status, ticket
|
|
29
|
+
if record
|
|
30
|
+
@closed_sd_jwt, @reference, @receipt_jwt = record.values_at("closed_sd_jwt", "reference", "receipt_jwt").map { |v| v&.freeze }
|
|
31
|
+
@processor_key = record.fetch("processor_key").freeze
|
|
32
|
+
@signed_wires = ResearchEvidence.send(:copy_frozen, record.fetch("signed_wires"))
|
|
33
|
+
end
|
|
34
|
+
freeze
|
|
35
|
+
end
|
|
36
|
+
def inspect = "#<AP2MandateVerifier::PaymentAcceptance::Result status=#{status}>"
|
|
37
|
+
private_class_method :new
|
|
38
|
+
end
|
|
39
|
+
class Execution
|
|
40
|
+
attr_reader :processor_key, :closed_sd_jwt, :reference, :payment
|
|
41
|
+
def initialize(record)
|
|
42
|
+
@processor_key, @closed_sd_jwt, @reference = record.values_at("processor_key", "closed_sd_jwt", "reference").map(&:freeze)
|
|
43
|
+
@payment = ResearchEvidence.send(:copy_frozen, record.fetch("payment"))
|
|
44
|
+
freeze
|
|
45
|
+
end
|
|
46
|
+
def inspect = "#<AP2MandateVerifier::PaymentAcceptance::Execution>"
|
|
47
|
+
private_class_method :new
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
class Service
|
|
51
|
+
def initialize(**arguments)
|
|
52
|
+
raise Invalid.new, cause: nil unless arguments.keys == [:store]
|
|
53
|
+
@store = arguments.fetch(:store)
|
|
54
|
+
end
|
|
55
|
+
def inspect = "#<AP2MandateVerifier::PaymentAcceptance::Service>"
|
|
56
|
+
# Every call starts from raw verifier inputs, never a caller-made proof.
|
|
57
|
+
def accept(mode:, verification_inputs:, tenant_id:, merchant_id:, operation_id:, approval_id:, occurrence_id:, order_id:)
|
|
58
|
+
scope = PaymentAcceptance.scope!({"tenant_id" => tenant_id, "merchant_id" => merchant_id, "operation_id" => operation_id,
|
|
59
|
+
"approval_id" => approval_id, "occurrence_id" => occurrence_id, "order_id" => order_id})
|
|
60
|
+
record = verified_record(mode, verification_inputs, scope)
|
|
61
|
+
@store.reserve!(scope: scope, instruction: record.fetch("instruction"), record: record)
|
|
62
|
+
rescue Conflict
|
|
63
|
+
Result.send(:new, :conflict)
|
|
64
|
+
rescue Unavailable
|
|
65
|
+
Result.send(:new, :unavailable)
|
|
66
|
+
rescue StandardError, LoadError
|
|
67
|
+
Result.send(:new, :rejected)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def start(ticket:, verification_inputs:)
|
|
71
|
+
old = @store.ticket_record!(ticket: ticket)
|
|
72
|
+
fresh = verified_record(old.fetch("mode").to_sym, verification_inputs, old.fetch("scope"))
|
|
73
|
+
raise Invalid unless old.fetch("instruction") == fresh.fetch("instruction") && old.fetch("signed_wires") == fresh.fetch("signed_wires")
|
|
74
|
+
record = @store.start!(ticket: ticket, verified_at: fresh.fetch("accepted_at"),
|
|
75
|
+
instruction: fresh.fetch("instruction"), signed_wires: fresh.fetch("signed_wires"))
|
|
76
|
+
Execution.send(:new, record) if record
|
|
77
|
+
rescue StandardError, LoadError
|
|
78
|
+
nil # An uncertain commit NEVER produces an execution handle.
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
private
|
|
82
|
+
def verified_record(mode, verification_inputs, scope)
|
|
83
|
+
args = PaymentAcceptance.copy!(verification_inputs)
|
|
84
|
+
raise Invalid unless args.instance_of?(Hash)
|
|
85
|
+
profile = PaymentAcceptance.profile!(mode, args.fetch(:profile_ref, mode == :selective ? SelectivePayment::PROFILE_REF : Payment::PROFILE_REF))
|
|
86
|
+
result = case mode
|
|
87
|
+
when :direct, :conditional
|
|
88
|
+
raise Invalid unless args[:checkout_mode] == mode
|
|
89
|
+
Payment.verify(**args)
|
|
90
|
+
when :selective then SelectivePayment.verify(**args)
|
|
91
|
+
else raise Invalid
|
|
92
|
+
end
|
|
93
|
+
raise Invalid unless result.verified?
|
|
94
|
+
checkout_args = args.fetch(:checkout_inputs)
|
|
95
|
+
if mode == :direct
|
|
96
|
+
checkout = Buyer.verify(**checkout_args)
|
|
97
|
+
raise Invalid unless checkout.verified?
|
|
98
|
+
cart = checkout.checkout
|
|
99
|
+
valid_until = [checkout.expires_at, result.expires_at].min
|
|
100
|
+
else
|
|
101
|
+
checkout = AP2MandateVerifier.verify_checkout(**checkout_args)
|
|
102
|
+
raise Invalid unless checkout.success?
|
|
103
|
+
raise Invalid unless checkout.evidence["checkout_binding"].fetch("tenant_id") == scope["tenant_id"]
|
|
104
|
+
cart = Payment.send(:jwt_payload!, checkout_args.fetch(:host_checkout_jws), "JWT")
|
|
105
|
+
valid_until = [checkout.evidence["valid_until"], result.expires_at].min
|
|
106
|
+
end
|
|
107
|
+
raise Invalid unless cart.fetch("id") == scope["order_id"] && cart.fetch("merchant").fetch("id") == scope["merchant_id"]
|
|
108
|
+
payment = result.payment.slice(*PaymentPolicy.fields(profile))
|
|
109
|
+
instruction = PaymentAcceptance.instruction!(mode, profile, cart, payment)
|
|
110
|
+
closed = InputValidator.snapshot!(args.fetch(:closed_sd_jwt), max_bytes: 32_769)
|
|
111
|
+
checkout_wires = if mode == :direct
|
|
112
|
+
checkout_args.slice(:closed_sd_jwt, :expected_checkout_jwt)
|
|
113
|
+
else
|
|
114
|
+
checkout_args.slice(:root_presentation, :terminal_jws, :host_checkout_jws)
|
|
115
|
+
end
|
|
116
|
+
{"scope" => scope, "mode" => mode.to_s, "profile_ref" => profile, "instruction" => instruction,
|
|
117
|
+
"payment" => result.payment, "closed_sd_jwt" => closed, "reference" => result.reference,
|
|
118
|
+
"signed_wires" => {"payment" => args.slice(:open_sd_jwt, :open_presentation, :closed_sd_jwt).transform_keys(&:to_s),
|
|
119
|
+
"checkout" => checkout_wires.transform_keys(&:to_s)},
|
|
120
|
+
"accepted_at" => args.fetch(:verified_at), "valid_until" => valid_until}
|
|
121
|
+
end
|
|
122
|
+
public
|
|
123
|
+
|
|
124
|
+
def finish(ticket:, receipt_jwt:, verified_at:)
|
|
125
|
+
record = @store.ticket_record!(ticket: ticket)
|
|
126
|
+
finalize(record, receipt_jwt, verified_at, ticket)
|
|
127
|
+
rescue Conflict
|
|
128
|
+
Result.send(:new, :conflict)
|
|
129
|
+
rescue Unavailable
|
|
130
|
+
Result.send(:new, :unavailable)
|
|
131
|
+
rescue StandardError, LoadError
|
|
132
|
+
Result.send(:new, :rejected)
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
def unknown(ticket:)
|
|
136
|
+
@store.unknown!(ticket: ticket)
|
|
137
|
+
rescue Unavailable
|
|
138
|
+
Result.send(:new, :unavailable)
|
|
139
|
+
rescue StandardError
|
|
140
|
+
Result.send(:new, :rejected)
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
# Receipt reconciliation can finalize an uncertain attempt but cannot
|
|
144
|
+
# recover its fence, reserve it again, or grant another execution handle.
|
|
145
|
+
def reconcile(receipt_jwt:, verified_at:, **scope)
|
|
146
|
+
record = @store.lookup_record!(scope: PaymentAcceptance.scope_keywords!(scope))
|
|
147
|
+
raise Invalid unless record
|
|
148
|
+
finalize(record, receipt_jwt, verified_at, nil)
|
|
149
|
+
rescue Conflict
|
|
150
|
+
Result.send(:new, :conflict)
|
|
151
|
+
rescue Unavailable
|
|
152
|
+
Result.send(:new, :unavailable)
|
|
153
|
+
rescue StandardError, LoadError
|
|
154
|
+
Result.send(:new, :rejected)
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def lookup(**scope)
|
|
158
|
+
record = @store.lookup_record!(scope: PaymentAcceptance.scope_keywords!(scope))
|
|
159
|
+
record ? PaymentAcceptance.result(record) : Result.send(:new, :rejected)
|
|
160
|
+
rescue Unavailable
|
|
161
|
+
Result.send(:new, :unavailable)
|
|
162
|
+
rescue StandardError
|
|
163
|
+
Result.send(:new, :rejected)
|
|
164
|
+
end
|
|
165
|
+
|
|
166
|
+
private
|
|
167
|
+
def finalize(record, receipt_jwt, verified_at, ticket)
|
|
168
|
+
jwt = InputValidator.snapshot!(receipt_jwt, max_bytes: 16_384)
|
|
169
|
+
context = record.fetch("receipt_context").transform_keys(&:to_sym)
|
|
170
|
+
raise Invalid unless record.key?("started_at")
|
|
171
|
+
context[:not_before] = [context.fetch(:not_before), record.fetch("started_at")].max
|
|
172
|
+
receipt = PaymentReceipt.verify(jwt: jwt, closed_sd_jwt: record.fetch("closed_sd_jwt"),
|
|
173
|
+
profile_ref: record.fetch("profile_ref") == SelectivePayment::PROFILE_REF ? Payment::PROFILE_REF : record.fetch("profile_ref"),
|
|
174
|
+
verified_at: verified_at, **context)
|
|
175
|
+
raise Invalid unless receipt.verified?
|
|
176
|
+
status = receipt.payment_succeeded? ? "receipt_success" : "receipt_error"
|
|
177
|
+
@store.finish!(scope: record.fetch("scope"), ticket: ticket, receipt_jwt: jwt, status: status)
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
%i[accept start finish unknown reconcile lookup].each do |name|
|
|
181
|
+
implementation = instance_method(name)
|
|
182
|
+
required = implementation.parameters.filter_map { |kind, key| key if kind == :keyreq }.freeze
|
|
183
|
+
allowed = implementation.parameters.filter_map { |kind, key| key if %i[keyreq key].include?(kind) }.freeze
|
|
184
|
+
rest = implementation.parameters.any? { |kind,_| kind == :keyrest }
|
|
185
|
+
define_method(name) do |**arguments|
|
|
186
|
+
raise Invalid unless (required - arguments.keys).empty? && (rest || (arguments.keys - allowed).empty?)
|
|
187
|
+
implementation.bind_call(self, **arguments)
|
|
188
|
+
rescue StandardError, LoadError
|
|
189
|
+
name == :start ? nil : Result.send(:new, :rejected)
|
|
190
|
+
end
|
|
191
|
+
public name
|
|
192
|
+
end
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
def self.scope!(value)
|
|
196
|
+
scope = copy!(value)
|
|
197
|
+
raise Invalid unless scope.instance_of?(Hash) && scope.keys.sort == SCOPE.sort
|
|
198
|
+
scope.each_value { |v| CheckoutReceipt.send(:text!, v, 256) }
|
|
199
|
+
ResearchEvidence.send(:copy_frozen, scope)
|
|
200
|
+
end
|
|
201
|
+
def self.scope_keywords!(value)
|
|
202
|
+
scope!(copy!(value).transform_keys { |key| key.instance_of?(Symbol) ? key.to_s : key })
|
|
203
|
+
end
|
|
204
|
+
def self.profile!(mode, value)
|
|
205
|
+
raise Invalid unless %i[direct conditional selective].include?(mode)
|
|
206
|
+
PaymentPolicy.profile!(value, selective: mode == :selective)
|
|
207
|
+
end
|
|
208
|
+
def self.instruction!(mode, profile, checkout, payment)
|
|
209
|
+
cart = InputBuilder.send(:copy!, checkout)
|
|
210
|
+
ScopedConstraints.multi_checkout!(cart)
|
|
211
|
+
details = Payment.send(:copy_details!, payment, profile_ref: profile)
|
|
212
|
+
terms = details.reject { |k,_| k == "transaction_id" }
|
|
213
|
+
if terms.key?("execution_date")
|
|
214
|
+
instant = PaymentPolicy.instant!(terms["execution_date"])
|
|
215
|
+
terms["execution_date"] = {"numerator" => instant.numerator, "denominator" => instant.denominator}
|
|
216
|
+
end
|
|
217
|
+
canonical({"mode" => mode.to_s, "profile_ref" => profile, "checkout" => cart, "payment" => terms})
|
|
218
|
+
end
|
|
219
|
+
def self.key(scope)
|
|
220
|
+
digest(canonical(scope.slice("tenant_id", "merchant_id", "operation_id")))
|
|
221
|
+
end
|
|
222
|
+
def self.canonical(value)
|
|
223
|
+
require "json"
|
|
224
|
+
raise Unavailable unless JSON::VERSION == InputValidator::JSON_VERSION
|
|
225
|
+
normalized = case value
|
|
226
|
+
when Hash then value.keys.sort.to_h { |k| [k, JSON.parse(canonical(value[k]))] }
|
|
227
|
+
when Array then value.map { |v| JSON.parse(canonical(v)) }
|
|
228
|
+
else value
|
|
229
|
+
end
|
|
230
|
+
JSON.generate(normalized)
|
|
231
|
+
end
|
|
232
|
+
def self.digest(value) = Digest::SHA256.hexdigest(value)
|
|
233
|
+
def self.result(record)
|
|
234
|
+
status = %w[reserved processing].include?(record.fetch("state")) ? :pending : record.fetch("state").to_sym
|
|
235
|
+
Result.send(:new, status, record)
|
|
236
|
+
end
|
|
237
|
+
# Raw verifier keyword graphs include Symbols. Bound/copy without invoking
|
|
238
|
+
# caller coercions or singleton callbacks, before any signature or storage.
|
|
239
|
+
def self.copy!(value, depth = 0, budget = [0, 0])
|
|
240
|
+
raise Invalid if depth > 20 || (budget[0] += 1) > 4096
|
|
241
|
+
raise Invalid unless Object.instance_method(:singleton_methods).bind_call(value, true).empty?
|
|
242
|
+
klass = Object.instance_method(:class).bind_call(value)
|
|
243
|
+
if klass == String
|
|
244
|
+
s = InputValidator.snapshot!(value)
|
|
245
|
+
raise Invalid if (budget[1] += s.bytesize) > 1_048_576
|
|
246
|
+
s
|
|
247
|
+
elsif klass == Hash
|
|
248
|
+
raise Invalid if value.size > 64
|
|
249
|
+
value.to_h do |k,v|
|
|
250
|
+
raise Invalid unless k.instance_of?(Symbol) || k.instance_of?(String)
|
|
251
|
+
[k.instance_of?(String) ? InputValidator.snapshot!(k, max_bytes: 256) : k, copy!(v, depth + 1, budget)]
|
|
252
|
+
end.freeze
|
|
253
|
+
elsif klass == Array
|
|
254
|
+
raise Invalid if value.size > 256
|
|
255
|
+
value.map { |v| copy!(v, depth + 1, budget) }.freeze
|
|
256
|
+
elsif [Integer, Symbol, NilClass, TrueClass, FalseClass].include?(klass)
|
|
257
|
+
value
|
|
258
|
+
else
|
|
259
|
+
raise Invalid
|
|
260
|
+
end
|
|
261
|
+
end
|
|
262
|
+
end
|
|
263
|
+
end
|