standard_id-apple 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +112 -0
- data/README.md +93 -4
- data/lib/generators/standard_id/apple/install/install_generator.rb +5 -2
- data/lib/generators/standard_id/apple/install/templates/initializer.rb.erb +12 -11
- data/lib/standard_id/apple/errors.rb +49 -0
- data/lib/standard_id/apple/providers/apple.rb +326 -110
- data/lib/standard_id/apple/version.rb +1 -1
- data/lib/standard_id/apple.rb +6 -1
- metadata +9 -15
- data/lib/standard_id/apple/railtie.rb +0 -13
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 9a3e07c309c99df7cef0af887b983707a504e9c68966899bb9f5a173e7fa6e45
|
|
4
|
+
data.tar.gz: fe8506b6efa0b7fad211136546e04f318057bcd53bb4961d61dcfd6352ec0118
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 723d58e82c79eb36a8c963e9f94e68718df906af0f498831e6095bc8ec7774f806a0ab4e8661942401654d055bf42fa96633a7ddca0d38d8f719721bb0a8419a
|
|
7
|
+
data.tar.gz: ca5b3cdd9a2a6ce0ab8dfb47dfc9291442d3f62e9149c00630088da543d512d0537540b92ee488159ef69d2d02ee39781075ff0ab03b6c998448afb881afdc74
|
data/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,118 @@ 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
|
+
|
|
38
|
+
## [0.6.0] - 2026-09-24
|
|
39
|
+
|
|
40
|
+
Adopts the provider-plugin API of standard_id 0.42.
|
|
41
|
+
|
|
42
|
+
### Upgrade
|
|
43
|
+
|
|
44
|
+
- **Requires `standard_id` 0.42** (`~> 0.42`, was `>= 0.29, < 1.0`). Bump both
|
|
45
|
+
together.
|
|
46
|
+
- **Rename `APPLE_PRIVATE_KEY_PEM` to `APPLE_PRIVATE_KEY`** when convenient.
|
|
47
|
+
Initializers from the 0.5.0 generator assign `ENV["APPLE_PRIVATE_KEY_PEM"]`
|
|
48
|
+
explicitly and keep working unchanged; the old name is also read as a
|
|
49
|
+
deprecated ENV fallback (see Deprecated).
|
|
50
|
+
- **Expect a boot warning if Apple is half-configured.** With
|
|
51
|
+
`apple_client_id` set and any of `apple_team_id` / `apple_key_id` /
|
|
52
|
+
`apple_private_key` blank, standard_id now logs a warning at boot (raises in
|
|
53
|
+
production under `c.social.provider_misconfiguration = :raise`). sidekick-web
|
|
54
|
+
can drop the gated `APPLE_PRIVATE_KEY` / `APPLE_KEY_ID` / `APPLE_TEAM_ID`
|
|
55
|
+
entries in `config/initializers/standard_health.rb` in favour of that
|
|
56
|
+
setting, or keep them for the health report.
|
|
57
|
+
- **Anyone rescuing on message text:** several messages changed (see Changed).
|
|
58
|
+
`StandardId::Apple::Railtie` no longer exists.
|
|
59
|
+
|
|
60
|
+
### Added
|
|
61
|
+
|
|
62
|
+
- **Required config fields.** `apple_private_key`, `apple_key_id` and
|
|
63
|
+
`apple_team_id` are declared `required: true`, so
|
|
64
|
+
`StandardId::Providers::Apple.configuration_errors` and standard_id's boot
|
|
65
|
+
check report them whenever `apple_client_id` (the enabling field) is set —
|
|
66
|
+
the two-stage check sidekick-web rebuilt by hand. `apple_mobile_client_id`
|
|
67
|
+
stays optional: the native `id_token` flow needs no signing key.
|
|
68
|
+
- **ENV fallback** through standard_id 0.42: `APPLE_CLIENT_ID`,
|
|
69
|
+
`APPLE_MOBILE_CLIENT_ID`, `APPLE_PRIVATE_KEY`, `APPLE_KEY_ID`, `APPLE_TEAM_ID`.
|
|
70
|
+
- **JWKS caching.** Apple's key set is cached in-process for an hour
|
|
71
|
+
(`JWKS_CACHE_TTL`) instead of being downloaded on every sign-in. A token whose
|
|
72
|
+
`kid` is not in the cached set triggers one refetch — Apple rotated — no more
|
|
73
|
+
than once a minute (`JWKS_MIN_REFRESH_INTERVAL`), so tokens with made-up
|
|
74
|
+
`kid`s cannot make this process hammer Apple. `reset_jwks_cache!` drops it.
|
|
75
|
+
- Specs for `resolve_params`, `skip_csrf?`, `supports_mobile_callback?` /
|
|
76
|
+
`flow_for`, nonce handling, JWKS caching and configuration, plus standard_id's
|
|
77
|
+
`"a registered StandardId provider"` shared example.
|
|
78
|
+
|
|
79
|
+
### Changed
|
|
80
|
+
|
|
81
|
+
- **The JWKS is fetched through `StandardId::HttpClient`** — 5s open / 10s read
|
|
82
|
+
timeouts and the private/internal-address guard — instead of a bare
|
|
83
|
+
`Net::HTTP.get_response` with Ruby's default 60s timeouts. HttpClient has no
|
|
84
|
+
public plain GET, so this calls its `validate_url!` / `start_connection`
|
|
85
|
+
directly; CI's compat job catches it if those change.
|
|
86
|
+
- **Nonce mismatches no longer leak the nonce.** The message was
|
|
87
|
+
`ID token nonce mismatch. Expected: <nonce>, got: <nonce>`; it is now
|
|
88
|
+
standard_id's `ID token nonce mismatch`, and the comparison is constant-time.
|
|
89
|
+
- **The duplicated helpers are gone** in favour of standard_id's
|
|
90
|
+
`Providers::Base`: `rescue_to_oauth_error`, `verify_nonce!`,
|
|
91
|
+
`build_authorization_url`, `extract_tokens` (the private
|
|
92
|
+
`extract_token_payload` is removed). `lib/standard_id/apple/railtie.rb` is
|
|
93
|
+
replaced by `StandardId::Providers.plugin_railtie(:apple, ...)`.
|
|
94
|
+
- **Error messages**, now consistently Apple-prefixed and never echoing a `kid`
|
|
95
|
+
or nonce:
|
|
96
|
+
- `Either code or id_token must be provided` → `Apple sign-in requires a code or an id_token`
|
|
97
|
+
- `Access token login flow is not supported for Apple` → `Apple sign-in does not support the access token flow`
|
|
98
|
+
- `Missing authorization code` → `Apple authorization code is missing`
|
|
99
|
+
- `Missing id_token` → `Apple id_token is missing`
|
|
100
|
+
- `Apple response missing id_token` → `Apple token response is missing id_token`
|
|
101
|
+
- `Apple OAuth credentials are incomplete` → `... are incomplete: <fields> not set`
|
|
102
|
+
- `Failed to exchange Apple authorization code: <error>` now falls back to
|
|
103
|
+
`HTTP <status>` when Apple's body names no error (it printed nothing).
|
|
104
|
+
- `JWK with kid '<kid>' not found in Apple's JWKS` → `Invalid Apple ID token: signing key not found in Apple's JWKS`
|
|
105
|
+
- `Failed to fetch JWK: ...` → `Failed to fetch Apple JWKS: ...`. A non-2xx
|
|
106
|
+
JWKS response is now `StandardId::OAuthError` (an upstream failure) rather
|
|
107
|
+
than `InvalidRequestError`.
|
|
108
|
+
- Install generator and README use the canonical `APPLE_PRIVATE_KEY`, and
|
|
109
|
+
document the ENV fallback, required fields and flows.
|
|
110
|
+
|
|
111
|
+
### Deprecated
|
|
112
|
+
|
|
113
|
+
- **`APPLE_PRIVATE_KEY_PEM`** as an ENV source for `apple_private_key`. Read only
|
|
114
|
+
when the field is never assigned and `APPLE_PRIVATE_KEY` is unset, with one
|
|
115
|
+
warning per process through `StandardId.deprecator`.
|
|
116
|
+
|
|
117
|
+
### Removed
|
|
118
|
+
|
|
119
|
+
- `StandardId::Apple::Railtie` (replaced by the Railtie `plugin_railtie`
|
|
120
|
+
defines, `StandardId::Providers::Railties::Apple`).
|
|
121
|
+
|
|
10
122
|
## [0.5.0] - 2026-07-31
|
|
11
123
|
|
|
12
124
|
### Added
|
data/README.md
CHANGED
|
@@ -4,7 +4,7 @@ This gem extracts the Apple OAuth provider from the core [`standard_id`](https:/
|
|
|
4
4
|
|
|
5
5
|
## Installation
|
|
6
6
|
|
|
7
|
-
Add the gem next to `standard_id`:
|
|
7
|
+
Requires `standard_id` 0.42 or later. Add the gem next to `standard_id`:
|
|
8
8
|
|
|
9
9
|
```ruby
|
|
10
10
|
# Gemfile
|
|
@@ -41,18 +41,96 @@ configuring by hand. Configure Apple credentials via the StandardId
|
|
|
41
41
|
configuration block, in the `social` scope:
|
|
42
42
|
|
|
43
43
|
```ruby
|
|
44
|
-
# config/initializers/
|
|
44
|
+
# config/initializers/standard_id_apple.rb
|
|
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
48
|
config.social.apple_team_id = ENV["APPLE_TEAM_ID"]
|
|
49
49
|
config.social.apple_key_id = ENV["APPLE_KEY_ID"]
|
|
50
|
-
config.social.apple_private_key = ENV["
|
|
50
|
+
config.social.apple_private_key = ENV["APPLE_PRIVATE_KEY"]
|
|
51
51
|
end
|
|
52
52
|
```
|
|
53
53
|
|
|
54
54
|
With those values in place, StandardId routes such as `/auth/callback/apple` continue to function using this provider gem.
|
|
55
55
|
|
|
56
|
+
### ENV fallback
|
|
57
|
+
|
|
58
|
+
On `standard_id` 0.42+, a field you never assign falls back to the ENV
|
|
59
|
+
variable named after it, upper-cased:
|
|
60
|
+
|
|
61
|
+
| Field | ENV variable |
|
|
62
|
+
|---|---|
|
|
63
|
+
| `apple_client_id` | `APPLE_CLIENT_ID` |
|
|
64
|
+
| `apple_mobile_client_id` | `APPLE_MOBILE_CLIENT_ID` |
|
|
65
|
+
| `apple_team_id` | `APPLE_TEAM_ID` |
|
|
66
|
+
| `apple_key_id` | `APPLE_KEY_ID` |
|
|
67
|
+
| `apple_private_key` | `APPLE_PRIVATE_KEY` (deprecated fallback: `APPLE_PRIVATE_KEY_PEM`) |
|
|
68
|
+
|
|
69
|
+
So with those variables set the block above is optional. Explicit
|
|
70
|
+
configuration, even `nil`, always wins. `APPLE_PRIVATE_KEY_PEM` — the name
|
|
71
|
+
install generators before 0.6.0 wrote — is still read when
|
|
72
|
+
`APPLE_PRIVATE_KEY` is unset and the field is never assigned, with a
|
|
73
|
+
deprecation warning; rename it. (An initializer that assigns
|
|
74
|
+
`ENV["APPLE_PRIVATE_KEY_PEM"]` explicitly keeps working as-is.)
|
|
75
|
+
|
|
76
|
+
### Required fields and the boot check
|
|
77
|
+
|
|
78
|
+
`apple_client_id` (the web Services ID) switches the provider on — it is what
|
|
79
|
+
`StandardId.social_provider_enabled?(:apple)` and the `apple_enabled` Inertia
|
|
80
|
+
prop report. While it is set, `apple_team_id`, `apple_key_id` and
|
|
81
|
+
`apple_private_key` are required: the code exchange signs its `client_secret`
|
|
82
|
+
with them, so without them the flow starts, the user authenticates with Apple,
|
|
83
|
+
and only then does the callback fail. StandardId checks this once every plugin
|
|
84
|
+
has registered:
|
|
85
|
+
|
|
86
|
+
```ruby
|
|
87
|
+
StandardId::Providers::Apple.configuration_errors
|
|
88
|
+
# => ["apple_private_key is required when apple_client_id is set"]
|
|
89
|
+
|
|
90
|
+
config.social.provider_misconfiguration = :raise # fail a production boot instead of warning
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
`apple_mobile_client_id` gates nothing: the native `id_token` flow verifies the
|
|
94
|
+
token against Apple's JWKS and needs no signing key. A native-only app (mobile
|
|
95
|
+
client ID set, `apple_client_id` not) is therefore "not enabled" for the web
|
|
96
|
+
UI while its native sign-in keeps working.
|
|
97
|
+
|
|
98
|
+
### Flows
|
|
99
|
+
|
|
100
|
+
| Flow | Audience (`client_id`) | Needs signing key |
|
|
101
|
+
|---|---|---|
|
|
102
|
+
| Web (`/auth/callback/apple`, form_post, CSRF skipped) | `apple_client_id` | yes |
|
|
103
|
+
| Native `id_token` (`/api/oauth/callback/apple`) | `apple_mobile_client_id` | no |
|
|
104
|
+
| Web flow on Android etc. (`flow=web` on the API callback, redirects back into the app) | `apple_client_id` | yes |
|
|
105
|
+
|
|
106
|
+
Apple's signing keys (JWKS) are fetched through `StandardId::HttpClient`
|
|
107
|
+
(timeouts, private-address guard) and cached in-process for an hour; a token
|
|
108
|
+
signed with an unknown key triggers one early refetch, at most once a minute.
|
|
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
|
+
|
|
56
134
|
### Two corrections to earlier versions of this section
|
|
57
135
|
|
|
58
136
|
**The `social.` prefix.** This section previously showed the flat form
|
|
@@ -92,7 +170,18 @@ without this gem in your Gemfile**, on any `standard_id` version. Configuring
|
|
|
92
170
|
|
|
93
171
|
## Testing
|
|
94
172
|
|
|
95
|
-
|
|
173
|
+
In a host app, pin the plugin's registration with standard_id's shared
|
|
174
|
+
example:
|
|
175
|
+
|
|
176
|
+
```ruby
|
|
177
|
+
require "standard_id/testing"
|
|
178
|
+
|
|
179
|
+
RSpec.describe "StandardId social providers" do
|
|
180
|
+
it_behaves_like "a registered StandardId provider", :apple
|
|
181
|
+
end
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Run this gem's spec suite:
|
|
96
185
|
|
|
97
186
|
```bash
|
|
98
187
|
bundle exec rspec
|
|
@@ -65,9 +65,12 @@ module StandardId
|
|
|
65
65
|
say " APPLE_MOBILE_CLIENT_ID the iOS bundle ID — optional, web-only apps skip it"
|
|
66
66
|
say " APPLE_TEAM_ID the 10-character Apple Developer team ID"
|
|
67
67
|
say " APPLE_KEY_ID the key ID of the Sign In with Apple private key"
|
|
68
|
-
say "
|
|
68
|
+
say " APPLE_PRIVATE_KEY the .p8 private key contents, PEM, newlines intact"
|
|
69
69
|
say ""
|
|
70
|
-
say "
|
|
70
|
+
say "APPLE_TEAM_ID, APPLE_KEY_ID and APPLE_PRIVATE_KEY are required whenever"
|
|
71
|
+
say "APPLE_CLIENT_ID is set; StandardId checks for them at boot."
|
|
72
|
+
say ""
|
|
73
|
+
say "APPLE_PRIVATE_KEY is multi-line. Most secret stores flatten it to"
|
|
71
74
|
say "literal \\n — if sign-in fails on a JWT signing error, that is why."
|
|
72
75
|
say "=" * 79
|
|
73
76
|
say ""
|
|
@@ -13,17 +13,17 @@
|
|
|
13
13
|
# routes a unique unqualified name to its owning scope, but it stops working
|
|
14
14
|
# the day another scope declares a colliding name. Use `config.social.`.
|
|
15
15
|
#
|
|
16
|
-
#
|
|
17
|
-
#
|
|
18
|
-
#
|
|
16
|
+
# ENV: on standard_id >= 0.42 a field this file does not assign falls back to
|
|
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).
|
|
19
22
|
#
|
|
20
|
-
#
|
|
21
|
-
#
|
|
22
|
-
#
|
|
23
|
-
#
|
|
24
|
-
# standard_id >= 0.33.0 declares every loaded provider's fields before
|
|
25
|
-
# `:load_config_initializers`, so the plain form is correct. Existing wrappers
|
|
26
|
-
# keep working and need no change.
|
|
23
|
+
# apple_client_id switches the web flow on. While it is set, StandardId's boot
|
|
24
|
+
# check requires apple_team_id, apple_key_id and apple_private_key (warns by
|
|
25
|
+
# default; `config.social.provider_misconfiguration = :raise` fails a
|
|
26
|
+
# production boot instead).
|
|
27
27
|
StandardId.configure do |config|
|
|
28
28
|
config.social.apple_client_id = ENV["APPLE_CLIENT_ID"]
|
|
29
29
|
|
|
@@ -38,5 +38,6 @@ StandardId.configure do |config|
|
|
|
38
38
|
# The .p8 contents in PEM form, newlines intact. Secret stores that flatten
|
|
39
39
|
# multi-line values to literal \n produce a key that parses but fails to
|
|
40
40
|
# sign — surfacing as a JWT error at callback time, not at boot.
|
|
41
|
-
|
|
41
|
+
# (Installs before standard_id-apple 0.6.0 used APPLE_PRIVATE_KEY_PEM.)
|
|
42
|
+
config.social.apple_private_key = ENV["APPLE_PRIVATE_KEY"]
|
|
42
43
|
end
|
|
@@ -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
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
require "uri"
|
|
2
|
-
require "net/http"
|
|
3
1
|
require "json"
|
|
4
2
|
require "jwt"
|
|
3
|
+
require "net/http"
|
|
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 = {
|
|
@@ -17,6 +20,22 @@ module StandardId
|
|
|
17
20
|
response_mode: DEFAULT_RESPONSE_MODE
|
|
18
21
|
}.freeze
|
|
19
22
|
|
|
23
|
+
# Apple's signing keys rotate rarely; an unknown `kid` forces an early
|
|
24
|
+
# refetch (see #fetch_jwk), so a long TTL costs nothing on rotation.
|
|
25
|
+
JWKS_CACHE_TTL = 3600
|
|
26
|
+
# Floor between forced refetches, so a stream of ID tokens carrying
|
|
27
|
+
# made-up `kid`s cannot turn this process into a request amplifier
|
|
28
|
+
# against Apple.
|
|
29
|
+
JWKS_MIN_REFRESH_INTERVAL = 60
|
|
30
|
+
|
|
31
|
+
# Pre-0.6.0 install generators wired `apple_private_key` to this
|
|
32
|
+
# variable. Still read, with a deprecation warning, when the canonical
|
|
33
|
+
# APPLE_PRIVATE_KEY is unset and the host never assigns the field.
|
|
34
|
+
LEGACY_PRIVATE_KEY_ENV = "APPLE_PRIVATE_KEY_PEM".freeze
|
|
35
|
+
|
|
36
|
+
@jwks_mutex = Mutex.new
|
|
37
|
+
@jwks_cache = nil
|
|
38
|
+
|
|
20
39
|
class << self
|
|
21
40
|
def provider_name
|
|
22
41
|
"apple"
|
|
@@ -29,18 +48,12 @@ module StandardId
|
|
|
29
48
|
def authorization_url(state:, redirect_uri:, **options)
|
|
30
49
|
ensure_basic_credentials!
|
|
31
50
|
|
|
32
|
-
|
|
51
|
+
build_authorization_url(
|
|
52
|
+
endpoint: AUTH_ENDPOINT,
|
|
33
53
|
client_id: StandardId.config.apple_client_id,
|
|
34
|
-
redirect_uri:,
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
supported_authorization_params.each do |param|
|
|
40
|
-
query[param] = options[param] || AUTHORIZATION_PARAM_DEFAULTS[param]
|
|
41
|
-
end
|
|
42
|
-
|
|
43
|
-
"#{AUTH_ENDPOINT}?#{URI.encode_www_form(query.compact)}"
|
|
54
|
+
redirect_uri:, state:, options:,
|
|
55
|
+
defaults: AUTHORIZATION_PARAM_DEFAULTS
|
|
56
|
+
)
|
|
44
57
|
end
|
|
45
58
|
|
|
46
59
|
def get_user_info(code: nil, id_token: nil, access_token: nil, redirect_uri: nil, nonce: nil, **options)
|
|
@@ -54,19 +67,32 @@ module StandardId
|
|
|
54
67
|
elsif code.present?
|
|
55
68
|
exchange_code_for_user_info(code: code, redirect_uri: redirect_uri, client_id: client_id, nonce: nonce)
|
|
56
69
|
elsif access_token.present?
|
|
57
|
-
raise StandardId::InvalidRequestError, "
|
|
70
|
+
raise StandardId::InvalidRequestError, "Apple sign-in does not support the access token flow"
|
|
58
71
|
else
|
|
59
|
-
raise StandardId::InvalidRequestError, "
|
|
72
|
+
raise StandardId::InvalidRequestError, "Apple sign-in requires a code or an id_token"
|
|
60
73
|
end
|
|
61
74
|
end
|
|
62
75
|
|
|
76
|
+
# `apple_client_id` (the web Services ID) switches the provider on —
|
|
77
|
+
# it is the enabling field, so StandardId's boot check reports the
|
|
78
|
+
# three signing credentials below whenever it is set. They are what
|
|
79
|
+
# the code exchange needs to sign its client_secret; without them the
|
|
80
|
+
# web flow starts fine and only fails at the callback, after the user
|
|
81
|
+
# has authenticated with Apple.
|
|
82
|
+
#
|
|
83
|
+
# `apple_mobile_client_id` gates nothing: the native id_token flow
|
|
84
|
+
# verifies against Apple's JWKS and needs no signing key.
|
|
85
|
+
#
|
|
86
|
+
# ENV fallbacks (standard_id >= 0.42) use the upper-cased field names:
|
|
87
|
+
# APPLE_CLIENT_ID, APPLE_MOBILE_CLIENT_ID, APPLE_PRIVATE_KEY,
|
|
88
|
+
# APPLE_KEY_ID, APPLE_TEAM_ID.
|
|
63
89
|
def config_schema
|
|
64
90
|
{
|
|
65
91
|
apple_client_id: { type: :string, default: nil },
|
|
66
92
|
apple_mobile_client_id: { type: :string, default: nil },
|
|
67
|
-
apple_private_key: { type: :string, default:
|
|
68
|
-
apple_key_id: { type: :string, default: nil },
|
|
69
|
-
apple_team_id: { type: :string, default: nil }
|
|
93
|
+
apple_private_key: { type: :string, default: -> { legacy_private_key_from_env }, required: true },
|
|
94
|
+
apple_key_id: { type: :string, default: nil, required: true },
|
|
95
|
+
apple_team_id: { type: :string, default: nil, required: true }
|
|
70
96
|
}
|
|
71
97
|
end
|
|
72
98
|
|
|
@@ -74,14 +100,19 @@ module StandardId
|
|
|
74
100
|
DEFAULT_SCOPE
|
|
75
101
|
end
|
|
76
102
|
|
|
103
|
+
# Apple posts the web callback (response_mode=form_post).
|
|
77
104
|
def skip_csrf?
|
|
78
105
|
true
|
|
79
106
|
end
|
|
80
107
|
|
|
108
|
+
# Android and other non-Apple platforms sign in through Apple's web
|
|
109
|
+
# flow and need the server to redirect back into the app.
|
|
81
110
|
def supports_mobile_callback?
|
|
82
111
|
true
|
|
83
112
|
end
|
|
84
113
|
|
|
114
|
+
# The web flow authenticates against the Services ID, the native flow
|
|
115
|
+
# against the app's bundle ID.
|
|
85
116
|
def resolve_params(params, context: {})
|
|
86
117
|
flow = context[:flow] || :web
|
|
87
118
|
client_id = flow == :mobile ? StandardId.config.apple_mobile_client_id : StandardId.config.apple_client_id
|
|
@@ -90,83 +121,158 @@ module StandardId
|
|
|
90
121
|
end
|
|
91
122
|
|
|
92
123
|
def exchange_code_for_user_info(code:, redirect_uri:, client_id: StandardId.config.apple_client_id, nonce: nil)
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
{}
|
|
124
|
+
rescue_to_oauth_error do
|
|
125
|
+
ensure_full_credentials!(client_id: client_id)
|
|
126
|
+
raise StandardId::InvalidRequestError, "Apple authorization code is missing" if code.blank?
|
|
127
|
+
|
|
128
|
+
token_response = HttpClient.post_form(TOKEN_ENDPOINT, {
|
|
129
|
+
client_id: client_id,
|
|
130
|
+
client_secret: generate_client_secret(client_id: client_id),
|
|
131
|
+
code: code,
|
|
132
|
+
grant_type: "authorization_code",
|
|
133
|
+
redirect_uri: redirect_uri
|
|
134
|
+
})
|
|
135
|
+
|
|
136
|
+
unless token_response.is_a?(Net::HTTPSuccess)
|
|
137
|
+
raise StandardId::InvalidRequestError,
|
|
138
|
+
"Failed to exchange Apple authorization code: #{error_reason(token_response)}"
|
|
109
139
|
end
|
|
110
|
-
raise StandardId::InvalidRequestError, "Failed to exchange Apple authorization code: #{error_body["error"]}"
|
|
111
|
-
end
|
|
112
140
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
141
|
+
parsed_token = JSON.parse(token_response.body)
|
|
142
|
+
id_token = parsed_token["id_token"]
|
|
143
|
+
raise StandardId::InvalidRequestError, "Apple token response is missing id_token" if id_token.blank?
|
|
116
144
|
|
|
117
|
-
|
|
118
|
-
|
|
145
|
+
user_info = verify_id_token(id_token: id_token, client_id: client_id, nonce: nonce)
|
|
146
|
+
build_response(user_info, tokens: extract_tokens(parsed_token))
|
|
147
|
+
end
|
|
148
|
+
end
|
|
119
149
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
150
|
+
def verify_id_token(id_token:, client_id: StandardId.config.apple_client_id, nonce: nil)
|
|
151
|
+
rescue_to_oauth_error do
|
|
152
|
+
raise StandardId::InvalidRequestError, "Apple id_token is missing" if id_token.blank?
|
|
153
|
+
raise StandardId::InvalidRequestError, "Apple client_id is not configured" if client_id.blank?
|
|
154
|
+
|
|
155
|
+
_unverified_payload, header = JWT.decode(id_token, nil, false)
|
|
156
|
+
jwk = fetch_jwk(kid: header["kid"])
|
|
157
|
+
|
|
158
|
+
verified_payload, = JWT.decode(
|
|
159
|
+
id_token,
|
|
160
|
+
jwk.public_key,
|
|
161
|
+
true,
|
|
162
|
+
algorithms: ["RS256"],
|
|
163
|
+
iss: ISSUER,
|
|
164
|
+
verify_iss: true,
|
|
165
|
+
aud: client_id,
|
|
166
|
+
verify_aud: true
|
|
167
|
+
)
|
|
123
168
|
|
|
124
|
-
|
|
169
|
+
# Web flow with a server-generated nonce; constant-time, and the
|
|
170
|
+
# error never echoes either value.
|
|
171
|
+
verify_nonce!(expected: nonce, actual: verified_payload["nonce"])
|
|
172
|
+
|
|
173
|
+
{
|
|
174
|
+
"sub" => verified_payload["sub"],
|
|
175
|
+
"email" => verified_payload["email"],
|
|
176
|
+
"email_verified" => verified_payload["email_verified"],
|
|
177
|
+
"is_private_email" => verified_payload["is_private_email"]
|
|
178
|
+
}.compact
|
|
179
|
+
rescue JWT::InvalidAudError => e
|
|
180
|
+
raise StandardId::InvalidRequestError, "Invalid Apple ID token audience: #{e.message}"
|
|
181
|
+
rescue JWT::DecodeError => e
|
|
182
|
+
raise StandardId::InvalidRequestError, "Invalid Apple ID token: #{e.message}"
|
|
183
|
+
end
|
|
125
184
|
end
|
|
126
185
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
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?
|
|
146
219
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
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 ')})"
|
|
154
262
|
end
|
|
155
263
|
|
|
156
|
-
|
|
157
|
-
"sub" => verified_payload["sub"],
|
|
158
|
-
"email" => verified_payload["email"],
|
|
159
|
-
"email_verified" => verified_payload["email_verified"],
|
|
160
|
-
"is_private_email" => verified_payload["is_private_email"]
|
|
161
|
-
}.compact
|
|
162
|
-
rescue JWT::InvalidAudError => e
|
|
163
|
-
raise StandardId::InvalidRequestError, "Invalid Apple ID token audience: #{e.message}"
|
|
164
|
-
rescue JWT::DecodeError => e
|
|
165
|
-
raise StandardId::InvalidRequestError, "Invalid Apple ID token: #{e.message}"
|
|
166
|
-
rescue StandardError => e
|
|
167
|
-
raise e if e.is_a?(StandardId::OAuthError)
|
|
264
|
+
ensure_full_credentials!(client_id: client_id)
|
|
168
265
|
|
|
169
|
-
|
|
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
|
+
|
|
273
|
+
# Drop the in-process JWKS cache (tests, or after a known rotation).
|
|
274
|
+
def reset_jwks_cache!
|
|
275
|
+
@jwks_mutex.synchronize { @jwks_cache = nil }
|
|
170
276
|
end
|
|
171
277
|
|
|
172
278
|
private
|
|
@@ -174,21 +280,21 @@ module StandardId
|
|
|
174
280
|
def ensure_basic_credentials!(client_id: StandardId.config.apple_client_id)
|
|
175
281
|
return if client_id.present?
|
|
176
282
|
|
|
177
|
-
raise StandardId::
|
|
283
|
+
raise StandardId::Apple::CredentialsMissingError, "Apple OAuth is not configured"
|
|
178
284
|
end
|
|
179
285
|
|
|
286
|
+
# The same fields StandardId's boot check reports (required_config_fields),
|
|
287
|
+
# checked again at the point of use because the mobile code exchange
|
|
288
|
+
# can run with only apple_mobile_client_id set. Names fields, never
|
|
289
|
+
# values.
|
|
180
290
|
def ensure_full_credentials!(client_id: nil)
|
|
181
291
|
ensure_basic_credentials!(client_id: client_id)
|
|
182
292
|
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
StandardId.config.apple_key_id,
|
|
186
|
-
StandardId.config.apple_team_id
|
|
187
|
-
]
|
|
293
|
+
missing = required_config_fields.select { |field| config_value(field).blank? }
|
|
294
|
+
return if missing.empty?
|
|
188
295
|
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
raise StandardId::InvalidRequestError, "Apple OAuth credentials are incomplete"
|
|
296
|
+
raise StandardId::Apple::CredentialsMissingError,
|
|
297
|
+
"Apple OAuth credentials are incomplete: #{missing.join(', ')} not set"
|
|
192
298
|
end
|
|
193
299
|
|
|
194
300
|
def generate_client_secret(client_id: StandardId.config.apple_client_id)
|
|
@@ -209,32 +315,142 @@ module StandardId
|
|
|
209
315
|
JWT.encode(payload, private_key, "ES256", header)
|
|
210
316
|
end
|
|
211
317
|
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
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
|
|
215
358
|
|
|
216
|
-
|
|
217
|
-
|
|
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
|
+
)
|
|
218
367
|
end
|
|
219
368
|
|
|
220
|
-
|
|
221
|
-
|
|
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
|
|
222
377
|
|
|
223
|
-
|
|
378
|
+
# Look `kid` up in Apple's JWKS, served from an in-process cache
|
|
379
|
+
# (JWKS_CACHE_TTL). An unknown `kid` refetches once — Apple may have
|
|
380
|
+
# rotated — subject to JWKS_MIN_REFRESH_INTERVAL.
|
|
381
|
+
def fetch_jwk(kid:)
|
|
382
|
+
raise StandardId::InvalidRequestError, "Invalid Apple ID token: header has no kid" if kid.blank?
|
|
383
|
+
|
|
384
|
+
jwk_data = find_jwk(jwks_keys, kid) || find_jwk(jwks_keys(refresh: true), kid)
|
|
385
|
+
raise StandardId::InvalidRequestError, "Invalid Apple ID token: signing key not found in Apple's JWKS" unless jwk_data
|
|
224
386
|
|
|
225
387
|
JWT::JWK.import(jwk_data)
|
|
226
|
-
|
|
227
|
-
raise e if e.is_a?(StandardId::OAuthError)
|
|
388
|
+
end
|
|
228
389
|
|
|
229
|
-
|
|
390
|
+
def find_jwk(keys, kid)
|
|
391
|
+
keys.find { |key| key["kid"] == kid }
|
|
230
392
|
end
|
|
231
393
|
|
|
232
|
-
def
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
394
|
+
def jwks_keys(refresh: false)
|
|
395
|
+
@jwks_mutex.synchronize do
|
|
396
|
+
now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
397
|
+
cache = @jwks_cache
|
|
398
|
+
|
|
399
|
+
stale = cache.nil? || now - cache[:fetched_at] > JWKS_CACHE_TTL
|
|
400
|
+
forced = refresh && cache && now - cache[:fetched_at] >= JWKS_MIN_REFRESH_INTERVAL
|
|
401
|
+
if stale || forced
|
|
402
|
+
@jwks_cache = cache = { keys: download_jwks, fetched_at: now }
|
|
403
|
+
end
|
|
404
|
+
|
|
405
|
+
cache[:keys]
|
|
406
|
+
end
|
|
407
|
+
end
|
|
408
|
+
|
|
409
|
+
# Fetched through StandardId::HttpClient's connection setup, so the
|
|
410
|
+
# request gets its timeouts and its private/internal-address guard.
|
|
411
|
+
# HttpClient has no public plain GET (only get_with_bearer, which would
|
|
412
|
+
# send an empty Authorization header), hence the two private calls.
|
|
413
|
+
def download_jwks
|
|
414
|
+
rescue_to_oauth_error("Failed to fetch Apple JWKS") do
|
|
415
|
+
uri, resolved_ip = HttpClient.send(:validate_url!, JWKS_URI)
|
|
416
|
+
response = HttpClient.send(:start_connection, uri, resolved_ip: resolved_ip) do |http|
|
|
417
|
+
http.request(Net::HTTP::Get.new(uri))
|
|
418
|
+
end
|
|
419
|
+
raise StandardId::OAuthError, "Failed to fetch Apple JWKS: HTTP #{response.code}" unless response.is_a?(Net::HTTPSuccess)
|
|
420
|
+
|
|
421
|
+
keys = JSON.parse(response.body)["keys"]
|
|
422
|
+
raise StandardId::OAuthError, "Failed to fetch Apple JWKS: response has no keys" unless keys.is_a?(Array)
|
|
423
|
+
|
|
424
|
+
keys
|
|
425
|
+
end
|
|
426
|
+
end
|
|
427
|
+
|
|
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)
|
|
434
|
+
body = JSON.parse(response.body.to_s)
|
|
435
|
+
reason = body["error"] if body.is_a?(Hash)
|
|
436
|
+
reason.is_a?(String) ? reason.presence : nil
|
|
437
|
+
rescue JSON::ParserError
|
|
438
|
+
nil
|
|
439
|
+
end
|
|
440
|
+
|
|
441
|
+
def legacy_private_key_from_env
|
|
442
|
+
value = ENV[LEGACY_PRIVATE_KEY_ENV]
|
|
443
|
+
return nil if value.blank?
|
|
444
|
+
|
|
445
|
+
# An unassigned field's default is re-evaluated on read; warn once.
|
|
446
|
+
return value if @legacy_private_key_warned
|
|
447
|
+
|
|
448
|
+
@legacy_private_key_warned = true
|
|
449
|
+
StandardId.deprecator.warn(
|
|
450
|
+
"standard_id-apple: reading apple_private_key from #{LEGACY_PRIVATE_KEY_ENV} is deprecated. " \
|
|
451
|
+
"Rename the variable to APPLE_PRIVATE_KEY (or assign config.social.apple_private_key explicitly)."
|
|
452
|
+
)
|
|
453
|
+
value
|
|
238
454
|
end
|
|
239
455
|
end
|
|
240
456
|
end
|
data/lib/standard_id/apple.rb
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
require "active_support/core_ext/numeric/time"
|
|
2
2
|
require "active_support/core_ext/hash/indifferent_access"
|
|
3
3
|
require "standard_id"
|
|
4
|
+
require "standard_id/apple/version"
|
|
4
5
|
require "standard_id/apple/providers/apple"
|
|
5
|
-
|
|
6
|
+
|
|
7
|
+
# Registers the provider from a Railtie's after_initialize (a no-op outside
|
|
8
|
+
# Rails). Its config fields are declared earlier, before config/initializers,
|
|
9
|
+
# by standard_id's own engine initializer.
|
|
10
|
+
StandardId::Providers.plugin_railtie(:apple, "StandardId::Providers::Apple")
|
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.
|
|
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.
|
|
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.
|
|
25
|
+
version: '8.1'
|
|
26
26
|
- !ruby/object:Gem::Dependency
|
|
27
27
|
name: jwt
|
|
28
28
|
requirement: !ruby/object:Gem::Requirement
|
|
@@ -47,22 +47,16 @@ dependencies:
|
|
|
47
47
|
name: standard_id
|
|
48
48
|
requirement: !ruby/object:Gem::Requirement
|
|
49
49
|
requirements:
|
|
50
|
-
- - "
|
|
51
|
-
- !ruby/object:Gem::Version
|
|
52
|
-
version: '0.29'
|
|
53
|
-
- - "<"
|
|
50
|
+
- - "~>"
|
|
54
51
|
- !ruby/object:Gem::Version
|
|
55
|
-
version: '
|
|
52
|
+
version: '0.42'
|
|
56
53
|
type: :runtime
|
|
57
54
|
prerelease: false
|
|
58
55
|
version_requirements: !ruby/object:Gem::Requirement
|
|
59
56
|
requirements:
|
|
60
|
-
- - "
|
|
61
|
-
- !ruby/object:Gem::Version
|
|
62
|
-
version: '0.29'
|
|
63
|
-
- - "<"
|
|
57
|
+
- - "~>"
|
|
64
58
|
- !ruby/object:Gem::Version
|
|
65
|
-
version: '
|
|
59
|
+
version: '0.42'
|
|
66
60
|
description: Extracted StandardId::Providers::Apple implementation packaged as a standalone
|
|
67
61
|
gem so StandardId installations can opt into Sign in with Apple independently.
|
|
68
62
|
email:
|
|
@@ -78,8 +72,8 @@ files:
|
|
|
78
72
|
- lib/generators/standard_id/apple/install/install_generator.rb
|
|
79
73
|
- lib/generators/standard_id/apple/install/templates/initializer.rb.erb
|
|
80
74
|
- lib/standard_id/apple.rb
|
|
75
|
+
- lib/standard_id/apple/errors.rb
|
|
81
76
|
- lib/standard_id/apple/providers/apple.rb
|
|
82
|
-
- lib/standard_id/apple/railtie.rb
|
|
83
77
|
- lib/standard_id/apple/version.rb
|
|
84
78
|
homepage: https://github.com/rarebit-one/standard_id_apple
|
|
85
79
|
licenses:
|
|
@@ -103,7 +97,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
|
|
|
103
97
|
- !ruby/object:Gem::Version
|
|
104
98
|
version: '0'
|
|
105
99
|
requirements: []
|
|
106
|
-
rubygems_version: 4.0.
|
|
100
|
+
rubygems_version: 4.0.10
|
|
107
101
|
specification_version: 4
|
|
108
102
|
summary: Apple Sign In provider plugin for the StandardId engine.
|
|
109
103
|
test_files: []
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
# frozen_string_literal: true
|
|
2
|
-
|
|
3
|
-
module StandardId
|
|
4
|
-
module Apple
|
|
5
|
-
class Railtie < ::Rails::Railtie
|
|
6
|
-
config.after_initialize do
|
|
7
|
-
StandardId::ProviderRegistry.register(:apple, StandardId::Providers::Apple)
|
|
8
|
-
|
|
9
|
-
Rails.logger.debug("[StandardId::Apple] registered provider") if Rails.logger
|
|
10
|
-
end
|
|
11
|
-
end
|
|
12
|
-
end
|
|
13
|
-
end
|