Update for 2023

This commit is contained in:
Erik Berlin 2023-08-10 07:23:20 -07:00
parent 4a375da4e2
commit 8d6792a74f
17 changed files with 423 additions and 393 deletions

29
.github/workflows/main.yml vendored Normal file
View file

@ -0,0 +1,29 @@
name: Ruby
on:
push:
branches:
- master
pull_request:
jobs:
build:
runs-on: ubuntu-latest
name: Ruby ${{ matrix.ruby }}
strategy:
matrix:
ruby:
- "3.0"
- "3.1"
- "3.2"
steps:
- uses: actions/checkout@v3
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: ${{ matrix.ruby }}
bundler-cache: true
- name: Run the default task
run: bundle exec rake

17
.gitignore vendored
View file

@ -1,10 +1,9 @@
*.rbc /.bundle/
.DS_Store /.yardoc
.bundle /_yardoc/
.yardoc /coverage/
/doc/
/pkg/
/spec/reports/
/tmp/
Gemfile.lock Gemfile.lock
coverage
doc
measurement
pkg
rdoc

View file

@ -1,57 +1,72 @@
Metrics/AbcSize: require:
Max: 16 - standard
- standard-performance
- rubocop-rspec
- rubocop-performance
- rubocop-rake
Metrics/BlockNesting: AllCops:
Max: 1 NewCops: enable
TargetRubyVersion: 3.0
Metrics/LineLength: Layout/ArgumentAlignment:
AllowURI: true Enabled: true
EnforcedStyle: with_fixed_indentation
Layout/ArrayAlignment:
Enabled: true
EnforcedStyle: with_fixed_indentation
Layout/EndAlignment:
Enabled: true
EnforcedStyleAlignWith: variable
Layout/HashAlignment:
Enabled: true
EnforcedHashRocketStyle: key
EnforcedColonStyle: key
EnforcedLastArgumentHashStyle: always_inspect
Layout/LineLength:
Enabled: false Enabled: false
Metrics/MethodLength: Layout/ParameterAlignment:
CountComments: false Enabled: true
Max: 7 EnforcedStyle: with_fixed_indentation
IndentationWidth: ~
Layout/SpaceInsideHashLiteralBraces:
Enabled: false
Metrics/ParameterLists: Metrics/ParameterLists:
Max: 4 CountKeywordArgs: false
CountKeywordArgs: true
Style/AccessModifierIndentation: RSpec/MultipleExpectations:
EnforcedStyle: outdent
Style/CollectionMethods:
PreferredMethods:
map: 'collect'
reduce: 'inject'
find: 'detect'
find_all: 'select'
Style/Documentation:
Enabled: false Enabled: false
Style/DotPosition: RSpec/ExampleLength:
EnforcedStyle: trailing
Style/DoubleNegation:
Enabled: false Enabled: false
Style/EachWithObject: RSpec/MessageSpies:
Enabled: false Enabled: false
Style/Encoding: RSpec/PendingWithoutReason:
Enabled: false Enabled: false
Style/HashSyntax: RSpec/FilePath:
EnforcedStyle: hash_rockets
Style/Lambda:
Enabled: false Enabled: false
Style/RaiseArgs: Style/Alias:
EnforcedStyle: compact Enabled: true
EnforcedStyle: prefer_alias_method
Style/SpaceInsideHashLiteralBraces: Style/FrozenStringLiteralComment:
EnforcedStyle: no_space Enabled: false
Style/TrailingComma: Style/StringLiterals:
EnforcedStyleForMultiline: 'comma' Enabled: true
EnforcedStyle: double_quotes
Style/StringLiteralsInInterpolation:
Enabled: true
EnforcedStyle: double_quotes

5
CHANGELOG.md Normal file
View file

@ -0,0 +1,5 @@
## [Unreleased]
## [0.4.0] - 2023-08-10
- Update

27
Gemfile
View file

@ -1,17 +1,14 @@
source 'https://rubygems.org' source "https://rubygems.org"
gem 'jruby-openssl', :platforms => :jruby
gem 'rake'
group :test do
gem 'backports'
gem 'coveralls'
gem 'mime-types', '~> 1.25', :platforms => [:jruby, :ruby_18]
gem 'rest-client', '~> 1.6.0', :platforms => [:jruby, :ruby_18]
gem 'rspec', '>= 2.14'
gem 'rubocop', '>= 0.28', :platforms => [:ruby_19, :ruby_20, :ruby_21]
gem 'simplecov', '>= 0.9'
gem 'yardstick'
end
# Specify your gem's dependencies in simple_oauth.gemspec
gemspec gemspec
gem "rake", ">= 13.0.6"
gem "rspec", ">= 3.12"
gem "rubocop", ">= 1.21"
gem "rubocop-performance", ">= 1.18"
gem "rubocop-rake", ">= 0.6"
gem "rubocop-rspec", ">= 0.31"
gem "simplecov", ">= 0.22"
gem "standard", ">= 1.30.1"
gem "webmock", ">= 3.18.1"

View file

