keycardai-oauth 0.13.0 → 0.14.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: b621681ef4ce18e982ba67929dd03d87d77d4d192b5f033f41c757216fe5a5f2
4
- data.tar.gz: b72fee9e5428766e744fba55c4e3d6472d78295d4cf821813bce7c2c6cd8582f
3
+ metadata.gz: fc9efe8a3b93bb81137cfb6829e5461ac369ccb9334dd7aca57e058263802b2f
4
+ data.tar.gz: 4e11001bf77f8c69a2ab4fa8066c204adeeb74edcc986f8d260717dd6d5d6fd4
5
5
  SHA512:
6
- metadata.gz: 6b4f0d9bfcaac6d44f753aba01d1fcba3ace14d292821e7ed00c0f0fa3678f90ce06af66ca49764c0dd5fc5dbc484c48b1abd3f1fff9453d5b25e7ec12cd3207
7
- data.tar.gz: '09f952deebbc83e695d33216a3a8c81b47b6860d85266df3ec166655d5cd71a2e154185021a884cf185134dce7a24776d50a6542ecf82e194fa793780553c640'
6
+ metadata.gz: e8b6eea8644d3f8d38c1520aca1152b5a4a7ffadf7c1c0df631e846954ee19d03a599cd315644c0792d64cf43d853c5770ba2eed7ce1c1e6f1147d13e6ff8150
7
+ data.tar.gz: 29e30c8a5deefa76102b3fd2f9a6a75877fe4ffa8de18e772f29b59b2a30c568aed103f928db6504c9512de140918257b337104518bf9c8170d58db26f3ea18a
data/CHANGELOG.md CHANGED
@@ -15,6 +15,33 @@ the loopback flow (RFC 8252), JWT signing and verification with a caching JWKS
15
15
  keyring, the three application credentials (ClientSecret with multi-zone,
16
16
  WebIdentity, WorkloadIdentity with pluggable token sources), and AccessContext.
17
17
 
