ap2_mandate_verifier 0.4.0 → 0.6.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,145 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ # Checkout-specific pinned Schema; independent of Verifier Result/Evidence.
5
+ module CheckoutReceipt
6
+ class Invalid < ArgumentError
7
+ def initialize = super("invalid checkout receipt information")
8
+ end
9
+ class Signed
10
+ attr_reader :jwt, :reference
11
+ def initialize(jwt, reference)
12
+ @jwt, @reference = jwt.freeze, reference.freeze
13
+ freeze
14
+ end
15
+ private_class_method :new
16
+ end
17
+ class Verification
18
+ attr_reader :code, :outcome, :order_id, :error, :error_description
19
+ def initialize(code, claims = nil)
20
+ @code = code
21
+ if claims
22
+ @outcome = claims.fetch("status").freeze
23
+ @order_id, @error, @error_description = claims.values_at("order_id", "error", "error_description").map { |v| v&.freeze }
24
+ end
25
+ freeze
26
+ end
27
+ def verified? = code == :receipt_verified
28
+ def purchase_succeeded? = verified? && outcome == "Success"
29
+ def purchase_rejected? = verified? && outcome == "Error"
30
+ private_class_method :new
31
+ end
32
+
33
+ # Exact received final closed SD-JWT, no disclosures or additional hop.
34
+ # A terminal compact JWS alone is intentionally not accepted or repaired.
35
+ def self.reference(closed_sd_jwt:, profile_ref: TrustContext::PROFILE_REF)
36
+ wire = InputValidator.snapshot!(closed_sd_jwt, max_bytes: 32_769)
37
+ raise Invalid unless wire.ascii_only? && wire.end_with?("~") && wire.count("~") == 1
38
+ compact = wire.byteslice(0, wire.bytesize - 1)
39
+ parts = compact.split(".", -1)
40
+ raise Invalid unless parts.size == 3
41
+ RootSignature.send(:dependencies!)
42
+ header = InputValidator.parse!(RootSignature.send(:decode!, parts[0], 2_048))
43
+ claims = InputValidator.parse!(RootSignature.send(:decode!, parts[1], 24_576))
44
+ signature = RootSignature.send(:decode!, parts[2], 64)
45
+ header!(header, "kb+sd-jwt")
46
+ raise Invalid unless signature.bytesize == 64
47
+ # Existing inline terminal grammar only, never general SD resolution.
48
+ PurchaseBinding.send(:exact!, claims, %w[aud delegate_payload iat nonce sd_hash])
49
+ %w[aud nonce sd_hash].each { |field| text!(claims[field], 512) }
50
+ epoch!(claims["iat"])
51
+ raise Invalid unless claims["sd_hash"].match?(/\A[A-Za-z0-9_-]{43}\z/)
52
+ closed = ScopedConstraints.send(:one!, claims["delegate_payload"])
53
+ PurchaseBinding.send(:exact!, closed, %w[checkout_hash checkout_jwt exp iat vct])
54
+ raise Invalid unless closed["vct"] == "mandate.checkout.1"
55
+ epoch!(closed["iat"]); epoch!(closed["exp"])
56
+ raise Invalid unless closed["exp"] > closed["iat"] && closed["checkout_hash"].instance_of?(String) &&
57
+ closed["checkout_hash"].match?(/\A[A-Za-z0-9_-]{43}\z/)
58
+ checkout = InputValidator.snapshot!(closed["checkout_jwt"], max_bytes: 16_384)
59
+ raise Invalid unless checkout.ascii_only? && checkout.split(".", -1).size == 3 &&
60
+ checkout.split(".", -1).all? { |part| part.match?(/\A[A-Za-z0-9_-]+\z/) }
61
+ checkout_parts = checkout.split(".", -1)
62
+ checkout_header = InputValidator.parse!(RootSignature.send(:decode!, checkout_parts[0], 2_048))
63
+ header!(checkout_header, "JWT")
64
+ raise Invalid unless RootSignature.send(:decode!, checkout_parts[2], 64).bytesize == 64
65
+ CheckoutJWT.send(:validate!, InputValidator.parse!(RootSignature.send(:decode!, checkout_parts[1], 12_000)), profile_ref: profile_ref)
66
+ raise Invalid unless closed["checkout_hash"] == hash(checkout)
67
+ hash(wire).freeze
68
+ rescue StandardError, LoadError
69
+ raise Invalid.new, cause: nil
70
+ end
71
+
72
+ def self.sign(closed_sd_jwt:, issuer:, outcome:, issued_at:, signer:, public_key_pem:, order_id: nil, error: nil, error_description: nil,
73
+ profile_ref: TrustContext::PROFILE_REF)
74
+ ref = reference(closed_sd_jwt: closed_sd_jwt, profile_ref: profile_ref)
75
+ claims = {"iss" => issuer, "status" => outcome, "iat" => issued_at, "reference" => ref}
76
+ claims["order_id"] = order_id unless order_id.nil?
77
+ claims["error"] = error unless error.nil?
78
+ claims["error_description"] = error_description unless error_description.nil?
79
+ claims = InputBuilder.send(:copy!, claims)
80
+ validate!(claims)
81
+ jwt = MerchantSignature.sign!(claims, signer, public_key_pem)
82
+ Signed.send(:new, jwt, ref)
83
+ rescue StandardError, LoadError
84
+ raise Invalid.new, cause: nil
85
+ end
86
+
87
+ # The Host supplies trusted enrollment key, expected signer and explicit time
88
+ # window independently. JWT iss/kid are never used to choose trust.
89
+ # Reference authenticates byte identity, not Mandate authorization/validity.
90
+ def self.verify(jwt:, closed_sd_jwt:, trusted_public_key_pem:, expected_issuer:, not_before:, not_after:, verified_at:,
91
+ profile_ref: TrustContext::PROFILE_REF)
92
+ expected = InputValidator.snapshot!(expected_issuer, max_bytes: 512)
93
+ text!(expected, 512)
94
+ [not_before, not_after, verified_at].each { |t| epoch!(t) }
95
+ raise Invalid unless not_before <= verified_at && verified_at <= not_after
96
+ ref = reference(closed_sd_jwt: closed_sd_jwt, profile_ref: profile_ref)
97
+ claims = RootSignature.verified_payload!(jwt, trusted_public_key_pem, expected_typ: "JWT", max_bytes: 16_384)
98
+ validate!(claims)
99
+ return Verification.send(:new, :receipt_issuer_mismatch) unless claims["iss"] == expected
100
+ return Verification.send(:new, :receipt_reference_mismatch) unless claims["reference"] == ref
101
+ return Verification.send(:new, :receipt_time_mismatch) unless claims["iat"].between?(not_before, verified_at)
102
+ Verification.send(:new, :receipt_verified, claims)
103
+ rescue StandardError, LoadError
104
+ Verification.send(:new, :receipt_verification_failed)
105
+ end
106
+
107
+ def self.validate!(claims)
108
+ raise Invalid unless claims.instance_of?(Hash)
109
+ fields = case claims["status"]
110
+ when "Success" then %w[iss status iat reference order_id]
111
+ when "Error" then %w[iss status iat reference error error_description]
112
+ else raise Invalid
113
+ end
114
+ raise Invalid unless claims.keys.sort == fields.sort
115
+ epoch!(claims["iat"])
116
+ (fields - %w[iat]).each { |field| text!(claims[field], field == "error_description" ? 2_048 : 512) }
117
+ raise Invalid unless claims["reference"].match?(/\A[A-Za-z0-9_-]{43}\z/)
118
+ end
119
+ def self.text!(value, max)
120
+ raise Invalid unless value.instance_of?(String) && value.bytesize.between?(1, max)
121
+ end
122
+ def self.epoch!(value)
123
+ raise Invalid unless Object.instance_method(:instance_of?).bind_call(value, Integer) && value.between?(0, PurchaseBinding::MAX_EPOCH)
124
+ end
125
+ def self.header!(header, typ)
126
+ raise Invalid unless header.instance_of?(Hash) && (header.keys - %w[alg typ kid]).empty? &&
127
+ header["alg"] == "ES256" && header["typ"] == typ
128
+ text!(header["kid"], 128) if header.key?("kid")
129
+ end
130
+ def self.hash(wire) = Base64.urlsafe_encode64(Digest::SHA256.digest(wire), padding: false)
131
+ %i[reference sign verify].each do |name|
132
+ implementation = method(name)
133
+ required = implementation.parameters.filter_map { |kind, field| field if kind == :keyreq }.freeze
134
+ fields = implementation.parameters.filter_map { |kind, field| field if %i[key keyreq].include?(kind) }.freeze
135
+ define_singleton_method(name) do |**arguments|
136
+ unless (required - arguments.keys).empty? && (arguments.keys - fields).empty?
137
+ next Verification.send(:new, :receipt_verification_failed) if name == :verify
138
+ raise Invalid.new, cause: nil
139
+ end
140
+ implementation.call(**arguments)
141
+ end
142
+ end
143
+ private_class_method :validate!, :text!, :epoch!, :header!, :hash
144
+ end
145
+ end
@@ -78,7 +78,8 @@ module AP2MandateVerifier
78
78
  host_checkout_jws: checkout, **context.fetch(:keys), expected_aud: binding["audience"],
