standard_id-apple 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: be7fc30fab9732c5874d6d9672193130821d23251e1d838bfaf952851f988a6f
4
- data.tar.gz: '0529585c83478d6ce4f11a48dbc2fb54548db01ff75f46a50f3f77673b8bc234'
3
+ metadata.gz: 9a3e07c309c99df7cef0af887b983707a504e9c68966899bb9f5a173e7fa6e45
4
+ data.tar.gz: fe8506b6efa0b7fad211136546e04f318057bcd53bb4961d61dcfd6352ec0118
5
5
  SHA512:
6
- metadata.gz: 0fcea150d715a749d08fbdea281f45e790901a4af7e9cacd090492b66f5e6c633fa3e249164d4613309c780350ee1d8ba3c674b7e685573862f1177f89d8dc1e
7
- data.tar.gz: 3f131c47f4e7ebe1021a967d3426356efdb80b8eeeed86ded1c3f4f5fb5210257ca58fe95a7292a9246404679cb83a0d38e30be5977ffed50a021ffaa5af2d4a
6
+ metadata.gz: 723d58e82c79eb36a8c963e9f94e68718df906af0f498831e6095bc8ec7774f806a0ab4e8661942401654d055bf42fa96633a7ddca0d38d8f719721bb0a8419a
7
+ data.tar.gz: ca5b3cdd9a2a6ce0ab8dfb47dfc9291442d3f62e9149c00630088da543d512d0537540b92ee488159ef69d2d02ee39781075ff0ab03b6c998448afb881afdc74
data/CHANGELOG.md CHANGED
@@ -7,6 +7,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.7.0] - 2026-10-06
11
+
12
+ ### Added
13
+
14
+ - **Token revocation helpers** for App Store Guideline 5.1.1(v) (revoke a
15
+ user's Apple tokens when their account is deleted):
16
+ - `StandardId::Providers::Apple.exchange_authorization_code(code, client_id:, redirect_uri: nil)`
17
+ — exchanges an authorization code at `/auth/token` and verifies the
18
+ returned id_token; returns `user_info` and `tokens`. `redirect_uri` is sent
19
+ only when given (native codes have none).
20
+ - `StandardId::Providers::Apple.revoke(token:, token_type_hint: nil, client_id:)`
21
+ — calls `/auth/revoke` with a `refresh_token` or `access_token`.
22
+ - Checked against Apple's REST docs on 2026-10-06
23
+ (`signinwithapplerestapi/generate-and-validate-tokens`, `.../revoke-tokens`).
24
+ - **`StandardId::Apple::TokenRequestError`** (`#reason`, `#http_status_code`,
25
+ `#retryable?`, `#invalid_grant?`) and
26
+ **`StandardId::Apple::CredentialsMissingError`**, both subclasses of
27
+ `StandardId::InvalidRequestError`. Messages carry Apple's `error` value, the
28
+ HTTP status or the exception class, never a code, token or client secret.
29
+
30
+ ### Changed
31
+
32
+ - The "Apple OAuth is not configured" / "credentials are incomplete" errors
33
+ are now `StandardId::Apple::CredentialsMissingError` (a subclass of the
34
+ `StandardId::InvalidRequestError` they were before; messages unchanged).
35
+ - **Requires Rails 8.1** (`activesupport >= 8.1`, was `>= 8.0`). Every
36
+ consumer app already runs 8.1; 8.0 was never exercised in CI.
37
+
10
38
  ## [0.6.0] - 2026-09-24
11
39
 
12
40
  Adopts the provider-plugin API of standard_id 0.42.
data/README.md CHANGED
@@ -107,6 +107,30 @@ Apple's signing keys (JWKS) are fetched through `StandardId::HttpClient`
107
107
  (timeouts, private-address guard) and cached in-process for an hour; a token
108
108
  signed with an unknown key triggers one early refetch, at most once a minute.
109
109
 
110
+ ### Token revocation (account deletion)
111
+
112
+ App Store Guideline 5.1.1(v) requires an app offering Sign in with Apple to
113
+ revoke the user's Apple tokens when their account is deleted. A native app
114
+ that only sends identity tokens leaves the server nothing to revoke, so have
115
+ the app obtain a fresh authorization code at deletion and send it along:
116
+
117
+ ```ruby
118
+ apple = StandardId::Providers::Apple
119
+ client_id = StandardId.config.apple_mobile_client_id # the code's audience
120
+
121
+ result = apple.exchange_authorization_code(code, client_id: client_id)
122
+ result[:user_info][:sub] # verified; check it matches the account being deleted
123
+ apple.revoke(token: result[:tokens][:refresh_token], token_type_hint: "refresh_token", client_id: client_id)
124
+ ```
125
+
126
+ Both need the signing key (`apple_team_id`, `apple_key_id`,
127
+ `apple_private_key`). Failures raise `StandardId::Apple::TokenRequestError`
128
+ (`#reason` is Apple's `error` value, `#invalid_grant?` means the code is
129
+ expired or used — get a new one; `#retryable?` covers timeouts, 429 and 5xx)
130
+ or `StandardId::Apple::CredentialsMissingError`. Both subclass
131
+ `StandardId::InvalidRequestError`, and no message contains a code, token or
132
+ client secret.
133
+
110
134
  ### Two corrections to earlier versions of this section
111
135
 
112
136
  **The `social.` prefix.** This section previously showed the flat form
@@ -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 = {
@@ -180,6 +183,93 @@ module StandardId
180
183
  end
181
184
  end
182
185
 
186
+ # Exchange an authorization code for the user's Apple tokens, and
187
+ # verify the returned id_token.
188
+ #
189
+ # The building block for token revocation (App Store Guideline
190
+ # 5.1.1(v)): an app that only ever sent identity tokens holds nothing
191
+ # it can revoke, so at account deletion it obtains a fresh
192
+ # authorization code, the server exchanges it here, then calls
193
+ # {revoke} with the refresh token.
194
+ #
195
+ # Apple's contract (POST https://appleid.apple.com/auth/token, form
196
+ # encoded; checked 2026-10-06 against
197
+ # https://developer.apple.com/documentation/signinwithapplerestapi/generate-and-validate-tokens):
198
+ # the code is single-use and valid for five minutes; `redirect_uri` is
199
+ # sent only if the original authorization request had one, which a
200
+ # native (AuthenticationServices) authorization does not.
201
+ #
202
+ # @param code [String] the authorization code
203
+ # @param client_id [String] the identifier the code was issued to: the
204
+ # app's bundle ID (apple_mobile_client_id) for a native code, the
205
+ # Services ID (apple_client_id, the default) for a web code
206
+ # @param redirect_uri [String, nil] only for codes from a web flow
207
+ # @return [ActiveSupport::HashWithIndifferentAccess] `user_info`
208
+ # (verified id_token claims: sub, email, ...) and `tokens`
209
+ # (access_token, refresh_token, id_token)
210
+ # @raise [StandardId::Apple::CredentialsMissingError] signing
211
+ # credentials or client_id not configured
212
+ # @raise [StandardId::Apple::TokenRequestError] Apple rejected the
213
+ # code (see #invalid_grant?), returned an error, could not be
214
+ # reached (see #retryable?), or returned an id_token that failed
215
+ # verification
216
+ # @raise [StandardId::InvalidRequestError] code is blank
217
+ def exchange_authorization_code(code, client_id: StandardId.config.apple_client_id, redirect_uri: nil)
218
+ raise StandardId::InvalidRequestError, "Apple authorization code is missing" if code.blank?
219
+
220
+ ensure_full_credentials!(client_id: client_id)
221
+
222
+ params = {
223
+ client_id: client_id,
224
+ client_secret: signed_client_secret(client_id),
225
+ code: code.to_s,
226
+ grant_type: "authorization_code"
227
+ }
228
+ params[:redirect_uri] = redirect_uri if redirect_uri.present?
229
+
230
+ response = post_to_apple(TOKEN_ENDPOINT, params, failure: "Failed to exchange Apple authorization code")
231
+ parsed = parse_token_response(response)
232
+
233
+ build_response(verified_claims(parsed["id_token"], client_id), tokens: extract_tokens(parsed))
234
+ end
235
+
236
+ # Revoke a user's Apple refresh or access token, ending the user's
237
+ # Sign in with Apple session for this app.
238
+ #
239
+ # Apple's contract (POST https://appleid.apple.com/auth/revoke, form
240
+ # encoded; checked 2026-10-06 against
241
+ # https://developer.apple.com/documentation/signinwithapplerestapi/revoke-tokens):
242
+ # 200 with no body when the token is revoked *or was already invalid*,
243
+ # 400 with an ErrorResponse otherwise. Revoking the refresh token is
244
+ # the one that matters; an access token expires within the hour.
245
+ #
246
+ # @param token [String] the refresh token (preferred) or access token
247
+ # @param token_type_hint [String, Symbol, nil] "refresh_token" or
248
+ # "access_token"
249
+ # @param client_id [String] the identifier the token was issued to
250
+ # (the same one used for {exchange_authorization_code})
251
+ # @return [true]
252
+ # @raise [StandardId::Apple::CredentialsMissingError]
253
+ # @raise [StandardId::Apple::TokenRequestError]
254
+ # @raise [StandardId::InvalidRequestError] token blank or hint unknown
255
+ def revoke(token:, token_type_hint: nil, client_id: StandardId.config.apple_client_id)
256
+ raise StandardId::InvalidRequestError, "Apple token to revoke is missing" if token.blank?
257
+
258
+ hint = token_type_hint&.to_s
259
+ if hint && !TOKEN_TYPE_HINTS.include?(hint)
260
+ raise StandardId::InvalidRequestError,
261
+ "Unsupported Apple token_type_hint (expected #{TOKEN_TYPE_HINTS.join(' or ')})"
262
+ end
263
+
264
+ ensure_full_credentials!(client_id: client_id)
265
+
266
+ params = { client_id: client_id, client_secret: signed_client_secret(client_id), token: token.to_s }
267
+ params[:token_type_hint] = hint if hint
268
+
269
+ post_to_apple(REVOKE_ENDPOINT, params, failure: "Failed to revoke Apple token")
270
+ true
271
+ end
272
+
183
273
  # Drop the in-process JWKS cache (tests, or after a known rotation).
184
274
  def reset_jwks_cache!
185
275
  @jwks_mutex.synchronize { @jwks_cache = nil }
@@ -190,7 +280,7 @@ module StandardId
190
280
  def ensure_basic_credentials!(client_id: StandardId.config.apple_client_id)
191
281
  return if client_id.present?
192
282
 
193
- raise StandardId::InvalidRequestError, "Apple OAuth is not configured"
283
+ raise StandardId::Apple::CredentialsMissingError, "Apple OAuth is not configured"
194
284
  end
195
285
 
196
286
  # The same fields StandardId's boot check reports (required_config_fields),
@@ -203,7 +293,7 @@ module StandardId
203
293
  missing = required_config_fields.select { |field| config_value(field).blank? }
204
294
  return if missing.empty?
205
295
 
206
- raise StandardId::InvalidRequestError,
296
+ raise StandardId::Apple::CredentialsMissingError,
207
297
  "Apple OAuth credentials are incomplete: #{missing.join(', ')} not set"
208
298
  end
209
299
 
@@ -225,6 +315,66 @@ module StandardId
225
315
  JWT.encode(payload, private_key, "ES256", header)
226
316
  end
227
317
 
318
+ # generate_client_secret for the token helpers: an unreadable private
319
+ # key is a configuration error, reported without the key material.
320
+ def signed_client_secret(client_id)
321
+ generate_client_secret(client_id: client_id)
322
+ rescue OpenSSL::PKey::PKeyError, ArgumentError
323
+ raise StandardId::Apple::CredentialsMissingError, "Apple OAuth credentials are invalid: apple_private_key could not be loaded"
324
+ end
325
+
326
+ # POST a form to Apple, raising TokenRequestError on a non-2xx response
327
+ # or a transport failure. Messages carry Apple's `error` value, the
328
+ # HTTP status or the exception class — never the request parameters,
329
+ # which hold the code/token and the client secret.
330
+ def post_to_apple(endpoint, params, failure:)
331
+ response = begin
332
+ HttpClient.post_form(endpoint, params)
333
+ rescue Timeout::Error, IOError, SocketError, SystemCallError, OpenSSL::SSL::SSLError, HttpClient::SsrfError => e
334
+ raise StandardId::Apple::TokenRequestError, "#{failure}: #{e.class.name}"
335
+ end
336
+ return response if response.is_a?(Net::HTTPSuccess)
337
+
338
+ reason = apple_error_value(response)
339
+ raise StandardId::Apple::TokenRequestError.new(
340
+ "#{failure}: #{reason || "HTTP #{response.code}"}",
341
+ reason: reason,
342
+ http_status_code: response.code.to_i
343
+ )
344
+ end
345
+
346
+ def parse_token_response(response)
347
+ parsed = JSON.parse(response.body.to_s)
348
+ raise JSON::ParserError, "not an object" unless parsed.is_a?(Hash)
349
+
350
+ parsed
351
+ rescue JSON::ParserError
352
+ raise StandardId::Apple::TokenRequestError.new(
353
+ "Apple token response is not valid JSON",
354
+ reason: "invalid_response",
355
+ http_status_code: response.code.to_i
356
+ )
357
+ end
358
+
359
+ # Verify the id_token from a token response. Any failure is reported as
360
+ # a TokenRequestError with no HTTP status (so #retryable? is true): the
361
+ # realistic cause is a failed JWKS fetch, not a bad token from Apple.
362
+ def verified_claims(id_token, client_id)
363
+ if id_token.blank?
364
+ raise StandardId::Apple::TokenRequestError.new(
365
+ "Apple token response is missing id_token", reason: "invalid_response", http_status_code: 200
366
+ )
367
+ end
368
+
369
+ verify_id_token(id_token: id_token, client_id: client_id)
370
+ rescue StandardId::Apple::TokenRequestError
371
+ raise
372
+ rescue StandardId::OAuthError => e
373
+ raise StandardId::Apple::TokenRequestError.new(
374
+ "Apple id_token from the token response failed verification: #{e.message}", reason: "invalid_id_token"
375
+ )
376
+ end
377
+
228
378
  # Look `kid` up in Apple's JWKS, served from an in-process cache
229
379
  # (JWKS_CACHE_TTL). An unknown `kid` refetches once — Apple may have
230
380
  # rotated — subject to JWKS_MIN_REFRESH_INTERVAL.
@@ -276,11 +426,16 @@ module StandardId
276
426
  end
277
427
 
278
428
  def error_reason(response)
429
+ apple_error_value(response) || "HTTP #{response.code}"
430
+ end
431
+
432
+ # Apple's ErrorResponse `error` value, or nil.
433
+ def apple_error_value(response)
279
434
  body = JSON.parse(response.body.to_s)
280
435
  reason = body["error"] if body.is_a?(Hash)
281
- reason.presence || "HTTP #{response.code}"
436
+ reason.is_a?(String) ? reason.presence : nil
282
437
  rescue JSON::ParserError
283
- "HTTP #{response.code}"
438
+ nil
284
439
  end
285
440
 
286
441
  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.7.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.7.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: []