Module: Legion::Extensions::Github::Helpers::Client

Constant Summary collapse

CREDENTIAL_RESOLVERS =
%i[
  resolve_vault_delegated resolve_settings_delegated
  resolve_broker_app
  resolve_vault_app resolve_settings_app
  resolve_vault_pat resolve_settings_pat
  resolve_gh_cli resolve_env
].freeze

Constants included from TokenCache

TokenCache::TOKEN_BUFFER_SECONDS

Instance Method Summary collapse

Methods included from ScopeRegistry

#credential_fingerprint, #invalidate_scope, #mark_rate_limited, #rate_limited?, #register_scope, #scope_status

Methods included from TokenCache

#fetch_token, #mark_rate_limited, #rate_limited?, #store_token

Instance Method Details

#connection(owner: nil, repo: nil, api_url: 'https://api.github.com', token: nil, **_opts) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/legion/extensions/github/helpers/client.rb', line 24

def connection(owner: nil, repo: nil, api_url: 'https://api.github.com', token: nil, **_opts)
  resolved = token ? { token: token } : resolve_credential(owner: owner, repo: repo)
  resolved_token = resolved&.dig(:token)
  @current_credential = resolved
  @skipped_fingerprints = []

  Faraday.new(url: api_url) do |conn|
    conn.use :github_credential_fallback, resolver: self
    conn.request :json
    conn.response :json, content_type: /\bjson$/
    conn.response :github_rate_limit, handler: self
    conn.response :github_scope_probe, handler: self
    conn.headers['Accept'] = 'application/vnd.github+json'
    conn.headers['Authorization'] = "Bearer #{resolved_token}" if resolved_token
    conn.headers['X-GitHub-Api-Version'] = '2022-11-28'
  end
end

#gh_cli_token_outputObject



294
295
296
297
298
299
300
301
# File 'lib/legion/extensions/github/helpers/client.rb', line 294

def gh_cli_token_output
  output = `gh auth token 2>/dev/null`.strip
  return nil unless $?&.success? && !output.empty? # rubocop:disable Style/SpecialGlobalVars

  output
rescue StandardError => _e
  nil
end

#max_fallback_retriesObject



68
69
70
# File 'lib/legion/extensions/github/helpers/client.rb', line 68

def max_fallback_retries
  CREDENTIAL_RESOLVERS.size
end

#on_rate_limit(remaining:, reset_at:, status:, url:) ⇒ Object

rubocop:disable Lint/UnusedMethodArgument



72
73
74
75
76
77
# File 'lib/legion/extensions/github/helpers/client.rb', line 72

def on_rate_limit(remaining:, reset_at:, status:, url:, **) # rubocop:disable Lint/UnusedMethodArgument
  fingerprint = @current_credential&.dig(:metadata, :credential_fingerprint)
  return unless fingerprint

  mark_rate_limited(fingerprint: fingerprint, reset_at: reset_at)
end

#on_scope_authorized(status:, url:, path:) ⇒ Object

rubocop:disable Lint/UnusedMethodArgument



87
88
89
90
91
92
93
# File 'lib/legion/extensions/github/helpers/client.rb', line 87

def on_scope_authorized(status:, url:, path:, **) # rubocop:disable Lint/UnusedMethodArgument
  fingerprint = @current_credential&.dig(:metadata, :credential_fingerprint)
  owner, repo = extract_owner_repo(path)
  return unless fingerprint && owner

  register_scope(fingerprint: fingerprint, owner: owner, repo: repo, status: :authorized)
end

#on_scope_denied(status:, url:, path:) ⇒ Object

rubocop:disable Lint/UnusedMethodArgument



79
80
81
82
83
84
85
# File 'lib/legion/extensions/github/helpers/client.rb', line 79

def on_scope_denied(status:, url:, path:, **) # rubocop:disable Lint/UnusedMethodArgument
  fingerprint = @current_credential&.dig(:metadata, :credential_fingerprint)
  owner, repo = extract_owner_repo(path)
  return unless fingerprint && owner

  register_scope(fingerprint: fingerprint, owner: owner, repo: repo, status: :denied)
end

#resolve_broker_appObject



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/legion/extensions/github/helpers/client.rb', line 143

