ap2_mandate_verifier 0.6.0 → 0.8.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.
@@ -17,6 +17,32 @@ module AP2MandateVerifier
17
17
  private_class_method :new
18
18
  end
19
19
 
20
+ class Verification
21
+ attr_reader :jwt, :checkout_hash, :checkout, :profile_ref
22
+ def initialize(jwt, checkout, profile_ref)
23
+ @jwt, @profile_ref = jwt, profile_ref
24
+ @checkout_hash = Base64.urlsafe_encode64(Digest::SHA256.digest(jwt), padding: false).freeze
25
+ @checkout = ResearchEvidence.send(:copy_frozen, checkout)
26
+ freeze
27
+ end
28
+ def verified? = true
29
+ private_class_method :new
30
+ end
31
+
32
+ # Merchant trust is selected by the application, never by received claims.
33
+ # Checkout has no signed expiry: the app must check current order state.
34
+ def self.verify(jwt:, trusted_public_key_pem:, expected_merchant_id:, profile_ref: TrustContext::PROFILE_REF)
35
+ wire = InputValidator.snapshot!(jwt, max_bytes: 16_384)
36
+ profile = InputValidator.snapshot!(profile_ref, max_bytes: 256)
37
+ merchant = InputValidator.snapshot!(expected_merchant_id, max_bytes: 512)
38
+ claims = RootSignature.verified_payload!(wire, trusted_public_key_pem, expected_typ: "JWT", max_bytes: 16_384)
39
+ validate!(claims, profile_ref: profile)
40
+ raise Invalid unless claims.fetch("merchant").fetch("id") == merchant
41
+ Verification.send(:new, wire, claims, profile)
42
+ rescue StandardError, LoadError
43
+ raise Invalid.new, cause: nil
44
+ end
45
+
20
46
  # signer.call receives the exact ASCII JWS signing input and must return a
21
47
  # 64-byte JOSE ES256 signature. The supplied independent public key verifies
22
48
  # the result before any signed object is returned (including remote signers).
@@ -74,7 +100,7 @@ module AP2MandateVerifier
74
100
  c.send(:totals!, checkout["totals"], total)
75
101
  nil
76
102
  end
77
- %i[sign es256_signer].each do |name|
103
+ %i[sign es256_signer verify].each do |name|
78
104
  implementation = method(name)
79
105
  fields = implementation.parameters.filter_map { |kind, field| field if kind == :keyreq }.freeze
80
106
  optional = implementation.parameters.filter_map { |kind, field| field if kind == :key }.freeze
@@ -33,6 +33,11 @@ module AP2MandateVerifier
33
33
  # Exact received final closed SD-JWT, no disclosures or additional hop.
34
34
  # A terminal compact JWS alone is intentionally not accepted or repaired.
35
35
  def self.reference(closed_sd_jwt:, profile_ref: TrustContext::PROFILE_REF)
36
+ profile_ref = InputValidator.snapshot!(profile_ref, max_bytes: 256)
37
+ if profile_ref == Buyer::PROFILE_REF
38
+ parsed = Buyer.send(:parse!, closed_sd_jwt)
39
+ return hash(parsed.fetch(:wire)).freeze
40
+ end
36
41
  wire = InputValidator.snapshot!(closed_sd_jwt, max_bytes: 32_769)
37
42
  raise Invalid unless wire.ascii_only? && wire.end_with?("~") && wire.count("~") == 1
38
43
  compact = wire.byteslice(0, wire.bytesize - 1)
