studio-engine 0.135.2 → 0.137.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.
Files changed (34) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +64 -11
  3. data/README.md +10 -0
  4. data/app/assets/javascripts/studio/cropper-1.6.2.min.js +10 -0
  5. data/app/assets/javascripts/studio/page_transition_reveal.js +3 -0
  6. data/app/assets/stylesheets/studio/cropper-1.6.2.min.css +9 -0
  7. data/app/controllers/concerns/studio/connection_flow.rb +215 -0
  8. data/app/controllers/concerns/studio/error_handling.rb +58 -1
  9. data/app/controllers/studio/connections_controller.rb +13 -0
  10. data/app/helpers/studio/page_header_helper.rb +26 -0
  11. data/app/helpers/studio_navbar_helper.rb +22 -0
  12. data/app/javascript/studio/application.js +1 -0
  13. data/app/javascript/studio/cropper.js +2 -2
  14. data/app/javascript/studio/page_header_self_styled.js +194 -0
  15. data/app/javascript/studio/page_transitions.js +42 -11
  16. data/app/javascript/studio/reload_visits.js +93 -0
  17. data/app/models/studio/connection.rb +137 -0
  18. data/app/models/studio/user_session.rb +216 -21
  19. data/app/views/layouts/_navbar.html.erb +11 -4
  20. data/app/views/studio/_cropper_assets.html.erb +14 -9
  21. data/app/views/studio/_legal_page.html.erb +52 -0
  22. data/app/views/studio/_page_header.html.erb +12 -2
  23. data/app/views/studio/page_header/_assets.html.erb +151 -0
  24. data/db/migrate/20261108120000_add_device_revocation_to_studio_user_sessions.rb +28 -0
  25. data/db/migrate/20261108130000_create_studio_connections.rb +35 -0
  26. data/lib/generators/studio/connections/connections_generator.rb +93 -0
  27. data/lib/studio/connections/stand_in.rb +89 -0
  28. data/lib/studio/connections.rb +483 -0
  29. data/lib/studio/engine.rb +14 -1
  30. data/lib/studio/host_schema.rb +53 -2
  31. data/lib/studio/page_header.rb +11 -2
  32. data/lib/studio/version.rb +1 -1
  33. data/lib/studio.rb +70 -0
  34. metadata +16 -1
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+
5
+ module Studio
6
+ module Generators
7
+ # Adopt the connections tooling (docs/CONNECTIONS.md) in one repeatable step:
8
+ #
9
+ # bin/rails g studio:connections
10
+ # bin/rails db:migrate
11
+ #
12
+ # What it does, each step idempotent (a second run changes nothing):
13
+ #
14
+ # 1. copies the engine's studio_connections migration into db/migrate,
15
+ # in exactly the form `studio_engine:install:migrations` writes (so that
16
+ # task later sees it and skips it), and ONLY that migration;
17
+ # 2. writes config/initializers/studio_connections.rb, a commented example
18
+ # provider to fill in, unless the file exists.
19
+ #
20
+ # It declares no provider and draws no route: the host names each provider
21
+ # it connects, and its routes, itself.
22
+ class ConnectionsGenerator < Rails::Generators::Base
23
+ MIGRATION_NAME = "create_studio_connections"
24
+ ENGINE_SCOPE = "studio_engine"
25
+ INITIALIZER = "config/initializers/studio_connections.rb"
26
+
27
+ def copy_migration
28
+ existing = Dir.glob(File.join(destination_root, "db/migrate/*_#{MIGRATION_NAME}{,.#{ENGINE_SCOPE}}.rb"))
29
+ if existing.any?
30
+ say_status :identical, existing.first.delete_prefix("#{destination_root}/"), :blue
31
+ return
32
+ end
33
+
34
+ source = self.class.engine_migration
35
+ original_version = File.basename(source)[/\A\d+/]
36
+ body = "# This migration comes from #{ENGINE_SCOPE} (originally #{original_version})\n#{File.read(source)}"
37
+ create_file "db/migrate/#{self.class.next_version}_#{MIGRATION_NAME}.#{ENGINE_SCOPE}.rb", body
38
+ end
39
+
40
+ def write_initializer
41
+ if File.exist?(File.join(destination_root, INITIALIZER))
42
+ say_status :identical, INITIALIZER, :blue
43
+ return
44
+ end
45
+
46
+ create_file INITIALIZER, INITIALIZER_BODY
47
+ end
48
+
49
+ def next_steps
50
+ say <<~TEXT
51
+
52
+ Connections installed. Next:
53
+ bin/rails db:migrate
54
+ Declare each provider in #{INITIALIZER}, then draw its routes in config/routes.rb:
55
+ Studio.draw_connection_routes(self, :files, path: "admin/files", controller: "admin/files")
56
+ Set the provider's client id and secret, and the app's Active Record encryption keys.
57
+ TEXT
58
+ end
59
+
60
+ def self.engine_migration
61
+ File.expand_path("../../../../db/migrate/20261108130000_#{MIGRATION_NAME}.rb", __dir__)
62
+ end
63
+
64
+ def self.next_version
65
+ Time.now.utc.strftime("%Y%m%d%H%M%S")
66
+ end
67
+
68
+ INITIALIZER_BODY = <<~RUBY
69
+ # frozen_string_literal: true
70
+
71
+ # Connections (studio-engine docs/CONNECTIONS.md). One Studio.define_connection
72
+ # per provider this app connects; each stays off until its client id and
73
+ # secret are set. Draw its routes in config/routes.rb with
74
+ # Studio.draw_connection_routes. The example below is a placeholder: no
75
+ # such provider exists.
76
+ #
77
+ # Studio.define_connection :files,
78
+ # label: "Example Files",
79
+ # env: { client_id: "EXAMPLE_FILES_CLIENT_ID", client_secret: "EXAMPLE_FILES_CLIENT_SECRET" },
80
+ # authorize_url: "https://files.example/oauth/authorize",
81
+ # token_url: "https://files.example/oauth/token",
82
+ # revoke_url: "https://files.example/oauth/revoke",
83
+ # scopes: %w[files.read],
84
+ # refresh: :rotating,
85
+ # account: :callback, account_param: "account_id", account_format: /\\A\\d{1,20}\\z/,
86
+ # filter_keys: %w[account_id]
87
+ #
88
+ # Who may connect (default: :require_admin from Studio::ErrorHandling):
89
+ # Studio.connection_admin_guard = :require_admin
90
+ RUBY
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ module Studio
6
+ module Connections
7
+ # A STAND-IN PROVIDER for the e2e lane and a local demo: a host walks a
8
+ # connection with no client registered at the provider. NEVER production
9
+ # (the Provider seams refuse it there).
10
+ #
11
+ # Studio::Connections::StandIn.install!(Studio.connection(:files))
12
+ # Studio::Connections::StandIn.install!(Studio.connection(:tenant),
13
+ # callback_params: { tenant: "00000000-0000-0000-0000-000000000000", admin_consent: "True" })
14
+ #
15
+ # The sign-in page comes straight back to the callback with the stand-in's
16
+ # code (and any callback_params). The token and revoke endpoints are stood
17
+ # in at the HTTP layer (Provider#http), so the real exchange, refresh and
18
+ # rotation run: like a rotating provider, every grant answers a new refresh
19
+ # token and only the LAST one issued for a token URL is honoured, so a
20
+ # refresh that failed to store its new pair shows up as Revoked on the next
21
+ # read. Access tokens live `access_lifetime` seconds. The memory is this
22
+ # process's own.
23
+ module StandIn
24
+ CODE = "studio-connection-stand-in-code"
25
+
26
+ class SignIn
27
+ def initialize(callback_params: {})
28
+ @callback_params = callback_params.to_h
29
+ end
30
+
31
+ def authorize_url(redirect_uri:, state:, account: nil)
32
+ query = { code: CODE }.merge(@callback_params).merge(state:)
33
+ "#{redirect_uri}?#{URI.encode_www_form(query)}"
34
+ end
35
+ end
36
+
37
+ # The token and revoke endpoints: (url, form, headers) -> [status, body].
38
+ class Tokens
39
+ attr_reader :requests
40
+
41
+ def initialize(access_lifetime: 3600)
42
+ @access_lifetime = access_lifetime
43
+ @live = {}
44
+ @requests = []
45
+ @lock = Mutex.new
46
+ end
47
+
48
+ def call(url, form, headers)
49
+ @lock.synchronize do
50
+ @requests << { url:, form:, headers: }
51
+ next [200, ""] if form.key?(:token)
52
+
53
+ case form[:grant_type]
54
+ when "authorization_code"
55
+ form[:code] == CODE ? issue(url) : refuse
56
+ when "refresh_token"
57
+ @live[url] && form[:refresh_token] == @live[url] ? issue(url) : refuse
58
+ when "client_credentials"
59
+ [200, { token_type: "Bearer", expires_in: @access_lifetime, access_token: "stand-in-access-#{SecureRandom.hex(8)}" }.to_json]
60
+ else [400, { error: "unsupported_grant_type" }.to_json]
61
+ end
62
+ end
63
+ end
64
+
65
+ private
66
+
67
+ def refuse = [400, { error: "invalid_grant", error_description: "the stand-in did not issue that" }.to_json]
68
+
69
+ def issue(url)
70
+ @live[url] = "stand-in-refresh-#{SecureRandom.hex(8)}"
71
+ [200, { access_token: "stand-in-access-#{SecureRandom.hex(8)}", refresh_token: @live[url],
72
+ expires_in: @access_lifetime, token_type: "bearer" }.to_json]
73
+ end
74
+ end
75
+
76
+ def self.install!(provider, callback_params: {}, access_lifetime: 3600)
77
+ provider.sign_in_stand_in = SignIn.new(callback_params:)
78
+ provider.http = Tokens.new(access_lifetime:)
79
+ provider
80
+ end
81
+
82
+ def self.uninstall!(provider)
83
+ provider.sign_in_stand_in = nil
84
+ provider.http = nil
85
+ provider
86
+ end
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,483 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "openssl"
5
+ require "uri"
6
+ require "json"
7
+ require "base64"
8
+ require "set"
9
+
10
+ module Studio
11
+ # CONNECTIONS: the generic tooling a host app uses to connect a third-party
12
+ # account over OAuth 2.0 (docs/CONNECTIONS.md). The engine knows no provider.
13
+ # A host declares each one in an initializer, and the engine gives it:
14
+ #
15
+ # * Studio::Connection, one table (studio_connections) holding one row per
16
+ # provider and account, with the tokens encrypted (bin/rails g studio:connections);
17
+ # * the OAuth plumbing on the Provider below: state, the authorize URL, the
18
+ # code exchange, the refresh policy, the revoke, and two test seams;
19
+ # * Studio::ConnectionFlow, the connect, callback and disconnect actions,
20
+ # and Studio.draw_connection_routes, which draws them;
21
+ # * the log filter for the keys a provider names (LOG_FILTER).
22
+ #
23
+ # Studio.define_connection :files,
24
+ # label: "Acme Files",
25
+ # env: { client_id: "ACME_CLIENT_ID", client_secret: "ACME_CLIENT_SECRET" },
26
+ # authorize_url: ->(account) { "https://#{account}.files.example/oauth/authorize" },
27
+ # token_url: ->(account) { "https://#{account}.files.example/oauth/token" },
28
+ # scopes: %w[files.read],
29
+ # refresh: :cached, refresh_margin: 1.day,
30
+ # account: :connect, account_param: "domain", account_format: /\A[a-z0-9-]{1,63}\z/
31
+ #
32
+ # Provider specifics (endpoints, scopes, quirks, readers, the admin page's
33
+ # live read) belong to the host. Nothing here is named after a vendor.
34
+ module Connections
35
+ # What reaching a provider can raise below HTTP: TLS, refused, timed out, DNS.
36
+ NETWORK_ERRORS = [OpenSSL::SSL::SSLError, SocketError, SystemCallError, Net::OpenTimeout, Net::ReadTimeout].freeze
37
+
38
+ ENCRYPTION_ENV = %w[ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY
39
+ ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT].freeze
40
+
41
+ class Error < StandardError; end
42
+ # The provider's client id or secret is not set on this server.
43
+ class NotConfigured < Error; end
44
+ # The provider no longer honours the stored grant: revoked, expired, superseded.
45
+ class Revoked < Error; end
46
+ # The provider is throttling this app or this token.
47
+ class RateLimited < Error; end
48
+
49
+ # Where the browser leg starts, per grant.
50
+ GRANTS = %i[authorization_code client_credentials].freeze
51
+ # How an access token is obtained after the browser leg:
52
+ # :rotating refresh on every call, under the row's lock, storing the
53
+ # answered refresh token before the access token is used; no
54
+ # access token is stored
55
+ # :cached keep the access token, encrypted, and refresh it under the
56
+ # row's lock only within refresh_margin of its expiry (or after
57
+ # a 401, named by `stale:`), storing the new pair before use
58
+ # :memory the client-credentials grant: no refresh token exists, and the
59
+ # access token lives in this process's memory only
60
+ REFRESH_POLICIES = %i[rotating cached memory].freeze
61
+ # Where the account a row is keyed by comes from:
62
+ # :connect the admin names it before Connect (a form param); it is kept
63
+ # in the session, and the callback never reads it from its query
64
+ # :callback the provider names it on the callback (a query param)
65
+ # :described the host's describe hook names it after the exchange
66
+ ACCOUNT_SOURCES = %i[connect callback described].freeze
67
+ CLIENT_AUTH = %i[form basic secret_only].freeze
68
+
69
+ # An account that fails the provider's format: it never reaches a URL or a row.
70
+ class InvalidAccount < ArgumentError; end
71
+
72
+ # One provider's drawn routes: where they live, the controller serving
73
+ # them, the route-name prefix, and the return_to allowlist (first = default).
74
+ Route = Struct.new(:provider, :path, :as, :controller, :return_paths, keyword_init: true)
75
+
76
+ class << self
77
+ def define(key, **options)
78
+ provider = Provider.new(key, **options)
79
+ registry_lock.synchronize do
80
+ @filter_keys = nil
81
+ registry[provider.key] = provider
82
+ end
83
+ end
84
+
85
+ def fetch(key)
86
+ registry_lock.synchronize { registry[key.to_s] } or raise ArgumentError, "no connection provider is defined as #{key.to_s.inspect}"
87
+ end
88
+
89
+ def defined?(key) = registry_lock.synchronize { registry.key?(key.to_s) }
90
+ def all = registry_lock.synchronize { registry.values }
91
+
92
+ # Forgets every provider and route. Tests only.
93
+ def reset!
94
+ registry_lock.synchronize do
95
+ registry.clear
96
+ routes.clear
97
+ @filter_keys = @controllers = nil
98
+ end
99
+ end
100
+
101
+ # The routes Studio.draw_connection_routes drew, by provider key.
102
+ def routes = (@routes ||= {})
103
+ def route(key) = registry_lock.synchronize { routes[key.to_s] }
104
+
105
+ def record_route(route)
106
+ registry_lock.synchronize do
107
+ @controllers = nil
108
+ routes[route.provider] = route
109
+ end
110
+ end
111
+
112
+ # The controllers that serve a callback, as params["controller"] names them.
113
+ # Memoized: the log filter asks on every logged parameter.
114
+ def controllers = @controllers || registry_lock.synchronize { @controllers ||= routes.values.map(&:controller).to_set.freeze }
115
+
116
+ # Every exact key a provider asked to keep out of the logs.
117
+ def filter_keys = @filter_keys || registry_lock.synchronize { @filter_keys ||= registry.values.flat_map(&:filter_keys).to_set.freeze }
118
+
119
+ # Can this app store a connection: are its Active Record encryption keys set?
120
+ def encryption_ready?
121
+ return false unless defined?(::ActiveRecord::Encryption)
122
+
123
+ config = ::ActiveRecord::Encryption.config
124
+ config.has_primary_key?.present? && config.has_key_derivation_salt?.present?
125
+ end
126
+
127
+ # True on a production server.
128
+ def production?
129
+ defined?(::Rails) && ::Rails.respond_to?(:env) && ::Rails.env.production?
130
+ end
131
+
132
+ # The test seams are allowed only in development and test (or with no
133
+ # Rails at all): a staging or QA environment refuses them as production does.
134
+ def seams_allowed?
135
+ return true unless defined?(::Rails) && ::Rails.respond_to?(:env)
136
+
137
+ ::Rails.env.development? || ::Rails.env.test?
138
+ end
139
+
140
+ private
141
+
142
+ def registry = (@registry ||= {})
143
+ def registry_lock = (@registry_lock ||= Monitor.new)
144
+ end
145
+
146
+ # THE LOG FILTER, which the engine appends to config.filter_parameters.
147
+ #
148
+ # Rails 8.1 filters the "Started GET" line's URL one query pair at a time,
149
+ # as a one-key hash with no controller to scope by
150
+ # (ActionDispatch::Http::FilterParameters#filtered_query_string), so a
151
+ # controller-scoped filter leaves a callback's account id in that line. A
152
+ # provider's filter_keys are therefore matched by EXACT key wherever they
153
+ # appear, String values only (a nested Hash under the same name is spared).
154
+ #
155
+ # The auth code is masked in the Parameters line of the connection
156
+ # controllers only: a bare `code` filter would mask every other `code` param
157
+ # in the app. It still rides the Started GET URL, where it is already spent.
158
+ LOG_FILTER = lambda do |key, value, params = nil|
159
+ next unless value.is_a?(String)
160
+
161
+ name = key.to_s
162
+ if Studio::Connections.filter_keys.include?(name)
163
+ value.replace("[FILTERED]")
164
+ elsif name == "code" && params.is_a?(Hash) && Studio::Connections.controllers.include?(params["controller"].to_s)
165
+ value.replace("[FILTERED]")
166
+ end
167
+ end
168
+
169
+ # One provider, as a host declared it. Every option is checked here, at
170
+ # boot, so a typo fails the host's boot instead of a sign-in.
171
+ class Provider
172
+ Token = Struct.new(:value, :expires_at)
173
+
174
+ attr_reader :key, :label, :env, :grant, :refresh, :refresh_margin, :scopes, :client_auth, :revoke_auth,
175
+ :revoke_format, :account_source, :account_param, :account_format, :private_account,
176
+ :authorize_params, :exchange_params, :rotation, :refresh_expires_in_key, :declined_errors,
177
+ :refusal_hint, :revoked_errors, :revoked_pattern, :rate_limited_statuses, :filter_keys,
178
+ :revoke_note, :callback_check, :describe
179
+
180
+ # Stand-in for the provider's token and revoke endpoints:
181
+ # (url, form, headers) -> [status, body]. nil means the provider itself.
182
+ # Tests, the e2e lane and a local demo only; refused outside development and test.
183
+ attr_reader :http
184
+
185
+ # Stand-in for the provider's sign-in page (authorize_url only), for the
186
+ # e2e lane and a local demo: anything answering
187
+ # authorize_url(redirect_uri:, state:, account:). Refused outside development and test.
188
+ # The code exchange and the refresh still run through .http.
189
+ attr_reader :sign_in_stand_in
190
+
191
+ def initialize(key, label:, env:, authorize_url:, token_url:, revoke_url: nil, grant: :authorization_code,
192
+ refresh: nil, refresh_margin: 5.minutes, scopes: [], client_auth: :form, revoke_auth: nil,
193
+ revoke_format: :form, account: :callback, account_param: nil, account_format: nil,
194
+ normalize_account: nil, private_account: false, authorize_params: {}, exchange_params: {},
195
+ rotation: nil, refresh_expires_in_key: nil, declined_errors: %w[access_denied],
196
+ refusal_hint: "Check the app's redirect URI, then start again.", revoked_errors: %w[invalid_grant],
197
+ revoked_pattern: nil, rate_limited_statuses: [429], filter_keys: [], revoke_note: nil,
198
+ callback_check: nil, describe: nil)
199
+ @key = key.to_s
200
+ raise ArgumentError, "a connection key is lower-case letters, digits and underscores: #{@key.inspect}" unless @key.match?(/\A[a-z][a-z0-9_]*\z/)
201
+
202
+ @label = label.to_s
203
+ @env = env.to_h.transform_keys(&:to_sym)
204
+ raise ArgumentError, "#{@key}: env names client_id and client_secret" unless @env.keys.sort == %i[client_id client_secret] && @env.values.all?(String)
205
+
206
+ @grant = choose(grant, GRANTS, "grant")
207
+ @refresh = choose(refresh || (@grant == :client_credentials ? :memory : :rotating), REFRESH_POLICIES, "refresh")
208
+ if (@grant == :client_credentials) != (@refresh == :memory)
209
+ raise ArgumentError, "#{@key}: the client-credentials grant, and only it, keeps its token in memory (refresh: :memory)"
210
+ end
211
+
212
+ @authorize_url = authorize_url
213
+ @token_url = token_url
214
+ @revoke_url = revoke_url
215
+ @refresh_margin = refresh_margin
216
+ @scopes = Array(scopes).map(&:to_s)
217
+ @client_auth = choose(client_auth, CLIENT_AUTH - [:secret_only], "client_auth")
218
+ @revoke_auth = choose(revoke_auth || @client_auth, CLIENT_AUTH, "revoke_auth")
219
+ @revoke_format = choose(revoke_format, %i[form json], "revoke_format")
220
+ @account_source = choose(account, ACCOUNT_SOURCES, "account")
221
+ @account_param = account_param&.to_s
222
+ @account_format = account_format
223
+ if %i[connect callback].include?(@account_source) && !(@account_param && @account_format.is_a?(Regexp))
224
+ raise ArgumentError, "#{@key}: an account from the #{@account_source} needs account_param and an account_format Regexp"
225
+ end
226
+ @normalize_account = normalize_account || ->(value) { value.to_s.strip }
227
+ @private_account = private_account ? true : false
228
+ @authorize_params = authorize_params.to_h
229
+ @exchange_params = exchange_params.to_h
230
+ @rotation = choose(rotation || (@refresh == :rotating ? :required : :optional), %i[required optional], "rotation")
231
+ @refresh_expires_in_key = refresh_expires_in_key&.to_s
232
+ @declined_errors = Array(declined_errors).map(&:to_s)
233
+ @refusal_hint = refusal_hint.to_s
234
+ @revoked_errors = Array(revoked_errors).map(&:to_s)
235
+ @revoked_pattern = revoked_pattern
236
+ @rate_limited_statuses = Array(rate_limited_statuses).map(&:to_i)
237
+ @filter_keys = Array(filter_keys).map(&:to_s)
238
+ # A private account's callback param is filtered whether or not the host listed it.
239
+ @filter_keys |= [@account_param] if @private_account && @account_source == :callback
240
+ @revoke_note = revoke_note || "Remove this app's access in #{@label} to revoke it there."
241
+ @callback_check = callback_check
242
+ @describe = describe
243
+ @cache = {}
244
+ @cache_lock = Mutex.new
245
+ end
246
+
247
+ def http=(callable)
248
+ refuse_seam_outside_dev_and_test!("http") unless callable.nil?
249
+ @http = callable
250
+ end
251
+
252
+ def sign_in_stand_in=(stand_in)
253
+ refuse_seam_outside_dev_and_test!("sign_in_stand_in") unless stand_in.nil?
254
+ @sign_in_stand_in = stand_in
255
+ end
256
+
257
+ def client_id = ENV[env[:client_id]].to_s
258
+ def client_secret = ENV[env[:client_secret]].to_s
259
+ def env_names = env.values
260
+
261
+ # The client id and secret are set on this server.
262
+ def configured? = env_names.all? { |name| ENV[name].to_s.strip != "" }
263
+
264
+ # Can a Connect start on this server: the client is set, or the stand-in is.
265
+ def connectable? = configured? || !sign_in_stand_in.nil?
266
+
267
+ def revocable? = !@revoke_url.nil?
268
+
269
+ # The account as a row keys it, or nil when it is not one: normalized,
270
+ # then held to account_format (always, when one is given). A strict
271
+ # format is what keeps an account named in a form out of a URL's host.
272
+ def normalize_account(value)
273
+ normalized = @normalize_account.call(value)
274
+ return nil if normalized.nil? || normalized.to_s.empty?
275
+
276
+ normalized = normalized.to_s
277
+ return nil if account_format && !account_format.match?(normalized)
278
+
279
+ normalized
280
+ end
281
+
282
+ # What a row is unique by: the account itself, or a keyed digest of it
283
+ # when the account is private (it is then stored only encrypted).
284
+ def account_key_for(account)
285
+ return account unless private_account
286
+
287
+ secret = defined?(::Rails) && ::Rails.application ? ::Rails.application.secret_key_base : raise(Error, "no secret_key_base to key a private account by")
288
+ OpenSSL::HMAC.hexdigest("SHA256", secret, "studio-connection:#{key}:#{account}")
289
+ end
290
+
291
+ # An endpoint's URL: the static String, or the callable's answer for a
292
+ # checked account (a per-account host). Raises InvalidAccount for an
293
+ # account that fails account_format, so it never reaches a URL.
294
+ def url_for(option, account)
295
+ value = { authorize: @authorize_url, token: @token_url, revoke: @revoke_url }.fetch(option)
296
+ return nil if value.nil?
297
+ return value.to_s unless value.respond_to?(:call)
298
+
299
+ checked = normalize_account(account) or raise InvalidAccount, "not a #{label} account"
300
+ value.call(checked).to_s
301
+ end
302
+
303
+ # Where the browser goes to sign in (a code grant) or approve the app (a
304
+ # client-credentials grant's admin consent).
305
+ def authorize_url(redirect_uri:, state:, account: nil)
306
+ return sign_in_stand_in.authorize_url(redirect_uri:, state:, account:) if sign_in_stand_in
307
+
308
+ ensure_configured!
309
+ params = { client_id:, redirect_uri:, state: }
310
+ if grant == :authorization_code
311
+ params[:response_type] = "code"
312
+ params[:scope] = scopes.join(" ") if scopes.any?
313
+ end
314
+ url = url_for(:authorize, account)
315
+ "#{url}#{url.include?('?') ? '&' : '?'}#{URI.encode_www_form(params.merge(authorize_params))}"
316
+ end
317
+
318
+ # The token endpoint's JSON for a sign-in's code.
319
+ def exchange_code(code:, redirect_uri:, account: nil)
320
+ token_request(account, { grant_type: "authorization_code", code:, redirect_uri: }.merge(exchange_params))
321
+ end
322
+
323
+ # An access token for `connection` (a Studio::Connection; for :memory,
324
+ # also a bare account id), by this provider's refresh policy. Raises
325
+ # Revoked when the provider no longer honours the grant.
326
+ def access_token(connection, stale: nil, now: Time.current)
327
+ case refresh
328
+ when :rotating then rotating_access_token(connection, now:)
329
+ when :cached then cached_access_token(connection, stale:, now:)
330
+ when :memory then memory_access_token(connection.respond_to?(:account_id) ? connection.account_id : connection, now:)
331
+ end
332
+ end
333
+
334
+ # Revokes the connection's grant at the provider. True when it took it;
335
+ # nil when this provider has no revoke endpoint; raises Error otherwise.
336
+ def revoke(connection)
337
+ return nil unless revocable?
338
+
339
+ token = connection.refresh_token.presence || connection.access_token
340
+ raise Error, "this connection holds no token to revoke" if token.to_s.empty?
341
+
342
+ form = { token: }
343
+ post(url_for(:revoke, connection.account_id), form, auth: revoke_auth, format: revoke_format, allow_empty: true)
344
+ true
345
+ end
346
+
347
+ # Drops the in-memory token of one account, or every account's (:memory).
348
+ def forget!(account = nil)
349
+ @cache_lock.synchronize { account ? @cache.delete(account.to_s.downcase) : @cache.clear }
350
+ end
351
+
352
+ # How many accounts have a token cached in this process (:memory).
353
+ def cached_count = @cache_lock.synchronize { @cache.size }
354
+
355
+ # When a grant's token stops working, from a seconds field; nil when the
356
+ # provider gave no positive lifetime.
357
+ def self.expiry(grant, field, now)
358
+ return nil if field.nil?
359
+
360
+ seconds = Integer(grant[field].to_s, exception: false)
361
+ seconds&.positive? ? now + seconds : nil
362
+ end
363
+
364
+ private
365
+
366
+ def choose(value, allowed, name)
367
+ value = value.to_sym
368
+ return value if allowed.include?(value)
369
+
370
+ raise ArgumentError, "#{@key}: #{name} is one of #{allowed.map(&:inspect).join(', ')}, not #{value.inspect}"
371
+ end
372
+
373
+ def refuse_seam_outside_dev_and_test!(name)
374
+ raise Error, "#{label}: the #{name} stand-in is for tests, the e2e lane and a local demo (development and test only)" unless Connections.seams_allowed?
375
+ end
376
+
377
+ def ensure_configured!
378
+ raise NotConfigured, "#{env_names.join(' and ')} are not set on this server" unless configured? || http
379
+ end
380
+
381
+ def rotating_access_token(connection, now:)
382
+ answer = connection.with_lock do
383
+ raise Revoked, "#{label}: this connection holds no refresh token; connect again" if connection.refresh_token.blank?
384
+
385
+ grant = token_request(connection.account_id, { grant_type: "refresh_token", refresh_token: connection.refresh_token })
386
+ connection.rotate!(grant, now:)
387
+ grant
388
+ end
389
+ # After the lock commits: a raise inside it would roll back the token the provider already rotated.
390
+ answer["access_token"].presence or raise Error, "#{label} answered a refresh with no access token"
391
+ end
392
+
393
+ def cached_access_token(connection, stale:, now:)
394
+ connection.with_lock do
395
+ current = connection.access_token
396
+ next current if stale.present? && current != stale
397
+ next current if stale.blank? && connection.access_fresh?(now)
398
+ raise Revoked, "#{label}: this connection holds no refresh token; connect again" if connection.refresh_token.blank?
399
+
400
+ grant = token_request(connection.account_id, { grant_type: "refresh_token", refresh_token: connection.refresh_token })
401
+ raise Error, "#{label} answered a refresh with no access token" if grant["access_token"].blank?
402
+
403
+ connection.rotate!(grant, now:)
404
+ grant["access_token"]
405
+ end
406
+ end
407
+
408
+ def memory_access_token(account, now:)
409
+ account = normalize_account(account) or raise InvalidAccount, "not a #{label} account"
410
+ cache_key = account.downcase
411
+ cached = @cache_lock.synchronize { @cache[cache_key] }
412
+ return cached.value if cached && cached.expires_at > now
413
+
414
+ form = { grant_type: "client_credentials" }
415
+ form[:scope] = scopes.join(" ") if scopes.any?
416
+ answer = token_request(account, form)
417
+ value = answer["access_token"].presence or raise Error, "#{label} answered a token request with no access token"
418
+ lifetime = answer["expires_in"].to_i
419
+ @cache_lock.synchronize { @cache[cache_key] = Token.new(value, now + lifetime - refresh_margin) }
420
+ value
421
+ end
422
+
423
+ def token_request(account, form)
424
+ post(url_for(:token, account), form, auth: client_auth, format: :form)
425
+ end
426
+
427
+ def post(url, form, auth:, format:, allow_empty: false)
428
+ ensure_configured!
429
+ headers = { "Accept" => "application/json",
430
+ "Content-Type" => format == :json ? "application/json" : "application/x-www-form-urlencoded" }
431
+ case auth
432
+ when :form then form = form.merge(client_id:, client_secret:)
433
+ when :secret_only then form = form.merge(client_secret:)
434
+ when :basic then headers["Authorization"] = "Basic #{Base64.strict_encode64("#{client_id}:#{client_secret}")}"
435
+ end
436
+ status, body = call(url, form, headers)
437
+ json = parse(body)
438
+ # A revoke (allow_empty) is confirmed by any 2xx, a 204 included; a token answer must be a 200 with a body.
439
+ return json if allow_empty ? (200..299).cover?(status) : (status == 200 && json.any?)
440
+
441
+ raise_for(status, json)
442
+ end
443
+
444
+ def raise_for(status, json)
445
+ detail = json["error_description"].to_s.lines.first.to_s.strip
446
+ detail = (json["error"] || json["message"] || json["errorMessage"]).to_s if detail.empty?
447
+ detail = "no detail" if detail.empty?
448
+ raise RateLimited, "#{label} is throttling this app (#{status}); try again in a few minutes" if rate_limited_statuses.include?(status)
449
+ raise Revoked, "#{label} no longer accepts this connection (#{detail}); connect again" if revoked?(status, json, detail)
450
+
451
+ raise Error, "#{label} answered #{status}: #{detail}"
452
+ end
453
+
454
+ def revoked?(status, json, detail)
455
+ return false unless [400, 401, 403].include?(status)
456
+
457
+ revoked_errors.include?(json["error"].to_s) || (revoked_pattern ? revoked_pattern.match?(detail) : false)
458
+ end
459
+
460
+ def parse(body)
461
+ json = JSON.parse(body.to_s)
462
+ json.is_a?(Hash) ? json : {}
463
+ rescue JSON::ParserError
464
+ {}
465
+ end
466
+
467
+ def call(url, form, headers)
468
+ return http.call(url, form, headers) if http
469
+
470
+ uri = URI(url)
471
+ raise Error, "#{label}: a token endpoint must be https" unless uri.scheme == "https"
472
+
473
+ request = Net::HTTP::Post.new(uri)
474
+ headers.each { |name, value| request[name] = value }
475
+ request.body = headers["Content-Type"] == "application/json" ? JSON.generate(form) : URI.encode_www_form(form)
476
+ response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 20) { _1.request(request) }
477
+ [response.code.to_i, response.body]
478
+ rescue *NETWORK_ERRORS => e
479
+ raise Error, "#{label} could not be reached: #{e.class}"
480
+ end
481
+ end
482
+ end
483
+ end