ap2_mandate_verifier 1.6.0 → 1.7.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.
@@ -0,0 +1,169 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ap2_mandate_verifier"
4
+ require "openssl"
5
+
6
+ module RubyIntegration
7
+ # Synthetic application storage, NOT enrollment or consent authentication.
8
+ # In production these records come from independently authenticated services.
9
+ # Never populate trust, order or approval from the received Payment Mandate.
10
+ module Inputs
11
+ M = AP2MandateVerifier
12
+ CHECKOUT_PROFILE = M::ConditionalCheckout::PROFILE_REF
13
+ module_function
14
+
15
+ def totals(amount)
16
+ %w[subtotal total].map { |type| {"type" => type, "amount" => amount} }
17
+ end
18
+
19
+ def signer(key) = M::CheckoutJWT.es256_signer(private_key: key)
20
+
21
+ def bootstrap(now:)
22
+ provider, agent, merchant = Array.new(3) { OpenSSL::PKey::EC.generate("prime256v1") }
23
+ seller = {"id" => "shop", "name" => "Synthetic office supplies"}
24
+ item = {"id" => "paper", "title" => "Synthetic paper"}
25
+ instrument = {"id" => "synthetic-card", "type" => "card"}
26
+ # Retain what the authenticated owner approved BEFORE issuing either Open.
27
+ # These local conditions are never reconstructed from an incoming Mandate.
28
+ approval = {"payment_instrument" => instrument,
29
+ "checkout_requirements" => [{"id" => "paper-choice", "quantity" => 1, "acceptable_items" => [item]}],
30
+ "payment_constraints" => [{"type" => "payment.amount_range", "currency" => "USD", "max" => 300},
31
+ {"type" => "payment.allowed_payees", "allowed" => [seller]},
32
+ {"type" => "payment.allowed_payment_instruments", "allowed" => [instrument]}]}
33
+ checkout = {"id" => "office-1", "merchant" => seller, "status" => "ready_for_complete",
34
+ "currency" => "USD", "line_items" => [{"id" => "row-1", "item" => item.merge("price" => 300),
35
+ "quantity" => 1, "totals" => totals(300)}], "totals" => totals(300), "links" => []}
36
+ opening = M::ConditionalCheckout.issue_open(merchant: seller,
37
+ requirements: approval.fetch("checkout_requirements"),
38
+ agent_public_key_pem: agent.public_to_pem, issued_at: now, expires_at: now + 60,
39
+ signer: signer(provider), public_key_pem: provider.public_to_pem)
40
+ checkout_jwt = M::CheckoutJWT.sign(checkout: checkout, profile_ref: CHECKOUT_PROFILE,
41
+ signer: signer(merchant), public_key_pem: merchant.public_to_pem).jwt
42
+
43
+ # Fixed IDs describe ONE protected state directory and ONE approved attempt.
44
+ # A new occurrence must get a separate authenticated application approval.
45
+ records = %w[Issuer Agent Merchant].zip([provider, agent, merchant]).map do |role, key|
46
+ {"role" => role, "identity" => role == "Merchant" ? "shop" : role.downcase,
47
+ "tenant_id" => "tenant", "purpose" => "checkout", "key_ref" => role.downcase,
48
+ "public_key_pem" => key.public_to_pem, "active" => true,
49
+ "not_before" => now - 1, "not_after" => now + 1000}
50
+ end
51
+ data = {
52
+ "now" => now,
53
+ "checkout" => checkout,
54
+ "order" => {"tenant_id" => "tenant", "buyer_account_id" => "buyer", "order_id" => "office-1",
55
+ "merchant_id" => "shop", "audience" => "merchant-host", "order_version" => "1",
56
+ "currency" => "USD", "expected_total" => 300},
57
+ "approval" => approval,
58
+ "trust_snapshot" => {"id" => "registry", "policy_version" => "1", "active" => true,
59
+ "not_before" => now - 1, "not_after" => now + 1000, "records" => records},
60
+ "selectors" => records.to_h do |record|
61
+ [record.fetch("role").downcase, record.slice("identity", "purpose", "key_ref")]
62
+ end,
63
+ "nonce" => "synthetic-one-use-nonce",
64
+ "challenge_issuer" => "host",
65
+ "scope" => {"tenant_id" => "tenant", "merchant_id" => "shop", "operation_id" => "operation-1",
66
+ "approval_id" => "approval-1", "occurrence_id" => "one", "order_id" => "office-1"},
67
+ "receipt_context" => {"trusted_public_key_pem" => merchant.public_to_pem,
68
+ "expected_issuer" => "shop", "expected_payment_id" => "payment-1",
69
+ "not_before" => now, "not_after" => now + 1000},
70
+ "wires" => {"checkout_open" => opening.root_presentation, "checkout_jwt" => checkout_jwt},
71
+ # Mock processor uses the synthetic merchant key. Provider private key
72
+ # is discarded; only these two mock actors need to sign after restart.
73
+ "mock_private_keys" => {"merchant" => merchant.private_to_pem, "agent" => agent.private_to_pem}
74
+ }
75
+ data["saved_challenge"] = M::InputBuilder.prepare(**host_inputs(data, now: now),
76
+ challenge_id: "challenge-1", nonce: data.fetch("nonce"), issuer_id: data.fetch("challenge_issuer"),
77
+ not_before: now, not_after: now + 60)
78
+ closed = M::ConditionalCheckout.issue_closed(root_presentation: opening.root_presentation,
79
+ checkout_jwt: checkout_jwt, trusted_issuer_public_key_pem: provider.public_to_pem,
80
+ agent_public_key_pem: agent.public_to_pem, trusted_merchant_public_key_pem: merchant.public_to_pem,
81
+ expected_merchant_id: "shop", audience: "merchant-host", nonce: data.fetch("nonce"),
82
+ verified_at: now, signer: signer(agent))
83
+ data.fetch("wires")["checkout_terminal"] = closed.terminal_jws
84
+ data.fetch("wires")["checkout_closed"] = M::ConditionalCheckout.present(
85
+ root_presentation: closed.root_presentation, terminal_jws: closed.terminal_jws,
86
+ checkout_jwt: closed.checkout_jwt).closed_sd_jwt
87
+ payment = expected_payment(data)
88
+ data["expected_payment"] = payment
89
+ data.fetch("wires")["payment_open"] = M::Payment.issue_open(
90
+ open_checkout_sd_jwt: opening.root_presentation,
91
+ constraints: data.fetch("approval").fetch("payment_constraints"), fixed: {},
92
+ agent_public_key_pem: agent.public_to_pem, issued_at: now, expires_at: now + 60,
93
+ signer: signer(provider), public_key_pem: provider.public_to_pem)
94
+ data.fetch("wires")["payment_closed"] = resign(data, now: now)
95
+ data
96
+ end
97
+
98
+ # Select from the CURRENT protected registry, never from JWT headers/claims.
99
+ def public_key(data, role)
100
+ selector = data.fetch("selectors").fetch(role)
101
+ records = data.fetch("trust_snapshot").fetch("records").select do |entry|
102
+ entry.fetch("role").downcase == role &&
103
+ entry.fetch("tenant_id") == data.fetch("order").fetch("tenant_id") &&
104
+ selector.all? { |field, value| entry.fetch(field) == value }
105
+ end
106
+ raise ArgumentError, "missing or ambiguous protected trust record" unless records.length == 1
107
+ records.first.fetch("public_key_pem")
108
+ end
109
+
110
+ def host_inputs(data, now:)
111
+ selectors = data.fetch("selectors").transform_keys(&:to_sym)
112
+ trust = M::InputBuilder.trust(snapshot: data.fetch("trust_snapshot"),
113
+ tenant_id: data.fetch("order").fetch("tenant_id"), verified_at: now,
114
+ profile_ref: CHECKOUT_PROFILE, **selectors)
115
+ {trust: trust, order: data.fetch("order"), root_presentation: data.fetch("wires").fetch("checkout_open"),
116
+ host_checkout_jws: data.fetch("wires").fetch("checkout_jwt")}
117
+ end
118
+
119
+ # Derive from our signed Checkout and separately approved instrument, not
120
+ # from the Payment being verified. Reconstruct on each accept/start call.
121
+ def expected_payment(data)
122
+ M::Payment.details(checkout_jwt: data.fetch("wires").fetch("checkout_jwt"),
123
+ trusted_merchant_public_key_pem: public_key(data, "merchant"),
124
+ expected_merchant_id: data.fetch("order").fetch("merchant_id"),
125
+ payment_instrument: data.fetch("approval").fetch("payment_instrument"))
126
+ end
127
+
128
+ def verification(data, now:)
129
+ # Presentation restores exact saved bytes; it does NOT authenticate them.
130
+ payment = M::Payment.present(open_sd_jwt: data.fetch("wires").fetch("payment_open"),
131
+ closed_sd_jwt: data.fetch("wires").fetch("payment_closed"))
132
+ checkout_inputs = M::InputBuilder.inputs(**host_inputs(data, now: now),
133
+ saved_challenge: M::InputBuilder.restore(saved_challenge: data.fetch("saved_challenge")),
134
+ terminal_jws: data.fetch("wires").fetch("checkout_terminal"),
135
+ expected_challenge_issuer_id: data.fetch("challenge_issuer"),
136
+ clock_source_id: "synthetic-clock", verified_at: now)
137
+ {open_sd_jwt: payment.open_sd_jwt,
138
+ closed_sd_jwt: payment.closed_sd_jwt, checkout_mode: :conditional,
139
+ checkout_inputs: checkout_inputs, expected_payment: expected_payment(data),
140
+ trusted_provider_public_key_pem: public_key(data, "issuer"),
141
+ expected_agent_public_key_pem: public_key(data, "agent"),
142
+ expected_audience: data.fetch("order").fetch("audience"), expected_nonce: data.fetch("nonce"),
143
+ verified_at: now}
144
+ end
145
+
146
+ # Return alternate bytes without ever replacing the first persisted wire.
147
+ def resign(data, now:)
148
+ key = OpenSSL::PKey.read(data.fetch("mock_private_keys").fetch("agent"))
149
+ M::Payment.issue_closed(open_sd_jwt: data.fetch("wires").fetch("payment_open"),
150
+ payment: expected_payment(data), trusted_provider_public_key_pem: public_key(data, "issuer"),
151
+ agent_public_key_pem: public_key(data, "agent"), audience: data.fetch("order").fetch("audience"),
152
+ nonce: data.fetch("nonce"), verified_at: now, signer: signer(key)).closed_sd_jwt
153
+ end
154
+
155
+ # A signed mock outcome proves authenticity/binding, not real settlement.
156
+ def receipt(data, wire:, outcome:, now:)
157
+ fields = case outcome
158
+ when "Success" then {psp_confirmation_id: "synthetic-psp", network_confirmation_id: "synthetic-network"}
159
+ when "Error" then {error: "declined", error_description: "Synthetic processor declined"}
160
+ else raise ArgumentError, "unsupported mock outcome"
161
+ end
162
+ context = data.fetch("receipt_context")
163
+ key = OpenSSL::PKey.read(data.fetch("mock_private_keys").fetch("merchant"))
164
+ M::PaymentReceipt.sign(closed_sd_jwt: wire, issuer: context.fetch("expected_issuer"),
165
+ payment_id: context.fetch("expected_payment_id"), outcome: outcome, issued_at: now,
166
+ signer: signer(key), public_key_pem: context.fetch("trusted_public_key_pem"), **fields).jwt
167
+ end
168
+ end
169
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+ gem "sqlite3", "= 2.10.2"
3
+ require "sqlite3"
4
+ module RubyIntegration
5
+ # Separate mock processor ledger: a committed row IS the synthetic side effect.
6
+ # This is not atomicity between an external PSP and an application's database.
7
+ class Processor
8
+ SCHEMA = "CREATE TABLE results (processor_key TEXT PRIMARY KEY, reference TEXT NOT NULL, receipt TEXT)"
9
+ def self.create(path)
10
+ File.open(path, File::WRONLY | File::CREAT | File::EXCL, 0o600) { |f| f.fsync }
11
+ db = SQLite3::Database.new(path, flags: SQLite3::Constants::Open::READWRITE)
12
+ db.execute(SCHEMA)
13
+ db.close
14
+ end
15
+ def initialize(path)
16
+ @db = SQLite3::Database.new(path, flags: SQLite3::Constants::Open::READWRITE)
17
+ raise "mock storage unavailable" unless @db.get_first_value("PRAGMA quick_check") == "ok" &&
18
+ @db.get_first_value("SELECT sql FROM sqlite_master WHERE name='results'") == SCHEMA
19
+ @db.busy_timeout = 5000
20
+ @db.execute("PRAGMA synchronous=FULL")
21
+ end
22
+ def dispatch(execution, receipt:)
23
+ @db.transaction(:immediate) do
24
+ old = query(execution.processor_key)
25
+ if old
26
+ raise "mock reference conflict" unless old.fetch("reference") == execution.reference
27
+ else
28
+ @db.execute("INSERT INTO results VALUES (?,?,?)", [execution.processor_key, execution.reference, receipt])
29
+ end
30
+ end
31
+ end
32
+ def query(key)
33
+ row = @db.get_first_row("SELECT reference,receipt FROM results WHERE processor_key=?", [key])
34
+ row && {"reference" => row[0], "receipt" => row[1]}
35
+ end
36
+ def count = @db.get_first_value("SELECT count(*) FROM results")
37
+ def close = @db.close
38
+ end
39
+ end
@@ -0,0 +1,161 @@
1
+ # frozen_string_literal: true
2
+ # Ruby-only synthetic application: no network, Rails, A2A or real payment.
3
+ require "ap2_mandate_verifier"
4
+ require "json"
5
+ require_relative "integration/inputs"
6
+ require_relative "integration/processor"
7
+ module RubyIntegration
8
+ M = AP2MandateVerifier
9
+ A = M::PaymentAcceptance
10
+ NOW = 1_800_000_000 # Explicit virtual clock. NEVER use this clock in a real app.
11
+ SCENARIOS = %w[success error pause-before-start expired-before-start crash-before-start crash-after-start crash-after-charge unknown delayed].freeze
12
+ class App
13
+ def self.init(directory)
14
+ # Partial bootstrap is a STOP. Never delete/recreate an existing directory.
15
+ Dir.mkdir(directory, 0o700)
16
+ data = Inputs.bootstrap(now: NOW)
17
+ File.open(File.join(directory, "app.json"), File::WRONLY | File::CREAT | File::EXCL, 0o600) do |file|
18
+ file.write(JSON.generate(data)); file.flush; file.fsync
19
+ end
20
+ store = A::SQLiteStore.create(path: File.join(directory, "acceptance.sqlite3"))
21
+ store.authorize!(**data.fetch("scope").transform_keys(&:to_sym), mode: :conditional,
22
+ profile_ref: M::Payment::PROFILE_REF, checkout: data.fetch("checkout"),
23
+ payment: data.fetch("expected_payment"), receipt_context: data.fetch("receipt_context"))
24
+ store.close
25
+ Processor.create(File.join(directory, "processor.sqlite3"))
26
+ File.open(directory, File::RDONLY) { |file| file.fsync }
27
+ {event: "initialized", sdk_state: "not_reserved", mock_dispatches: 0}
28
+ ensure
29
+ store&.close rescue nil
30
+ end
31
+ def initialize(directory)
32
+ @directory = directory
33
+ @data = current_data
34
+ @scope = @data.fetch("scope").transform_keys(&:to_sym)
35
+ @store = A::SQLiteStore.new(path: File.join(directory, "acceptance.sqlite3"))
36
+ @service = A::Service.new(store: @store)
37
+ @processor = Processor.new(File.join(directory, "processor.sqlite3"))
38
+ end
39
+ def close
40
+ @processor&.close
41
+ @store&.close
42
+ end
43
+ def current_data
44
+ path = File.join(@directory, "app.json")
45
+ raise "application state unavailable" unless File.file?(path) && File.size(path) <= 131_072
46
+ JSON.parse(File.binread(path))
47
+ end
48
+ def run(scenario)
49
+ raise "unknown scenario" unless SCENARIOS.include?(scenario)
50
+ inputs = Inputs.verification(current_data, now: NOW)
51
+ # Educational check only: accept/start reverify raw CURRENT inputs themselves.
52
+ raise "verification failed" unless M::Payment.verify(**inputs).verified?
53
+ accepted = @service.accept(**@scope, mode: :conditional, verification_inputs: inputs)
54
+ unless accepted.ticket
55
+ require_existing!(accepted)
56
+ return summary("no_new_ticket", accepted)
57
+ end
58
+ crash("reserved_before_start", accepted) if scenario == "crash-before-start"
59
+ # Same-process interruption retains the opaque Ticket. Restart does not.
60
+ if scenario == "pause-before-start"
61
+ @store.close
62
+ @store = A::SQLiteStore.new(path: File.join(@directory, "acceptance.sqlite3"))
63
+ @service = A::Service.new(store: @store)
64
+ end
65
+ fresh = Inputs.verification(current_data, now: scenario == "expired-before-start" ? NOW + 61 : NOW)
66
+ execution = @service.start(ticket: accepted.ticket, verification_inputs: fresh)
67
+ return summary("start_blocked", @service.lookup(**@scope)) unless execution
68
+ crash("started_before_dispatch", @service.lookup(**@scope)) if scenario == "crash-after-start"
69
+ issued_at = scenario == "delayed" ? NOW + 120 : NOW
70
+ receipt = unless scenario == "unknown"
71
+ Inputs.receipt(@data, wire: execution.closed_sd_jwt, outcome: scenario == "error" ? "Error" : "Success", now: issued_at)
72
+ end
73
+ @processor.dispatch(execution, receipt: receipt)
74
+ crash("processor_committed_before_finish", @service.lookup(**@scope)) if scenario == "crash-after-charge"
75
+ if %w[unknown delayed].include?(scenario)
76
+ return summary("awaiting_reconciliation", @service.unknown(ticket: accepted.ticket))
77
+ end
78
+ final = @service.finish(ticket: accepted.ticket, receipt_jwt: receipt, verified_at: NOW)
79
+ raise "Receipt finalization failed" unless %i[receipt_success receipt_error].include?(final.status)
80
+ summary("finished", final)
81
+ end
82
+ def retry(resigned: false)
83
+ fresh = Inputs.verification(current_data, now: NOW)
84
+ fresh[:closed_sd_jwt] = Inputs.resign(@data, now: NOW) if resigned
85
+ previous = @service.lookup(**@scope)
86
+ raise "no existing attempt" unless previous.processor_key
87
+ result = @service.accept(**@scope, mode: :conditional, verification_inputs: fresh)
88
+ raise "retry changed identity" if result.ticket || result.processor_key != previous.processor_key ||
89
+ result.closed_sd_jwt != previous.closed_sd_jwt || result.reference != previous.reference
90
+ summary(resigned ? "resigned_retry" : "exact_retry", result).merge(original_identity_preserved: true)
91
+ end
92
+ def recover
93
+ original = @service.lookup(**@scope)
94
+ require_existing!(original)
95
+ saved = @processor.query(original.processor_key) # QUERY only, never dispatch.
96
+ raise "processor reference mismatch" if saved && saved.fetch("reference") != original.reference
97
+ receipt = saved && saved.fetch("receipt")
98
+ unless receipt
99
+ return summary("operator_reconciliation_required", original).merge(result: "unknown")
100
+ end
101
+ # Receipt window is independent of the expired Mandate/challenge.
102
+ final = @service.reconcile(**@scope, receipt_jwt: receipt, verified_at: NOW + 120)
103
+ raise "recovery changed identity" if final.ticket || (final.processor_key && final.processor_key != original.processor_key)
104
+ raise "Receipt reconciliation failed" unless %i[receipt_success receipt_error].include?(final.status)
105
+ summary("reconciled", final)
106
+ end
107
+ def require_existing!(result)
108
+ raise "attempt unavailable or invalid" unless result.processor_key &&
109
+ %i[pending unknown receipt_success receipt_error].include?(result.status)
110
+ end
111
+ def inspect_state
112
+ result = @service.lookup(**@scope)
113
+ require_existing!(result)
114
+ summary("inspection", result)
115
+ end
116
+ def summary(event, result)
117
+ raise "invalid result state" unless result.processor_key &&
118
+ %i[reserved pending unknown receipt_success receipt_error].include?(result.status)
119
+ value = {event: event, sdk_state: result.status, ticket: !result.ticket.nil?, mock_dispatches: @processor.count}
120
+ if %i[receipt_success receipt_error].include?(result.status)
121
+ value[:receipt_authentic] = true
122
+ value[:reported_outcome] = result.status == :receipt_success ? "Success" : "Error"
123
+ end
124
+ value
125
+ end
126
+ def crash(event, result)
127
+ puts JSON.generate(summary(event, result).merge(simulated_process_exit: 75))
128
+ $stdout.flush
129
+ Process.exit!(75) # No ensure/normal cleanup; next CLI is a different Ruby process.
130
+ end
131
+ end
132
+ def self.cli(args)
133
+ command, directory, option = args
134
+ raise "invalid command" unless args.size.between?(2, 3) && directory &&
135
+ %w[init run recover retry inspect].include?(command) &&
136
+ (command == "run" || command == "retry" || option.nil?) &&
137
+ (command != "retry" || option.nil? || option == "resigned")
138
+ result = if command == "init"
139
+ App.init(directory)
140
+ else
141
+ app = App.new(directory)
142
+ case command
143
+ when "run" then app.run(option || "success")
144
+ when "retry" then app.retry(resigned: option == "resigned")
145
+ when "recover" then app.recover
146
+ when "inspect" then app.inspect_state
147
+ end
148
+ end
149
+ feature = $LOADED_FEATURES.find { |path| path.end_with?("/ap2_mandate_verifier.rb") }
150
+ spec = Gem.loaded_specs["ap2_mandate_verifier"]
151
+ puts JSON.generate(result.merge(sdk_version: spec&.version&.to_s || "source",
152
+ sdk_load: spec && feature.start_with?(spec.full_gem_path + "/") ? "installed_gem" : "repository_lib",
153
+ ruby: RUBY_VERSION, fixture_clock: NOW))
154
+ rescue StandardError, LoadError
155
+ warn "STOP: invalid command or unavailable/inconsistent state; preserve all files and investigate."
156
+ return 1
157
+ ensure
158
+ app&.close
159
+ end
160
+ end
161
+ exit(RubyIntegration.cli(ARGV) || 0) if $PROGRAM_NAME == __FILE__
@@ -8,7 +8,11 @@ module AP2MandateVerifier
8
8
  FIELDS = %w[transaction_id payee payment_amount payment_instrument].freeze
