Class: Ably::Auth
- Inherits:
-
Object
- Object
- Ably::Auth
- Includes:
- Modules::Conversions, Modules::HttpHelpers
- Defined in:
- lib/submodules/ably-ruby/lib/ably/auth.rb
Overview
Auth is responsible for authentication with Ably using basic or token authentication
Find out more about Ably authentication at: www.ably.io/documentation/general/authentication/
Constant Summary collapse
- TOKEN_DEFAULTS =
Default capability Hash object and TTL in seconds for issued tokens
{ capability: { '*' => ['*'] }, ttl: 60 * 60 # 1 hour in seconds }
Instance Attribute Summary collapse
-
#client_id ⇒ String
readonly
The provided client ID, used for identifying this client for presence purposes.
-
#current_token_details ⇒ Ably::Models::TokenDetails
readonly
Current Models::TokenDetails issued by this library or one of the provided callbacks used to authenticate requests.
-
#key ⇒ String
readonly
Complete API key containing both the key name and key secret, if present.
-
#key_name ⇒ String
readonly
Key name (public part of the API key), if present.
-
#key_secret ⇒ String
readonly
Key secret (private secure part of the API key), if present.
-
#options ⇒ Hash
(also: #auth_options)
readonly
Auth options configured for this client.
-
#token ⇒ String
readonly
Token string provided to the Client constructor that is used to authenticate all requests.
Instance Method Summary collapse
-
#auth_header ⇒ String
Auth header string used in HTTP requests to Ably.
-
#auth_params ⇒ Hash
Auth params used in URI endpoint for Realtime connections.
-
#authentication_security_requirements_met? ⇒ Boolean
Returns false when attempting to send an API Key over a non-secure connection Token auth must be used for non-secure connections.
-
#authorise(options = {}) ⇒ Ably::Models::TokenDetails
Ensures valid auth credentials are present for the library instance.
-
#create_token_request(options = {}) ⇒ Models::TokenRequest
Creates and signs a token request that can then subsequently be used by any client to request a token.
-
#initialize(client, options) ⇒ Auth
constructor
Creates an Auth object.
-
#request_token(options = {}) ⇒ Ably::Models::TokenDetails
Request a Models::TokenDetails which can be used to make authenticated token based requests.
-
#token_renewable? ⇒ Boolean
True if prerequisites for creating a new token request are present.
-
#using_basic_auth? ⇒ Boolean
True when Basic Auth is being used to authenticate with Ably.
-
#using_token_auth? ⇒ Boolean
True when Token Auth is being used to authenticate with Ably.
Constructor Details
#initialize(client, options) ⇒ Auth
Creates an Auth object
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/submodules/ably-ruby/lib/ably/auth.rb', line 46 def initialize(client, ) ensure_valid_auth_attributes = .dup @client = client @options = unless .kind_of?(Hash) raise ArgumentError, 'Expected auth_options to be a Hash' end if [:key] && ([:key_secret] || [:key_name]) raise ArgumentError, 'key and key_name or key_secret are mutually exclusive. Provider either a key or key_name & key_secret' end split_api_key_into_key_and_secret! if [:key] if using_basic_auth? && !api_key_present? raise ArgumentError, 'key is missing. Either an API key, token, or token auth method must be provided' end if has_client_id? raise ArgumentError, 'client_id cannot be provided without a complete API key. Key name & Secret is needed to authenticate with Ably and obtain a token' unless api_key_present? ensure_utf_8 :client_id, client_id end @options.freeze end |
Instance Attribute Details
#client_id ⇒ String (readonly)
Returns The provided client ID, used for identifying this client for presence purposes.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 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 67 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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 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 204 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 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 |
# File 'lib/submodules/ably-ruby/lib/ably/auth.rb', line 27 class Auth include Ably::Modules::Conversions include Ably::Modules::HttpHelpers # Default capability Hash object and TTL in seconds for issued tokens TOKEN_DEFAULTS = { capability: { '*' => ['*'] }, ttl: 60 * 60 # 1 hour in seconds } attr_reader :options, :current_token_details alias_method :auth_options, :options # Creates an Auth object # # @param [Ably::Rest::Client] client {Ably::Rest::Client} this Auth object uses # @param [Hash] options (see Ably::Rest::Client#initialize) # @option (see Ably::Rest::Client#initialize) # def initialize(client, ) ensure_valid_auth_attributes = .dup @client = client @options = unless .kind_of?(Hash) raise ArgumentError, 'Expected auth_options to be a Hash' end if [:key] && ([:key_secret] || [:key_name]) raise ArgumentError, 'key and key_name or key_secret are mutually exclusive. Provider either a key or key_name & key_secret' end split_api_key_into_key_and_secret! if [:key] if using_basic_auth? && !api_key_present? raise ArgumentError, 'key is missing. Either an API key, token, or token auth method must be provided' end if has_client_id? raise ArgumentError, 'client_id cannot be provided without a complete API key. Key name & Secret is needed to authenticate with Ably and obtain a token' unless api_key_present? ensure_utf_8 :client_id, client_id end @options.freeze end # Ensures valid auth credentials are present for the library instance. This may rely on an already-known and valid token, and will obtain a new token if necessary. # # In the event that a new token request is made, the specified options are used. # # @param [Hash] options the options for the token request # @option options (see #request_token) # @option options [String] :key API key comprising the key name and key secret in a single string # @option options [Boolean] :force obtains a new token even if the current token is valid # # @return (see #request_token) # # @example # # will issue a simple token request using basic auth # client = Ably::Rest::Client.new(key: 'key.id:secret') # token = client.auth.authorise # # # will use token request from block to authorise if not already authorised # token = client.auth.authorise do |options| # # create token_request object # token_request # end # def ( = {}) ensure_valid_auth_attributes if current_token_details && ![:force] return current_token_details unless current_token_details.expired? end = .clone split_api_key_into_key_and_secret! if [:key] @options = @options.merge() # update default options @current_token_details = request_token() end # Request a {Ably::Models::TokenDetails} which can be used to make authenticated token based requests # # @param [Hash] options the options for the token request # @option options [String] :key complete API key for the designated application # @option options [String] :client_id client ID identifying this connection to other clients (defaults to client client_id if configured) # @option options [String] :auth_url a URL to be used to GET or POST a set of token request params, to obtain a signed token request. # @option options [Hash] :auth_headers a set of application-specific headers to be added to any request made to the authUrl # @option options [Hash] :auth_params a set of application-specific query params to be added to any request made to the authUrl # @option options [Symbol] :auth_method HTTP method to use with auth_url, must be either `:get` or `:post` (defaults to :get) # @option options [Proc] :auth_callback this Proc / block will be called with the {#auth_options Auth#auth_options Hash} as the first argument whenever a new token is required. # The Proc should return a token string, {Ably::Models::TokenDetails} or JSON equivalent, {Ably::Models::TokenRequest} or JSON equivalent # @option options [Integer] :ttl validity time in seconds for the requested {Ably::Models::TokenDetails}. Limits may apply, see {https://www.ably.io/documentation/other/authentication} # @option options [Hash] :capability canonicalised representation of the resource paths and associated operations # @option options [Boolean] :query_time when true will query the {https://www.ably.io Ably} system for the current time instead of using the local time # @option options [Time] :timestamp the time of the of the request # @option options [String] :nonce an unquoted, unescaped random string of at least 16 characters # # @return [Ably::Models::TokenDetails] # # @example # # simple token request using basic auth # client = Ably::Rest::Client.new(key: 'key.id:secret') # token = client.auth.request_token # # # token request using auth block # token = client.auth.request_token do |options| # # create token_request object # token_request # end # def request_token( = {}) ensure_valid_auth_attributes = .merge() token_request = if auth_callback = .delete(:auth_callback) auth_callback.call() elsif auth_url = .delete(:auth_url) token_request_from_auth_url(auth_url, ) else create_token_request() end case token_request when Ably::Models::TokenDetails return token_request when Hash return Ably::Models::TokenDetails.new(token_request) if IdiomaticRubyWrapper(token_request).has_key?(:issued) when String return Ably::Models::TokenDetails.new(token: token_request) end token_request = Ably::Models::TokenRequest(token_request) response = client.post("/keys/#{token_request.key_name}/requestToken", token_request.hash, send_auth_header: false, disable_automatic_reauthorise: true) Ably::Models::TokenDetails.new(response.body) end # Creates and signs a token request that can then subsequently be used by any client to request a token # # @param [Hash] options the options for the token request # @option options [String] :key complete API key for the designated application # @option options [String] :client_id client ID identifying this connection to other clients # @option options [Integer] :ttl validity time in seconds for the requested {Ably::Models::TokenDetails}. Limits may apply, see {https://www.ably.io/documentation/other/authentication} # @option options [Hash] :capability canonicalised representation of the resource paths and associated operations # @option options [Boolean] :query_time when true will query the {https://www.ably.io Ably} system for the current time instead of using the local time # @option options [Time] :timestamp the time of the of the request # @option options [String] :nonce an unquoted, unescaped random string of at least 16 characters # # @return [Models::TokenRequest] # # @example # client.auth.create_token_request(id: 'asd.asd', ttl: 3600) # #<Ably::Models::TokenRequest:0x007fd5d919df78 # # @hash={ # # :id=>"asds.adsa", # # :clientId=>nil, # # :ttl=>3600000, # # :timestamp=>1428973674000, # # :capability=>"{\"*\":[\"*\"]}", # # :nonce=>"95e543b88299f6bae83df9b12fbd1ecd", # # :mac=>"881oZHeFo6oMim7....uE56a8gUxHw=" # # } # #>> def create_token_request( = {}) ensure_valid_auth_attributes = .clone split_api_key_into_key_and_secret! if [:key] request_key_name = .delete(:key_name) || key_name request_key_secret = .delete(:key_secret) || key_secret raise Ably::Exceptions::TokenRequestError, 'Key Name and Key Secret are required to generate a new token request' unless request_key_name && request_key_secret = if [:query_time] client.time else .delete(:timestamp) || Time.now end = Time.at() if .kind_of?(Integer) token_request = { keyName: [:key_name] || request_key_name, clientId: [:client_id] || client_id, ttl: (([:ttl] || TOKEN_DEFAULTS.fetch(:ttl)) * 1000).to_i, timestamp: (.to_f * 1000).round, capability: [:capability] || TOKEN_DEFAULTS.fetch(:capability), nonce: [:nonce] || SecureRandom.hex.force_encoding('UTF-8') } token_request[:capability] = JSON.dump(token_request[:capability]) if token_request[:capability].is_a?(Hash) token_request[:mac] = sign_params(token_request, request_key_secret) # Undocumented feature to request a persisted token token_request[:persisted] = [:persisted] if [:persisted] Models::TokenRequest.new(token_request) end def key "#{key_name}:#{key_secret}" if api_key_present? end def key_name [:key_name] end def key_secret [:key_secret] end # True when Basic Auth is being used to authenticate with Ably def using_basic_auth? !using_token_auth? end # True when Token Auth is being used to authenticate with Ably def using_token_auth? return [:use_token_auth] if .has_key?(:use_token_auth) token || current_token_details || has_client_id? || token_creatable_externally? end def client_id [:client_id] end def token token_object = [:token] || [:token_details] if token_object.kind_of?(Ably::Models::TokenDetails) token_object.token else token_object end end # Auth header string used in HTTP requests to Ably # # @return [String] HTTP authentication value used in HTTP_AUTHORIZATION header def auth_header if using_token_auth? token_auth_header else basic_auth_header end end # Auth params used in URI endpoint for Realtime connections # # @return [Hash] Auth params for a new Realtime connection def auth_params if using_token_auth? token_auth_params else basic_auth_params end end # True if prerequisites for creating a new token request are present # # One of the following criterion must be met: # * Valid API key and token option not provided as token options cannot be determined # * Authentication callback for new token requests # * Authentication URL for new token requests # # @return [Boolean] def token_renewable? token_creatable_externally? || (api_key_present? && !token) end # Returns false when attempting to send an API Key over a non-secure connection # Token auth must be used for non-secure connections # # @return [Boolean] def authentication_security_requirements_met? client.use_tls? || using_token_auth? end private attr_reader :client def ensure_valid_auth_attributes(attributes) if attributes[:timestamp] unless attributes[:timestamp].kind_of?(Time) || attributes[:timestamp].kind_of?(Numeric) raise ArgumentError, ':timestamp must be a Time or positive Integer value of seconds since epoch' end end if attributes[:ttl] unless attributes[:ttl].kind_of?(Numeric) && attributes[:ttl].to_f > 0 raise ArgumentError, ':ttl must be a positive Numeric value representing time to live in seconds' end end if attributes[:auth_headers] unless attributes[:auth_headers].kind_of?(Hash) raise ArgumentError, ':auth_headers must be a valid Hash' end end if attributes[:auth_params] unless attributes[:auth_params].kind_of?(Hash) raise ArgumentError, ':auth_params must be a valid Hash' end end if attributes[:auth_method] unless %(get post).include?(attributes[:auth_method].to_s) raise ArgumentError, ':auth_method must be either :get or :post' end end if attributes[:auth_callback] unless attributes[:auth_callback].respond_to?(:call) raise ArgumentError, ':auth_callback must be a Proc' end end end def ensure_api_key_sent_over_secure_connection raise Ably::Exceptions::InsecureRequestError, 'Cannot use Basic Auth over non-TLS connections' unless authentication_security_requirements_met? end # Basic Auth HTTP Authorization header value def basic_auth_header ensure_api_key_sent_over_secure_connection "Basic #{encode64("#{key}")}" end def split_api_key_into_key_and_secret!() api_key_parts = [:key].to_s.match(/(?<name>[\w_-]+\.[\w_-]+):(?<secret>[\w_-]+)/) raise ArgumentError, 'key is invalid' unless api_key_parts [:key_name] = api_key_parts[:name].encode(Encoding::UTF_8) [:key_secret] = api_key_parts[:secret].encode(Encoding::UTF_8) .delete :key end # Returns the current token if it exists or authorises and retrieves a token def token_auth_string if token token else .token end end # Token Auth HTTP Authorization header value def token_auth_header "Bearer #{encode64(token_auth_string)}" end # Basic Auth params to authenticate the Realtime connection def basic_auth_params ensure_api_key_sent_over_secure_connection { key: key } end # Token Auth params to authenticate the Realtime connection def token_auth_params { access_token: token_auth_string } end # Sign the request params using the secret # # @return [Hash] def sign_params(params, secret) text = params.values_at( :keyName, :ttl, :capability, :clientId, :timestamp, :nonce ).map do |val| "#{val}\n" end.join('') encode64( OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, secret, text) ) end # Retrieve a token request from a specified URL, expects a JSON response # # @return [Hash] def token_request_from_auth_url(auth_url, = {}) uri = URI.parse(auth_url) connection = Faraday.new("#{uri.scheme}://#{uri.host}", ) method = [:auth_method] || :get response = connection.send(method) do |request| request.url uri.path request.params = [:auth_params] || {} request.headers = [:auth_headers] || {} end if !response.body.kind_of?(Hash) && response.headers['Content-Type'] != 'text/plain' raise Ably::Exceptions::InvalidResponseBody, "Content Type #{response.headers['Content-Type']} is not supported by this client library" end response.body end # Return a Hash of connection options to initiate the Faraday::Connection with # # @return [Hash] def @connection_options ||= { builder: middleware, headers: { accept: client.mime_type, user_agent: user_agent }, request: { open_timeout: 5, timeout: 10 } } end # Return a Faraday middleware stack to initiate the Faraday::Connection with # # @see http://mislav.uniqpath.com/2011/07/faraday-advanced-http/ def middleware @middleware ||= Faraday::RackBuilder.new do |builder| setup_outgoing_middleware builder # Raise exceptions if response code is invalid builder.use Ably::Rest::Middleware::ExternalExceptions setup_incoming_middleware builder, client.logger # Set Faraday's HTTP adapter builder.adapter Faraday.default_adapter end end def auth_callback_present? !![:auth_callback] end def token_url_present? !![:auth_url] end def token_creatable_externally? auth_callback_present? || token_url_present? end def has_client_id? !!client_id end def api_key_present? key_name && key_secret end end |
#current_token_details ⇒ Ably::Models::TokenDetails (readonly)
Returns Current Models::TokenDetails issued by this library or one of the provided callbacks used to authenticate requests.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 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 67 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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 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 204 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 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 |
# File 'lib/submodules/ably-ruby/lib/ably/auth.rb', line 27 class Auth include Ably::Modules::Conversions include Ably::Modules::HttpHelpers # Default capability Hash object and TTL in seconds for issued tokens TOKEN_DEFAULTS = { capability: { '*' => ['*'] }, ttl: 60 * 60 # 1 hour in seconds } attr_reader :options, :current_token_details alias_method :auth_options, :options # Creates an Auth object # # @param [Ably::Rest::Client] client {Ably::Rest::Client} this Auth object uses # @param [Hash] options (see Ably::Rest::Client#initialize) # @option (see Ably::Rest::Client#initialize) # def initialize(client, ) ensure_valid_auth_attributes = .dup @client = client @options = unless .kind_of?(Hash) raise ArgumentError, 'Expected auth_options to be a Hash' end if [:key] && ([:key_secret] || [:key_name]) raise ArgumentError, 'key and key_name or key_secret are mutually exclusive. Provider either a key or key_name & key_secret' end split_api_key_into_key_and_secret! if [:key] if using_basic_auth? && !api_key_present? raise ArgumentError, 'key is missing. Either an API key, token, or token auth method must be provided' end if has_client_id? raise ArgumentError, 'client_id cannot be provided without a complete API key. Key name & Secret is needed to authenticate with Ably and obtain a token' unless api_key_present? ensure_utf_8 :client_id, client_id end @options.freeze end # Ensures valid auth credentials are present for the library instance. This may rely on an already-known and valid token, and will obtain a new token if necessary. # # In the event that a new token request is made, the specified options are used. # # @param [Hash] options the options for the token request # @option options (see #request_token) # @option options [String] :key API key comprising the key name and key secret in a single string # @option options [Boolean] :force obtains a new token even if the current token is valid # # @return (see #request_token) # # @example # # will issue a simple token request using basic auth # client = Ably::Rest::Client.new(key: 'key.id:secret') # token = client.auth.authorise # # # will use token request from block to authorise if not already authorised # token = client.auth.authorise do |options| # # create token_request object # token_request # end # def ( = {}) ensure_valid_auth_attributes if current_token_details && ![:force] return current_token_details unless current_token_details.expired? end = .clone split_api_key_into_key_and_secret! if [:key] @options = @options.merge() # update default options @current_token_details = request_token() end # Request a {Ably::Models::TokenDetails} which can be used to make authenticated token based requests # # @param [Hash] options the options for the token request # @option options [String] :key complete API key for the designated application # @option options [String] :client_id client ID identifying this connection to other clients (defaults to client client_id if configured) # @option options [String] :auth_url a URL to be used to GET or POST a set of token request params, to obtain a signed token request. # @option options [Hash] :auth_headers a set of application-specific headers to be added to any request made to the authUrl # @option options [Hash] :auth_params a set of application-specific query params to be added to any request made to the authUrl # @option options [Symbol] :auth_method HTTP method to use with auth_url, must be either `:get` or `:post` (defaults to :get) # @option options [Proc] :auth_callback this Proc / block will be called with the {#auth_options Auth#auth_options Hash} as the first argument whenever a new token is required. # The Proc should return a token string, {Ably::Models::TokenDetails} or JSON equivalent, {Ably::Models::TokenRequest} or JSON equivalent # @option options [Integer] :ttl validity time in seconds for the requested {Ably::Models::TokenDetails}. Limits may apply, see {https://www.ably.io/documentation/other/authentication} # @option options [Hash] :capability canonicalised representation of the resource paths and associated operations # @option options [Boolean] :query_time when true will query the {https://www.ably.io Ably} system for the current time instead of using the local time # @option options [Time] :timestamp the time of the of the request # @option options [String] :nonce an unquoted, unescaped random string of at least 16 characters # # @return [Ably::Models::TokenDetails] # # @example # # simple token request using basic auth # client = Ably::Rest::Client.new(key: 'key.id:secret') # token = client.auth.request_token # # # token request using auth block # token = client.auth.request_token do |options| # # create token_request object # token_request # end # def request_token( = {}) ensure_valid_auth_attributes = .merge() token_request = if auth_callback = .delete(:auth_callback) auth_callback.call() elsif auth_url = .delete(:auth_url) token_request_from_auth_url(auth_url, ) else create_token_request() end case token_request when Ably::Models::TokenDetails return token_request when Hash return Ably::Models::TokenDetails.new(token_request) if IdiomaticRubyWrapper(token_request).has_key?(:issued) when String return Ably::Models::TokenDetails.new(token: token_request) end token_request = Ably::Models::TokenRequest(token_request) response = client.post("/keys/#{token_request.key_name}/requestToken", token_request.hash, send_auth_header: false, disable_automatic_reauthorise: true) Ably::Models::TokenDetails.new(response.body) end # Creates and signs a token request that can then subsequently be used by any client to request a token # # @param [Hash] options the options for the token request # @option options [String] :key complete API key for the designated application # @option options [String] :client_id client ID identifying this connection to other clients # @option options [Integer] :ttl validity time in seconds for the requested {Ably::Models::TokenDetails}. Limits may apply, see {https://www.ably.io/documentation/other/authentication} # @option options [Hash] :capability canonicalised representation of the resource paths and associated operations # @option options [Boolean] :query_time when true will query the {https://www.ably.io Ably} system for the current time instead of using the local time # @option options [Time] :timestamp the time of the of the request # @option options [String] :nonce an unquoted, unescaped random string of at least 16 characters # # @return [Models::TokenRequest] # # @example # client.auth.create_token_request(id: 'asd.asd', ttl: 3600) # #<Ably::Models::TokenRequest:0x007fd5d919df78 # # @hash={ # # :id=>"asds.adsa", # # :clientId=>nil, # # :ttl=>3600000, # # :timestamp=>1428973674000, # # :capability=>"{\"*\":[\"*\"]}", # # :nonce=>"95e543b88299f6bae83df9b12fbd1ecd", # # :mac=>"881oZHeFo6oMim7....uE56a8gUxHw=" # # } # #>> def create_token_request( = {}) ensure_valid_auth_attributes = .clone split_api_key_into_key_and_secret! if [:key] request_key_name = .delete(:key_name) || key_name request_key_secret = .delete(:key_secret) || key_secret raise Ably::Exceptions::TokenRequestError, 'Key Name and Key Secret are required to generate a new token request' unless request_key_name && request_key_secret = if [:query_time] client.time else .delete(:timestamp) || Time.now end = Time.at() if .kind_of?(Integer) token_request = { keyName: [:key_name] || request_key_name, clientId: [:client_id] || client_id, ttl: (([:ttl] || TOKEN_DEFAULTS.fetch(:ttl)) * 1000).to_i, timestamp: (.to_f * 1000).round, capability: [:capability] || TOKEN_DEFAULTS.fetch(:capability), nonce: [:nonce] || SecureRandom.hex.force_encoding('UTF-8') } token_request[:capability] = JSON.dump(token_request[:capability]) if token_request[:capability].is_a?(Hash) token_request[:mac] = sign_params(token_request, request_key_secret) # Undocumented feature to request a persisted token token_request[:persisted] = [:persisted] if [:persisted] Models::TokenRequest.new(token_request) end def key "#{key_name}:#{key_secret}" if api_key_present? end def key_name [:key_name] end def key_secret [:key_secret] end # True when Basic Auth is being used to authenticate with Ably def using_basic_auth? !using_token_auth? end # True when Token Auth is being used to authenticate with Ably def using_token_auth? return [:use_token_auth] if .has_key?(:use_token_auth) token || current_token_details || has_client_id? || token_creatable_externally? end def client_id [:client_id] end def token token_object = [:token] || [:token_details] if token_object.kind_of?(Ably::Models::TokenDetails) token_object.token else token_object end end # Auth header string used in HTTP requests to Ably # # @return [String] HTTP authentication value used in HTTP_AUTHORIZATION header def auth_header if using_token_auth? token_auth_header else basic_auth_header end end # Auth params used in URI endpoint for Realtime connections # # @return [Hash] Auth params for a new Realtime connection def auth_params if using_token_auth? token_auth_params else basic_auth_params end end # True if prerequisites for creating a new token request are present # # One of the following criterion must be met: # * Valid API key and token option not provided as token options cannot be determined # * Authentication callback for new token requests # * Authentication URL for new token requests # # @return [Boolean] def token_renewable? token_creatable_externally? || (api_key_present? && !token) end # Returns false when attempting to send an API Key over a non-secure connection # Token auth must be used for non-secure connections # # @return [Boolean] def authentication_security_requirements_met? client.use_tls? || using_token_auth? end private attr_reader :client def ensure_valid_auth_attributes(attributes) if attributes[:timestamp] unless attributes[:timestamp].kind_of?(Time) || attributes[:timestamp].kind_of?(Numeric) raise ArgumentError, ':timestamp must be a Time or positive Integer value of seconds since epoch' end end if attributes[:ttl] unless attributes[:ttl].kind_of?(Numeric) && attributes[:ttl].to_f > 0 raise ArgumentError, ':ttl must be a positive Numeric value representing time to live in seconds' end end if attributes[:auth_headers] unless attributes[:auth_headers].kind_of?(Hash) raise ArgumentError, ':auth_headers must be a valid Hash' end end if attributes[:auth_params] unless attributes[:auth_params].kind_of?(Hash) raise ArgumentError, ':auth_params must be a valid Hash' end end if attributes[:auth_method] unless %(get post).include?(attributes[:auth_method].to_s) raise ArgumentError, ':auth_method must be either :get or :post' end end if attributes[:auth_callback] unless attributes[:auth_callback].respond_to?(:call) raise ArgumentError, ':auth_callback must be a Proc' end end end def ensure_api_key_sent_over_secure_connection raise Ably::Exceptions::InsecureRequestError, 'Cannot use Basic Auth over non-TLS connections' unless authentication_security_requirements_met? end # Basic Auth HTTP Authorization header value def basic_auth_header ensure_api_key_sent_over_secure_connection "Basic #{encode64("#{key}")}" end def split_api_key_into_key_and_secret!() api_key_parts = [:key].to_s.match(/(?<name>[\w_-]+\.[\w_-]+):(?<secret>[\w_-]+)/) raise ArgumentError, 'key is invalid' unless api_key_parts [:key_name] = api_key_parts[:name].encode(Encoding::UTF_8) [:key_secret] = api_key_parts[:secret].encode(Encoding::UTF_8) .delete :key end # Returns the current token if it exists or authorises and retrieves a token def token_auth_string if token token else .token end end # Token Auth HTTP Authorization header value def token_auth_header "Bearer #{encode64(token_auth_string)}" end # Basic Auth params to authenticate the Realtime connection def basic_auth_params ensure_api_key_sent_over_secure_connection { key: key } end # Token Auth params to authenticate the Realtime connection def token_auth_params { access_token: token_auth_string } end # Sign the request params using the secret # # @return [Hash] def sign_params(params, secret) text = params.values_at( :keyName, :ttl, :capability, :clientId, :timestamp, :nonce ).map do |val| "#{val}\n" end.join('') encode64( OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, secret, text) ) end # Retrieve a token request from a specified URL, expects a JSON response # # @return [Hash] def token_request_from_auth_url(auth_url, = {}) uri = URI.parse(auth_url) connection = Faraday.new("#{uri.scheme}://#{uri.host}", ) method = [:auth_method] || :get response = connection.send(method) do |request| request.url uri.path request.params = [:auth_params] || {} request.headers = [:auth_headers] || {} end if !response.body.kind_of?(Hash) && response.headers['Content-Type'] != 'text/plain' raise Ably::Exceptions::InvalidResponseBody, "Content Type #{response.headers['Content-Type']} is not supported by this client library" end response.body end # Return a Hash of connection options to initiate the Faraday::Connection with # # @return [Hash] def @connection_options ||= { builder: middleware, headers: { accept: client.mime_type, user_agent: user_agent }, request: { open_timeout: 5, timeout: 10 } } end # Return a Faraday middleware stack to initiate the Faraday::Connection with # # @see http://mislav.uniqpath.com/2011/07/faraday-advanced-http/ def middleware @middleware ||= Faraday::RackBuilder.new do |builder| setup_outgoing_middleware builder # Raise exceptions if response code is invalid builder.use Ably::Rest::Middleware::ExternalExceptions setup_incoming_middleware builder, client.logger # Set Faraday's HTTP adapter builder.adapter Faraday.default_adapter end end def auth_callback_present? !![:auth_callback] end def token_url_present? !![:auth_url] end def token_creatable_externally? auth_callback_present? || token_url_present? end def has_client_id? !!client_id end def api_key_present? key_name && key_secret end end |
#key ⇒ String (readonly)
Returns Complete API key containing both the key name and key secret, if present.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 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 67 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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 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 204 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 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 |
# File 'lib/submodules/ably-ruby/lib/ably/auth.rb', line 27 class Auth include Ably::Modules::Conversions include Ably::Modules::HttpHelpers # Default capability Hash object and TTL in seconds for issued tokens TOKEN_DEFAULTS = { capability: { '*' => ['*'] }, ttl: 60 * 60 # 1 hour in seconds } attr_reader :options, :current_token_details alias_method :auth_options, :options # Creates an Auth object # # @param [Ably::Rest::Client] client {Ably::Rest::Client} this Auth object uses # @param [Hash] options (see Ably::Rest::Client#initialize) # @option (see Ably::Rest::Client#initialize) # def initialize(client, ) ensure_valid_auth_attributes = .dup @client = client @options = unless .kind_of?(Hash) raise ArgumentError, 'Expected auth_options to be a Hash' end if [:key] && ([:key_secret] || [:key_name]) raise ArgumentError, 'key and key_name or key_secret are mutually exclusive. Provider either a key or key_name & key_secret' end split_api_key_into_key_and_secret! if [:key] if using_basic_auth? && !api_key_present? raise ArgumentError, 'key is missing. Either an API key, token, or token auth method must be provided' end if has_client_id? raise ArgumentError, 'client_id cannot be provided without a complete API key. Key name & Secret is needed to authenticate with Ably and obtain a token' unless api_key_present? ensure_utf_8 :client_id, client_id end @options.freeze end # Ensures valid auth credentials are present for the library instance. This may rely on an already-known and valid token, and will obtain a new token if necessary. # # In the event that a new token request is made, the specified options are used. # # @param [Hash] options the options for the token request # @option options (see #request_token) # @option options [String] :key API key comprising the key name and key secret in a single string # @option options [Boolean] :force obtains a new token even if the current token is valid # # @return (see #request_token) # # @example # # will issue a simple token request using basic auth # client = Ably::Rest::Client.new(key: 'key.id:secret') # token = client.auth.authorise # # # will use token request from block to authorise if not already authorised # token = client.auth.authorise do |options| # # create token_request object # token_request # end # def ( = {}) ensure_valid_auth_attributes if current_token_details && ![:force] return current_token_details unless current_token_details.expired? end = .clone split_api_key_into_key_and_secret! if [:key] @options = @options.merge() # update default options @current_token_details = request_token() end # Request a {Ably::Models::TokenDetails} which can be used to make authenticated token based requests # # @param [Hash] options the options for the token request # @option options [String] :key complete API key for the designated application # @option options [String] :client_id client ID identifying this connection to other clients (defaults to client client_id if configured) # @option options [String] :auth_url a URL to be used to GET or POST a set of token request params, to obtain a signed token request. # @option options [Hash] :auth_headers a set of application-specific headers to be added to any request made to the authUrl # @option options [Hash] :auth_params a set of application-specific query params to be added to any request made to the authUrl # @option options [Symbol] :auth_method HTTP method to use with auth_url, must be either `:get` or `:post` (defaults to :get) # @option options [Proc] :auth_callback this Proc / block will be called with the {#auth_options Auth#auth_options Hash} as the first argument whenever a new token is required. # The Proc should return a token string, {Ably::Models::TokenDetails} or JSON equivalent, {Ably::Models::TokenRequest} or JSON equivalent # @option options [Integer] :ttl validity time in seconds for the requested {Ably::Models::TokenDetails}. Limits may apply, see {https://www.ably.io/documentation/other/authentication} # @option options [Hash] :capability canonicalised representation of the resource paths and associated operations # @option options [Boolean] :query_time when true will query the {https://www.ably.io Ably} system for the current time instead of using the local time # @option options [Time] :timestamp the time of the of the request # @option options [String] :nonce an unquoted, unescaped random string of at least 16 characters # # @return [Ably::Models::TokenDetails] # # @example # # simple token request using basic auth # client = Ably::Rest::Client.new(key: 'key.id:secret') # token = client.auth.request_token # # # token request using auth block # token = client.auth.request_token do |options| # # create token_request object # token_request # end # def request_token( = {}) ensure_valid_auth_attributes = .merge() token_request = if auth_callback = .delete(:auth_callback) auth_callback.call() elsif auth_url = .delete(:auth_url) token_request_from_auth_url(auth_url, ) else create_token_request() end case token_request when Ably::Models::TokenDetails return token_request when Hash return Ably::Models::TokenDetails.new(token_request) if IdiomaticRubyWrapper(token_request).has_key?(:issued) when String return Ably::Models::TokenDetails.new(token: token_request) end token_request = Ably::Models::TokenRequest(token_request) response = client.post("/keys/#{token_request.key_name}/requestToken", token_request.hash, send_auth_header: false, disable_automatic_reauthorise: true) Ably::Models::TokenDetails.new(response.body) end # Creates and signs a token request that can then subsequently be used by any client to request a token # # @param [Hash] options the options for the token request # @option options [String] :key complete API key for the designated application # @option options [String] :client_id client ID identifying this connection to other clients # @option options [Integer] :ttl validity time in seconds for the requested {Ably::Models::TokenDetails}. Limits may apply, see {https://www.ably.io/documentation/other/authentication} # @option options [Hash] :capability canonicalised representation of the resource paths and associated operations # @option options [Boolean] :query_time when true will query the {https://www.ably.io Ably} system for the current time instead of using the local time # @option options [Time] :timestamp the time of the of the request # @option options [String] :nonce an unquoted, unescaped random string of at least 16 characters # # @return [Models::TokenRequest] # # @example # client.auth.create_token_request(id: 'asd.asd', ttl: 3600) # #<Ably::Models::TokenRequest:0x007fd5d919df78 # # @hash={ # # :id=>"asds.adsa", # # :clientId=>nil, # # :ttl=>3600000, # # :timestamp=>1428973674000, # # :capability=>"{\"*\":[\"*\"]}", # # :nonce=>"95e543b88299f6bae83df9b12fbd1ecd", # # :mac=>"881oZHeFo6oMim7....uE56a8gUxHw=" # # } # #>> def create_token_request( = {}) ensure_valid_auth_attributes = .clone split_api_key_into_key_and_secret! if [:key] request_key_name = .delete(:key_name) || key_name request_key_secret = .delete(:key_secret) || key_secret raise Ably::Exceptions::TokenRequestError, 'Key Name and Key Secret are required to generate a new token request' unless request_key_name && request_key_secret = if [:query_time] client.time else .delete(:timestamp) || Time.now end = Time.at() if .kind_of?(Integer) token_request = { keyName: [:key_name] || request_key_name, clientId: [:client_id] || client_id, ttl: (([:ttl] || TOKEN_DEFAULTS.fetch(:ttl)) * 1000).to_i, timestamp: (.to_f * 1000).round, capability: [:capability] || TOKEN_DEFAULTS.fetch(:capability), nonce: [:nonce] || SecureRandom.hex.force_encoding('UTF-8') } token_request[:capability] = JSON.dump(token_request[:capability]) if token_request[:capability].is_a?(Hash) token_request[:mac] = sign_params(token_request, request_key_secret) # Undocumented feature to request a persisted token token_request[:persisted] = [:persisted] if [:persisted] Models::TokenRequest.new(token_request) end def key "#{key_name}:#{key_secret}" if api_key_present? end def key_name [:key_name] end def key_secret [:key_secret] end # True when Basic Auth is being used to authenticate with Ably def using_basic_auth? !using_token_auth? end # True when Token Auth is being used to authenticate with Ably def using_token_auth? return [:use_token_auth] if .has_key?(:use_token_auth) token || current_token_details || has_client_id? || token_creatable_externally? end def client_id [:client_id] end def token token_object = [:token] || [:token_details] if token_object.kind_of?(Ably::Models::TokenDetails) token_object.token else token_object end end # Auth header string used in HTTP requests to Ably # # @return [String] HTTP authentication value used in HTTP_AUTHORIZATION header def auth_header if using_token_auth? token_auth_header else basic_auth_header end end # Auth params used in URI endpoint for Realtime connections # # @return [Hash] Auth params for a new Realtime connection def auth_params if using_token_auth? token_auth_params else basic_auth_params end end # True if prerequisites for creating a new token request are present # # One of the following criterion must be met: # * Valid API key and token option not provided as token options cannot be determined # * Authentication callback for new token requests # * Authentication URL for new token requests # # @return [Boolean] def token_renewable? token_creatable_externally? || (api_key_present? && !token) end # Returns false when attempting to send an API Key over a non-secure connection # Token auth must be used for non-secure connections # # @return [Boolean] def authentication_security_requirements_met? client.use_tls? || using_token_auth? end private attr_reader :client def ensure_valid_auth_attributes(attributes) if attributes[:timestamp] unless attributes[:timestamp].kind_of?(Time) || attributes[:timestamp].kind_of?(Numeric) raise ArgumentError, ':timestamp must be a Time or positive Integer value of seconds since epoch' end end if attributes[:ttl] unless attributes[:ttl].kind_of?(Numeric) && attributes[:ttl].to_f > 0 raise ArgumentError, ':ttl must be a positive Numeric value representing time to live in seconds' end end if attributes[:auth_headers] unless attributes[:auth_headers].kind_of?(Hash) raise ArgumentError, ':auth_headers must be a valid Hash' end end if attributes[:auth_params] unless attributes[:auth_params].kind_of?(Hash) raise ArgumentError, ':auth_params must be a valid Hash' end end if attributes[:auth_method] unless %(get post).include?(attributes[:auth_method].to_s) raise ArgumentError, ':auth_method must be either :get or :post' end end if attributes[:auth_callback] unless attributes[:auth_callback].respond_to?(:call) raise ArgumentError, ':auth_callback must be a Proc' end end end def ensure_api_key_sent_over_secure_connection raise Ably::Exceptions::InsecureRequestError, 'Cannot use Basic Auth over non-TLS connections' unless authentication_security_requirements_met? end # Basic Auth HTTP Authorization header value def basic_auth_header ensure_api_key_sent_over_secure_connection "Basic #{encode64("#{key}")}" end def split_api_key_into_key_and_secret!() api_key_parts = [:key].to_s.match(/(?<name>[\w_-]+\.[\w_-]+):(?<secret>[\w_-]+)/) raise ArgumentError, 'key is invalid' unless api_key_parts [:key_name] = api_key_parts[:name].encode(Encoding::UTF_8) [:key_secret] = api_key_parts[:secret].encode(Encoding::UTF_8) .delete :key end # Returns the current token if it exists or authorises and retrieves a token def token_auth_string if token token else .token end end # Token Auth HTTP Authorization header value def token_auth_header "Bearer #{encode64(token_auth_string)}" end # Basic Auth params to authenticate the Realtime connection def basic_auth_params ensure_api_key_sent_over_secure_connection { key: key } end # Token Auth params to authenticate the Realtime connection def token_auth_params { access_token: token_auth_string } end # Sign the request params using the secret # # @return [Hash] def sign_params(params, secret) text = params.values_at( :keyName, :ttl, :capability, :clientId, :timestamp, :nonce ).map do |val| "#{val}\n" end.join('') encode64( OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, secret, text) ) end # Retrieve a token request from a specified URL, expects a JSON response # # @return [Hash] def token_request_from_auth_url(auth_url, = {}) uri = URI.parse(auth_url) connection = Faraday.new("#{uri.scheme}://#{uri.host}", ) method = [:auth_method] || :get response = connection.send(method) do |request| request.url uri.path request.params = [:auth_params] || {} request.headers = [:auth_headers] || {} end if !response.body.kind_of?(Hash) && response.headers['Content-Type'] != 'text/plain' raise Ably::Exceptions::InvalidResponseBody, "Content Type #{response.headers['Content-Type']} is not supported by this client library" end response.body end # Return a Hash of connection options to initiate the Faraday::Connection with # # @return [Hash] def @connection_options ||= { builder: middleware, headers: { accept: client.mime_type, user_agent: user_agent }, request: { open_timeout: 5, timeout: 10 } } end # Return a Faraday middleware stack to initiate the Faraday::Connection with # # @see http://mislav.uniqpath.com/2011/07/faraday-advanced-http/ def middleware @middleware ||= Faraday::RackBuilder.new do |builder| setup_outgoing_middleware builder # Raise exceptions if response code is invalid builder.use Ably::Rest::Middleware::ExternalExceptions setup_incoming_middleware builder, client.logger # Set Faraday's HTTP adapter builder.adapter Faraday.default_adapter end end def auth_callback_present? !![:auth_callback] end def token_url_present? !![:auth_url] end def token_creatable_externally? auth_callback_present? || token_url_present? end def has_client_id? !!client_id end def api_key_present? key_name && key_secret end end |
#key_name ⇒ String (readonly)
Returns Key name (public part of the API key), if present.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 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 67 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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 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 204 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 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 |
# File 'lib/submodules/ably-ruby/lib/ably/auth.rb', line 27 class Auth include Ably::Modules::Conversions include Ably::Modules::HttpHelpers # Default capability Hash object and TTL in seconds for issued tokens TOKEN_DEFAULTS = { capability: { '*' => ['*'] }, ttl: 60 * 60 # 1 hour in seconds } attr_reader :options, :current_token_details alias_method :auth_options, :options # Creates an Auth object # # @param [Ably::Rest::Client] client {Ably::Rest::Client} this Auth object uses # @param [Hash] options (see Ably::Rest::Client#initialize) # @option (see Ably::Rest::Client#initialize) # def initialize(client, ) ensure_valid_auth_attributes = .dup @client = client @options = unless .kind_of?(Hash) raise ArgumentError, 'Expected auth_options to be a Hash' end if [:key] && ([:key_secret] || [:key_name]) raise ArgumentError, 'key and key_name or key_secret are mutually exclusive. Provider either a key or key_name & key_secret' end split_api_key_into_key_and_secret! if [:key] if using_basic_auth? && !api_key_present? raise ArgumentError, 'key is missing. Either an API key, token, or token auth method must be provided' end if has_client_id? raise ArgumentError, 'client_id cannot be provided without a complete API key. Key name & Secret is needed to authenticate with Ably and obtain a token' unless api_key_present? ensure_utf_8 :client_id, client_id end @options.freeze end # Ensures valid auth credentials are present for the library instance. This may rely on an already-known and valid token, and will obtain a new token if necessary. # # In the event that a new token request is made, the specified options are used. # # @param [Hash] options the options for the token request # @option options (see #request_token) # @option options [String] :key API key comprising the key name and key secret in a single string # @option options [Boolean] :force obtains a new token even if the current token is valid # # @return (see #request_token) # # @example # # will issue a simple token request using basic auth # client = Ably::Rest::Client.new(key: 'key.id:secret') # token = client.auth.authorise # # # will use token request from block to authorise if not already authorised # token = client.auth.authorise do |options| # # create token_request object # token_request # end # def ( = {}) ensure_valid_auth_attributes if current_token_details && ![:force] return current_token_details unless current_token_details.expired? end = .clone split_api_key_into_key_and_secret! if [:key] @options = @options.merge() # update default options @current_token_details = request_token() end # Request a {Ably::Models::TokenDetails} which can be used to make authenticated token based requests # # @param [Hash] options the options for the token request # @option options [String] :key complete API key for the designated application # @option options [String] :client_id client ID identifying this connection to other clients (defaults to client client_id if configured) # @option options [String] :auth_url a URL to be used to GET or POST a set of token request params, to obtain a signed token request. # @option options [Hash] :auth_headers a set of application-specific headers to be added to any request made to the authUrl # @option options [Hash] :auth_params a set of application-specific query params to be added to any request made to the authUrl # @option options [Symbol] :auth_method HTTP method to use with auth_url, must be either `:get` or `:post` (defaults to :get) # @option options [Proc] :auth_callback this Proc / block will be called with the {#auth_options Auth#auth_options Hash} as the first argument whenever a new token is required. # The Proc should return a token string, {Ably::Models::TokenDetails} or JSON equivalent, {Ably::Models::TokenRequest} or JSON equivalent # @option options [Integer] :ttl validity time in seconds for the requested {Ably::Models::TokenDetails}. Limits may apply, see {https://www.ably.io/documentation/other/authentication} # @option options [Hash] :capability canonicalised representation of the resource paths and associated operations # @option options [Boolean] :query_time when true will query the {https://www.ably.io Ably} system for the current time instead of using the local time # @option options [Time] :timestamp the time of the of the request # @option options [String] :nonce an unquoted, unescaped random string of at least 16 characters # # @return [Ably::Models::TokenDetails] # # @example # # simple token request using basic auth # client = Ably::Rest::Client.new(key: 'key.id:secret') # token = client.auth.request_token # # # token request using auth block # token = client.auth.request_token do |options| # # create token_request object # token_request # end # def request_token( = {}) ensure_valid_auth_attributes = .merge() token_request = if auth_callback = .delete(:auth_callback) auth_callback.call() elsif auth_url = .delete(:auth_url) token_request_from_auth_url(auth_url, ) else create_token_request() end case token_request when Ably::Models::TokenDetails return token_request when Hash return Ably::Models::TokenDetails.new(token_request) if IdiomaticRubyWrapper(token_request).has_key?(:issued) when String return Ably::Models::TokenDetails.new(token: token_request) end token_request = Ably::Models::TokenRequest(token_request) response = client.post("/keys/#{token_request.key_name}/requestToken", token_request.hash, send_auth_header: false, disable_automatic_reauthorise: true) Ably::Models::TokenDetails.new(response.body) end # Creates and signs a token request that can then subsequently be used by any client to request a token # # @param [Hash] options the options for the token request # @option options [String] :key complete API key for the designated application # @option options [String] :client_id client ID identifying this connection to other clients # @option options [Integer] :ttl validity time in seconds for the requested {Ably::Models::TokenDetails}. Limits may apply, see {https://www.ably.io/documentation/other/authentication} # @option options [Hash] :capability canonicalised representation of the resource paths and associated operations # @option options [Boolean] :query_time when true will query the {https://www.ably.io Ably} system for the current time instead of using the local time # @option options [Time] :timestamp the time of the of the request # @option options [String] :nonce an unquoted, unescaped random string of at least 16 characters # # @return [Models::TokenRequest] # # @example # client.auth.create_token_request(id: 'asd.asd', ttl: 3600) # #<Ably::Models::TokenRequest:0x007fd5d919df78 # # @hash={ # # :id=>"asds.adsa", # # :clientId=>nil, # # :ttl=>3600000, # # :timestamp=>1428973674000, # # :capability=>"{\"*\":[\"*\"]}", # # :nonce=>"95e543b88299f6bae83df9b12fbd1ecd", # # :mac=>"881oZHeFo6oMim7....uE56a8gUxHw=" # # } # #>> def create_token_request( = {}) ensure_valid_auth_attributes = .clone split_api_key_into_key_and_secret! if [:key] request_key_name = .delete(:key_name) || key_name request_key_secret = .delete(:key_secret) || key_secret raise Ably::Exceptions::TokenRequestError, 'Key Name and Key Secret are required to generate a new token request' unless request_key_name && request_key_secret = if [:query_time] client.time else .delete(:timestamp) || Time.now end = Time.at() if .kind_of?(Integer) token_request = { keyName: [:key_name] || request_key_name, clientId: [:client_id] || client_id, ttl: (([:ttl] || TOKEN_DEFAULTS.fetch(:ttl)) * 1000).to_i, timestamp: (.to_f * 1000).round, capability: [:capability] || TOKEN_DEFAULTS.fetch(:capability), nonce: [:nonce] || SecureRandom.hex.force_encoding('UTF-8') } token_request[:capability] = JSON.dump(token_request[:capability]) if token_request[:capability].is_a?(Hash) token_request[:mac] = sign_params(token_request, request_key_secret) # Undocumented feature to request a persisted token token_request[:persisted] = [:persisted] if [:persisted] Models::TokenRequest.new(token_request) end def key "#{key_name}:#{key_secret}" if api_key_present? end def key_name [:key_name] end def key_secret [:key_secret] end # True when Basic Auth is being used to authenticate with Ably def using_basic_auth? !using_token_auth? end # True when Token Auth is being used to authenticate with Ably def using_token_auth? return [:use_token_auth] if .has_key?(:use_token_auth) token || current_token_details || has_client_id? || token_creatable_externally? end def client_id [:client_id] end def token token_object = [:token] || [:token_details] if token_object.kind_of?(Ably::Models::TokenDetails) token_object.token else token_object end end # Auth header string used in HTTP requests to Ably # # @return [String] HTTP authentication value used in HTTP_AUTHORIZATION header def auth_header if using_token_auth? token_auth_header else basic_auth_header end end # Auth params used in URI endpoint for Realtime connections # # @return [Hash] Auth params for a new Realtime connection def auth_params if using_token_auth? token_auth_params else basic_auth_params end end # True if prerequisites for creating a new token request are present # # One of the following criterion must be met: # * Valid API key and token option not provided as token options cannot be determined # * Authentication callback for new token requests # * Authentication URL for new token requests # # @return [Boolean] def token_renewable? token_creatable_externally? || (api_key_present? && !token) end # Returns false when attempting to send an API Key over a non-secure connection # Token auth must be used for non-secure connections # # @return [Boolean] def authentication_security_requirements_met? client.use_tls? || using_token_auth? end private attr_reader :client def ensure_valid_auth_attributes(attributes) if attributes[:timestamp] unless attributes[:timestamp].kind_of?(Time) || attributes[:timestamp].kind_of?(Numeric) raise ArgumentError, ':timestamp must be a Time or positive Integer value of seconds since epoch' end end if attributes[:ttl] unless attributes[:ttl].kind_of?(Numeric) && attributes[:ttl].to_f > 0 raise ArgumentError, ':ttl must be a positive Numeric value representing time to live in seconds' end end if attributes[:auth_headers] unless attributes[:auth_headers].kind_of?(Hash) raise ArgumentError, ':auth_headers must be a valid Hash' end end if attributes[:auth_params] unless attributes[:auth_params].kind_of?(Hash) raise ArgumentError, ':auth_params must be a valid Hash' end end if attributes[:auth_method] unless %(get post).include?(attributes[:auth_method].to_s) raise ArgumentError, ':auth_method must be either :get or :post' end end if attributes[:auth_callback] unless attributes[:auth_callback].respond_to?(:call) raise ArgumentError, ':auth_callback must be a Proc' end end end def ensure_api_key_sent_over_secure_connection raise Ably::Exceptions::InsecureRequestError, 'Cannot use Basic Auth over non-TLS connections' unless authentication_security_requirements_met? end # Basic Auth HTTP Authorization header value def basic_auth_header ensure_api_key_sent_over_secure_connection "Basic #{encode64("#{key}")}" end def split_api_key_into_key_and_secret!() api_key_parts = [:key].to_s.match(/(?<name>[\w_-]+\.[\w_-]+):(?<secret>[\w_-]+)/) raise ArgumentError, 'key is invalid' unless api_key_parts [:key_name] = api_key_parts[:name].encode(Encoding::UTF_8) [:key_secret] = api_key_parts[:secret].encode(Encoding::UTF_8) .delete :key end # Returns the current token if it exists or authorises and retrieves a token def token_auth_string if token token else .token end end # Token Auth HTTP Authorization header value def token_auth_header "Bearer #{encode64(token_auth_string)}" end # Basic Auth params to authenticate the Realtime connection def basic_auth_params ensure_api_key_sent_over_secure_connection { key: key } end # Token Auth params to authenticate the Realtime connection def token_auth_params { access_token: token_auth_string } end # Sign the request params using the secret # # @return [Hash] def sign_params(params, secret) text = params.values_at( :keyName, :ttl, :capability, :clientId, :timestamp, :nonce ).map do |val| "#{val}\n" end.join('') encode64( OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, secret, text) ) end # Retrieve a token request from a specified URL, expects a JSON response # # @return [Hash] def token_request_from_auth_url(auth_url, = {}) uri = URI.parse(auth_url) connection = Faraday.new("#{uri.scheme}://#{uri.host}", ) method = [:auth_method] || :get response = connection.send(method) do |request| request.url uri.path request.params = [:auth_params] || {} request.headers = [:auth_headers] || {} end if !response.body.kind_of?(Hash) && response.headers['Content-Type'] != 'text/plain' raise Ably::Exceptions::InvalidResponseBody, "Content Type #{response.headers['Content-Type']} is not supported by this client library" end response.body end # Return a Hash of connection options to initiate the Faraday::Connection with # # @return [Hash] def @connection_options ||= { builder: middleware, headers: { accept: client.mime_type, user_agent: user_agent }, request: { open_timeout: 5, timeout: 10 } } end # Return a Faraday middleware stack to initiate the Faraday::Connection with # # @see http://mislav.uniqpath.com/2011/07/faraday-advanced-http/ def middleware @middleware ||= Faraday::RackBuilder.new do |builder| setup_outgoing_middleware builder # Raise exceptions if response code is invalid builder.use Ably::Rest::Middleware::ExternalExceptions setup_incoming_middleware builder, client.logger # Set Faraday's HTTP adapter builder.adapter Faraday.default_adapter end end def auth_callback_present? !![:auth_callback] end def token_url_present? !![:auth_url] end def token_creatable_externally? auth_callback_present? || token_url_present? end def has_client_id? !!client_id end def api_key_present? key_name && key_secret end end |
#key_secret ⇒ String (readonly)
Returns Key secret (private secure part of the API key), if present.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 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 67 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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 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 204 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 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 |
# File 'lib/submodules/ably-ruby/lib/ably/auth.rb', line 27 class Auth include Ably::Modules::Conversions include Ably::Modules::HttpHelpers # Default capability Hash object and TTL in seconds for issued tokens TOKEN_DEFAULTS = { capability: { '*' => ['*'] }, ttl: 60 * 60 # 1 hour in seconds } attr_reader :options, :current_token_details alias_method :auth_options, :options # Creates an Auth object # # @param [Ably::Rest::Client] client {Ably::Rest::Client} this Auth object uses # @param [Hash] options (see Ably::Rest::Client#initialize) # @option (see Ably::Rest::Client#initialize) # def initialize(client, ) ensure_valid_auth_attributes = .dup @client = client @options = unless .kind_of?(Hash) raise ArgumentError, 'Expected auth_options to be a Hash' end if [:key] && ([:key_secret] || [:key_name]) raise ArgumentError, 'key and key_name or key_secret are mutually exclusive. Provider either a key or key_name & key_secret' end split_api_key_into_key_and_secret! if [:key] if using_basic_auth? && !api_key_present? raise ArgumentError, 'key is missing. Either an API key, token, or token auth method must be provided' end if has_client_id? raise ArgumentError, 'client_id cannot be provided without a complete API key. Key name & Secret is needed to authenticate with Ably and obtain a token' unless api_key_present? ensure_utf_8 :client_id, client_id end @options.freeze end # Ensures valid auth credentials are present for the library instance. This may rely on an already-known and valid token, and will obtain a new token if necessary. # # In the event that a new token request is made, the specified options are used. # # @param [Hash] options the options for the token request # @option options (see #request_token) # @option options [String] :key API key comprising the key name and key secret in a single string # @option options [Boolean] :force obtains a new token even if the current token is valid # # @return (see #request_token) # # @example # # will issue a simple token request using basic auth # client = Ably::Rest::Client.new(key: 'key.id:secret') # token = client.auth.authorise # # # will use token request from block to authorise if not already authorised # token = client.auth.authorise do |options| # # create token_request object # token_request # end # def ( = {}) ensure_valid_auth_attributes if current_token_details && ![:force] return current_token_details unless current_token_details.expired? end = .clone split_api_key_into_key_and_secret! if [:key] @options = @options.merge() # update default options @current_token_details = request_token() end # Request a {Ably::Models::TokenDetails} which can be used to make authenticated token based requests # # @param [Hash] options the options for the token request # @option options [String] :key complete API key for the designated application # @option options [String] :client_id client ID identifying this connection to other clients (defaults to client client_id if configured) # @option options [String] :auth_url a URL to be used to GET or POST a set of token request params, to obtain a signed token request. # @option options [Hash] :auth_headers a set of application-specific headers to be added to any request made to the authUrl # @option options [Hash] :auth_params a set of application-specific query params to be added to any request made to the authUrl # @option options [Symbol] :auth_method HTTP method to use with auth_url, must be either `:get` or `:post` (defaults to :get) # @option options [Proc] :auth_callback this Proc / block will be called with the {#auth_options Auth#auth_options Hash} as the first argument whenever a new token is required. # The Proc should return a token string, {Ably::Models::TokenDetails} or JSON equivalent, {Ably::Models::TokenRequest} or JSON equivalent # @option options [Integer] :ttl validity time in seconds for the requested {Ably::Models::TokenDetails}. Limits may apply, see {https://www.ably.io/documentation/other/authentication} # @option options [Hash] :capability canonicalised representation of the resource paths and associated operations # @option options [Boolean] :query_time when true will query the {https://www.ably.io Ably} system for the current time instead of using the local time # @option options [Time] :timestamp the time of the of the request # @option options [String] :nonce an unquoted, unescaped random string of at least 16 characters # # @return [Ably::Models::TokenDetails] # # @example # # simple token request using basic auth # client = Ably::Rest::Client.new(key: 'key.id:secret') # token = client.auth.request_token # # # token request using auth block # token = client.auth.request_token do |options| # # create token_request object # token_request # end # def request_token( = {}) ensure_valid_auth_attributes = .merge() token_request = if auth_callback = .delete(:auth_callback) auth_callback.call() elsif auth_url = .delete(:auth_url) token_request_from_auth_url(auth_url, ) else create_token_request() end case token_request when Ably::Models::TokenDetails return token_request when Hash return Ably::Models::TokenDetails.new(token_request) if IdiomaticRubyWrapper(token_request).has_key?(:issued) when String return Ably::Models::TokenDetails.new(token: token_request) end token_request = Ably::Models::TokenRequest(token_request) response = client.post("/keys/#{token_request.key_name}/requestToken", token_request.hash, send_auth_header: false, disable_automatic_reauthorise: true) Ably::Models::TokenDetails.new(response.body) end # Creates and signs a token request that can then subsequently be used by any client to request a token # # @param [Hash] options the options for the token request # @option options [String] :key complete API key for the designated application # @option options [String] :client_id client ID identifying this connection to other clients # @option options [Integer] :ttl validity time in seconds for the requested {Ably::Models::TokenDetails}. Limits may apply, see {https://www.ably.io/documentation/other/authentication} # @option options [Hash] :capability canonicalised representation of the resource paths and associated operations # @option options [Boolean] :query_time when true will query the {https://www.ably.io Ably} system for the current time instead of using the local time # @option options [Time] :timestamp the time of the of the request # @option options [String] :nonce an unquoted, unescaped random string of at least 16 characters # # @return [Models::TokenRequest] # # @example # client.auth.create_token_request(id: 'asd.asd', ttl: 3600) # #<Ably::Models::TokenRequest:0x007fd5d919df78 # # @hash={ # # :id=>"asds.adsa", # # :clientId=>nil, # # :ttl=>3600000, # # :timestamp=>1428973674000, # # :capability=>"{\"*\":[\"*\"]}", # # :nonce=>"95e543b88299f6bae83df9b12fbd1ecd", # # :mac=>"881oZHeFo6oMim7....uE56a8gUxHw=" # # } # #>> def create_token_request( = {}) ensure_valid_auth_attributes = .clone split_api_key_into_key_and_secret! if [:key] request_key_name = .delete(:key_name) || key_name request_key_secret = .delete(:key_secret) || key_secret raise Ably::Exceptions::TokenRequestError, 'Key Name and Key Secret are required to generate a new token request' unless request_key_name && request_key_secret = if [:query_time] client.time else .delete(:timestamp) || Time.now end = Time.at() if .kind_of?(Integer) token_request = { keyName: [:key_name] || request_key_name, clientId: [:client_id] || client_id, ttl: (([:ttl] || TOKEN_DEFAULTS.fetch(:ttl)) * 1000).to_i, timestamp: (.to_f * 1000).round, capability: [:capability] || TOKEN_DEFAULTS.fetch(:capability), nonce: [:nonce] || SecureRandom.hex.force_encoding('UTF-8') } token_request[:capability] = JSON.dump(token_request[:capability]) if token_request[:capability].is_a?(Hash) token_request[:mac] = sign_params(token_request, request_key_secret) # Undocumented feature to request a persisted token token_request[:persisted] = [:persisted] if [:persisted] Models::TokenRequest.new(token_request) end def key "#{key_name}:#{key_secret}" if api_key_present? end def key_name [:key_name] end def key_secret [:key_secret] end # True when Basic Auth is being used to authenticate with Ably def using_basic_auth? !using_token_auth? end # True when Token Auth is being used to authenticate with Ably def using_token_auth? return [:use_token_auth] if .has_key?(:use_token_auth) token || current_token_details || has_client_id? || token_creatable_externally? end def client_id [:client_id] end def token token_object = [:token] || [:token_details] if token_object.kind_of?(Ably::Models::TokenDetails) token_object.token else token_object end end # Auth header string used in HTTP requests to Ably # # @return [String] HTTP authentication value used in HTTP_AUTHORIZATION header def auth_header if using_token_auth? token_auth_header else basic_auth_header end end # Auth params used in URI endpoint for Realtime connections # # @return [Hash] Auth params for a new Realtime connection def auth_params if using_token_auth? token_auth_params else basic_auth_params end end # True if prerequisites for creating a new token request are present # # One of the following criterion must be met: # * Valid API key and token option not provided as token options cannot be determined # * Authentication callback for new token requests # * Authentication URL for new token requests # # @return [Boolean] def token_renewable? token_creatable_externally? || (api_key_present? && !token) end # Returns false when attempting to send an API Key over a non-secure connection # Token auth must be used for non-secure connections # # @return [Boolean] def authentication_security_requirements_met? client.use_tls? || using_token_auth? end private attr_reader :client def ensure_valid_auth_attributes(attributes) if attributes[:timestamp] unless attributes[:timestamp].kind_of?(Time) || attributes[:timestamp].kind_of?(Numeric) raise ArgumentError, ':timestamp must be a Time or positive Integer value of seconds since epoch' end end if attributes[:ttl] unless attributes[:ttl].kind_of?(Numeric) && attributes[:ttl].to_f > 0 raise ArgumentError, ':ttl must be a positive Numeric value representing time to live in seconds' end end if attributes[:auth_headers] unless attributes[:auth_headers].kind_of?(Hash) raise ArgumentError, ':auth_headers must be a valid Hash' end end if attributes[:auth_params] unless attributes[:auth_params].kind_of?(Hash) raise ArgumentError, ':auth_params must be a valid Hash' end end if attributes[:auth_method] unless %(get post).include?(attributes[:auth_method].to_s) raise ArgumentError, ':auth_method must be either :get or :post' end end if attributes[:auth_callback] unless attributes[:auth_callback].respond_to?(:call) raise ArgumentError, ':auth_callback must be a Proc' end end end def ensure_api_key_sent_over_secure_connection raise Ably::Exceptions::InsecureRequestError, 'Cannot use Basic Auth over non-TLS connections' unless authentication_security_requirements_met? end # Basic Auth HTTP Authorization header value def basic_auth_header ensure_api_key_sent_over_secure_connection "Basic #{encode64("#{key}")}" end def split_api_key_into_key_and_secret!() api_key_parts = [:key].to_s.match(/(?<name>[\w_-]+\.[\w_-]+):(?<secret>[\w_-]+)/) raise ArgumentError, 'key is invalid' unless api_key_parts [:key_name] = api_key_parts[:name].encode(Encoding::UTF_8) [:key_secret] = api_key_parts[:secret].encode(Encoding::UTF_8) .delete :key end # Returns the current token if it exists or authorises and retrieves a token def token_auth_string if token token else .token end end # Token Auth HTTP Authorization header value def token_auth_header "Bearer #{encode64(token_auth_string)}" end # Basic Auth params to authenticate the Realtime connection def basic_auth_params ensure_api_key_sent_over_secure_connection { key: key } end # Token Auth params to authenticate the Realtime connection def token_auth_params { access_token: token_auth_string } end # Sign the request params using the secret # # @return [Hash] def sign_params(params, secret) text = params.values_at( :keyName, :ttl, :capability, :clientId, :timestamp, :nonce ).map do |val| "#{val}\n" end.join('') encode64( OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, secret, text) ) end # Retrieve a token request from a specified URL, expects a JSON response # # @return [Hash] def token_request_from_auth_url(auth_url, = {}) uri = URI.parse(auth_url) connection = Faraday.new("#{uri.scheme}://#{uri.host}", ) method = [:auth_method] || :get response = connection.send(method) do |request| request.url uri.path request.params = [:auth_params] || {} request.headers = [:auth_headers] || {} end if !response.body.kind_of?(Hash) && response.headers['Content-Type'] != 'text/plain' raise Ably::Exceptions::InvalidResponseBody, "Content Type #{response.headers['Content-Type']} is not supported by this client library" end response.body end # Return a Hash of connection options to initiate the Faraday::Connection with # # @return [Hash] def @connection_options ||= { builder: middleware, headers: { accept: client.mime_type, user_agent: user_agent }, request: { open_timeout: 5, timeout: 10 } } end # Return a Faraday middleware stack to initiate the Faraday::Connection with # # @see http://mislav.uniqpath.com/2011/07/faraday-advanced-http/ def middleware @middleware ||= Faraday::RackBuilder.new do |builder| setup_outgoing_middleware builder # Raise exceptions if response code is invalid builder.use Ably::Rest::Middleware::ExternalExceptions setup_incoming_middleware builder, client.logger # Set Faraday's HTTP adapter builder.adapter Faraday.default_adapter end end def auth_callback_present? !![:auth_callback] end def token_url_present? !![:auth_url] end def token_creatable_externally? auth_callback_present? || token_url_present? end def has_client_id? !!client_id end def api_key_present? key_name && key_secret end end |
#options ⇒ Hash (readonly) Also known as: auth_options
Returns Ably::Auth options configured for this client.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 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 67 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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 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 204 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 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 |
# File 'lib/submodules/ably-ruby/lib/ably/auth.rb', line 27 class Auth include Ably::Modules::Conversions include Ably::Modules::HttpHelpers # Default capability Hash object and TTL in seconds for issued tokens TOKEN_DEFAULTS = { capability: { '*' => ['*'] }, ttl: 60 * 60 # 1 hour in seconds } attr_reader :options, :current_token_details alias_method :auth_options, :options # Creates an Auth object # # @param [Ably::Rest::Client] client {Ably::Rest::Client} this Auth object uses # @param [Hash] options (see Ably::Rest::Client#initialize) # @option (see Ably::Rest::Client#initialize) # def initialize(client, ) ensure_valid_auth_attributes = .dup @client = client @options = unless .kind_of?(Hash) raise ArgumentError, 'Expected auth_options to be a Hash' end if [:key] && ([:key_secret] || [:key_name]) raise ArgumentError, 'key and key_name or key_secret are mutually exclusive. Provider either a key or key_name & key_secret' end split_api_key_into_key_and_secret! if [:key] if using_basic_auth? && !api_key_present? raise ArgumentError, 'key is missing. Either an API key, token, or token auth method must be provided' end if has_client_id? raise ArgumentError, 'client_id cannot be provided without a complete API key. Key name & Secret is needed to authenticate with Ably and obtain a token' unless api_key_present? ensure_utf_8 :client_id, client_id end @options.freeze end # Ensures valid auth credentials are present for the library instance. This may rely on an already-known and valid token, and will obtain a new token if necessary. # # In the event that a new token request is made, the specified options are used. # # @param [Hash] options the options for the token request # @option options (see #request_token) # @option options [String] :key API key comprising the key name and key secret in a single string # @option options [Boolean] :force obtains a new token even if the current token is valid # # @return (see #request_token) # # @example # # will issue a simple token request using basic auth # client = Ably::Rest::Client.new(key: 'key.id:secret') # token = client.auth.authorise # # # will use token request from block to authorise if not already authorised # token = client.auth.authorise do |options| # # create token_request object # token_request # end # def ( = {}) ensure_valid_auth_attributes if current_token_details && ![:force] return current_token_details unless current_token_details.expired? end = .clone split_api_key_into_key_and_secret! if [:key] @options = @options.merge() # update default options @current_token_details = request_token() end # Request a {Ably::Models::TokenDetails} which can be used to make authenticated token based requests # # @param [Hash] options the options for the token request # @option options [String] :key complete API key for the designated application # @option options [String] :client_id client ID identifying this connection to other clients (defaults to client client_id if configured) # @option options [String] :auth_url a URL to be used to GET or POST a set of token request params, to obtain a signed token request. # @option options [Hash] :auth_headers a set of application-specific headers to be added to any request made to the authUrl # @option options [Hash] :auth_params a set of application-specific query params to be added to any request made to the authUrl # @option options [Symbol] :auth_method HTTP method to use with auth_url, must be either `:get` or `:post` (defaults to :get) # @option options [Proc] :auth_callback this Proc / block will be called with the {#auth_options Auth#auth_options Hash} as the first argument whenever a new token is required. # The Proc should return a token string, {Ably::Models::TokenDetails} or JSON equivalent, {Ably::Models::TokenRequest} or JSON equivalent # @option options [Integer] :ttl validity time in seconds for the requested {Ably::Models::TokenDetails}. Limits may apply, see {https://www.ably.io/documentation/other/authentication} # @option options [Hash] :capability canonicalised representation of the resource paths and associated operations # @option options [Boolean] :query_time when true will query the {https://www.ably.io Ably} system for the current time instead of using the local time # @option options [Time] :timestamp the time of the of the request # @option options [String] :nonce an unquoted, unescaped random string of at least 16 characters # # @return [Ably::Models::TokenDetails] # # @example # # simple token request using basic auth # client = Ably::Rest::Client.new(key: 'key.id:secret') # token = client.auth.request_token # # # token request using auth block # token = client.auth.request_token do |options| # # create token_request object # token_request # end # def request_token( = {}) ensure_valid_auth_attributes = .merge() token_request = if auth_callback = .delete(:auth_callback) auth_callback.call() elsif auth_url = .delete(:auth_url) token_request_from_auth_url(auth_url, ) else create_token_request() end case token_request when Ably::Models::TokenDetails return token_request when Hash return Ably::Models::TokenDetails.new(token_request) if IdiomaticRubyWrapper(token_request).has_key?(:issued) when String return Ably::Models::TokenDetails.new(token: token_request) end token_request = Ably::Models::TokenRequest(token_request) response = client.post("/keys/#{token_request.key_name}/requestToken", token_request.hash, send_auth_header: false, disable_automatic_reauthorise: true) Ably::Models::TokenDetails.new(response.body) end # Creates and signs a token request that can then subsequently be used by any client to request a token # # @param [Hash] options the options for the token request # @option options [String] :key complete API key for the designated application # @option options [String] :client_id client ID identifying this connection to other clients # @option options [Integer] :ttl validity time in seconds for the requested {Ably::Models::TokenDetails}. Limits may apply, see {https://www.ably.io/documentation/other/authentication} # @option options [Hash] :capability canonicalised representation of the resource paths and associated operations # @option options [Boolean] :query_time when true will query the {https://www.ably.io Ably} system for the current time instead of using the local time # @option options [Time] :timestamp the time of the of the request # @option options [String] :nonce an unquoted, unescaped random string of at least 16 characters # # @return [Models::TokenRequest] # # @example # client.auth.create_token_request(id: 'asd.asd', ttl: 3600) # #<Ably::Models::TokenRequest:0x007fd5d919df78 # # @hash={ # # :id=>"asds.adsa", # # :clientId=>nil, # # :ttl=>3600000, # # :timestamp=>1428973674000, # # :capability=>"{\"*\":[\"*\"]}", # # :nonce=>"95e543b88299f6bae83df9b12fbd1ecd", # # :mac=>"881oZHeFo6oMim7....uE56a8gUxHw=" # # } # #>> def create_token_request( = {}) ensure_valid_auth_attributes = .clone split_api_key_into_key_and_secret! if [:key] request_key_name = .delete(:key_name) || key_name request_key_secret = .delete(:key_secret) || key_secret raise Ably::Exceptions::TokenRequestError, 'Key Name and Key Secret are required to generate a new token request' unless request_key_name && request_key_secret = if [:query_time] client.time else .delete(:timestamp) || Time.now end = Time.at() if .kind_of?(Integer) token_request = { keyName: [:key_name] || request_key_name, clientId: [:client_id] || client_id, ttl: (([:ttl] || TOKEN_DEFAULTS.fetch(:ttl)) * 1000).to_i, timestamp: (.to_f * 1000).round, capability: [:capability] || TOKEN_DEFAULTS.fetch(:capability), nonce: [:nonce] || SecureRandom.hex.force_encoding('UTF-8') } token_request[:capability] = JSON.dump(token_request[:capability]) if token_request[:capability].is_a?(Hash) token_request[:mac] = sign_params(token_request, request_key_secret) # Undocumented feature to request a persisted token token_request[:persisted] = [:persisted] if [:persisted] Models::TokenRequest.new(token_request) end def key "#{key_name}:#{key_secret}" if api_key_present? end def key_name [:key_name] end def key_secret [:key_secret] end # True when Basic Auth is being used to authenticate with Ably def using_basic_auth? !using_token_auth? end # True when Token Auth is being used to authenticate with Ably def using_token_auth? return [:use_token_auth] if .has_key?(:use_token_auth) token || current_token_details || has_client_id? || token_creatable_externally? end def client_id [:client_id] end def token token_object = [:token] || [:token_details] if token_object.kind_of?(Ably::Models::TokenDetails) token_object.token else token_object end end # Auth header string used in HTTP requests to Ably # # @return [String] HTTP authentication value used in HTTP_AUTHORIZATION header def auth_header if using_token_auth? token_auth_header else basic_auth_header end end # Auth params used in URI endpoint for Realtime connections # # @return [Hash] Auth params for a new Realtime connection def auth_params if using_token_auth? token_auth_params else basic_auth_params end end # True if prerequisites for creating a new token request are present # # One of the following criterion must be met: # * Valid API key and token option not provided as token options cannot be determined # * Authentication callback for new token requests # * Authentication URL for new token requests # # @return [Boolean] def token_renewable? token_creatable_externally? || (api_key_present? && !token) end # Returns false when attempting to send an API Key over a non-secure connection # Token auth must be used for non-secure connections # # @return [Boolean] def authentication_security_requirements_met? client.use_tls? || using_token_auth? end private attr_reader :client def ensure_valid_auth_attributes(attributes) if attributes[:timestamp] unless attributes[:timestamp].kind_of?(Time) || attributes[:timestamp].kind_of?(Numeric) raise ArgumentError, ':timestamp must be a Time or positive Integer value of seconds since epoch' end end if attributes[:ttl] unless attributes[:ttl].kind_of?(Numeric) && attributes[:ttl].to_f > 0 raise ArgumentError, ':ttl must be a positive Numeric value representing time to live in seconds' end end if attributes[:auth_headers] unless attributes[:auth_headers].kind_of?(Hash) raise ArgumentError, ':auth_headers must be a valid Hash' end end if attributes[:auth_params] unless attributes[:auth_params].kind_of?(Hash) raise ArgumentError, ':auth_params must be a valid Hash' end end if attributes[:auth_method] unless %(get post).include?(attributes[:auth_method].to_s) raise ArgumentError, ':auth_method must be either :get or :post' end end if attributes[:auth_callback] unless attributes[:auth_callback].respond_to?(:call) raise ArgumentError, ':auth_callback must be a Proc' end end end def ensure_api_key_sent_over_secure_connection raise Ably::Exceptions::InsecureRequestError, 'Cannot use Basic Auth over non-TLS connections' unless authentication_security_requirements_met? end # Basic Auth HTTP Authorization header value def basic_auth_header ensure_api_key_sent_over_secure_connection "Basic #{encode64("#{key}")}" end def split_api_key_into_key_and_secret!() api_key_parts = [:key].to_s.match(/(?<name>[\w_-]+\.[\w_-]+):(?<secret>[\w_-]+)/) raise ArgumentError, 'key is invalid' unless api_key_parts [:key_name] = api_key_parts[:name].encode(Encoding::UTF_8) [:key_secret] = api_key_parts[:secret].encode(Encoding::UTF_8) .delete :key end # Returns the current token if it exists or authorises and retrieves a token def token_auth_string if token token else .token end end # Token Auth HTTP Authorization header value def token_auth_header "Bearer #{encode64(token_auth_string)}" end # Basic Auth params to authenticate the Realtime connection def basic_auth_params ensure_api_key_sent_over_secure_connection { key: key } end # Token Auth params to authenticate the Realtime connection def token_auth_params { access_token: token_auth_string } end # Sign the request params using the secret # # @return [Hash] def sign_params(params, secret) text = params.values_at( :keyName, :ttl, :capability, :clientId, :timestamp, :nonce ).map do |val| "#{val}\n" end.join('') encode64( OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, secret, text) ) end # Retrieve a token request from a specified URL, expects a JSON response # # @return [Hash] def token_request_from_auth_url(auth_url, = {}) uri = URI.parse(auth_url) connection = Faraday.new("#{uri.scheme}://#{uri.host}", ) method = [:auth_method] || :get response = connection.send(method) do |request| request.url uri.path request.params = [:auth_params] || {} request.headers = [:auth_headers] || {} end if !response.body.kind_of?(Hash) && response.headers['Content-Type'] != 'text/plain' raise Ably::Exceptions::InvalidResponseBody, "Content Type #{response.headers['Content-Type']} is not supported by this client library" end response.body end # Return a Hash of connection options to initiate the Faraday::Connection with # # @return [Hash] def @connection_options ||= { builder: middleware, headers: { accept: client.mime_type, user_agent: user_agent }, request: { open_timeout: 5, timeout: 10 } } end # Return a Faraday middleware stack to initiate the Faraday::Connection with # # @see http://mislav.uniqpath.com/2011/07/faraday-advanced-http/ def middleware @middleware ||= Faraday::RackBuilder.new do |builder| setup_outgoing_middleware builder # Raise exceptions if response code is invalid builder.use Ably::Rest::Middleware::ExternalExceptions setup_incoming_middleware builder, client.logger # Set Faraday's HTTP adapter builder.adapter Faraday.default_adapter end end def auth_callback_present? !![:auth_callback] end def token_url_present? !![:auth_url] end def token_creatable_externally? auth_callback_present? || token_url_present? end def has_client_id? !!client_id end def api_key_present? key_name && key_secret end end |
#token ⇒ String (readonly)
Returns Token string provided to the Client constructor that is used to authenticate all requests.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 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 67 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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 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 204 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 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 |
# File 'lib/submodules/ably-ruby/lib/ably/auth.rb', line 27 class Auth include Ably::Modules::Conversions include Ably::Modules::HttpHelpers # Default capability Hash object and TTL in seconds for issued tokens TOKEN_DEFAULTS = { capability: { '*' => ['*'] }, ttl: 60 * 60 # 1 hour in seconds } attr_reader :options, :current_token_details alias_method :auth_options, :options # Creates an Auth object # # @param [Ably::Rest::Client] client {Ably::Rest::Client} this Auth object uses # @param [Hash] options (see Ably::Rest::Client#initialize) # @option (see Ably::Rest::Client#initialize) # def initialize(client, ) ensure_valid_auth_attributes = .dup @client = client @options = unless .kind_of?(Hash) raise ArgumentError, 'Expected auth_options to be a Hash' end if [:key] && ([:key_secret] || [:key_name]) raise ArgumentError, 'key and key_name or key_secret are mutually exclusive. Provider either a key or key_name & key_secret' end split_api_key_into_key_and_secret! if [:key] if using_basic_auth? && !api_key_present? raise ArgumentError, 'key is missing. Either an API key, token, or token auth method must be provided' end if has_client_id? raise ArgumentError, 'client_id cannot be provided without a complete API key. Key name & Secret is needed to authenticate with Ably and obtain a token' unless api_key_present? ensure_utf_8 :client_id, client_id end @options.freeze end # Ensures valid auth credentials are present for the library instance. This may rely on an already-known and valid token, and will obtain a new token if necessary. # # In the event that a new token request is made, the specified options are used. # # @param [Hash] options the options for the token request # @option options (see #request_token) # @option options [String] :key API key comprising the key name and key secret in a single string # @option options [Boolean] :force obtains a new token even if the current token is valid # # @return (see #request_token) # # @example # # will issue a simple token request using basic auth # client = Ably::Rest::Client.new(key: 'key.id:secret') # token = client.auth.authorise # # # will use token request from block to authorise if not already authorised # token = client.auth.authorise do |options| # # create token_request object # token_request # end # def ( = {}) ensure_valid_auth_attributes if current_token_details && ![:force] return current_token_details unless current_token_details.expired? end = .clone split_api_key_into_key_and_secret! if [:key] @options = @options.merge() # update default options @current_token_details = request_token() end # Request a {Ably::Models::TokenDetails} which can be used to make authenticated token based requests # # @param [Hash] options the options for the token request # @option options [String] :key complete API key for the designated application # @option options [String] :client_id client ID identifying this connection to other clients (defaults to client client_id if configured) # @option options [String] :auth_url a URL to be used to GET or POST a set of token request params, to obtain a signed token request. # @option options [Hash] :auth_headers a set of application-specific headers to be added to any request made to the authUrl # @option options [Hash] :auth_params a set of application-specific query params to be added to any request made to the authUrl # @option options [Symbol] :auth_method HTTP method to use with auth_url, must be either `:get` or `:post` (defaults to :get) # @option options [Proc] :auth_callback this Proc / block will be called with the {#auth_options Auth#auth_options Hash} as the first argument whenever a new token is required. # The Proc should return a token string, {Ably::Models::TokenDetails} or JSON equivalent, {Ably::Models::TokenRequest} or JSON equivalent # @option options [Integer] :ttl validity time in seconds for the requested {Ably::Models::TokenDetails}. Limits may apply, see {https://www.ably.io/documentation/other/authentication} # @option options [Hash] :capability canonicalised representation of the resource paths and associated operations # @option options [Boolean] :query_time when true will query the {https://www.ably.io Ably} system for the current time instead of using the local time # @option options [Time] :timestamp the time of the of the request # @option options [String] :nonce an unquoted, unescaped random string of at least 16 characters # # @return [Ably::Models::TokenDetails] # # @example # # simple token request using basic auth # client = Ably::Rest::Client.new(key: 'key.id:secret') # token = client.auth.request_token # # # token request using auth block # token = client.auth.request_token do |options| # # create token_request object # token_request # end # def request_token( = {}) ensure_valid_auth_attributes = .merge() token_request = if auth_callback = .delete(:auth_callback) auth_callback.call() elsif auth_url = .delete(:auth_url) token_request_from_auth_url(auth_url, ) else create_token_request() end case token_request when Ably::Models::TokenDetails return token_request when Hash return Ably::Models::TokenDetails.new(token_request) if IdiomaticRubyWrapper(token_request).has_key?(:issued) when String return Ably::Models::TokenDetails.new(token: token_request) end token_request = Ably::Models::TokenRequest(token_request) response = client.post("/keys/#{token_request.key_name}/requestToken", token_request.hash, send_auth_header: false, disable_automatic_reauthorise: true) Ably::Models::TokenDetails.new(response.body) end # Creates and signs a token request that can then subsequently be used by any client to request a token # # @param [Hash] options the options for the token request # @option options [String] :key complete API key for the designated application # @option options [String] :client_id client ID identifying this connection to other clients # @option options [Integer] :ttl validity time in seconds for the requested {Ably::Models::TokenDetails}. Limits may apply, see {https://www.ably.io/documentation/other/authentication} # @option options [Hash] :capability canonicalised representation of the resource paths and associated operations # @option options [Boolean] :query_time when true will query the {https://www.ably.io Ably} system for the current time instead of using the local time # @option options [Time] :timestamp the time of the of the request # @option options [String] :nonce an unquoted, unescaped random string of at least 16 characters # # @return [Models::TokenRequest] # # @example # client.auth.create_token_request(id: 'asd.asd', ttl: 3600) # #<Ably::Models::TokenRequest:0x007fd5d919df78 # # @hash={ # # :id=>"asds.adsa", # # :clientId=>nil, # # :ttl=>3600000, # # :timestamp=>1428973674000, # # :capability=>"{\"*\":[\"*\"]}", # # :nonce=>"95e543b88299f6bae83df9b12fbd1ecd", # # :mac=>"881oZHeFo6oMim7....uE56a8gUxHw=" # # } # #>> def create_token_request( = {}) ensure_valid_auth_attributes = .clone split_api_key_into_key_and_secret! if [:key] request_key_name = .delete(:key_name) || key_name request_key_secret = .delete(:key_secret) || key_secret raise Ably::Exceptions::TokenRequestError, 'Key Name and Key Secret are required to generate a new token request' unless request_key_name && request_key_secret = if [:query_time] client.time else .delete(:timestamp) || Time.now end = Time.at() if .kind_of?(Integer) token_request = { keyName: [:key_name] || request_key_name, clientId: [:client_id] || client_id, ttl: (([:ttl] || TOKEN_DEFAULTS.fetch(:ttl)) * 1000).to_i, timestamp: (.to_f * 1000).round, capability: [:capability] || TOKEN_DEFAULTS.fetch(:capability), nonce: [:nonce] || SecureRandom.hex.force_encoding('UTF-8') } token_request[:capability] = JSON.dump(token_request[:capability]) if token_request[:capability].is_a?(Hash) token_request[:mac] = sign_params(token_request, request_key_secret) # Undocumented feature to request a persisted token token_request[:persisted] = [:persisted] if [:persisted] Models::TokenRequest.new(token_request) end def key "#{key_name}:#{key_secret}" if api_key_present? end def key_name [:key_name] end def key_secret [:key_secret] end # True when Basic Auth is being used to authenticate with Ably def using_basic_auth? !using_token_auth? end # True when Token Auth is being used to authenticate with Ably def using_token_auth? return [:use_token_auth] if .has_key?(:use_token_auth) token || current_token_details || has_client_id? || token_creatable_externally? end def client_id [:client_id] end def token token_object = [:token] || [:token_details] if token_object.kind_of?(Ably::Models::TokenDetails) token_object.token else token_object end end # Auth header string used in HTTP requests to Ably # # @return [String] HTTP authentication value used in HTTP_AUTHORIZATION header def auth_header if using_token_auth? token_auth_header else basic_auth_header end end # Auth params used in URI endpoint for Realtime connections # # @return [Hash] Auth params for a new Realtime connection def auth_params if using_token_auth? token_auth_params else basic_auth_params end end # True if prerequisites for creating a new token request are present # # One of the following criterion must be met: # * Valid API key and token option not provided as token options cannot be determined # * Authentication callback for new token requests # * Authentication URL for new token requests # # @return [Boolean] def token_renewable? token_creatable_externally? || (api_key_present? && !token) end # Returns false when attempting to send an API Key over a non-secure connection # Token auth must be used for non-secure connections # # @return [Boolean] def authentication_security_requirements_met? client.use_tls? || using_token_auth? end private attr_reader :client def ensure_valid_auth_attributes(attributes) if attributes[:timestamp] unless attributes[:timestamp].kind_of?(Time) || attributes[:timestamp].kind_of?(Numeric) raise ArgumentError, ':timestamp must be a Time or positive Integer value of seconds since epoch' end end if attributes[:ttl] unless attributes[:ttl].kind_of?(Numeric) && attributes[:ttl].to_f > 0 raise ArgumentError, ':ttl must be a positive Numeric value representing time to live in seconds' end end if attributes[:auth_headers] unless attributes[:auth_headers].kind_of?(Hash) raise ArgumentError, ':auth_headers must be a valid Hash' end end if attributes[:auth_params] unless attributes[:auth_params].kind_of?(Hash) raise ArgumentError, ':auth_params must be a valid Hash' end end if attributes[:auth_method] unless %(get post).include?(attributes[:auth_method].to_s) raise ArgumentError, ':auth_method must be either :get or :post' end end if attributes[:auth_callback] unless attributes[:auth_callback].respond_to?(:call) raise ArgumentError, ':auth_callback must be a Proc' end end end def ensure_api_key_sent_over_secure_connection raise Ably::Exceptions::InsecureRequestError, 'Cannot use Basic Auth over non-TLS connections' unless authentication_security_requirements_met? end # Basic Auth HTTP Authorization header value def basic_auth_header ensure_api_key_sent_over_secure_connection "Basic #{encode64("#{key}")}" end def split_api_key_into_key_and_secret!() api_key_parts = [:key].to_s.match(/(?<name>[\w_-]+\.[\w_-]+):(?<secret>[\w_-]+)/) raise ArgumentError, 'key is invalid' unless api_key_parts [:key_name] = api_key_parts[:name].encode(Encoding::UTF_8) [:key_secret] = api_key_parts[:secret].encode(Encoding::UTF_8) .delete :key end # Returns the current token if it exists or authorises and retrieves a token def token_auth_string if token token else .token end end # Token Auth HTTP Authorization header value def token_auth_header "Bearer #{encode64(token_auth_string)}" end # Basic Auth params to authenticate the Realtime connection def basic_auth_params ensure_api_key_sent_over_secure_connection { key: key } end # Token Auth params to authenticate the Realtime connection def token_auth_params { access_token: token_auth_string } end # Sign the request params using the secret # # @return [Hash] def sign_params(params, secret) text = params.values_at( :keyName, :ttl, :capability, :clientId, :timestamp, :nonce ).map do |val| "#{val}\n" end.join('') encode64( OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, secret, text) ) end # Retrieve a token request from a specified URL, expects a JSON response # # @return [Hash] def token_request_from_auth_url(auth_url, = {}) uri = URI.parse(auth_url) connection = Faraday.new("#{uri.scheme}://#{uri.host}", ) method = [:auth_method] || :get response = connection.send(method) do |request| request.url uri.path request.params = [:auth_params] || {} request.headers = [:auth_headers] || {} end if !response.body.kind_of?(Hash) && response.headers['Content-Type'] != 'text/plain' raise Ably::Exceptions::InvalidResponseBody, "Content Type #{response.headers['Content-Type']} is not supported by this client library" end response.body end # Return a Hash of connection options to initiate the Faraday::Connection with # # @return [Hash] def @connection_options ||= { builder: middleware, headers: { accept: client.mime_type, user_agent: user_agent }, request: { open_timeout: 5, timeout: 10 } } end # Return a Faraday middleware stack to initiate the Faraday::Connection with # # @see http://mislav.uniqpath.com/2011/07/faraday-advanced-http/ def middleware @middleware ||= Faraday::RackBuilder.new do |builder| setup_outgoing_middleware builder # Raise exceptions if response code is invalid builder.use Ably::Rest::Middleware::ExternalExceptions setup_incoming_middleware builder, client.logger # Set Faraday's HTTP adapter builder.adapter Faraday.default_adapter end end def auth_callback_present? !![:auth_callback] end def token_url_present? !![:auth_url] end def token_creatable_externally? auth_callback_present? || token_url_present? end def has_client_id? !!client_id end def api_key_present? key_name && key_secret end end |
Instance Method Details
#auth_header ⇒ String
Auth header string used in HTTP requests to Ably
275 276 277 278 279 280 281 |
# File 'lib/submodules/ably-ruby/lib/ably/auth.rb', line 275 def auth_header if using_token_auth? token_auth_header else basic_auth_header end end |
#auth_params ⇒ Hash
Auth params used in URI endpoint for Realtime connections
286 287 288 289 290 291 292 |
# File 'lib/submodules/ably-ruby/lib/ably/auth.rb', line 286 def auth_params if using_token_auth? token_auth_params else basic_auth_params end end |
#authentication_security_requirements_met? ⇒ Boolean
Returns false when attempting to send an API Key over a non-secure connection Token auth must be used for non-secure connections
310 311 312 |
# File 'lib/submodules/ably-ruby/lib/ably/auth.rb', line 310 def authentication_security_requirements_met? client.use_tls? || using_token_auth? end |
#authorise(options = {}) ⇒ Ably::Models::TokenDetails
Ensures valid auth credentials are present for the library instance. This may rely on an already-known and valid token, and will obtain a new token if necessary.
In the event that a new token request is made, the specified options are used.
98 99 100 101 102 103 104 105 106 107 108 109 110 |
# File 'lib/submodules/ably-ruby/lib/ably/auth.rb', line 98 def ( = {}) ensure_valid_auth_attributes if current_token_details && ![:force] return current_token_details unless current_token_details.expired? end = .clone split_api_key_into_key_and_secret! if [:key] @options = @options.merge() # update default options @current_token_details = request_token() end |
#create_token_request(options = {}) ⇒ Models::TokenRequest
Creates and signs a token request that can then subsequently be used by any client to request a token
199 200 201 202 203 204 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 |
# File 'lib/submodules/ably-ruby/lib/ably/auth.rb', line 199 def create_token_request( = {}) ensure_valid_auth_attributes = .clone split_api_key_into_key_and_secret! if [:key] request_key_name = .delete(:key_name) || key_name request_key_secret = .delete(:key_secret) || key_secret raise Ably::Exceptions::TokenRequestError, 'Key Name and Key Secret are required to generate a new token request' unless request_key_name && request_key_secret = if [:query_time] client.time else .delete(:timestamp) || Time.now end = Time.at() if .kind_of?(Integer) token_request = { keyName: [:key_name] || request_key_name, clientId: [:client_id] || client_id, ttl: (([:ttl] || TOKEN_DEFAULTS.fetch(:ttl)) * 1000).to_i, timestamp: (.to_f * 1000).round, capability: [:capability] || TOKEN_DEFAULTS.fetch(:capability), nonce: [:nonce] || SecureRandom.hex.force_encoding('UTF-8') } token_request[:capability] = JSON.dump(token_request[:capability]) if token_request[:capability].is_a?(Hash) token_request[:mac] = sign_params(token_request, request_key_secret) # Undocumented feature to request a persisted token token_request[:persisted] = [:persisted] if [:persisted] Models::TokenRequest.new(token_request) end |
#request_token(options = {}) ⇒ Ably::Models::TokenDetails
Request a Models::TokenDetails which can be used to make authenticated token based requests
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 |
# File 'lib/submodules/ably-ruby/lib/ably/auth.rb', line 142 def request_token( = {}) ensure_valid_auth_attributes = .merge() token_request = if auth_callback = .delete(:auth_callback) auth_callback.call() elsif auth_url = .delete(:auth_url) token_request_from_auth_url(auth_url, ) else create_token_request() end case token_request when Ably::Models::TokenDetails return token_request when Hash return Ably::Models::TokenDetails.new(token_request) if IdiomaticRubyWrapper(token_request).has_key?(:issued) when String return Ably::Models::TokenDetails.new(token: token_request) end token_request = Ably::Models::TokenRequest(token_request) response = client.post("/keys/#{token_request.key_name}/requestToken", token_request.hash, send_auth_header: false, disable_automatic_reauthorise: true) Ably::Models::TokenDetails.new(response.body) end |
#token_renewable? ⇒ Boolean
True if prerequisites for creating a new token request are present
One of the following criterion must be met:
-
Valid API key and token option not provided as token options cannot be determined
-
Authentication callback for new token requests
-
Authentication URL for new token requests
302 303 304 |
# File 'lib/submodules/ably-ruby/lib/ably/auth.rb', line 302 def token_renewable? token_creatable_externally? || (api_key_present? && !token) end |
#using_basic_auth? ⇒ Boolean
True when Basic Auth is being used to authenticate with Ably
248 249 250 |
# File 'lib/submodules/ably-ruby/lib/ably/auth.rb', line 248 def using_basic_auth? !using_token_auth? end |
#using_token_auth? ⇒ Boolean
True when Token Auth is being used to authenticate with Ably
253 254 255 256 |
# File 'lib/submodules/ably-ruby/lib/ably/auth.rb', line 253 def using_token_auth? return [:use_token_auth] if .has_key?(:use_token_auth) token || current_token_details || has_client_id? || token_creatable_externally? end |