79
79
  expected_nonce: challenge["nonce"], verified_at: verified_at,
80
80
  expected_checkout_id: binding["order_id"], expected_merchant_id: binding["merchant_id"],
81
- expected_currency: binding["currency"], expected_total_minor: binding["expected_total"])
81
+ expected_currency: binding["currency"], expected_total_minor: binding["expected_total"],
82
+ profile_ref: references.fetch("profile_ref"))
82
83
  open, closed, proof = details.values_at(:open, :closed, :terminal)
83
84
  starts = [context.fetch(:valid_from), challenge["not_before"], open["iat"], closed["iat"], proof["iat"]]
84
85
  ends = [context.fetch(:valid_until), challenge["not_after"], open["exp"], closed["exp"], proof["iat"] + 301]
@@ -33,28 +33,29 @@ module AP2MandateVerifier
33
33
 
34
34
  # All registry entries are preserved, including inactive/nonselected entries.
35
35
  # Selection is explicit Host policy, never extracted from signed claims.
36
- def self.trust(snapshot:, tenant_id:, issuer:, agent:, merchant:, verified_at:)
36
+ def self.trust(snapshot:, tenant_id:, issuer:, agent:, merchant:, verified_at:, profile_ref: TrustContext::PROFILE_REF)
37
37
  verified_at = copy!(verified_at)