18
+ ## 0.14.0-keycardai-oauth (2026-11-26)
19
+
20
+
21
+ - feat(keycardai-oauth): actor token source on the token exchange client (SDK-99) (#101)
22
+ - * feat(keycardai-oauth): actor token source on the token exchange client (SDK-99)
23
+ - * fix(keycardai-oauth): mark transport-shaped token source failures retryable
24
+ - * fix(keycardai-oauth): mark only transient Fly socket errnos retryable
25
+ - ---------
26
+ - Co-authored-by: devin-ai-keycard <devin-ai@keycard.ai>
27
+
28
+ ## 0.13.1-keycardai-oauth (2026-11-26)
29
+
30
+
31
+ - fix(keycardai-oauth): leave tokens and secrets out of printed forms (SDK-126) (#105)
32
+ - * fix(keycardai-oauth): leave tokens and secrets out of printed forms
33
+ - TokenResponse, AccessToken, ClientRegistrationResponse and PKCE::Pair
34
+ leave their secrets out of inspect, to_s and pp. The token clients,
35
+ DeviceAuthorizationClient, WebIdentity, WorkloadIdentity,
36
+ PrivateKeyManager and JWTSigner show identifiers and the credential's
37
+ class only. to_h, raw and the readers keep the values.
38
+ - Refs SDK-126, keycard-sdk-spec#113.
39
+ - (cherry picked from commit e7189b803d47384f4620b5799301b283fcb60cb2)
40
+ - * fix(keycardai-oauth): keep client authentication values out of to_json
41
+ - ClientAuthentication is not a persisted value, so to_json falls back to the printed form and a JSON log formatter never writes the client secret or assertion. to_h still returns the values.
42
+ - ---------
43
+ - Co-authored-by: Larry Osakwe <23560354+Larry-Osakwe@users.noreply.github.com>
44
+
18
45
  ## 0.13.0-keycardai-oauth (2026-11-26)
19
46
 
20
47
 
@@ -11,6 +11,8 @@ module Keycardai
11
11
  # It never includes a grant parameter such as grant_type or
12
12
  # subject_token_type. The caller merges it into its own request.
13
13
  ClientAuthentication = Data.define(:headers, :params) do
14
+ include PrintedForm
15
+
14
16
  # @param headers [Hash{String => String}]
15
17
  # @param params [Hash{String => String}] form fields
16
18
  def initialize(headers: {}, params: {})
@@ -24,12 +26,6 @@ module Keycardai
24
26
  def inspect
25
27
  "#<data #{self.class} headers=#{headers.keys.inspect}, params=#{params.keys.inspect}>"
26
28
  end
27
- alias_method :to_s, :inspect
28
-
29
- # Used by pp.
30
- def pretty_print(printer)
31
- printer.text(inspect)
32
- end
33
29
  end
34
30
 
35
31
  # Internals for operations that authenticate with a credential's client
@@ -24,6 +24,8 @@ module Keycardai
24
24
  # A token operation for a zone not in the map fails closed: the credential
25
25
  # raises rather than fall back to another zone's secret.
26
26
  class ClientSecret
27
+ include PrintedForm
28
+
27
29
  # @overload initialize(client_id, client_secret)
28
30
  # @overload initialize(issuer_map)
29
31
  # @param issuer_map [Hash{String => Array(String, String)}]
@@ -86,12 +88,6 @@ module Keycardai
86
88
  shown = multi_zone? ? "issuers=#{issuers.inspect}" : "client_id=#{@pair.first.inspect}"
87
89
  "#<#{self.class} #{shown}>"
88
90
  end
89
- alias to_s inspect
90
-
91
- # Used by pp.
92
- def pretty_print(printer)
93
- printer.text(inspect)
94
- end
95
91
 
96
92
  # Build the token-exchange form parameters. Client authentication goes
97
93
  # in the Basic header, never in the body.
@@ -105,14 +101,7 @@ module Keycardai
105
101
  # @return [Hash]
106
102
  def prepare_token_exchange_request(subject_token:, resource: nil, audience: nil, scope: nil,
107
103
  token_endpoint: nil, issuer: nil)
108
- {
109
- "grant_type" => GrantType::TOKEN_EXCHANGE,
110
- "subject_token" => subject_token,
111
- "subject_token_type" => TokenType::ACCESS_TOKEN,
112
- "resource" => resource,
113
- "audience" => audience,
114
- "scope" => scope
115
- }.compact
104
+ TokenExchangeForm.build(subject_token: subject_token, resource: resource, audience: audience, scope: scope)
116
105
  end
117
106
 
118
107
  private
@@ -16,6 +16,8 @@ module Keycardai
16
16
 
17
17
  # Resolves and constructs a credential from one environment mapping.
18
18
  class CredentialDiscovery
19
+ include PrintedForm
20
+
19
21
  SELECTOR = "KEYCARD_APPLICATION_CREDENTIAL_TYPE"
20
22
  STORAGE_DIR = "KEYCARD_WEB_IDENTITY_KEY_STORAGE_DIR"
21
23
  TYPES = %w[client_secret workload_identity web_identity].freeze
@@ -43,6 +45,10 @@ module Keycardai
43
45
  end
44
46
  end
45
47
 
48
+ def inspect
49
+ "#<#{self.class} client_id=#{@client_id.inspect}, resolvable=#{@resolvable.inspect}>"
50
+ end
51
+
46
52
  private
47
53
 
48
54
  def value(env, name)
@@ -17,6 +17,8 @@ module Keycardai
17
17
  DeviceAuthorization = Data.define(
18
18
  :device_code, :user_code, :verification_uri, :verification_uri_complete, :expires_in, :interval, :expires_at
19
19
  ) do
20
+ include PrintedForm::Serializable
21
+
20
22
  # @param device_code [String]
21
23
  # @param user_code [String]
22
24
  # @param verification_uri [String]
@@ -38,12 +40,6 @@ module Keycardai
38
40
  shown = to_h.except(:device_code).map { |name, value| "#{name}=#{value.inspect}" }
39
41
  "#<data #{self.class} #{shown.join(", ")}>"
40
42
  end
41
- alias_method :to_s, :inspect
42
-
43
- # Used by pp.
44
- def pretty_print(printer)
45
- printer.text(inspect)
46
- end
47
43
 
48
44
  # Parse a 2xx device authorization response.
49
45
  #
@@ -118,6 +114,8 @@ module Keycardai
118
114
  # token_endpoint from the metadata passed in, or from discovery. It does
119
115
  # not keep state between operations, except the discovery cache.
120
116
  class DeviceAuthorizationClient
117
+ include PrintedForm
118
+
121
119
  # Poll interval, in seconds, when the response omits one (RFC 8628 §3.2).
122
120
  DEFAULT_INTERVAL = 5
123
121
  # Seconds added to the interval on each slow_down (RFC 8628 §3.5).
@@ -197,6 +195,15 @@ module Keycardai
197
195
  DeviceAuthorization.from_response(response, received_at: @clock.call)
198
196
  end
199
197
 
198
+ # Shows the issuer, the public client_id, and the credential's class. A
199
+ # credential defined outside the SDK may print its own secrets.
200
+ #
201
+ # @return [String]
202
+ def inspect
203
+ "#<#{self.class} issuer=#{@issuer.inspect}, client_id=#{@client_id.inspect}, " \
204
+ "credential=#{PrintedForm.type_of(@credential)}>"
205
+ end
206
+
200
207
  # Poll the token endpoint once with the authorization's device_code.
201
208
  #
202
209
  # If you call poll_token in a loop, wait at least
@@ -217,6 +217,11 @@ module Keycardai
217
217
  super(message)
218
218
  @source = source
219
219
  end
220
+
221
+ # @return [Boolean] configuration errors are not retryable
222
+ def retryable?
223
+ false
224
+ end
220
225
  end
221
226
 
222
227
  # A workload-identity source failed at request time: file unreadable or
@@ -226,9 +231,15 @@ module Keycardai
226
231
  # @return [String]
227
232
  attr_reader :source
228
233
 
229
- def initialize(message, source:)
234
+ def initialize(message, source:, retryable: false)
230
235
  super(message)
231
236
  @source = source
237
+ @retryable = retryable
238
+ end
239
+
240
+ # @return [Boolean] whether repeating the fetch unchanged could succeed
241
+ def retryable?
242
+ @retryable
232
243
  end
233
244
  end
234
245
  end
@@ -14,6 +14,8 @@ module Keycardai
14
14
  # claims omit iss and the signer carries an issuer, iss is filled in; a
15
15
  # caller-supplied iss is preserved.
16
16
  class JWTSigner
17
+ include PrintedForm
18
+
17
19
  ALGORITHM = "RS256"
18
20
 
19
21
  # @param key [OpenSSL::PKey::RSA] the RSA private signing key
@@ -31,6 +33,13 @@ module Keycardai
31
33
  @issuer = issuer
32
34
  end
33
35
 
36
+ # Shows the key ID and the default issuer. Never shows the private key.
37
+ #
38
+ # @return [String]
39
+ def inspect
40
+ "#<#{self.class} kid=#{@kid.inspect}, issuer=#{@issuer.inspect}>"
41
+ end
42
+
34
43
  # Sign a claim set into a compact JWS (header.payload.signature).
35
44
  #
36
45
  # @param claims [Hash] payload claims; string or symbol keys
@@ -14,7 +14,19 @@ module Keycardai
14
14
  METHODS = %w[S256 plain].freeze
15
15
 
16
16
  # A verifier with its derived challenge.
17
- Pair = Data.define(:code_verifier, :code_challenge, :code_challenge_method)
17
+ Pair = Data.define(:code_verifier, :code_challenge, :code_challenge_method) do
18
+ include PrintedForm::Serializable
19
+
20
+ # Leaves out code_verifier, and code_challenge too when the method is
21
+ # plain, because a plain challenge is the verifier. #to_h keeps both.
22
+ #
23
+ # @return [String]
24
+ def inspect
25
+ hidden = code_challenge_method == "plain" ? %i[code_verifier code_challenge] : %i[code_verifier]
26
+ shown = to_h.except(*hidden).map { |name, value| "#{name}=#{value.inspect}" }
27
+ "#<data #{self.class} #{shown.join(", ")}>"
28
+ end
29
+ end
18
30
 
19
31
  module_function
20
32
 
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Keycardai
6
+ module OAuth
7
+ # Makes to_s and pp print the same text as inspect. A type that holds a
8
+ # secret defines inspect to leave the secret out, then includes this so
9
+ # every printed form leaves it out (keycard-sdk-spec base.md, Printed
10
+ # forms). #to_h and the readers still return the values. Not public API.
11
+ module PrintedForm
12
+ # @return [String] the same text as inspect
13
+ def to_s
14
+ inspect
15
+ end
16
+
17
+ # Used by pp.
18
+ def pretty_print(printer)
19
+ printer.text(inspect)
20
+ end
21
+
22
+ # The class name of an object the SDK does not define, such as a
23
+ # caller's credential, which may print its own secrets.
24
+ #
25
+ # @return [String] the class name, or "nil"
26
+ def self.type_of(value)
27
+ value.nil? ? "nil" : value.class.name || value.class.to_s
28
+ end
29
+
30
+ # Data values serialize all their fields for persistence.
31
+ module Serializable
32
+ include PrintedForm
33
+
34
+ def to_json(...)
35
+ to_h.to_json(...)
36
+ end
37
+ end
38
+ end
39
+ private_constant :PrintedForm
40
+ end
41
+ end
@@ -45,6 +45,8 @@ module Keycardai
45
45
  # private_key_jwt client assertions with it. WebIdentity composes this;
46
46
  # it is also usable standalone.
47
47
  class PrivateKeyManager
48
+ include PrintedForm
49
+
48
50
  ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
49
51
  DEFAULT_ASSERTION_LIFETIME = 300
50
52
 
@@ -62,6 +64,13 @@ module Keycardai
62
64
  @mutex = Mutex.new
63
65
  end
64
66
 
67
+ # Shows the key ID. Never shows the private key.
68
+ #
69
+ # @return [String]
70
+ def inspect
71
+ "#<#{self.class} key_id=#{@key_id.inspect}>"
72
+ end
73
+
65
74
  # Load the persisted keypair, generating and storing one on first use.
66
75
  #
67
76
  # @return [OpenSSL::PKey::RSA]
@@ -12,6 +12,19 @@ module Keycardai
12
12
  :client_id, :client_secret, :client_id_issued_at, :client_secret_expires_at,
13
13
  :registration_access_token, :registration_client_uri, :raw
14
14
  ) do
15
+ include PrintedForm::Serializable
16
+
17
+ # Shows every member except client_secret and
18
+ # registration_access_token, and only the field names of +raw+. #to_h
19
+ # and +raw+ keep the values.
20
+ #
21
+ # @return [String]
22
+ def inspect
23
+ shown = to_h.except(:client_secret, :registration_access_token, :raw)
24
+ .map { |name, value| "#{name}=#{value.inspect}" }
25
+ "#<data #{self.class} #{shown.join(", ")}, raw=#{raw.to_h.keys.inspect}>"
26
+ end
27
+
15
28
  # @param field [String] a response field name
16
29
  # @return [Object, nil] the field's value from the full response body
17
30
  def [](field)
@@ -20,18 +20,24 @@ module Keycardai
20
20
  # @param client_id [String, nil] shared-secret client id (HTTP Basic)
21
21
  # @param client_secret [String, nil] shared-secret client secret;
22
22
  # provide both or neither
23
+ # @param actor [#identity_token, #call, nil] supplies the acting
24
+ # workload's identity token, sent as actor_token with type JWT on
25
+ # every exchange unless the request sets its own; never sent on
26
+ # impersonate
23
27
  # @param http_client [#get, #post_form] pluggable transport
24
28
  # @param timeout [Numeric, nil] request timeout in seconds
25
29
  # @param discovery_ttl [Numeric] token-endpoint cache lifetime in seconds
26
30
  # @param clock [#call] returns the current Time; override in tests
27
31
  # @raise [ConfigurationError] when only one of client_id/client_secret is
28
- # given, or a credential is combined with a raw pair
29
- def initialize(issuer:, credential: nil, client_id: nil, client_secret: nil,
32
+ # given, a credential is combined with a raw pair, or actor responds
33
+ # to neither identity_token nor call
34
+ def initialize(issuer:, credential: nil, client_id: nil, client_secret: nil, actor: nil,
30
35
  http_client: HTTP::NetHTTPClient.new, timeout: nil,
31
36
  discovery_ttl: TokenRequests::DEFAULT_DISCOVERY_TTL, clock: MetadataRetry::WALL_CLOCK)
32
37
  initialize_token_client(issuer: issuer, credential: credential, client_id: client_id,
33
38
  client_secret: client_secret, http_client: http_client, timeout: timeout,
34
39
  discovery_ttl: discovery_ttl, clock: clock)
40
+ @actor = actor ? WorkloadIdentity.normalize_source(actor) : nil
35
41
  end
36
42
 
37
43
  # Exchange a subject token (RFC 8693).
@@ -43,7 +49,8 @@ module Keycardai
43
49
  # @param scope [String, nil] space-separated scopes for the issued token
44
50
  # @param requested_token_type [String, nil]
45
51
  # @param actor_token [String, nil] the acting party's token, for explicit
46
- # delegation; requires actor_token_type
52
+ # delegation; overrides the client's actor source when set and requires
53
+ # actor_token_type
47
54
  # @param actor_token_type [String, nil]
48
55
  # @param client_assertion [String, nil] client-authentication assertion,
49
56
  # form-encoded in the body; requires client_assertion_type
@@ -57,6 +64,8 @@ module Keycardai
57
64
  # authentication. Defaults to the client's issuer.
58
65
  # @return [TokenResponse]
59
66
  # @raise [ConfigurationError] when the request sets client_id with HTTP Basic
67
+ # @raise [WorkloadIdentityConfigurationError, WorkloadIdentityRuntimeError]
68
+ # when the configured actor source fails
60
69
  # @raise [OAuthError] an RFC 6749 §5.2 error response (invalid_grant,
61
70
  # invalid_target, invalid_scope, unauthorized_client, ...)
62
71
  # @raise [HTTPError, ProtocolError, NetworkError]
@@ -85,8 +94,9 @@ module Keycardai
85
94
 
86
95
  # Impersonate a named user: a substitute-user token exchange for
87
96
  # privileged operations performed on the user's behalf. No actor token
88
- # is sent; the authorization server derives the acting party from client
89
- # authentication and records it in the issued token's act chain.
97
+ # is sent even when an actor source is configured; the authorization
98
+ # server derives the acting party from client authentication and records
99
+ # it in the issued token's act chain.
90
100
  #
91
101
  # @param user_identifier [String] the target user (becomes sub)
92
102
  # @param resource [String] target resource for the issued token
@@ -98,13 +108,13 @@ module Keycardai
98
108
  def impersonate(user_identifier:, resource:, scope: nil, issuer: nil)
99
109
  raise ArgumentError, "resource must be a non-empty string" if resource.nil? || resource.empty?
100
110
 
101
- exchange_token(
102
- subject_token: OAuth.build_substitute_user_token(user_identifier),
103
- subject_token_type: TokenType::SUBSTITUTE_USER,
104
- resource: resource,
105
- scope: scope,
106
- issuer: issuer
107
- )
111
+ overrides = {
112
+ "subject_token_type" => TokenType::SUBSTITUTE_USER,
113
+ "resource" => resource,
114
+ "scope" => scope
115
+ }.compact
116
+ post_exchange(OAuth.build_substitute_user_token(user_identifier), overrides, issuer || @issuer,
117
+ include_actor: false)
108
118
  end
109
119
 
110
120
  private
@@ -115,25 +125,35 @@ module Keycardai
115
125
 
116
126
  # An explicit client_assertion authenticates the client on its own, so
117
127
  # the credential adds no Basic header and prepares no assertion.
118
- def post_exchange(subject_token, overrides, issuer)
128
+ def post_exchange(subject_token, overrides, issuer, include_actor: true)
119
129
  params = { "grant_type" => GrantType::TOKEN_EXCHANGE, "subject_token" => subject_token,
120
130
  "subject_token_type" => TokenType::ACCESS_TOKEN }.merge(overrides)
121
- return post_token_request(params, issuer: issuer, authorization: nil) if overrides["client_assertion"]
131
+ if overrides["client_assertion"]
132
+ params = with_actor(params) if include_actor
133
+ return post_token_request(params, issuer: issuer, authorization: nil)
134
+ end
122
135
 
123
136
  authorization = @credential&.authorization_header(issuer: issuer)
124
137
  reject_client_id_with_basic(overrides, authorization)
138
+ params = with_actor(params) if include_actor
125
139
  params = with_assertion(params, issuer) if @credential && !authorization
126
140
  post_token_request(params, issuer: issuer, authorization: authorization)
127
141
  end
128
142
 
129
143
  # A request client_id never travels beside HTTP Basic: fail before any
130
- # HTTP request, including discovery.
144
+ # HTTP request, including discovery, and before calling the actor source.
131
145
  def reject_client_id_with_basic(overrides, authorization)
132
146
  return unless overrides.key?("client_id") && authorization&.match?(/\ABasic\s/i)
133
147
 
134
148
  raise ConfigurationError, "token exchange client_id cannot be sent with HTTP Basic"
135
149
  end
136
150
 
151
+ def with_actor(params)
152
+ return params if !@actor || params.key?("actor_token")
153
+
154
+ params.merge("actor_token" => WorkloadIdentity.fetch_token(@actor), "actor_token_type" => TokenType::JWT)
155
+ end
156
+
137
157
  def with_assertion(params, issuer)
138
158
  prepared = @credential.prepare_token_exchange_request(
139
159
  subject_token: params.fetch("subject_token"), resource: params["resource"],
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Keycardai
4
+ module OAuth
5
+ # Prepared exchange parameters retain their Hash API and wire values.
6
+ class TokenExchangeForm < Hash
7
+ include PrintedForm
8
+
9
+ def self.build(subject_token:, resource:, audience:, scope:, authentication: {})
10
+ params = {
11
+ "grant_type" => GrantType::TOKEN_EXCHANGE,
12
+ "subject_token" => subject_token,
13
+ "subject_token_type" => TokenType::ACCESS_TOKEN,
14
+ "resource" => resource,
15
+ "audience" => audience,
16
+ "scope" => scope
17
+ }
18
+ self[params.compact.merge(authentication)]
19
+ end
20
+
21
+ def inspect
22
+ to_h.except("subject_token", "actor_token", "client_assertion", "client_secret").inspect
23
+ end
24
+ end
25
+ private_constant :TokenExchangeForm
26
+ end
27
+ end
@@ -8,6 +8,8 @@ module Keycardai
8
8
  # endpoint discovery with caching, shared-secret (HTTP Basic) client
9
9
  # authentication, and RFC 6749 §5.2 error parsing. Not public API.
10
10
  module TokenRequests
11
+ include PrintedForm
12
+
11
13
  # Default lifetime of a discovered token endpoint, in seconds; the same
12
14
  # knob and default as the JWKS keyring's jwks_uri cache.
13
15
  DEFAULT_DISCOVERY_TTL = 3600
@@ -61,6 +63,14 @@ module Keycardai
61
63
  status: response.status, body: response.body)
62
64
  end
63
65
 
66
+ # Shows the issuer and the credential's class. A credential defined
67
+ # outside the SDK may print its own secrets.
68
+ #
69
+ # @return [String]
70
+ def inspect
71
+ "#<#{self.class} issuer=#{@issuer.inspect}, credential=#{PrintedForm.type_of(@credential)}>"
72
+ end
73
+
64
74
  private
65
75
 
66
76
  def initialize_token_client(issuer:, credential:, client_id:, client_secret:, http_client:, timeout:,
@@ -98,11 +98,14 @@ module Keycardai
98
98
  response = begin
99
99
  @http_client.get(url, headers: { "Metadata-Flavor" => "Google" }, timeout: @timeout)
100
100
  rescue NetworkError, ResponseBodyTooLargeError => e
101
- raise WorkloadIdentityRuntimeError.new("metadata server unreachable: #{e.message}", source: "gcp-metadata")
101
+ retryable = e.is_a?(NetworkError) || e.retryable?
102
+ raise WorkloadIdentityRuntimeError.new("metadata server unreachable: #{e.message}",
103
+ source: "gcp-metadata", retryable: retryable)
102
104
  end
103
105
  unless response.success?
106
+ retryable = response.status == 429 || response.status >= 500
104
107
  raise WorkloadIdentityRuntimeError.new("metadata server returned HTTP #{response.status}",
105
- source: "gcp-metadata")
108
+ source: "gcp-metadata", retryable: retryable)
106
109
  end
107
110
 
108
111
  response.body
@@ -118,6 +121,11 @@ module Keycardai
118
121
  class FlyTokenSource
119
122
  DEFAULT_SOCKET_PATH = "/.fly/api"
120
123
  TOKEN_PATH = "/v1/tokens/oidc"
124
+ TRANSIENT_SOCKET_ERRORS = [
125
+ Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::ECONNABORTED,
126
+ Errno::ETIMEDOUT, Errno::EPIPE, Errno::EAGAIN, Errno::EWOULDBLOCK,
127
+ Errno::EINTR
128
+ ].freeze
121
129
 
122
130
  # @param audience [String, nil] included as {"aud": audience} when set
123
131
  # @param socket_path [String]
@@ -132,7 +140,9 @@ module Keycardai
132
140
  body = JSON.dump(@audience ? { "aud" => @audience } : {})
133
141
  status, response_body = post_over_socket(body)
134
142
  unless (200..299).cover?(status)
135
- raise WorkloadIdentityRuntimeError.new("fly API returned HTTP #{status}", source: "fly")
143
+ retryable = status == 429 || status >= 500
144
+ raise WorkloadIdentityRuntimeError.new("fly API returned HTTP #{status}",
145
+ source: "fly", retryable: retryable)
136
146
  end
137
147
 
138
148
  response_body
@@ -154,8 +164,9 @@ module Keycardai
154
164
  parse_http_response(socket.read)
155
165
  end
156
166
  rescue SystemCallError => e
167
+ retryable = TRANSIENT_SOCKET_ERRORS.any? { |err| e.is_a?(err) }
157
168
  raise WorkloadIdentityRuntimeError.new("fly API socket #{@socket_path} unreachable: #{e.message}",
158
- source: "fly")
169
+ source: "fly", retryable: retryable)
159
170
  end
160
171
 
161
172
  def parse_http_response(raw)
@@ -28,6 +28,19 @@ module Keycardai
28
28
  TokenResponse = Data.define(
29
29
  :access_token, :token_type, :expires_in, :scope, :issued_token_type, :refresh_token, :id_token, :raw
30
30
  ) do
31
+ include PrintedForm::Serializable
32
+
33
+ # Shows every member except the access, refresh, and ID tokens, and
34
+ # only the field names of +raw+. #to_h and +raw+ keep the tokens, so a
35
+ # stored response can be used.
36
+ #
37
+ # @return [String]
38
+ def inspect
39
+ shown = to_h.except(:access_token, :refresh_token, :id_token, :raw)
40
+ .map { |name, value| "#{name}=#{value.inspect}" }
41
+ "#<data #{self.class} #{shown.join(", ")}, raw=#{raw.to_h.keys.inspect}>"
42
+ end
43
+
31
44
  # @param payload [Hash] the parsed token-endpoint response body
32
45
  # @return [TokenResponse]
33
46
  # @raise [ProtocolError] invalid_response when the response has no
@@ -21,6 +21,15 @@ module Keycardai
21
21
  # #subject and #client_id are RFC 9068. The other two are Keycard claims
22
22
  # and are absent from a non-Keycard token, so they return nil there.
23
23
  AccessToken = Data.define(:token, :claims) do
24
+ include PrintedForm::Serializable
25
+
26
+ # Shows the claims and leaves out the bearer token. #token keeps it.
27
+ #
28
+ # @return [String]
29
+ def inspect
30
+ "#<data #{self.class} claims=#{claims.inspect}>"
31
+ end
32
+
24
33
  # @return [String] the token's subject: the user for a user-present
25
34
  # token, the application for an application token
26
35
  def subject
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Keycardai
4
4
  module OAuth
5
- VERSION = "0.13.0"
5
+ VERSION = "0.14.0"
6
6
  end
7
7
  end
@@ -14,6 +14,8 @@ module Keycardai
14
14
  # Holds no shared secret and contributes no Basic header. Never reads
15
15
  # environment variables; the caller supplies storage configuration.
16
16
  class WebIdentity
17
+ include PrintedForm
18
+
17
19
  # @param client_id [String, nil] the registered OAuth client id, signed
18
20
  # as the assertion's iss and sub; required for client authentication
19
21
  # @param server_name [String, nil] sanitized into the key id when no
@@ -38,6 +40,13 @@ module Keycardai
38
40
  @key_manager.key_id
39
41
  end
40
42
 
43
+ # Shows the client ID and the key ID. Never shows the private key.
44
+ #
45
+ # @return [String]
46
+ def inspect
47
+ "#<#{self.class} client_id=#{@client_id.inspect}, key_id=#{key_id.inspect}>"
48
+ end
49
+
41
50
  # Assertion-based authentication contributes no Basic header.
42
51
  #
43
52
  # @param issuer [String, nil] unused; part of the Credential interface
@@ -63,14 +72,9 @@ module Keycardai
63
72
  raise ConfigurationError, "WebIdentity requires the token_endpoint as the assertion audience"
64
73
  end
65
74
 
66
- {
67
- "grant_type" => GrantType::TOKEN_EXCHANGE,
68
- "subject_token" => subject_token,
69
- "subject_token_type" => TokenType::ACCESS_TOKEN,
70
- "resource" => resource,
71
- "audience" => audience,
72
- "scope" => scope
73
- }.compact.merge(client_authentication(issuer: issuer, endpoint: token_endpoint).params)
75
+ authentication = client_authentication(issuer: issuer, endpoint: token_endpoint)
76
+ TokenExchangeForm.build(subject_token: subject_token, resource: resource, audience: audience, scope: scope,
77
+ authentication: authentication.params)
74
78
  end
75
79
 
76
80
  # Client authentication for one request: a newly signed client assertion
@@ -11,6 +11,8 @@ module Keycardai
11
11
  #
12
12
  # Holds no shared secret and contributes no Basic header.
13
13
  class WorkloadIdentity
14
+ include PrintedForm
15
+
14
16
  attr_reader :client_id
15
17
 
16
18
  # @param source [#identity_token, #call] supplies the platform-signed
@@ -22,10 +24,59 @@ module Keycardai
22
24
  # @raise [ConfigurationError] when the source is missing or has neither
23
25
  # an identity_token method nor call
24
26
  def initialize(source:, client_id: nil)
25
- @source = normalize_source(source)
27
+ @source = self.class.normalize_source(source)
26
28
  @client_id = client_id
27
29
  end
28
30
 
31
+ # Normalize an identity-token source: return an object that responds to
32
+ # +identity_token+, wrap a bare callable in +FunctionTokenSource+, or
33
+ # raise +ConfigurationError+.
34
+ #
35
+ # @param source [#identity_token, #call]
36
+ # @return [#identity_token]
37
+ # @raise [ConfigurationError]
38
+ def self.normalize_source(source)
39
+ return source if source.respond_to?(:identity_token)
40
+ return FunctionTokenSource.new(source) if source.respond_to?(:call)
41
+
42
+ raise ConfigurationError, "WorkloadIdentity source must respond to identity_token or call"
43
+ end
44
+
45
+ # Fetch a token from a normalized identity-token source. Passes
46
+ # +WorkloadIdentityConfigurationError+ and +WorkloadIdentityRuntimeError+
47
+ # through untouched, and wraps any other failure or empty token in
48
+ # +WorkloadIdentityRuntimeError+ with the source identifier and cause.
49
+ #
50
+ # @param source [#identity_token]
51
+ # @return [String]
52
+ # @raise [WorkloadIdentityConfigurationError, WorkloadIdentityRuntimeError]
53
+ def self.fetch_token(source)
54
+ token = source.identity_token
55
+ if token.nil? || token.empty?
56
+ raise WorkloadIdentityRuntimeError.new("identity token source returned an empty token",
57
+ source: source_identifier_for(source))
58
+ end
59
+
60
+ token
61
+ rescue WorkloadIdentityRuntimeError, WorkloadIdentityConfigurationError
62
+ raise
63
+ rescue StandardError => e
64
+ raise WorkloadIdentityRuntimeError.new("identity token source failed: #{e.message}",
65
+ source: source_identifier_for(source))
66
+ end
67
+
68
+ def self.source_identifier_for(source)
69
+ source.respond_to?(:source_identifier) ? source.source_identifier : "custom"
70
+ end
71
+ private_class_method :source_identifier_for
72
+
73
+ # Shows the client ID and the source's class.
74
+ #
75
+ # @return [String]
76
+ def inspect
77
+ "#<#{self.class} client_id=#{@client_id.inspect}, source=#{PrintedForm.type_of(@source)}>"
78
+ end
79
+
29
80
  # Assertion-based authentication contributes no Basic header.
30
81
  #
31
82
  # @param issuer [String, nil] unused; part of the Credential interface
@@ -47,14 +98,9 @@ module Keycardai
47
98
  # @raise [WorkloadIdentityRuntimeError] the source failed to produce a token
48
99
  def prepare_token_exchange_request(subject_token:, resource: nil, audience: nil, scope: nil,
49
100
  token_endpoint: nil, issuer: nil)
50
- {
51
- "grant_type" => GrantType::TOKEN_EXCHANGE,
52
- "subject_token" => subject_token,
53
- "subject_token_type" => TokenType::ACCESS_TOKEN,
54
- "resource" => resource,
55
- "audience" => audience,
56
- "scope" => scope
57
- }.compact.merge(client_authentication(issuer: issuer, endpoint: token_endpoint).params)
101
+ authentication = client_authentication(issuer: issuer, endpoint: token_endpoint)
102
+ TokenExchangeForm.build(subject_token: subject_token, resource: resource, audience: audience, scope: scope,
103
+ authentication: authentication.params)
58
104
  end
59
105
 
60
106
  # Client authentication for one request, as form fields: the source's
@@ -91,30 +137,8 @@ module Keycardai
91
137
 
92
138
  private
93
139
 
94
- def normalize_source(source)
95
- return source if source.respond_to?(:identity_token)
96
- return FunctionTokenSource.new(source) if source.respond_to?(:call)
97
-
98
- raise ConfigurationError, "WorkloadIdentity source must respond to identity_token or call"
99
- end
100
-
101
140
  def fetch_identity_token
102
- token = @source.identity_token
103
- if token.nil? || token.empty?
104
- raise WorkloadIdentityRuntimeError.new("identity token source returned an empty token",
105
- source: source_identifier)
106
- end
107
-
108
- token
109
- rescue WorkloadIdentityRuntimeError, WorkloadIdentityConfigurationError
110
- raise
111
- rescue StandardError => e
112
- raise WorkloadIdentityRuntimeError.new("identity token source failed: #{e.message}",
113
- source: source_identifier)
114
- end
115
-
116
- def source_identifier
117
- @source.respond_to?(:source_identifier) ? @source.source_identifier : "custom"
141
+ self.class.fetch_token(@source)
118
142
  end
119
143
 
120
144
  # Adapter making a bare callable usable as an identity-token source.
@@ -2,11 +2,13 @@
2
2
 
3
3
  require_relative "oauth/version"
4
4
  require_relative "oauth/errors"
5
+ require_relative "oauth/printed_form"
5
6
  require_relative "oauth/http"
6
7
  require_relative "oauth/metadata_retry"
7
8
  require_relative "oauth/discovery"
8
9
  require_relative "oauth/userinfo"
9
10
  require_relative "oauth/token_types"
11
+ require_relative "oauth/token_exchange_form"
10
12
  require_relative "oauth/token_requests"
11
13
  require_relative "oauth/client_authentication"
12
14
  require_relative "oauth/substitute_user"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: keycardai-oauth
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.13.0
4
+ version: 0.14.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Keycard
@@ -54,10 +54,12 @@ files:
54
54
  - lib/keycardai/oauth/jwt_verifier.rb
55
55
  - lib/keycardai/oauth/metadata_retry.rb
56
56
  - lib/keycardai/oauth/pkce.rb
57
+ - lib/keycardai/oauth/printed_form.rb
57
58
  - lib/keycardai/oauth/private_key.rb
58
59
  - lib/keycardai/oauth/registration.rb
59
60
  - lib/keycardai/oauth/substitute_user.rb
60
61
  - lib/keycardai/oauth/token_exchange_client.rb
62
+ - lib/keycardai/oauth/token_exchange_form.rb
61
63
  - lib/keycardai/oauth/token_requests.rb
62
64
  - lib/keycardai/oauth/token_revocation.rb
63
65
  - lib/keycardai/oauth/token_sources.rb