9
9
  MAX_LIFETIME = 600
10
10
  class Invalid < ArgumentError
11
- def initialize = super("invalid payment information")
11
+ attr_reader :diagnostic_reason
12
+ def initialize
13
+ @diagnostic_reason = :undetermined
14
+ super("invalid payment information")
15
+ end
12
16
  end
13
17
  class Presentation
14
18
  attr_reader :open_sd_jwt, :closed_sd_jwt
@@ -20,9 +24,10 @@ module AP2MandateVerifier
20
24
  private_class_method :new
21
25
  end
22
26
  class Verification
23
- attr_reader :code, :payment, :reference, :expires_at
24
- def initialize(payment = nil, wire = nil)
27
+ attr_reader :code, :payment, :reference, :expires_at, :diagnostic
28
+ def initialize(payment = nil, wire = nil, reason: :undetermined)
25
29
  @code = payment ? :payment_verified : :payment_verification_failed
30
+ @diagnostic = PaymentDiagnostics.build(:payment_verification, reason) unless payment
26
31
  if payment
27
32
  @payment = ResearchEvidence.send(:copy_frozen, payment)
28
33
  @reference = Payment.send(:digest, wire).freeze
@@ -174,53 +179,54 @@ module AP2MandateVerifier
174
179
  when :direct
