Compare commits

...

61 commits

Author SHA1 Message Date
6df44cae57
Merge pull request #1 from samsonjs/fix-ruby-3.4-warning
Fix Ruby 3.4 warnings
2025-07-22 08:53:29 -07:00
73c287fb4b
Update version to 0.3.1 2025-06-08 12:14:50 -07:00
3c5f590f95
Fix warnings in Ruby 3.4
- Update RuboCop config to use plugins instead of require for extensions

- Replace deprecated RSpec/FilePath with RSpec/SpecFilePathFormat and
  RSpec/SpecFilePathSuffix

- Fix URI parser deprecation by using URI::RFC2396_PARSER instead of
  URI::DEFAULT_PARSER

- Replace Hash#select with Hash#slice for better performance and clarity

- Add base64 dependency to gemspec for Ruby 3.4 compatibility
2025-06-08 10:30:40 -07:00
Erik Berlin
8d6792a74f Update for 2023 2023-08-16 14:51:14 -07:00
Erik Michaels-Ober
4a375da4e2 Bump version to 0.3.1 2014-12-28 17:34:53 -06:00
Erik Michaels-Ober
9c55f41af1 Fix specs on JRuby 2014-12-28 17:25:35 -06:00
Erik Michaels-Ober
987239fefe Fix RuboCop offenses 2014-12-28 08:55:42 -06:00
Erik Michaels-Ober
07c7f80079 Merge pull request #20 from mpapis/features/add_ignored_keys
add IGNORED_KEYS for options used in signature calculations
2014-12-28 08:49:26 -06:00
Michal Papis
e772b6734c
add :signature to IGNORED_KEYS, improve tests 2014-11-05 15:58:46 +01:00
Michal Papis
234fd8793b
add IGNORED_KEYS for options used in signature calculations 2014-11-05 15:48:43 +01:00
Erik Michaels-Ober
cbc2df1ca0 Merge pull request #18 from stve/plaintext-spec
fix description on PLAINTEXT spec
2014-10-31 16:23:37 +01:00
Steve Agalloco
c9ed688bea fix description on PLAINTEXT spec 2014-10-31 10:58:08 -04:00
Erik Michaels-Ober
85ed12045c Fix typo [ci skip] 2014-10-09 02:44:50 +02:00
Erik Michaels-Ober
4f79360ae1 Bump version to 0.3.0 2014-10-09 02:42:18 +02:00
Erik Michaels-Ober
8de6ba138a Don't package test files with gem [ci skip] 2014-10-09 02:16:40 +02:00
Erik Michaels-Ober
be8a895c73 Put a comma after the last item of a multiline array or hash 2014-09-23 23:11:41 +02:00
Erik Michaels-Ober
acfc793be6 %w-literals should be delimited by ( and ) 2014-09-23 23:11:38 +02:00
Erik Michaels-Ober
91a007358c Merge pull request #17 from mpapis/features/raise_on_extra_option_keys
ignored string options
2014-09-23 22:43:09 +02:00
Michal Papis
62147887a6 raise error when option keys not found in ATTRIBUTE_KEYS 2014-09-23 22:09:13 +02:00
Erik Michaels-Ober
466ea5c7b8 Update simplecov dependency to >= 0.9 2014-08-21 21:02:41 +02:00
Erik Michaels-Ober
1007241ebd Lock rest-client to ~> 1.6.0 on Ruby 1.8.7 2014-08-21 20:51:06 +02:00
Erik Michaels-Ober
600f640fff Flip secret bit to enable Docker builds 2014-08-21 20:25:24 +02:00
Erik Michaels-Ober
4fb9cdfe4d Update rubocop dependency to >= 0.23 2014-06-23 08:22:41 +02:00
Erik Michaels-Ober
5663895b4e Allow failure on Rubinius 2 2014-05-02 13:56:01 +02:00
Erik Michaels-Ober
e40b445be1 Use _ to indicate that block argument is unused 2014-05-02 12:54:41 +02:00
Erik Michaels-Ober
65a3bdcde8 Fix RuboCop offenses introduced in version 0.20.0 2014-04-02 21:12:55 +02:00
Erik Michaels-Ober
300f73d018 Add Yardstick 2014-03-24 11:23:03 +01:00
Erik Michaels-Ober
a4443c04f5 Enforce code coverage minimums 2014-03-24 11:18:17 +01:00
Erik Michaels-Ober
b813b8b892 Use resolution-independent SVG badges [ci skip] 2014-03-24 11:18:17 +01:00
Erik Michaels-Ober
c19aab01f8 Fix RuboCop offenses 2014-03-24 11:18:17 +01:00
Erik Michaels-Ober
595ab454c1 Add RuboCop 2014-03-24 11:18:11 +01:00
Erik Michaels-Ober
cf00517e81 Fail slow 2014-03-24 10:54:15 +01:00
Erik Michaels-Ober
f60702269d Replace stub with allow...to receive 2013-07-09 10:16:15 +02:00
Erik Michaels-Ober
76c2548c49 Replace should_receive with expect...to receive 2013-07-09 10:12:10 +02:00
Erik Michaels-Ober
d4d7f88451 Add Code Climate badge [ci skip] 2013-03-13 07:41:30 -07:00
Erik Michaels-Ober
cdebe1a2eb Fix indentation [ci skip] 2013-02-26 10:39:07 -08:00
Erik Michaels-Ober
847e7bd8c6 Fix typo in badge [ci skip] 2013-02-25 16:41:47 -08:00
Erik Michaels-Ober
c53f4ddcab Add Coveralls for code coverage reporting 2013-02-25 16:40:40 -08:00
Erik Michaels-Ober
bbba30621d The source :rubygems is deprecated because HTTP requests are insecure. 2013-02-14 09:08:21 -08:00
Erik Michaels-Ober
c9db31725d Convert LICENSE to Markdown [ci skip] 2013-02-09 08:07:22 -08:00
Erik Michaels-Ober
8e05c9adaf Reword [ci skip] 2013-02-09 07:45:13 -08:00
Erik Michaels-Ober
a74d28245c Add official support for Ruby 2.0.0 [ci skip] 2013-02-08 22:28:47 -08:00
Erik Michaels-Ober
01d084ba82 Don't implicitly require simplecov 2013-02-06 11:39:17 -08:00
Erik Michaels-Ober
960a969590 Fix typo in ff6d87ef82 2013-02-02 20:53:32 -08:00
Erik Michaels-Ober
ff6d87ef82 Add bundler development dependency 2013-02-02 08:18:02 -08:00
Erik Michaels-Ober
fb0ba20cb8 Move development dependencies into Gemfile 2013-01-26 00:42:24 -08:00
Erik Michaels-Ober
3d340dd4c0 Use canonical method names in class 2012-12-01 18:26:38 -08:00
Erik Michaels-Ober
e951d6a892 Bump version to 0.2.0 2012-12-01 18:19:56 -08:00
Erik Michaels-Ober
02d041d028 Alias encode to escape and decode to unescape 2012-12-01 18:18:29 -08:00
Erik Michaels-Ober
f67afa46fa Fix "URI.escape is obsolete" warnings on Ruby >= 1.9 2012-12-01 18:09:58 -08:00
Erik Michaels-Ober
496a6726ca Add #licenses declaration to gemspec 2012-11-17 20:28:30 -08:00
Erik Michaels-Ober
365ca8b930 Fail fast 2012-11-17 20:27:20 -08:00
Erik Michaels-Ober
c769ca330e Convert specs to the new RSpec expectation syntax
See http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
2012-10-10 06:48:35 -07:00
Erik Michaels-Ober
80d23acf27 Run specs in random order to catch order-dependency bugs 2012-10-10 00:30:35 -07:00
Erik Michaels-Ober
a8d6e244b7 Move "Contributing" section into dedicated document for better GitHub integration
See https://github.com/blog/1184-contributing-guidelines.
2012-10-07 12:08:19 -07:00
Erik Michaels-Ober
18065a7bf5 Bump version to 0.1.9 2012-07-20 08:57:46 -07:00
Erik Michaels-Ober
167b696eb5 Merge pull request #6 from Viximo/feature/callback
OAuth attributes should include optional OAuth 1.0a keys
2012-07-19 08:47:57 -07:00
Erik Michaels-Ober
27ce779af0 Merge pull request #4 from steeve/patch-1
Only put option when there is a value. (Causes errors with Netflix API).
2012-07-19 08:42:11 -07:00
Matt Griffin
02328a8f14 OAuth attributes should include optional OAuth 1.0a keys: oauth_callback and oauth_verifier 2012-03-08 16:48:45 -05:00
Steeve Morin
62a01b6d18 simple key/value presence test for attributes 2011-09-28 14:21:40 +03:00
Steeve Morin
c75b82d392 Only put option when there is a value. (Causes errors with Netflix API). 2011-09-27 18:32:38 +03:00
24 changed files with 571 additions and 387 deletions