def resolve_broker_app
  return nil unless defined?(Legion::Identity::Broker)

  token = Legion::Identity::Broker.token_for(:github)
  return nil unless token

  lease = Legion::Identity::Broker.lease_for(:github)
  installation_id = lease&.&.dig(:installation_id) || 'unknown'
  fp = credential_fingerprint(auth_type:  :app_installation,
                              identifier: "broker_app_#{installation_id}")
  { token: token, auth_type: :app_installation,
    metadata: { source: :broker, credential_type: :installation_token,
                credential_fingerprint: fp } }
rescue StandardError => _e
  nil
end

#resolve_credential(owner: nil, repo: nil) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/legion/extensions/github/helpers/client.rb', line 95

def resolve_credential(owner: nil, repo: nil)
  CREDENTIAL_RESOLVERS.each do |method|
    next unless respond_to?(method, true)

    result = send(method)
    next unless result

    fingerprint = result.dig(:metadata, :credential_fingerprint)

    next if fingerprint && rate_limited?(fingerprint: fingerprint)

    if owner && fingerprint
      scope = scope_status(fingerprint: fingerprint, owner: owner, repo: repo)
      next if scope == :denied
    end

    return result
  end
  nil
end

#resolve_envObject



303
304
305
306
307
308
309
# File 'lib/legion/extensions/github/helpers/client.rb', line 303

def resolve_env
  token = ENV.fetch('GITHUB_TOKEN', nil)
  return nil if token.nil? || token.empty?

  fp = credential_fingerprint(auth_type: :env, identifier: 'env')
  { token: token, auth_type: :env, metadata: { source: :env, credential_fingerprint: fp } }
end

#resolve_gh_cliObject



276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/legion/extensions/github/helpers/client.rb', line 276

def resolve_gh_cli
  if cache_connected? || local_cache_connected?
    cached = cache_connected? ? cache_get('github:cli_token') : local_cache_get('github:cli_token')
    return cached if cached
  end

  output = gh_cli_token_output
  return nil unless output

  fp = credential_fingerprint(auth_type: :cli, identifier: 'gh_cli')
  result = { token: output, auth_type: :cli, metadata: { source: :gh_cli, credential_fingerprint: fp } }
  cache_set('github:cli_token', result, ttl: 300) if cache_connected?
  local_cache_set('github:cli_token', result, ttl: 300) if local_cache_connected?
  result
rescue StandardError => _e
  nil
end

#resolve_next_credential(owner: nil, repo: nil) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/legion/extensions/github/helpers/client.rb', line 42

def resolve_next_credential(owner: nil, repo: nil)
  fingerprint = @current_credential&.dig(:metadata, :credential_fingerprint)
  @skipped_fingerprints ||= []
  @skipped_fingerprints << fingerprint if fingerprint

  CREDENTIAL_RESOLVERS.each do |method|
    next unless respond_to?(method, true)

    result = send(method)
    next unless result

    fp = result.dig(:metadata, :credential_fingerprint)
    next if fp && @skipped_fingerprints.include?(fp)
    next if fp && rate_limited?(fingerprint: fp)

    if owner && fp
      scope = scope_status(fingerprint: fp, owner: owner, repo: repo)
      next if scope == :denied
    end

    @current_credential = result
    return result
  end
  nil
end

#resolve_settings_appObject



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/legion/extensions/github/helpers/client.rb', line 205

def resolve_settings_app
  return nil unless defined?(Legion::Settings)

  app_id = begin
    Legion::Settings.dig(:github, :app, :app_id)
  rescue StandardError => _e
    nil
  end
  return nil unless app_id

  fp = credential_fingerprint(auth_type: :app_installation, identifier: "settings_app_#{app_id}")

  key_path = begin
    Legion::Settings.dig(:github, :app, :private_key_path)
  rescue StandardError => _e
    nil
  end
  installation_id = begin
    Legion::Settings.dig(:github, :app, :installation_id)
  rescue StandardError => _e
    nil
  end
  return nil unless key_path && installation_id

  cached = fetch_token(auth_type: :app_installation, installation_id: installation_id)
  return cached.merge(metadata: { source: :settings, credential_fingerprint: fp }) if cached

  private_key = ::File.read(key_path)
  jwt = generate_jwt(app_id: app_id, private_key: private_key)[:result]
  token_data = create_installation_token(jwt: jwt, installation_id: installation_id)[:result]
  return nil unless token_data&.dig('token')

  expires_at = begin
    Time.parse(token_data['expires_at'])
  rescue StandardError => _e
    Time.now + 3600
  end
  result = { token: token_data['token'], auth_type: :app_installation,
             expires_at: expires_at, installation_id: installation_id,
             metadata: { source: :settings, installation_id: installation_id,
                         credential_fingerprint: fp } }
  store_token(**result)
  result