@ -1,20 +1,21 @@
Copyright (c) 2010-2013 Steve Richert, Erik Michaels-Ober The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining Copyright (c) 2010-2023 Steve Richert, Erik Michaels-Ober
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be Permission is hereby granted, free of charge, to any person obtaining a copy
included in all copies or substantial portions of the Software. of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, The above copyright notice and this permission notice shall be included in
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF all copies or substantial portions of the Software.
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -1,44 +1,24 @@
# simple_oauth # simple_oauth
[![Gem Version](http://img.shields.io/gem/v/simple_oauth.svg)][gem]
[![Build Status](http://img.shields.io/travis/laserlemon/simple_oauth.svg)][travis]
[![Dependency Status](http://img.shields.io/gemnasium/laserlemon/simple_oauth.svg)][gemnasium]
[![Code Climate](http://img.shields.io/codeclimate/github/laserlemon/simple_oauth.svg)][codeclimate]
[![Coverage Status](http://img.shields.io/coveralls/laserlemon/simple_oauth.svg)][coveralls]
[gem]: https://rubygems.org/gems/simple_oauth
[travis]: http://travis-ci.org/laserlemon/simple_oauth
[gemnasium]: https://gemnasium.com/laserlemon/simple_oauth
[codeclimate]: https://codeclimate.com/github/laserlemon/simple_oauth
[coveralls]: https://coveralls.io/r/laserlemon/simple_oauth
Simply builds and verifies OAuth headers Simply builds and verifies OAuth headers
## Supported Rubies ## Installation
This library aims to support and is [tested
against](http://travis-ci.org/laserlemon/simple_oauth) the following Ruby
implementations:
* Ruby 1.8.7 Install the gem and add to the application's Gemfile by executing:
* Ruby 1.9.3
* Ruby 2.0.0
* Ruby 2.1
* [JRuby](http://jruby.org/)
* [Rubinius](http://rubini.us/)
If something doesn't work on one of these interpreters, it's a bug. $ bundle add simple_oauth
This library may inadvertently work (or seem to work) on other Ruby If bundler is not being used to manage dependencies, install the gem by executing:
implementations, however support will only be provided for the versions listed
above.
If you would like this library to support another Ruby version, you may $ gem install simple_oauth
volunteer to be a maintainer. Being a maintainer entails making sure all tests
run and pass on that implementation. When something breaks on your
implementation, you will be responsible for providing patches in a timely
fashion. If critical issues for a particular implementation exist at the time
of a major release, support for that Ruby version may be dropped.
## Copyright
Copyright (c) 2010-2013 Steve Richert, Erik Michaels-Ober. See ## Contributing
[LICENSE](LICENSE.md) for details.
Bug reports and pull requests are welcome on GitHub at https://github.com/laserlemon/simple_oauth.
This project conforms to [Standard Ruby](https://github.com/standardrb/standard). Patches that dont maintain that standard will not be accepted.
## License
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).

View file

@ -1,27 +1,10 @@
require 'bundler/gem_tasks' require "bundler/gem_tasks"
require 'rspec/core/rake_task' require "rspec/core/rake_task"
require "rubocop/rake_task"
require "standard/rake"
RSpec::Core::RakeTask.new(:spec) RSpec::Core::RakeTask.new(:spec)
task :test => :spec RuboCop::RakeTask.new
begin task default: %i[spec rubocop standard]
require 'rubocop/rake_task'
RuboCop::RakeTask.new
rescue LoadError
task :rubocop do
$stderr.puts 'RuboCop is disabled'
end
end
require 'yardstick/rake/measurement'
Yardstick::Rake::Measurement.new do |measurement|
measurement.output = 'measurement/report.txt'
end
require 'yardstick/rake/verify'
Yardstick::Rake::Verify.new do |verify|
verify.threshold = 47
end
task :default => [:spec, :rubocop, :verify_measurements]

10
bin/console Executable file
View file

@ -0,0 +1,10 @@
#!/usr/bin/env ruby
require "bundler/setup"
require "simple_oauth"
# You can add fixtures and/or initialization code here to make experimenting
# with your gem easier. You can also use a different console, if you like.
require "irb"
IRB.start(__FILE__)

8
bin/setup Executable file
View file

@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
set -vx
bundle install
# Do any other automated setup that you need to do here

View file

@ -1 +1,2 @@
require 'simple_oauth/header' require_relative "simple_oauth/header"
require_relative "simple_oauth/version"

View file

@ -1,35 +1,36 @@
require 'openssl' require "openssl"
require 'uri' require "uri"
require 'base64' require "base64"
require 'cgi' require "cgi"
module SimpleOAuth module SimpleOAuth
# Generates OAuth header for HTTP request
class Header class Header
ATTRIBUTE_KEYS = [:callback, :consumer_key, :nonce, :signature_method, :timestamp, :token, :verifier, :version] unless defined? ::SimpleOAuth::Header::ATTRIBUTE_KEYS ATTRIBUTE_KEYS = %i[callback consumer_key nonce signature_method timestamp token verifier version].freeze unless defined? ::SimpleOAuth::Header::ATTRIBUTE_KEYS
IGNORED_KEYS = [:consumer_secret, :token_secret, :signature] unless defined? ::SimpleOAuth::Header::IGNORED_KEYS IGNORED_KEYS = %i[consumer_secret token_secret signature].freeze unless defined? ::SimpleOAuth::Header::IGNORED_KEYS
attr_reader :method, :params, :options attr_reader :method, :params, :options
class << self class << self
def default_options def default_options
{ {
:nonce => OpenSSL::Random.random_bytes(16).unpack('H*')[0], nonce: OpenSSL::Random.random_bytes(16).unpack1("H*"),
:signature_method => 'HMAC-SHA1', signature_method: "HMAC-SHA1",
:timestamp => Time.now.to_i.to_s, timestamp: Time.now.to_i.to_s,
:version => '1.0', version: "1.0"
} }
end end
def parse(header) def parse(header)
header.to_s.sub(/^OAuth\s/, '').split(/,\s*/).inject({}) do |attributes, pair| header.to_s.sub(/^OAuth\s/, "").split(/,\s*/).inject({}) do |attributes, pair|
match = pair.match(/^(\w+)\=\"([^\"]*)\"$/) match = pair.match(/^(\w+)="([^"]*)"$/)
attributes.merge(match[1].sub(/^oauth_/, '').to_sym => unescape(match[2])) attributes.merge(match[1].sub(/^oauth_/, "").to_sym => unescape(match[2]))
end end
end end
def escape(value) def escape(value)
uri_parser.escape(value.to_s, /[^a-z0-9\-\.\_\~]/i) uri_parser.escape(value.to_s, /[^a-z0-9\-._~]/i)
end end
alias_method :encode, :escape alias_method :encode, :escape
@ -38,10 +39,10 @@ module SimpleOAuth
end end
alias_method :decode, :unescape alias_method :decode, :unescape
private private
def uri_parser def uri_parser
@uri_parser ||= URI.const_defined?(:Parser) ? URI::Parser.new : URI @uri_parser ||= URI.const_defined?(:Parser) ? URI::DEFAULT_PARSER : URI
end end
end end
@ -74,44 +75,42 @@ module SimpleOAuth
end end
def signed_attributes def signed_attributes
attributes.merge(:oauth_signature => signature) attributes.merge(oauth_signature: signature)
end end
private private
def normalized_attributes def normalized_attributes
signed_attributes.sort_by { |k, _| k.to_s }.collect { |k, v| %(#{k}="#{self.class.escape(v)}") }.join(', ') signed_attributes.sort_by { |k, _| k.to_s }.collect { |k, v| %(#{k}="#{self.class.escape(v)}") }.join(", ")
end end
def attributes def attributes
matching_keys, extra_keys = options.keys.partition { |key| ATTRIBUTE_KEYS.include?(key) } matching_keys, extra_keys = options.keys.partition { |key| ATTRIBUTE_KEYS.include?(key) }
extra_keys -= IGNORED_KEYS extra_keys -= IGNORED_KEYS
if options[:ignore_extra_keys] || extra_keys.empty? raise "SimpleOAuth: Found extra option keys not matching ATTRIBUTE_KEYS:\n [#{extra_keys.collect(&:inspect).join(", ")}]" unless options[:ignore_extra_keys] || extra_keys.empty?
Hash[options.select { |key, _| matching_keys.include?(key) }.collect { |key, value| [:"oauth_#{key}", value] }]
else options.select { |key, _| matching_keys.include?(key) }.transform_keys { |key| :"oauth_#{key}" }
fail "SimpleOAuth: Found extra option keys not matching ATTRIBUTE_KEYS:\n [#{extra_keys.collect(&:inspect).join(', ')}]"
end
end end
def signature def signature
send(options[:signature_method].downcase.tr('-', '_') + '_signature') send("#{options[:signature_method].downcase.tr("-", "_")}_signature")
end end
def hmac_sha1_signature def hmac_sha1_signature
Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::SHA1.new, secret, signature_base)).chomp.gsub(/\n/, '') Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest.new("SHA1"), secret, signature_base)).chomp.delete("\n")
end end
def secret def secret
options.values_at(:consumer_secret, :token_secret).collect { |v| self.class.escape(v) }.join('&') options.values_at(:consumer_secret, :token_secret).collect { |v| self.class.escape(v) }.join("&")
end end
alias_method :plaintext_signature, :secret alias_method :plaintext_signature, :secret
def signature_base def signature_base
[method, url, normalized_params].collect { |v| self.class.escape(v) }.join('&') [method, url, normalized_params].collect { |v| self.class.escape(v) }.join("&")
end end
def normalized_params def normalized_params
signature_params.collect { |p| p.collect { |v| self.class.escape(v) } }.sort.collect { |p| p.join('=') }.join('&') signature_params.collect { |p| p.collect { |v| self.class.escape(v) } }.sort.collect { |p| p.join("=") }.join("&")
end end
def signature_params def signature_params
@ -119,11 +118,11 @@ module SimpleOAuth
end end
def url_params def url_params
CGI.parse(@uri.query || '').inject([]) { |p, (k, vs)| p + vs.sort.collect { |v| [k, v] } } CGI.parse(@uri.query || "").inject([]) { |p, (k, vs)| p + vs.sort.collect { |v| [k, v] } }
end end
def rsa_sha1_signature def rsa_sha1_signature
Base64.encode64(private_key.sign(OpenSSL::Digest::SHA1.new, signature_base)).chomp.gsub(/\n/, '') Base64.encode64(private_key.sign(OpenSSL::Digest.new("SHA1"), signature_base)).chomp.delete("\n")
end end
def private_key def private_key

View file

@ -0,0 +1,3 @@
module SimpleOauth
VERSION = "0.1.0".freeze
end

View file

@ -1,15 +1,33 @@
require_relative "lib/simple_oauth/version"
Gem::Specification.new do |spec| Gem::Specification.new do |spec|
spec.add_development_dependency 'bundler', '~> 1.0' spec.name = "simple_oauth"
spec.name = 'simple_oauth' spec.version = SimpleOauth::VERSION
spec.version = '0.3.1' spec.authors = ["Steve Richert", "Erik Berlin"]
spec.email = ["steve.richert@gmail.com", "sferik@gmail.com"]
spec.authors = ['Steve Richert', 'Erik Michaels-Ober'] spec.summary = "Simply builds and verifies OAuth headers"
spec.email = %w(steve.richert@gmail.com sferik@gmail.com) spec.description = spec.summary
spec.description = 'Simply builds and verifies OAuth headers' spec.homepage = "https://github.com/laserlemon/simple_oauth"
spec.summary = spec.description spec.license = "MIT"
spec.homepage = 'https://github.com/laserlemon/simple_oauth' spec.required_ruby_version = ">= 3.0"
spec.licenses = %w(MIT)
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.start_with?('spec/') } spec.metadata["allowed_push_host"] = "https://rubygems.org"
spec.require_paths = %w(lib)
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = "https://github.com/laserlemon/simple_oauth"
spec.metadata["changelog_uri"] = "https://github.com/laserlemon/simple_oauth/blob/master/CHANGELOG.md"
# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(__dir__) do
`git ls-files -z`.split("\x0").reject do |f|
(File.expand_path(f) == __FILE__) ||
f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor Gemfile])
end
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.metadata["rubygems_mfa_required"] = "true"
end end

View file

@ -1,20 +1,17 @@
if RUBY_VERSION >= '1.9' $LOAD_PATH.unshift File.expand_path("../lib", __dir__)
require 'simplecov'
require 'coveralls'
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter] require "simplecov"
SimpleCov.start do SimpleCov.start do
add_filter '/spec/' add_filter "/spec/"
minimum_coverage(100) minimum_coverage(100)
end
end end
require 'simple_oauth' require "rspec"
require 'rspec' require "simple_oauth"
def uri_parser def uri_parser
@uri_parser ||= URI.const_defined?(:Parser) ? URI::Parser.new : URI @uri_parser ||= URI.const_defined?(:Parser) ? URI::DEFAULT_PARSER : URI
end end
RSpec.configure do |config| RSpec.configure do |config|
@ -23,4 +20,4 @@ RSpec.configure do |config|
end end
end end
Dir[File.expand_path('../support/**/*.rb', __FILE__)].each { |f| require f } Dir[File.expand_path("support/**/*.rb", __dir__)].each { |f| require f }

View file

@ -1,379 +1,364 @@
# encoding: utf-8 require "helper"
require 'helper'
describe SimpleOAuth::Header do describe SimpleOAuth::Header do
describe '.default_options' do describe ".default_options" do
let(:default_options) { SimpleOAuth::Header.default_options } let(:default_options) { described_class.default_options }
it 'is different every time' do it "is different every time" do
expect(SimpleOAuth::Header.default_options).not_to eq default_options expect(described_class.default_options).not_to eq default_options
end end
it 'is used for new headers' do it "is used for new headers" do
allow(SimpleOAuth::Header).to receive(:default_options).and_return(default_options) allow(described_class).to receive(:default_options).and_return(default_options)
header = SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friendships.json', {}) header = described_class.new(:get, "https://api.twitter.com/1/statuses/friendships.json", {})
expect(header.options).to eq default_options expect(header.options).to eq default_options
end end
it 'includes a signature method and an OAuth version' do it "includes a signature method and an OAuth version" do
expect(default_options[:signature_method]).not_to be_nil expect(default_options[:signature_method]).not_to be_nil
expect(default_options[:version]).not_to be_nil expect(default_options[:version]).not_to be_nil
end end
end end
describe '.escape' do describe ".escape" do
it 'escapes (most) non-word characters' do it "escapes (most) non-word characters" do
[' ', '!', '@', '#', '$', '%', '^', '&'].each do |character| [" ", "!", "@", "#", "$", "%", "^", "&"].each do |character|
escaped = SimpleOAuth::Header.escape(character) escaped = described_class.escape(character)
expect(escaped).not_to eq character expect(escaped).not_to eq character
expect(escaped).to eq uri_parser.escape(character, /.*/) expect(escaped).to eq uri_parser.escape(character, /.*/)
end end
end end
it 'does not escape - . or ~' do it "does not escape - . or ~" do
['-', '.', '~'].each do |character| ["-", ".", "~"].each do |character|
escaped = SimpleOAuth::Header.escape(character) escaped = described_class.escape(character)
expect(escaped).to eq character expect(escaped).to eq character
end end
end end
def self.test_special_characters it "escapes non-ASCII characters" do
it 'escapes non-ASCII characters' do expect(described_class.escape("é")).to eq "%C3%A9"
expect(SimpleOAuth::Header.escape('é')).to eq '%C3%A9'
end
it 'escapes multibyte characters' do
expect(SimpleOAuth::Header.escape('あ')).to eq '%E3%81%82'
end
end end
if RUBY_VERSION >= '1.9' it "escapes multibyte characters" do
test_special_characters expect(described_class.escape("")).to eq "%E3%81%82"
else
%w(n N e E s S u U).each do |kcode|
describe %(when $KCODE = "#{kcode}") do
original_kcode = $KCODE # rubocop:disable GlobalVars
begin
$KCODE = kcode # rubocop:disable GlobalVars
test_special_characters
ensure
$KCODE = original_kcode # rubocop:disable GlobalVars
end
end
end
end end
end end
describe '.unescape' do describe ".unescape" do
pending pending
end end
describe '.parse' do describe ".parse" do
let(:header) { SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friends.json', {}) } let(:header) { described_class.new(:get, "https://api.twitter.com/1/statuses/friends.json", {}) }
let(:parsed_options) { SimpleOAuth::Header.parse(header) } let(:parsed_options) { described_class.parse(header) }
it 'returns a hash' do it "returns a hash" do
expect(parsed_options).to be_a(Hash) expect(parsed_options).to be_a(Hash)
end end
it 'includes the options used to build the header' do it "includes the options used to build the header" do
expect(parsed_options.reject { |k, _| k == :signature }).to eq header.options expect(parsed_options.except(:signature)).to eq header.options
end end
it 'includes a signature' do it "includes a signature" do
expect(header.options).not_to have_key(:signature) expect(header.options).not_to have_key(:signature)
expect(parsed_options).to have_key(:signature) expect(parsed_options).to have_key(:signature)
expect(parsed_options[:signature]).not_to be_nil expect(parsed_options[:signature]).not_to be_nil
end end
it "handles optional 'linear white space'" do it "handles optional 'linear white space'" do
parsed_header_with_spaces = SimpleOAuth::Header.parse 'OAuth oauth_consumer_key="abcd", oauth_nonce="oLKtec51GQy", oauth_signature="efgh%26mnop", oauth_signature_method="PLAINTEXT", oauth_timestamp="1286977095", oauth_token="ijkl", oauth_version="1.0"' parsed_header_with_spaces = described_class.parse 'OAuth oauth_consumer_key="abcd", oauth_nonce="oLKtec51GQy", oauth_signature="efgh%26mnop", oauth_signature_method="PLAINTEXT", oauth_timestamp="1286977095", oauth_token="ijkl", oauth_version="1.0"'
expect(parsed_header_with_spaces).to be_a_kind_of(Hash) expect(parsed_header_with_spaces).to be_a(Hash)
expect(parsed_header_with_spaces.keys.size).to eq 7 expect(parsed_header_with_spaces.keys.size).to eq 7
parsed_header_with_tabs = SimpleOAuth::Header.parse 'OAuth oauth_consumer_key="abcd", oauth_nonce="oLKtec51GQy", oauth_signature="efgh%26mnop", oauth_signature_method="PLAINTEXT", oauth_timestamp="1286977095", oauth_token="ijkl", oauth_version="1.0"' parsed_header_with_tabs = described_class.parse 'OAuth oauth_consumer_key="abcd", oauth_nonce="oLKtec51GQy", oauth_signature="efgh%26mnop", oauth_signature_method="PLAINTEXT", oauth_timestamp="1286977095", oauth_token="ijkl", oauth_version="1.0"'
expect(parsed_header_with_tabs).to be_a_kind_of(Hash) expect(parsed_header_with_tabs).to be_a(Hash)
expect(parsed_header_with_tabs.keys.size).to eq 7 expect(parsed_header_with_tabs.keys.size).to eq 7
parsed_header_with_spaces_and_tabs = SimpleOAuth::Header.parse 'OAuth oauth_consumer_key="abcd", oauth_nonce="oLKtec51GQy", oauth_signature="efgh%26mnop", oauth_signature_method="PLAINTEXT", oauth_timestamp="1286977095", oauth_token="ijkl", oauth_version="1.0"' parsed_header_with_spaces_and_tabs = described_class.parse 'OAuth oauth_consumer_key="abcd", oauth_nonce="oLKtec51GQy", oauth_signature="efgh%26mnop", oauth_signature_method="PLAINTEXT", oauth_timestamp="1286977095", oauth_token="ijkl", oauth_version="1.0"'
expect(parsed_header_with_spaces_and_tabs).to be_a_kind_of(Hash) expect(parsed_header_with_spaces_and_tabs).to be_a(Hash)
expect(parsed_header_with_spaces_and_tabs.keys.size).to eq 7 expect(parsed_header_with_spaces_and_tabs.keys.size).to eq 7
parsed_header_without_spaces = SimpleOAuth::Header.parse 'OAuth oauth_consumer_key="abcd",oauth_nonce="oLKtec51GQy",oauth_signature="efgh%26mnop",oauth_signature_method="PLAINTEXT",oauth_timestamp="1286977095",oauth_token="ijkl",oauth_version="1.0"' parsed_header_without_spaces = described_class.parse 'OAuth oauth_consumer_key="abcd",oauth_nonce="oLKtec51GQy",oauth_signature="efgh%26mnop",oauth_signature_method="PLAINTEXT",oauth_timestamp="1286977095",oauth_token="ijkl",oauth_version="1.0"'
expect(parsed_header_without_spaces).to be_a_kind_of(Hash) expect(parsed_header_without_spaces).to be_a(Hash)
expect(parsed_header_without_spaces.keys.size).to eq 7 expect(parsed_header_without_spaces.keys.size).to eq 7
end end
end end
describe '#initialize' do describe "#initialize" do
let(:header) { SimpleOAuth::Header.new(:get, 'HTTPS://api.TWITTER.com:443/1/statuses/friendships.json?foo=bar#anchor', {}) } let(:header) do
described_class.new(:get, "HTTPS://api.TWITTER.com:443/1/statuses/friendships.json?foo=bar#anchor", {})
it 'stringifies and uppercases the request method' do
expect(header.method).to eq 'GET'
end end
it 'downcases the scheme and authority' do it "stringifies and uppercases the request method" do
expect(header.method).to eq "GET"
end
it "downcases the scheme and authority" do
expect(header.url).to match %r{^https://api\.twitter\.com/} expect(header.url).to match %r{^https://api\.twitter\.com/}
end end
it 'ignores the query and fragment' do it "ignores the query and fragment" do
expect(header.url).to match %r{/1/statuses/friendships\.json$} expect(header.url).to match %r{/1/statuses/friendships\.json$}
end end
end end
describe '#valid?' do describe "#valid?" do
context 'using the HMAC-SHA1 signature method' do context "when using the HMAC-SHA1 signature method" do
it 'requires consumer and token secrets' do it "requires consumer and token secrets" do
secrets = {:consumer_secret => 'CONSUMER_SECRET', :token_secret => 'TOKEN_SECRET'} secrets = {consumer_secret: "CONSUMER_SECRET", token_secret: "TOKEN_SECRET"}
header = SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friends.json', {}, secrets) header = described_class.new(:get, "https://api.twitter.com/1/statuses/friends.json", {}, secrets)
parsed_header = SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friends.json', {}, header) parsed_header = described_class.new(:get, "https://api.twitter.com/1/statuses/friends.json", {}, header)
expect(parsed_header).not_to be_valid expect(parsed_header).not_to be_valid
expect(parsed_header).to be_valid(secrets) expect(parsed_header).to be_valid(secrets)
end end
end end
context 'using the RSA-SHA1 signature method' do context "when using the RSA-SHA1 signature method" do
it 'requires an identical private key' do it "requires an identical private key" do
secrets = {:consumer_secret => rsa_private_key} secrets = {consumer_secret: rsa_private_key}
header = SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friends.json', {}, secrets.merge(:signature_method => 'RSA-SHA1')) header = described_class.new(:get, "https://api.twitter.com/1/statuses/friends.json", {},
parsed_header = SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friends.json', {}, header) secrets.merge(signature_method: "RSA-SHA1"))
expect { parsed_header.valid? }.to raise_error parsed_header = described_class.new(:get, "https://api.twitter.com/1/statuses/friends.json", {}, header)
expect { parsed_header.valid? }.to raise_error(TypeError)
expect(parsed_header).to be_valid(secrets) expect(parsed_header).to be_valid(secrets)
end end
end end
context 'using the PLAINTEXT signature method' do context "when using the PLAINTEXT signature method" do
it 'requires consumer and token secrets' do it "requires consumer and token secrets" do
secrets = {:consumer_secret => 'CONSUMER_SECRET', :token_secret => 'TOKEN_SECRET'} secrets = {consumer_secret: "CONSUMER_SECRET", token_secret: "TOKEN_SECRET"}
header = SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friends.json', {}, secrets.merge(:signature_method => 'PLAINTEXT')) header = described_class.new(:get, "https://api.twitter.com/1/statuses/friends.json", {},
parsed_header = SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friends.json', {}, header) secrets.merge(signature_method: "PLAINTEXT"))
parsed_header = described_class.new(:get, "https://api.twitter.com/1/statuses/friends.json", {}, header)
expect(parsed_header).not_to be_valid expect(parsed_header).not_to be_valid
expect(parsed_header).to be_valid(secrets) expect(parsed_header).to be_valid(secrets)
end end
end end
end end
describe '#normalized_attributes' do describe "#normalized_attributes" do
let(:header) { SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friends.json', {}) } let(:header) { described_class.new(:get, "https://api.twitter.com/1/statuses/friends.json", {}) }
let(:normalized_attributes) { header.send(:normalized_attributes) } let(:normalized_attributes) { header.send(:normalized_attributes) }
it 'returns a sorted-key, quoted-value and comma-separated list' do it "returns a sorted-key, quoted-value and comma-separated list" do
allow(header).to receive(:signed_attributes).and_return(:d => 1, :c => 2, :b => 3, :a => 4) allow(header).to receive(:signed_attributes).and_return(d: 1, c: 2, b: 3, a: 4)
expect(normalized_attributes).to eq 'a="4", b="3", c="2", d="1"' expect(normalized_attributes).to eq 'a="4", b="3", c="2", d="1"'
end end
it 'URI encodes its values' do it "URI encodes its values" do
allow(header).to receive(:signed_attributes).and_return(1 => '!', 2 => '@', 3 => '#', 4 => '$') allow(header).to receive(:signed_attributes).and_return(1 => "!", 2 => "@", 3 => "#", 4 => "$")
expect(normalized_attributes).to eq '1="%21", 2="%40", 3="%23", 4="%24"' expect(normalized_attributes).to eq '1="%21", 2="%40", 3="%23", 4="%24"'
end end
end end
describe '#signed_attributes' do describe "#signed_attributes" do
it 'includes the OAuth signature' do it "includes the OAuth signature" do
header = SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friends.json', {}) header = described_class.new(:get, "https://api.twitter.com/1/statuses/friends.json", {})
expect(header.send(:signed_attributes)).to have_key(:oauth_signature) expect(header.send(:signed_attributes)).to have_key(:oauth_signature)
end end
end end
describe '#attributes' do describe "#attributes" do
let(:header) do let(:header) do
options = {} options = {}
SimpleOAuth::Header::ATTRIBUTE_KEYS.each { |k| options[k] = k.to_s.upcase } SimpleOAuth::Header::ATTRIBUTE_KEYS.each { |k| options[k] = k.to_s.upcase }
options[:other] = 'OTHER' options[:other] = "OTHER"
SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friendships.json', {}, options) described_class.new(:get, "https://api.twitter.com/1/statuses/friendships.json", {}, options)
end end
it "prepends keys with 'oauth_'" do it "prepends keys with 'oauth_'" do
header.options[:ignore_extra_keys] = true header.options[:ignore_extra_keys] = true
expect(header.send(:attributes).keys).to be_all { |k| k.to_s =~ /^oauth_/ } expect(header.send(:attributes).keys).to(be_all { |k| k.to_s =~ /^oauth_/ })
end end
it 'excludes keys not included in the list of valid attributes' do it "excludes keys not included in the list of valid attributes" do
header.options[:ignore_extra_keys] = true header.options[:ignore_extra_keys] = true
expect(header.send(:attributes).keys).to be_all { |k| k.is_a?(Symbol) } expect(header.send(:attributes).keys).to(be_all { |k| k.is_a?(Symbol) })
expect(header.send(:attributes)).not_to have_key(:oauth_other) expect(header.send(:attributes)).not_to have_key(:oauth_other)
end end
it 'preserves values for valid keys' do it "preserves values for valid keys" do
header.options[:ignore_extra_keys] = true header.options[:ignore_extra_keys] = true
expect(header.send(:attributes).size).to eq SimpleOAuth::Header::ATTRIBUTE_KEYS.size expect(header.send(:attributes).size).to eq SimpleOAuth::Header::ATTRIBUTE_KEYS.size
expect(header.send(:attributes)).to be_all { |k, v| k.to_s == "oauth_#{v.downcase}" } expect(header.send(:attributes)).to(be_all { |k, v| k.to_s == "oauth_#{v.downcase}" })
end end
it 'raises exception for extra keys' do it "raises exception for extra keys" do
expect { header.send(:attributes) }.to raise_error(RuntimeError, "SimpleOAuth: Found extra option keys not matching ATTRIBUTE_KEYS:\n [:other]") expect do
header.send(:attributes)
end.to raise_error(RuntimeError,
"SimpleOAuth: Found extra option keys not matching ATTRIBUTE_KEYS:\n [:other]")
end end
end end
describe '#signature' do describe "#signature" do
context 'calls the appropriate signature method' do specify "when using HMAC-SHA1" do
specify 'when using HMAC-SHA1' do header = described_class.new(:get, "https://api.twitter.com/1/statuses/friends.json", {}, signature_method: "HMAC-SHA1")
header = SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friends.json', {}, :signature_method => 'HMAC-SHA1') expect(header).to receive(:hmac_sha1_signature).once.and_return("HMAC_SHA1_SIGNATURE")
expect(header).to receive(:hmac_sha1_signature).once.and_return('HMAC_SHA1_SIGNATURE') expect(header.send(:signature)).to eq "HMAC_SHA1_SIGNATURE"
expect(header.send(:signature)).to eq 'HMAC_SHA1_SIGNATURE' end
end
specify 'when using RSA-SHA1' do specify "when using RSA-SHA1" do
header = SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friends.json', {}, :signature_method => 'RSA-SHA1') header = described_class.new(:get, "https://api.twitter.com/1/statuses/friends.json", {}, signature_method: "RSA-SHA1")
expect(header).to receive(:rsa_sha1_signature).once.and_return('RSA_SHA1_SIGNATURE') expect(header).to receive(:rsa_sha1_signature).once.and_return("RSA_SHA1_SIGNATURE")
expect(header.send(:signature)).to eq 'RSA_SHA1_SIGNATURE' expect(header.send(:signature)).to eq "RSA_SHA1_SIGNATURE"
end end
specify 'when using PLAINTEXT' do specify "when using PLAINTEXT" do
header = SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friends.json', {}, :signature_method => 'PLAINTEXT') header = described_class.new(:get, "https://api.twitter.com/1/statuses/friends.json", {}, signature_method: "PLAINTEXT")
expect(header).to receive(:plaintext_signature).once.and_return('PLAINTEXT_SIGNATURE') expect(header).to receive(:plaintext_signature).once.and_return("PLAINTEXT_SIGNATURE")
expect(header.send(:signature)).to eq 'PLAINTEXT_SIGNATURE' expect(header.send(:signature)).to eq "PLAINTEXT_SIGNATURE"
end
end end
end end
describe '#hmac_sha1_signature' do describe "#hmac_sha1_signature" do
it 'reproduces a successful Twitter GET' do it "reproduces a successful Twitter GET" do
options = { options = {
:consumer_key => '8karQBlMg6gFOwcf8kcoYw', consumer_key: "8karQBlMg6gFOwcf8kcoYw",
:consumer_secret => '3d0vcHyUiiqADpWxolW8nlDIpSWMlyK7YNgc5Qna2M', consumer_secret: "3d0vcHyUiiqADpWxolW8nlDIpSWMlyK7YNgc5Qna2M",
:nonce => '547fed103e122eecf84c080843eedfe6', nonce: "547fed103e122eecf84c080843eedfe6",
:signature_method => 'HMAC-SHA1', signature_method: "HMAC-SHA1",
:timestamp => '1286830180', timestamp: "1286830180",
:token => '201425800-Sv4sTcgoffmHGkTCue0JnURT8vrm4DiFAkeFNDkh', token: "201425800-Sv4sTcgoffmHGkTCue0JnURT8vrm4DiFAkeFNDkh",
:token_secret => 'T5qa1tF57tfDzKmpM89DHsNuhgOY4NT6DlNLsTFcuQ', token_secret: "T5qa1tF57tfDzKmpM89DHsNuhgOY4NT6DlNLsTFcuQ"
} }
header = SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friends.json', {}, options) header = described_class.new(:get, "https://api.twitter.com/1/statuses/friends.json", {}, options)
expect(header.to_s).to eq 'OAuth oauth_consumer_key="8karQBlMg6gFOwcf8kcoYw", oauth_nonce="547fed103e122eecf84c080843eedfe6", oauth_signature="i9CT6ahDRAlfGX3hKYf78QzXsaw%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1286830180", oauth_token="201425800-Sv4sTcgoffmHGkTCue0JnURT8vrm4DiFAkeFNDkh", oauth_version="1.0"' expect(header.to_s).to eq 'OAuth oauth_consumer_key="8karQBlMg6gFOwcf8kcoYw", oauth_nonce="547fed103e122eecf84c080843eedfe6", oauth_signature="i9CT6ahDRAlfGX3hKYf78QzXsaw%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1286830180", oauth_token="201425800-Sv4sTcgoffmHGkTCue0JnURT8vrm4DiFAkeFNDkh", oauth_version="1.0"'
end end
it 'reproduces a successful Twitter POST' do it "reproduces a successful Twitter POST" do
options = { options = {
:consumer_key => '8karQBlMg6gFOwcf8kcoYw', consumer_key: "8karQBlMg6gFOwcf8kcoYw",
:consumer_secret => '3d0vcHyUiiqADpWxolW8nlDIpSWMlyK7YNgc5Qna2M', consumer_secret: "3d0vcHyUiiqADpWxolW8nlDIpSWMlyK7YNgc5Qna2M",
:nonce => 'b40a3e0f18590ecdcc0e273f7d7c82f8', nonce: "b40a3e0f18590ecdcc0e273f7d7c82f8",
:signature_method => 'HMAC-SHA1', signature_method: "HMAC-SHA1",
:timestamp => '1286830181', timestamp: "1286830181",
:token => '201425800-Sv4sTcgoffmHGkTCue0JnURT8vrm4DiFAkeFNDkh', token: "201425800-Sv4sTcgoffmHGkTCue0JnURT8vrm4DiFAkeFNDkh",
:token_secret => 'T5qa1tF57tfDzKmpM89DHsNuhgOY4NT6DlNLsTFcuQ', token_secret: "T5qa1tF57tfDzKmpM89DHsNuhgOY4NT6DlNLsTFcuQ"
} }
header = SimpleOAuth::Header.new(:post, 'https://api.twitter.com/1/statuses/update.json', {:status => 'hi, again'}, options) header = described_class.new(:post, "https://api.twitter.com/1/statuses/update.json",
{status: "hi, again"}, options)
expect(header.to_s).to eq 'OAuth oauth_consumer_key="8karQBlMg6gFOwcf8kcoYw", oauth_nonce="b40a3e0f18590ecdcc0e273f7d7c82f8", oauth_signature="mPqSFKejrWWk3ZT9bTQjhO5b2xI%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1286830181", oauth_token="201425800-Sv4sTcgoffmHGkTCue0JnURT8vrm4DiFAkeFNDkh", oauth_version="1.0"' expect(header.to_s).to eq 'OAuth oauth_consumer_key="8karQBlMg6gFOwcf8kcoYw", oauth_nonce="b40a3e0f18590ecdcc0e273f7d7c82f8", oauth_signature="mPqSFKejrWWk3ZT9bTQjhO5b2xI%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1286830181", oauth_token="201425800-Sv4sTcgoffmHGkTCue0JnURT8vrm4DiFAkeFNDkh", oauth_version="1.0"'
end end
end end
describe '#secret' do describe "#secret" do
let(:header) { SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friendships.json', {}) } let(:header) { described_class.new(:get, "https://api.twitter.com/1/statuses/friendships.json", {}) }
let(:secret) { header.send(:secret) } let(:secret) { header.send(:secret) }
it 'combines the consumer and token secrets with an ampersand' do it "combines the consumer and token secrets with an ampersand" do
allow(header).to receive(:options).and_return(:consumer_secret => 'CONSUMER_SECRET', :token_secret => 'TOKEN_SECRET') allow(header).to receive(:options).and_return(consumer_secret: "CONSUMER_SECRET",
expect(secret).to eq 'CONSUMER_SECRET&TOKEN_SECRET' token_secret: "TOKEN_SECRET")
expect(secret).to eq "CONSUMER_SECRET&TOKEN_SECRET"
end end
it 'URI encodes each secret value before combination' do it "URI encodes each secret value before combination" do
allow(header).to receive(:options).and_return(:consumer_secret => 'CONSUM#R_SECRET', :token_secret => 'TOKEN_S#CRET') allow(header).to receive(:options).and_return(consumer_secret: "CONSUM#R_SECRET",
expect(secret).to eq 'CONSUM%23R_SECRET&TOKEN_S%23CRET' token_secret: "TOKEN_S#CRET")
expect(secret).to eq "CONSUM%23R_SECRET&TOKEN_S%23CRET"
end end
end end
describe '#signature_base' do describe "#signature_base" do
let(:header) { SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friendships.json', {}) } let(:header) { described_class.new(:get, "https://api.twitter.com/1/statuses/friendships.json", {}) }
let(:signature_base) { header.send(:signature_base) } let(:signature_base) { header.send(:signature_base) }
it 'combines the request method, URL and normalized parameters using ampersands' do it "combines the request method, URL and normalized parameters using ampersands" do
allow(header).to receive(:method).and_return('METHOD') allow(header).to receive_messages(method: "METHOD", url: "URL", normalized_params: "NORMALIZED_PARAMS")
allow(header).to receive(:url).and_return('URL') expect(signature_base).to eq "METHOD&URL&NORMALIZED_PARAMS"
allow(header).to receive(:normalized_params).and_return('NORMALIZED_PARAMS')
expect(signature_base).to eq 'METHOD&URL&NORMALIZED_PARAMS'
end end
it 'URI encodes each value before combination' do it "URI encodes each value before combination" do
allow(header).to receive(:method).and_return('ME#HOD') allow(header).to receive_messages(method: "ME#HOD", url: "U#L", normalized_params: "NORMAL#ZED_PARAMS")
allow(header).to receive(:url).and_return('U#L') expect(signature_base).to eq "ME%23HOD&U%23L&NORMAL%23ZED_PARAMS"
allow(header).to receive(:normalized_params).and_return('NORMAL#ZED_PARAMS')
expect(signature_base).to eq 'ME%23HOD&U%23L&NORMAL%23ZED_PARAMS'
end end
end end
describe '#normalized_params' do describe "#normalized_params" do
let(:header) do let(:header) do
header = SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friendships.json', {}) header = described_class.new(:get, "https://api.twitter.com/1/statuses/friendships.json", {})
allow(header).to receive(:signature_params).and_return([%w(A 4), %w(B 3), %w(B 2), %w(C 1), ['D[]', '0 ']]) allow(header).to receive(:signature_params).and_return([%w[A 4], %w[B 3], %w[B 2], %w[C 1], ["D[]", "0 "]])
header header
end end
let(:signature_params) { header.send(:signature_params) } let(:signature_params) { header.send(:signature_params) }
let(:normalized_params) { header.send(:normalized_params) } let(:normalized_params) { header.send(:normalized_params) }
it 'joins key/value pairs with equal signs and ampersands' do it "joins key/value pairs with equal signs and ampersands" do
expect(normalized_params).to be_a(String) expect(normalized_params).to be_a(String)
parts = normalized_params.split('&') parts = normalized_params.split("&")
expect(parts.size).to eq signature_params.size expect(parts.size).to eq signature_params.size
pairs = parts.collect { |p| p.split('=') } pairs = parts.collect { |p| p.split("=") }
expect(pairs).to be_all { |p| p.size == 2 } expect(pairs).to(be_all { |p| p.size == 2 })
end end
end end
describe '#signature_params' do describe "#signature_params" do
let(:header) { SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friendships.json', {}) } let(:header) { described_class.new(:get, "https://api.twitter.com/1/statuses/friendships.json", {}) }
let(:signature_params) { header.send(:signature_params) } let(:signature_params) { header.send(:signature_params) }
it 'combines OAuth header attributes, body parameters and URL parameters into an flattened array of key/value pairs' do it "combines OAuth header attributes, body parameters and URL parameters into an flattened array of key/value pairs" do
allow(header).to receive(:attributes).and_return(:attribute => 'ATTRIBUTE') allow(header).to receive_messages(attributes: {attribute: "ATTRIBUTE"}, params: {"param" => "PARAM"},
allow(header).to receive(:params).and_return('param' => 'PARAM') url_params: [%w[url_param 1], %w[url_param 2]])
allow(header).to receive(:url_params).and_return([%w(url_param 1), %w(url_param 2)])
expect(signature_params).to eq [ expect(signature_params).to eq [
[:attribute, 'ATTRIBUTE'], [:attribute, "ATTRIBUTE"],
%w(param PARAM), %w[param PARAM],
%w(url_param 1), %w[url_param 1],
%w(url_param 2), %w[url_param 2]
] ]
end end
end end
describe '#url_params' do describe "#url_params" do
it 'returns an empty array when the URL has no query parameters' do it "returns an empty array when the URL has no query parameters" do
header = SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friendships.json', {}) header = described_class.new(:get, "https://api.twitter.com/1/statuses/friendships.json", {})
expect(header.send(:url_params)).to eq [] expect(header.send(:url_params)).to eq []
end end
it 'returns an array of key/value pairs for each query parameter' do it "returns an array of key/value pairs for each query parameter" do
header = SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friendships.json?test=TEST', {}) header = described_class.new(:get, "https://api.twitter.com/1/statuses/friendships.json?test=TEST", {})
expect(header.send(:url_params)).to eq [%w(test TEST)] expect(header.send(:url_params)).to eq [%w[test TEST]]
end end
it 'sorts values for repeated keys' do it "sorts values for repeated keys" do
header = SimpleOAuth::Header.new(:get, 'https://api.twitter.com/1/statuses/friendships.json?test=3&test=1&test=2', {}) header = described_class.new(:get,
expect(header.send(:url_params)).to eq [%w(test 1), %w(test 2), %w(test 3)] "https://api.twitter.com/1/statuses/friendships.json?test=3&test=1&test=2", {})
expect(header.send(:url_params)).to eq [%w[test 1], %w[test 2], %w[test 3]]
end end
end end
describe '#rsa_sha1_signature' do describe "#rsa_sha1_signature" do
it 'reproduces a successful OAuth example GET' do it "reproduces a successful OAuth example GET" do
options = { options = {
:consumer_key => 'dpf43f3p2l4k3l03', consumer_key: "dpf43f3p2l4k3l03",
:consumer_secret => rsa_private_key, consumer_secret: rsa_private_key,
:nonce => '13917289812797014437', nonce: "13917289812797014437",
:signature_method => 'RSA-SHA1', signature_method: "RSA-SHA1",
:timestamp => '1196666512', timestamp: "1196666512"
} }
header = SimpleOAuth::Header.new(:get, 'http://photos.example.net/photos', {:file => 'vacaction.jpg', :size => 'original'}, options) header = described_class.new(:get, "http://photos.example.net/photos",
{file: "vacaction.jpg", size: "original"}, options)
expect(header.to_s).to eq 'OAuth oauth_consumer_key="dpf43f3p2l4k3l03", oauth_nonce="13917289812797014437", oauth_signature="jvTp%2FwX1TYtByB1m%2BPbyo0lnCOLIsyGCH7wke8AUs3BpnwZJtAuEJkvQL2%2F9n4s5wUmUl4aCI4BwpraNx4RtEXMe5qg5T1LVTGliMRpKasKsW%2F%2Fe%2BRinhejgCuzoH26dyF8iY2ZZ%2F5D1ilgeijhV%2FvBka5twt399mXwaYdCwFYE%3D", oauth_signature_method="RSA-SHA1", oauth_timestamp="1196666512", oauth_version="1.0"' expect(header.to_s).to eq 'OAuth oauth_consumer_key="dpf43f3p2l4k3l03", oauth_nonce="13917289812797014437", oauth_signature="jvTp%2FwX1TYtByB1m%2BPbyo0lnCOLIsyGCH7wke8AUs3BpnwZJtAuEJkvQL2%2F9n4s5wUmUl4aCI4BwpraNx4RtEXMe5qg5T1LVTGliMRpKasKsW%2F%2Fe%2BRinhejgCuzoH26dyF8iY2ZZ%2F5D1ilgeijhV%2FvBka5twt399mXwaYdCwFYE%3D", oauth_signature_method="RSA-SHA1", oauth_timestamp="1196666512", oauth_version="1.0"'
end end
end end
describe '#private_key' do describe "#private_key" do
pending pending
end end
describe '#plaintext_signature' do describe "#plaintext_signature" do
it 'reproduces a successful OAuth example GET' do it "reproduces a successful OAuth example GET" do
options = { options = {
:consumer_key => 'abcd', consumer_key: "abcd",
:consumer_secret => 'efgh', consumer_secret: "efgh",
:nonce => 'oLKtec51GQy', nonce: "oLKtec51GQy",
:signature_method => 'PLAINTEXT', signature_method: "PLAINTEXT",
:timestamp => '1286977095', timestamp: "1286977095",
:token => 'ijkl', token: "ijkl",
:token_secret => 'mnop', token_secret: "mnop"
} }
header = SimpleOAuth::Header.new(:get, 'http://host.net/resource?name=value', {:name => 'value'}, options) header = described_class.new(:get, "http://host.net/resource?name=value", {name: "value"}, options)
expect(header.to_s).to eq 'OAuth oauth_consumer_key="abcd", oauth_nonce="oLKtec51GQy", oauth_signature="efgh%26mnop", oauth_signature_method="PLAINTEXT", oauth_timestamp="1286977095", oauth_token="ijkl", oauth_version="1.0"' expect(header.to_s).to eq 'OAuth oauth_consumer_key="abcd", oauth_nonce="oLKtec51GQy", oauth_signature="efgh%26mnop", oauth_signature_method="PLAINTEXT", oauth_timestamp="1286977095", oauth_token="ijkl", oauth_version="1.0"'
end end
end end

View file

@ -1,5 +1,5 @@
module RSAHelpers module RSAHelpers
PRIVATE_KEY_PATH = File.expand_path('../fixtures/rsa-private-key', __FILE__) PRIVATE_KEY_PATH = File.expand_path("fixtures/rsa-private-key", __dir__)
def rsa_private_key def rsa_private_key
@rsa_private_key ||= File.read(PRIVATE_KEY_PATH) @rsa_private_key ||= File.read(PRIVATE_KEY_PATH)