View file

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

16
.gitignore vendored
View file

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

2
.rspec Normal file
View file

@ -0,0 +1,2 @@
--color
--order random

77
.rubocop.yml Normal file
View file

@ -0,0 +1,77 @@
require:
- standard
plugins:
- standard-performance
- rubocop-rspec
- rubocop-performance
- rubocop-rake
AllCops:
NewCops: enable
TargetRubyVersion: 3.0
Layout/ArgumentAlignment:
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
Layout/ParameterAlignment:
Enabled: true
EnforcedStyle: with_fixed_indentation
IndentationWidth: ~
Layout/SpaceInsideHashLiteralBraces:
Enabled: false
Metrics/ParameterLists:
CountKeywordArgs: false
RSpec/MultipleExpectations:
Enabled: false
RSpec/ExampleLength:
Enabled: false
RSpec/MessageSpies:
Enabled: false
RSpec/PendingWithoutReason:
Enabled: false
RSpec/SpecFilePathFormat:
Enabled: false
RSpec/SpecFilePathSuffix:
Enabled: false
Style/Alias:
Enabled: true
EnforcedStyle: prefer_alias_method
Style/FrozenStringLiteralComment:
Enabled: false
Style/StringLiterals:
Enabled: true
EnforcedStyle: double_quotes
Style/StringLiteralsInInterpolation:
Enabled: true
EnforcedStyle: double_quotes