38
+ profile = TrustContext.profile!(copy!(profile_ref))
38
39
  source = copy!(snapshot)
39
40
  shape!(source, %w[id policy_version active not_before not_after records], "snapshot")
40
41
  invalid!("snapshot.records", :invalid_type) unless source["records"].instance_of?(Array)
41
42
  invalid!("snapshot.records", :invalid_value) unless source["records"].length.between?(1, 16)
42
43
  source["records"].each do |record|
43
44
  shape!(record, RECORD_FIELDS)
44
- record.merge!("profile_ref" => TrustContext::PROFILE_REF, "profile_version" => TrustContext::PROFILE_VERSION,
45
+ record.merge!("profile_ref" => profile[:ref], "profile_version" => profile[:version],
45
46
  "algorithm" => "ES256", "key_fingerprint" => Digest::SHA256.hexdigest(record.fetch("public_key_pem")))
46
47
  end
47
48
  body = json!(source, 65_536)
48
49
  selection = {"trust_snapshot_id" => source["id"], "policy_version" => source["policy_version"],
49
50
  "trust_content_hash" => Digest::SHA256.hexdigest(body), "tenant_id" => copy!(tenant_id),
50
- "profile_ref" => TrustContext::PROFILE_REF, "profile_version" => TrustContext::PROFILE_VERSION,
51
- "profile_definition_hash" => TrustContext::PROFILE_HASH,
51
+ "profile_ref" => profile[:ref], "profile_version" => profile[:version],
52
+ "profile_definition_hash" => profile[:hash],
52
53
  "Issuer" => copy!(issuer), "Agent" => copy!(agent), "Merchant" => copy!(merchant)}
53
54
  TrustContext::ROLES.each_key { |role| shape!(selection[role], %w[identity purpose key_ref], role.downcase) }
54
55
  wire = json!({"snapshot" => {"id" => source["id"], "policy_version" => source["policy_version"],
55
56
  "content_hash" => selection["trust_content_hash"], "body" => body},
56
- "profile" => {"profile_ref" => TrustContext::PROFILE_REF, "version" => TrustContext::PROFILE_VERSION,
57
- "definition_hash" => TrustContext::PROFILE_HASH, "body" => TrustContext::PROFILE_BODY}})
57
+ "profile" => {"profile_ref" => profile[:ref], "version" => profile[:version],
58
+ "definition_hash" => profile[:hash], "body" => profile[:body]}})
58
59
  selected = json!(selection, 16_384)
59
60
  context = TrustContext.verified_context!(trust_json: wire, selection_json: selected, verified_at: verified_at,
60
61
  expected_merchant_id: selection.fetch("Merchant").fetch("identity"))
@@ -94,8 +95,8 @@ module AP2MandateVerifier
94
95
  "B" => binding!(context, order, root_presentation, host_checkout_jws),
95
96
  "not_before" => copy!(not_before), "not_after" => copy!(not_after), "state" => "issued"}
96
97
  HostBinding::REFERENCES.each { |field| challenge[field] = context.fetch(:references).fetch(field) }
97
- saved = json!({"format_version" => FORMAT_VERSION, "profile_ref" => TrustContext::PROFILE_REF,
98
- "profile_version" => TrustContext::PROFILE_VERSION, "challenge" => challenge}, 32_768)
98
+ saved = json!({"format_version" => FORMAT_VERSION, "profile_ref" => context.fetch(:references).fetch("profile_ref"),
99
+ "profile_version" => context.fetch(:references).fetch("profile_version"), "challenge" => challenge}, 32_768)
99
100
  restore(saved_challenge: saved)
100
101
  rescue Invalid
101
102
  raise
@@ -111,13 +112,16 @@ module AP2MandateVerifier
111
112
  wire = InputValidator.snapshot!(saved_challenge, max_bytes: 32_768)
112
113
  value = InputValidator.parse!(wire)
113
114
  shape!(value, %w[format_version profile_ref profile_version challenge], "saved_challenge")
115
+ invalid!("saved_challenge", :unsupported_saved_format) unless
116
+ [TrustContext::PROFILE_REF, TrustContext::MULTI_PROFILE_REF].include?(value["profile_ref"])
117
+ profile = TrustContext.profile!(value["profile_ref"])
114
118
  invalid!("saved_challenge", :unsupported_saved_format) unless value.values_at("format_version", "profile_ref", "profile_version") ==
115
- [FORMAT_VERSION, TrustContext::PROFILE_REF, TrustContext::PROFILE_VERSION]
119
+ [FORMAT_VERSION, profile[:ref], profile[:version]]
116
120
  challenge = value["challenge"]
117
121
  shape!(challenge, HostBinding::CHALLENGE_FIELDS)
118
122
  HostBinding.send(:binding!, challenge["B"])
119
123
  invalid! unless challenge["B"].values_at("profile_ref", "profile_version") ==
120
- [TrustContext::PROFILE_REF, TrustContext::PROFILE_VERSION]
124
+ profile.values_at(:ref, :version)
121
125
  %w[challenge_id nonce issuer_id trust_snapshot_id policy_version state].each { |field| HostBinding.send(:id!, challenge[field]) }
122
126
  %w[trust_content_hash profile_definition_hash].each { |field| HostBinding.send(:hash!, challenge[field]) }