@@ -0,0 +1,150 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ # Additive issuer/Agent APIs for the unchanged complete-disclosure profile.
5
+ module ConditionalCheckout
6
+ PROFILE_REF = ScopedConstraints::MULTI_PROFILE_REF
7
+ class Invalid < ArgumentError
8
+ def initialize = super("invalid conditional checkout information")
9
+ end
10
+ class Open
11
+ attr_reader :root_presentation
12
+ def initialize(wire)
13
+ @root_presentation = wire.freeze
14
+ freeze
15
+ end
16
+ private_class_method :new
17
+ end
18
+ class Closed
19
+ attr_reader :root_presentation, :terminal_jws, :checkout_jwt, :closed_sd_jwt
20
+ def initialize(root, terminal, checkout)
21
+ @root_presentation, @terminal_jws, @checkout_jwt = root.freeze, terminal.freeze, checkout.freeze
22
+ @closed_sd_jwt = (terminal + "~").freeze
23
+ freeze
24
+ end
25
+ private_class_method :new
26
+ end
27
+
28
+ def self.issue_open(merchant:, requirements:, agent_public_key_pem:, issued_at:, expires_at:, signer:, public_key_pem:)
29
+ RootSignature.send(:dependencies!)
30
+ merchant = InputBuilder.send(:copy!, merchant)
31
+ requirements = InputBuilder.send(:copy!, requirements)
32
+ constraints = [{"type" => "checkout.line_items", "items" => requirements},
33
+ {"type" => "checkout.allowed_merchants", "allowed" => [merchant]}]
34
+ ScopedConstraints.send(:multi_open!, constraints)
35
+ PurchaseBinding.send(:times!, {"iat" => issued_at, "exp" => expires_at}, issued_at)
36
+ agent = InputValidator.snapshot!(agent_public_key_pem, max_bytes: 1_024)
37
+ provider = InputValidator.snapshot!(public_key_pem, max_bytes: 1_024)
38
+ jwk = RootSignature.public_jwk!(agent)
39
+ disclosures = []
40
+ requirements.each do |requirement|
41
+ requirement["acceptable_items"] = requirement["acceptable_items"].map do |candidate|
42
+ disclose!(candidate, disclosures)
43
+ end
44
+ end
45
+ constraints[1]["allowed"] = [disclose!(merchant, disclosures)]
46
+ opening = {"vct" => "mandate.checkout.open.1", "iat" => issued_at, "exp" => expires_at,
47
+ "cnf" => {"jwk" => jwk}, "constraints" => constraints}
48
+ content = []
49
+ marker = disclose!(opening, content)
50
+ jwt = MerchantSignature.sign!({"delegate_payload" => [marker], "_sd_alg" => "sha-256"}, signer, provider,
51
+ typ: "example+sd-jwt")
52
+ wire = ([jwt] + content + disclosures + [""]).join("~")
53
+ open!(wire, provider, agent, issued_at)
54
+ Open.send(:new, wire)
55
+ rescue StandardError, LoadError
56
+ raise Invalid.new, cause: nil
57
+ end
58
+
59
+ # Provider private key is deliberately absent from this Agent API.
60
+ def self.issue_closed(root_presentation:, checkout_jwt:, trusted_issuer_public_key_pem:,
61
+ agent_public_key_pem:, trusted_merchant_public_key_pem:, expected_merchant_id:,
62
+ audience:, nonce:, verified_at:, signer:)
63
+ root = InputValidator.snapshot!(root_presentation)
64
+ checkout = InputValidator.snapshot!(checkout_jwt, max_bytes: 16_384)
65
+ provider = InputValidator.snapshot!(trusted_issuer_public_key_pem, max_bytes: 1_024)
66
+ agent = InputValidator.snapshot!(agent_public_key_pem, max_bytes: 1_024)
67
+ merchant = InputValidator.snapshot!(trusted_merchant_public_key_pem, max_bytes: 1_024)
68
+ identity = InputValidator.snapshot!(expected_merchant_id, max_bytes: 256)
69
+ aud = InputValidator.snapshot!(audience, max_bytes: 512)
70
+ challenge = InputValidator.snapshot!(nonce, max_bytes: 512)
71
+ raise Invalid if aud.empty? || challenge.empty?
72
+ CheckoutReceipt.send(:epoch!, verified_at)
73
+ opening = open!(root, provider, agent, verified_at)
74
+ checked = CheckoutJWT.verify(jwt: checkout, trusted_public_key_pem: merchant,
75
+ expected_merchant_id: identity, profile_ref: PROFILE_REF)
76
+ ScopedConstraints.send(:multi_constraints!, {open: opening, checkout: checked.checkout},
77
+ checked.checkout.fetch("currency"), ScopedConstraints.multi_checkout!(checked.checkout))
78
+ closed = {"vct" => "mandate.checkout.1", "iat" => opening.fetch("iat"), "exp" => opening.fetch("exp"),
79
+ "checkout_jwt" => checkout, "checkout_hash" => checked.checkout_hash}
80
+ terminal = MerchantSignature.sign!({"aud" => aud, "nonce" => challenge, "iat" => verified_at,
81
+ "sd_hash" => digest(root), "delegate_payload" => [closed]}, signer, agent, typ: "kb+sd-jwt")
82
+ # Final handoff repeats the complete existing signature/condition path.
83
+ ScopedConstraints.check!(root_presentation: root, terminal_jws: terminal, host_checkout_jws: checkout,
84
+ trusted_issuer_public_key_pem: provider, expected_agent_public_key_pem: agent,
85
+ trusted_merchant_public_key_pem: merchant, expected_aud: aud, expected_nonce: challenge,
86
+ verified_at: verified_at, expected_checkout_id: checked.checkout.fetch("id"), expected_merchant_id: identity,
87
+ expected_currency: checked.checkout.fetch("currency"),
88
+ expected_total_minor: ScopedConstraints.multi_checkout!(checked.checkout), profile_ref: PROFILE_REF)
89
+ Closed.send(:new, root, terminal, checkout)
90
+ rescue StandardError, LoadError
91
+ raise Invalid.new, cause: nil
92
+ end
93
+
94
+ # Storage/transport only, never an authentication or authorization result.
95
+ def self.present(root_presentation:, terminal_jws:, checkout_jwt:)
96
+ root = InputValidator.snapshot!(root_presentation)
97
+ terminal = InputValidator.snapshot!(terminal_jws, max_bytes: 32_768)
98
+ checkout = InputValidator.snapshot!(checkout_jwt, max_bytes: 16_384)
99
+ # Exact commitment closure without claiming signature authentication.
100
+ opening = RootDisclosures.send(:structural_root!, root).fetch("delegate_payload").first
101
+ PurchaseBinding.send(:exact!, opening, %w[cnf constraints exp iat vct])
102
+ raise Invalid unless opening["vct"] == "mandate.checkout.open.1"
103
+ PurchaseBinding.send(:times!, opening, opening["iat"])
104
+ PurchaseBinding.send(:exact!, opening["cnf"], %w[jwk])
105
+ PurchaseBinding.send(:exact!, opening["cnf"]["jwk"], %w[kty crv x y])
106
+ jwk = opening["cnf"]["jwk"]
107
+ raise Invalid unless jwk["kty"] == "EC" && jwk["crv"] == "P-256" &&
108
+ %w[x y].all? { |f| RootSignature.send(:decode!, jwk[f], 32).bytesize == 32 }
109
+ ScopedConstraints.send(:multi_open!, opening["constraints"])
110
+ CheckoutReceipt.reference(closed_sd_jwt: terminal + "~", profile_ref: PROFILE_REF)
111
+ claims = InputValidator.parse!(RootSignature.send(:decode!, terminal.split(".", -1)[1], 24_576))
112
+ raise Invalid unless claims["sd_hash"] == digest(root) &&
113
+ claims.fetch("delegate_payload").first.fetch("checkout_jwt") == checkout &&
114
+ %w[iat exp].all? { |f| claims.fetch("delegate_payload").first[f] == opening[f] }
115
+ Closed.send(:new, root, terminal, checkout)
116
+ rescue StandardError, LoadError
117
+ raise Invalid.new, cause: nil
118
+ end
119
+
120
+ def self.open!(wire, provider, agent, now)
121
+ opening = RootDisclosures.verified_root!(wire, provider, profile_ref: PROFILE_REF).fetch("delegate_payload").first
122
+ PurchaseBinding.send(:exact!, opening, %w[cnf constraints exp iat vct])
123
+ raise Invalid unless opening["vct"] == "mandate.checkout.open.1"
124
+ PurchaseBinding.send(:times!, opening, now)
125
+ PurchaseBinding.send(:exact!, opening["cnf"], %w[jwk])
126
+ raise Invalid unless opening["cnf"]["jwk"] == RootSignature.public_jwk!(agent)
127
+ ScopedConstraints.send(:multi_open!, opening["constraints"])
128
+ opening
129
+ end
130
+ def self.digest(wire) = Base64.urlsafe_encode64(Digest::SHA256.digest(wire), padding: false)
131
+ def self.disclose!(value, disclosures)
132
+ require "securerandom"
133
+ salt = Base64.urlsafe_encode64(SecureRandom.random_bytes(16), padding: false)
134
+ wire = Base64.urlsafe_encode64(JSON.generate([salt, value]), padding: false)
135
+ disclosures << wire
136
+ {"..." => digest(wire)}
137
+ end
138
+ %i[issue_open issue_closed present].each do |name|
139
+ implementation = method(name)
140
+ fields = implementation.parameters.map(&:last).freeze
141
+ define_singleton_method(name) do |**arguments|
142
+ unless (fields - arguments.keys).empty? && (arguments.keys - fields).empty?
143
+ raise Invalid.new, cause: nil
144
+ end
145
+ implementation.call(**arguments)
146
+ end
147
+ end
148
+ private_class_method :open!, :digest, :disclose!
149
+ end
150
+ end
@@ -3,19 +3,24 @@
3
3
  module AP2MandateVerifier