175
180
  raise Invalid if open_sd_jwt || expected_agent_public_key_pem || expected_audience || expected_nonce
176
181
  checked = Buyer.verify(**checkout_inputs)
177
- raise Invalid unless checked.verified? && expected.fetch("transaction_id") == checked.checkout_hash
182
+ raise PaymentDiagnostics.invalid(Invalid, :checkout_not_verified) unless checked.verified?
183
+ raise PaymentDiagnostics.invalid(Invalid, :checkout_binding_mismatch) unless expected.fetch("transaction_id") == checked.checkout_hash
178
184
  bind_checkout!(expected, checked.checkout)
179
185
  claims, wire = verified_root!(closed_sd_jwt, trusted_provider_public_key_pem, profile_ref: profile_ref)
180
186
  when :conditional
181
187
  checked = AP2MandateVerifier.verify_checkout(**checkout_inputs)
182
- raise Invalid unless checked.success?
188
+ raise PaymentDiagnostics.invalid(Invalid, :checkout_not_verified) unless checked.success?
183
189
  checkout = checkout_inputs.fetch(:host_checkout_jws)
184
- raise Invalid unless expected.fetch("transaction_id") == digest(checkout)
190
+ raise PaymentDiagnostics.invalid(Invalid, :checkout_binding_mismatch) unless expected.fetch("transaction_id") == digest(checkout)
185
191
  # Fully verified Host evidence binds independent Merchant order state.