View file

@ -1,10 +1,21 @@
language: ruby
env:
global:
- JRUBY_OPTS="$JRUBY_OPTS --debug"
rvm:
- rbx-18mode
- rbx-19mode
- 1.8.7
- 1.9.3
- 2.0.0
- 2.1
- jruby-18mode
- jruby-19mode
- 1.8.7
- 1.9.2
- 1.9.3
- jruby-head
- rbx-2
- ruby-head
matrix:
allow_failures:
- rvm: jruby-head
- rvm: rbx-2
- rvm: ruby-head
fast_finish: true
sudo: false

View file

@ -1,4 +1,5 @@
--markup markdown
-
HISTORY.md
CONTRIBUTING.md
LICENSE.md
README.md

5
CHANGELOG.md Normal file
View file

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

8
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,8 @@
## Contributing
1. Fork the project.
2. Create a topic branch.
3. Add failing tests.
4. Add code to pass the failing tests.
5. Run `bundle exec rake`. If failing, repeat step 4.
6. Commit and push your changes.
7. Submit a pull request. Please do not include changes to the gemspec.

17
Gemfile
View file

@ -1,7 +1,14 @@
source 'https://rubygems.org'
platforms :jruby do
gem 'jruby-openssl', '~> 0.7'
end
source "https://rubygems.org"
# Specify your gem's dependencies in simple_oauth.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"

22
LICENSE
View file

@ -1,22 +0,0 @@
Copyright (c) 2010 Steve Richert, Erik Michaels-Ober
MIT License
Permission is hereby granted, free of charge, to any person obtaining
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
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE 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.