4
4
  # Internal ES256 primitive. Callers must validate the payload's own profile.
5
5
  module MerchantSignature
6
- def self.sign!(claims, signer, public_key_pem)
6
+ def self.sign!(claims, signer, public_key_pem, typ: "JWT")
7
7
  RootSignature.send(:dependencies!)
8
- payload = InputBuilder.send(:json!, claims, 12_000)
8
+ raise ArgumentError unless %w[JWT example+sd-jwt kb+sd-jwt].include?(typ)
9
+ terminal = typ == "kb+sd-jwt"
10
+ # A terminal embeds the original, already encoded Merchant JWT. Preserve
11
+ # Merchant/Direct bounds; only Agent terminals use their verifier limits.
12
+ payload = InputBuilder.send(:json!, claims, terminal ? 24_576 : 12_000)
9
13
  pem = InputValidator.snapshot!(public_key_pem, max_bytes: 1_024)
10
14
  RootSignature.public_jwk!(pem)
11
- header = Base64.urlsafe_encode64('{"alg":"ES256","typ":"JWT"}', padding: false)
15
+ header = Base64.urlsafe_encode64(JSON.generate({"alg" => "ES256", "typ" => typ}), padding: false)
12
16
  input = "#{header}.#{Base64.urlsafe_encode64(payload, padding: false)}".freeze
