cerbos 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (45) hide show
  1. checksums.yaml +7 -0
  2. data/.yardopts +9 -0
  3. data/CHANGELOG.md +9 -0
  4. data/LICENSE.txt +190 -0
  5. data/README.md +67 -0
  6. data/cerbos.gemspec +36 -0
  7. data/lib/cerbos/client.rb +188 -0
  8. data/lib/cerbos/error.rb +112 -0
  9. data/lib/cerbos/input/attributes.rb +29 -0
  10. data/lib/cerbos/input/aux_data.rb +26 -0
  11. data/lib/cerbos/input/jwt.rb +38 -0
  12. data/lib/cerbos/input/principal.rb +63 -0
  13. data/lib/cerbos/input/resource.rb +63 -0
  14. data/lib/cerbos/input/resource_check.rb +35 -0
  15. data/lib/cerbos/input/resource_query.rb +55 -0
  16. data/lib/cerbos/input.rb +36 -0
  17. data/lib/cerbos/mutual_tls.rb +33 -0
  18. data/lib/cerbos/output/check_resources.rb +226 -0
  19. data/lib/cerbos/output/plan_resources.rb +149 -0
  20. data/lib/cerbos/output/server_info.rb +38 -0
  21. data/lib/cerbos/output.rb +37 -0
  22. data/lib/cerbos/protobuf/cerbos/audit/v1/audit_pb.rb +48 -0
  23. data/lib/cerbos/protobuf/cerbos/effect/v1/effect_pb.rb +23 -0
  24. data/lib/cerbos/protobuf/cerbos/engine/v1/engine_pb.rb +166 -0
  25. data/lib/cerbos/protobuf/cerbos/policy/v1/policy_pb.rb +247 -0
  26. data/lib/cerbos/protobuf/cerbos/request/v1/request_pb.rb +178 -0
  27. data/lib/cerbos/protobuf/cerbos/response/v1/response_pb.rb +230 -0
  28. data/lib/cerbos/protobuf/cerbos/schema/v1/schema_pb.rb +37 -0
  29. data/lib/cerbos/protobuf/cerbos/svc/v1/svc_pb.rb +21 -0
  30. data/lib/cerbos/protobuf/cerbos/svc/v1/svc_services_pb.rb +73 -0
  31. data/lib/cerbos/protobuf/cerbos/telemetry/v1/telemetry_pb.rb +99 -0
  32. data/lib/cerbos/protobuf/google/api/annotations_pb.rb +17 -0
  33. data/lib/cerbos/protobuf/google/api/expr/v1alpha1/checked_pb.rb +117 -0
  34. data/lib/cerbos/protobuf/google/api/expr/v1alpha1/syntax_pb.rb +113 -0
  35. data/lib/cerbos/protobuf/google/api/field_behavior_pb.rb +27 -0
  36. data/lib/cerbos/protobuf/google/api/http_pb.rb +39 -0
  37. data/lib/cerbos/protobuf/protoc-gen-openapiv2/options/annotations_pb.rb +21 -0
  38. data/lib/cerbos/protobuf/protoc-gen-openapiv2/options/openapiv2_pb.rb +200 -0
  39. data/lib/cerbos/protobuf/validate/validate_pb.rb +293 -0
  40. data/lib/cerbos/protobuf.rb +9 -0
  41. data/lib/cerbos/tls.rb +24 -0
  42. data/lib/cerbos/version.rb +6 -0
  43. data/lib/cerbos.rb +22 -0
  44. data/yard_extensions.rb +33 -0
  45. metadata +107 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: f52b0341101110bf6a44cee73e5199fd11651de535744cffcb3da7e1fb118b56