21
LICENSE.md Normal file
View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2010-2023 Steve Richert, Erik Michaels-Ober
Permission is hereby granted, free of charge, to any person obtaining 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 included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
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,42 +1,24 @@
# simple_oauth [![Build Status](https://secure.travis-ci.org/laserlemon/simple_oauth.png)](http://travis-ci.org/laserlemon/simple_oauth) [![Dependency Status](https://gemnasium.com/laserlemon/simple_oauth.png)](https://gemnasium.com/laserlemon/simple_oauth)
# simple_oauth
Simply builds and verifies OAuth headers
## Installation
Install the gem and add to the application's Gemfile by executing:
$ bundle add simple_oauth
If bundler is not being used to manage dependencies, install the gem by executing:
$ gem install simple_oauth
## Contributing
1. Fork the project.
2. Create a topic branch.
3. Add failing tests.
4. Add code to pass the failing tests.
5. Run `bundle exec rake`. If failing, repeat step 4.
6. Commit and push your changes.
7. Submit a pull request. Please do not include changes to the gemspec.
## Supported Rubies
This library aims to support and is [tested
against](http://travis-ci.org/laserlemon/simple_oauth) the following Ruby
implementations:
Bug reports and pull requests are welcome on GitHub at https://github.com/laserlemon/simple_oauth.
* Ruby 1.8.7
* Ruby 1.9.2
* Ruby 1.9.3
* Ruby head
* [JRuby](http://www.jruby.org/)
* [Rubinius](http://rubini.us/)
This project conforms to [Standard Ruby](https://github.com/standardrb/standard). Patches that dont maintain that standard will not be accepted.
If something doesn't work on one of these interpreters, it should be considered
a bug.
## License
This library may inadvertently work (or seem to work) on other Ruby
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
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 personally 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 Steve Richert, Erik Michaels-Ober.
See [LICENSE](https://github.com/laserlemon/simple_oauth/blob/master/LICENSE) for details.
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).

View file

@ -1,6 +1,10 @@
require 'bundler/gem_tasks'
require 'rspec/core/rake_task'
require "bundler/gem_tasks"
require "rspec/core/rake_task"
require "rubocop/rake_task"
require "standard/rake"
RSpec::Core::RakeTask.new(:spec)
task :default => :spec
RuboCop::RakeTask.new
task default: %i[spec rubocop standard]

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,38 +1,51 @@
require 'openssl'
require 'uri'
require 'base64'
require 'cgi'
require "openssl"
require "uri"
require "base64"
require "cgi"
module SimpleOAuth
# Generates OAuth header for HTTP request
class Header
ATTRIBUTE_KEYS = [:consumer_key, :nonce, :signature_method, :timestamp, :token, :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
def self.default_options
{
:nonce => OpenSSL::Random.random_bytes(16).unpack('H*')[0],
:signature_method => 'HMAC-SHA1',
:timestamp => Time.now.to_i.to_s,
:version => '1.0'
}
end
def self.encode(value)
URI.encode(value.to_s, /[^a-z0-9\-\.\_\~]/i)
end
def self.decode(value)
URI.decode(value.to_s)
end
def self.parse(header)
header.to_s.sub(/^OAuth\s/, '').split(/,\s*/).inject({}) do |attributes, pair|
match = pair.match(/^(\w+)\=\"([^\"]*)\"$/)
attributes.merge(match[1].sub(/^oauth_/, '').to_sym => decode(match[2]))
end
end
IGNORED_KEYS = %i[consumer_secret token_secret signature].freeze unless defined? ::SimpleOAuth::Header::IGNORED_KEYS
attr_reader :method, :params, :options
class << self
def default_options
{
nonce: OpenSSL::Random.random_bytes(16).unpack1("H*"),
signature_method: "HMAC-SHA1",
timestamp: Time.now.to_i.to_s,
version: "1.0"
}
end
def parse(header)
header.to_s.sub(/^OAuth\s/, "").split(/,\s*/).inject({}) do |attributes, pair|
match = pair.match(/^(\w+)="([^"]*)"$/)
attributes.merge(match[1].sub(/^oauth_/, "").to_sym => unescape(match[2]))
end
end
def escape(value)
uri_parser.escape(value.to_s, /[^a-z0-9\-._~]/i)
end
alias_method :encode, :escape
def unescape(value)
uri_parser.unescape(value.to_s)
end
alias_method :decode, :unescape
private
def uri_parser
@uri_parser ||= URI.const_defined?(:Parser) ? URI::RFC2396_PARSER : URI
end
end
def initialize(method, url, params, oauth = {})
@method = method.to_s.upcase
@uri = URI.parse(url.to_s)
@ -62,38 +75,42 @@ module SimpleOAuth
end
def signed_attributes
attributes.merge(:oauth_signature => signature)
attributes.merge(oauth_signature: signature)
end
private
def normalized_attributes
signed_attributes.sort_by{|k,v| k.to_s }.map{|k,v| %(#{k}="#{self.class.encode(v)}") }.join(', ')
signed_attributes.sort_by { |k, _| k.to_s }.collect { |k, v| %(#{k}="#{self.class.escape(v)}") }.join(", ")
end
def attributes
ATTRIBUTE_KEYS.inject({}){|a,k| options.key?(k) ? a.merge(:"oauth_#{k}" => options[k]) : a }
matching_keys, extra_keys = options.keys.partition { |key| ATTRIBUTE_KEYS.include?(key) }
extra_keys -= IGNORED_KEYS
raise "SimpleOAuth: Found extra option keys not matching ATTRIBUTE_KEYS:\n [#{extra_keys.collect(&:inspect).join(", ")}]" unless options[:ignore_extra_keys] || extra_keys.empty?
options.slice(*matching_keys).transform_keys { |key| :"oauth_#{key}" }
end
def signature
send(options[:signature_method].downcase.tr('-', '_') + '_signature')
send("#{options[:signature_method].downcase.tr("-", "_")}_signature")
end
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
def secret
options.values_at(:consumer_secret, :token_secret).map{|v| self.class.encode(v) }.join('&')
options.values_at(:consumer_secret, :token_secret).collect { |v| self.class.escape(v) }.join("&")
end
alias_method :plaintext_signature, :secret
def signature_base
[method, url, normalized_params].map{|v| self.class.encode(v) }.join('&')
[method, url, normalized_params].collect { |v| self.class.escape(v) }.join("&")
end
def normalized_params
signature_params.map{|p| p.map{|v| self.class.encode(v) } }.sort.map{|p| p.join('=') }.join('&')
signature_params.collect { |p| p.collect { |v| self.class.escape(v) } }.sort.collect { |p| p.join("=") }.join("&")
end
def signature_params
@ -101,16 +118,15 @@ module SimpleOAuth
end
def url_params
CGI.parse(@uri.query || '').inject([]){|p,(k,vs)| p + vs.sort.map{|v| [k, v] } }
CGI.parse(@uri.query || "").inject([]) { |p, (k, vs)| p + vs.sort.collect { |v| [k, v] } }
end
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
def private_key
OpenSSL::PKey::RSA.new(options[:consumer_secret])
end
end
end

View file

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

View file

@ -1,20 +1,35 @@
# encoding: utf-8
require_relative "lib/simple_oauth/version"
Gem::Specification.new do |gem|
gem.name = 'simple_oauth'
gem.version = '0.1.8'
Gem::Specification.new do |spec|
spec.name = "simple_oauth"
spec.version = SimpleOauth::VERSION
spec.authors = ["Steve Richert", "Erik Berlin"]
spec.email = ["steve.richert@gmail.com", "sferik@gmail.com"]
gem.authors = ["Steve Richert", "Erik Michaels-Ober"]
gem.email = ['steve.richert@gmail.com', 'sferik@gmail.com']
gem.description = 'Simply builds and verifies OAuth headers'
gem.summary = gem.description
gem.homepage = 'https://github.com/laserlemon/simple_oauth'
spec.summary = "Simply builds and verifies OAuth headers"
spec.description = spec.summary
spec.homepage = "https://github.com/laserlemon/simple_oauth"
spec.license = "MIT"
spec.required_ruby_version = ">= 3.0"
gem.add_development_dependency 'rake'
gem.add_development_dependency 'rspec', '~> 2.0'
gem.add_development_dependency 'simplecov'
spec.metadata["allowed_push_host"] = "https://rubygems.org"
gem.files = `git ls-files`.split($\)
gem.test_files = gem.files.grep(/^test\//)
gem.require_paths = ["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"
spec.add_dependency "base64"
end

23
spec/helper.rb Normal file
View file

@ -0,0 +1,23 @@
$LOAD_PATH.unshift File.expand_path("../lib", __dir__)
require "simplecov"
SimpleCov.start do
add_filter "/spec/"
minimum_coverage(100)
end
require "rspec"
require "simple_oauth"
def uri_parser
@uri_parser ||= URI.const_defined?(:Parser) ? URI::DEFAULT_PARSER : URI
end
RSpec.configure do |config|
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
Dir[File.expand_path("support/**/*.rb", __dir__)].each { |f| require f }

View file

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

View file

@ -1,10 +0,0 @@
unless ENV['CI']
require 'simplecov'
SimpleCov.start do
add_filter 'spec'
end
end
require 'simple_oauth'
Dir[File.expand_path('../support/**/*.rb', __FILE__)].each{|f| require f }

View file

@ -1,5 +1,5 @@
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
@rsa_private_key ||= File.read(PRIVATE_KEY_PATH)