123
127
  %w[not_before not_after].each { |field| HostBinding.send(:time!, challenge[field]) }
@@ -253,10 +257,11 @@ module AP2MandateVerifier
253
257
  %i[trust restore_trust prepare restore inputs].each do |name|
254
258
  implementation = method(name)
255
259
  fields = implementation.parameters.filter_map { |kind, field| field if kind == :keyreq }.freeze
260
+ optional = implementation.parameters.filter_map { |kind, field| field if kind == :key }.freeze
256
261
  define_singleton_method(name) do |**arguments|
257
262
  missing = fields.find { |field| !arguments.key?(field) }
258
263
  invalid!(missing&.to_s, :missing_required_field) if missing
259
- invalid!("arguments", :unknown_field) unless arguments.length == fields.length
264
+ invalid!("arguments", :unknown_field) unless (arguments.keys - fields - optional).empty?
260
265
  implementation.call(**arguments)
261
266
  end
262
267
  end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ # Internal ES256 primitive. Callers must validate the payload's own profile.
5
+ module MerchantSignature
6
+ def self.sign!(claims, signer, public_key_pem)
7
+ RootSignature.send(:dependencies!)
8
+ payload = InputBuilder.send(:json!, claims, 12_000)
9
+ pem = InputValidator.snapshot!(public_key_pem, max_bytes: 1_024)
10
+ RootSignature.public_jwk!(pem)
11
+ header = Base64.urlsafe_encode64('{"alg":"ES256","typ":"JWT"}', padding: false)
12
+ input = "#{header}.#{Base64.urlsafe_encode64(payload, padding: false)}".freeze
13
+ raw = signer.call(input)
14
+ raise ArgumentError unless Object.instance_method(:instance_of?).bind_call(raw, String) &&
15
+ String.instance_method(:bytesize).bind_call(raw) == 64
16
+ signature = String.instance_method(:byteslice).bind_call(raw, 0, 64)
17
+ jwt = "#{input}.#{Base64.urlsafe_encode64(signature, padding: false)}"
18
+ raise ArgumentError unless RootSignature.verified_payload!(jwt, pem, expected_typ: "JWT", max_bytes: 16_384) == claims
19
+ jwt.freeze
20
+ end
21
+ end
22
+ end
@@ -24,7 +24,8 @@ module AP2MandateVerifier
24
24
  def self.verified_details!(root_presentation:, terminal_jws:, host_checkout_jws:,
25
25
  trusted_issuer_public_key_pem:, expected_agent_public_key_pem:,
26
26
  trusted_merchant_public_key_pem:, expected_aud:, expected_nonce:,
27
- verified_at:, expected_checkout_id:, expected_merchant_id:)
27
+ verified_at:, expected_checkout_id:, expected_merchant_id:,
28
+ profile_ref: TrustContext::PROFILE_REF)
28
29
  # Snapshot every caller-owned byte string before starting cryptography.
29
30
  root_wire = InputValidator.snapshot!(root_presentation)
30
31
  terminal_wire = InputValidator.snapshot!(terminal_jws, max_bytes: 32_768)
@@ -39,7 +40,11 @@ module AP2MandateVerifier
39
40
  raise RootSignature::Unavailable, :purchase_context_unavailable unless integer?(verified_at) &&
40
41
  verified_at.between?(0, MAX_EPOCH)
41
42
 
42
- root = RootDisclosures.verified_root!(root_wire, issuer_pem)
43
+ root = if profile_ref == TrustContext::PROFILE_REF
44
+ RootDisclosures.verified_root!(root_wire, issuer_pem)
45
+ else
46
+ RootDisclosures.verified_root!(root_wire, issuer_pem, profile_ref: profile_ref)
47
+ end
43
48
  open = root.fetch("delegate_payload").first
44
49
  exact!(open, %w[cnf constraints exp iat vct])
45
50
  raise Rejected, :unsupported_purchase_profile unless open["vct"] == "mandate.checkout.open.1"
@@ -21,11 +21,13 @@ module AP2MandateVerifier
21
21
 
22
22
  # Internal handoff only: signature and entire closure are verified first.
23
23
  # AP2 semantics, constraints and Host authorization remain unvalidated.
24
- def self.verified_root!(source, issuer_pem)
24
+ def self.verified_root!(source, issuer_pem, profile_ref: TrustContext::PROFILE_REF)
25
+ multi = profile_ref == "ap2.checkout.single_merchant_multi_item"
26
+ raise Rejected, :unsupported_disclosure_profile unless multi || profile_ref == TrustContext::PROFILE_REF
25
27
  wire = InputValidator.snapshot!(source)
26
28
  raise Rejected, :invalid_root_presentation unless wire.ascii_only? && wire.end_with?("~")
27
29
  parts = wire.split("~", -1)
28
- raise Rejected, :invalid_root_presentation unless parts.size.between?(3, MAX_DISCLOSURES + 2) &&
30
+ raise Rejected, :invalid_root_presentation unless parts.size.between?(3, (multi ? 66 : MAX_DISCLOSURES) + 2) &&
29
31
  parts.last == "" && !parts.first.empty? && parts[1...-1].none?(&:empty?)
30
32
  # No disclosure decode, digest graph or trusted claims before signature.
31
33
  payload = RootSignature.verified_payload!(parts.first, issuer_pem)
