ap2_mandate_verifier 0.5.0 → 0.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.
- checksums.yaml +4 -4
- data/README.md +32 -11
- data/docs/BUYER_DIRECT_CHECKOUT.md +180 -0
- data/docs/MERCHANT_SIGNING.md +28 -4
- data/docs/MULTI_ITEM_CHECKOUT.md +119 -0
- data/docs/SUPPORT_CONTRACT.md +47 -7
- data/lib/ap2_mandate_verifier/buyer.rb +153 -0
- data/lib/ap2_mandate_verifier/checkout_jwt.rb +38 -5
- data/lib/ap2_mandate_verifier/checkout_receipt.rb +13 -6
- data/lib/ap2_mandate_verifier/host_binding.rb +2 -1
- data/lib/ap2_mandate_verifier/input_builder.rb +16 -11
- data/lib/ap2_mandate_verifier/merchant_signature.rb +4 -3
- data/lib/ap2_mandate_verifier/purchase_binding.rb +7 -2
- data/lib/ap2_mandate_verifier/root_disclosures.rb +33 -10
- data/lib/ap2_mandate_verifier/scoped_constraints.rb +143 -2
- data/lib/ap2_mandate_verifier/trust_context.rb +21 -4
- data/lib/ap2_mandate_verifier.rb +3 -2
- metadata +4 -1
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module AP2MandateVerifier
|
|
4
|
+
# Optional Direct/Human Present profile; never an Open -> Closed chain.
|
|
5
|
+
module Buyer
|
|
6
|
+
PROFILE_REF = "ap2.checkout.direct.single_merchant".freeze
|
|
7
|
+
CHECKOUT_PROFILE = ScopedConstraints::MULTI_PROFILE_REF
|
|
8
|
+
MAX_LIFETIME = 600
|
|
9
|
+
class Invalid < ArgumentError
|
|
10
|
+
def initialize = super("invalid direct checkout information")
|
|
11
|
+
end
|
|
12
|
+
class Issued
|
|
13
|
+
attr_reader :closed_sd_jwt
|
|
14
|
+
def initialize(wire)
|
|
15
|
+
@closed_sd_jwt = wire.freeze
|
|
16
|
+
freeze
|
|
17
|
+
end
|
|
18
|
+
private_class_method :new
|
|
19
|
+
end
|
|
20
|
+
class Verification
|
|
21
|
+
attr_reader :code, :checkout, :checkout_hash, :reference, :expires_at
|
|
22
|
+
def initialize(code, parsed = nil)
|
|
23
|
+
@code = code
|
|
24
|
+
if parsed
|
|
25
|
+
@checkout = parsed.fetch(:checkout)
|
|
26
|
+
@checkout_hash = parsed.fetch(:closed).fetch("checkout_hash").freeze
|
|
27
|
+
@expires_at = parsed.fetch(:closed).fetch("exp")
|
|
28
|
+
@reference = Buyer.send(:hash, parsed.fetch(:wire)).freeze
|
|
29
|
+
end
|
|
30
|
+
freeze
|
|
31
|
+
end
|
|
32
|
+
def verified? = code == :direct_checkout_verified
|
|
33
|
+
private_class_method :new
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# Only the authenticated approval backend calls this method. The approved
|
|
37
|
+
# wire comes from its protected approval record, never an Agent boolean.
|
|
38
|
+
# This is an equality contract, not authentication of the approver.
|
|
39
|
+
def self.issue_closed(checkout_jwt:, approved_checkout_jwt:, trusted_merchant_public_key_pem:,
|
|
40
|
+
expected_merchant_id:, issued_at:, expires_at:, signer:, public_key_pem:)
|
|
41
|
+
wire = InputValidator.snapshot!(checkout_jwt, max_bytes: 16_384)
|
|
42
|
+
approved = InputValidator.snapshot!(approved_checkout_jwt, max_bytes: 16_384)
|
|
43
|
+
raise Invalid unless wire == approved
|
|
44
|
+
epoch!(issued_at); epoch!(expires_at)
|
|
45
|
+
raise Invalid unless expires_at > issued_at && expires_at - issued_at <= MAX_LIFETIME
|
|
46
|
+
checked = CheckoutJWT.verify(jwt: wire, trusted_public_key_pem: trusted_merchant_public_key_pem,
|
|
47
|
+
expected_merchant_id: expected_merchant_id, profile_ref: CHECKOUT_PROFILE)
|
|
48
|
+
require "securerandom"
|
|
49
|
+
disclosure = encode([encode(SecureRandom.random_bytes(16)), "checkout_jwt", checked.jwt])
|
|
50
|
+
closed = {"vct" => "mandate.checkout.1", "checkout_hash" => checked.checkout_hash,
|
|
51
|
+
"iat" => issued_at, "exp" => expires_at, "_sd" => [hash(disclosure)]}
|
|
52
|
+
content = encode([encode(SecureRandom.random_bytes(16)), closed])
|
|
53
|
+
payload = {"delegate_payload" => [{"..." => hash(content)}], "_sd_alg" => "sha-256"}
|
|
54
|
+
jwt = MerchantSignature.sign!(payload, signer, public_key_pem, typ: "example+sd-jwt")
|
|
55
|
+
result = "#{jwt}~#{content}~#{disclosure}~"
|
|
56
|
+
parse!(result)
|
|
57
|
+
Issued.send(:new, result)
|
|
58
|
+
rescue StandardError, LoadError
|
|
59
|
+
raise Invalid.new, cause: nil
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# All two disclosures are required for this profile. No Agent signature,
|
|
63
|
+
# aud, nonce, or KB-JWT is added. Restoration preserves the exact bytes.
|
|
64
|
+
def self.present_closed(closed_sd_jwt:)
|
|
65
|
+
parse!(closed_sd_jwt).fetch(:wire)
|
|
66
|
+
rescue StandardError, LoadError
|
|
67
|
+
raise Invalid.new, cause: nil
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# Merchant supplies independently registered Provider/Merchant keys and
|
|
71
|
+
# the exact current order from its own database. Success is not Host ALLOW.
|
|
72
|
+
def self.verify(closed_sd_jwt:, trusted_provider_public_key_pem:, trusted_merchant_public_key_pem:,
|
|
73
|
+
expected_checkout_jwt:, expected_merchant_id:, verified_at:)
|
|
74
|
+
epoch!(verified_at)
|
|
75
|
+
parsed = parse!(closed_sd_jwt)
|
|
76
|
+
RootSignature.verified_payload!(parsed.fetch(:jwt), trusted_provider_public_key_pem)
|
|
77
|
+
closed = parsed.fetch(:closed)
|
|
78
|
+
raise Invalid unless closed.fetch("iat") <= verified_at && verified_at < closed.fetch("exp")
|
|
79
|
+
expected = InputValidator.snapshot!(expected_checkout_jwt, max_bytes: 16_384)
|
|
80
|
+
raise Invalid unless closed.fetch("checkout_jwt") == expected
|
|
81
|
+
checked = CheckoutJWT.verify(jwt: expected, trusted_public_key_pem: trusted_merchant_public_key_pem,
|
|
82
|
+
expected_merchant_id: expected_merchant_id, profile_ref: CHECKOUT_PROFILE)
|
|
83
|
+
Verification.send(:new, :direct_checkout_verified, parsed.merge(checkout: checked.checkout))
|
|
84
|
+
rescue StandardError, LoadError
|
|
85
|
+
Verification.send(:new, :direct_checkout_verification_failed)
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
# Exact bounded grammar, not a general selective-disclosure resolver.
|
|
89
|
+
# Every commitment is consumed exactly once, without decoys/hidden fields.
|
|
90
|
+
def self.parse!(source)
|
|
91
|
+
RootSignature.send(:dependencies!)
|
|
92
|
+
wire = InputValidator.snapshot!(source, max_bytes: 32_768)
|
|
93
|
+
raise Invalid unless wire.ascii_only?
|
|
94
|
+
jwt, content, disclosure, tail, *extra = wire.split("~", -1)
|
|
95
|
+
raise Invalid unless tail == "" && extra.empty?
|
|
96
|
+
parts = jwt.split(".", -1)
|
|
97
|
+
raise Invalid unless parts.size == 3
|
|
98
|
+
header = InputValidator.parse!(RootSignature.send(:decode!, parts[0], 2_048))
|
|
99
|
+
CheckoutReceipt.send(:header!, header, "example+sd-jwt")
|
|
100
|
+
raise Invalid unless RootSignature.send(:decode!, parts[2], 64).bytesize == 64
|
|
101
|
+
payload = InputValidator.parse!(RootSignature.send(:decode!, parts[1], 2_048))
|
|
102
|
+
exact!(payload, %w[_sd_alg delegate_payload])
|
|
103
|
+
raise Invalid unless payload["_sd_alg"] == "sha-256"
|
|
104
|
+
pointer = ScopedConstraints.send(:one!, payload["delegate_payload"])
|
|
105
|
+
exact!(pointer, ["..."])
|
|
106
|
+
raise Invalid unless pointer["..."] == hash(content)
|
|
107
|
+
revealed = decode_disclosure!(content, 2)
|
|
108
|
+
closed = revealed[1]
|
|
109
|
+
exact!(closed, %w[_sd checkout_hash exp iat vct])
|
|
110
|
+
raise Invalid unless closed["vct"] == "mandate.checkout.1" && closed["_sd"] == [hash(disclosure)]
|
|
111
|
+
epoch!(closed["iat"]); epoch!(closed["exp"])
|
|
112
|
+
raise Invalid unless closed["exp"] > closed["iat"] && closed["exp"] - closed["iat"] <= MAX_LIFETIME
|
|
113
|
+
leaf = decode_disclosure!(disclosure, 3)
|
|
114
|
+
raise Invalid unless leaf[1] == "checkout_jwt"
|
|
115
|
+
checkout = InputValidator.snapshot!(leaf[2], max_bytes: 16_384)
|
|
116
|
+
raise Invalid unless closed["checkout_hash"] == hash(checkout)
|
|
117
|
+
# Parse supported merchant syntax too, without claiming its authenticity.
|
|
118
|
+
checkout_parts = checkout.split(".", -1)
|
|
119
|
+
raise Invalid unless checkout_parts.size == 3
|
|
120
|
+
checkout_header = InputValidator.parse!(RootSignature.send(:decode!, checkout_parts[0], 2_048))
|
|
121
|
+
CheckoutReceipt.send(:header!, checkout_header, "JWT")
|
|
122
|
+
raise Invalid unless RootSignature.send(:decode!, checkout_parts[2], 64).bytesize == 64
|
|
123
|
+
claims = InputValidator.parse!(RootSignature.send(:decode!, checkout_parts[1], 12_000))
|
|
124
|
+
CheckoutJWT.send(:validate!, claims, profile_ref: CHECKOUT_PROFILE)
|
|
125
|
+
{wire: wire, jwt: jwt, closed: closed.merge("checkout_jwt" => checkout)}
|
|
126
|
+
end
|
|
127
|
+
def self.decode_disclosure!(wire, size)
|
|
128
|
+
value = InputValidator.parse!(RootSignature.send(:decode!, wire, 24_576))
|
|
129
|
+
raise Invalid unless value.instance_of?(Array) && value.size == size &&
|
|
130
|
+
value[0].instance_of?(String) && value[0].match?(/\A[A-Za-z0-9_-]{22,128}\z/)
|
|
131
|
+
value
|
|
132
|
+
end
|
|
133
|
+
def self.epoch!(value) = CheckoutReceipt.send(:epoch!, value)
|
|
134
|
+
def self.exact!(value, fields) = PurchaseBinding.send(:exact!, value, fields)
|
|
135
|
+
def self.hash(wire) = Base64.urlsafe_encode64(Digest::SHA256.digest(wire), padding: false)
|
|
136
|
+
def self.encode(value)
|
|
137
|
+
require "json"
|
|
138
|
+
Base64.urlsafe_encode64(value.instance_of?(String) ? value : JSON.generate(value), padding: false)
|
|
139
|
+
end
|
|
140
|
+
%i[issue_closed present_closed verify].each do |name|
|
|
141
|
+
implementation = method(name)
|
|
142
|
+
fields = implementation.parameters.map(&:last).freeze
|
|
143
|
+
define_singleton_method(name) do |**arguments|
|
|
144
|
+
unless (fields - arguments.keys).empty? && (arguments.keys - fields).empty?
|
|
145
|
+
next Verification.send(:new, :direct_checkout_verification_failed) if name == :verify
|
|
146
|
+
raise Invalid.new, cause: nil
|
|
147
|
+
end
|
|
148
|
+
implementation.call(**arguments)
|
|
149
|
+
end
|
|
150
|
+
end
|
|
151
|
+
private_class_method :parse!, :decode_disclosure!, :epoch!, :exact!, :hash, :encode
|
|
152
|
+
end
|
|
153
|
+
end
|
|
@@ -17,13 +17,39 @@ 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).
|
|
23
|
-
def self.sign(checkout:, signer:, public_key_pem:)
|
|
49
|
+
def self.sign(checkout:, signer:, public_key_pem:, profile_ref: TrustContext::PROFILE_REF)
|
|
24
50
|
RootSignature.send(:dependencies!)
|
|
25
51
|
value = InputBuilder.send(:copy!, checkout)
|
|
26
|
-
validate!(value)
|
|
52
|
+
validate!(value, profile_ref: profile_ref)
|
|
27
53
|
jwt = MerchantSignature.sign!(value, signer, public_key_pem)
|
|
28
54
|
Signed.send(:new, jwt)
|
|
29
55
|
rescue StandardError, LoadError
|
|
@@ -44,7 +70,13 @@ module AP2MandateVerifier
|
|
|
44
70
|
raise Invalid.new, cause: nil
|
|
45
71
|
end
|
|
46
72
|
|
|
47
|
-
def self.validate!(checkout)
|
|
73
|
+
def self.validate!(checkout, profile_ref: TrustContext::PROFILE_REF)
|
|
74
|
+
profile_ref = InputValidator.snapshot!(profile_ref, max_bytes: 256)
|
|
75
|
+
if profile_ref == ScopedConstraints::MULTI_PROFILE_REF
|
|
76
|
+
ScopedConstraints.multi_checkout!(checkout)
|
|
77
|
+
return nil
|
|
78
|
+
end
|
|
79
|
+
raise Invalid unless profile_ref == TrustContext::PROFILE_REF
|
|
48
80
|
c = ScopedConstraints
|
|
49
81
|
c.send(:exact!, checkout, %w[currency id line_items links merchant status totals])
|
|
50
82
|
c.send(:text!, checkout["id"])
|
|
@@ -68,11 +100,12 @@ module AP2MandateVerifier
|
|
|
68
100
|
c.send(:totals!, checkout["totals"], total)
|
|
69
101
|
nil
|
|
70
102
|
end
|
|
71
|
-
%i[sign es256_signer].each do |name|
|
|
103
|
+
%i[sign es256_signer verify].each do |name|
|
|
72
104
|
implementation = method(name)
|
|
73
105
|
fields = implementation.parameters.filter_map { |kind, field| field if kind == :keyreq }.freeze
|
|
106
|
+
optional = implementation.parameters.filter_map { |kind, field| field if kind == :key }.freeze
|
|
74
107
|
define_singleton_method(name) do |**arguments|
|
|
75
|
-
raise Invalid.new, cause: nil unless (fields - arguments.keys).empty? && (arguments.keys - fields).empty?
|
|
108
|
+
raise Invalid.new, cause: nil unless (fields - arguments.keys).empty? && (arguments.keys - fields - optional).empty?
|
|
76
109
|
implementation.call(**arguments)
|
|
77
110
|
end
|
|
78
111
|
end
|
|
@@ -32,7 +32,12 @@ module AP2MandateVerifier
|
|
|
32
32
|
|
|
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
|
-
def self.reference(closed_sd_jwt:)
|
|
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)
|
|
@@ -62,15 +67,16 @@ module AP2MandateVerifier
|
|
|
62
67
|
checkout_header = InputValidator.parse!(RootSignature.send(:decode!, checkout_parts[0], 2_048))
|
|
63
68
|
header!(checkout_header, "JWT")
|
|
64
69
|
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)))
|
|
70
|
+
CheckoutJWT.send(:validate!, InputValidator.parse!(RootSignature.send(:decode!, checkout_parts[1], 12_000)), profile_ref: profile_ref)
|
|
66
71
|
raise Invalid unless closed["checkout_hash"] == hash(checkout)
|
|
67
72
|
hash(wire).freeze
|
|
68
73
|
rescue StandardError, LoadError
|
|
69
74
|
raise Invalid.new, cause: nil
|
|
70
75
|
end
|
|
71
76
|
|
|
72
|
-
def self.sign(closed_sd_jwt:, issuer:, outcome:, issued_at:, signer:, public_key_pem:, order_id: nil, error: nil, error_description: nil
|
|
73
|
-
|
|
77
|
+
def self.sign(closed_sd_jwt:, issuer:, outcome:, issued_at:, signer:, public_key_pem:, order_id: nil, error: nil, error_description: nil,
|
|
78
|
+
profile_ref: TrustContext::PROFILE_REF)
|
|
79
|
+
ref = reference(closed_sd_jwt: closed_sd_jwt, profile_ref: profile_ref)
|
|
74
80
|
claims = {"iss" => issuer, "status" => outcome, "iat" => issued_at, "reference" => ref}
|
|
75
81
|
claims["order_id"] = order_id unless order_id.nil?
|
|
76
82
|
claims["error"] = error unless error.nil?
|
|
@@ -86,12 +92,13 @@ module AP2MandateVerifier
|
|
|
86
92
|
# The Host supplies trusted enrollment key, expected signer and explicit time
|
|
87
93
|
# window independently. JWT iss/kid are never used to choose trust.
|
|
88
94
|
# Reference authenticates byte identity, not Mandate authorization/validity.
|
|
89
|
-
def self.verify(jwt:, closed_sd_jwt:, trusted_public_key_pem:, expected_issuer:, not_before:, not_after:, verified_at
|
|
95
|
+
def self.verify(jwt:, closed_sd_jwt:, trusted_public_key_pem:, expected_issuer:, not_before:, not_after:, verified_at:,
|
|
96
|
+
profile_ref: TrustContext::PROFILE_REF)
|
|
90
97
|
expected = InputValidator.snapshot!(expected_issuer, max_bytes: 512)
|
|
91
98
|
text!(expected, 512)
|
|
92
99
|
[not_before, not_after, verified_at].each { |t| epoch!(t) }
|
|
93
100
|
raise Invalid unless not_before <= verified_at && verified_at <= not_after
|
|
94
|
-
ref = reference(closed_sd_jwt: closed_sd_jwt)
|
|
101
|
+
ref = reference(closed_sd_jwt: closed_sd_jwt, profile_ref: profile_ref)
|
|
95
102
|
claims = RootSignature.verified_payload!(jwt, trusted_public_key_pem, expected_typ: "JWT", max_bytes: 16_384)
|
|
96
103
|
validate!(claims)
|
|
97
104
|
return Verification.send(:new, :receipt_issuer_mismatch) unless claims["iss"] == expected
|
|
@@ -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" =>
|
|
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" =>
|
|
51
|
-
"profile_definition_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" =>
|
|
57
|
-
"definition_hash" =>
|
|
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" =>
|
|
98
|
-
"profile_version" =>
|
|
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,
|
|
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
|
-
|
|
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.
|
|
264
|
+
invalid!("arguments", :unknown_field) unless (arguments.keys - fields - optional).empty?
|
|
260
265
|
implementation.call(**arguments)
|
|
261
266
|
end
|
|
262
267
|
end
|
|
@@ -3,19 +3,20 @@
|
|
|
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
8
|
payload = InputBuilder.send(:json!, claims, 12_000)
|
|
9
9
|
pem = InputValidator.snapshot!(public_key_pem, max_bytes: 1_024)
|
|
10
10
|
RootSignature.public_jwk!(pem)
|
|
11
|
-
|
|
11
|
+
raise ArgumentError unless %w[JWT example+sd-jwt].include?(typ)
|
|
12
|
+
header = Base64.urlsafe_encode64(JSON.generate({"alg" => "ES256", "typ" => typ}), padding: false)
|
|
12
13
|
input = "#{header}.#{Base64.urlsafe_encode64(payload, padding: false)}".freeze
|
|
13
14
|
raw = signer.call(input)
|
|
14
15
|
raise ArgumentError unless Object.instance_method(:instance_of?).bind_call(raw, String) &&
|
|
15
16
|
String.instance_method(:bytesize).bind_call(raw) == 64
|
|
16
17
|
signature = String.instance_method(:byteslice).bind_call(raw, 0, 64)
|
|
17
18
|
jwt = "#{input}.#{Base64.urlsafe_encode64(signature, padding: false)}"
|
|
18
|
-
raise ArgumentError unless RootSignature.verified_payload!(jwt, pem, expected_typ:
|
|
19
|
+
raise ArgumentError unless RootSignature.verified_payload!(jwt, pem, expected_typ: typ, max_bytes: 16_384) == claims
|
|
19
20
|
jwt.freeze
|
|
20
21
|
end
|
|
21
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 =
|
|
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
|
-
|
|
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 == ["..."] &&
|
|
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
|