rescue StandardError => _e
  nil
end

#resolve_settings_delegatedObject



130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/legion/extensions/github/helpers/client.rb', line 130

def resolve_settings_delegated
  return nil unless defined?(Legion::Settings)

  token = Legion::Settings.dig(:github, :oauth, :access_token)
  return nil unless token

  fp = credential_fingerprint(auth_type: :oauth_user, identifier: 'settings_delegated')
  { token: token, auth_type: :oauth_user,
    metadata: { source: :settings, credential_fingerprint: fp } }
rescue StandardError => _e
  nil
end

#resolve_settings_patObject



264
265
266
267
268
269
270
271
272
273
274
# File 'lib/legion/extensions/github/helpers/client.rb', line 264

def resolve_settings_pat
  return nil unless defined?(Legion::Settings)

  token = Legion::Settings.dig(:github, :token)
  return nil unless token

  fp = credential_fingerprint(auth_type: :pat, identifier: 'settings_pat')
  { token: token, auth_type: :pat, metadata: { source: :settings, credential_fingerprint: fp } }
rescue StandardError => _e
  nil
end

#resolve_vault_appObject



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/legion/extensions/github/helpers/client.rb', line 160

def resolve_vault_app
  return nil unless defined?(Legion::Crypt)

  private_key = begin
    vault_get('github/app/private_key')
  rescue StandardError => _e
    nil
  end
  return nil unless private_key

  app_id = begin
    vault_get('github/app/app_id')
  rescue StandardError => _e
    nil
  end
  installation_id = begin
    vault_get('github/app/installation_id')
  rescue StandardError => _e
    nil
  end
  return nil unless app_id && installation_id

  fp = credential_fingerprint(auth_type: :app_installation, identifier: "vault_app_#{app_id}")
  cached = fetch_token(auth_type: :app_installation, installation_id: installation_id)
  return cached.merge(metadata: { source: :vault, credential_fingerprint: fp }) if cached

  jwt = generate_jwt(app_id: app_id, private_key: private_key)[:result]
  token_data = create_installation_token(jwt: jwt, installation_id: installation_id)[:result]
  return nil unless token_data&.dig('token')

  expires_at = begin
    Time.parse(token_data['expires_at'])
  rescue StandardError => _e
    Time.now + 3600
  end
  result = { token: token_data['token'], auth_type: :app_installation,
             expires_at: expires_at, installation_id: installation_id,
             metadata: { source: :vault, installation_id: installation_id,
                         credential_fingerprint: fp } }
  store_token(**result)
  result
rescue StandardError => _e
  nil
end

#resolve_vault_delegatedObject



116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/legion/extensions/github/helpers/client.rb', line 116

def resolve_vault_delegated
  return nil unless defined?(Legion::Crypt)

  token_data = vault_get('github/oauth/delegated/token')
  return nil unless token_data&.dig('access_token')

  fp = credential_fingerprint(auth_type: :oauth_user, identifier: 'vault_delegated')
  { token: token_data['access_token'], auth_type: :oauth_user,
    expires_at: token_data['expires_at'],
    metadata: { source: :vault, credential_fingerprint: fp } }
rescue StandardError => _e
  nil
end

#resolve_vault_patObject



252
253
254
255
256
257
258
259
260
261
262
# File 'lib/legion/extensions/github/helpers/client.rb', line 252

def resolve_vault_pat
  return nil unless defined?(Legion::Crypt)

  token = vault_get('github/token')
  return nil unless token

  fp = credential_fingerprint(auth_type: :pat, identifier: 'vault_pat')
  { token: token, auth_type: :pat, metadata: { source: :vault, credential_fingerprint: fp } }
rescue StandardError => _e
  nil
end