4
+ data.tar.gz: 7a304a44d0525bd24a8c4c21fcdd41dbde1fb6643fd265b44913e195ba6a32ff
5
+ SHA512:
6
+ metadata.gz: 10f7d4f801f0f4f377ecfdfb72bc37d55a71e88f14afa20ff73d17f8d613e2c53f3ead87520cd05b8924da8e422b8838c09546e8b7982399021a267a8511786f
7
+ data.tar.gz: 42011ce4bea4f14fe770ca7f70c7be27c2c40a644429fc5cad9bee1a2b1ac86f638d07052dee4337f68c02d6a82071711e86f3006f0c6f6bcdd021ed7602b7e5
data/.yardopts ADDED
@@ -0,0 +1,9 @@
1
+ --exclude lib/cerbos/protobuf
2
+ --load yard_extensions.rb
3
+ --markup markdown
4
+ --markup-provider commonmarker
5
+ --no-private
6
+ -
7
+ CHANGELOG.md
8
+ LICENSE.txt
9
+ README.md
data/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ ## [Unreleased]
2
+ No notable changes.
3
+
4
+ ## [0.1.0] - 2022-05-12
5
+ ### Added
6
+ - Initial implementation of `Cerbos::Client` ([#2](https://github.com/cerbos/cerbos-sdk-ruby/pull/2))
7
+
8
+ [Unreleased]: https://github.com/cerbos/cerbos-sdk-ruby/compare/v0.1.0...HEAD
9
+ [0.1.0]: https://github.com/cerbos/cerbos-sdk-ruby/compare/4481009e9dec2e1e6a2df8ea2f828690ceabbefc...v0.1.0
data/LICENSE.txt ADDED
@@ -0,0 +1,190 @@
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
+ Copyright 2022 Zenauth Ltd
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,67 @@
1
+ # Cerbos Ruby SDK
2
+
3
+ [![Gem](https://img.shields.io/gem/v/cerbos?style=flat-square)](https://rubygems.org/gems/cerbos)
4
+  
5
+ [![Documentation](https://img.shields.io/badge/yard-docs-blue?style=flat-square)](https://www.rubydoc.info/gems/cerbos)
6
+
7
+ [Cerbos](https://cerbos.dev) helps you super-charge your authorization implementation by writing context-aware access control policies for your application resources.
8
+ Author access rules using an intuitive YAML configuration language, use your Git-ops infrastructure to test and deploy them, and make simple API requests to the Cerbos policy decision point (PDP) server to evaluate the policies and make dynamic access decisions.
9
+
10
+ The Cerbos Ruby SDK makes it easy to interact with the Cerbos PDP from your Ruby applications.
11
+
12
+ ## Prerequisites
13
+
14
+ - Cerbos 0.16+
15
+ - Ruby 2.7+
16
+
17
+ ## Installation
18
+
19
+ Install the gem and add it to your application's Gemfile by running
20
+
21
+ ```console
22
+ $ bundle add cerbos
23
+ ```
24
+
25
+ If you're not using Bundler to manage dependencies, install the gem by running
26
+
27
+ ```console
28
+ $ gem install cerbos
29
+ ```
30
+
31
+ ### Note for M1 Mac users
32
+
33
+ Unfortunately, the `grpc` gem currently ships a `universal-darwin` native gem which doesn't actually work on `arm64-darwin` platforms ([grpc/grpc#29100](https://github.com/grpc/grpc/issues/29100)).
34
+ If you install the precompiled gem on an M1 Mac, you'll get a `LoadError` including the message "incompatible architecture (have 'x86_64', need 'arm64e')" when you attempt to load the `cerbos` gem.
35
+
36
+ Until that issue is resolved, you can work around it by compiling native extensions from source.
37
+ Configure Bundler to do so by running
38
+
39
+ ```console
40
+ $ bundle config set --local force_ruby_platform true
41
+ ```
42
+
43
+ ## Example usage
44
+
45
+ ```ruby
46
+ client = Cerbos::Client.new("localhost:3593", tls: false)
47
+
48
+ decision = client.check_resource(
49
+ principal: {
50
+ id: "user@example.com",
51
+ roles: ["USER"],
52
+ },
53
+ resource: {
54
+ kind: "document",
55
+ id: "1",
56
+ attributes: {
57
+ owner: "author@example.com"
58
+ }
59
+ },
60
+ actions: ["view", "edit"]
61
+ )
62
+
63
+ decision.allow?("view") # => true
64
+ decision.allow?("edit") # => false
65
+ ```
66
+
67
+ For more details, [see the `Client` documentation](https://www.rubydoc.info/gems/cerbos/Cerbos/Client).
data/cerbos.gemspec ADDED
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/cerbos/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "cerbos"
7
+ spec.version = Cerbos::VERSION
8
+ spec.summary = "Client library for authorization via Cerbos"
9
+ spec.description = "Perform authorization in Ruby applications by interacting with the Cerbos policy decision point."
10
+ spec.authors = ["Cerbos"]
11
+ spec.email = ["help@cerbos.dev"]
12
+ spec.license = "Apache-2.0"
13
+
14
+ spec.homepage = "https://github.com/cerbos/cerbos-sdk-ruby"
15
+ spec.metadata["bug_tracker_uri"] = "#{spec.homepage}/issues"
16
+ spec.metadata["changelog_uri"] = "#{spec.homepage}/blob/main/CHANGELOG.md"
17
+ spec.metadata["documentation_uri"] = "https://www.rubydoc.info/gems/#{spec.name}/#{spec.version}"
18
+ spec.metadata["homepage_uri"] = spec.homepage
19
+ spec.metadata["source_code_uri"] = spec.homepage
20
+
21
+ spec.metadata["rubygems_mfa_required"] = "true"
22
+
23
+ spec.require_paths = ["lib"]
24
+ spec.files = Dir[
25
+ "lib/**/*.rb",
26
+ ".yardopts",
27
+ "cerbos.gemspec",
28
+ "CHANGELOG.md",
29
+ "LICENSE.txt",
30
+ "README.md",
31
+ "yard_extensions.rb"
32
+ ]
33
+
34
+ spec.required_ruby_version = ">= 2.7.0"
35
+ spec.add_dependency "grpc", "~> 1.45"
36
+ end
@@ -0,0 +1,188 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cerbos
4
+ # A client for interacting with the Cerbos policy decision point (PDP) server over gRPC.
5
+ #
6
+ # An instance of the client may be shared between threads.
7
+ # However, due to [an issue in the underlying `grpc` gem](https://github.com/grpc/grpc/issues/8798), it's not possible to use the client before and after process forks.
8
+ # If your application runs on a forking webserver (for example, Puma in clustered mode), then you'll need to ensure that you only create client instances in the child (worker) processes.
9
+ class Client
10
+ # Create a client for interacting with the Cerbos PDP server over gRPC.
11
+ #
12
+ # @param target [String] Cerbos PDP server address (`"host", "host:port"`, or `"unix:/path/to/socket"`).
13
+ # @param tls [TLS, MutualTLS, false] gRPC connection encryption settings (`false` for plaintext).
14
+ # @param grpc_channel_args [Hash{String, Symbol => String, Integer}] low-level settings for the gRPC channel (see [available keys in the gRPC documentation](https://grpc.github.io/grpc/core/group__grpc__arg__keys.html)).
15
+ # @param playground_instance [String, nil] identifier of the playground instance to use when prototyping against the hosted demo PDP.
16
+ # @param timeout [Numeric, nil] timeout for gRPC calls, in seconds (`nil` to never time out).
17
+ #
18
+ # @example Connect via TCP with no encryption
19
+ # client = Cerbos::Client.new("localhost:3593", tls: false)
20
+ #
21
+ # @example Connect via a Unix socket with no encryption
22
+ # client = Cerbos::Client.new("unix:/var/run/cerbos.grpc.sock", tls: false)
23
+ #
24
+ # @example Connect to the hosted demo PDP to experiment [in the playground](https://play.cerbos.dev)
25
+ # client = Cerbos::Client.new("demo-pdp.cerbos.cloud", tls: Cerbos::TLS.new, playground_instance: "gE623b0180QlsG5a4QIN6UOZ6f3iSFW2")
26
+ def initialize(target, tls:, grpc_channel_args: {}, playground_instance: nil, timeout: nil)
27
+ handle_errors do
28
+ credentials = tls ? tls.to_channel_credentials : :this_channel_is_insecure
29
+
30
+ unless playground_instance.nil?
31
+ credentials = credentials.compose(GRPC::Core::CallCredentials.new(->(*) { {"playground-instance" => playground_instance} }))
32
+ end
33
+
34
+ channel_args = grpc_channel_args.merge({
35
+ "grpc.primary_user_agent" => [grpc_channel_args["grpc.primary_user_agent"], "cerbos-sdk-ruby/#{VERSION}"].compact.join(" ")
36
+ })
37
+
38
+ @cerbos_service = Protobuf::Cerbos::Svc::V1::CerbosService::Stub.new(
39
+ target,
40
+ credentials,
41
+ channel_args: channel_args,
42
+ timeout: timeout
43
+ )
44
+ end
45
+ end
46
+
47
+ # Check a principal's permissions on a resource.
48
+ #
49
+ # @param principal [Input::Principal, Hash] the principal to check.
50
+ # @param resource [Input::Resource, Hash] the resource to check.
51
+ # @param actions [Input::Resource, Hash] the actions to check.
52
+ # @param aux_data [Input::AuxData, Hash, nil] auxiliary data.
53
+ # @param include_metadata [Boolean] `true` to include additional metadata ({Output::CheckResources::Result::Metadata}) in the results.
54
+ # @param request_id [String] identifier for tracing the request.
55
+ #
56
+ # @return [Output::CheckResources::Result]
57
+ #
58
+ # @example
59
+ # decision = client.check_resource(
60
+ # principal: {id: "user@example.com", roles: ["USER"]},
61
+ # resource: {kind: "document", id: "1"},
62
+ # actions: ["view", "edit"]
63
+ # )
64
+ #
65
+ # decision.allow?("view") # => true
66
+ def check_resource(principal:, resource:, actions:, aux_data: nil, include_metadata: false, request_id: SecureRandom.uuid)
67
+ handle_errors do
68
+ check_resources(
69
+ principal: principal,
70
+ resources: [Input::ResourceCheck.new(resource: resource, actions: actions)],
71
+ aux_data: aux_data,
72
+ include_metadata: include_metadata,
73
+ request_id: request_id
74
+ ).find_result(resource)
75
+ end
76
+ end
77
+
78
+ # Check a principal's permissions on a set of resources.
79
+ #
80
+ # @param principal [Input::Principal, Hash] the principal to check.
81
+ # @param resources [Array<Input::ResourceCheck, Hash>] the resources and actions to check.
82
+ # @param aux_data [Input::AuxData, Hash, nil] auxiliary data.
83
+ # @param include_metadata [Boolean] `true` to include additional metadata ({Output::CheckResources::Result::Metadata}) in the results.
84
+ # @param request_id [String] identifier for tracing the request.
85
+ #
86
+ # @return [Output::CheckResources]
87
+ #
88
+ # @example
89
+ # decision = client.check_resources(
90
+ # principal: {id: "user@example.com", roles: ["USER"]},
91
+ # resources: [
92
+ # {
93
+ # resource: {kind: "document", id: "1"},
94
+ # actions: ["view", "edit"]
95
+ # },
96
+ # {
97
+ # resource: {kind: "image", id: "1"},
98
+ # actions: ["delete"]
99
+ # }
100
+ # ]
101
+ # )
102
+ #
103
+ # result.allow?(resource: {kind: "document", id: "1"}, action: "view") # => true
104
+ def check_resources(principal:, resources:, aux_data: nil, include_metadata: false, request_id: SecureRandom.uuid)
105
+ handle_errors do
106
+ request = Protobuf::Cerbos::Request::V1::CheckResourcesRequest.new(
107
+ principal: Input.coerce_required(principal, Input::Principal).to_protobuf,
108
+ resources: Input.coerce_array(resources, Input::ResourceCheck).map(&:to_protobuf),
109
+ aux_data: Input.coerce_optional(aux_data, Input::AuxData)&.to_protobuf,
110
+ include_meta: include_metadata,
111
+ request_id: request_id
112
+ )
113
+
114
+ response = perform_request(@cerbos_service, :check_resources, request)
115
+
116
+ Output::CheckResources.from_protobuf(response)
117
+ end
118
+ end
119
+
120
+ # Produce a query plan that can be used to obtain a list of resources on which a principal is allowed to perform a particular action.
121
+ #
122
+ # @param principal [Input::Principal, Hash] the principal for whom to plan.
123
+ # @param resource [Input::ResourceQuery, Hash] partial details of the resources for which to plan.
124
+ # @param action [String] the action for which to plan.
125
+ # @param aux_data [Input::AuxData, Hash, nil] auxiliary data.
126
+ # @param include_metadata [Boolean] `true` to include additional metadata ({Output::CheckResources::Result::Metadata}) in the results.
127
+ # @param request_id [String] identifier for tracing the request.
128
+ #
129
+ # @return [Output::PlanResources]
130
+ #
131
+ # @example
132
+ # plan = client.plan_resources(
133
+ # principal: {id: "user@example.com", roles: ["USER"]},
134
+ # resource: {kind: "document"},
135
+ # action: "view"
136
+ # )
137
+ #
138
+ # plan.conditional? # => true
139
+ # plan.condition # => #<Cerbos::Output::PlanResources::Expression ...>
140
+ def plan_resources(principal:, resource:, action:, aux_data: nil, include_metadata: false, request_id: SecureRandom.uuid)
141
+ handle_errors do
142
+ request = Protobuf::Cerbos::Request::V1::PlanResourcesRequest.new(
143
+ principal: Input.coerce_required(principal, Input::Principal).to_protobuf,
144
+ resource: Input.coerce_required(resource, Input::ResourceQuery).to_protobuf,
145
+ action: action,
146
+ aux_data: Input.coerce_optional(aux_data, Input::AuxData)&.to_protobuf,
147
+ include_meta: include_metadata,
148
+ request_id: request_id
149
+ )
150
+
151
+ response = perform_request(@cerbos_service, :plan_resources, request)
152
+
153
+ Output::PlanResources.from_protobuf(response)
154
+ end
155
+ end
156
+
157
+ # Retrieve information about the Cerbos PDP server.
158
+ #
159
+ # @return [Output::ServerInfo]
160
+ def server_info
161
+ handle_errors do
162
+ request = Protobuf::Cerbos::Request::V1::ServerInfoRequest.new
163
+
164
+ response = perform_request(@cerbos_service, :server_info, request)
165
+
166
+ Output::ServerInfo.from_protobuf(response)
167
+ end
168
+ end
169
+
170
+ private
171
+
172
+ def handle_errors
173
+ yield
174
+ rescue Error
175
+ raise
176
+ rescue ArgumentError, TypeError => error
177
+ raise Error::InvalidArgument.new(details: error.message)
178
+ rescue GRPC::BadStatus => error
179
+ raise Error::NotOK.from_grpc_bad_status(error)
180
+ rescue => error
181
+ raise Error, error.message
182
+ end
183
+
184
+ def perform_request(service, rpc, request)
185
+ service.public_send(rpc, request)
186
+ end
187
+ end
188
+ end
@@ -0,0 +1,112 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cerbos
4
+ # Base type for errors thrown by the `cerbos` gem.
5
+ class Error < StandardError
6
+ # An error indicating an unsuccessful gRPC operation.
7
+ class NotOK < Error
8
+ # The gRPC status code.
9
+ #
10
+ # @return [Integer]
11
+ #
12
+ # @see https://grpc.github.io/grpc/core/md_doc_statuscodes.html Status codes in the gRPC documentation
13
+ attr_reader :code
14
+
15
+ # The gRPC error details.
16
+ #
17
+ # @return [String]
18
+ attr_reader :details
19
+
20
+ # The gRPC error metadata.
21
+ #
22
+ # @return [Hash]
23
+ attr_reader :metadata
24
+
25
+ # @private
26
+ def self.from_grpc_bad_status(error)
27
+ GRPC_BAD_STATUS_ERROR_CLASS.fetch(error.class, self).new(
28
+ code: error.code,
29
+ details: error.details,
30
+ metadata: error.metadata
31
+ )
32
+ end
33
+
34
+ # @private
35
+ def initialize(code:, details:, metadata: {})
36
+ super("gRPC error #{code}: #{details}")
37
+
38
+ @code = code
39
+ @details = details
40
+ @metadata = metadata
41
+ end
42
+ end
43
+
44
+ # The gRPC operation was cancelled.
45
+ class Cancelled < NotOK
46
+ def initialize(code: GRPC::Core::StatusCodes::CANCELLED, **args)
47
+ super
48
+ end
49
+ end
50
+
51
+ # The gRPC operation timed out.
52
+ class DeadlineExceeded < NotOK
53
+ def initialize(code: GRPC::Core::StatusCodes::DEADLINE_EXCEEDED, **args)
54
+ super
55
+ end
56
+ end
57
+
58
+ # The gRPC operation failed due to an internal error.
59
+ class InternalError < NotOK
60
+ def initialize(code: GRPC::Core::StatusCodes::INTERNAL, **args)
61
+ super
62
+ end
63
+ end
64
+
65
+ # The gRPC operation was rejected because an argument was invalid.
66
+ class InvalidArgument < NotOK
67
+ def initialize(code: GRPC::Core::StatusCodes::INVALID_ARGUMENT, **args)
68
+ super
69
+ end
70
+ end
71
+
72
+ # The gRPC operation failed because a resource has been exhausted.
73
+ class ResourceExhausted < NotOK
74
+ def initialize(code: GRPC::Core::StatusCodes::RESOURCE_EXHAUSTED, **args)
75
+ super
76
+ end
77
+ end
78
+
79
+ # The gRPC operation was rejected because it did not have valid authentication credentials.
80
+ class Unauthenticated < NotOK
81
+ def initialize(code: GRPC::Core::StatusCodes::UNAUTHENTICATED, **args)
82
+ super
83
+ end
84
+ end
85
+
86
+ # The gRPC operation failed because the service is unavailable.
87
+ class Unavailable < NotOK
88
+ def initialize(code: GRPC::Core::StatusCodes::UNAVAILABLE, **args)
89
+ super
90
+ end
91
+ end
92
+
93
+ # The gRPC operation is not supported.
94
+ class Unimplemented < NotOK
95
+ def initialize(code: GRPC::Core::StatusCodes::UNIMPLEMENTED, **args)
96
+ super
97
+ end
98
+ end
99
+
100
+ GRPC_BAD_STATUS_ERROR_CLASS = {
101
+ GRPC::Cancelled => Cancelled,
102
+ GRPC::DeadlineExceeded => DeadlineExceeded,
103
+ GRPC::Internal => InternalError,
104
+ GRPC::InvalidArgument => InvalidArgument,
105
+ GRPC::ResourceExhausted => ResourceExhausted,
106
+ GRPC::Unauthenticated => Unauthenticated,
107
+ GRPC::Unavailable => Unavailable,
108
+ GRPC::Unimplemented => Unimplemented
109
+ }.freeze
110
+ private_constant :GRPC_BAD_STATUS_ERROR_CLASS
111
+ end
112
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cerbos
4
+ module Input
5
+ # Attributes for a principal or resource.
6
+ class Attributes
7
+ # Specify a principal's or resource's attributes.
8
+ #
9
+ # @param attributes [Hash{Symbol => String, Numeric, Boolean, Array, Hash, nil}] the principal's or resource's attributes.
10
+ def initialize(**attributes)
11
+ @attributes = attributes
12
+ end
13
+
14
+ # The principal's or resource's attributes.
15
+ #
16
+ # @return [Hash{Symbol => String, Numeric, Boolean, Array, Hash, nil}]
17
+ def to_hash
18
+ @attributes
19
+ end
20
+
21
+ alias_method :to_h, :to_hash
22
+
23
+ # @private
24
+ def to_protobuf
25
+ @attributes.transform_values { |value| Google::Protobuf::Value.from_ruby(value) }
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cerbos
4
+ module Input
5
+ # Auxiliary data sources that can be referenced in policy conditions.
6
+ class AuxData
7
+ # A JSON Web Token (JWT) to use as an auxiliary data source.
8
+ #
9
+ # @return [JWT]
10
+ # @return [nil] if not provided.
11
+ attr_reader :jwt
12
+
13
+ # Specify auxiliary data sources.
14
+ #
15
+ # @param jwt [JWT, Hash, nil] a JSON Web Token (JWT) to use as an auxiliary data source.
16
+ def initialize(jwt: nil)
17
+ @jwt = Input.coerce_optional(jwt, JWT)
18
+ end
19
+
20
+ # @private
21
+ def to_protobuf
22
+ Protobuf::Cerbos::Request::V1::AuxData.new(jwt: jwt&.to_protobuf)
23
+ end
24
+ end
25
+ end
26
+ end