aserto 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 16cd06af827e4a2522cefc9d6d699d4e7d027ca6780a7d70560e2b6bf1abca24
4
+ data.tar.gz: 0e23e7ccdb687e005b57f80b446dfce4dce244df30c5c7411b4634aa1c2f0e45
5
+ SHA512:
6
+ metadata.gz: 460cd9aa2f3380aff50a1ca15ebb6f052c8de0f34a98ba8fc84a7bc21c740cc1ab51ee954976010fb27a2d757ca42ef4d3853b544c4447282bedbca4405ae910
7
+ data.tar.gz: 0c339a31a7c92c0ace5139f0cd7081f06e9ea77ad5afc43d21e62d758ad36187ebbad4d0901207b6b03ed09982a99b93f0535b3bd779fb79b93f1d1f0004f8c0
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,217 @@
1
+ # Ruby Rack Middleware for Aserto
2
+
3
+ `Aserto::Authorization` is a middleware that allows Ruby applications to use Aserto as the Authorization provider.
4
+
5
+ ## Prerequisites
6
+ * [Ruby](https://www.ruby-lang.org/en/downloads/) 2.7 or newer.
7
+ * An [Aserto](https://console.aserto.com) account.
8
+
9
+ ## Installation
10
+ Add to your application Gemfile:
11
+
12
+ ```ruby
13
+ gem "aserto"
14
+ ```
15
+
16
+ And then execute:
17
+ ```bash
18
+ bundle install
19
+ ```
20
+ Or install it yourself as:
21
+ ```bash
22
+ gem install aserto
23
+ ```
24
+
25
+ ## Configuration
26
+ The following configuration settings are required for the authorization middleware:
27
+ - policy_id
28
+ - tenant_id
29
+ - authorizer_api_key
30
+ - policy_root
31
+
32
+ These settings can be retrieved from the [Policy Settings](https://console.aserto.com/ui/policies) page of your Aserto account.
33
+
34
+ The middleware accepts the following optional parameters:
35
+
36
+ | Parameter name | Default value | Description |
37
+ | -------------- | ------------- | ----------- |
38
+ | enabled | true | Enables or disables Aserto Authorization |
39
+ | service_url | `"authorizer.prod.aserto.com:8443"` | Sets the URL for the authorizer endpoint. |
40
+ | decision | `"allowed"` | The decision that will be used by the middleware when creating an authorizer request. |
41
+ | logger | `STDOUT` | The logger to be used by the middleware. |
42
+ | identity_mapping | `{ type: :none }` | The strategy for retrieveing the identity, possible values: `:jwt, :sub, :none` |
43
+ | disabled_for | `[{}]` | Which path and actions to skip the authorization for. |
44
+ | on_unauthorized | `-> { return [403, {}, ["Forbidden"]] }`| A lambda that is executed when the authorization fails. |
45
+
46
+ ## Identity
47
+ To determine the identity of the user, the middleware can be configured to use a JWT token or a claim using the `identity_mapping` config.
48
+ ```ruby
49
+ # configure the middleware to use a JWT token form the `my-auth-header` header.
50
+ config.identity_mapping = {
51
+ type: :jwt,
52
+ from: "my-auth-header",
53
+ }
54
+ ```
55
+ ```ruby
56
+ # configure the middleware to use a claim from the JWT token.
57
+ # This will decode the JWT token and extract the `sub` field from payload.
58
+ config.identity_mapping = {
59
+ type: :sub,
60
+ from: :sub,
61
+ }
62
+ ```
63
+
64
+ The whole identity resolution can be overwritten by providing a custom function.
65
+ ```ruby
66
+ # config/initializers/aserto.rb
67
+
68
+ # needs to return a hash with the identity having `type` and `identity` keys.
69
+ # supported types: `:jwt, :sub, :none`
70
+ Aserto.with_identity_mapper do |request|
71
+ {
72
+ type: :sub,
73
+ identity: "my custom identity",
74
+ }
75
+ end
76
+ ```
77
+
78
+ ## URL path to policy mapping
79
+ By default, when computing the policy path, the middleware:
80
+ * converts all slashes to dots
81
+ * converts any character that is not alpha, digit, dot or underscore to underscore
82
+ * converts uppercase characters in the URL path to lowercases
83
+
84
+ This behavior can be overwritten by providing a custom function:
85
+
86
+ ```ruby
87
+ # config/initializers/aserto.rb
88
+
89
+ # must return a String
90
+ Aserto.with_policy_path_mapper do |policy_root, request|
91
+ method = request.request_method
92
+ path = request.path_info
93
+
94
+ "custom: #{policy_root}.#{method}.#{path}"
95
+ end
96
+ ```
97
+
98
+ ## Resource
99
+ A resource can be any structured data that the authorization policy uses to evaluate decisions. By default, middleware do not include a resource in authorization calls.
100
+
101
+ This behavior can be overwritten by providing a custom function:
102
+
103
+ ```ruby
104
+ # config/initializers/aserto.rb
105
+
106
+ # must return a Hash
107
+ Aserto.with_resource_mapper do |request|
108
+ { resource: request.path_info }
109
+ end
110
+ ```
111
+
112
+ ## Disable authorization for specific paths
113
+
114
+ The middleware exposes a `disable_for` configuration option that
115
+ accepts an array of hashes with the following keys:
116
+ - path - the path to disable authorization for
117
+ - actions - an array of actions to disable authorization for
118
+
119
+ ### Rails
120
+ You can find the paths and actions using `bundle exec rails routes`
121
+ ```bash
122
+ bundle exec rails routes
123
+
124
+ Prefix Verb URI Pattern Controller#Action
125
+
126
+ api_v1_users GET /api/users(.:format) api/v1/users#index {:format=>:json}
127
+ POST /api/users(.:format) api/v1/users#create {:format=>:json}
128
+ api_v1_user GET /api/users/:id(.:format) api/v1/users#show {:format=>:json}
129
+ ```
130
+ ```ruby
131
+ # disables get user by id
132
+ config.disabled_for = [
133
+ {
134
+ path: '/api/users/:id'
135
+ actions: [:GET]
136
+ }
137
+ ]
138
+ ```
139
+ ## Examples
140
+
141
+ ### Rails
142
+ ```ruby
143
+ # config/initializers/aserto.rb
144
+
145
+ Rails.application.config.middleware.use Aserto::Authorization do |config|
146
+ config.enabled = true
147
+ config.policy_id = "my-policy-id"
148
+ config.tenant_id = "my-tenant-id"
149
+ config.authorizer_api_key = Rails.application.credentials.aserto[:authorizer_api_key]
150
+ config.policy_root = "peoplefinder"
151
+ config.service_url = "authorizer.prod.aserto.com:8443"
152
+ config.decision = "allowed"
153
+ config.logger = Rails.logger
154
+ config.identity_mapping = {
155
+ type: :sub,
156
+ from: :sub
157
+ }
158
+ config.disabled_for = [
159
+ {
160
+ path: "/api/users",
161
+ actions: %i[GET POST]
162
+ },
163
+ {
164
+ path: "/api/authentication",
165
+ actions: %i[POST]
166
+ }
167
+ ]
168
+ config.on_unauthorized = lambda do |env|
169
+ puts env
170
+ return [403, {}, ["Forbidden"]]
171
+ end
172
+ end
173
+ ```
174
+
175
+ ### Sinatra
176
+ ```ruby
177
+ # server.rb
178
+
179
+ # aserto middleware
180
+ use Aserto::Authorization do |config|
181
+ config.enabled = true
182
+ config.policy_id = "my-policy-id"
183
+ config.tenant_id = "my-tenant-id"
184
+ config.authorizer_api_key = ENV['authorizer_api_key']
185
+ config.policy_root = "peoplefinder"
186
+ config.service_url = "authorizer.prod.aserto.com:8443"
187
+ config.decision = "allowed"
188
+ config.disabled_for = [
189
+ {
190
+ path: "/api/users/:id",
191
+ actions: %i[GET]
192
+ },
193
+ {
194
+ path: "/",
195
+ actions: %i[GET]
196
+ }
197
+ ]
198
+
199
+ end
200
+ ```
201
+ ## Development
202
+ Prerequisites:
203
+
204
+ - go >= 1.17 to run mage
205
+ - Ruby >= 2.7.0 to run the code
206
+
207
+
208
+ Run `bundle install` to install dependencies. Then, run `bundle exec rspec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
209
+
210
+
211
+ ## Contributing
212
+
213
+ Bug reports and pull requests are welcome on GitHub at https://github.com/aserto-dev/aserto-ruby. This project is intended to be a safe, welcoming space for collaboration.
214
+
215
+ ## License
216
+
217
+ The gem is available as open source under the terms of the [Apache-2.0 License](https://www.apache.org/licenses/LICENSE-2.0).
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.0.1
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "aserto-grpc-authz"
4
+
5
+ module Aserto
6
+ class AuthClient
7
+ attr_reader :client, :config, :request
8
+
9
+ INTERNAL_MAPPING = {
10
+ unknown: Aserto::Api::V1::IdentityType::IDENTITY_TYPE_UNKNOWN,
11
+ none: Aserto::Api::V1::IdentityType::IDENTITY_TYPE_NONE,
12
+ sub: Aserto::Api::V1::IdentityType::IDENTITY_TYPE_SUB,
13
+ jwt: Aserto::Api::V1::IdentityType::IDENTITY_TYPE_JWT
14
+ }.freeze
15
+
16
+ private_constant :INTERNAL_MAPPING
17
+
18
+ def initialize(request)
19
+ @request = request
20
+ @config = Aserto.config
21
+ @client = Aserto::Authorizer::Authorizer::V1::Authorizer::Stub.new(
22
+ config.service_url,
23
+ GRPC::Core::ChannelCredentials.new
24
+ )
25
+ end
26
+
27
+ def is
28
+ is_request = Aserto::Authorizer::Authorizer::V1::IsRequest.new(
29
+ {
30
+ policy_context: policy_context,
31
+ identity_context: identity_context,
32
+ resource_context: resource_context
33
+ }
34
+ )
35
+
36
+ begin
37
+ response = client.is(
38
+ is_request, { metadata: {
39
+ "aserto-tenant-id": config.tenant_id,
40
+ authorization: "basic #{config.authorizer_api_key}"
41
+ } }
42
+ )
43
+ rescue GRPC::BadStatus => e
44
+ Aserto.logger.error(e.inspect)
45
+ false
46
+ end
47
+ response.to_h.dig(:decisions, 0, :is) || false
48
+ end
49
+
50
+ private
51
+
52
+ def policy_context
53
+ path = Aserto::PolicyPathMapper.execute(config.policy_root, request)
54
+ Aserto.logger.debug "aserto authorizing: #{path}"
55
+
56
+ Aserto::Api::V1::PolicyContext.new(
57
+ {
58
+ id: config.policy_id,
59
+ path: path,
60
+ decisions: [config.decision]
61
+ }
62
+ )
63
+ end
64
+
65
+ def identity_context
66
+ identity = Aserto::IdentityMapper.execute(request)
67
+ Aserto::Api::V1::IdentityContext.new(
68
+ {
69
+ identity: identity.fetch(:identity, "null"),
70
+ type: INTERNAL_MAPPING[identity.fetch(:type, :unknown)]
71
+ }
72
+ )
73
+ end
74
+
75
+ def resource_context
76
+ ResourceMapper.execute(request)
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aserto
4
+ class Authorization
5
+ attr_reader :config
6
+
7
+ def initialize(app, options = {})
8
+ @app = app
9
+ @config = Aserto.config(options)
10
+ yield @config if block_given?
11
+ end
12
+
13
+ def call(env)
14
+ request = Rack::Request.new(env)
15
+
16
+ allowed = if enabled?(request)
17
+ Aserto.logger.debug("Aserto authorization enabled")
18
+ client = Aserto::AuthClient.new(request)
19
+ client.is
20
+ else
21
+ Aserto.logger.debug("Aserto authorization not enabled")
22
+ true
23
+ end
24
+
25
+ Aserto.logger.debug("Aserto authorization result -> allowed: #{allowed}")
26
+ return @app.call env if allowed
27
+
28
+ config.on_unauthorized.call(env)
29
+ end
30
+
31
+ private
32
+
33
+ def route(request)
34
+ if defined? ::Rails
35
+ require "aserto/rails/utils"
36
+
37
+ Aserto::Rails::Utils.route(request)
38
+ elsif defined? ::Sinatra
39
+ require "aserto/sinatra/utils"
40
+ Aserto::Sinatra::Utils.route(request)
41
+ end
42
+ end
43
+
44
+ def enabled?(request)
45
+ route_info = route(request)
46
+ if route_info
47
+ config.enabled && config.disabled_for.none? do |hash|
48
+ hash[:path] == route_info[:path] && hash[:actions].include?(route_info[:action])
49
+ end
50
+ else
51
+ config.enabled
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "logger"
4
+
5
+ module Aserto
6
+ class Config
7
+ class << self
8
+ def default_logger
9
+ logger = Logger.new($stdout)
10
+ logger.progname = "aserto"
11
+ logger
12
+ end
13
+
14
+ def validate!
15
+ error_message = ""
16
+ REQUIRED_OPTIONS.each do |option|
17
+ if !instance_variable_defined?(:"@#{option}") ||
18
+ instance_variable_get(:"@#{option}") == ""
19
+ error_message += "Missing required option: #{option}\n"
20
+ end
21
+ end
22
+ raise error_message if error_message != ""
23
+ end
24
+ end
25
+
26
+ DEFAULT_ATTRS = {
27
+ authorizer_api_key: "",
28
+ service_url: "authorizer.prod.aserto.com:8443",
29
+ decision: "allowed",
30
+ disabled_for: [{}],
31
+ enabled: true,
32
+ identity_mapping: {
33
+ type: :none
34
+ },
35
+ logger: Config.default_logger,
36
+ policy_id: "",
37
+ policy_root: "",
38
+ tenant_id: "",
39
+ on_unauthorized: lambda do |_env|
40
+ return [403, {}, ["Forbidden"]]
41
+ end
42
+ }.freeze
43
+
44
+ OPTIONS = DEFAULT_ATTRS.keys.freeze
45
+
46
+ REQUIRED_OPTIONS = OPTIONS - %i[
47
+ service_url decision disabled_for identity_mapping enabled logger
48
+ ].freeze
49
+
50
+ private_constant :DEFAULT_ATTRS, :OPTIONS, :REQUIRED_OPTIONS
51
+
52
+ attr_accessor(*OPTIONS)
53
+
54
+ def initialize(options)
55
+ OPTIONS.each do |key|
56
+ send("#{key}=", options[key] || DEFAULT_ATTRS[key])
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aserto
4
+ module IdentityMapper
5
+ module Base
6
+ def extract_data(token)
7
+ require "jwt"
8
+
9
+ ((JWT.decode token, nil, false) || [])[0]
10
+ rescue StandardError
11
+ Aserto.logger.error("Invalid auth token")
12
+ nil
13
+ end
14
+
15
+ def valid?(token)
16
+ require "jwt"
17
+
18
+ return false unless token
19
+
20
+ begin
21
+ JWT.decode token, nil, false
22
+ true
23
+ rescue StandardError
24
+ false
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aserto
4
+ module IdentityMapper
5
+ module Jwt
6
+ extend Aserto::IdentityMapper::Base
7
+
8
+ class << self
9
+ def execute(request)
10
+ config = Aserto.config
11
+ auth_token = request.get_header(
12
+ config.identity_mapping[:from] || "HTTP_AUTHORIZATION"
13
+ )
14
+ return {} unless valid?(auth_token)
15
+
16
+ {
17
+ type: :jwt,
18
+ identity: auth_token
19
+ }
20
+ end
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aserto
4
+ module IdentityMapper
5
+ module None
6
+ class << self
7
+ def execute(_request)
8
+ {
9
+ type: :none,
10
+ identity: "null"
11
+ }
12
+ end
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aserto
4
+ module IdentityMapper
5
+ module Sub
6
+ extend Aserto::IdentityMapper::Base
7
+
8
+ class << self
9
+ def execute(request)
10
+ config = Aserto.config
11
+ auth_token = request.get_header("HTTP_AUTHORIZATION")
12
+ return {} unless auth_token
13
+
14
+ auth_token = auth_token.split.last if auth_token
15
+ data = extract_data(auth_token) || {}
16
+
17
+ {
18
+ type: :sub,
19
+ identity: data[config.identity_mapping[:from].to_s]
20
+ }
21
+ end
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "identity_mapper/base"
4
+ require_relative "identity_mapper/none"
5
+ require_relative "identity_mapper/sub"
6
+ require_relative "identity_mapper/jwt"
7
+
8
+ module Aserto
9
+ module IdentityMapper
10
+ STRATEGY = {
11
+ none: Aserto::IdentityMapper::None,
12
+ sub: Aserto::IdentityMapper::Sub,
13
+ jwt: Aserto::IdentityMapper::Jwt
14
+ }.freeze
15
+
16
+ class << self
17
+ def execute(request)
18
+ STRATEGY[
19
+ Aserto.config.identity_mapping[:type].to_sym || :none
20
+ ].execute(request)
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aserto
4
+ module PolicyPathMapper
5
+ class << self
6
+ def execute(policy_root, request)
7
+ method = request.request_method
8
+ path = request.path_info
9
+
10
+ if defined? ::Rails
11
+ require "aserto/rails/utils"
12
+
13
+ route = Aserto::Rails::Utils.route(request)
14
+ path = route[:path] if route
15
+ end
16
+
17
+ if defined? ::Sinatra
18
+ require "aserto/sinatra/utils"
19
+
20
+ route = Aserto::Sinatra::Utils.route(request)
21
+ path = route[:path] if route
22
+ end
23
+
24
+ policy_path = +"#{policy_root}.#{method}.#{path}"
25
+ policy_path.tr!("/", ".")
26
+ policy_path.gsub!("..", ".")
27
+ policy_path.gsub!(":", "__")
28
+ policy_path.gsub!(/[^a-zA-Z0-9._]/, "_")
29
+ policy_path.chomp!(".")
30
+ policy_path
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aserto
4
+ module Rails
5
+ module Utils
6
+ class << self
7
+ # Finds the Rails route for the given path.
8
+ # If the route is not found, returns nil.
9
+ # If the route is found, returns a hash with the following keys:
10
+ # :path
11
+ # :action
12
+ #
13
+ # Eg:
14
+ # route("/api/v1/users/1") => {
15
+ # :action => :GET,
16
+ # :path => "/api/v1/users/:id" }
17
+ def route(request)
18
+ return unless defined? ::Rails
19
+
20
+ path = request.path_info
21
+ route = ::Rails.application.routes.routes.to_a.find do |cr|
22
+ cr.path.to_regexp.match?(path)
23
+ end
24
+
25
+ return unless route
26
+
27
+ {
28
+ path: route.path.spec.to_s.sub("(.:format)", ""),
29
+ action: request.request_method.to_sym
30
+ }
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aserto
4
+ module ResourceMapper
5
+ class << self
6
+ def execute(_request)
7
+ {}
8
+ end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aserto
4
+ module Sinatra
5
+ module Utils
6
+ class << self
7
+ # Finds the Sinatra route for the given path.
8
+ # If the route is not found, returns nil.
9
+ # If the route is found, returns a hash with the following keys:
10
+ # :path
11
+ # :action
12
+ #
13
+ # Eg:
14
+ # route("/api/v1/users/1") => {
15
+ # :action => :GET,
16
+ # :path => "/api/v1/users/:id" }
17
+ def route(request)
18
+ return unless defined? ::Sinatra
19
+
20
+ path = request.path_info
21
+ routes = ::Sinatra::Application.routes[request.request_method].map do |route|
22
+ route.flatten.first
23
+ end
24
+ route = routes.find do |r|
25
+ r.match(path)
26
+ end
27
+
28
+ return unless route
29
+
30
+ substitutions = route.match(path).named_captures
31
+ unless substitutions&.any?
32
+ return {
33
+ path: route.to_s,
34
+ action: request.request_method.to_sym
35
+ }
36
+ end
37
+
38
+ substitutions.each_pair do |sub, val|
39
+ path.sub!(val, ":#{sub}")
40
+ end
41
+ {
42
+ path: path,
43
+ action: request.request_method.to_sym
44
+ }
45
+ end
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aserto
4
+ VERSION = File.read(
5
+ File.join(__dir__, "..", "..", "VERSION")
6
+ ).chomp
7
+ end
data/lib/aserto.rb ADDED
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rack"
4
+ require "aserto-grpc-authz"
5
+
6
+ require_relative "aserto/version"
7
+ require_relative "aserto/config"
8
+ require_relative "aserto/authorization"
9
+ require_relative "aserto/policy_path_mapper"
10
+ require_relative "aserto/identity_mapper"
11
+ require_relative "aserto/resource_mapper"
12
+ require_relative "aserto/auth_client"
13
+
14
+ module Aserto
15
+ class << self
16
+ def config(options = {})
17
+ @config ||= Config.new(options)
18
+ end
19
+
20
+ def logger
21
+ config.logger
22
+ end
23
+
24
+ def configure
25
+ yield config
26
+ end
27
+
28
+ # Allows the initializer to provide a custom
29
+ # implementation for the PolicyPathMapper
30
+ #
31
+ # Aserto.with_policy_path_mapper do |policy_root, request|
32
+ # method = request.request_method
33
+ # path = request.path_info
34
+ # "custom => #{policy_root}.#{method}.#{path}"
35
+ # end
36
+ def with_policy_path_mapper
37
+ Aserto::PolicyPathMapper.class_eval do |klass|
38
+ klass.define_singleton_method(:execute) do |policy_root, request|
39
+ yield(policy_root, request) if block_given?
40
+ end
41
+ end
42
+ end
43
+
44
+ # Allows the initializer to provide a custom
45
+ # implementation for the ResourceMapper
46
+ #
47
+ # Aserto.with_resource_mapper do |request|
48
+ # { resource: request.path_info }
49
+ # end
50
+ def with_resource_mapper
51
+ Aserto::ResourceMapper.class_eval do |klass|
52
+ klass.define_singleton_method(:execute) do |request|
53
+ yield(request) if block_given?
54
+ end
55
+ end
56
+ end
57
+
58
+ # Allows the initializer to provide a custom
59
+ # implementation for the IdentityMapper
60
+ #
61
+ # Aserto.with_identity_mapper do |request|
62
+ # {
63
+ # sub: "test",
64
+ # type: Aserto::Api::V1::IdentityType::IDENTITY_TYPE_NONE
65
+ # }
66
+ # end
67
+ def with_identity_mapper
68
+ Aserto::IdentityMapper.class_eval do |klass|
69
+ klass.define_singleton_method(:execute) do |request|
70
+ yield(request) if block_given?
71
+ end
72
+ end
73
+ end
74
+ end
75
+ end
metadata ADDED
@@ -0,0 +1,197 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: aserto
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Aserto
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2022-07-19 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: aserto-grpc-authz
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.0.6
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.0.6
27
+ - !ruby/object:Gem::Dependency
28
+ name: jwt
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '2.4'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '2.4'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rack
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '2.0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '2.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: bundler
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: 1.15.0
62
+ - - "<"
63
+ - !ruby/object:Gem::Version
64
+ version: '3.0'
65
+ type: :development
66
+ prerelease: false
67
+ version_requirements: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: 1.15.0
72
+ - - "<"
73
+ - !ruby/object:Gem::Version
74
+ version: '3.0'
75
+ - !ruby/object:Gem::Dependency
76
+ name: codecov
77
+ requirement: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - "~>"
80
+ - !ruby/object:Gem::Version
81
+ version: '0.6'
82
+ type: :development
83
+ prerelease: false
84
+ version_requirements: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - "~>"
87
+ - !ruby/object:Gem::Version
88
+ version: '0.6'
89
+ - !ruby/object:Gem::Dependency
90
+ name: grpc_mock
91
+ requirement: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - "~>"
94
+ - !ruby/object:Gem::Version
95
+ version: '0.4'
96
+ type: :development
97
+ prerelease: false
98
+ version_requirements: !ruby/object:Gem::Requirement
99
+ requirements:
100
+ - - "~>"
101
+ - !ruby/object:Gem::Version
102
+ version: '0.4'
103
+ - !ruby/object:Gem::Dependency
104
+ name: rspec
105
+ requirement: !ruby/object:Gem::Requirement
106
+ requirements:
107
+ - - "~>"
108
+ - !ruby/object:Gem::Version
109
+ version: '3.0'
110
+ type: :development
111
+ prerelease: false
112
+ version_requirements: !ruby/object:Gem::Requirement
113
+ requirements:
114
+ - - "~>"
115
+ - !ruby/object:Gem::Version
116
+ version: '3.0'
117
+ - !ruby/object:Gem::Dependency
118
+ name: rubocop-performance
119
+ requirement: !ruby/object:Gem::Requirement
120
+ requirements:
121
+ - - "~>"
122
+ - !ruby/object:Gem::Version
123
+ version: '1.14'
124
+ type: :development
125
+ prerelease: false
126
+ version_requirements: !ruby/object:Gem::Requirement
127
+ requirements:
128
+ - - "~>"
129
+ - !ruby/object:Gem::Version
130
+ version: '1.14'
131
+ - !ruby/object:Gem::Dependency
132
+ name: rubocop-rspec
133
+ requirement: !ruby/object:Gem::Requirement
134
+ requirements:
135
+ - - "~>"
136
+ - !ruby/object:Gem::Version
137
+ version: '2.11'
138
+ type: :development
139
+ prerelease: false
140
+ version_requirements: !ruby/object:Gem::Requirement
141
+ requirements:
142
+ - - "~>"
143
+ - !ruby/object:Gem::Version
144
+ version: '2.11'
145
+ description: Aserto Middleware
146
+ email:
147
+ - aserto@aserto.com
148
+ executables: []
149
+ extensions: []
150
+ extra_rdoc_files: []
151
+ files:
152
+ - LICENSE
153
+ - README.md
154
+ - VERSION
155
+ - lib/aserto.rb
156
+ - lib/aserto/auth_client.rb
157
+ - lib/aserto/authorization.rb
158
+ - lib/aserto/config.rb
159
+ - lib/aserto/identity_mapper.rb
160
+ - lib/aserto/identity_mapper/base.rb
161
+ - lib/aserto/identity_mapper/jwt.rb
162
+ - lib/aserto/identity_mapper/none.rb
163
+ - lib/aserto/identity_mapper/sub.rb
164
+ - lib/aserto/policy_path_mapper.rb
165
+ - lib/aserto/rails/utils.rb
166
+ - lib/aserto/resource_mapper.rb
167
+ - lib/aserto/sinatra/utils.rb
168
+ - lib/aserto/version.rb
169
+ homepage: https://www.aserto.com
170
+ licenses:
171
+ - Apache-2.0
172
+ metadata:
173
+ allowed_push_host: https://rubygems.org
174
+ homepage_uri: https://www.aserto.com
175
+ source_code_uri: https://github.com/aserto-dev/aserto-ruby
176
+ changelog_uri: https://github.com/aserto-dev/aserto-ruby
177
+ rubygems_mfa_required: 'true'
178
+ post_install_message:
179
+ rdoc_options: []
180
+ require_paths:
181
+ - lib
182
+ required_ruby_version: !ruby/object:Gem::Requirement
183
+ requirements:
184
+ - - ">="
185
+ - !ruby/object:Gem::Version
186
+ version: 2.7.0
187
+ required_rubygems_version: !ruby/object:Gem::Requirement
188
+ requirements:
189
+ - - ">="
190
+ - !ruby/object:Gem::Version
191
+ version: '0'
192
+ requirements: []
193
+ rubygems_version: 3.3.7
194
+ signing_key:
195
+ specification_version: 4
196
+ summary: Aserto Middleware
197
+ test_files: []