186
192
  binding = checked.evidence["checkout_binding"]
187
193
  amount = expected.fetch("payment_amount")
188
- raise Invalid unless expected.fetch("payee").fetch("id") == binding.fetch("merchant_id") &&
194
+ raise PaymentDiagnostics.invalid(Invalid, :checkout_binding_mismatch) unless expected.fetch("payee").fetch("id") == binding.fetch("merchant_id") &&
189
195
  amount.fetch("currency") == binding.fetch("currency") && amount.fetch("amount") == binding.fetch("expected_total")
190
196
  # Full Checkout verifier already authenticated these exact JWT bytes.
191
197
  payload = jwt_payload!(checkout, "JWT")
192
198
  bind_checkout!(expected, payload)
193
199
  opening, root = verified_root!(open_sd_jwt, trusted_provider_public_key_pem, profile_ref: profile_ref)
194
200
  open!(opening, profile_ref: profile_ref); valid_now!(opening, verified_at)
195
- raise Invalid unless opening.fetch("cnf") == {"jwk" => RootSignature.public_jwk!(expected_agent_public_key_pem)}
201
+ raise PaymentDiagnostics.invalid(Invalid, :payment_binding_mismatch) unless opening.fetch("cnf") == {"jwk" => RootSignature.public_jwk!(expected_agent_public_key_pem)}
196
202
  terminal, wire = final!(closed_sd_jwt, conditional: true, profile_ref: profile_ref)