@@ -48,13 +50,14 @@ module AP2MandateVerifier
48
50
  used = {}
49
51
  observed = []
50
52
  budget = [0]
51
- resolved = walk!(payload, [], mapping, used, observed, budget, 1)
52
- raise Rejected, :unsupported_disclosure_profile unless observed.sort_by(&:to_s) == PATHS.sort_by(&:to_s)
53
+ resolved = walk!(payload, [], mapping, used, observed, budget, 1, multi)
54
+ paths = multi ? multi_paths!(resolved) : PATHS
55
+ raise Rejected, :unsupported_disclosure_profile unless observed.sort_by(&:to_s) == paths.sort_by(&:to_s)
53
56
  raise Rejected, :extra_disclosure unless used.size == mapping.size
54
57
  resolved
55
58
  end
56
59
 
57
- def self.walk!(value, path, mapping, used, observed, budget, depth)
60
+ def self.walk!(value, path, mapping, used, observed, budget, depth, multi)
58
61
  budget[0] += 1
59
62
  raise Rejected, :disclosure_limit_exceeded if budget[0] > 2_048 ||
60
63
  (depth > 24 && (value.instance_of?(Hash) || value.instance_of?(Array)))
@@ -63,13 +66,14 @@ module AP2MandateVerifier
63
66
  raise Rejected, :unsupported_disclosure_profile if value.key?("_sd") || value.key?("...") ||
64
67
  (path != [] && value.key?("_sd_alg"))
65
68
  raise Rejected, :disclosure_limit_exceeded if value.size > 32
66
- value.to_h { |key, child| [key, walk!(child, path + [key], mapping, used, observed, budget, depth + 1)] }
69
+ value.to_h { |key, child| [key, walk!(child, path + [key], mapping, used, observed, budget, depth + 1, multi)] }
67
70
  when Array
68
71
  raise Rejected, :disclosure_limit_exceeded if value.size > 16
69
72
  value.each_with_index.map do |item, index|
70
73
  here = path + [index]
71
74
  if item.instance_of?(Hash) && item.key?("...")
72
- raise Rejected, :unsupported_disclosure_profile unless item.keys == ["..."] && PATHS.include?(here)
75
+ raise Rejected, :unsupported_disclosure_profile unless item.keys == ["..."] &&
76
+ (multi ? multi_path?(here) : PATHS.include?(here))
73
77
  digest = item["..."]
74
78
  raise Rejected, :invalid_disclosure unless digest.instance_of?(String) &&
75
79
  digest.bytesize == 43 && decode!(digest).bytesize == 32
@@ -77,9 +81,9 @@ module AP2MandateVerifier
77
81
  raise Rejected, :missing_disclosure unless mapping.key?(digest)
78
82
  used[digest] = true
79
83
  observed << here
80
- walk!(mapping.fetch(digest), here + ["disclosed"], mapping, used, observed, budget, depth + 1)
84
+ walk!(mapping.fetch(digest), here + ["disclosed"], mapping, used, observed, budget, depth + 1, multi)
81
85
  else
82
- walk!(item, here, mapping, used, observed, budget, depth + 1)
86
+ walk!(item, here, mapping, used, observed, budget, depth + 1, multi)
83
87
  end
84
88
  end
85
89
  else
@@ -87,6 +91,25 @@ module AP2MandateVerifier
87
91
  end
88
92
  end
89
93
 
94
+ def self.multi_path?(path)
95
+ return true if PATHS[0..1].include?(path)
96
+ path.size == 9 && path[0, 6] == ["delegate_payload", 0, "disclosed", "constraints", 0, "items"] &&
97
+ path[6].instance_of?(Integer) && path[6].between?(0, 7) &&
98
+ path[7] == "acceptable_items" && path[8].instance_of?(Integer) && path[8].between?(0, 7)
99
+ end
100
+
101
+ def self.multi_paths!(resolved)
102
+ items = resolved.dig("delegate_payload", 0, "constraints", 0, "items")
103
+ raise Rejected, :unsupported_disclosure_profile unless items.instance_of?(Array) && items.size.between?(1, 8)
104
+ paths = PATHS[0..1].dup
105
+ items.each_with_index do |item, i|
106
+ candidates = item.instance_of?(Hash) && item["acceptable_items"]
107
+ raise Rejected, :unsupported_disclosure_profile unless candidates.instance_of?(Array) && candidates.size.between?(1, 8)
108
+ candidates.each_index { |j| paths << ["delegate_payload", 0, "disclosed", "constraints", 0, "items", i, "acceptable_items", j] }
109
+ end
110
+ paths
111
+ end
112
+
90
113
  def self.decode!(part)
91
114
  raise Rejected, :invalid_disclosure unless part.match?(/\A[A-Za-z0-9_-]+\z/)
92
115
  raw = Base64.urlsafe_decode64(part + "=" * (-part.bytesize % 4))
@@ -95,6 +118,6 @@ module AP2MandateVerifier
95
118
  rescue ArgumentError
96
119
  raise Rejected, :invalid_disclosure
97
120
  end
98
- private_class_method :walk!, :decode!
121
+ private_class_method :walk!, :decode!, :multi_path?, :multi_paths!
99
122
  end
100
123
  end
@@ -6,6 +6,10 @@ module AP2MandateVerifier
6
6
  module ScopedConstraints
