From 2ffa33a506d935082db6d343f7750e29278ccbf7 Mon Sep 17 00:00:00 2001 From: Zoey Lan Date: Tue, 27 Oct 2026 13:53:28 -0600 Subject: [PATCH] Add JWT client assertion support to client credentials `ShopifyAPI::Auth::ClientCredentials.client_credentials` takes an optional `client_assertion:`. When passed, the token request authenticates with the JWT, sends no client secret, and turns off inherited HTTP Basic or digest auth for that request only. `ShopifyAPI::Auth::ClientAssertion.create` signs one assertion with an `RS256` or `ES256` key the app owns. `client_id` defaults to `Context.api_key`, and `audience:` covers development stores without a `myshopify.com` domain. Client-credentials requests no longer follow redirects for either authentication mode, since the request body carries the app's credentials. Co-Authored-By: Claude --- CHANGELOG.md | 7 + docs/usage/oauth.md | 128 ++++++- lib/shopify_api/auth/client_assertion.rb | 157 ++++++++ lib/shopify_api/auth/client_credentials.rb | 65 +++- lib/shopify_api/clients/http_client.rb | 66 +++- lib/shopify_api/clients/http_request.rb | 6 + .../errors/invalid_client_assertion_error.rb | 9 + test/auth/client_assertion_test.rb | 349 ++++++++++++++++++ test/auth/client_credentials_test.rb | 342 +++++++++++++++++ test/clients/http_client_test.rb | 132 +++++++ 10 files changed, 1243 insertions(+), 18 deletions(-) create mode 100644 lib/shopify_api/auth/client_assertion.rb create mode 100644 lib/shopify_api/errors/invalid_client_assertion_error.rb create mode 100644 test/auth/client_assertion_test.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 127bab169..619b7ee29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,13 @@ Note: For changes to the API, see https://shopify.dev/changelog?filter=api ## Unreleased +- [#1475](https://github.com/Shopify/shopify-api-ruby/pull/1475) Add an optional `client_assertion:` argument to `ShopifyAPI::Auth::ClientCredentials.client_credentials`. When supplied, the token request authenticates with a JWT client assertion and sends no client secret. Omitting it, or passing `nil`, keeps the existing client-secret behavior. See the [OAuth documentation](docs/usage/oauth.md#client-assertion-authentication). +- [#1475](https://github.com/Shopify/shopify-api-ruby/pull/1475) Add `ShopifyAPI::Auth::ClientAssertion.create`, an optional helper that signs a client assertion with an `RS256` (RSA, 2048-bit minimum) or `ES256` (EC P-256) private key your app owns. `client_id` defaults to `ShopifyAPI::Context.api_key`, the only value the helper reads from the context, and it never generates, imports, stores, or rotates keys. +- [#1475](https://github.com/Shopify/shopify-api-ruby/pull/1475) Add `ShopifyAPI::Errors::InvalidClientAssertionError`, raised for a blank or non-`String` assertion, for an assertion with surrounding whitespace, and for invalid signer input. +- [#1475](https://github.com/Shopify/shopify-api-ruby/pull/1475) For client-assertion token requests only, send HTTParty's inherited Basic and digest authentication as `nil`, so a single-use assertion is never replayed against a digest challenge, and reject a URL that carries userinfo before I/O. The HTTP transport, connection settings, non-credential headers, and global HTTParty defaults are unchanged, and everything else in global HTTParty state stays the caller's responsibility. +- ⚠️ [Behavior change] [#1475](https://github.com/Shopify/shopify-api-ruby/pull/1475) `ShopifyAPI::Auth::ClientCredentials.client_credentials` no longer follows redirects, with either authentication method, and raises `ShopifyAPI::Errors::HttpResponseError` naming the status and the target instead. A 307 or 308 would otherwise forward the credential-bearing request body to the redirect target. This changes the existing client-secret path, including for apps that enabled redirects through global HTTParty defaults; no request is sent to the redirect target. Other operations keep their redirect policy. + - Limitation: this applies to the client-credentials token request only. `ShopifyAPI::Auth::Oauth.validate_auth_callback`, both `ShopifyAPI::Auth::TokenExchange` requests (`exchange_token` and `migrate_to_expiring_token`), and `ShopifyAPI::Auth::RefreshToken.refresh_access_token` still POST the client secret under HTTParty's default redirect policy. + ## 16.3.1 (2026-10-22) - [#1472](https://github.com/Shopify/shopify-api-ruby/pull/1472) `ShopifyAPI::Auth.embedded_app_url` now raises `ShopifyAPI::Errors::InvalidShopError` unless the decoded `host` is a trusted Shopify Admin host (see `ShopifyAPI::Utils::ShopValidator`). URLs for supported Admin hosts are unchanged. - [#1472](https://github.com/Shopify/shopify-api-ruby/pull/1472) `ShopifyAPI::Auth::Oauth.begin_auth` now validates and normalizes `shop` with `ShopifyAPI::Utils::ShopValidator.sanitize!`, and raises `ShopifyAPI::Errors::InvalidShopError` for untrusted domains. diff --git a/docs/usage/oauth.md b/docs/usage/oauth.md index 6a459a68e..a78e59177 100644 --- a/docs/usage/oauth.md +++ b/docs/usage/oauth.md @@ -277,18 +277,29 @@ end ### Client Credentials Grant > [!NOTE] -> You can only use the client credentials grant when building apps for your own organization. +> Existing client-secret eligibility rules are unchanged. Assertion authentication also supports eligible +> public apps with a registered public key and an existing installation on the target shop, when the +> Shopify token endpoint supports this authentication method. > [!WARNING] > [token exchange](#token-exchange) (for embedded apps) or the [authorization code grant](#authorization-code-grant) should be used instead of the client credentials grant, if your app is a browser based web app. #### Perform Client Credentials Grant Use [`ShopifyAPI::Auth::ClientCredentials`](https://github.com/Shopify/shopify-api-ruby/blob/main/lib/shopify_api/auth/client_credentials.rb) to -exchange the [app's client ID and client secret](https://shopify.dev/docs/apps/build/authentication-authorization/client-secrets) for an access token. +obtain an application-only access token using the [app's client ID and client secret](https://shopify.dev/docs/apps/build/authentication-authorization/client-secrets), +or a [signed client assertion](#client-assertion-authentication). + +Client-credentials requests do not follow HTTP redirects, with either authentication method. A redirect +raises `ShopifyAPI::Errors::HttpResponseError`; no request is sent to its target. This prevents a 307/308 +from forwarding the credential-bearing POST body. This intentionally changes the previous secret-path +behavior, including when global HTTParty defaults enable redirects. Explicit routing and connection +settings remain supported, and other operations keep their redirect policy. + #### Input | Parameter | Type | Required? | Default Value | Notes | | -------------- | ---------------------- | :-------: | :-----------: | ----------------------------------------------------------------------------------------------------------- | | `shop` | `String` | Yes | - | A Shopify domain name in the form `{exampleshop}.myshopify.com`. | +| `client_assertion` | `String` | No | `nil` | A signed JWT client assertion. When omitted or `nil`, the grant authenticates with the app's client secret as before. Leading or trailing whitespace is rejected rather than trimmed. See [Client Assertion Authentication](#client-assertion-authentication). | #### Output This method returns the new `ShopifyAPI::Auth::Session` object from the client credentials grant, your app should store this `Session` object to be used later [when making authenticated API calls](#using-oauth-session-to-make-authenticated-api-calls). @@ -307,6 +318,119 @@ end ``` +### Client Assertion Authentication + +Instead of the app's client secret, the client credentials grant can authenticate with a short-lived JWT +client assertion signed by a private key your app owns. Pass the assertion as `client_assertion:`; the +request then sends only `client_id`, `grant_type`, `client_assertion_type` and `client_assertion`, and no +client secret. + +To generate a key pair, register its public key with your app and see the claims Shopify expects, read +[Get application-only access tokens](https://shopify.dev/docs/apps/build/authentication-authorization/application-only-access-tokens). + +> [!IMPORTANT] +> An assertion is **single use**. Every token request — including every retry after a failure — needs a +> newly created assertion, because a second use of the same assertion is refused. This library makes one +> HTTP attempt per call and does not follow redirects on the assertion request, so a consumed assertion is +> never replayed on your behalf. + +The assertion request uses the same HTTP transport as other requests. For this call only, it sends +`basic_auth` and `digest_auth` as `nil`, so inherited Basic or digest credentials are never attached and +HTTParty cannot replay the single-use assertion against a digest challenge. Global HTTParty defaults are +not modified, connection settings such as proxy, CA, and timeout configuration remain in effect, and so do +non-credential headers. Requests without an assertion keep their authentication and connection settings, +but follow the same no-redirect policy. + +The request also fails before I/O with `ShopifyAPI::Errors::InvalidHttpRequestError` if +`ShopifyAPI::Context.api_host` contains URL userinfo (`user:password@host`). HTTParty rebuilds Basic +credentials from the URL after the `nil` override, so those credentials would otherwise be sent. + +Everything else in global HTTParty state is yours to control, and this library neither inspects nor changes +it. Two cases are worth calling out: a `logger` with `log_format: :curl` writes `request.raw_body`, and +therefore the assertion, into your application log; and default headers such as `Cookie` or +`Proxy-Authorization`, along with `HTTParty.cookies`, are attached to this request like any other. Custom +connection adapters and diagnostic logging must not add OAuth credentials, replay the assertion, or log it. + +Your app owns the key pair. This library never generates, imports, stores, or rotates keys, and never reads +a key from `ShopifyAPI::Context`. Register the matching public key with Shopify and pass its key ID as +`kid`. Omitting `client_assertion` keeps the existing client-secret behavior, and a blank or non-`String` +value raises `ShopifyAPI::Errors::InvalidClientAssertionError` rather than silently falling back to the +secret. + +> [!IMPORTANT] +> **You must supply the target shop's permanent domain.** The helper normalizes case and surrounding +> whitespace only; it does not look up the permanent domain or verify the shop's identity. Every domain that +> is not a `myshopify.com` domain is rejected, including custom storefront domains and the development +> domains `ShopifyAPI::Utils::ShopValidator` trusts. A valid +> `myshopify.com` domain is used as supplied, so you must select the correct shop and use the same canonical +> domain when exchanging the assertion. + +#### Creating an assertion + +[`ShopifyAPI::Auth::ClientAssertion.create`](https://github.com/Shopify/shopify-api-ruby/blob/main/lib/shopify_api/auth/client_assertion.rb) +is an optional helper that signs an assertion with a key your app already holds in memory. It modifies +nothing, needs no client secret, and the only value it reads from `ShopifyAPI::Context` is `api_key`, as the +default for `client_id`. + +| Parameter | Type | Required? | Default Value | Notes | +| --------- | ---- | :-------: | :-----------: | ----- | +| `shop` | `String` | Yes | - | The shop's permanent `{shop}.myshopify.com` domain, which becomes the assertion's `aud`. Only case and surrounding whitespace are normalized; a bare shop handle, a full URL, an `admin.shopify.com/store/{shop}` URL, and anything that is not a `myshopify.com` domain are all rejected. Not used when `audience` is supplied. | +| `client_id` | `String` | No | `ShopifyAPI::Context.api_key` | Your app's client ID. Becomes both `iss` and `sub`, which Shopify requires to match the `client_id` the token request sends — so the default is normally the right value. | +| `kid` | `String` | Yes | - | The key ID of the registered public key. Surrounding whitespace is trimmed, and a `kid` longer than 255 characters is rejected, since Shopify cannot store one. | +| `private_key` | `OpenSSL::PKey::RSA` or `OpenSSL::PKey::EC` | Yes | - | A private key object. RSA keys must be at least 2048 bits (`RS256`); EC keys must use the P-256 curve (`ES256`). Anything else is rejected. | +| `lifetime_seconds` | `Integer` | No | `60` | Must be between 1 and 300. Out-of-range values are rejected, not clamped. | +| `audience` | `String` | No | `nil` | Sets the `aud` claim directly and skips all `shop` validation. For development environments only, where the shop's permanent domain is not a `myshopify.com` domain; you are responsible for the value. | + +```ruby +# `private_key` is an OpenSSL::PKey::RSA or OpenSSL::PKey::EC private key your app loaded itself. +def authenticate_with_assertion(shop, private_key) + assertion = ShopifyAPI::Auth::ClientAssertion.create( + shop: shop, + kid: "my-registered-key-id", + private_key: private_key, + ) + + session = ShopifyAPI::Auth::ClientCredentials.client_credentials( + shop: shop, + client_assertion: assertion, + ) + SessionRepository.store_session(session) +end +``` + +The algorithm is derived from the key, and the claims (`iss`, `sub`, `aud`, `iat`, `exp`, and a fresh `jti` +per call) are built by the library. Supplying your own claims, headers, or algorithm is not supported. If +you sign elsewhere — with a KMS or HSM, for example — skip this helper and pass the finished assertion +string straight to `client_credentials`. + +Keep the signing host's clock synchronized. Shopify checks `iat` and `exp` against its own clock, so a host +whose clock is off can sign assertions that are rejected. If the clock may drift, raise `lifetime_seconds` +toward 300. + +Pass the full `{shop}.myshopify.com` domain to both calls, as the example above does. The signer and +`client_credentials` accept the same canonical domain, so one value works for both. + +A development store whose permanent domain is not a `myshopify.com` domain is rejected by the signer. Pass +`audience:` in that case, built as +`https://{permanent domain}/admin/oauth/access_token`, and keep it out of production code paths. + +Your app still needs its real client secret configured: `ShopifyAPI::Context.setup` requires +`api_secret_key`, and other parts of this library use it, such as webhook HMAC and session-token +verification. On the assertion path it is never read, never sent, and never used. + +#### Troubleshooting + +A `401 invalid_client` response means the assertion was rejected. The response doesn't say why, so check +that: + +- the `kid` names an active key registered for this app +- the assertion was signed with that key's private key +- `aud` is `https://{the shop's permanent domain}/admin/oauth/access_token` +- `iss` and `sub` are the `client_id` the request sends +- the assertion is new: each one can only be used once + +A `5xx` response is temporary. Sign a new assertion before you retry. + ## Expiring Offline Access Tokens diff --git a/lib/shopify_api/auth/client_assertion.rb b/lib/shopify_api/auth/client_assertion.rb new file mode 100644 index 000000000..721380a8d --- /dev/null +++ b/lib/shopify_api/auth/client_assertion.rb @@ -0,0 +1,157 @@ +# typed: strict +# frozen_string_literal: true + +module ShopifyAPI + module Auth + module ClientAssertion + extend T::Sig + + DEFAULT_LIFETIME_SECONDS = 60 + # Mirrors Shopify's own bound: an assertion whose `exp - iat` is more than 5 minutes is rejected, and + # exactly 300 seconds is accepted. Check this value against + # https://shopify.dev/docs/apps/build/authentication-authorization/application-only-access-tokens + # before changing it. + MAX_LIFETIME_SECONDS = 300 + RSA_ALGORITHM = "RS256" + EC_ALGORITHM = "ES256" + MIN_RSA_KEY_BITS = 2048 + # Shopify accepts a `kid` of at most 255 characters, so a longer one can never match. + MAX_KID_LENGTH = 255 + SUPPORTED_EC_CURVES = T.let(["prime256v1", "secp256r1"].freeze, T::Array[String]) + PERMANENT_SHOP_DOMAIN = /\A[a-z0-9][a-z0-9_-]*\.myshopify\.com\z/ + MYSHOPIFY_DOMAIN = "myshopify.com" + + class << self + extend T::Sig + + sig do + params( + shop: String, + kid: String, + private_key: T.any(OpenSSL::PKey::RSA, OpenSSL::PKey::EC), + client_id: T.nilable(String), + lifetime_seconds: Integer, + audience: T.nilable(String), + ).returns(String) + end + def create( + shop:, + kid:, + private_key:, + client_id: nil, + lifetime_seconds: DEFAULT_LIFETIME_SECONDS, + audience: nil + ) + audience = audience.nil? ? audience_for(shop) : validated_audience(audience) + # The only value read from `ShopifyAPI::Context`, and only when the caller omits it. The server + # requires `iss` and `sub` to equal the `client_id` the request posts, which is `Context.api_key`. + client_id = Context.api_key if client_id.nil? + client_id = validated_value(client_id, "client_id") + kid = validated_kid(kid) + validate_lifetime!(lifetime_seconds) + signing_key, algorithm = validated_key_with_algorithm(private_key) + + issued_at = Time.now.to_i + claims = { + "iss" => client_id, + "sub" => client_id, + "aud" => audience, + "iat" => issued_at, + "exp" => issued_at + lifetime_seconds, + "jti" => SecureRandom.uuid, + } + + JWT.encode(claims, signing_key, algorithm, { "kid" => kid, "typ" => "JWT" }) + end + + private + + # Only the shop's canonical permanent domain is accepted, so that the signer and + # `ClientCredentials.client_credentials` agree on what a shop is. Case is normalized with ASCII + # folding only: Unicode folding maps characters such as U+212A KELVIN SIGN onto ASCII letters, which + # would turn one shop's name into another real shop's audience. + sig { params(shop: String).returns(String) } + def audience_for(shop) + host = shop.strip.tr("A-Z", "a-z") + unless PERMANENT_SHOP_DOMAIN.match?(host) + raise Errors::InvalidClientAssertionError, + "shop must be a permanent #{MYSHOPIFY_DOMAIN} domain in the form " \ + "{handle}.#{MYSHOPIFY_DOMAIN}, got: #{shop.inspect}" + end + + ClientCredentials.token_endpoint_url(host) + end + + sig { params(audience: String).returns(String) } + def validated_audience(audience) + validated_value(audience, "audience") + end + + # Trimmed rather than rejected: a value read from a file or pasted from a terminal often carries a + # newline, and the server matches `iss` and `kid` exactly, so an untrimmed value can only ever fail. + sig { params(value: String, name: String).returns(String) } + def validated_value(value, name) + trimmed = value.strip + raise Errors::InvalidClientAssertionError, "#{name} must be a non-empty String" if trimmed.empty? + + trimmed + end + + sig { params(kid: String).returns(String) } + def validated_kid(kid) + trimmed = validated_value(kid, "kid") + if trimmed.length > MAX_KID_LENGTH + raise Errors::InvalidClientAssertionError, + "kid must be at most #{MAX_KID_LENGTH} characters, got: #{trimmed.length}" + end + + trimmed + end + + sig { params(lifetime_seconds: Integer).void } + def validate_lifetime!(lifetime_seconds) + return if lifetime_seconds.positive? && lifetime_seconds <= MAX_LIFETIME_SECONDS + + raise Errors::InvalidClientAssertionError, + "lifetime_seconds must be between 1 and #{MAX_LIFETIME_SECONDS}, got: #{lifetime_seconds}" + end + + # Takes `Object` so that the checks below still run for an app that has turned sorbet-runtime's + # call validation off. + sig do + params(private_key: Object).returns([T.any(OpenSSL::PKey::RSA, OpenSSL::PKey::EC), String]) + end + def validated_key_with_algorithm(private_key) + case private_key + when OpenSSL::PKey::RSA + unless private_key.private? + raise Errors::InvalidClientAssertionError, "private_key must be an RSA private key, not a public key" + end + + if private_key.n.num_bits < MIN_RSA_KEY_BITS + raise Errors::InvalidClientAssertionError, + "RSA private_key must be at least #{MIN_RSA_KEY_BITS} bits, got: #{private_key.n.num_bits}" + end + + [private_key, RSA_ALGORITHM] + when OpenSSL::PKey::EC + unless private_key.private? + raise Errors::InvalidClientAssertionError, "private_key must be an EC private key, not a public key" + end + + unless SUPPORTED_EC_CURVES.include?(private_key.group.curve_name) + raise Errors::InvalidClientAssertionError, + "EC private_key must use the P-256 curve, got: #{private_key.group.curve_name}" + end + + [private_key, EC_ALGORITHM] + else + raise Errors::InvalidClientAssertionError, + "private_key must be an OpenSSL::PKey::RSA or OpenSSL::PKey::EC private key, " \ + "got: #{private_key.class}" + end + end + end + end + end +end diff --git a/lib/shopify_api/auth/client_credentials.rb b/lib/shopify_api/auth/client_credentials.rb index b1973d9aa..35dd83c71 100644 --- a/lib/shopify_api/auth/client_credentials.rb +++ b/lib/shopify_api/auth/client_credentials.rb @@ -7,16 +7,31 @@ module ClientCredentials extend T::Sig CLIENT_CREDENTIALS_GRANT_TYPE = "client_credentials" + CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" + TOKEN_ENDPOINT_BASE_PATH = "/admin/oauth" + TOKEN_ENDPOINT_PATH = "access_token" class << self extend T::Sig + # The URL this grant posts to. `ClientAssertion.create` derives the assertion's `aud` claim from + # here rather than spelling the URL out again: Shopify rejects an assertion whose `aud` is not the + # endpoint the request arrives at, and reports it as an indistinguishable `invalid_client`. + sig { params(shop: String).returns(String) } + def token_endpoint_url(shop) + "https://#{shop}#{TOKEN_ENDPOINT_BASE_PATH}/#{TOKEN_ENDPOINT_PATH}" + end + + # `client_assertion` is typed `T.untyped` so that a wrong type reaches the validation below: + # sorbet-runtime's TypeError message embeds the offending argument, and a JWT is short enough that + # the truncated message shows a usable part of a live credential. sig do params( shop: String, + client_assertion: T.untyped, ).returns(ShopifyAPI::Auth::Session) end - def client_credentials(shop:) + def client_credentials(shop:, client_assertion: nil) unless ShopifyAPI::Context.setup? raise ShopifyAPI::Errors::ContextNotSetupError, "ShopifyAPI::Context not setup, please call ShopifyAPI::Context.setup" @@ -24,20 +39,32 @@ def client_credentials(shop:) validated_shop = Utils::ShopValidator.sanitize!(shop) shop_session = ShopifyAPI::Auth::Session.new(shop: validated_shop) - body = { - client_id: ShopifyAPI::Context.api_key, - client_secret: ShopifyAPI::Context.api_secret_key, - grant_type: CLIENT_CREDENTIALS_GRANT_TYPE, - } + body = if client_assertion.nil? + { + client_id: ShopifyAPI::Context.api_key, + client_secret: ShopifyAPI::Context.api_secret_key, + grant_type: CLIENT_CREDENTIALS_GRANT_TYPE, + } + else + { + client_id: ShopifyAPI::Context.api_key, + grant_type: CLIENT_CREDENTIALS_GRANT_TYPE, + client_assertion_type: CLIENT_ASSERTION_TYPE, + client_assertion: validated_assertion(client_assertion), + } + end - client = Clients::HttpClient.new(session: shop_session, base_path: "/admin/oauth") + client = Clients::HttpClient.new(session: shop_session, base_path: TOKEN_ENDPOINT_BASE_PATH) response = client.request( Clients::HttpRequest.new( http_method: :post, - path: "access_token", + path: TOKEN_ENDPOINT_PATH, body: body, body_type: "application/json", + tries: 1, + follow_redirects: false, + suppress_inherited_http_auth: !client_assertion.nil?, ), ) response_hash = T.cast(response.body, T::Hash[String, T.untyped]).to_h @@ -47,6 +74,28 @@ def client_credentials(shop:) access_token_response: Oauth::AccessTokenResponse.from_hash(response_hash), ) end + + private + + sig { params(client_assertion: Object).returns(String) } + def validated_assertion(client_assertion) + unless client_assertion.is_a?(String) + raise ShopifyAPI::Errors::InvalidClientAssertionError, + "client_assertion must be a String, got: #{client_assertion.class}" + end + if client_assertion.strip.empty? + raise ShopifyAPI::Errors::InvalidClientAssertionError, "client_assertion must not be blank" + end + + # Rejected rather than trimmed: a JWT that arrived with whitespace around it means the caller's + # plumbing is wrong, and the server compares the assertion byte for byte. + unless client_assertion == client_assertion.strip + raise ShopifyAPI::Errors::InvalidClientAssertionError, + "client_assertion must not have leading or trailing whitespace" + end + + client_assertion + end end end end diff --git a/lib/shopify_api/clients/http_client.rb b/lib/shopify_api/clients/http_client.rb index 6aeff5050..fe8809c84 100644 --- a/lib/shopify_api/clients/http_client.rb +++ b/lib/shopify_api/clients/http_client.rb @@ -32,11 +32,16 @@ def initialize(base_path:, session: nil) end end - sig { params(request: HttpRequest, response_as_struct: T::Boolean).returns(HttpResponse) } + sig do + params( + request: HttpRequest, + response_as_struct: T::Boolean, + ).returns(HttpResponse) + end def request(request, response_as_struct: false) request.verify - headers = @headers + headers = @headers.dup headers["Content-Type"] = T.must(request.body_type) if request.body_type headers = headers.merge(T.must(request.extra_headers)) if request.extra_headers @@ -48,14 +53,30 @@ def request(request, response_as_struct: false) response = HttpResponse.new(code: 0, headers: {}, body: "") while tries < request.tries tries += 1 - res = T.cast(HTTParty.send( - request.http_method, - parsed_uri.to_s, + request_options = { headers: headers, query: request.query, body: request.body.class == Hash ? T.unsafe(request.body).to_json : request.body, + } + request_options[:follow_redirects] = request.follow_redirects unless request.follow_redirects.nil? + + if request.suppress_inherited_http_auth + verify_no_url_credentials!(parsed_uri) + request_options.merge!(basic_auth: nil, digest_auth: nil) + end + + res = T.cast(HTTParty.send( + request.http_method, + parsed_uri.to_s, + **request_options, ), HTTParty::Response) + if request.follow_redirects == false && res.code.to_i.between?(300, 399) + blocked_response = HttpResponse.new(code: res.code.to_i, headers: res.headers.to_h, body: res.body.to_s) + raise ShopifyAPI::Errors::HttpResponseError.new(response: blocked_response), + blocked_redirect_message(res) + end + begin body = res.body.nil? || res.body.empty? ? {} : JSON.parse(res.body) rescue JSON::ParserError @@ -111,9 +132,14 @@ def request_url(request) sig { params(response: HttpResponse).returns(String) } def serialized_error(response) body = {} - body["errors"] = response.body["errors"] if response.body["errors"] - body["error"] = response.body["error"] if response.body["error"] - body["error_description"] = response.body["error_description"] if response.body["error"] + # Only a parsed JSON object has error members. On an unparsed body `response.body["errors"]` is + # `String#[]`, so an HTML page containing the word "errors" would report `{"errors":"errors"}`. + if response.body.is_a?(Hash) + error_body = T.cast(response.body, T::Hash[String, T.untyped]) + body["errors"] = error_body["errors"] if error_body["errors"] + body["error"] = error_body["error"] if error_body["error"] + body["error_description"] = error_body["error_description"] if error_body["error_description"] + end if response.headers["x-request-id"] id = T.must(response.headers["x-request-id"])[0] @@ -124,6 +150,30 @@ def serialized_error(response) private + # A redirect on a credential-bearing request is the one error here a developer cannot diagnose from + # the status alone, so it says what happened, what was not sent, and what to check. + sig { params(res: HTTParty::Response).returns(String) } + def blocked_redirect_message(res) + location = res.headers["location"] + target = location.nil? || location.empty? ? "an unnamed location" : location + + "Refused to follow the #{res.code} redirect to #{target}, because this request was sent with " \ + "redirects disabled: following it would forward the request body, and any credentials in it, to " \ + "the redirect target. Nothing was sent there. Check any proxy or ShopifyAPI::Context.api_host " \ + "configuration in front of the endpoint, and retry with a newly created client assertion if you " \ + "are using one." + end + + # HTTParty's `set_basic_auth_from_uri` rebuilds `basic_auth` from the URL after an explicit `nil` + # override, so suppressing inherited authentication is not enough on its own. + sig { params(parsed_uri: URI::Generic).void } + def verify_no_url_credentials!(parsed_uri) + return unless parsed_uri.userinfo + + raise ShopifyAPI::Errors::InvalidHttpRequestError, + "Cannot send a request with HTTP authentication disabled to a URL containing credentials." + end + sig do params( headers: T::Hash[T.any(Symbol, String), T.untyped], diff --git a/lib/shopify_api/clients/http_request.rb b/lib/shopify_api/clients/http_request.rb index 17a293c18..4b4ba47a4 100644 --- a/lib/shopify_api/clients/http_request.rb +++ b/lib/shopify_api/clients/http_request.rb @@ -13,6 +13,12 @@ class HttpRequest < T::Struct prop :query, T.nilable(T::Hash[T.any(Symbol, String), T.untyped]) prop :extra_headers, T.nilable(T::Hash[T.any(Symbol, String), T.untyped]) prop :tries, Integer, default: 1 + # Unset leaves redirect handling to HTTParty, including any policy the app set in default_options. + prop :follow_redirects, T.nilable(T::Boolean) + # Sends this one request with HTTParty's inherited Basic and digest authentication turned off. Digest + # auth matters most: HTTParty replays the whole request on a 401 challenge, which would replay a + # single-use credential such as a client assertion. + prop :suppress_inherited_http_auth, T::Boolean, default: false sig { void } def verify diff --git a/lib/shopify_api/errors/invalid_client_assertion_error.rb b/lib/shopify_api/errors/invalid_client_assertion_error.rb new file mode 100644 index 000000000..166a9c2e4 --- /dev/null +++ b/lib/shopify_api/errors/invalid_client_assertion_error.rb @@ -0,0 +1,9 @@ +# typed: strict +# frozen_string_literal: true + +module ShopifyAPI + module Errors + class InvalidClientAssertionError < StandardError + end + end +end diff --git a/test/auth/client_assertion_test.rb b/test/auth/client_assertion_test.rb new file mode 100644 index 000000000..7c9c3217d --- /dev/null +++ b/test/auth/client_assertion_test.rb @@ -0,0 +1,349 @@ +# typed: false +# frozen_string_literal: true + +require_relative "../test_helper" + +module ShopifyAPITest + module Auth + class ClientAssertionTest < Test::Unit::TestCase + # Generated once per process: key generation is slow, and every assertion here is verified against the + # matching public key, so which key is generated does not change any expected value. + RSA_PRIVATE_KEY = OpenSSL::PKey::RSA.generate(2048) + EC_PRIVATE_KEY = OpenSSL::PKey::EC.generate("prime256v1") + FIXED_TIME = Time.at(1_760_000_000) + + def setup + super() + + @shop = "test-shop.myshopify.com" + @client_id = "test-client-id" + @kid = "test-key-2026-10" + @audience = "https://test-shop.myshopify.com/admin/oauth/access_token" + end + + def test_create_with_rsa_key_returns_assertion_verifiable_by_the_matching_public_key + assertion = create_assertion(private_key: RSA_PRIVATE_KEY) + + claims, header = JWT.decode(assertion, RSA_PRIVATE_KEY.public_key, true, algorithm: "RS256") + + assert_equal("RS256", header["alg"]) + assert_equal(@kid, header["kid"]) + assert_equal("JWT", header["typ"]) + assert_equal(@client_id, claims["iss"]) + assert_equal(@client_id, claims["sub"]) + assert_equal(@audience, claims["aud"]) + end + + def test_create_with_ec_p256_key_returns_assertion_verifiable_by_the_matching_public_key + assertion = create_assertion(private_key: EC_PRIVATE_KEY) + + claims, header = JWT.decode(assertion, ec_public_key, true, algorithm: "ES256") + + assert_equal("ES256", header["alg"]) + assert_equal(@kid, header["kid"]) + assert_equal(@client_id, claims["iss"]) + assert_equal(@audience, claims["aud"]) + end + + # The server requires exactly these claims and reads only these header members. Anything extra is at + # best ignored and at worst rejected, so the set is pinned rather than spot-checked. + def test_create_sets_exactly_the_expected_header_members_and_claims + claims, header = JWT.decode(create_assertion(private_key: EC_PRIVATE_KEY), nil, false) + + assert_equal(["alg", "kid", "typ"], header.keys.sort) + assert_equal(["aud", "exp", "iat", "iss", "jti", "sub"], claims.keys.sort) + end + + def test_create_signature_fails_verification_against_an_unrelated_public_key + assertion = create_assertion(private_key: RSA_PRIVATE_KEY) + + assert_raises(JWT::VerificationError) do + JWT.decode(assertion, OpenSSL::PKey::RSA.generate(2048).public_key, true, algorithm: "RS256") + end + end + + def test_create_sets_integer_iat_and_exp_sixty_seconds_apart_by_default + Time.stubs(:now).returns(FIXED_TIME) + + claims = decode_unverified(create_assertion(private_key: RSA_PRIVATE_KEY)) + + assert_instance_of(Integer, claims["iat"]) + assert_instance_of(Integer, claims["exp"]) + assert_equal(FIXED_TIME.to_i, claims["iat"]) + assert_equal(FIXED_TIME.to_i + 60, claims["exp"]) + end + + def test_create_sets_exp_from_the_supplied_lifetime_seconds + Time.stubs(:now).returns(FIXED_TIME) + + claims = decode_unverified(create_assertion(private_key: RSA_PRIVATE_KEY, lifetime_seconds: 300)) + + assert_equal(FIXED_TIME.to_i + 300, claims["exp"]) + end + + def test_create_returns_a_different_jti_on_every_call_with_identical_arguments + Time.stubs(:now).returns(FIXED_TIME) + + first = decode_unverified(create_assertion(private_key: RSA_PRIVATE_KEY)) + second = decode_unverified(create_assertion(private_key: RSA_PRIVATE_KEY)) + + refute_equal(first["jti"], second["jti"]) + assert_match(/\A[0-9a-f-]{36}\z/, first["jti"]) + end + + # The canonical domain is the only form `ClientCredentials.client_credentials` accepts for every shop, + # so it is the only form the signer accepts. + def test_create_rejects_shop_handles_full_urls_and_unified_admin_urls + ["test-shop", "https://test-shop.myshopify.com", "https://admin.shopify.com/store/test-shop"].each do |shop| + error = assert_raises(ShopifyAPI::Errors::InvalidClientAssertionError) do + create_assertion(shop: shop, private_key: RSA_PRIVATE_KEY) + end + + assert_match(/permanent myshopify.com domain in the form/, error.message) + end + end + + def test_create_normalizes_shop_case_and_surrounding_whitespace + ["TEST-SHOP.MyShopify.com", " test-shop.myshopify.com\n"].each do |shop| + claims = decode_unverified(create_assertion(shop: shop, private_key: RSA_PRIVATE_KEY)) + + assert_equal(@audience, claims["aud"]) + end + end + + # U+212A KELVIN SIGN folds to "k" under Unicode case mapping, which would name a different real shop. + def test_create_rejects_a_shop_whose_name_only_becomes_canonical_under_unicode_case_folding + assert_raises(ShopifyAPI::Errors::InvalidClientAssertionError) do + create_assertion(shop: "test-sho\u212A.myshopify.com", private_key: RSA_PRIVATE_KEY) + end + end + + def test_create_uses_an_explicit_audience_override_verbatim + claims = decode_unverified( + create_assertion( + shop: @shop, + private_key: RSA_PRIVATE_KEY, + audience: " https://test-shop.shopify.io/admin/oauth/access_token\n", + ), + ) + + assert_equal("https://test-shop.shopify.io/admin/oauth/access_token", claims["aud"]) + end + + def test_create_rejects_a_blank_audience_override + error = assert_raises(ShopifyAPI::Errors::InvalidClientAssertionError) do + create_assertion(shop: @shop, private_key: RSA_PRIVATE_KEY, audience: " ") + end + + assert_match(/audience must be a non-empty String/, error.message) + end + + # Underscore handles exist, and both ShopValidator::HOSTNAME_REGEX and the token endpoint accept them. + def test_create_accepts_an_underscore_in_the_shop_handle + claims = decode_unverified(create_assertion(shop: "my_shop.myshopify.com", private_key: RSA_PRIVATE_KEY)) + + assert_equal("https://my_shop.myshopify.com/admin/oauth/access_token", claims["aud"]) + end + + def test_create_rejects_a_shop_on_a_trusted_but_non_permanent_domain + error = assert_raises(ShopifyAPI::Errors::InvalidClientAssertionError) do + create_assertion(shop: "test-shop.myshopify.io", private_key: RSA_PRIVATE_KEY) + end + + assert_match(/permanent myshopify.com domain/, error.message) + end + + def test_create_rejects_an_untrusted_shop_domain + assert_raises(ShopifyAPI::Errors::InvalidClientAssertionError) do + create_assertion(shop: "attacker.example", private_key: RSA_PRIVATE_KEY) + end + end + + def test_create_defaults_client_id_to_the_configured_api_key + claims = decode_unverified( + ShopifyAPI::Auth::ClientAssertion.create(shop: @shop, kid: @kid, private_key: RSA_PRIVATE_KEY), + ) + + assert_equal(ShopifyAPI::Context.api_key, claims["iss"]) + assert_equal(ShopifyAPI::Context.api_key, claims["sub"]) + end + + def test_create_prefers_an_explicit_client_id_over_the_configured_api_key + claims = decode_unverified(create_assertion(private_key: RSA_PRIVATE_KEY)) + + refute_equal(ShopifyAPI::Context.api_key, @client_id) + assert_equal(@client_id, claims["iss"]) + end + + def test_create_rejects_an_omitted_client_id_when_no_api_key_is_configured + modify_context(api_key: "") + + error = assert_raises(ShopifyAPI::Errors::InvalidClientAssertionError) do + ShopifyAPI::Auth::ClientAssertion.create(shop: @shop, kid: @kid, private_key: RSA_PRIVATE_KEY) + end + + assert_match(/client_id must be a non-empty String/, error.message) + end + + def test_create_rejects_a_blank_client_id + ["", " "].each do |client_id| + error = assert_raises(ShopifyAPI::Errors::InvalidClientAssertionError) do + create_assertion(client_id: client_id, private_key: RSA_PRIVATE_KEY) + end + + assert_match(/client_id must be a non-empty String/, error.message) + end + end + + def test_create_rejects_a_blank_kid + error = assert_raises(ShopifyAPI::Errors::InvalidClientAssertionError) do + create_assertion(kid: " ", private_key: RSA_PRIVATE_KEY) + end + + assert_match(/kid must be a non-empty String/, error.message) + end + + # Both are matched exactly by the server, so an untrimmed value can only ever fail there. + def test_create_trims_surrounding_whitespace_from_client_id_and_kid + assertion = create_assertion( + client_id: " #{@client_id}\n", + kid: " #{@kid} \n", + private_key: RSA_PRIVATE_KEY, + ) + + claims, header = JWT.decode(assertion, nil, false) + + assert_equal(@client_id, claims["iss"]) + assert_equal(@client_id, claims["sub"]) + assert_equal(@kid, header["kid"]) + end + + def test_create_rejects_a_kid_longer_than_the_registrable_maximum + error = assert_raises(ShopifyAPI::Errors::InvalidClientAssertionError) do + create_assertion(kid: "k" * 256, private_key: RSA_PRIVATE_KEY) + end + + assert_match(/kid must be at most 255 characters/, error.message) + end + + def test_create_accepts_a_kid_of_the_registrable_maximum_length + kid = "k" * 255 + + _claims, header = JWT.decode(create_assertion(kid: kid, private_key: RSA_PRIVATE_KEY), nil, false) + + assert_equal(kid, header["kid"]) + end + + def test_create_rejects_lifetime_seconds_outside_one_to_three_hundred_without_clamping + [0, -1, 301, 3600].each do |lifetime_seconds| + error = assert_raises(ShopifyAPI::Errors::InvalidClientAssertionError) do + create_assertion(private_key: RSA_PRIVATE_KEY, lifetime_seconds: lifetime_seconds) + end + + assert_match(/lifetime_seconds must be between 1 and 300/, error.message) + end + end + + def test_create_accepts_the_boundary_lifetimes_of_one_and_three_hundred_seconds + Time.stubs(:now).returns(FIXED_TIME) + + [1, 300].each do |lifetime_seconds| + claims = decode_unverified(create_assertion(private_key: RSA_PRIVATE_KEY, lifetime_seconds:)) + + assert_equal(FIXED_TIME.to_i + lifetime_seconds, claims["exp"]) + end + end + + def test_create_rejects_a_non_integer_lifetime_seconds + assert_raises(TypeError) do + create_assertion(private_key: RSA_PRIVATE_KEY, lifetime_seconds: "60") + end + end + + def test_create_rejects_an_rsa_key_below_two_thousand_forty_eight_bits + error = assert_raises(ShopifyAPI::Errors::InvalidClientAssertionError) do + create_assertion(private_key: OpenSSL::PKey::RSA.generate(1024)) + end + + assert_match(/at least 2048 bits/, error.message) + end + + def test_create_rejects_an_ec_key_on_a_curve_other_than_p256 + error = assert_raises(ShopifyAPI::Errors::InvalidClientAssertionError) do + create_assertion(private_key: OpenSSL::PKey::EC.generate("secp384r1")) + end + + assert_match(/must use the P-256 curve/, error.message) + end + + def test_create_rejects_an_rsa_public_key + error = assert_raises(ShopifyAPI::Errors::InvalidClientAssertionError) do + create_assertion(private_key: OpenSSL::PKey::RSA.new(RSA_PRIVATE_KEY.public_to_pem)) + end + + assert_match(/must be an RSA private key, not a public key/, error.message) + end + + def test_create_rejects_an_ec_public_key + error = assert_raises(ShopifyAPI::Errors::InvalidClientAssertionError) do + create_assertion(private_key: ec_public_key) + end + + assert_match(/must be an EC private key, not a public key/, error.message) + end + + def test_create_rejects_an_unsupported_key_type + [RSA_PRIVATE_KEY.to_pem, { pem: "key" }, :key].each do |private_key| + assert_raises(TypeError) { create_assertion(private_key:) } + end + end + + # sorbet-runtime truncates the offending value to its first and last few characters, which for a PEM + # are the BEGIN and END lines. + def test_create_rejects_a_pem_string_without_echoing_the_key_body + pem = RSA_PRIVATE_KEY.to_pem + key_body = T.must(pem.lines[1..-2]).join.delete("\n") + + error = assert_raises(TypeError) { create_assertion(private_key: pem) } + + refute_includes(error.message, key_body) + end + + # Reachable only for an app that has turned sorbet-runtime's call validation off, which is why the + # runtime check is still there. + def test_validated_key_rejects_an_unsupported_key_type_without_echoing_the_supplied_value + error = assert_raises(ShopifyAPI::Errors::InvalidClientAssertionError) do + ShopifyAPI::Auth::ClientAssertion.send(:validated_key_with_algorithm, { pem: "SUPER-SECRET-KEY" }) + end + + assert_equal( + "private_key must be an OpenSSL::PKey::RSA or OpenSSL::PKey::EC private key, got: Hash", + error.message, + ) + refute_includes(error.message, "SECRET") + end + + def test_create_signs_without_a_configured_api_secret_key + modify_context(api_key: "", api_secret_key: "") + + claims = decode_unverified(create_assertion(private_key: RSA_PRIVATE_KEY)) + + assert_equal(@client_id, claims["iss"]) + end + + private + + def create_assertion(shop: @shop, client_id: @client_id, kid: @kid, private_key:, **options) + ShopifyAPI::Auth::ClientAssertion.create(shop:, client_id:, kid:, private_key:, **options) + end + + def decode_unverified(assertion) + JWT.decode(assertion, nil, false)[0] + end + + def ec_public_key + OpenSSL::PKey::EC.new(EC_PRIVATE_KEY.public_to_pem) + end + end + end +end diff --git a/test/auth/client_credentials_test.rb b/test/auth/client_credentials_test.rb index b5c6995d8..c8fd42a3f 100644 --- a/test/auth/client_credentials_test.rb +++ b/test/auth/client_credentials_test.rb @@ -6,6 +6,9 @@ module ShopifyAPITest module Auth class ClientCredentialsTest < Test::Unit::TestCase + # Generated once per process: key generation is slow and no expected value depends on which key it is. + EC_PRIVATE_KEY = OpenSSL::PKey::EC.generate("prime256v1") + def setup super() @@ -20,6 +23,14 @@ def setup scope: "scope1,scope2", expires_in: 1000, } + @assertion = "header.payload.signature" + @client_assertion_request = { + client_id: ShopifyAPI::Context.api_key, + grant_type: "client_credentials", + client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", + client_assertion: @assertion, + } + @token_url = "https://#{@shop}/admin/oauth/access_token" end def test_client_credentials_context_not_setup @@ -53,6 +64,337 @@ def test_client_credentials_offline_token assert_equal(expected_session, session) end + + def test_client_credentials_with_nil_assertion_sends_the_existing_client_secret_body + stub_token_request(body: @client_credentials_request) + + ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop, client_assertion: nil) + + assert_requested(:post, @token_url, times: 1) + end + + def test_client_credentials_with_assertion_sends_only_the_four_assertion_fields + captured_request = capture_token_request + + ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop, client_assertion: @assertion) + + assert_equal( + { + "client_id" => ShopifyAPI::Context.api_key, + "grant_type" => "client_credentials", + "client_assertion_type" => "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", + "client_assertion" => @assertion, + }, + JSON.parse(captured_request.last.body), + ) + end + + # Deliberately literal-free on both sides: the audience comes out of the signed assertion and the stub + # is built from it, so a divergence between the signer's `aud` and the posted URL fails here. + def test_client_credentials_posts_to_the_url_the_signed_assertion_names_as_its_audience + assertion = ShopifyAPI::Auth::ClientAssertion.create( + shop: @shop, + client_id: ShopifyAPI::Context.api_key, + kid: "test-key-2026-10", + private_key: EC_PRIVATE_KEY, + ) + audience = JWT.decode(assertion, nil, false).first["aud"] + stub_request(:post, audience) + .to_return(body: @offline_token_response.to_json, headers: { content_type: "application/json" }) + + session = ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop, client_assertion: assertion) + + assert_requested(:post, audience, times: 1) + assert_equal(@offline_token_response[:access_token], session.access_token) + end + + def test_client_credentials_with_assertion_sends_no_credential_headers + captured_request = capture_token_request + + ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop, client_assertion: @assertion) + + header_names = captured_request.last.headers.keys.map(&:downcase) + + refute_includes(header_names, "x-shopify-access-token") + refute_includes(header_names, "authorization") + end + + # The exact-body assertion above covers the body alone; this covers the whole serialized request, so a + # later change to the body shape cannot quietly reintroduce the secret somewhere else. + def test_client_credentials_with_assertion_sends_the_configured_secret_nowhere + sentinel = "SENTINEL-SECRET-DO-NOT-SEND" + modify_context(api_secret_key: sentinel) + assertion = ShopifyAPI::Auth::ClientAssertion.create( + shop: @shop, + kid: "test-key-2026-10", + private_key: EC_PRIVATE_KEY, + ) + captured_request = capture_token_request + + ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop, client_assertion: assertion) + + request = captured_request.fetch(0) + claims, header = JWT.decode(assertion, nil, false) + + refute_includes(assertion, sentinel) + refute_includes(claims.to_json, sentinel) + refute_includes(header.to_json, sentinel) + refute_includes(request.body.to_s, sentinel) + refute_includes(request.headers.to_s, sentinel) + refute_includes(request.uri.to_s, sentinel) + end + + def test_client_credentials_with_assertion_returns_a_session_with_scopes_and_expiry + stub_token_request( + body: @client_assertion_request, + response: @offline_token_response.merge(expires_in: 3600), + ) + + session = ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop, client_assertion: @assertion) + + assert_equal("offline_#{@shop}", session.id) + assert_equal(@offline_token_response[:access_token], session.access_token) + assert_equal("scope1,scope2", session.scope.to_s) + assert_nil(session.refresh_token) + assert_in_delta(Time.now.to_i + 3600, session.expires.to_i, 5) + end + + def test_client_credentials_with_assertion_uses_the_response_expiry_for_a_custom_app_lifetime + stub_token_request( + body: @client_assertion_request, + response: @offline_token_response.merge(expires_in: 86_400), + ) + + session = ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop, client_assertion: @assertion) + + assert_in_delta(Time.now.to_i + 86_400, session.expires.to_i, 5) + end + + def test_client_credentials_rejects_a_blank_assertion_without_falling_back_to_the_secret + ["", " "].each do |client_assertion| + assert_raises(ShopifyAPI::Errors::InvalidClientAssertionError) do + ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop, client_assertion:) + end + end + + assert_not_requested(:post, @token_url) + end + + # A value read from a file or pasted from a terminal arrives with a newline, and the server compares + # the assertion byte for byte, so sending it would fail with an opaque `invalid_client`. + def test_client_credentials_rejects_an_assertion_with_surrounding_whitespace + [" #{@assertion}", "#{@assertion}\n"].each do |client_assertion| + error = assert_raises(ShopifyAPI::Errors::InvalidClientAssertionError) do + ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop, client_assertion:) + end + + assert_match(/must not have leading or trailing whitespace/, error.message) + end + + assert_not_requested(:post, @token_url) + end + + def test_client_credentials_rejects_a_non_string_assertion_without_echoing_the_supplied_value + error = assert_raises(ShopifyAPI::Errors::InvalidClientAssertionError) do + ShopifyAPI::Auth::ClientCredentials.client_credentials( + shop: @shop, + client_assertion: { assertion: "SUPER-SECRET-ASSERTION" }, + ) + end + + assert_equal("client_assertion must be a String, got: Hash", error.message) + refute_includes(error.message, "SECRET") + assert_not_requested(:post, @token_url) + end + + def test_client_credentials_with_assertion_makes_one_attempt_on_server_error_statuses + [429, 500, 503].each do |status| + WebMock.reset! + stub_request(:post, @token_url).to_return(status: status, body: "{}") + + assert_raises(ShopifyAPI::Errors::HttpResponseError) do + ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop, client_assertion: @assertion) + end + + assert_requested(:post, @token_url, times: 1) + end + end + + def test_client_credentials_with_assertion_makes_one_attempt_when_the_connection_times_out + stub_request(:post, @token_url).to_timeout + + assert_raises(Net::OpenTimeout) do + ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop, client_assertion: @assertion) + end + + assert_requested(:post, @token_url, times: 1) + end + + def test_client_credentials_with_assertion_raises_without_retrying_on_an_invalid_client_response + stub_request(:post, @token_url) + .to_return(status: 401, body: { error: "invalid_client" }.to_json) + + error = assert_raises(ShopifyAPI::Errors::HttpResponseError) do + ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop, client_assertion: @assertion) + end + + assert_equal(401, error.code) + assert_requested(:post, @token_url, times: 1) + end + + def test_client_credentials_rejects_redirects_with_either_authentication_method + [nil, @assertion].each do |assertion| + [301, 302, 303, 307, 308].each do |status| + ["", "redirect", @offline_token_response.to_json].each do |body| + WebMock.reset! + redirect_url = "https://other-shop.myshopify.com/admin/oauth/access_token" + expected_body = assertion.nil? ? @client_credentials_request : @client_assertion_request + stub_request(:post, @token_url).with(body: expected_body) + .to_return(status: status, headers: { "Location" => redirect_url }, body: body) + stub_request(:post, redirect_url).to_return(body: @offline_token_response.to_json) + stub_request(:get, redirect_url).to_return(body: @offline_token_response.to_json) + + error = assert_raises(ShopifyAPI::Errors::HttpResponseError) do + ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop, client_assertion: assertion) + end + + assert_equal(status, error.code) + assert_match(/Refused to follow the #{status} redirect to #{Regexp.escape(redirect_url)}/, error.message) + assert_requested(:post, @token_url, times: 1) + assert_not_requested(:post, redirect_url) + assert_not_requested(:get, redirect_url) + end + end + end + end + + def test_client_credentials_overrides_enabled_redirect_defaults_without_changing_them + inherited_options = HTTParty::Basement.default_options.merge(follow_redirects: true) + HTTParty::Basement.stubs(:default_options).returns(inherited_options) + redirect_url = "https://#{@shop}/admin/oauth/access_token_redirected" + stub_request(:post, @token_url).with(body: @client_credentials_request) + .to_return(status: 302, headers: { "Location" => redirect_url }, body: "") + stub_request(:get, redirect_url).to_return(body: @offline_token_response.to_json) + + assert_raises(ShopifyAPI::Errors::HttpResponseError) do + ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop) + end + + assert_requested(:post, @token_url, times: 1) + assert_not_requested(:get, redirect_url) + assert_equal(true, inherited_options[:follow_redirects]) + end + + def test_client_credentials_with_assertion_disables_inherited_basic_auth_and_keeps_other_headers + inherited_options = HTTParty::Basement.default_options.merge( + basic_auth: { username: "inherited-user", password: "inherited-password" }, + headers: { "X-Global" => "1" }, + ) + HTTParty::Basement.stubs(:default_options).returns(inherited_options) + captured_request = capture_token_request + + ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop, client_assertion: @assertion) + + header_names = captured_request.last.headers.keys.map(&:downcase) + + refute_includes(header_names, "authorization") + refute_includes(header_names, "x-shopify-access-token") + assert_equal("1", captured_request.last.headers["X-Global"]) + end + + def test_client_credentials_with_assertion_disables_digest_auth_without_a_challenge_retry + inherited_options = HTTParty::Basement.default_options.merge( + digest_auth: { username: "inherited-user", password: "inherited-password" }, + ) + HTTParty::Basement.stubs(:default_options).returns(inherited_options) + stub_request(:post, @token_url).to_return( + status: 401, + body: { error: "invalid_client" }.to_json, + headers: { "WWW-Authenticate" => 'Digest realm="shop", nonce="nonce", qop="auth"' }, + ) + + assert_raises(ShopifyAPI::Errors::HttpResponseError) do + ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop, client_assertion: @assertion) + end + + assert_requested(:post, @token_url, times: 1) + assert_equal("inherited-user", inherited_options.dig(:digest_auth, :username)) + end + + def test_client_credentials_without_assertion_still_inherits_httparty_credentials + stub_inherited_httparty_credentials + captured_request = capture_token_request + + ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop) + + header_names = captured_request.last.headers.keys.map(&:downcase) + + assert_includes(header_names, "authorization") + assert_includes(header_names, "x-global") + end + + def test_client_credentials_with_assertion_fails_before_io_when_api_host_carries_credentials + modify_context(api_host: "user:password@internal.example.com") + + error = assert_raises(ShopifyAPI::Errors::InvalidHttpRequestError) do + ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop, client_assertion: @assertion) + end + + assert_match(/URL containing credentials/, error.message) + assert_not_requested(:post, @token_url) + end + + def test_client_credentials_without_assertion_honours_an_inherited_disabled_redirect_policy + inherited_options = HTTParty::Basement.default_options.merge(follow_redirects: false) + HTTParty::Basement.stubs(:default_options).returns(inherited_options) + redirect_url = "https://#{@shop}/admin/oauth/access_token_redirected" + stub_request(:post, @token_url).to_return(status: 302, headers: { "Location" => redirect_url }, body: "") + stub_request(:get, redirect_url) + .to_return(body: @offline_token_response.to_json, headers: { content_type: "application/json" }) + + assert_raises(ShopifyAPI::Errors::HttpResponseError) do + ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop) + end + + assert_not_requested(:get, redirect_url) + end + + def test_client_credentials_with_assertion_does_not_log_the_assertion + log_output = StringIO.new + modify_context(logger: ::Logger.new(log_output)) + stub_request(:post, @token_url).to_return(status: 401, body: { error: "invalid_client" }.to_json) + + error = assert_raises(ShopifyAPI::Errors::HttpResponseError) do + ShopifyAPI::Auth::ClientCredentials.client_credentials(shop: @shop, client_assertion: @assertion) + end + + refute_includes(log_output.string, @assertion) + refute_includes(error.message, @assertion) + end + + private + + def stub_token_request(body:, response: @offline_token_response) + stub_request(:post, @token_url) + .with(body: body) + .to_return(body: response.to_json, headers: { content_type: "application/json" }) + end + + def capture_token_request + captured_request = [] + stub_request(:post, @token_url) + .with { |request| captured_request << request } + .to_return(body: @offline_token_response.to_json, headers: { content_type: "application/json" }) + captured_request + end + + def stub_inherited_httparty_credentials + inherited_options = HTTParty::Basement.default_options.merge( + basic_auth: { username: "inherited-user", password: "inherited-password" }, + headers: { "Authorization" => "Bearer INHERITED", "X-Global" => "1" }, + ) + HTTParty::Basement.stubs(:default_options).returns(inherited_options) + end end end end diff --git a/test/clients/http_client_test.rb b/test/clients/http_client_test.rb index 3f2282d2b..b49714cf0 100644 --- a/test/clients/http_client_test.rb +++ b/test/clients/http_client_test.rb @@ -196,6 +196,17 @@ def test_error_message_with_oauth_error_and_description assert(parsed_error["error_reference"]) end + # `invalid_client` is returned with no description at all, and the key read used to be `error`. + def test_error_message_omits_a_description_the_response_did_not_send + stub_request(@request.http_method, "https://#{@shop}#{@base_path}/#{@request.path}") + .with(body: @request.body.to_json, query: @request.query, headers: @expected_headers) + .to_return(body: { "error": "invalid_client" }.to_json, status: 401) + + error = assert_raises(ShopifyAPI::Errors::HttpResponseError) { @client.request(@request) } + + assert_equal({ "error" => "invalid_client" }, JSON.parse(error.message)) + end + def test_non_retriable_error_code stub_request(@request.http_method, "https://#{@shop}#{@base_path}/#{@request.path}") .with(body: @request.body.to_json, query: @request.query, headers: @expected_headers) @@ -300,6 +311,68 @@ def test_json_parser_error assert_equal(502, error.code) end + def test_requests_without_a_redirect_override_still_follow_redirects + redirect_url = "https://#{@shop}#{@base_path}/redirected" + stub_request(:post, "https://#{@shop}#{@base_path}/#{@request.path}") + .with(query: @request.query) + .to_return(status: 302, headers: { "Location" => redirect_url }, body: "") + stub_request(:get, redirect_url).to_return(body: @success_body.to_json, headers: @response_headers) + + verify_http_request + + assert_requested(:get, redirect_url, times: 1) + end + + def test_a_requests_body_type_does_not_leak_into_the_next_request + apply_simple_http_stub + verify_http_request + captured_requests = [] + stub_request(:get, "https://#{@shop}#{@base_path}/#{@request.path}") + .with { |request| captured_requests << request } + .to_return(body: @success_body.to_json, headers: @response_headers) + + @client.request(ShopifyAPI::Clients::HttpRequest.new(http_method: :get, path: @request.path)) + + refute_includes(captured_requests.fetch(0).headers.keys.map(&:downcase), "content-type") + end + + def test_blocked_redirect_raises_an_error_naming_the_target_and_what_was_not_sent + @request.follow_redirects = false + redirect_url = "https://#{@shop}#{@base_path}/redirected" + stub_request(:post, "https://#{@shop}#{@base_path}/#{@request.path}") + .with(query: @request.query) + .to_return(status: 307, headers: { "Location" => redirect_url }, body: "moved") + + error = assert_raises(ShopifyAPI::Errors::HttpResponseError) { @client.request(@request) } + + assert_equal(307, error.code) + assert_includes(error.message, "307") + assert_includes(error.message, redirect_url) + assert_includes(error.message, "Nothing was sent there") + end + + # `response.body["errors"]` is `String#[]` on an unparsed body, so "errors" in an HTML page used to + # come back as `{"errors":"errors"}`. + def test_unparsable_error_body_does_not_report_invented_error_members + stub_request(:post, "https://#{@shop}#{@base_path}/#{@request.path}") + .with(query: @request.query) + .to_return(status: 500, body: "errors happened") + + error = assert_raises(ShopifyAPI::Errors::HttpResponseError) { @client.request(@request) } + + assert_equal(500, error.code) + refute_includes(error.message, "errors") + end + + def test_disabling_redirects_does_not_change_nonredirect_json_parser_errors + @request.follow_redirects = false + stub_request(:post, "https://#{@shop}#{@base_path}/#{@request.path}") + .with(query: @request.query) + .to_return(body: "Bad Request", status: 400) + + assert_raises(JSON::ParserError) { @client.request(@request) } + end + def test_response_as_struct stub_request(@request.http_method, "https://#{@shop}#{@base_path}/#{@request.path}") .with(body: @request.body.to_json, query: @request.query, headers: @expected_headers) @@ -310,6 +383,44 @@ def test_response_as_struct assert_equal("nested_value", response.body.key.nested_key) end + def test_suppressed_inherited_http_auth_rejects_a_url_carrying_credentials + modify_context(api_host: "user:password@internal.example.com") + + error = assert_raises(ShopifyAPI::Errors::InvalidHttpRequestError) do + token_less_client.request(suppressed_auth_request) + end + + assert_match(/URL containing credentials/, error.message) + end + + def test_suppressed_inherited_http_auth_preserves_connection_settings_and_noncredential_headers + captured_options = [] + connection_options = { timeout: 17, ssl_ca_file: "/custom/ca.pem", http_proxyaddr: "proxy.example", http_proxyport: 8080 } + inherited_options = HTTParty::Basement.default_options.merge(connection_options).merge( + basic_auth: { username: "inherited-user", password: "inherited-password" }, + headers: { "X-Global" => "preserved" }, + connection_adapter: lambda { |uri, options| + captured_options << options + HTTParty::ConnectionAdapter.call(uri, options) + }, + ) + HTTParty::Basement.stubs(:default_options).returns(inherited_options) + captured_requests = [] + stub_request(:post, authentication_request_url) + .with { |request| captured_requests << request } + .to_return(body: @success_body.to_json, headers: @response_headers) + + response = token_less_client.request(suppressed_auth_request) + + assert(response.ok?) + assert_equal(1, captured_options.size) + assert_equal(connection_options, captured_options.fetch(0).slice(*connection_options.keys)) + assert_nil(captured_options.fetch(0)[:basic_auth]) + assert_equal("preserved", captured_requests.fetch(0).headers["X-Global"]) + refute_includes(captured_requests.fetch(0).headers.keys.map(&:downcase), "authorization") + assert_equal("inherited-user", inherited_options.dig(:basic_auth, :username)) + end + private def simple_http_test(http_method) @@ -318,6 +429,27 @@ def simple_http_test(http_method) verify_http_request end + def token_less_client + ShopifyAPI::Clients::HttpClient.new( + session: ShopifyAPI::Auth::Session.new(shop: @shop), + base_path: @base_path, + ) + end + + def suppressed_auth_request + ShopifyAPI::Clients::HttpRequest.new( + http_method: :post, + path: "some-path", + body: { foo: "bar" }, + body_type: "application/json", + suppress_inherited_http_auth: true, + ) + end + + def authentication_request_url + "https://#{@shop}#{@base_path}/some-path" + end + def apply_simple_http_stub stub_request(@request.http_method, "https://#{@shop}#{@base_path}/#{@request.path}") .with(body: @request.body.to_json, query: @request.query, headers: @expected_headers)