keycardai-oauth 0.12.0 → 0.13.1

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: 7ccdb651e530f4a1ad780531eef59ed0d02f30a96bebb4104f9010ea4f784b24
4
- data.tar.gz: 8942a274d0a490f8faadb19348b547b74f09f03ba90252d2bc3ee77e12715dd1
3
+ metadata.gz: bea3543557872871f3bf07497a4726dd80c93a7952bfc287de9c839549aafa86
4
+ data.tar.gz: 7387d40704ed417795864ad8130d709c9242c65724193ddab8a0be1a0da424d1
5
5
  SHA512:
6
- metadata.gz: 8d6292413c8a8efbf361a3bbed96ebdfb22f53a60cd27b367a16b234cfbd7872a2f2401091ba4acfe97633b0658939c600158a829dc4c3bf880323706f374415
7
- data.tar.gz: 4e788c4f977841dea9409c7001e79d64cc2fa340a48ffa7e4c01ca24c076423a09c1005038859de39107d269234df78017bffc89ee1aca8b0c41800cb7893612
6
+ metadata.gz: e4a24f1daa6c4e6d845fe6a9d0914f4b2f59bd73f1ccffa78609b617b231d49c1d648d6b457c797e2cb6df87d7c2428e4bea9396471fa6e39969692504fb4f06
7
+ data.tar.gz: dcd880b7d247b572d9e7b390b850f2058b9e0241358e8920d1c79bd5c704cbc043096cd71c2e464c33377099d1e44305df04644f23d8982d510b8b0686a7ecae
data/CHANGELOG.md CHANGED
@@ -15,6 +15,37 @@ 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.13.1-keycardai-oauth (2026-11-26)
19
+
20
+
21
+ - fix(keycardai-oauth): leave tokens and secrets out of printed forms (SDK-126) (#105)
22
+ - * fix(keycardai-oauth): leave tokens and secrets out of printed forms
23
+ - TokenResponse, AccessToken, ClientRegistrationResponse and PKCE::Pair
24
+ leave their secrets out of inspect, to_s and pp. The token clients,
25
+ DeviceAuthorizationClient, WebIdentity, WorkloadIdentity,
26
+ PrivateKeyManager and JWTSigner show identifiers and the credential's
27
+ class only. to_h, raw and the readers keep the values.
28
+ - Refs SDK-126, keycard-sdk-spec#113.
29
+ - (cherry picked from commit e7189b803d47384f4620b5799301b283fcb60cb2)
30
+ - * fix(keycardai-oauth): keep client authentication values out of to_json
31
+ - 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.
32
+ - ---------
33
+ - Co-authored-by: Larry Osakwe <23560354+Larry-Osakwe@users.noreply.github.com>
34
+
35
+ ## 0.13.0-keycardai-oauth (2026-11-26)
36
+
37
+
38
+ - feat(keycardai-oauth): discover the application credential from the environment (SDK-6) (#99)
39
+ - * feat(keycardai-oauth): discover the application credential from the environment (SDK-6)
40
+ - Implements keycardai/keycard-sdk-spec credential-discovery.md v2
41
+ - Refs SDK-6
42
+ - Co-Authored-By: Larry Osakwe <larry@keycard.ai>
43
+ - * docs: count token revocation in the conformance summary
44
+ - ---------
45
+ - Co-authored-by: devin-ai-keycard <devin-ai@keycard.ai>
46
+ Co-authored-by: Larry Osakwe <larry@keycard.ai>
47
+ Co-authored-by: Larry Osakwe <23560354+Larry-Osakwe@users.noreply.github.com>
48
+
18
49
  ## 0.12.0-keycardai-oauth (2026-11-25)
19
50
 
20
51
 
data/README.md CHANGED
@@ -23,11 +23,37 @@ Capabilities:
23
23
  - UserInfo: the signed-in user's identity claims (OIDC Core 1.0 §5.3)
24
24
  - JWT signing and verification, JWKS keyring with caching
25
25
  - Application credentials: ClientSecret (incl. multi-zone), WebIdentity (RFC 7523),
26
- WorkloadIdentity with pluggable identity token sources
26
+ WorkloadIdentity with pluggable identity token sources, and opt-in discovery
27
27
  - AccessContext: the non-throwing per-request container for delegated tokens
28
28
 
29
29
  ## Quickstart
30
30
 
31
+ ### Discover an application credential
32
+
33
+ ```ruby
34
+ require "keycardai/oauth"
35
+
36
+ credential = Keycardai::OAuth.discover_application_credential
37
+ ```
38
+
39
+ Discovery runs only when called. It reads the process environment by default,
40
+ or an explicit string-keyed mapping passed as `env:`. It discovers a client
41
+ secret from `KEYCARD_CLIENT_ID` and `KEYCARD_CLIENT_SECRET`, workload identity
42
+ from the first non-empty variable in the `FileTokenSource` discovery list, or
43
+ web identity from `KEYCARD_WEB_IDENTITY_KEY_STORAGE_DIR`.
44
+
45
+ Set `KEYCARD_APPLICATION_CREDENTIAL_TYPE` to `client_secret`,
46
+ `workload_identity`, or `web_identity` to choose one when multiple types are
47
+ configured. `eks_workload_identity` is a deprecated alias for
48
+ `workload_identity`. Selecting `web_identity` without a storage directory uses
49
+ the WebIdentity default, and `web_identity_server_name:` supplies its key name.
50
+ A discovered WebIdentity has no registered client id; construct it explicitly
51
+ with `client_id:` for operations that sign client assertions.
52
+
53
+ Discovery configuration errors raise `Keycardai::OAuth::CredentialDiscoveryError`
54
+ with a symbolic `reason` and a `resolvable` list. Pass the zone URL separately;
55
+ credential discovery does not read `KEYCARD_ZONE_URL`.
56
+
31
57
  ### Verify an inbound token
32
58
 
33
59
  ```ruby
@@ -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
@@ -43,7 +39,7 @@ module Keycardai
43
39
  # client_authentication, or when neither credential nor a non-empty
44
40
  # client_id is set. A credential that responds to
45
41
  # check_client_authentication is checked with it, so a WorkloadIdentity
46
- # without client_id raises here. Call it before any request.
42
+ # or WebIdentity without client_id raises here. Call it before any request.
47
43
  #
48
44
  # @raise [ConfigurationError]
49
45
  def validate(credential:, client_id:, client_secret: nil)
@@ -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
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Keycardai
4
+ # OAuth primitives and application credentials for Keycard.
5
+ module OAuth
6
+ # Builds the application credential described by the environment.
7
+ #
8
+ # @param env [#[]] mapping with environment variable names as string keys
9
+ # @param web_identity_server_name [String, nil] name used for the WebIdentity key id
10
+ # @return [ClientSecret, WorkloadIdentity, WebIdentity]
11
+ # @raise [CredentialDiscoveryError] the configuration does not select a usable credential
12
+ # @raise [WorkloadIdentityConfigurationError] the selected token file is missing or empty
13
+ def self.discover_application_credential(env: ENV, web_identity_server_name: nil)
14
+ CredentialDiscovery.new(env).discover(web_identity_server_name)
15
+ end
16
+
17
+ # Resolves and constructs a credential from one environment mapping.
18
+ class CredentialDiscovery
19
+ include PrintedForm
20
+
21
+ SELECTOR = "KEYCARD_APPLICATION_CREDENTIAL_TYPE"
22
+ STORAGE_DIR = "KEYCARD_WEB_IDENTITY_KEY_STORAGE_DIR"
23
+ TYPES = %w[client_secret workload_identity web_identity].freeze
24
+
25
+ def initialize(env)
26
+ @client_id = value(env, "KEYCARD_CLIENT_ID")
27
+ @client_secret = value(env, "KEYCARD_CLIENT_SECRET")
28
+ @token_file = FileTokenSource::DEFAULT_ENV_VARS.lazy.filter_map { |name| value(env, name) }.first
29
+ @storage_dir = value(env, STORAGE_DIR)
30
+ @selector = value(env, SELECTOR)
31
+ @resolvable = []
32
+ @resolvable << "client_secret" if @client_id && @client_secret
33
+ @resolvable << "workload_identity" if @token_file
34
+ @resolvable << "web_identity" if @storage_dir
35
+ end
36
+
37
+ def discover(web_identity_server_name)
38
+ case @selector ? selected_type : inferred_type
39
+ when "client_secret"
40
+ ClientSecret.new(@client_id, @client_secret)
41
+ when "workload_identity"
42
+ WorkloadIdentity.new(source: FileTokenSource.new(token_file_path: @token_file), client_id: @client_id)
43
+ when "web_identity"
44
+ WebIdentity.new(server_name: web_identity_server_name, storage_dir: @storage_dir)
45
+ end
46
+ end
47
+
48
+ def inspect
49
+ "#<#{self.class} client_id=#{@client_id.inspect}, resolvable=#{@resolvable.inspect}>"
50
+ end
51
+
52
+ private
53
+
54
+ def value(env, name)
55
+ value = env[name]
56
+ value if value && !value.empty?
57
+ end
58
+
59
+ def selected_type
60
+ type = @selector == "eks_workload_identity" ? "workload_identity" : @selector
61
+ fail_discovery(:unknown_type, "Unknown #{SELECTOR}; use one of #{TYPES.join(", ")}") unless TYPES.include?(type)
62
+ return type if type == "web_identity" || @resolvable.include?(type)
63
+
64
+ inputs = if type == "client_secret"
65
+ "both KEYCARD_CLIENT_ID and KEYCARD_CLIENT_SECRET"
66
+ else
67
+ "a token file path in one of #{FileTokenSource::DEFAULT_ENV_VARS.join(", ")}"
68
+ end
69
+ fail_discovery(:not_satisfiable, "#{SELECTOR}=#{type} requires #{inputs}")
70
+ end
71
+
72
+ def inferred_type
73
+ if @client_secret && !@client_id
74
+ fail_discovery(:incomplete, "KEYCARD_CLIENT_SECRET is set without KEYCARD_CLIENT_ID")
75
+ end
76
+ if @resolvable.empty?
77
+ fail_discovery(:absent, "No application credential found in the environment. Set KEYCARD_CLIENT_ID " \
78
+ "and KEYCARD_CLIENT_SECRET, a token file variable, or #{STORAGE_DIR}")
79
+ end
80
+ if @resolvable.size > 1
81
+ fail_discovery(:ambiguous, "The environment configures #{@resolvable.join(" and ")}. " \
82
+ "Set #{SELECTOR} to choose one")
83
+ end
84
+ @resolvable.first
85
+ end
86
+
87
+ def fail_discovery(reason, message)
88
+ raise CredentialDiscoveryError.new(message, reason: reason, resolvable: @resolvable)
89
+ end
90
+ end
91
+ private_constant :CredentialDiscovery
92
+ end
93
+ end
@@ -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
@@ -14,6 +14,20 @@ module Keycardai
14
14
  end
15
15
  end
16
16
 
17
+ # The environment does not describe a single usable application credential.
18
+ class CredentialDiscoveryError < ConfigurationError
19
+ # @return [Symbol] absent, ambiguous, incomplete, unknown_type, or not_satisfiable
20
+ attr_reader :reason
21
+ # @return [Array<String>] canonical credential types the environment configures
22
+ attr_reader :resolvable
23
+
24
+ def initialize(message, reason:, resolvable:)
25
+ super(message)
26
+ @reason = reason
27
+ @resolvable = resolvable.dup.freeze
28
+ end
29
+ end
30
+
17
31
  # A transport-level failure (DNS, TLS, timeout) wrapping the underlying
18
32
  # exception as +cause+.
19
33
  class NetworkError < Keycardai::Error
@@ -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)
@@ -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:,
@@ -10,11 +10,10 @@ module Keycardai
10
10
  # Covers EKS (AWS_* env vars), AKS (AZURE_FEDERATED_TOKEN_FILE), any
11
11
  # Kubernetes projected service-account token, and file-mode CI providers.
12
12
  #
13
- # Path discovery through the well-known env vars below is the one blessed
14
- # environment read in the SDK (a deliberate platform convention). An
15
- # explicit token_file_path wins; env_var_name is consulted first when
16
- # given. The resolved file is validated at construction (exists,
17
- # non-empty), preserving fail-fast behavior.
13
+ # Path discovery through the well-known env vars follows a platform
14
+ # convention. An explicit token_file_path wins; env_var_name is consulted
15
+ # first when given. The resolved file must exist and be non-empty at
16
+ # construction.
18
17
  class FileTokenSource
19
18
  DEFAULT_ENV_VARS = %w[
20
19
  KEYCARD_EKS_WORKLOAD_IDENTITY_TOKEN_FILE
@@ -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.12.0"
5
+ VERSION = "0.13.1"
6
6
  end
7
7
  end
@@ -14,8 +14,10 @@ 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
- # @param client_id [String] the registered OAuth client id, signed as
18
- # the assertion's iss and sub
17
+ include PrintedForm
18
+
19
+ # @param client_id [String, nil] the registered OAuth client id, signed
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
20
22
  # key_id is given
21
23
  # @param key_id [String, nil] explicit key id (the JWT kid); otherwise
@@ -23,11 +25,8 @@ module Keycardai
23
25
  # @param storage [#load, #store, nil] pluggable keypair storage
24
26
  # @param storage_dir [String, nil] directory for the default file store
25
27
  # @param clock [#call] returns the current Time; override in tests
26
- # @raise [ConfigurationError] missing client_id
27
- def initialize(client_id:, server_name: nil, key_id: nil, storage: nil, storage_dir: nil,
28
+ def initialize(client_id: nil, server_name: nil, key_id: nil, storage: nil, storage_dir: nil,
28
29
  clock: -> { Time.now })
29
- raise ConfigurationError, "WebIdentity requires a client_id" if client_id.nil? || client_id.empty?
30
-
31
30
  @client_id = client_id
32
31
  storage ||= FilePrivateKeyStorage.new(dir: storage_dir || FilePrivateKeyStorage::DEFAULT_DIR)
33
32
  @key_manager = PrivateKeyManager.new(
@@ -41,6 +40,13 @@ module Keycardai
41
40
  @key_manager.key_id
42
41
  end
43
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
+
44
50
  # Assertion-based authentication contributes no Basic header.
45
51
  #
46
52
  # @param issuer [String, nil] unused; part of the Credential interface
@@ -59,21 +65,16 @@ module Keycardai
59
65
  # @param scope [String, nil]
60
66
  # @param issuer [String, nil] unused; part of the Credential interface
61
67
  # @return [Hash]
62
- # @raise [ConfigurationError] when token_endpoint is missing
68
+ # @raise [ConfigurationError] when the client_id or token_endpoint is missing
63
69
  def prepare_token_exchange_request(subject_token:, token_endpoint: nil, resource: nil,
64
70
  audience: nil, scope: nil, issuer: nil)
65
71
  if token_endpoint.nil? || token_endpoint.empty?
66
72
  raise ConfigurationError, "WebIdentity requires the token_endpoint as the assertion audience"
67
73
  end
68
74
 
69
- {
70
- "grant_type" => GrantType::TOKEN_EXCHANGE,
71
- "subject_token" => subject_token,
72
- "subject_token_type" => TokenType::ACCESS_TOKEN,
73
- "resource" => resource,
74
- "audience" => audience,
75
- "scope" => scope
76
- }.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)
77
78
  end
78
79
 
79
80
  # Client authentication for one request: a newly signed client assertion
@@ -83,17 +84,25 @@ module Keycardai
83
84
  # @param issuer [String, nil] unused; part of the Credential interface
84
85
  # @param endpoint [String] the assertion audience URL
85
86
  # @return [ClientAuthentication]
86
- # @raise [ConfigurationError] when endpoint is missing
87
+ # @raise [ConfigurationError] when the client_id or endpoint is missing
87
88
  def client_authentication(issuer:, endpoint:)
88
89
  if endpoint.nil? || endpoint.empty?
89
90
  raise ConfigurationError, "WebIdentity requires the endpoint URL as the assertion audience"
90
91
  end
91
92
 
93
+ check_client_authentication
92
94
  assertion = @key_manager.create_client_assertion(client_id: @client_id, audience: endpoint)
93
95
  ClientAuthentication.new(params: { "client_assertion" => assertion,
94
96
  "client_assertion_type" => PrivateKeyManager::ASSERTION_TYPE })
95
97
  end
96
98
 
99
+ # @raise [ConfigurationError] when the client_id is missing
100
+ def check_client_authentication
101
+ return unless @client_id.nil? || @client_id.empty?
102
+
103
+ raise ConfigurationError, "WebIdentity requires a client_id for client authentication"
104
+ end
105
+
97
106
  # The public JWKS the authorization server verifies assertions against.
98
107
  #
99
108
  # @return [Hash] {"keys" => [...]}
@@ -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
@@ -26,6 +28,13 @@ module Keycardai
26
28
  @client_id = client_id
27
29
  end
28
30
 
31
+ # Shows the client ID and the source's class.
32
+ #
33
+ # @return [String]
34
+ def inspect
35
+ "#<#{self.class} client_id=#{@client_id.inspect}, source=#{PrintedForm.type_of(@source)}>"
36
+ end
37
+
29
38
  # Assertion-based authentication contributes no Basic header.
30
39
  #
31
40
  # @param issuer [String, nil] unused; part of the Credential interface
@@ -47,14 +56,9 @@ module Keycardai
47
56
  # @raise [WorkloadIdentityRuntimeError] the source failed to produce a token
48
57
  def prepare_token_exchange_request(subject_token:, resource: nil, audience: nil, scope: nil,
49
58
  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)
59
+ authentication = client_authentication(issuer: issuer, endpoint: token_endpoint)
60
+ TokenExchangeForm.build(subject_token: subject_token, resource: resource, audience: audience, scope: scope,
61
+ authentication: authentication.params)
58
62
  end
59
63
 
60
64
  # Client authentication for one request, as form fields: the source's
@@ -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"
@@ -20,6 +22,7 @@ require_relative "oauth/private_key"
20
22
  require_relative "oauth/web_identity"
21
23
  require_relative "oauth/workload_identity"
22
24
  require_relative "oauth/token_sources"
25
+ require_relative "oauth/credential_discovery"
23
26
  require_relative "oauth/access_context"
24
27
  require_relative "oauth/exchange_tokens"
25
28
  require_relative "oauth/token_verifier"
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.12.0
4
+ version: 0.13.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Keycard
@@ -43,6 +43,7 @@ files:
43
43
  - lib/keycardai/oauth/client_authentication.rb
44
44
  - lib/keycardai/oauth/client_credentials_client.rb
45
45
  - lib/keycardai/oauth/client_secret.rb
46
+ - lib/keycardai/oauth/credential_discovery.rb
46
47
  - lib/keycardai/oauth/device_authorization.rb
47
48
  - lib/keycardai/oauth/discovery.rb
48
49
  - lib/keycardai/oauth/errors.rb
@@ -53,10 +54,12 @@ files:
53
54
  - lib/keycardai/oauth/jwt_verifier.rb
54
55
  - lib/keycardai/oauth/metadata_retry.rb
55
56
  - lib/keycardai/oauth/pkce.rb
57
+ - lib/keycardai/oauth/printed_form.rb
56
58
  - lib/keycardai/oauth/private_key.rb
57
59
  - lib/keycardai/oauth/registration.rb
58
60
  - lib/keycardai/oauth/substitute_user.rb
59
61
  - lib/keycardai/oauth/token_exchange_client.rb
62
+ - lib/keycardai/oauth/token_exchange_form.rb
60
63
  - lib/keycardai/oauth/token_requests.rb
61
64
  - lib/keycardai/oauth/token_revocation.rb
62
65
  - lib/keycardai/oauth/token_sources.rb