mockcard 2.0.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 9c100d9588ec9e1b0c87d8ff55b4233397252fe99ecbaff0aeb5c0584052d833
4
+ data.tar.gz: 4e34c4c19e69280733cd409c85c04ed099db94002eeb0f12b2dea0ded30c71fd
5
+ SHA512:
6
+ metadata.gz: c5ccb4e390ac8ca2efbbdada59d35e88c3232656b8ecb1e2d5261e0f8c875a02d05034d90966785cbe868c304b8b7c4a346b394829ced63935a3bbf2e5af2988
7
+ data.tar.gz: 6568d1897b0d244c848fc8b01d3ca7f438715309398e6e5ff7e7fa0035eb2159d52b9d7a4c3e3b112f5893abb5906b20371163414953d6a3c5ec812e10f5fb63
data/LICENSE ADDED
@@ -0,0 +1,18 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Arixeva Labs <hello@arixevalabs.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
6
+ associated documentation files (the "Software"), to deal in the Software without restriction,
7
+ including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
8
+ and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
9
+ subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all copies or substantial
12
+ portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
15
+ LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
16
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
17
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
18
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # mockcard (Ruby)
2
+
3
+ Payment failure testing for Ruby. Run MockCard's chaos scenarios against your webhook handler in CI,
4
+ assert what your app did, and guard production against MockCard's monitoring probes. Standard library
5
+ only. Rails apps: add `mockcard-rails` for the middleware, credentials and generator.
6
+
7
+ Author: Arixeva Labs <hello@arixevalabs.com> · [mockcard.io](https://www.mockcard.io) · MIT
8
+
9
+ ```ruby
10
+ gem "mockcard", group: :test
11
+ ```
12
+
13
+ ## Chaos run (Minitest or RSpec)
14
+
15
+ ```ruby
16
+ include MockCard::Assertions
17
+
18
+ run = MockCard::Runner.run_chaos(MockCard::Client.new,
19
+ project_id: "prj_…", target: "http://127.0.0.1:3000/webhooks/stripe",
20
+ assertions: { "duplicate" => { "order fulfilled once" => ->(_ctx) { Order.paid.count == 1 } } })
21
+ assert_chaos_run_passed(run)
22
+ ```
23
+
24
+ Works with the Pay gem: point `target` at Pay's webhook route.
25
+
26
+ ## Production probe guard
27
+
28
+ ```ruby
29
+ if MockCard::Probe.probe?(request.headers) && MockCard::Probe.verify(request.headers, request.raw_post, ENV["MOCKCARD_PROBE_SECRET"])
30
+ response.set_header(MockCard::Probe::ACK_HEADER, "skipped")
31
+ return head :ok
32
+ end
33
+ ```
34
+
35
+ API reference: https://www.mockcard.io/openapi.yaml
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ # HTTP client for the MockCard API (X-Api-Key auth); errors raise MockCard::Error.
4
+ #
5
+ # Author: Arixeva Labs <hello@arixevalabs.com>
6
+ require "json"
7
+ require "net/http"
8
+ require "uri"
9
+
10
+ module MockCard
11
+ # Raised for every non-2xx API response. #status is the HTTP status (0 for network errors),
12
+ # #code MockCard's machine-readable code, e.g. "invalid_api_key".
13
+ class Error < StandardError
14
+ attr_reader :status, :code
15
+
16
+ # @param status [Integer] HTTP status.
17
+ # @param code [String] MockCard error code.
18
+ # @param message [String] Human-readable explanation.
19
+ def initialize(status, code, message)
20
+ super(message)
21
+ @status = status
22
+ @code = code
23
+ end
24
+ end
25
+
26
+ # API client.
27
+ class Client
28
+ # @param api_key [String, nil] Your API key; defaults to ENV["MOCKCARD_API_KEY"].
29
+ # @param base_url [String] API origin.
30
+ # @raise [MockCard::Error] when no API key is given or found.
31
+ def initialize(api_key: ENV["MOCKCARD_API_KEY"], base_url: ENV.fetch("MOCKCARD_BASE_URL", "https://www.mockcard.io"))
32
+ raise Error.new(0, "missing_api_key", "Pass api_key or set MOCKCARD_API_KEY.") if api_key.to_s.empty?
33
+
34
+ @api_key = api_key
35
+ @base_url = base_url.chomp("/")
36
+ end
37
+
38
+ # Sends an authenticated request.
39
+ # @param method [Symbol] :get or :post.
40
+ # @param path [String] API path, e.g. "/api/v1/runs".
41
+ # @param body [Hash, nil] JSON body.
42
+ # @return [Hash] The decoded JSON response.
43
+ # @raise [MockCard::Error] for non-2xx responses and network failures.
44
+ def request(method, path, body = nil)
45
+ uri = URI("#{@base_url}#{path}")
46
+ req = (method == :post ? Net::HTTP::Post : Net::HTTP::Get).new(uri)
47
+ req["X-Api-Key"] = @api_key
48
+ req["User-Agent"] = "mockcard-ruby/2.0.0"
49
+ if body
50
+ req["Content-Type"] = "application/json"
51
+ req.body = JSON.generate(body)
52
+ end
53
+ res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", read_timeout: 30) { |http| http.request(req) }
54
+ data = JSON.parse(res.body.to_s.empty? ? "{}" : res.body)
55
+ return data if res.is_a?(Net::HTTPSuccess)
56
+
57
+ error = data["error"].is_a?(Hash) ? data["error"] : {}
58
+ raise Error.new(res.code.to_i, error.fetch("code", "http_error"), error.fetch("message", "HTTP #{res.code}"))
59
+ rescue SocketError, SystemCallError, Net::OpenTimeout, Net::ReadTimeout => e
60
+ raise Error.new(0, "network_error", e.message)
61
+ end
62
+
63
+ # @return [Array<Hash>] Your projects.
64
+ def list_projects = request(:get, "/api/v1/projects")["projects"]
65
+
66
+ # Creates a project (account-scoped key). @return [Hash] project and probe_secret (shown only now).
67
+ def create_project(name, gateway: "stripe") = request(:post, "/api/v1/projects", { name: name, gateway: gateway })
68
+
69
+ # Creates a run. @param options [Hash] project_id (required), mode, scenarios, target_url, time_scale, trigger, commit_sha, branch.
70
+ def create_run(**options) = request(:post, "/api/v1/runs", options.compact)
71
+
72
+ # @return [Hash] The run with its score and checks.
73
+ def get_run(run_id) = request(:get, "/api/v1/runs/#{run_id}")["run"]
74
+
75
+ # Reports pull-run results (once per run). @return [Hash] The scored run.
76
+ def report_results(run_id, deliveries, assertions = [])
77
+ request(:post, "/api/v1/runs/#{run_id}/results", { deliveries: deliveries, assertions: assertions })["run"]
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Production probe guard. MockCard monitors send probes with "MockCard-Probe: 1" and
4
+ # "MockCard-Signature: t=<unix>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">" under your project's probe
5
+ # secret. Verify, skip all processing, and answer 2xx with "MockCard-Probe-Ack: skipped". A forged
6
+ # probe header can only make your handler skip, never process.
7
+ #
8
+ # Author: Arixeva Labs <hello@arixevalabs.com>
9
+ require "openssl"
10
+
11
+ module MockCard
12
+ module Probe
13
+ ACK_HEADER = "MockCard-Probe-Ack"
14
+ TOLERANCE_SECONDS = 300
15
+ SIGNATURE = /\At=(\d+),v1=([0-9a-f]{64})\z/
16
+
17
+ module_function
18
+
19
+ # Reads a header case-insensitively; also accepts Rack-style HTTP_* keys (request.env).
20
+ # @return [String, nil]
21
+ def header(headers, name)
22
+ rack = "HTTP_#{name.upcase.tr('-', '_')}"
23
+ headers.each { |k, v| return v.to_s if k.to_s.casecmp?(name) || k.to_s == rack }
24
+ nil
25
+ end
26
+
27
+ # @param headers [Hash] Request headers or Rack env.
28
+ # @return [Boolean] whether the request claims to be a MockCard probe (verify before trusting it).
29
+ def probe?(headers) = header(headers, "mockcard-probe") == "1"
30
+
31
+ # Verifies a probe's signature and age.
32
+ # @param headers [Hash] Request headers or Rack env.
33
+ # @param raw_body [String] The exact request body.
34
+ # @param probe_secret [String] Your project's probe secret.
35
+ # @param now [Integer, nil] Current Unix time (injectable for tests).
36
+ # @return [Boolean] true for a genuine, recent MockCard probe.
37
+ def verify(headers, raw_body, probe_secret, now: nil)
38
+ return false if probe_secret.to_s.empty? || !probe?(headers)
39
+
40
+ match = SIGNATURE.match(header(headers, "mockcard-signature").to_s) or return false
41
+ timestamp, given = match.captures
42
+ return false if ((now || Time.now.to_i) - timestamp.to_i).abs > TOLERANCE_SECONDS
43
+
44
+ expected = OpenSSL::HMAC.hexdigest("SHA256", probe_secret, "#{timestamp}.#{raw_body}")
45
+ OpenSSL.fixed_length_secure_compare(expected, given)
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Pull-mode chaos runs for CI: MockCard plans and signs; this delivers the events to your app (which
4
+ # MockCard can't reach) with the planned timing — deliveries due together go out concurrently — runs
5
+ # your outcome assertions, and reports everything back to be scored.
6
+ #
7
+ # Author: Arixeva Labs <hello@arixevalabs.com>
8
+ require "json"
9
+ require "net/http"
10
+ require "uri"
11
+
12
+ module MockCard
13
+ module Runner
14
+ module_function
15
+
16
+ # Delivers one event. @return [Hash] what the app answered.
17
+ def deliver(target, delivery, timeout)
18
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
19
+ uri = URI(target)
20
+ req = Net::HTTP::Post.new(uri, { "Content-Type" => "application/json" }.merge(delivery["headers"]))
21
+ req.body = delivery["body"]
22
+ res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", read_timeout: timeout, open_timeout: timeout) { |h| h.request(req) }
23
+ { "delivery_id" => delivery["id"], "status_code" => res.code.to_i, "duration_ms" => elapsed_ms(started) }
24
+ rescue StandardError => e
25
+ { "delivery_id" => delivery["id"], "status_code" => nil, "duration_ms" => elapsed_ms(started), "error" => e.message }
26
+ end
27
+
28
+ # @return [Integer] milliseconds since started.
29
+ def elapsed_ms(started) = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round
30
+
31
+ # Delivers planned events at their offsets.
32
+ # @param deliveries [Array<Hash>] Planned deliveries from the API.
33
+ # @param target [String] Your webhook URL.
34
+ # @param timeout [Numeric] Per-delivery timeout in seconds.
35
+ # @param sleeper [#call] Waits (seconds); injectable for tests.
36
+ # @param sender [#call] (target, delivery) -> result; injectable for tests.
37
+ # @return [Array<Hash>] One result per delivery, in delivery order.
38
+ def deliver_all(deliveries, target, timeout: 10, sleeper: ->(s) { sleep(s) }, sender: nil)
39
+ sender ||= ->(t, d) { deliver(t, d, timeout) }
40
+ elapsed = 0
41
+ deliveries.group_by { |d| d["at_ms"] }.sort.flat_map do |at, batch|
42
+ sleeper.call((at - elapsed) / 1000.0) if at > elapsed
43
+ elapsed = at
44
+ batch.map { |d| Thread.new { sender.call(target, d) } }.map(&:value)
45
+ end
46
+ end
47
+
48
+ # Runs plan → deliver → assert → report.
49
+ # @param client [MockCard::Client]
50
+ # @param project_id [String]
51
+ # @param target [String] Your webhook URL as the app sees it.
52
+ # @param scenarios [Array<String>, nil]
53
+ # @param assertions [Hash] { "duplicate" => { "fulfilled once" => ->(ctx) { true | false | "message" } } }
54
+ # @param time_scale [Float, nil] 0–1, shrinks waits.
55
+ # @return [Hash] The scored run.
56
+ def run_chaos(client, project_id:, target:, scenarios: nil, assertions: {}, time_scale: nil, **deliver_options)
57
+ created = client.create_run(project_id: project_id, mode: "pull", scenarios: scenarios, time_scale: time_scale,
58
+ trigger: ENV["CI"] ? "ci" : "api", commit_sha: ENV["GITHUB_SHA"],
59
+ branch: ENV["GITHUB_HEAD_REF"] || ENV["GITHUB_REF_NAME"])
60
+ deliveries = created.fetch("deliveries", [])
61
+ results = deliver_all(deliveries, target, **deliver_options)
62
+ checks = created.fetch("expectations", []).flat_map do |exp|
63
+ scenario = exp["scenario"]
64
+ mine = deliveries.each_with_index.select { |d, _| d["scenario"] == scenario }
65
+ ctx = { scenario: scenario, expectation: exp["expectation"], deliveries: mine.map { |d, i| { delivery: d, result: results[i] } },
66
+ events: mine.map { |d, _| JSON.parse(d["body"]) } }
67
+ (assertions[scenario] || assertions[scenario.to_sym] || {}).map do |name, check|
68
+ verdict = begin
69
+ check.call(ctx)
70
+ rescue StandardError => e
71
+ e.message
72
+ end
73
+ verdict == true ? { scenario: scenario, name: name.to_s, passed: true } : { scenario: scenario, name: name.to_s, passed: false, message: verdict.is_a?(String) ? verdict : "Assertion returned false" }
74
+ end
75
+ end
76
+ client.report_results(created["run"]["id"], results, checks)
77
+ end
78
+
79
+ # @return [Array<String>] readable lines for the failed checks.
80
+ def failed_checks(run) = (run.dig("results", "checks") || []).reject { |c| c["passed"] }.map { |c| "✗ #{c['scenario']} · #{c['name']}: #{c['detail']}" }
81
+ end
82
+
83
+ # Minitest and RSpec helper: `assert_chaos_run_passed(run)` / `expect(run).to pass_chaos`.
84
+ module Assertions
85
+ # Fails with every failed check listed when the run didn't pass.
86
+ # @param run [Hash] The scored run.
87
+ def assert_chaos_run_passed(run)
88
+ message = "MockCard run #{run['id']} #{run['status']} (score #{run['score']}/100)\n#{Runner.failed_checks(run).join("\n")}"
89
+ respond_to?(:assert_equal) ? assert_equal("passed", run["status"], message) : (raise message unless run["status"] == "passed")
90
+ end
91
+ end
92
+ end
data/lib/mockcard.rb ADDED
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ # MockCard SDK for Ruby: chaos runs in CI, payment webhook checks and the production probe guard.
4
+ # Standard library only. API reference: https://www.mockcard.io/openapi.yaml
5
+ #
6
+ # Author: Arixeva Labs <hello@arixevalabs.com>
7
+ require_relative "mockcard/client"
8
+ require_relative "mockcard/probe"
9
+ require_relative "mockcard/runner"
metadata ADDED
@@ -0,0 +1,52 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: mockcard
3
+ version: !ruby/object:Gem::Version
4
+ version: 2.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Arixeva Labs
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: "Run MockCard's payment chaos scenarios (duplicate, late, missing and 3DS-abandoned webhooks, declines) against your webhook handler in CI, assert what your app did with Minitest or RSpec, and guard production against MockCard's monitoring probes. Standard library only."
13
+ email: hello@arixevalabs.com
14
+ executables: []
15
+ extensions: []
16
+ extra_rdoc_files: []
17
+ files:
18
+ - LICENSE
19
+ - README.md
20
+ - lib/mockcard.rb
21
+ - lib/mockcard/client.rb
22
+ - lib/mockcard/probe.rb
23
+ - lib/mockcard/runner.rb
24
+ homepage: "https://www.mockcard.io"
25
+ licenses:
26
+ - MIT
27
+ metadata:
28
+ homepage_uri: "https://www.mockcard.io"
29
+ documentation_uri: "https://www.mockcard.io/docs"
30
+ source_code_uri: "https://github.com/arixevalabs/mockcard-ruby"
31
+ bug_tracker_uri: "https://github.com/arixevalabs/mockcard-ruby/issues"
32
+ rubygems_mfa_required: "true"
33
+ rdoc_options: []
34
+ require_paths:
35
+ - lib
36
+ required_ruby_version: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ -
39
+ - ">="
40
+ - !ruby/object:Gem::Version
41
+ version: "3.1"
42
+ required_rubygems_version: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ -
45
+ - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: "0"
48
+ requirements: []
49
+ rubygems_version: 4.1.0
50
+ specification_version: 4
51
+ summary: "MockCard SDK for Ruby: chaos runs in CI, payment webhook checks and the production probe guard."
52
+ test_files: []