studio-engine 0.136.0 → 0.138.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +29 -0
- data/README.md +29 -0
- data/app/assets/tailwind/studio_engine/engine.css +228 -0
- data/app/controllers/concerns/studio/connection_flow.rb +215 -0
- data/app/controllers/sessions_controller.rb +12 -3
- data/app/controllers/studio/connections_controller.rb +13 -0
- data/app/controllers/studio/integrations_controller.rb +43 -0
- data/app/controllers/studio/local_reviews_controller.rb +12 -0
- data/app/javascript/studio/carousel.js +66 -0
- data/app/javascript/studio/controllers/carousel_controller.js +203 -1
- data/app/models/concerns/studio/account.rb +143 -0
- data/app/models/concerns/studio/omniauth_user.rb +9 -17
- data/app/models/error_log.rb +14 -5
- data/app/models/studio/connection.rb +137 -0
- data/app/views/studio/_carousel.html.erb +58 -14
- data/app/views/studio/integrations/_card.html.erb +50 -0
- data/app/views/studio/integrations/index.html.erb +22 -0
- data/app/views/studio/integrations/show.html.erb +24 -0
- data/app/views/style/_tricks.html.erb +15 -0
- data/config/studio_tricks.yml +7 -0
- data/db/migrate/20261006120001_ensure_error_logs_table.rb +3 -1
- data/db/migrate/20261006120002_ensure_theme_settings_table.rb +3 -2
- data/db/migrate/20261108130000_create_studio_connections.rb +35 -0
- data/db/migrate/20261108160000_require_slugs_on_engine_tables.rb +119 -0
- data/db/migrate/20261108160001_add_engine_state_checks.rb +94 -0
- data/db/migrate/20261108170000_add_users_role_known_check.rb +69 -0
- data/lib/generators/studio/connections/connections_generator.rb +103 -0
- data/lib/studio/connections/stand_in.rb +89 -0
- data/lib/studio/connections.rb +524 -0
- data/lib/studio/engine.rb +8 -0
- data/lib/studio/integrations/egnyte.rb +69 -0
- data/lib/studio/integrations/microsoft_365.rb +63 -0
- data/lib/studio/integrations/quickbooks.rb +86 -0
- data/lib/studio/integrations.rb +265 -0
- data/lib/studio/node_tooling/README.md +9 -1
- data/lib/studio/node_tooling/e2e_helpers.js +93 -1
- data/lib/studio/node_tooling/playwright_base.js +51 -4
- data/lib/studio/roles.rb +17 -0
- data/lib/studio/version.rb +1 -1
- data/lib/studio.rb +118 -0
- metadata +22 -2
|
@@ -0,0 +1,524 @@
|
|
|
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 tooling 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 in this file is named after a vendor:
|
|
34
|
+
# the engine's own definitions live in Studio::Integrations (docs/INTEGRATIONS.md).
|
|
35
|
+
module Connections
|
|
36
|
+
# What reaching a provider can raise below HTTP: TLS, refused, timed out, DNS.
|
|
37
|
+
NETWORK_ERRORS = [OpenSSL::SSL::SSLError, SocketError, SystemCallError, Net::OpenTimeout, Net::ReadTimeout].freeze
|
|
38
|
+
|
|
39
|
+
ENCRYPTION_ENV = %w[ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY
|
|
40
|
+
ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT].freeze
|
|
41
|
+
|
|
42
|
+
# Every refusal below. A provider that names a trace_header (Intuit's
|
|
43
|
+
# intuit_tid) puts the answering call's trace id on the error: as #trace_id,
|
|
44
|
+
# and in the message, so the error log and the page carry it. Never a token.
|
|
45
|
+
class Error < StandardError
|
|
46
|
+
attr_reader :trace_header, :trace_id
|
|
47
|
+
|
|
48
|
+
def initialize(message = nil, trace_header: nil, trace_id: nil)
|
|
49
|
+
@trace_header = trace_header
|
|
50
|
+
@trace_id = trace_id.to_s.strip.presence
|
|
51
|
+
super(@trace_id && message ? "#{message} [#{@trace_header}: #{@trace_id}]" : message)
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
# The provider's client id or secret is not set on this server.
|
|
55
|
+
class NotConfigured < Error; end
|
|
56
|
+
# The provider no longer honours the stored grant: revoked, expired, superseded.
|
|
57
|
+
class Revoked < Error; end
|
|
58
|
+
# The provider is throttling this app or this token.
|
|
59
|
+
class RateLimited < Error; end
|
|
60
|
+
|
|
61
|
+
# Where the browser leg starts, per grant.
|
|
62
|
+
GRANTS = %i[authorization_code client_credentials].freeze
|
|
63
|
+
# How an access token is obtained after the browser leg:
|
|
64
|
+
# :rotating refresh on every call, under the row's lock, storing the
|
|
65
|
+
# answered refresh token before the access token is used; no
|
|
66
|
+
# access token is stored
|
|
67
|
+
# :cached keep the access token, encrypted, and refresh it under the
|
|
68
|
+
# row's lock only within refresh_margin of its expiry (or after
|
|
69
|
+
# a 401, named by `stale:`), storing the new pair before use
|
|
70
|
+
# :memory the client-credentials grant: no refresh token exists, and the
|
|
71
|
+
# access token lives in this process's memory only
|
|
72
|
+
REFRESH_POLICIES = %i[rotating cached memory].freeze
|
|
73
|
+
# Where the account a row is keyed by comes from:
|
|
74
|
+
# :connect the admin names it before Connect (a form param); it is kept
|
|
75
|
+
# in the session, and the callback never reads it from its query
|
|
76
|
+
# :callback the provider names it on the callback (a query param)
|
|
77
|
+
# :described the host's describe hook names it after the exchange
|
|
78
|
+
ACCOUNT_SOURCES = %i[connect callback described].freeze
|
|
79
|
+
CLIENT_AUTH = %i[form basic secret_only].freeze
|
|
80
|
+
|
|
81
|
+
# An account that fails the provider's format: it never reaches a URL or a row.
|
|
82
|
+
class InvalidAccount < ArgumentError; end
|
|
83
|
+
|
|
84
|
+
# One provider's drawn routes: where they live, the controller serving
|
|
85
|
+
# them, the route-name prefix, and the return_to allowlist (first = default).
|
|
86
|
+
Route = Struct.new(:provider, :path, :as, :controller, :return_paths, keyword_init: true)
|
|
87
|
+
|
|
88
|
+
class << self
|
|
89
|
+
def define(key, **options)
|
|
90
|
+
provider = Provider.new(key, **options)
|
|
91
|
+
registry_lock.synchronize do
|
|
92
|
+
@filter_keys = nil
|
|
93
|
+
registry[provider.key] = provider
|
|
94
|
+
end
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def fetch(key)
|
|
98
|
+
registry_lock.synchronize { registry[key.to_s] } or raise ArgumentError, "no connection provider is defined as #{key.to_s.inspect}"
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
def defined?(key) = registry_lock.synchronize { registry.key?(key.to_s) }
|
|
102
|
+
def all = registry_lock.synchronize { registry.values }
|
|
103
|
+
|
|
104
|
+
# Forgets every provider and route. Tests only.
|
|
105
|
+
def reset!
|
|
106
|
+
registry_lock.synchronize do
|
|
107
|
+
registry.clear
|
|
108
|
+
routes.clear
|
|
109
|
+
@filter_keys = @controllers = nil
|
|
110
|
+
end
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# The routes Studio.draw_connection_routes drew, by provider key.
|
|
114
|
+
def routes = (@routes ||= {})
|
|
115
|
+
def route(key) = registry_lock.synchronize { routes[key.to_s] }
|
|
116
|
+
|
|
117
|
+
def record_route(route)
|
|
118
|
+
registry_lock.synchronize do
|
|
119
|
+
@controllers = nil
|
|
120
|
+
routes[route.provider] = route
|
|
121
|
+
end
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
# The controllers that serve a callback, as params["controller"] names them.
|
|
125
|
+
# Memoized: the log filter asks on every logged parameter.
|
|
126
|
+
def controllers = @controllers || registry_lock.synchronize { @controllers ||= routes.values.map(&:controller).to_set.freeze }
|
|
127
|
+
|
|
128
|
+
# Every exact key a provider asked to keep out of the logs.
|
|
129
|
+
def filter_keys = @filter_keys || registry_lock.synchronize { @filter_keys ||= registry.values.flat_map(&:filter_keys).to_set.freeze }
|
|
130
|
+
|
|
131
|
+
# Can this app store a connection: are its Active Record encryption keys set?
|
|
132
|
+
def encryption_ready?
|
|
133
|
+
return false unless defined?(::ActiveRecord::Encryption)
|
|
134
|
+
|
|
135
|
+
config = ::ActiveRecord::Encryption.config
|
|
136
|
+
config.has_primary_key?.present? && config.has_key_derivation_salt?.present?
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
# True on a production server.
|
|
140
|
+
def production?
|
|
141
|
+
defined?(::Rails) && ::Rails.respond_to?(:env) && ::Rails.env.production?
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
# The test seams are allowed only in development and test (or with no
|
|
145
|
+
# Rails at all): a staging or QA environment refuses them as production does.
|
|
146
|
+
def seams_allowed?
|
|
147
|
+
return true unless defined?(::Rails) && ::Rails.respond_to?(:env)
|
|
148
|
+
|
|
149
|
+
::Rails.env.development? || ::Rails.env.test?
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
private
|
|
153
|
+
|
|
154
|
+
def registry = (@registry ||= {})
|
|
155
|
+
def registry_lock = (@registry_lock ||= Monitor.new)
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
# THE LOG FILTER, which the engine appends to config.filter_parameters.
|
|
159
|
+
#
|
|
160
|
+
# Rails 8.1 filters the "Started GET" line's URL one query pair at a time,
|
|
161
|
+
# as a one-key hash with no controller to scope by
|
|
162
|
+
# (ActionDispatch::Http::FilterParameters#filtered_query_string), so a
|
|
163
|
+
# controller-scoped filter leaves a callback's account id in that line. A
|
|
164
|
+
# provider's filter_keys are therefore matched by EXACT key wherever they
|
|
165
|
+
# appear, String values only (a nested Hash under the same name is spared).
|
|
166
|
+
#
|
|
167
|
+
# The auth code is masked in the Parameters line of the connection
|
|
168
|
+
# controllers only: a bare `code` filter would mask every other `code` param
|
|
169
|
+
# in the app. It still rides the Started GET URL, where it is already spent.
|
|
170
|
+
LOG_FILTER = lambda do |key, value, params = nil|
|
|
171
|
+
next unless value.is_a?(String)
|
|
172
|
+
|
|
173
|
+
name = key.to_s
|
|
174
|
+
if Studio::Connections.filter_keys.include?(name)
|
|
175
|
+
value.replace("[FILTERED]")
|
|
176
|
+
elsif name == "code" && params.is_a?(Hash) && Studio::Connections.controllers.include?(params["controller"].to_s)
|
|
177
|
+
value.replace("[FILTERED]")
|
|
178
|
+
end
|
|
179
|
+
end
|
|
180
|
+
|
|
181
|
+
# One provider, as a host declared it. Every option is checked here, at
|
|
182
|
+
# boot, so a typo fails the host's boot instead of a sign-in.
|
|
183
|
+
class Provider
|
|
184
|
+
Token = Struct.new(:value, :expires_at)
|
|
185
|
+
|
|
186
|
+
attr_reader :key, :label, :env, :grant, :refresh, :refresh_margin, :scopes, :client_auth, :revoke_auth,
|
|
187
|
+
:revoke_format, :account_source, :account_param, :account_format, :private_account,
|
|
188
|
+
:authorize_params, :exchange_params, :rotation, :refresh_expires_in_key, :declined_errors,
|
|
189
|
+
:refusal_hint, :revoked_errors, :revoked_pattern, :rate_limited_statuses, :filter_keys,
|
|
190
|
+
:revoke_note, :callback_check, :describe, :trace_header
|
|
191
|
+
|
|
192
|
+
# Stand-in for the provider's token and revoke endpoints:
|
|
193
|
+
# (url, form, headers) -> [status, body]. nil means the provider itself.
|
|
194
|
+
# Tests, the e2e lane and a local demo only; refused outside development and test.
|
|
195
|
+
attr_reader :http
|
|
196
|
+
|
|
197
|
+
# Stand-in for the provider's sign-in page (authorize_url only), for the
|
|
198
|
+
# e2e lane and a local demo: anything answering
|
|
199
|
+
# authorize_url(redirect_uri:, state:, account:). Refused outside development and test.
|
|
200
|
+
# The code exchange and the refresh still run through .http.
|
|
201
|
+
attr_reader :sign_in_stand_in
|
|
202
|
+
|
|
203
|
+
def initialize(key, label:, env:, authorize_url:, token_url:, revoke_url: nil, grant: :authorization_code,
|
|
204
|
+
refresh: nil, refresh_margin: 5.minutes, scopes: [], client_auth: :form, revoke_auth: nil,
|
|
205
|
+
revoke_format: :form, account: :callback, account_param: nil, account_format: nil,
|
|
206
|
+
normalize_account: nil, private_account: false, authorize_params: {}, exchange_params: {},
|
|
207
|
+
rotation: nil, refresh_expires_in_key: nil, declined_errors: %w[access_denied],
|
|
208
|
+
refusal_hint: "Check the app's redirect URI, then start again.", revoked_errors: %w[invalid_grant],
|
|
209
|
+
revoked_pattern: nil, rate_limited_statuses: [429], filter_keys: [], revoke_note: nil,
|
|
210
|
+
callback_check: nil, describe: nil, trace_header: nil)
|
|
211
|
+
@key = key.to_s
|
|
212
|
+
raise ArgumentError, "a connection key is lower-case letters, digits and underscores: #{@key.inspect}" unless @key.match?(/\A[a-z][a-z0-9_]*\z/)
|
|
213
|
+
|
|
214
|
+
@label = label.to_s
|
|
215
|
+
@env = env.to_h.transform_keys(&:to_sym)
|
|
216
|
+
raise ArgumentError, "#{@key}: env names client_id and client_secret" unless @env.keys.sort == %i[client_id client_secret] && @env.values.all?(String)
|
|
217
|
+
|
|
218
|
+
@grant = choose(grant, GRANTS, "grant")
|
|
219
|
+
@refresh = choose(refresh || (@grant == :client_credentials ? :memory : :rotating), REFRESH_POLICIES, "refresh")
|
|
220
|
+
if (@grant == :client_credentials) != (@refresh == :memory)
|
|
221
|
+
raise ArgumentError, "#{@key}: the client-credentials grant, and only it, keeps its token in memory (refresh: :memory)"
|
|
222
|
+
end
|
|
223
|
+
|
|
224
|
+
@authorize_url = authorize_url
|
|
225
|
+
@token_url = token_url
|
|
226
|
+
@revoke_url = revoke_url
|
|
227
|
+
@refresh_margin = refresh_margin
|
|
228
|
+
@scopes = Array(scopes).map(&:to_s)
|
|
229
|
+
@client_auth = choose(client_auth, CLIENT_AUTH - [:secret_only], "client_auth")
|
|
230
|
+
@revoke_auth = choose(revoke_auth || @client_auth, CLIENT_AUTH, "revoke_auth")
|
|
231
|
+
@revoke_format = choose(revoke_format, %i[form json], "revoke_format")
|
|
232
|
+
@account_source = choose(account, ACCOUNT_SOURCES, "account")
|
|
233
|
+
@account_param = account_param&.to_s
|
|
234
|
+
@account_format = account_format
|
|
235
|
+
if %i[connect callback].include?(@account_source) && !(@account_param && @account_format.is_a?(Regexp))
|
|
236
|
+
raise ArgumentError, "#{@key}: an account from the #{@account_source} needs account_param and an account_format Regexp"
|
|
237
|
+
end
|
|
238
|
+
@normalize_account = normalize_account || ->(value) { value.to_s.strip }
|
|
239
|
+
@private_account = private_account ? true : false
|
|
240
|
+
@authorize_params = authorize_params.to_h
|
|
241
|
+
@exchange_params = exchange_params.to_h
|
|
242
|
+
@rotation = choose(rotation || (@refresh == :rotating ? :required : :optional), %i[required optional], "rotation")
|
|
243
|
+
@refresh_expires_in_key = refresh_expires_in_key&.to_s
|
|
244
|
+
@declined_errors = Array(declined_errors).map(&:to_s)
|
|
245
|
+
@refusal_hint = refusal_hint.to_s
|
|
246
|
+
@revoked_errors = Array(revoked_errors).map(&:to_s)
|
|
247
|
+
@revoked_pattern = revoked_pattern
|
|
248
|
+
@rate_limited_statuses = Array(rate_limited_statuses).map(&:to_i)
|
|
249
|
+
@filter_keys = Array(filter_keys).map(&:to_s)
|
|
250
|
+
# A private account's callback param is filtered whether or not the host listed it.
|
|
251
|
+
@filter_keys |= [@account_param] if @private_account && @account_source == :callback
|
|
252
|
+
@revoke_note = revoke_note || "Remove this app's access in #{@label} to revoke it there."
|
|
253
|
+
@callback_check = callback_check
|
|
254
|
+
@describe = describe
|
|
255
|
+
# A response header naming the call for the provider's support (Intuit:
|
|
256
|
+
# intuit_tid). Read from every token, refresh and revoke answer, logged
|
|
257
|
+
# with the call, kept as #last_trace_id and put on every error raised.
|
|
258
|
+
@trace_header = trace_header&.to_s
|
|
259
|
+
@cache = {}
|
|
260
|
+
@cache_lock = Mutex.new
|
|
261
|
+
end
|
|
262
|
+
|
|
263
|
+
def http=(callable)
|
|
264
|
+
refuse_seam_outside_dev_and_test!("http") unless callable.nil?
|
|
265
|
+
@http = callable
|
|
266
|
+
end
|
|
267
|
+
|
|
268
|
+
def sign_in_stand_in=(stand_in)
|
|
269
|
+
refuse_seam_outside_dev_and_test!("sign_in_stand_in") unless stand_in.nil?
|
|
270
|
+
@sign_in_stand_in = stand_in
|
|
271
|
+
end
|
|
272
|
+
|
|
273
|
+
def client_id = ENV[env[:client_id]].to_s
|
|
274
|
+
def client_secret = ENV[env[:client_secret]].to_s
|
|
275
|
+
def env_names = env.values
|
|
276
|
+
|
|
277
|
+
# The client id and secret are set on this server.
|
|
278
|
+
def configured? = env_names.all? { |name| ENV[name].to_s.strip != "" }
|
|
279
|
+
|
|
280
|
+
# Can a Connect start on this server: the client is set, or the stand-in is.
|
|
281
|
+
def connectable? = configured? || !sign_in_stand_in.nil?
|
|
282
|
+
|
|
283
|
+
def revocable? = !@revoke_url.nil?
|
|
284
|
+
|
|
285
|
+
# The account as a row keys it, or nil when it is not one: normalized,
|
|
286
|
+
# then held to account_format (always, when one is given). A strict
|
|
287
|
+
# format is what keeps an account named in a form out of a URL's host.
|
|
288
|
+
def normalize_account(value)
|
|
289
|
+
normalized = @normalize_account.call(value)
|
|
290
|
+
return nil if normalized.nil? || normalized.to_s.empty?
|
|
291
|
+
|
|
292
|
+
normalized = normalized.to_s
|
|
293
|
+
return nil if account_format && !account_format.match?(normalized)
|
|
294
|
+
|
|
295
|
+
normalized
|
|
296
|
+
end
|
|
297
|
+
|
|
298
|
+
# What a row is unique by: the account itself, or a keyed digest of it
|
|
299
|
+
# when the account is private (it is then stored only encrypted).
|
|
300
|
+
def account_key_for(account)
|
|
301
|
+
return account unless private_account
|
|
302
|
+
|
|
303
|
+
secret = defined?(::Rails) && ::Rails.application ? ::Rails.application.secret_key_base : raise(Error, "no secret_key_base to key a private account by")
|
|
304
|
+
OpenSSL::HMAC.hexdigest("SHA256", secret, "studio-connection:#{key}:#{account}")
|
|
305
|
+
end
|
|
306
|
+
|
|
307
|
+
# An endpoint's URL: the static String, or the callable's answer for a
|
|
308
|
+
# checked account (a per-account host). Raises InvalidAccount for an
|
|
309
|
+
# account that fails account_format, so it never reaches a URL.
|
|
310
|
+
def url_for(option, account)
|
|
311
|
+
value = { authorize: @authorize_url, token: @token_url, revoke: @revoke_url }.fetch(option)
|
|
312
|
+
return nil if value.nil?
|
|
313
|
+
return value.to_s unless value.respond_to?(:call)
|
|
314
|
+
|
|
315
|
+
checked = normalize_account(account) or raise InvalidAccount, "not a #{label} account"
|
|
316
|
+
value.call(checked).to_s
|
|
317
|
+
end
|
|
318
|
+
|
|
319
|
+
# Where the browser goes to sign in (a code grant) or approve the app (a
|
|
320
|
+
# client-credentials grant's admin consent).
|
|
321
|
+
def authorize_url(redirect_uri:, state:, account: nil)
|
|
322
|
+
return sign_in_stand_in.authorize_url(redirect_uri:, state:, account:) if sign_in_stand_in
|
|
323
|
+
|
|
324
|
+
ensure_configured!
|
|
325
|
+
params = { client_id:, redirect_uri:, state: }
|
|
326
|
+
if grant == :authorization_code
|
|
327
|
+
params[:response_type] = "code"
|
|
328
|
+
params[:scope] = scopes.join(" ") if scopes.any?
|
|
329
|
+
end
|
|
330
|
+
url = url_for(:authorize, account)
|
|
331
|
+
"#{url}#{url.include?('?') ? '&' : '?'}#{URI.encode_www_form(params.merge(authorize_params))}"
|
|
332
|
+
end
|
|
333
|
+
|
|
334
|
+
# The token endpoint's JSON for a sign-in's code.
|
|
335
|
+
def exchange_code(code:, redirect_uri:, account: nil)
|
|
336
|
+
token_request(account, { grant_type: "authorization_code", code:, redirect_uri: }.merge(exchange_params))
|
|
337
|
+
end
|
|
338
|
+
|
|
339
|
+
# An access token for `connection` (a Studio::Connection; for :memory,
|
|
340
|
+
# also a bare account id), by this provider's refresh policy. Raises
|
|
341
|
+
# Revoked when the provider no longer honours the grant.
|
|
342
|
+
def access_token(connection, stale: nil, now: Time.current)
|
|
343
|
+
case refresh
|
|
344
|
+
when :rotating then rotating_access_token(connection, now:)
|
|
345
|
+
when :cached then cached_access_token(connection, stale:, now:)
|
|
346
|
+
when :memory then memory_access_token(connection.respond_to?(:account_id) ? connection.account_id : connection, now:)
|
|
347
|
+
end
|
|
348
|
+
end
|
|
349
|
+
|
|
350
|
+
# Revokes the connection's grant at the provider. True when it took it;
|
|
351
|
+
# nil when this provider has no revoke endpoint; raises Error otherwise.
|
|
352
|
+
def revoke(connection)
|
|
353
|
+
return nil unless revocable?
|
|
354
|
+
|
|
355
|
+
token = connection.refresh_token.presence || connection.access_token
|
|
356
|
+
raise Error, "this connection holds no token to revoke" if token.to_s.empty?
|
|
357
|
+
|
|
358
|
+
form = { token: }
|
|
359
|
+
post(url_for(:revoke, connection.account_id), form, auth: revoke_auth, format: revoke_format, allow_empty: true)
|
|
360
|
+
true
|
|
361
|
+
end
|
|
362
|
+
|
|
363
|
+
# Drops the in-memory token of one account, or every account's (:memory).
|
|
364
|
+
def forget!(account = nil)
|
|
365
|
+
@cache_lock.synchronize { account ? @cache.delete(account.to_s.downcase) : @cache.clear }
|
|
366
|
+
end
|
|
367
|
+
|
|
368
|
+
# The trace_header value of this thread's latest call to the provider, or nil.
|
|
369
|
+
def last_trace_id = (Thread.current[:studio_connection_traces] ||= {})[key]
|
|
370
|
+
|
|
371
|
+
# Reads trace_header from a response's headers (a Hash or a Net::HTTPResponse),
|
|
372
|
+
# remembers it as last_trace_id, and logs it with the call (no token, no body).
|
|
373
|
+
# Host readers call it on their own responses too.
|
|
374
|
+
def record_trace(headers, call:, status:)
|
|
375
|
+
return nil unless trace_header
|
|
376
|
+
|
|
377
|
+
value = case headers
|
|
378
|
+
when Hash then headers.find { |name, _| name.to_s.casecmp?(trace_header) }&.last
|
|
379
|
+
else headers.respond_to?(:[]) ? headers[trace_header] : nil
|
|
380
|
+
end
|
|
381
|
+
value = Array(value).first.to_s.strip.presence
|
|
382
|
+
(Thread.current[:studio_connection_traces] ||= {})[key] = value
|
|
383
|
+
if defined?(::Rails) && ::Rails.respond_to?(:logger) && ::Rails.logger
|
|
384
|
+
::Rails.logger.info("[studio_connection] provider=#{key} call=#{call} status=#{status} #{trace_header}=#{value || '-'}")
|
|
385
|
+
end
|
|
386
|
+
value
|
|
387
|
+
end
|
|
388
|
+
|
|
389
|
+
# How many accounts have a token cached in this process (:memory).
|
|
390
|
+
def cached_count = @cache_lock.synchronize { @cache.size }
|
|
391
|
+
|
|
392
|
+
# When a grant's token stops working, from a seconds field; nil when the
|
|
393
|
+
# provider gave no positive lifetime.
|
|
394
|
+
def self.expiry(grant, field, now)
|
|
395
|
+
return nil if field.nil?
|
|
396
|
+
|
|
397
|
+
seconds = Integer(grant[field].to_s, exception: false)
|
|
398
|
+
seconds&.positive? ? now + seconds : nil
|
|
399
|
+
end
|
|
400
|
+
|
|
401
|
+
private
|
|
402
|
+
|
|
403
|
+
def choose(value, allowed, name)
|
|
404
|
+
value = value.to_sym
|
|
405
|
+
return value if allowed.include?(value)
|
|
406
|
+
|
|
407
|
+
raise ArgumentError, "#{@key}: #{name} is one of #{allowed.map(&:inspect).join(', ')}, not #{value.inspect}"
|
|
408
|
+
end
|
|
409
|
+
|
|
410
|
+
def refuse_seam_outside_dev_and_test!(name)
|
|
411
|
+
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?
|
|
412
|
+
end
|
|
413
|
+
|
|
414
|
+
def ensure_configured!
|
|
415
|
+
raise NotConfigured, "#{env_names.join(' and ')} are not set on this server" unless configured? || http
|
|
416
|
+
end
|
|
417
|
+
|
|
418
|
+
def rotating_access_token(connection, now:)
|
|
419
|
+
answer = connection.with_lock do
|
|
420
|
+
raise Revoked, "#{label}: this connection holds no refresh token; connect again" if connection.refresh_token.blank?
|
|
421
|
+
|
|
422
|
+
grant = token_request(connection.account_id, { grant_type: "refresh_token", refresh_token: connection.refresh_token })
|
|
423
|
+
connection.rotate!(grant, now:)
|
|
424
|
+
grant
|
|
425
|
+
end
|
|
426
|
+
# After the lock commits: a raise inside it would roll back the token the provider already rotated.
|
|
427
|
+
answer["access_token"].presence or raise Error, "#{label} answered a refresh with no access token"
|
|
428
|
+
end
|
|
429
|
+
|
|
430
|
+
def cached_access_token(connection, stale:, now:)
|
|
431
|
+
connection.with_lock do
|
|
432
|
+
current = connection.access_token
|
|
433
|
+
next current if stale.present? && current != stale
|
|
434
|
+
next current if stale.blank? && connection.access_fresh?(now)
|
|
435
|
+
raise Revoked, "#{label}: this connection holds no refresh token; connect again" if connection.refresh_token.blank?
|
|
436
|
+
|
|
437
|
+
grant = token_request(connection.account_id, { grant_type: "refresh_token", refresh_token: connection.refresh_token })
|
|
438
|
+
raise Error, "#{label} answered a refresh with no access token" if grant["access_token"].blank?
|
|
439
|
+
|
|
440
|
+
connection.rotate!(grant, now:)
|
|
441
|
+
grant["access_token"]
|
|
442
|
+
end
|
|
443
|
+
end
|
|
444
|
+
|
|
445
|
+
def memory_access_token(account, now:)
|
|
446
|
+
account = normalize_account(account) or raise InvalidAccount, "not a #{label} account"
|
|
447
|
+
cache_key = account.downcase
|
|
448
|
+
cached = @cache_lock.synchronize { @cache[cache_key] }
|
|
449
|
+
return cached.value if cached && cached.expires_at > now
|
|
450
|
+
|
|
451
|
+
form = { grant_type: "client_credentials" }
|
|
452
|
+
form[:scope] = scopes.join(" ") if scopes.any?
|
|
453
|
+
answer = token_request(account, form)
|
|
454
|
+
value = answer["access_token"].presence or raise Error, "#{label} answered a token request with no access token"
|
|
455
|
+
lifetime = answer["expires_in"].to_i
|
|
456
|
+
@cache_lock.synchronize { @cache[cache_key] = Token.new(value, now + lifetime - refresh_margin) }
|
|
457
|
+
value
|
|
458
|
+
end
|
|
459
|
+
|
|
460
|
+
def token_request(account, form)
|
|
461
|
+
post(url_for(:token, account), form, auth: client_auth, format: :form)
|
|
462
|
+
end
|
|
463
|
+
|
|
464
|
+
def post(url, form, auth:, format:, allow_empty: false)
|
|
465
|
+
ensure_configured!
|
|
466
|
+
headers = { "Accept" => "application/json",
|
|
467
|
+
"Content-Type" => format == :json ? "application/json" : "application/x-www-form-urlencoded" }
|
|
468
|
+
case auth
|
|
469
|
+
when :form then form = form.merge(client_id:, client_secret:)
|
|
470
|
+
when :secret_only then form = form.merge(client_secret:)
|
|
471
|
+
when :basic then headers["Authorization"] = "Basic #{Base64.strict_encode64("#{client_id}:#{client_secret}")}"
|
|
472
|
+
end
|
|
473
|
+
status, body, answered = call(url, form, headers)
|
|
474
|
+
trace = record_trace(answered, call: form.key?(:token) ? "revoke" : form[:grant_type].to_s, status:)
|
|
475
|
+
json = parse(body)
|
|
476
|
+
# A revoke (allow_empty) is confirmed by any 2xx, a 204 included; a token answer must be a 200 with a body.
|
|
477
|
+
return json if allow_empty ? (200..299).cover?(status) : (status == 200 && json.any?)
|
|
478
|
+
|
|
479
|
+
raise_for(status, json, trace)
|
|
480
|
+
end
|
|
481
|
+
|
|
482
|
+
def raise_for(status, json, trace = nil)
|
|
483
|
+
detail = json["error_description"].to_s.lines.first.to_s.strip
|
|
484
|
+
detail = (json["error"] || json["message"] || json["errorMessage"]).to_s if detail.empty?
|
|
485
|
+
detail = "no detail" if detail.empty?
|
|
486
|
+
traced = { trace_header:, trace_id: trace }
|
|
487
|
+
raise RateLimited.new("#{label} is throttling this app (#{status}); try again in a few minutes", **traced) if rate_limited_statuses.include?(status)
|
|
488
|
+
raise Revoked.new("#{label} no longer accepts this connection (#{detail}); connect again", **traced) if revoked?(status, json, detail)
|
|
489
|
+
|
|
490
|
+
raise Error.new("#{label} answered #{status}: #{detail}", **traced)
|
|
491
|
+
end
|
|
492
|
+
|
|
493
|
+
def revoked?(status, json, detail)
|
|
494
|
+
return false unless [400, 401, 403].include?(status)
|
|
495
|
+
|
|
496
|
+
revoked_errors.include?(json["error"].to_s) || (revoked_pattern ? revoked_pattern.match?(detail) : false)
|
|
497
|
+
end
|
|
498
|
+
|
|
499
|
+
def parse(body)
|
|
500
|
+
json = JSON.parse(body.to_s)
|
|
501
|
+
json.is_a?(Hash) ? json : {}
|
|
502
|
+
rescue JSON::ParserError
|
|
503
|
+
{}
|
|
504
|
+
end
|
|
505
|
+
|
|
506
|
+
# [status, body, response headers]. A stand-in may answer [status, body]
|
|
507
|
+
# or [status, body, { "header" => "value" }].
|
|
508
|
+
def call(url, form, headers)
|
|
509
|
+
return http.call(url, form, headers) if http
|
|
510
|
+
|
|
511
|
+
uri = URI(url)
|
|
512
|
+
raise Error, "#{label}: a token endpoint must be https" unless uri.scheme == "https"
|
|
513
|
+
|
|
514
|
+
request = Net::HTTP::Post.new(uri)
|
|
515
|
+
headers.each { |name, value| request[name] = value }
|
|
516
|
+
request.body = headers["Content-Type"] == "application/json" ? JSON.generate(form) : URI.encode_www_form(form)
|
|
517
|
+
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 20) { _1.request(request) }
|
|
518
|
+
[response.code.to_i, response.body, response]
|
|
519
|
+
rescue *NETWORK_ERRORS => e
|
|
520
|
+
raise Error, "#{label} could not be reached: #{e.class}"
|
|
521
|
+
end
|
|
522
|
+
end
|
|
523
|
+
end
|
|
524
|
+
end
|
data/lib/studio/engine.rb
CHANGED
|
@@ -315,6 +315,14 @@ module Studio
|
|
|
315
315
|
app.config.filter_parameters += [/(\A|\.)voice\.(embeddings|embedding|audio)\z/, /\Avoice_embedding\z/]
|
|
316
316
|
end
|
|
317
317
|
|
|
318
|
+
# The connections' log filter (Studio::Connections::LOG_FILTER): each
|
|
319
|
+
# provider's filter_keys by exact key, and the auth code on the connection
|
|
320
|
+
# controllers. One lambda that reads the registry when it runs, so a
|
|
321
|
+
# provider declared in a host initializer, after this, is covered.
|
|
322
|
+
initializer "studio.connections.filter_parameters" do |app|
|
|
323
|
+
app.config.filter_parameters += [Studio::Connections::LOG_FILTER]
|
|
324
|
+
end
|
|
325
|
+
|
|
318
326
|
initializer "studio.footer_only_eager_load" do
|
|
319
327
|
next if Studio.active_record?
|
|
320
328
|
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Studio
|
|
4
|
+
module Integrations
|
|
5
|
+
# EGNYTE, the connection only. A host's readers (folders, files) are its
|
|
6
|
+
# own; they call Studio.integration(:egnyte).api_base(connection).
|
|
7
|
+
#
|
|
8
|
+
# * Every Egnyte domain answers on its own host, <domain>.egnyte.com, so
|
|
9
|
+
# the admin types the domain at Connect (a POST, CSRF-checked). It is
|
|
10
|
+
# normalized ("Acme", "acme.egnyte.com" and "https://acme.egnyte.com/"
|
|
11
|
+
# are all "acme") and held to a DNS label before it reaches a URL.
|
|
12
|
+
# * One scope, Egnyte.filesystem, on the authorize URL and the exchange.
|
|
13
|
+
# The sign-in page and the token endpoint share one path.
|
|
14
|
+
# * CACHED tokens: the access token lives 30 days and Egnyte asks callers
|
|
15
|
+
# to cache it (its token endpoint allows about 100 requests an hour), so
|
|
16
|
+
# the row keeps it and refreshes only within a day of its expiry or after
|
|
17
|
+
# a 401. A refresh answers a new pair, stored before use.
|
|
18
|
+
# * The revoke takes the token and the client secret, not the id.
|
|
19
|
+
# * The token endpoint throttles with a 409 (and the API with a 429); an
|
|
20
|
+
# "invalid refresh token" detail means the grant is gone.
|
|
21
|
+
#
|
|
22
|
+
# Checked against the hub's Egnyte::OAuthClient, EgnyteConnection and
|
|
23
|
+
# Egnyte::Reader (mcritchie-studio), which cite Egnyte's authentication docs.
|
|
24
|
+
module Egnyte
|
|
25
|
+
HOST_SUFFIX = ".egnyte.com"
|
|
26
|
+
TOKEN_PATH = "/puboauth/token"
|
|
27
|
+
REVOKE_PATH = "/pubapi/v1/tokens/revoke"
|
|
28
|
+
API_PATH = "/pubapi/v1"
|
|
29
|
+
SCOPE = "Egnyte.filesystem"
|
|
30
|
+
# A DNS label: what may stand before .egnyte.com. Nothing else reaches a URL.
|
|
31
|
+
DOMAIN = /\A[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\z/
|
|
32
|
+
|
|
33
|
+
def self.host(domain) = "https://#{domain}#{HOST_SUFFIX}"
|
|
34
|
+
|
|
35
|
+
# The bare domain from what an admin typed, lower-cased (still unchecked).
|
|
36
|
+
def self.normalize(value)
|
|
37
|
+
value.to_s.strip.downcase.sub(%r{\Ahttps?://}, "").sub(%r{[/?#].*\z}, "").delete_suffix(HOST_SUFFIX)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
Integrations.register :egnyte,
|
|
41
|
+
label: "Egnyte",
|
|
42
|
+
summary: "An Egnyte domain's files, read with a user's own sign-in.",
|
|
43
|
+
connection: {
|
|
44
|
+
authorize_url: ->(domain) { "#{Egnyte.host(domain)}#{TOKEN_PATH}" },
|
|
45
|
+
token_url: ->(domain) { "#{Egnyte.host(domain)}#{TOKEN_PATH}" },
|
|
46
|
+
revoke_url: ->(domain) { "#{Egnyte.host(domain)}#{REVOKE_PATH}" },
|
|
47
|
+
scopes: [SCOPE], exchange_params: { scope: SCOPE },
|
|
48
|
+
client_auth: :form, revoke_auth: :secret_only,
|
|
49
|
+
refresh: :cached, refresh_margin: 1.day,
|
|
50
|
+
account: :connect, account_param: "egnyte_domain", account_format: DOMAIN,
|
|
51
|
+
normalize_account: ->(value) { Egnyte.normalize(value) },
|
|
52
|
+
rate_limited_statuses: [409, 429], revoked_pattern: /invalid refresh token|invalid_grant/i,
|
|
53
|
+
refusal_hint: "Check the developer key's redirect URI, then start again."
|
|
54
|
+
},
|
|
55
|
+
account_label: "Egnyte domain",
|
|
56
|
+
account_hint: "yourcompany (from yourcompany.egnyte.com)",
|
|
57
|
+
describe: lambda { |_integration, grant:, account:, get:|
|
|
58
|
+
token = grant["access_token"].to_s
|
|
59
|
+
next {} if token.empty?
|
|
60
|
+
|
|
61
|
+
username = get.call("#{Egnyte.host(account)}#{API_PATH}/whoami", token)["username"].to_s.strip
|
|
62
|
+
{ metadata: username.empty? ? {} : { "username" => username } }
|
|
63
|
+
},
|
|
64
|
+
default_label: ->(domain) { "#{domain}#{HOST_SUFFIX}" },
|
|
65
|
+
api_base: ->(_integration, connection) { "#{Egnyte.host(connection.account_id)}#{API_PATH}" },
|
|
66
|
+
stand_in: { answer: { "username" => "stand-in" } }
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
end
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Studio
|
|
4
|
+
module Integrations
|
|
5
|
+
# MICROSOFT 365 (Microsoft Graph, app-only), the connection only. A host's
|
|
6
|
+
# readers (users, teams, sites) are its own; they call
|
|
7
|
+
# Studio.integration(:microsoft_365).api_base(connection) with a token from
|
|
8
|
+
# Studio.connection(:microsoft_365).access_token(connection).
|
|
9
|
+
#
|
|
10
|
+
# * A tenant administrator approves the app at Microsoft's admin-consent
|
|
11
|
+
# page (common: the tenant is not known until they sign in). Microsoft
|
|
12
|
+
# comes back with ?tenant=<GUID>&admin_consent=True; anything but an
|
|
13
|
+
# approval refuses the callback.
|
|
14
|
+
# * The tenant id is private: stored only encrypted, the row keyed by a
|
|
15
|
+
# digest, the callback's tenant param kept out of the logs by exact
|
|
16
|
+
# key. It is lower-cased, so one tenant never makes two rows.
|
|
17
|
+
# * CLIENT CREDENTIALS on the tenant's own token endpoint, with the Graph
|
|
18
|
+
# .default scope (the application permissions the app registration
|
|
19
|
+
# lists). No refresh token exists: the access token lives in this
|
|
20
|
+
# process's memory only, per tenant.
|
|
21
|
+
# * unauthorized_client means the app is not found in, or not enabled
|
|
22
|
+
# for, the tenant: the grant is gone.
|
|
23
|
+
# * NO REVOKE endpoint: consent is removed in the tenant's admin center.
|
|
24
|
+
#
|
|
25
|
+
# Checked against the hub's Msgraph::OAuthClient and Msgraph::Reader
|
|
26
|
+
# (mcritchie-studio), which cite Microsoft's identity-platform docs.
|
|
27
|
+
module Microsoft365
|
|
28
|
+
LOGIN_HOST = "https://login.microsoftonline.com"
|
|
29
|
+
AUTHORIZE_URL = "#{LOGIN_HOST}/common/adminconsent"
|
|
30
|
+
SCOPE = "https://graph.microsoft.com/.default"
|
|
31
|
+
API_URL = "https://graph.microsoft.com/v1.0"
|
|
32
|
+
TENANT_ID = /\A\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\z/
|
|
33
|
+
|
|
34
|
+
Integrations.register :microsoft_365,
|
|
35
|
+
label: "Microsoft 365",
|
|
36
|
+
summary: "A Microsoft 365 tenant, read app-only after an administrator approves the app.",
|
|
37
|
+
connection: {
|
|
38
|
+
grant: :client_credentials,
|
|
39
|
+
authorize_url: AUTHORIZE_URL,
|
|
40
|
+
token_url: ->(tenant) { "#{LOGIN_HOST}/#{tenant}/oauth2/v2.0/token" },
|
|
41
|
+
scopes: [SCOPE],
|
|
42
|
+
account: :callback, account_param: "tenant", account_format: TENANT_ID,
|
|
43
|
+
normalize_account: ->(value) { value.to_s.strip.downcase },
|
|
44
|
+
private_account: true, filter_keys: %w[tenant],
|
|
45
|
+
revoked_errors: %w[unauthorized_client],
|
|
46
|
+
declined_errors: %w[access_denied permission_denied consent_required],
|
|
47
|
+
callback_check: lambda { |params|
|
|
48
|
+
"Microsoft did not report an approval. Nothing was connected." unless params[:admin_consent].to_s.casecmp?("true")
|
|
49
|
+
},
|
|
50
|
+
refusal_hint: "A tenant bought through a reseller may block the approval; otherwise check the app registration's redirect URI, then start again.",
|
|
51
|
+
revoke_note: "Remove the app in the tenant's Microsoft Entra admin center (Enterprise applications) to revoke its access there."
|
|
52
|
+
},
|
|
53
|
+
describe: lambda { |integration, grant:, account:, get:|
|
|
54
|
+
token = integration.provider.access_token(account)
|
|
55
|
+
{ label: get.call("#{API_URL}/organization/#{account}", token)["displayName"] }
|
|
56
|
+
},
|
|
57
|
+
default_label: ->(_tenant) { "Microsoft 365 tenant" },
|
|
58
|
+
api_base: ->(_integration, _connection) { API_URL },
|
|
59
|
+
stand_in: { callback_params: { tenant: "00000000-0000-0000-0000-000000000000", admin_consent: "True" },
|
|
60
|
+
answer: { "displayName" => "Stand-in Tenant" } }
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
end
|