13
17
  raw = signer.call(input)
14
18
  raise ArgumentError unless Object.instance_method(:instance_of?).bind_call(raw, String) &&
15
19
  String.instance_method(:bytesize).bind_call(raw) == 64
16
20
  signature = String.instance_method(:byteslice).bind_call(raw, 0, 64)
17
21
  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
22
+ raise ArgumentError unless RootSignature.verified_payload!(jwt, pem, expected_typ: typ,
23
+ max_bytes: terminal ? 32_768 : 16_384) == claims
19
24
  jwt.freeze
20
25
  end
21
26
  end
@@ -31,7 +31,30 @@ module AP2MandateVerifier
31
31
  parts.last == "" && !parts.first.empty? && parts[1...-1].none?(&:empty?)
32
32
  # No disclosure decode, digest graph or trusted claims before signature.
33
33
  payload = RootSignature.verified_payload!(parts.first, issuer_pem)
34
+ resolve!(parts, payload, multi)
35
+ end
36
+
37
+ # Internal structural restoration only. Never authenticates an issuer.
38
+ # Shares the exact closure walker with the authenticated verification path.
39
+ def self.structural_root!(source)
40
+ wire = InputValidator.snapshot!(source)
41
+ raise Rejected, :invalid_root_presentation unless wire.ascii_only? && wire.end_with?("~")
42
+ parts = wire.split("~", -1)
43
+ raise Rejected, :invalid_root_presentation unless parts.size.between?(3, 68) && parts.last == "" &&
44
+ parts[0...-1].none?(&:empty?)
45
+ jwt = parts.first.split(".", -1)
46
+ raise Rejected, :invalid_root_presentation unless jwt.size == 3
47
+ RootSignature.send(:dependencies!)
48
+ header = InputValidator.parse!(RootSignature.send(:decode!, jwt[0], 2_048))
49
+ CheckoutReceipt.send(:header!, header, "example+sd-jwt")
50
+ raise Rejected, :invalid_root_presentation unless RootSignature.send(:decode!, jwt[2], 64).bytesize == 64
51
+ payload = InputValidator.parse!(RootSignature.send(:decode!, jwt[1], 24_576))
52
+ resolve!(parts, payload, true)
53
+ end
54
+
55
+ def self.resolve!(parts, payload, multi)
34
56
  raise Rejected, :unsupported_disclosure_profile unless
57
+ payload.instance_of?(Hash) &&
35
58
  (payload.keys - %w[delegate_payload _sd_alg]).empty? &&
36
59
  (!payload.key?("_sd_alg") || payload["_sd_alg"] == "sha-256") &&
37
60
  payload["delegate_payload"].instance_of?(Array) && payload["delegate_payload"].size == 1
@@ -118,6 +141,6 @@ module AP2MandateVerifier
118
141
  rescue ArgumentError