7
7
  MAX_AMOUNT = 9_007_199_254_740_991
8
8
  MAX_QUANTITY = 1_000_000
9
+ MULTI_PROFILE_REF = "ap2.checkout.single_merchant_multi_item"
10
+ MAX_LINES = 8
11
+ MAX_REQUIREMENTS = 8
12
+ MAX_CANDIDATES = 8
9
13
  CURRENCIES = %w[USD EUR JPY].freeze
10
14
  CORE_INSTANCE_OF = Object.instance_method(:instance_of?)
11
15
  class Rejected < RootSignature::Rejected; end
@@ -16,7 +20,7 @@ module AP2MandateVerifier
16
20
  end
17
21
 
18
22
  # Internal claims handoff after the complete existing limited profile.
19
- def self.verified_constraints!(expected_currency:, expected_total_minor:, **binding_inputs)
23
+ def self.verified_constraints!(expected_currency:, expected_total_minor:, profile_ref: TrustContext::PROFILE_REF, **binding_inputs)
20
24
  begin
21
25
  currency = InputValidator.snapshot!(expected_currency, max_bytes: 3)
22
26
  rescue InputValidator::Invalid
@@ -25,6 +29,12 @@ module AP2MandateVerifier
25
29
  raise RootSignature::Unavailable, :constraint_context_unavailable unless
26
30
  CURRENCIES.include?(currency) && CORE_INSTANCE_OF.bind_call(expected_total_minor, Integer) &&
27
31
  expected_total_minor.between?(0, MAX_AMOUNT)
32
+ if profile_ref == MULTI_PROFILE_REF
33
+ details = PurchaseBinding.verified_details!(**binding_inputs, profile_ref: profile_ref)
34
+ multi_constraints!(details, currency, expected_total_minor)
35
+ return details
36
+ end
37
+ raise Rejected, :unsupported_scoped_profile unless profile_ref == TrustContext::PROFILE_REF
28
38
  details = PurchaseBinding.verified_details!(**binding_inputs)
29
39
  open, checkout = details.values_at(:open, :checkout)
30
40
  constraints = open["constraints"]
@@ -76,6 +86,136 @@ module AP2MandateVerifier
76
86
  details
77
87
  end
78
88
 
89
+ # New profile only. IDs identify products; titles are descriptive text.
90
+ # Original arrays remain intact; this graph is solely a quantity proof.
91
+ def self.multi_constraints!(details, currency, expected_total)
92
+ open, checkout = details.values_at(:open, :checkout)
93
+ constraints = open["constraints"]
94
+ raise Rejected, :unsupported_constraint unless constraints.instance_of?(Array) && constraints.size == 2
95
+ required, allowed = constraints
96
+ exact!(required, %w[items type])
97
+ exact!(allowed, %w[allowed type])
98
+ raise Rejected, :unsupported_constraint unless required["type"] == "checkout.line_items" && allowed["type"] == "checkout.allowed_merchants"
99
+ requirements = bounded_array!(required["items"], MAX_REQUIREMENTS)
100
+ unique_ids!(requirements)
101
+ requirements.each do |requirement|
102
+ exact!(requirement, %w[acceptable_items id quantity])
103
+ quantity!(requirement["quantity"])
104
+ candidates = bounded_array!(requirement["acceptable_items"], MAX_CANDIDATES)
105
+ unique_ids!(candidates)
106
+ candidates.each do |candidate|
107
+ exact!(candidate, %w[id title])
108
+ text!(candidate["title"], 512)
109
+ end
110
+ end
111
+ merchant = one!(allowed["allowed"])
112
+ exact!(merchant, %w[id name])
113
+ text!(merchant["id"])
114
+ text!(merchant["name"], 512)
115
+ raise Rejected, :constraint_mismatch unless checkout["merchant"] == merchant
116
+ raise Rejected, :currency_mismatch unless checkout["currency"] == currency
117
+ amount = multi_checkout!(checkout)
118
+ raise Rejected, :amount_mismatch unless amount == expected_total
119
+ quantities_match!(requirements, checkout["line_items"])
120
+ end
121
+
122
+ # Also shared with the explicitly selected merchant signing profile.
123
+ def self.multi_checkout!(checkout)
124
+ exact!(checkout, %w[currency id line_items links merchant status totals])
125
+ text!(checkout["id"])
126
+ exact!(checkout["merchant"], %w[id name])
127
+ text!(checkout["merchant"]["id"])
128
+ text!(checkout["merchant"]["name"], 512)
129
+ text!(checkout["currency"], 3)
130
+ raise Rejected, :unsupported_scoped_profile unless CURRENCIES.include?(checkout["currency"]) &&
131
+ checkout["status"] == "ready_for_complete"
132
+ raise Rejected, :invalid_scoped_schema unless checkout["links"].instance_of?(Array)
133
+ raise Rejected, :unsupported_scoped_profile unless checkout["links"].empty?
134
+ lines = bounded_array!(checkout["line_items"], MAX_LINES)
135
+ unique_ids!(lines)
136
+ amount = 0
137
+ lines.each do |line|
138
+ exact!(line, %w[id item quantity totals])
139
+ quantity!(line["quantity"])
140
+ item = line["item"]
141
+ exact!(item, %w[id price title])
142
+ text!(item["id"])
143
+ text!(item["title"], 512)
144
+ amount!(item["price"])
145
+ line_amount = item["price"] * line["quantity"]
146
+ amount!(line_amount)
147
+ totals!(line["totals"], line_amount)
148
+ amount += line_amount
149
+ amount!(amount)
150
+ end
151
+ totals!(checkout["totals"], amount)
152
+ amount
153
+ end
154
+
155
+ def self.bounded_array!(value, limit)
156
+ raise Rejected, :invalid_scoped_schema unless value.instance_of?(Array)
157
+ raise Rejected, :constraint_limit_exceeded unless value.length.between?(1, limit)
158
+ value
159
+ end
160
+
161
+ def self.unique_ids!(values)
162
+ ids = values.map do |value|
163
+ raise Rejected, :invalid_scoped_schema unless value.instance_of?(Hash)
164
+ text!(value["id"])
165
+ value["id"]
166
+ end
167
+ raise Rejected, :invalid_scoped_schema unless ids.uniq.length == ids.length
168
+ end
169
+
170
+ # Integral max flow with reverse residual edges avoids greedy false rejects.
171
+ # At most 18 vertices, 64 candidate edges; capacities never expand per unit.
172
+ def self.quantities_match!(requirements, lines)
173
+ demand = requirements.sum { |requirement| requirement["quantity"] }
174
+ supply = lines.sum { |line| line["quantity"] }
175
+ raise Rejected, :constraint_mismatch unless demand == supply
176
+ sink = 1 + requirements.length + lines.length
177
+ residual = Array.new(sink + 1) { Array.new(sink + 1, 0) }
178
+ requirements.each_with_index do |requirement, i|
179
+ r = i + 1
180
+ residual[0][r] = requirement["quantity"]
181
+ ids = requirement["acceptable_items"].map { |candidate| candidate["id"] }
182
+ lines.each_with_index do |line, j|
183
+ residual[r][requirements.length + j + 1] = demand if ids.include?(line["item"]["id"])
184
+ end
185
+ end
186
+ lines.each_with_index { |line, j| residual[requirements.length + j + 1][sink] = line["quantity"] }
187
+ flow = 0
188
+ loop do
189
+ parents = Array.new(sink + 1)
190
+ parents[0] = 0
191
+ queue = [0]
192
+ until queue.empty? || parents[sink]
193
+ u = queue.shift
194
+ residual[u].each_with_index do |capacity, v|
195
+ next unless capacity > 0 && parents[v].nil?
196
+ parents[v] = u
197
+ queue << v
198
+ end
199
+ end
200
+ break unless parents[sink]
201
+ amount, v = demand, sink
202
+ until v == 0
203
+ u = parents[v]
204
+ amount = [amount, residual[u][v]].min
205
+ v = u
206
+ end
207
+ v = sink
208
+ until v == 0
209
+ u = parents[v]
210
+ residual[u][v] -= amount
211
+ residual[v][u] += amount
212
+ v = u
213
+ end
214
+ flow += amount
215
+ end
216
+ raise Rejected, :constraint_mismatch unless flow == demand
217
+ end
218
+
79
219
  def self.exact!(value, fields)