197
203
  RootSignature.verified_payload!(wire.split("~", -1).first, expected_agent_public_key_pem,
198
204
  expected_typ: "kb+sd-jwt", max_bytes: 32_768)
199
205
  expected_audience = InputValidator.snapshot!(expected_audience, max_bytes: 512)
200
206
  expected_nonce = InputValidator.snapshot!(expected_nonce, max_bytes: 512)
201
207
  text!(expected_audience, 512); text!(expected_nonce, 512)
202
- raise Invalid unless terminal.fetch("aud") == expected_audience && terminal.fetch("nonce") == expected_nonce &&
208
+ raise PaymentDiagnostics.invalid(Invalid, :payment_binding_mismatch) unless terminal.fetch("aud") == expected_audience && terminal.fetch("nonce") == expected_nonce &&
203
209
  terminal.fetch("sd_hash") == digest(root) && terminal.fetch("iat") <= verified_at &&
204
210
  verified_at - terminal.fetch("iat") <= 300
205
211
  claims = terminal.fetch("delegate_payload").first
206
212
  closed!(claims, profile_ref: profile_ref); valid_now!(claims, verified_at)
207
213
  if PaymentPolicy.long?(profile_ref)
208
- raise Invalid unless %w[iat exp].all? { |f| claims.fetch(f) == opening.fetch(f) }
214
+ raise PaymentDiagnostics.invalid(Invalid, :payment_binding_mismatch) unless %w[iat exp].all? { |f| claims.fetch(f) == opening.fetch(f) }
209
215
  else
