Class: HaveAPI::DocumentationOAuth
- Inherits:
-
Object
- Object
- HaveAPI::DocumentationOAuth
- Defined in:
- lib/haveapi/documentation_oauth.rb
Overview
Optional confidential OAuth client used only by the HTML documentation.
Defined Under Namespace
Modules: Helpers Classes: Failure, Invalid, Transport
Constant Summary collapse
- COOKIE_LIMIT =
3800- RESPONSE_LIMIT =
16_384- PENDING_LIFETIME =
600- FIELDS =
%i[client_id client_secret redirect_uri session_secret scope session_lifetime switch_user switch_user_revoke_params].freeze
Instance Method Summary collapse
- #authenticate(handler, version) ⇒ Object
- #callback(handler) ⇒ Object
- #controls(handler, version) ⇒ Object
-
#initialize(**options) ⇒ DocumentationOAuth
constructor
A new instance of DocumentationOAuth.
- #inspect ⇒ Object
- #login(handler) ⇒ Object
- #logout(handler) ⇒ Object
- #mount(server, sinatra) ⇒ Object
Constructor Details
#initialize(**options) ⇒ DocumentationOAuth
Returns a new instance of DocumentationOAuth.
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 |
# File 'lib/haveapi/documentation_oauth.rb', line 68 def initialize(**) raise Invalid, 'Unknown documentation OAuth configuration' unless (.keys - FIELDS).empty? @client_id = scalar([:client_id], 256) @client_secret = scalar([:client_secret], 2048) @redirect_uri = endpoint([:redirect_uri], query: false) secret = [:session_secret] unless secret.is_a?(String) && secret.bytesize.between?(64, 4096) raise Invalid, 'Documentation OAuth requires a session secret of at least 64 bytes' end @scope = .fetch(:scope, []) unless @scope.is_a?(Array) && @scope.length <= 32 && @scope.all? do |value| value.is_a?(String) && value.bytesize.between?(1, 256) && value.match?(/\A[\x21\x23-\x5b\x5d-\x7e]+\z/) end raise Invalid, 'Invalid documentation OAuth scope' end @scope = @scope.map { |value| value.dup.freeze }.freeze @lifetime = .fetch(:session_lifetime, 3600) unless @lifetime.is_a?(Integer) && @lifetime.between?(1, 86_400) raise Invalid, 'Invalid documentation OAuth session lifetime' end @switch_user = .fetch(:switch_user, false) unless @switch_user.equal?(true) || @switch_user.equal?(false) raise Invalid, 'Invalid documentation OAuth switch-user capability' end revoke_params = .fetch(:switch_user_revoke_params, {}) unless revoke_params.is_a?(Hash) && revoke_params.all? do |name, value| name.is_a?(String) && value.is_a?(String) && !%w[client_id client_secret token token_type_hint].include?(name) end raise Invalid, 'Invalid documentation OAuth switch-user revoke parameters' end @switch_user_revoke_params = revoke_params.to_h { |name, value| [name.dup.freeze, value.dup.freeze] }.freeze @origin = "#{@redirect_uri.scheme}://#{@redirect_uri.host}" @origin += ":#{@redirect_uri.port}" unless @redirect_uri.port == 443 key = ActiveSupport::KeyGenerator.new(secret, iterations: 65_536) .generate_key('haveapi.documentation-oauth.v1', 32) @encryptor = ActiveSupport::MessageEncryptor.new(key, cipher: 'aes-256-gcm', serializer: JSON) @transport = Transport.new end |
Instance Method Details
#authenticate(handler, version) ⇒ Object
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 |
# File 'lib/haveapi/documentation_oauth.rb', line 143 def authenticate(handler, version) handler.instance_variable_set(:@documentation_oauth_csrf, nil) protect_response(handler, referrer_policy: 'strict-origin') return unless documentation_origin?(handler) && (handler.request.get? || handler.request.head?) session = (handler, 'session') return unless session user = @server.auth_chain.authenticate_oauth2_token(version, handler.request, session.fetch('token')) if user handler.instance_variable_set(:@documentation_oauth_csrf, session.fetch('csrf')) else (handler, 'session') handler.instance_variable_set(:@documentation_oauth_message, HaveAPI.('haveapi.documentation.oauth.session_ended')) end user end |
#callback(handler) ⇒ Object
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 |
# File 'lib/haveapi/documentation_oauth.rb', line 194 def callback(handler) protect_response(handler) require_origin(handler) pending = (handler, 'pending') (handler, 'pending') values = strict_query(handler, %w[code state error error_description error_uri]) unless pending && !values.has_key?('error') && nonce?(values['state']) && secure_equal?(values['state'], pending['state']) && token?(values['code']) raise Failure, 'Documentation sign-in failed' end data = JSON.parse(@transport.post(@endpoints.fetch(:token), credentials.merge( 'grant_type' => 'authorization_code', 'code' => values.fetch('code'), 'redirect_uri' => @redirect_uri.to_s, 'code_verifier' => pending.fetch('verifier') ))) unless data.is_a?(Hash) && token?(data['access_token']) && data['token_type'].to_s.downcase == 'bearer' raise Failure, 'Documentation sign-in failed' end duration = Float(data['expires_in']) raise Failure, 'Documentation sign-in failed' unless duration.finite? && duration > 0 expiry = Time.now.to_f + [duration, @lifetime].min (handler, 'session', { 'token' => data.fetch('access_token'), 'expires' => expiry, 'csrf' => SecureRandom.urlsafe_base64(32) }) handler.redirect(destination_url(return_location(pending.fetch('return'))), 303) rescue Failure, Invalid, JSON::ParserError, ArgumentError, TypeError failure_page(handler) end |
#controls(handler, version) ⇒ Object
161 162 163 164 165 166 167 168 169 170 171 172 173 |
# File 'lib/haveapi/documentation_oauth.rb', line 161 def controls(handler, version) selection = handler.documentation_selection destination = return_location('version' => version.to_s, **selection) csrf = handler.instance_variable_get(:@documentation_oauth_csrf) controls = { signed_in: !csrf.nil?, csrf_token: csrf, login_url: "#{@origin}#{@routes.fetch('login')}?#{URI.encode_www_form(destination)}", logout_url: "#{@origin}#{@routes.fetch('logout')}", message: handler.instance_variable_get(:@documentation_oauth_message) } controls[:switch_user] = true if @switch_user && csrf controls end |
#inspect ⇒ Object
114 115 116 |
# File 'lib/haveapi/documentation_oauth.rb', line 114 def inspect '#<HaveAPI::DocumentationOAuth configured>' end |
#login(handler) ⇒ Object
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 |
# File 'lib/haveapi/documentation_oauth.rb', line 175 def login(handler) protect_response(handler) require_origin(handler) destination = return_location(strict_query(handler, %w[version page resource fragment])) expiry = Time.now.to_f + PENDING_LIFETIME state = SecureRandom.urlsafe_base64(32) verifier = SecureRandom.urlsafe_base64(48) (handler, 'pending', { 'state' => state, 'verifier' => verifier, 'return' => destination, 'expires' => expiry }) query = URI.decode_www_form(@endpoints.fetch(:authorize).query.to_s) query += { client_id: @client_id, response_type: 'code', redirect_uri: @redirect_uri.to_s, scope: @scope.join(' '), state:, code_challenge_method: 'S256', code_challenge: Base64.urlsafe_encode64(Digest::SHA256.digest(verifier), padding: false) }.to_a target = @endpoints.fetch(:authorize).dup target.query = URI.encode_www_form(query) handler.redirect(target.to_s, 302) rescue Failure, Invalid failure_page(handler) end |
#logout(handler) ⇒ Object
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 |
# File 'lib/haveapi/documentation_oauth.rb', line 224 def logout(handler) protect_response(handler) require_origin(handler) switch_user = switch_user_request?(handler) session = (handler, 'session') csrf = handler.params['csrf'] unless handler.request.env['HTTP_ORIGIN'] == @origin && session && nonce?(csrf) && secure_equal?(csrf, session['csrf']) handler.halt(403, handler.documentation_t('oauth.sign_out_invalid')) end (handler, 'session') (handler, 'pending') parameters = credentials.merge('token' => session.fetch('token'), 'token_type_hint' => 'access_token') parameters.merge!(@switch_user_revoke_params) if switch_user begin @transport.post(@endpoints.fetch(:revoke), parameters) rescue Failure handler.halt(502, { 'content-type' => 'text/html; charset=utf-8' }, "<p>#{CGI.escapeHTML(handler.documentation_t('oauth.sign_out_incomplete'))}</p>" \ "<p><a href=\"#{CGI.escapeHTML(destination_url('version' => @server.default_version.to_s))}\">#{CGI.escapeHTML(handler.documentation_t('oauth.return'))}</a></p>") end if switch_user handler.redirect("#{@origin}#{@routes.fetch('login')}?#{URI.encode_www_form(version: @server.default_version.to_s)}", 303) end handler.redirect(destination_url('version' => @server.default_version.to_s), 303) end |
#mount(server, sinatra) ⇒ Object
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
# File 'lib/haveapi/documentation_oauth.rb', line 118 def mount(server, sinatra) raise Invalid, 'Documentation OAuth is already mounted' if @server @server = server @path = server.root.end_with?('/') ? server.root : "#{server.root}/" @routes = %w[login callback logout].to_h { |name| [name, "#{@path}_documentation/oauth/#{name}"] }.freeze unless @redirect_uri.path == @routes.fetch('callback') raise Invalid, 'Documentation OAuth callback does not match the API mount' end = server.auth_chain.provider_descriptions(server.default_version)[:oauth2] raise Invalid, 'Documentation OAuth requires an OAuth provider' unless .is_a?(Hash) @endpoints = %i[authorize token revoke].to_h do |name| [name, endpoint([:"#{name}_url"])] end.freeze binding = Digest::SHA256.hexdigest([@client_id, @redirect_uri.to_s, @path].join("\0")) @purposes = %w[pending session].to_h { |kind| [kind, "haveapi.docs.#{binding}.#{kind}"] }.freeze @names = %w[pending session].to_h { |kind| [kind, "haveapi_docs_#{Digest::SHA256.hexdigest(@path)[0, 12]}_#{kind}"] }.freeze that = self sinatra.get(@routes.fetch('login')) { with_documentation_locale(persist: false) { that.login(self) } } sinatra.get(@routes.fetch('callback')) { with_documentation_locale(persist: false) { that.callback(self) } } sinatra.post(@routes.fetch('logout')) { with_documentation_locale(persist: false) { that.logout(self) } } end |