119
142
  raise Rejected, :invalid_disclosure
120
143
  end
121
- private_class_method :walk!, :decode!, :multi_path?, :multi_paths!
144
+ private_class_method :walk!, :decode!, :multi_path?, :multi_paths!, :resolve!, :structural_root!
122
145
  end
123
146
  end
@@ -90,7 +90,16 @@ module AP2MandateVerifier
90
90
  # Original arrays remain intact; this graph is solely a quantity proof.
91
91
  def self.multi_constraints!(details, currency, expected_total)
92
92
  open, checkout = details.values_at(:open, :checkout)
93
- constraints = open["constraints"]
93
+ merchant, requirements = multi_open!(open["constraints"])
94
+ raise Rejected, :constraint_mismatch unless checkout["merchant"] == merchant
95
+ raise Rejected, :currency_mismatch unless checkout["currency"] == currency
96
+ amount = multi_checkout!(checkout)
97
+ raise Rejected, :amount_mismatch unless amount == expected_total
98
+ quantities_match!(requirements, checkout["line_items"])
99
+ end
100
+
101
+ # Internal shared closed-world Open grammar, also used before issuance.
102
+ def self.multi_open!(constraints)
94
103
  raise Rejected, :unsupported_constraint unless constraints.instance_of?(Array) && constraints.size == 2
95
104
  required, allowed = constraints
96
105
  exact!(required, %w[items type])
@@ -112,11 +121,7 @@ module AP2MandateVerifier
112
121
  exact!(merchant, %w[id name])
113
122
  text!(merchant["id"])
114
123
  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"])
124
+ [merchant, requirements]
120
125
  end
121
126
 
122
127
  # Also shared with the explicitly selected merchant signing profile.
@@ -249,7 +254,7 @@ module AP2MandateVerifier
249
254
  raise Rejected, :amount_mismatch unless values.all? { |entry| entry["amount"] == expected }
250
255
  end
251
256
  private_class_method :exact!, :one!, :text!, :quantity!, :amount!, :totals!,
252
- :multi_constraints!, :bounded_array!, :unique_ids!, :quantities_match!
257
+ :multi_constraints!, :multi_open!, :bounded_array!, :unique_ids!, :quantities_match!
253
258
  private_constant :CORE_INSTANCE_OF
254
259
  end
255
260
  end
@@ -13,6 +13,8 @@ require_relative "ap2_mandate_verifier/input_builder"
13
13
  require_relative "ap2_mandate_verifier/merchant_signature"
14
14
  require_relative "ap2_mandate_verifier/checkout_jwt"
15
15
  require_relative "ap2_mandate_verifier/checkout_receipt"
16
+ require_relative "ap2_mandate_verifier/buyer"
17
+ require_relative "ap2_mandate_verifier/conditional_checkout"
16
18
 
17
19
  module AP2MandateVerifier
18
20
  # Accepts original JSON bytes only. Syntax validity is not AP2 validity,
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ap2_mandate_verifier
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.6.0
4
+ version: 0.8.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - AP2 Mandate Verifier contributors
@@ -88,15 +88,22 @@ extensions: []
88
88
  extra_rdoc_files: []
89
89
  files:
90
90
  - LICENSE
91
+ - README.ja.md
91
92
  - README.md
93
+ - docs/BUYER_DIRECT_CHECKOUT.md
94
+ - docs/CONDITIONAL_CHECKOUT.md
92
95
  - docs/DIAGNOSTICS.ja.md
93
96
  - docs/DIAGNOSTICS.md
94
97
  - docs/MERCHANT_SIGNING.md
95
98
  - docs/MULTI_ITEM_CHECKOUT.md
99
+ - docs/RELEASE_080_CANDIDATE.md
96
100
  - docs/SUPPORT_CONTRACT.md
101
+ - examples/conditional_checkout.rb
97
102
  - lib/ap2_mandate_verifier.rb
103
+ - lib/ap2_mandate_verifier/buyer.rb
98
104
  - lib/ap2_mandate_verifier/checkout_jwt.rb
99
105
  - lib/ap2_mandate_verifier/checkout_receipt.rb
106
+ - lib/ap2_mandate_verifier/conditional_checkout.rb
100
107
  - lib/ap2_mandate_verifier/diagnostic.rb
101
108
  - lib/ap2_mandate_verifier/host_binding.rb
102
109
  - lib/ap2_mandate_verifier/input_builder.rb