210
- raise Invalid unless terminal.fetch("iat") == claims.fetch("iat") && claims.fetch("iat") >= opening.fetch("iat") &&
216
+ raise PaymentDiagnostics.invalid(Invalid, :payment_binding_mismatch) unless terminal.fetch("iat") == claims.fetch("iat") && claims.fetch("iat") >= opening.fetch("iat") &&
211
217
  claims.fetch("exp") <= opening.fetch("exp")
212
218
  end
213
219
  conditions!(opening, claims, profile_ref: profile_ref)
214
220
  reference = opening.fetch("constraints").find { |c| c["type"] == "payment.reference" }
215
- raise Invalid unless reference.fetch("conditional_transaction_id") == digest(checkout_inputs.fetch(:root_presentation))
221
+ raise PaymentDiagnostics.invalid(Invalid, :checkout_binding_mismatch) unless reference.fetch("conditional_transaction_id") == digest(checkout_inputs.fetch(:root_presentation))
216
222
  else raise Invalid
217
223
  end
218
224
  closed!(claims, profile_ref: profile_ref); valid_now!(claims, verified_at)
219
225
  PaymentPolicy.bind_context!(claims, context) if context
220
- raise Invalid unless claims.slice(*PaymentPolicy.fields(profile_ref)) == expected
226
+ raise PaymentDiagnostics.invalid(Invalid, :payment_binding_mismatch) unless claims.slice(*PaymentPolicy.fields(profile_ref)) == expected
221
227
  Verification.send(:new, claims, wire)
222
- rescue StandardError, LoadError
223
- Verification.send(:new)
228
+ rescue StandardError, LoadError => error
229
+ Verification.send(:new, reason: PaymentDiagnostics.reason(error))
224
230
  end
225
231
 
226
232
  def self.reference(closed_sd_jwt:, profile_ref: PROFILE_REF)
@@ -313,14 +319,14 @@ module AP2MandateVerifier
313
319
  conditions!(base, closed)
314
320
  return nil
315
321
  end
316
- FIELDS.drop(1).each { |f| raise Invalid if opening.key?(f) && opening[f] != closed[f] }
322
+ FIELDS.drop(1).each { |f| raise PaymentDiagnostics.invalid(Invalid, :payment_conditions_mismatch) if opening.key?(f) && opening[f] != closed[f] }
317
323
  opening.fetch("constraints").each do |c|
318
324
  case c["type"]