80
220
  raise Rejected, :invalid_scoped_schema unless value.instance_of?(Hash) && (fields - value.keys).empty?
81
221
  raise Rejected, :unsupported_scoped_profile unless (value.keys - fields).empty?
@@ -108,7 +248,8 @@ module AP2MandateVerifier
108
248
  raise Rejected, :unsupported_scoped_profile unless values.map { |entry| entry["type"] }.sort == %w[subtotal total]
109
249
  raise Rejected, :amount_mismatch unless values.all? { |entry| entry["amount"] == expected }
110
250
  end
111
- private_class_method :exact!, :one!, :text!, :quantity!, :amount!, :totals!
251
+ private_class_method :exact!, :one!, :text!, :quantity!, :amount!, :totals!,
252
+ :multi_constraints!, :bounded_array!, :unique_ids!, :quantities_match!
112
253
  private_constant :CORE_INSTANCE_OF
113
254
  end
114
255
  end
@@ -8,6 +8,22 @@ module AP2MandateVerifier
8
8
  PROFILE_REF = "ap2.checkout.single_merchant_sku"
9
9
  PROFILE_VERSION = "1"
10
10
  PROFILE_HASH = Digest::SHA256.hexdigest(PROFILE_BODY).freeze
11
+ MULTI_PROFILE_REF = "ap2.checkout.single_merchant_multi_item"
12
+ MULTI_PROFILE_VERSION = "1"
13
+ MULTI_PROFILE_BODY = '{"profile_ref":"ap2.checkout.single_merchant_multi_item","version":"1","ap2_source":"b4587ac1d055888a73b4b21750973cffba961793","algorithm":"ES256","key_format":"canonical-public-SPKI-P256-SHA256","root_type":"example+sd-jwt","terminal_type":"kb+sd-jwt","checkout_type":"JWT","disclosure_path_semantics":"root-walker-with-synthetic-disclosed-edges","disclosure_positions":["delegate_payload[0]","delegate_payload[0].disclosed.constraints[0].items[*].acceptable_items[*]","delegate_payload[0].disclosed.constraints[1].allowed[0]"],"constraints":["checkout.line_items","checkout.allowed_merchants"],"max_disclosures":66,"max_disclosure_segment_bytes":8192,"max_root_bytes":131072,"max_graph_nodes":2048,"max_graph_depth":24,"max_array_entries":16,"max_line_items":8,"max_requirements":8,"max_candidates_per_requirement":8,"quantity_matching":"integer-max-flow-product-id-exact-coverage","duplicate_line_ids":"reject","duplicate_requirement_ids":"reject","same_product_multiple_lines":"allow","amount_model":"integer-minor-unit-no-tax-shipping-discount"}'.freeze
14
+ MULTI_PROFILE_HASH = Digest::SHA256.hexdigest(MULTI_PROFILE_BODY).freeze
15
+
16
+ # Explicit Host policy registration. Signed token claims never select this.
17
+ def self.profile!(reference)
18
+ case reference
19
+ when PROFILE_REF
20
+ {ref: PROFILE_REF, version: PROFILE_VERSION, body: PROFILE_BODY, hash: PROFILE_HASH}.freeze
21
+ when MULTI_PROFILE_REF
22
+ {ref: MULTI_PROFILE_REF, version: MULTI_PROFILE_VERSION, body: MULTI_PROFILE_BODY, hash: MULTI_PROFILE_HASH}.freeze
23
+ else
24
+ reject!(:unsupported_trust_profile)
25
+ end
26
+ end
11
27
  ROLES = {"Issuer" => :trusted_issuer_public_key_pem,
12
28
  "Agent" => :expected_agent_public_key_pem,
13
29
  "Merchant" => :trusted_merchant_public_key_pem}.freeze
