swagger_shield 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: a77114331c4b36bc63927cffa6d71b64e3edbc2f93874ecab7855669b54ed89e
4
+ data.tar.gz: 28707bd376642cd675ba0e105d2e9ec930a7ed790241f0dd5c38f802a54afb9e
5
+ SHA512:
6
+ metadata.gz: cbeaf6b524b1cb69077c6d862b7c4ae8a273b141d8b36b5b8e4e35322c3d77a48d6246d801e30651704e2e8582ed8b7feb13490210140b1038621b9764911e05
7
+ data.tar.gz: 185fb9066698ef7f206ad6c1e92ad8732bb6da34be8399b9a2450f885c37c18e94f7427835b470389e9a83777bc61ee3cd233ddcaaf5aeadbac302c1d878217d
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+
11
+ # rspec failure tracking
12
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.4.2
5
+ before_install: gem install bundler -v 1.15.4
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at arielmcaplan@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in swagger_shield.gemspec
6
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 amcaplan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,91 @@
1
+ # SwaggerShield
2
+
3
+ Tired of getting weird errors when users (or your own clients) submit random
4
+ junk to your Rails API? `SwaggerShield` is here to save the day!
5
+
6
+ ## Usage
7
+
8
+ ```ruby
9
+ # You can add to any controller, or to ApplicationController if you want
10
+ # SwaggerShield to protect your whole app.
11
+ class ApplicationController < ActionController::API
12
+ SwaggerShield.protect!(
13
+ self,
14
+
15
+ # replace with the location of your actual swagger YAML file:
16
+ swagger_file: File.join('config', 'swagger.yml'),
17
+
18
+ # add on any valid "if" or "unless" conditionals that can be applied to a
19
+ # Rails before_action
20
+ if: -> { current_user.test_user? },
21
+ unless: -> { params[:skip_swagger_shield] }
22
+ )
23
+ end
24
+ ```
25
+
26
+ Now, everything will work as before, as long as the requests are properly
27
+ formatted. But if requests don't match your Swagger spec:
28
+
29
+ ![You Shall Not Pass!](https://i0.wp.com/gifrific.com/wp-content/uploads/2017/11/you-shall-not-pass-gandalf-lotr.gif)
30
+
31
+ OK, maybe it's not that dramatic. But your client will see an error pointing to
32
+ exactly what they messed up in the request:
33
+
34
+ ```json
35
+ {
36
+ "errors": [
37
+ {
38
+ "status": "422",
39
+ "detail": "The property '#/widget/price' of type string did not match the following type: integer",
40
+ "source": {
41
+ "pointer": "#/widget/price"
42
+ }
43
+ }
44
+ ]
45
+ }
46
+ ```
47
+
48
+ (Only errors in JSON API format are supported, hopefully that'll be updated
49
+ soon...)
50
+
51
+ ## Warning!
52
+
53
+ This project is under active development, being built up in stages as bits
54
+ become necessary for projects that make money. So there's still plenty of stuff
55
+ to implement; use at your own risk.
56
+
57
+ That said, the project will gratefully accept the implementation of new types,
58
+ better error messaging, etc., basically anything you find useful in your own
59
+ work which seems generally applicable. So please [contribute](#development)!
60
+
61
+ ## Installation
62
+
63
+ Add this line to your application's Gemfile:
64
+
65
+ ```ruby
66
+ gem 'swagger_shield'
67
+ ```
68
+
69
+ And then execute:
70
+
71
+ $ bundle
72
+
73
+ Or install it yourself as:
74
+
75
+ $ gem install swagger_shield
76
+
77
+ ## Development
78
+
79
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
80
+
81
+ ## Contributing
82
+
83
+ Bug reports and pull requests are welcome on GitHub at https://github.com/amcaplan/swagger_shield. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
84
+
85
+ ## License
86
+
87
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
88
+
89
+ ## Code of Conduct
90
+
91
+ Everyone interacting in the SwaggerShield project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/amcaplan/swagger_shield/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "swagger_shield"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ require "pry"
11
+ Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,15 @@
1
+ require "swagger_shield/version"
2
+ require "json-schema"
3
+ require "swagger_shield/shield"
4
+ require "swagger_shield/before_action"
5
+
6
+ module SwaggerShield
7
+ class << self
8
+ def protect!(controller, swagger_file:, **opts)
9
+ shield = SwaggerShield::Shield.new(
10
+ YAML.load_file(swagger_file)
11
+ )
12
+ controller.before_action SwaggerShield::BeforeAction.new(shield), **opts
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,32 @@
1
+ module SwaggerShield
2
+ class BeforeAction
3
+ def initialize(shield)
4
+ @shield = shield
5
+ end
6
+
7
+ def before(controller)
8
+ request = controller.request
9
+ params = controller.params
10
+
11
+ errors = shield.validate(
12
+ request.path,
13
+ request.method,
14
+ params.to_unsafe_h
15
+ )
16
+
17
+ unless errors.empty?
18
+ formatted = errors.map { |error|
19
+ {
20
+ status: '422',
21
+ detail: error[:message],
22
+ source: { pointer: error[:fragment] }
23
+ }
24
+ }
25
+ controller.render json: { errors: formatted }, status: :unprocessable_entity
26
+ end
27
+ end
28
+
29
+ private
30
+ attr_reader :shield
31
+ end
32
+ end
@@ -0,0 +1,114 @@
1
+ module SwaggerShield
2
+ class Shield
3
+ def initialize(swagger_spec)
4
+ @swagger_spec = swagger_spec.deep_dup
5
+ load_route_definitions!
6
+ end
7
+
8
+ def validate(path, method, params)
9
+ canonical_path_id = identify_path(path, paths[method])
10
+
11
+ JSON::Validator.fully_validate(
12
+ swagger_spec,
13
+ params,
14
+ fragment: "#/route_lookups/#{method}/#{canonical_path_id}/schema",
15
+ errors_as_objects: true
16
+ ).map { |error|
17
+ {
18
+ message: error[:message].match(/(?<message_part>.*) in schema/)[:message_part],
19
+ fragment: error[:fragment]
20
+ }
21
+ }
22
+ end
23
+
24
+ private
25
+ attr_reader :swagger_spec
26
+
27
+ def paths
28
+ swagger_spec['route_lookups'] ||= Hash.new do |h, k|
29
+ h[k] = {}
30
+ end
31
+ end
32
+
33
+ def load_route_definitions!
34
+ base_path = swagger_spec.fetch('basePath', '')
35
+ swagger_spec['paths'].each do |path, methods|
36
+ path_id_regex = Regexp.new('\A' + base_path + path.gsub(/\{\w+\}/, "[^/]+") + '\z')
37
+ path_info = {
38
+ 'original_path' => path,
39
+ 'regex' => path_id_regex,
40
+ }
41
+
42
+ methods.each do |method, method_info|
43
+ required = []
44
+ properties = {}
45
+
46
+ each_param(method_info['parameters']) do |param|
47
+ required << param['name'] if param['required']
48
+ properties[param['name']] = param_schema_from(param)
49
+ end
50
+
51
+ paths[method.upcase][path_id_regex.hash.to_s] = {
52
+ 'regex' => path_id_regex,
53
+ 'schema' => {
54
+ 'type' => 'object',
55
+ 'required' => required,
56
+ 'properties' => properties
57
+ }
58
+ }
59
+ end
60
+ end
61
+ end
62
+
63
+ def each_param(params)
64
+ (params || []).each do |param|
65
+ if (schema = param['schema'])
66
+ if (ref = schema['$ref'])
67
+ schema = resolve_reference(ref)
68
+ end
69
+ schema['properties'].each do |name, definition|
70
+ yield(
71
+ 'name' => name,
72
+ 'schema' => definition,
73
+ 'required' => schema['required'].include?(name)
74
+ )
75
+ end
76
+ else
77
+ yield param
78
+ end
79
+ end
80
+ end
81
+
82
+ def resolve_reference(ref)
83
+ ref.match(/#\/(?<path>.*)/)[:path].split('/').inject(swagger_spec) do |resolved, branch|
84
+ resolved[branch]
85
+ end
86
+ end
87
+
88
+ def param_schema_from(param)
89
+ param.fetch('schema') {
90
+ baseline = param.except('name', 'in', 'required')
91
+ return baseline unless param['in'] == 'path'
92
+ case param['type']
93
+ when 'integer'
94
+ {
95
+ 'description' => baseline.delete('description'),
96
+ 'anyOf' => [
97
+ baseline,
98
+ {
99
+ 'type' => 'string',
100
+ 'pattern' => '\A[0-9]\z'
101
+ }
102
+ ]
103
+ }
104
+ else
105
+ baseline
106
+ end
107
+ }
108
+ end
109
+
110
+ def identify_path(path, paths)
111
+ paths.find { |_, info| info['regex'] =~ path }.first
112
+ end
113
+ end
114
+ end
@@ -0,0 +1,3 @@
1
+ module SwaggerShield
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,32 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "swagger_shield/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "swagger_shield"
8
+ spec.version = SwaggerShield::VERSION
9
+ spec.authors = ["amcaplan"]
10
+ spec.email = ["arielmcaplan@gmail.com"]
11
+
12
+ spec.summary = %q{Protect your API from malformed requests with Swagger Shield!}
13
+ spec.description = %q{Validates requests to your API against your Swagger spec.}
14
+ spec.homepage = "https://github.com/amcaplan/swagger_shield"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+ spec.bindir = "exe"
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_runtime_dependency "json-schema", "~> 2.5"
25
+
26
+ spec.add_development_dependency "bundler", "~> 1.15"
27
+ spec.add_development_dependency "rake", "~> 10.0"
28
+ spec.add_development_dependency "rspec", "~> 3.0"
29
+ spec.add_development_dependency "rails", "~> 5.0"
30
+ spec.add_development_dependency "rspec-rails", "~> 3.6"
31
+ spec.add_development_dependency "pry", "~> 0"
32
+ end
metadata ADDED
@@ -0,0 +1,157 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: swagger_shield
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - amcaplan
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-11-27 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: json-schema
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '2.5'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.5'
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.15'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.15'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '10.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '10.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '3.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '3.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rails
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '5.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '5.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rspec-rails
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '3.6'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '3.6'
97
+ - !ruby/object:Gem::Dependency
98
+ name: pry
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ description: Validates requests to your API against your Swagger spec.
112
+ email:
113
+ - arielmcaplan@gmail.com
114
+ executables: []
115
+ extensions: []
116
+ extra_rdoc_files: []
117
+ files:
118
+ - ".gitignore"
119
+ - ".rspec"
120
+ - ".travis.yml"
121
+ - CODE_OF_CONDUCT.md
122
+ - Gemfile
123
+ - LICENSE.txt
124
+ - README.md
125
+ - Rakefile
126
+ - bin/console
127
+ - bin/setup
128
+ - lib/swagger_shield.rb
129
+ - lib/swagger_shield/before_action.rb
130
+ - lib/swagger_shield/shield.rb
131
+ - lib/swagger_shield/version.rb
132
+ - swagger_shield.gemspec
133
+ homepage: https://github.com/amcaplan/swagger_shield
134
+ licenses:
135
+ - MIT
136
+ metadata: {}
137
+ post_install_message:
138
+ rdoc_options: []
139
+ require_paths:
140
+ - lib
141
+ required_ruby_version: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - ">="
144
+ - !ruby/object:Gem::Version
145
+ version: '0'
146
+ required_rubygems_version: !ruby/object:Gem::Requirement
147
+ requirements:
148
+ - - ">="
149
+ - !ruby/object:Gem::Version
150
+ version: '0'
151
+ requirements: []
152
+ rubyforge_project:
153
+ rubygems_version: 2.7.1
154
+ signing_key:
155
+ specification_version: 4
156
+ summary: Protect your API from malformed requests with Swagger Shield!
157
+ test_files: []