319
- when "payment.allowed_payees" then raise Invalid unless c["allowed"].include?(closed["payee"])
320
- when "payment.allowed_payment_instruments" then raise Invalid unless c["allowed"].include?(closed["payment_instrument"])
325
+ when "payment.allowed_payees" then raise PaymentDiagnostics.invalid(Invalid, :payment_conditions_mismatch) unless c["allowed"].include?(closed["payee"])
326
+ when "payment.allowed_payment_instruments" then raise PaymentDiagnostics.invalid(Invalid, :payment_conditions_mismatch) unless c["allowed"].include?(closed["payment_instrument"])
321
327
  when "payment.amount_range"
322
328
  a = closed.fetch("payment_amount")
323
- raise Invalid unless a["currency"] == c["currency"] && a["amount"].between?(c.fetch("min", 0), c["max"])
329
+ raise PaymentDiagnostics.invalid(Invalid, :payment_conditions_mismatch) unless a["currency"] == c["currency"] && a["amount"].between?(c.fetch("min", 0), c["max"])
324
330
  when "payment.reference" # Checked against the verified Checkout chain in verify.
325
331
  else raise Invalid
326
332
  end
@@ -346,7 +352,7 @@ module AP2MandateVerifier
346
352
  end
347
353
  def self.valid_now!(v, now)
348
354
  CheckoutReceipt.send(:epoch!, now)
349
- raise Invalid unless v.fetch("iat") <= now && now < v.fetch("exp")
355
+ raise PaymentDiagnostics.invalid(Invalid, :payment_time_mismatch) unless v.fetch("iat") <= now && now < v.fetch("exp")
350
356
  end
351
357
  def self.checkout_open!(wire, profile_ref: ScopedConstraints::MULTI_PROFILE_REF)
352
358
  wire = InputValidator.snapshot!(wire)
@@ -447,7 +453,7 @@ module AP2MandateVerifier
447
453
  fields = implementation.parameters.map(&:last).freeze
448
454
  define_singleton_method(name) do |**args|
449
455
  unless (required - args.keys).empty? && (args.keys - fields).empty?
450
- next Verification.send(:new) if name == :verify
456
+ next Verification.send(:new, reason: :invalid_arguments) if name == :verify
451
457
  raise Invalid
452
458
  end
453
459
  implementation.call(**args)
@@ -5,7 +5,11 @@ module AP2MandateVerifier
5
5
  module PaymentAcceptance
6
6
  SCOPE = %w[tenant_id merchant_id operation_id approval_id occurrence_id order_id].freeze
7
7
  class Invalid < ArgumentError
8
- def initialize = super("invalid payment acceptance information")
8
+ attr_reader :diagnostic_reason
9
+ def initialize
10
+ @diagnostic_reason = :undetermined
11
+ super("invalid payment acceptance information")
12
+ end
9
13
  end
10
14
  class Unavailable < StandardError
11
15
  def initialize = super("payment acceptance storage unavailable")
@@ -23,9 +27,12 @@ module AP2MandateVerifier
23
27
  private_class_method :new
24
28
  end
25
29
  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)
30
+ attr_reader :diagnostic, :status, :ticket, :closed_sd_jwt, :reference, :receipt_jwt, :processor_key, :signed_wires
31
+ def initialize(status, record = nil, ticket = nil, reason: nil)
28
32
  @status, @ticket = status, ticket
33
+ unless %i[reserved receipt_success].include?(status)
34
+ @diagnostic = PaymentDiagnostics.build(:payment_acceptance, reason || (%i[conflict unavailable pending unknown receipt_error].include?(status) ? status : :undetermined))
35
+ end
29
36
  if record
30
37
  @closed_sd_jwt, @reference, @receipt_jwt = record.values_at("closed_sd_jwt", "reference", "receipt_jwt").map { |v| v&.freeze }
31
38
  @processor_key = record.fetch("processor_key").freeze
@@ -48,6 +55,18 @@ module AP2MandateVerifier
48
55
  private_class_method :new
49
56
  end
50
57
 
58
+ # Per-call immutable observation; never an authorization or retry instruction.
59
+ class StartResult
60
+ attr_reader :execution, :diagnostic
61
+ def initialize(execution, reason = :undetermined)
62
+ @execution = execution
63
+ @diagnostic = PaymentDiagnostics.build(:payment_execution, reason) unless execution
64
+ freeze
65
+ end
66
+ def inspect = "#<AP2MandateVerifier::PaymentAcceptance::StartResult>"
67
+ private_class_method :new
68
+ end
69
+
51
70
  class Service
52
71
  def initialize(**arguments)
53
72
  raise Invalid.new, cause: nil unless arguments.keys == [:store]
@@ -64,14 +83,24 @@ module AP2MandateVerifier
64
83
  Result.send(:new, :conflict)
65
84
  rescue Unavailable
66
85
  Result.send(:new, :unavailable)
86
+ rescue Invalid => error
87
+ Result.send(:new, :rejected, reason: error.diagnostic_reason)
67
88
  rescue StandardError, LoadError
68
89
  Result.send(:new, :rejected)
69
90
  end
70
91
 
71
92
  def start(ticket:, verification_inputs:)
93
+ start_observation(ticket: ticket, verification_inputs: verification_inputs).execution
94
+ end
95
+
96
+ def start_with_diagnostic(ticket:, verification_inputs:)
97
+ start_observation(ticket: ticket, verification_inputs: verification_inputs)
98
+ end
99
+
100
+ def start_observation(ticket:, verification_inputs:)
72
101
  old = @store.ticket_record!(ticket: ticket)
