standard_id-apple 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: be7fc30fab9732c5874d6d9672193130821d23251e1d838bfaf952851f988a6f
4
- data.tar.gz: '0529585c83478d6ce4f11a48dbc2fb54548db01ff75f46a50f3f77673b8bc234'
3
+ metadata.gz: c5bb7427c0d928fdf21192e6a48c70431a51a2e3c05d3b96dd192eab760247f0
4
+ data.tar.gz: ef547da4fd6b44facb4cafca70b80a98b65cec3859a6715b1c72160a51769aa1
5
5
  SHA512:
6
- metadata.gz: 0fcea150d715a749d08fbdea281f45e790901a4af7e9cacd090492b66f5e6c633fa3e249164d4613309c780350ee1d8ba3c674b7e685573862f1177f89d8dc1e
7
- data.tar.gz: 3f131c47f4e7ebe1021a967d3426356efdb80b8eeeed86ded1c3f4f5fb5210257ca58fe95a7292a9246404679cb83a0d38e30be5977ffed50a021ffaa5af2d4a
6
+ metadata.gz: f49035c18090743a5513da37b8eb3e66eef03a430a050aa8643492e668f8cff2cb26d7b0247a21b0854ea086023115b0b62a2fc85f613bb965f8dacecf8335ea
7
+ data.tar.gz: 4e23288305fcf8b7dc59fd203ad62b40c3f85dd0983b931a0c948a4d1c75c3712905e46efa4f4c63ae2e37eec3bae7317e7ca09e92aa17564035c21dcb5a47d2
data/CHANGELOG.md CHANGED
@@ -7,6 +7,52 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.8.0] - 2026-10-08
11
+
12
+ ### Added
13
+
14
+ - **`apple_redirect_uri`** (optional, ENV fallback `APPLE_REDIRECT_URI`): the
15
+ return URL web-flow codes are authorized against when the caller exchanges
16
+ them without one — normally `https://<host>/auth/callback_mobile/apple`,
17
+ registered on the Services ID.
18
+
19
+ ### Fixed
20
+
21
+ - **`flow=web` code exchanges through the API callback** (e.g. Android signing
22
+ in through Apple's web flow) sent no `redirect_uri` to Apple's token
23
+ endpoint, so Apple rejected them with `invalid_grant`. `resolve_params` now
24
+ fills the configured `apple_redirect_uri` for the web flow when the caller
25
+ passed none. A caller's `redirect_uri` (the browser callback's) still wins,
26
+ and the native flow is unchanged. No-op until `apple_redirect_uri` is set.
27
+
28
+ ## [0.7.0] - 2026-10-06
29
+
30
+ ### Added
31
+
32
+ - **Token revocation helpers** for App Store Guideline 5.1.1(v) (revoke a
33
+ user's Apple tokens when their account is deleted):
34
+ - `StandardId::Providers::Apple.exchange_authorization_code(code, client_id:, redirect_uri: nil)`
35
+ — exchanges an authorization code at `/auth/token` and verifies the
36
+ returned id_token; returns `user_info` and `tokens`. `redirect_uri` is sent
37
+ only when given (native codes have none).
38
+ - `StandardId::Providers::Apple.revoke(token:, token_type_hint: nil, client_id:)`
39
+ — calls `/auth/revoke` with a `refresh_token` or `access_token`.
40
+ - Checked against Apple's REST docs on 2026-10-06
41
+ (`signinwithapplerestapi/generate-and-validate-tokens`, `.../revoke-tokens`).
42
+ - **`StandardId::Apple::TokenRequestError`** (`#reason`, `#http_status_code`,
43
+ `#retryable?`, `#invalid_grant?`) and
44
+ **`StandardId::Apple::CredentialsMissingError`**, both subclasses of
45
+ `StandardId::InvalidRequestError`. Messages carry Apple's `error` value, the
46
+ HTTP status or the exception class, never a code, token or client secret.
47
+
48
+ ### Changed
49
+
50
+ - The "Apple OAuth is not configured" / "credentials are incomplete" errors
51
+ are now `StandardId::Apple::CredentialsMissingError` (a subclass of the
52
+ `StandardId::InvalidRequestError` they were before; messages unchanged).
53
+ - **Requires Rails 8.1** (`activesupport >= 8.1`, was `>= 8.0`). Every
54
+ consumer app already runs 8.1; 8.0 was never exercised in CI.
55
+
10
56
  ## [0.6.0] - 2026-09-24
11
57
 
12
58
  Adopts the provider-plugin API of standard_id 0.42.
data/README.md CHANGED
@@ -45,6 +45,7 @@ configuration block, in the `social` scope:
45
45
  StandardId.configure do |config|
46
46
  config.social.apple_client_id = ENV["APPLE_CLIENT_ID"]
47
47
  config.social.apple_mobile_client_id = ENV["APPLE_MOBILE_CLIENT_ID"] # optional
48
+ config.social.apple_redirect_uri = ENV["APPLE_REDIRECT_URI"] # optional, see Flows
48
49
  config.social.apple_team_id = ENV["APPLE_TEAM_ID"]
49
50
  config.social.apple_key_id = ENV["APPLE_KEY_ID"]
50
51
  config.social.apple_private_key = ENV["APPLE_PRIVATE_KEY"]
@@ -62,6 +63,7 @@ variable named after it, upper-cased:
62
63
  |---|---|
63
64
  | `apple_client_id` | `APPLE_CLIENT_ID` |
64
65
  | `apple_mobile_client_id` | `APPLE_MOBILE_CLIENT_ID` |
66
+ | `apple_redirect_uri` | `APPLE_REDIRECT_URI` |
65
67
  | `apple_team_id` | `APPLE_TEAM_ID` |
66
68
  | `apple_key_id` | `APPLE_KEY_ID` |
67
69
  | `apple_private_key` | `APPLE_PRIVATE_KEY` (deprecated fallback: `APPLE_PRIVATE_KEY_PEM`) |
@@ -103,10 +105,42 @@ UI while its native sign-in keeps working.
103
105
  | Native `id_token` (`/api/oauth/callback/apple`) | `apple_mobile_client_id` | no |
104
106
  | Web flow on Android etc. (`flow=web` on the API callback, redirects back into the app) | `apple_client_id` | yes |
105
107
 
108
+ Apple only exchanges a web-flow code when the token request carries the same
109
+ `redirect_uri` the authorization used. The browser callback passes its own
110
+ URL. The API callback passes none, so for `flow=web` there set
111
+ `apple_redirect_uri` to the return URL those codes are authorized against,
112
+ normally the mobile bounce `https://<host>/auth/callback_mobile/apple`
113
+ (registered on the Services ID). A `redirect_uri` the caller passes always
114
+ wins, and the native flow never sends one.
115
+
106
116
  Apple's signing keys (JWKS) are fetched through `StandardId::HttpClient`
107
117
  (timeouts, private-address guard) and cached in-process for an hour; a token
108
118
  signed with an unknown key triggers one early refetch, at most once a minute.
109
119
 
120
+ ### Token revocation (account deletion)
121
+
122
+ App Store Guideline 5.1.1(v) requires an app offering Sign in with Apple to
123
+ revoke the user's Apple tokens when their account is deleted. A native app
124
+ that only sends identity tokens leaves the server nothing to revoke, so have
125
+ the app obtain a fresh authorization code at deletion and send it along:
126
+
127
+ ```ruby
128
+ apple = StandardId::Providers::Apple
129
+ client_id = StandardId.config.apple_mobile_client_id # the code's audience
130
+
131
+ result = apple.exchange_authorization_code(code, client_id: client_id)
132
+ result[:user_info][:sub] # verified; check it matches the account being deleted
133
+ apple.revoke(token: result[:tokens][:refresh_token], token_type_hint: "refresh_token", client_id: client_id)
134
+ ```
135
+
136
+ Both need the signing key (`apple_team_id`, `apple_key_id`,
137
+ `apple_private_key`). Failures raise `StandardId::Apple::TokenRequestError`
138
+ (`#reason` is Apple's `error` value, `#invalid_grant?` means the code is
139
+ expired or used — get a new one; `#retryable?` covers timeouts, 429 and 5xx)
140
+ or `StandardId::Apple::CredentialsMissingError`. Both subclass
141
+ `StandardId::InvalidRequestError`, and no message contains a code, token or
142
+ client secret.
143
+
110
144
  ### Two corrections to earlier versions of this section
111
145
 
112
146
  **The `social.` prefix.** This section previously showed the flat form
@@ -2,7 +2,7 @@
2
2
 
3
3
  # Apple Sign In credentials for StandardId.
4
4
  #
5
- # These five fields are declared by the standard_id-apple gem, NOT by
5
+ # These six fields are declared by the standard_id-apple gem, NOT by
6
6
  # standard_id — they do not exist unless this gem is in the Gemfile, on any
7
7
  # standard_id version. Removing the gem and leaving this file behind raises
8
8
  # `StandardId::ConfigurationError: Unknown field 'apple_client_id' for scope
@@ -15,10 +15,10 @@
15
15
  #
16
16
  # ENV: on standard_id >= 0.42 a field this file does not assign falls back to
17
17
  # the ENV variable named after it, upper-cased — APPLE_CLIENT_ID,
18
- # APPLE_MOBILE_CLIENT_ID, APPLE_TEAM_ID, APPLE_KEY_ID, APPLE_PRIVATE_KEY — which
19
- # are the names used below. The assignments are kept so the wiring is visible;
20
- # delete any you prefer to leave to the fallback, or point one at another
21
- # source (e.g. Rails credentials).
18
+ # APPLE_MOBILE_CLIENT_ID, APPLE_REDIRECT_URI, APPLE_TEAM_ID, APPLE_KEY_ID,
19
+ # APPLE_PRIVATE_KEY — which are the names used below. The assignments are kept
20
+ # so the wiring is visible; delete any you prefer to leave to the fallback, or
21
+ # point one at another source (e.g. Rails credentials).
22
22
  #
23
23
  # apple_client_id switches the web flow on. While it is set, StandardId's boot
24
24
  # check requires apple_team_id, apple_key_id and apple_private_key (warns by
@@ -32,6 +32,12 @@ StandardId.configure do |config|
32
32
  # on a web-only app is correct — don't point it at APPLE_CLIENT_ID.
33
33
  config.social.apple_mobile_client_id = ENV["APPLE_MOBILE_CLIENT_ID"]
34
34
 
35
+ # Optional: the return URL web-flow codes exchanged through the API callback
36
+ # (`flow=web`, e.g. Android) were authorized against — normally
37
+ # https://<host>/auth/callback_mobile/apple, registered on the Services ID.
38
+ # Apple rejects the exchange (invalid_grant) without it.
39
+ config.social.apple_redirect_uri = ENV["APPLE_REDIRECT_URI"]
40
+
35
41
  config.social.apple_team_id = ENV["APPLE_TEAM_ID"]
36
42
  config.social.apple_key_id = ENV["APPLE_KEY_ID"]
37
43
 
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module StandardId
4
+ module Apple
5
+ # Raised by the token helpers (`exchange_authorization_code`, `revoke`)
6
+ # when Apple rejects a request or cannot be reached.
7
+ #
8
+ # Subclasses StandardId::InvalidRequestError so existing `rescue
9
+ # StandardId::InvalidRequestError` / `rescue StandardId::OAuthError`
10
+ # handling keeps working. The message names Apple's `error` value (or the
11
+ # HTTP status, or the network failure class) — never a token, code or
12
+ # client secret.
13
+ class TokenRequestError < StandardId::InvalidRequestError
14
+ # @return [String, nil] Apple's `error` value, e.g. "invalid_grant"
15
+ # (see Apple's ErrorResponse: invalid_request, invalid_client,
16
+ # invalid_grant, unauthorized_client, unsupported_grant_type,
17
+ # invalid_scope)
18
+ attr_reader :reason
19
+
20
+ # @return [Integer, nil] Apple's HTTP status; nil when no response was
21
+ # received (timeout, connection failure)
22
+ attr_reader :http_status_code
23
+
24
+ def initialize(message = nil, reason: nil, http_status_code: nil)
25
+ super(message)
26
+ @reason = reason
27
+ @http_status_code = http_status_code
28
+ end
29
+
30
+ # True when retrying the same request may succeed: no response at all
31
+ # (timeout, connection error), throttling or an Apple-side 5xx.
32
+ def retryable?
33
+ http_status_code.nil? || http_status_code == 429 || http_status_code >= 500
34
+ end
35
+
36
+ # The authorization code (or token) is invalid, expired or already
37
+ # used. Authorization codes are single-use and valid for five minutes,
38
+ # so the remedy is a fresh code from the client, not a retry.
39
+ def invalid_grant?
40
+ reason == "invalid_grant"
41
+ end
42
+ end
43
+
44
+ # The Apple signing credentials (team id, key id, private key) or the
45
+ # client id needed to sign a client_secret are not configured. A server
46
+ # misconfiguration, not a client error.
47
+ class CredentialsMissingError < StandardId::InvalidRequestError; end
48
+ end
49
+ end
@@ -2,6 +2,7 @@ require "json"
2
2
  require "jwt"
3
3
  require "net/http"
4
4
  require "openssl"
5
+ require "standard_id/apple/errors"
5
6
 
6
7
  module StandardId
7
8
  module Providers
@@ -10,6 +11,8 @@ module StandardId
10
11
  AUTH_ENDPOINT = "#{ISSUER}/auth/authorize".freeze
11
12
  TOKEN_ENDPOINT = "#{ISSUER}/auth/token".freeze
12
13
  JWKS_URI = "#{ISSUER}/auth/keys".freeze
14
+ REVOKE_ENDPOINT = "#{ISSUER}/auth/revoke".freeze
15
+ TOKEN_TYPE_HINTS = %w[refresh_token access_token].freeze
13
16
  DEFAULT_SCOPE = "name email".freeze
14
17
  DEFAULT_RESPONSE_MODE = "form_post".freeze
15
18
  AUTHORIZATION_PARAM_DEFAULTS = {
@@ -82,11 +85,16 @@ module StandardId
82
85
  #
83
86
  # ENV fallbacks (standard_id >= 0.42) use the upper-cased field names:
84
87
  # APPLE_CLIENT_ID, APPLE_MOBILE_CLIENT_ID, APPLE_PRIVATE_KEY,
85
- # APPLE_KEY_ID, APPLE_TEAM_ID.
88
+ # APPLE_KEY_ID, APPLE_TEAM_ID, APPLE_REDIRECT_URI.
89
+ #
90
+ # `apple_redirect_uri` is optional: the return URL a web-flow code
91
+ # was issued against, for callers that exchange the code without
92
+ # passing one (see #resolve_params).
86
93
  def config_schema
87
94
  {
88
95
  apple_client_id: { type: :string, default: nil },
89
96
  apple_mobile_client_id: { type: :string, default: nil },
97
+ apple_redirect_uri: { type: :string, default: nil },
90
98
  apple_private_key: { type: :string, default: -> { legacy_private_key_from_env }, required: true },
91
99
  apple_key_id: { type: :string, default: nil, required: true },
92
100
  apple_team_id: { type: :string, default: nil, required: true }
@@ -110,11 +118,24 @@ module StandardId
110
118
 
111
119
  # The web flow authenticates against the Services ID, the native flow
112
120
  # against the app's bundle ID.
121
+ #
122
+ # A web-flow code must be exchanged with the redirect_uri it was
123
+ # authorized against, or Apple answers invalid_grant. The browser
124
+ # callback passes its own URL. The API callback (`flow=web`, e.g.
125
+ # Android signing in through Apple's web flow and bouncing back via
126
+ # `/auth/callback_mobile/apple`) passes none, so the configured
127
+ # `apple_redirect_uri` fills the gap. A redirect_uri the caller did
128
+ # pass always wins; the native flow never gets one.
113
129
  def resolve_params(params, context: {})
114
130
  flow = context[:flow] || :web
115
- client_id = flow == :mobile ? StandardId.config.apple_mobile_client_id : StandardId.config.apple_client_id
131
+ return params.merge(client_id: StandardId.config.apple_mobile_client_id) if flow == :mobile
116
132
 
117
- params.merge(client_id: client_id)
133
+ resolved = params.merge(client_id: StandardId.config.apple_client_id)
134
+ configured_redirect_uri = StandardId.config.apple_redirect_uri
135
+ if resolved[:redirect_uri].blank? && configured_redirect_uri.present?
136
+ resolved[:redirect_uri] = configured_redirect_uri
137
+ end
138
+ resolved
118
139
  end
119
140
 
120
141
  def exchange_code_for_user_info(code:, redirect_uri:, client_id: StandardId.config.apple_client_id, nonce: nil)
@@ -180,6 +201,93 @@ module StandardId
180
201
  end
181
202
  end
182
203
 
204
+ # Exchange an authorization code for the user's Apple tokens, and
205
+ # verify the returned id_token.
206
+ #
207
+ # The building block for token revocation (App Store Guideline
208
+ # 5.1.1(v)): an app that only ever sent identity tokens holds nothing
209
+ # it can revoke, so at account deletion it obtains a fresh
210
+ # authorization code, the server exchanges it here, then calls
211
+ # {revoke} with the refresh token.
212
+ #
213
+ # Apple's contract (POST https://appleid.apple.com/auth/token, form
214
+ # encoded; checked 2026-10-06 against
215
+ # https://developer.apple.com/documentation/signinwithapplerestapi/generate-and-validate-tokens):
216
+ # the code is single-use and valid for five minutes; `redirect_uri` is
217
+ # sent only if the original authorization request had one, which a
218
+ # native (AuthenticationServices) authorization does not.
219
+ #
220
+ # @param code [String] the authorization code
221
+ # @param client_id [String] the identifier the code was issued to: the
222
+ # app's bundle ID (apple_mobile_client_id) for a native code, the
223
+ # Services ID (apple_client_id, the default) for a web code
224
+ # @param redirect_uri [String, nil] only for codes from a web flow
225
+ # @return [ActiveSupport::HashWithIndifferentAccess] `user_info`
226
+ # (verified id_token claims: sub, email, ...) and `tokens`
227
+ # (access_token, refresh_token, id_token)
228
+ # @raise [StandardId::Apple::CredentialsMissingError] signing
229
+ # credentials or client_id not configured
230
+ # @raise [StandardId::Apple::TokenRequestError] Apple rejected the
231
+ # code (see #invalid_grant?), returned an error, could not be
232
+ # reached (see #retryable?), or returned an id_token that failed
233
+ # verification
234
+ # @raise [StandardId::InvalidRequestError] code is blank
235
+ def exchange_authorization_code(code, client_id: StandardId.config.apple_client_id, redirect_uri: nil)
236
+ raise StandardId::InvalidRequestError, "Apple authorization code is missing" if code.blank?
237
+
238
+ ensure_full_credentials!(client_id: client_id)
239
+
240
+ params = {
241
+ client_id: client_id,
242
+ client_secret: signed_client_secret(client_id),
243
+ code: code.to_s,
244
+ grant_type: "authorization_code"
245
+ }
246
+ params[:redirect_uri] = redirect_uri if redirect_uri.present?
247
+
248
+ response = post_to_apple(TOKEN_ENDPOINT, params, failure: "Failed to exchange Apple authorization code")
249
+ parsed = parse_token_response(response)
250
+
251
+ build_response(verified_claims(parsed["id_token"], client_id), tokens: extract_tokens(parsed))
252
+ end
253
+
254
+ # Revoke a user's Apple refresh or access token, ending the user's
255
+ # Sign in with Apple session for this app.
256
+ #
257
+ # Apple's contract (POST https://appleid.apple.com/auth/revoke, form
258
+ # encoded; checked 2026-10-06 against
259
+ # https://developer.apple.com/documentation/signinwithapplerestapi/revoke-tokens):
260
+ # 200 with no body when the token is revoked *or was already invalid*,
261
+ # 400 with an ErrorResponse otherwise. Revoking the refresh token is
262
+ # the one that matters; an access token expires within the hour.
263
+ #
264
+ # @param token [String] the refresh token (preferred) or access token
265
+ # @param token_type_hint [String, Symbol, nil] "refresh_token" or
266
+ # "access_token"
267
+ # @param client_id [String] the identifier the token was issued to
268
+ # (the same one used for {exchange_authorization_code})
269
+ # @return [true]
270
+ # @raise [StandardId::Apple::CredentialsMissingError]
271
+ # @raise [StandardId::Apple::TokenRequestError]
272
+ # @raise [StandardId::InvalidRequestError] token blank or hint unknown
273
+ def revoke(token:, token_type_hint: nil, client_id: StandardId.config.apple_client_id)
274
+ raise StandardId::InvalidRequestError, "Apple token to revoke is missing" if token.blank?
275
+
276
+ hint = token_type_hint&.to_s
277
+ if hint && !TOKEN_TYPE_HINTS.include?(hint)
278
+ raise StandardId::InvalidRequestError,
279
+ "Unsupported Apple token_type_hint (expected #{TOKEN_TYPE_HINTS.join(' or ')})"
280
+ end
281
+
282
+ ensure_full_credentials!(client_id: client_id)
283
+
284
+ params = { client_id: client_id, client_secret: signed_client_secret(client_id), token: token.to_s }
285
+ params[:token_type_hint] = hint if hint
286
+
287
+ post_to_apple(REVOKE_ENDPOINT, params, failure: "Failed to revoke Apple token")
288
+ true
289
+ end
290
+
183
291
  # Drop the in-process JWKS cache (tests, or after a known rotation).
184
292
  def reset_jwks_cache!
185
293
  @jwks_mutex.synchronize { @jwks_cache = nil }
@@ -190,7 +298,7 @@ module StandardId
190
298
  def ensure_basic_credentials!(client_id: StandardId.config.apple_client_id)
191
299
  return if client_id.present?
192
300
 
193
- raise StandardId::InvalidRequestError, "Apple OAuth is not configured"
301
+ raise StandardId::Apple::CredentialsMissingError, "Apple OAuth is not configured"
194
302
  end
195
303
 
196
304
  # The same fields StandardId's boot check reports (required_config_fields),
@@ -203,7 +311,7 @@ module StandardId
203
311
  missing = required_config_fields.select { |field| config_value(field).blank? }
204
312
  return if missing.empty?
205
313
 
206
- raise StandardId::InvalidRequestError,
314
+ raise StandardId::Apple::CredentialsMissingError,
207
315
  "Apple OAuth credentials are incomplete: #{missing.join(', ')} not set"
208
316
  end
209
317
 
@@ -225,6 +333,66 @@ module StandardId
225
333
  JWT.encode(payload, private_key, "ES256", header)
226
334
  end
227
335
 
336
+ # generate_client_secret for the token helpers: an unreadable private
337
+ # key is a configuration error, reported without the key material.
338
+ def signed_client_secret(client_id)
339
+ generate_client_secret(client_id: client_id)
340
+ rescue OpenSSL::PKey::PKeyError, ArgumentError
341
+ raise StandardId::Apple::CredentialsMissingError, "Apple OAuth credentials are invalid: apple_private_key could not be loaded"
342
+ end
343
+
344
+ # POST a form to Apple, raising TokenRequestError on a non-2xx response
345
+ # or a transport failure. Messages carry Apple's `error` value, the
346
+ # HTTP status or the exception class — never the request parameters,
347
+ # which hold the code/token and the client secret.
348
+ def post_to_apple(endpoint, params, failure:)
349
+ response = begin
350
+ HttpClient.post_form(endpoint, params)
351
+ rescue Timeout::Error, IOError, SocketError, SystemCallError, OpenSSL::SSL::SSLError, HttpClient::SsrfError => e
352
+ raise StandardId::Apple::TokenRequestError, "#{failure}: #{e.class.name}"
353
+ end
354
+ return response if response.is_a?(Net::HTTPSuccess)
355
+
356
+ reason = apple_error_value(response)
357
+ raise StandardId::Apple::TokenRequestError.new(
358
+ "#{failure}: #{reason || "HTTP #{response.code}"}",
359
+ reason: reason,
360
+ http_status_code: response.code.to_i
361
+ )
362
+ end
363
+
364
+ def parse_token_response(response)
365
+ parsed = JSON.parse(response.body.to_s)
366
+ raise JSON::ParserError, "not an object" unless parsed.is_a?(Hash)
367
+
368
+ parsed
369
+ rescue JSON::ParserError
370
+ raise StandardId::Apple::TokenRequestError.new(
371
+ "Apple token response is not valid JSON",
372
+ reason: "invalid_response",
373
+ http_status_code: response.code.to_i
374
+ )
375
+ end
376
+
377
+ # Verify the id_token from a token response. Any failure is reported as
378
+ # a TokenRequestError with no HTTP status (so #retryable? is true): the
379
+ # realistic cause is a failed JWKS fetch, not a bad token from Apple.
380
+ def verified_claims(id_token, client_id)
381
+ if id_token.blank?
382
+ raise StandardId::Apple::TokenRequestError.new(
383
+ "Apple token response is missing id_token", reason: "invalid_response", http_status_code: 200
384
+ )
385
+ end
386
+
387
+ verify_id_token(id_token: id_token, client_id: client_id)
388
+ rescue StandardId::Apple::TokenRequestError
389
+ raise
390
+ rescue StandardId::OAuthError => e
391
+ raise StandardId::Apple::TokenRequestError.new(
392
+ "Apple id_token from the token response failed verification: #{e.message}", reason: "invalid_id_token"
393
+ )
394
+ end
395
+
228
396
  # Look `kid` up in Apple's JWKS, served from an in-process cache
229
397
  # (JWKS_CACHE_TTL). An unknown `kid` refetches once — Apple may have
230
398
  # rotated — subject to JWKS_MIN_REFRESH_INTERVAL.
@@ -276,11 +444,16 @@ module StandardId
276
444
  end
277
445
 
278
446
  def error_reason(response)
447
+ apple_error_value(response) || "HTTP #{response.code}"
448
+ end
449
+
450
+ # Apple's ErrorResponse `error` value, or nil.
451
+ def apple_error_value(response)
279
452
  body = JSON.parse(response.body.to_s)
280
453
  reason = body["error"] if body.is_a?(Hash)
281
- reason.presence || "HTTP #{response.code}"
454
+ reason.is_a?(String) ? reason.presence : nil
282
455
  rescue JSON::ParserError
283
- "HTTP #{response.code}"
456
+ nil
284
457
  end
285
458
 
286
459
  def legacy_private_key_from_env
@@ -2,6 +2,6 @@
2
2
 
3
3
  module StandardId
4
4
  module Apple
5
- VERSION = "0.6.0"
5
+ VERSION = "0.8.0"
6
6
  end
7
7
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: standard_id-apple
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.6.0
4
+ version: 0.8.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Jaryl Sim
@@ -15,14 +15,14 @@ dependencies:
15
15
  requirements:
16
16
  - - ">="
17
17
  - !ruby/object:Gem::Version
18
- version: '8.0'
18
+ version: '8.1'
19
19
  type: :runtime
20
20
  prerelease: false
21
21
  version_requirements: !ruby/object:Gem::Requirement
22
22
  requirements:
23
23
  - - ">="
24
24
  - !ruby/object:Gem::Version
25
- version: '8.0'
25
+ version: '8.1'
26
26
  - !ruby/object:Gem::Dependency
27
27
  name: jwt
28
28
  requirement: !ruby/object:Gem::Requirement
@@ -72,6 +72,7 @@ files:
72
72
  - lib/generators/standard_id/apple/install/install_generator.rb
73
73
  - lib/generators/standard_id/apple/install/templates/initializer.rb.erb
74
74
  - lib/standard_id/apple.rb
75
+ - lib/standard_id/apple/errors.rb
75
76
  - lib/standard_id/apple/providers/apple.rb
76
77
  - lib/standard_id/apple/version.rb
77
78
  homepage: https://github.com/rarebit-one/standard_id_apple
@@ -96,7 +97,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
96
97
  - !ruby/object:Gem::Version
97
98
  version: '0'
98
99
  requirements: []
99
- rubygems_version: 4.0.3
100
+ rubygems_version: 4.0.10
100
101
  specification_version: 4
101
102
  summary: Apple Sign In provider plugin for the StandardId engine.
102
103
  test_files: []