@@ -73,9 +89,10 @@ module AP2MandateVerifier
73
89
  selection.values_at("trust_snapshot_id", "policy_version", "trust_content_hash")
74
90
  live!(snapshot, verified_at, :inactive_trust_snapshot, :trust_snapshot_time_mismatch)
75
91
  _profile, wire = body!(trust["profile"], %w[profile_ref version], "definition_hash", 8_192)
76
- reject!(:unsupported_trust_profile) unless wire == PROFILE_BODY &&
77
- trust["profile"].values_at("profile_ref", "version", "definition_hash") == [PROFILE_REF, PROFILE_VERSION, PROFILE_HASH] &&
78
- selection.values_at("profile_ref", "profile_version", "profile_definition_hash") == [PROFILE_REF, PROFILE_VERSION, PROFILE_HASH]
92
+ profile = profile!(selection["profile_ref"])
93
+ reject!(:unsupported_trust_profile) unless wire == profile[:body] &&
94
+ trust["profile"].values_at("profile_ref", "version", "definition_hash") == profile.values_at(:ref, :version, :hash) &&
95
+ selection.values_at("profile_ref", "profile_version", "profile_definition_hash") == profile.values_at(:ref, :version, :hash)
79
96
  records = snapshot["records"]
80
97
  reject! unless records.instance_of?(Array) && records.length.between?(1, 16)
81
98
  records.each do |record|
@@ -83,7 +100,7 @@ module AP2MandateVerifier
83
100
  %w[identity tenant_id purpose key_ref profile_ref profile_version].each { |f| id!(record[f]) }
84
101
  reject! unless ROLES.key?(record["role"])
85
102
  window!(record)
86
- reject!(:unsupported_trust_profile) unless record.values_at("profile_ref", "profile_version", "algorithm") == [PROFILE_REF, PROFILE_VERSION, "ES256"]
103
+ reject!(:unsupported_trust_profile) unless record.values_at("profile_ref", "profile_version", "algorithm") == [profile[:ref], profile[:version], "ES256"]
87
104
  digest!(record["key_fingerprint"])
88
105
  begin
89
106
  RootSignature.public_jwk!(record["public_key_pem"])
@@ -10,6 +10,9 @@ require_relative "ap2_mandate_verifier/trust_context"
10
10
  require_relative "ap2_mandate_verifier/host_binding"
11
11
  require_relative "ap2_mandate_verifier/research_result"
12
12
  require_relative "ap2_mandate_verifier/input_builder"
13
+ require_relative "ap2_mandate_verifier/merchant_signature"
14
+ require_relative "ap2_mandate_verifier/checkout_jwt"
15
+ require_relative "ap2_mandate_verifier/checkout_receipt"
13
16
 
14
17
  module AP2MandateVerifier
15
18
  # Accepts original JSON bytes only. Syntax validity is not AP2 validity,
@@ -95,9 +98,9 @@ module AP2MandateVerifier
95
98
  inputs = inputs.to_h do |key, value|
96
99
  [key, %i[verified_at expected_total_minor].include?(key) ? value : InputValidator.snapshot!(value)]
97
100
  end
98
- keys = TrustContext.keys!(trust_json: trust_json, selection_json: selection_json,
101
+ context = TrustContext.verified_context!(trust_json: trust_json, selection_json: selection_json,
99
102
  verified_at: inputs[:verified_at], expected_merchant_id: inputs[:expected_merchant_id])
100
- ScopedConstraints.check!(**inputs, **keys)
103
+ ScopedConstraints.check!(**inputs, **context.fetch(:keys), profile_ref: context.fetch(:references).fetch("profile_ref"))
101
104
  Result.new(status: :unverified, code: :scoped_constraints_verified_only)
102
105
  rescue InputValidator::Unavailable, RootSignature::Unavailable => error
103
106
  Result.new(status: :unavailable, code: error.code)