73
102
  fresh = verified_record(old.fetch("mode").to_sym, verification_inputs, old.fetch("scope"))
74
- raise Invalid unless old.fetch("instruction") == fresh.fetch("instruction") && old.fetch("signed_wires") == fresh.fetch("signed_wires")
103
+ raise PaymentDiagnostics.invalid(Invalid, :saved_binding_mismatch) unless old.fetch("instruction") == fresh.fetch("instruction") && old.fetch("signed_wires") == fresh.fetch("signed_wires")
75
104
  record = if LongPayment.profile?(old.fetch("profile_ref"))
76
105
  @store.start_long!(ticket: ticket, verified_at: fresh.fetch("accepted_at"),
77
106
  instruction: fresh.fetch("instruction"), signed_wires: fresh.fetch("signed_wires"),
@@ -84,12 +113,22 @@ module AP2MandateVerifier
84
113
  # Existing adapters retain their public signature. The returned handle
85
114
  # must still expose the freshly verified shorter Host deadline.
86
115
  record = record.merge("valid_until" => [record.fetch("valid_until"), fresh.fetch("valid_until")].min)
87
- Execution.send(:new, record)
116
+ StartResult.send(:new, Execution.send(:new, record))
117
+ else
118
+ StartResult.send(:new, nil)
88
119
  end
120
+ rescue Unavailable
121
+ StartResult.send(:new, nil, :unavailable)
122
+ rescue Conflict
123
+ StartResult.send(:new, nil, :conflict)
124
+ rescue Invalid => error
125
+ StartResult.send(:new, nil, error.diagnostic_reason)
89
126
  rescue StandardError, LoadError
90
- nil # An uncertain commit NEVER produces an execution handle.
127
+ StartResult.send(:new, nil) # An uncertain commit NEVER produces a handle.
91
128
  end
92
129
 
130
+ private :start_observation
131
+
93
132
  private
94
133
  def verified_record(mode, verification_inputs, scope)
95
134
  args = PaymentAcceptance.copy!(verification_inputs)
@@ -102,7 +141,7 @@ module AP2MandateVerifier
102
141
  when :selective then SelectivePayment.verify(**args)
103
142
  else raise Invalid
104
143
  end
105
- raise Invalid unless result.verified?
144
+ raise PaymentDiagnostics.invalid(Invalid, :payment_not_verified) unless result.verified?
106
145
  checkout_args = args.fetch(:checkout_inputs)
107
146
  if mode == :direct
108
147
  checkout = Buyer.verify(**checkout_args)
@@ -150,6 +189,8 @@ module AP2MandateVerifier
150
189
  Result.send(:new, :conflict)
151
190
  rescue Unavailable
152
191
  Result.send(:new, :unavailable)
192
+ rescue Invalid => error
193
+ Result.send(:new, :rejected, reason: error.diagnostic_reason)
153
194
  rescue StandardError, LoadError
154
195
  Result.send(:new, :rejected)
155
196
  end
@@ -172,6 +213,8 @@ module AP2MandateVerifier
172
213
  Result.send(:new, :conflict)
173
214
  rescue Unavailable
174
215
  Result.send(:new, :unavailable)
216
+ rescue Invalid => error
217
+ Result.send(:new, :rejected, reason: error.diagnostic_reason)
175
218
  rescue StandardError, LoadError
176
219
  Result.send(:new, :rejected)
177
220
  end
@@ -194,12 +237,12 @@ module AP2MandateVerifier
194
237
  receipt = PaymentReceipt.verify(jwt: jwt, closed_sd_jwt: record.fetch("closed_sd_jwt"),
195
238
  profile_ref: record.fetch("profile_ref") == SelectivePayment::PROFILE_REF ? Payment::PROFILE_REF : record.fetch("profile_ref"),
196
239
  verified_at: verified_at, **context)
197
- raise Invalid unless receipt.verified?
240
+ raise PaymentDiagnostics.invalid(Invalid, :receipt_not_verified) unless receipt.verified?
198
241
  status = receipt.payment_succeeded? ? "receipt_success" : "receipt_error"
199
242
  @store.finish!(scope: record.fetch("scope"), ticket: ticket, receipt_jwt: jwt, status: status)
200
243
  end
201
244
 
202
- %i[accept start finish unknown reconcile lookup].each do |name|
245
+ %i[accept start start_with_diagnostic finish unknown reconcile lookup].each do |name|
203
246
  implementation = instance_method(name)
204
247
  required = implementation.parameters.filter_map { |kind, key| key if kind == :keyreq }.freeze
205
248
  allowed = implementation.parameters.filter_map { |kind, key| key if %i[keyreq key].include?(kind) }.freeze
@@ -208,7 +251,13 @@ module AP2MandateVerifier
208
251
  raise Invalid unless (required - arguments.keys).empty? && (rest || (arguments.keys - allowed).empty?)
209
252
  implementation.bind_call(self, **arguments)
210
253
  rescue StandardError, LoadError
211
- name == :start ? nil : Result.send(:new, :rejected)
254
+ if name == :start
255
+ nil
256
+ elsif name == :start_with_diagnostic
257
+ StartResult.send(:new, nil)
258
+ else
259
+ Result.send(:new, :rejected)
260
+ end
212
261
  end
213
262
  public name
214
263
  end