cyclid-core 0.1.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.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 8ae5e120afdbe2e4dc79c0106ab71fb478018cda
4
+ data.tar.gz: 703042beb35a28c7b69912f152c6c82c77690af1
5
+ SHA512:
6
+ metadata.gz: 3e8dcb8faabca9d3398d15dd307c1772beebceb1a906d46001cc7b2d711c0b52f71557b6d4eb7f1f55ba0dc5d5d6caa319c109c1c8ba577066a875cc372c4ce1
7
+ data.tar.gz: f7baace3ced717be03739b144aec4fffdb3fa0b36abbf988c3e4d662588a00e8c08c484fb77bc71d74f7773efddfd13799621e74abe43419a7cdfdea64e2be11
data/LICENSE ADDED
@@ -0,0 +1,199 @@
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
+ Cyclid-core includes code from warden-hmac-authentication, which is
177
+ licensed under the MIT license:
178
+
179
+ Copyright (c) 2011 Florian Gilcher <florian.gilcher@asquera.de>,
180
+ Felix Gilcher <felix.gilcher@asquera.de>
181
+
182
+ Permission is hereby granted, free of charge, to any person obtaining
183
+ a copy of this software and associated documentation files (the
184
+ "Software"), to deal in the Software without restriction, including
185
+ without limitation the rights to use, copy, modify, merge, publish,
186
+ distribute, sublicense, and/or sell copies of the Software, and to
187
+ permit persons to whom the Software is furnished to do so, subject to
188
+ the following conditions:
189
+
190
+ The above copyright notice and this permission notice shall be
191
+ included in all copies or substantial portions of the Software.
192
+
193
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
194
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
195
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
196
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
197
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
198
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
199
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,12 @@
1
+ # Cyclid Core
2
+
3
+ This Gem contains files which are shared between the Cyclid API & Cyclid client.
4
+
5
+ ## hmac.rb
6
+
7
+ HMAC method signing class, which originated from the warden-hmac-authentication Gem.
8
+
9
+ ## constants.rb and errors.rb
10
+
11
+ Constant definitions for error codes and job statuses, along with human readable string mappings for converting codes to human readable text.
12
+
@@ -0,0 +1,53 @@
1
+ # Copyright 2016 Liqwyd Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ module Cyclid
16
+ # Module for the Cyclid API
17
+ module API
18
+ # Constant values
19
+ module Constants
20
+ # Identifiers for job statuses
21
+ module JobStatus
22
+ # Submitted
23
+ NEW = 0
24
+ # Runner has started, waiting for build host
25
+ WAITING = 1
26
+ # Runner has started
27
+ STARTED = 2
28
+ # Job has had a failed stage
29
+ FAILING = 3
30
+
31
+ # Job succeeded
32
+ SUCCEEDED = 10
33
+ # Job failed
34
+ FAILED = 11
35
+ end
36
+
37
+ # Human readable job status strings
38
+ JOB_STATUSES = {
39
+ JobStatus::NEW => 'New',
40
+ JobStatus::WAITING => 'Waiting',
41
+ JobStatus::STARTED => 'Started',
42
+ JobStatus::FAILING => 'Failing',
43
+ JobStatus::SUCCEEDED => 'Succeeded',
44
+ JobStatus::FAILED => 'Failed'
45
+ }.freeze
46
+
47
+ # Other one-off constants
48
+ #
49
+ # Default size for generating RSA key pairs
50
+ RSA_KEY_LENGTH = 2048
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,77 @@
1
+ # Copyright 2016 Liqwyd Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ module Cyclid
16
+ # Module for the Cyclid API
17
+ module API
18
+ # Error codes, for REST etc. statuses
19
+ module Errors
20
+ # Identifiers for HTTP JSON error bodies
21
+ module HTTPErrors
22
+ # Success
23
+ NO_ERROR = 0
24
+ # Something caught an exception
25
+ INTERNAL_ERROR = 1
26
+ # The JSON in the request body could not be parsed
27
+ INVALID_JSON = 2
28
+ # Invalid username or password, or not an admin
29
+ AUTH_FAILURE = 3
30
+ # A unique entry already exists
31
+ DUPLICATE = 4
32
+
33
+ # User does not exist
34
+ INVALID_USER = 10
35
+ # Organization does not exist
36
+ INVALID_ORG = 11
37
+ # Stage does not exist
38
+ INVALID_STAGE = 12
39
+ # No plugin found for the given action
40
+ INVALID_ACTION = 13
41
+ # Job definition is incorrect or does not exist
42
+ INVALID_JOB = 14
43
+ # Requested plugin does not exist
44
+ INVALID_PLUGIN = 15
45
+ # Could not get a configuration for the given plugin
46
+ INVALID_PLUGIN_CONFIG = 16
47
+
48
+ # API plugin request failed
49
+ PLUGIN_ERROR = 20
50
+ end
51
+
52
+ # Human readable error strings
53
+ ERROR_MESSAGES = {
54
+ HTTPErrors::NO_ERROR => 'Success',
55
+ HTTPErrors::INTERNAL_ERROR => 'Internal error',
56
+ HTTPErrors::INVALID_JSON => 'The JSON in the request body could not be parsed',
57
+ HTTPErrors::AUTH_FAILURE => 'Invalid username or password, or not an admin',
58
+ HTTPErrors::DUPLICATE => 'Entry already exists',
59
+ HTTPErrors::INVALID_USER => 'User does not exist',
60
+ HTTPErrors::INVALID_ORG => 'Organization does not exist',
61
+ HTTPErrors::INVALID_STAGE => 'Stage does not exist',
62
+ HTTPErrors::INVALID_ACTION => 'No plugin found for the given action',
63
+ HTTPErrors::INVALID_JOB => 'Job definition is incorrect or does not exist',
64
+ HTTPErrors::INVALID_PLUGIN => 'Requested plugin does not exist',
65
+ HTTPErrors::INVALID_PLUGIN_CONFIG => 'Could not get a configuration for the given plugin',
66
+ HTTPErrors::PLUGIN_ERROR => 'API plugin request failed'
67
+ }.freeze
68
+ end
69
+
70
+ # Internal exceptions
71
+ module Exceptions
72
+ # Base class for all internal Cyclid exceptions
73
+ class CyclidError < StandardError
74
+ end
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,268 @@
1
+ # rubocop:disable Metrics/LineLength, Style/FormatString
2
+ #
3
+ # Copyright (c) 2011 Florian Gilcher <florian.gilcher@asquera.de>, Felix Gilcher <felix.gilcher@asquera.de>
4
+ #
5
+ # Permission is hereby granted, free of charge, to any person obtaining
6
+ # a copy of this software and associated documentation files (the
7
+ # "Software"), to deal in the Software without restriction, including
8
+ # without limitation the rights to use, copy, modify, merge, publish,
9
+ # distribute, sublicense, and/or sell copies of the Software, and to
10
+ # permit persons to whom the Software is furnished to do so, subject to
11
+ # the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be
14
+ # included in all copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ require 'openssl'
25
+ require 'rack/utils'
26
+
27
+ module Cyclid
28
+ # Container for the HMAC authentication code
29
+ module HMAC
30
+ # Helper class that provides signing capabilites for the hmac strategies.
31
+ #
32
+ # @author Felix Gilcher <felix.gilcher@asquera.de>
33
+ class Signer
34
+ attr_accessor :secret, :algorithm, :default_opts
35
+
36
+ # HMAC defaults
37
+ DEFAULT_OPTS = {
38
+ auth_scheme: 'HMAC',
39
+ auth_param: 'auth',
40
+ auth_header: 'Authorization',
41
+ auth_header_format: '%{auth_scheme} %{signature}',
42
+ query_based: false,
43
+ use_alternate_date_header: false,
44
+ extra_auth_params: {},
45
+ ignore_params: []
46
+ }.freeze
47
+
48
+ # create a new HMAC instance
49
+ #
50
+ # @param [String] algorithm The hashing-algorithm to use. See the openssl documentation for valid values.
51
+ # @param [Hash] default_opts The default options for all calls that take opts
52
+ #
53
+ # @option default_opts [String] :auth_scheme ('HMAC') The name of the authorization scheme used in the Authorization header and to construct various header-names
54
+ # @option default_opts [String] :auth_param ('auth') The name of the authentication param to use for query based authentication
55
+ # @option default_opts [String] :auth_header ('Authorization') The name of the authorization header to use
56
+ # @option default_opts [String] :auth_header_format ('%{auth_scheme} %{signature}') The format of the authorization header. Will be interpolated with the given options and the signature.
57
+ # @option default_opts [String] :nonce_header ('X-#{auth_scheme}-Nonce') The header name for the request nonce
58
+ # @option default_opts [String] :alternate_date_header ('X-#{auth_scheme}-Date') The header name for the alternate date header
59
+ # @option default_opts [Bool] :query_based (false) Whether to use query based authentication
60
+ # @option default_opts [Bool] :use_alternate_date_header (false) Use the alternate date header instead of `Date`
61
+ # @option default_opts [Hash] :extra_auth_params ({}) Additional parameters to inject in the auth parameter
62
+ # @option default_opts [Array<Symbol>] :ignore_params ([]) Params to ignore for signing
63
+ #
64
+ def initialize(algorithm = 'sha256', default_opts = {})
65
+ self.algorithm = algorithm
66
+ default_opts[:nonce_header] ||= 'X-%{scheme}-Nonce' % { scheme: (default_opts[:auth_scheme] || 'HMAC') }
67
+ default_opts[:alternate_date_header] ||= 'X-%{scheme}-Date' % { scheme: (default_opts[:auth_scheme] || 'HMAC') }
68
+ self.default_opts = DEFAULT_OPTS.merge(default_opts)
69
+ end
70
+
71
+ # Generate the signature from a hash representation
72
+ #
73
+ # returns nil if no secret or an empty secret was given
74
+ #
75
+ # @param [Hash] params the parameters to create the representation with
76
+ # @option params [String] :secret The secret to generate the signature with
77
+ # @option params [String] :method The HTTP Verb of the request
78
+ # @option params [String] :date The date of the request as it was formatted in the request
79
+ # @option params [String] :nonce ('') The nonce given in the request
80
+ # @option params [String] :path The path portion of the request
81
+ # @option params [Hash] :query ({}) The query parameters given in the request. Must not contain the auth param.
82
+ # @option params [Hash] :headers ({}) All headers given in the request (optional and required)
83
+ # @option params [String] :auth_scheme ('HMAC') The name of the authorization scheme used in the Authorization header and to construct various header-names
84
+ # @option params [String] :auth_param ('auth') The name of the authentication param to use for query based authentication
85
+ # @option params [Hash] :extra_auth_params ({}) Additional parameters to inject in the auth parameter
86
+ # @option params [Array<Symbol>] :ignore_params ([]) Params to ignore for signing
87
+ # @option params [String] :auth_header ('Authorization') The name of the authorization header to use
88
+ # @option params [String] :auth_header_format ('%{auth_scheme} %{signature}') The format of the authorization header. Will be interpolated with the given options and the signature.
89
+ # @option params [String] :nonce_header ('X-#{auth_scheme}-Nonce') The header name for the request nonce
90
+ # @option params [String] :alternate_date_header ('X-#{auth_scheme}-Date') The header name for the alternate date header
91
+ # @option params [Bool] :query_based (false) Whether to use query based authentication
92
+ # @option params [Bool] :use_alternate_date_header (false) Use the alternate date header instead of `Date`
93
+ #
94
+ # @return [String] the signature
95
+ def generate_signature(params)
96
+ secret = params.delete(:secret)
97
+
98
+ # jruby stumbles over empty secrets, we regard them as invalid anyways, so we return an empty digest if no scret was given
99
+ if '' == secret.to_s
100
+ nil
101
+ else
102
+ OpenSSL::HMAC.hexdigest(algorithm, secret, canonical_representation(params))
103
+ end
104
+ end
105
+
106
+ # compares the given signature with the signature created from a hash representation
107
+ #
108
+ # @param [String] signature the signature to compare with
109
+ # @param [Hash] params the parameters to create the representation with
110
+ # @option params [String] :secret The secret to generate the signature with
111
+ # @option params [String] :method The HTTP Verb of the request
112
+ # @option params [String] :date The date of the request as it was formatted in the request
113
+ # @option params [String] :nonce ('') The nonce given in the request
114
+ # @option params [String] :path The path portion of the request
115
+ # @option params [Hash] :query ({}) The query parameters given in the request. Must not contain the auth param.
116
+ # @option params [Hash] :headers ({}) All headers given in the request (optional and required)
117
+ # @option params [String] :auth_scheme ('HMAC') The name of the authorization scheme used in the Authorization header and to construct various header-names
118
+ # @option params [String] :auth_param ('auth') The name of the authentication param to use for query based authentication
119
+ # @option params [Hash] :extra_auth_params ({}) Additional parameters to inject in the auth parameter
120
+ # @option params [Array<Symbol>] :ignore_params ([]) Params to ignore for signing
121
+ # @option params [String] :auth_header ('Authorization') The name of the authorization header to use
122
+ # @option params [String] :auth_header_format ('%{auth_scheme} %{signature}') The format of the authorization header. Will be interpolated with the given options and the signature.
123
+ # @option params [String] :nonce_header ('X-#{auth_scheme}-Nonce') The header name for the request nonce
124
+ # @option params [String] :alternate_date_header ('X-#{auth_scheme}-Date') The header name for the alternate date header
125
+ # @option params [Bool] :query_based (false) Whether to use query based authentication
126
+ # @option params [Bool] :use_alternate_date_header (false) Use the alternate date header instead of `Date`
127
+ #
128
+ # @return [Bool] true if the signature matches
129
+ def validate_signature(signature, params)
130
+ compare_hashes(signature, generate_signature(params))
131
+ end
132
+
133
+ # generates the canonical representation for a given request
134
+ #
135
+ # @param [Hash] params the parameters to create the representation with
136
+ # @option params [String] :method The HTTP Verb of the request
137
+ # @option params [String] :date The date of the request as it was formatted in the request
138
+ # @option params [String] :nonce ('') The nonce given in the request
139
+ # @option params [String] :path The path portion of the request
140
+ # @option params [Hash] :query ({}) The query parameters given in the request. Must not contain the auth param.
141
+ # @option params [Hash] :headers ({}) All headers given in the request (optional and required)
142
+ # @option params [String] :auth_scheme ('HMAC') The name of the authorization scheme used in the Authorization header and to construct various header-names
143
+ # @option params [String] :auth_param ('auth') The name of the authentication param to use for query based authentication
144
+ # @option params [Hash] :extra_auth_params ({}) Additional parameters to inject in the auth parameter
145
+ # @option params [Array<Symbol>] :ignore_params ([]) Params to ignore for signing
146
+ # @option params [String] :auth_header ('Authorization') The name of the authorization header to use
147
+ # @option params [String] :auth_header_format ('%{auth_scheme} %{signature}') The format of the authorization header. Will be interpolated with the given options and the signature.
148
+ # @option params [String] :nonce_header ('X-#{auth_scheme}-Nonce') The header name for the request nonce
149
+ # @option params [String] :alternate_date_header ('X-#{auth_scheme}-Date') The header name for the alternate date header
150
+ # @option params [Bool] :query_based (false) Whether to use query based authentication
151
+ # @option params [Bool] :use_alternate_date_header (false) Use the alternate date header instead of `Date`
152
+ #
153
+ # @return [String] the canonical representation
154
+ def canonical_representation(params)
155
+ rep = ''
156
+
157
+ rep << "#{params[:method].upcase}\n"
158
+ rep << "date:#{params[:date]}\n"
159
+ rep << "nonce:#{params[:nonce]}\n"
160
+
161
+ (params[:headers] || {}).sort.each do |pair|
162
+ name, value = *pair
163
+ rep << "#{name.downcase}:#{value}\n"
164
+ end
165
+
166
+ rep << params[:path]
167
+
168
+ p = (params[:query] || {}).dup
169
+
170
+ unless p.empty?
171
+ query = p.sort.map do |key, value|
172
+ '%{key}=%{value}' % {
173
+ key: Rack::Utils.unescape(key.to_s),
174
+ value: Rack::Utils.unescape(value.to_s)
175
+ }
176
+ end.join('&')
177
+ rep << "?#{query}"
178
+ end
179
+
180
+ rep
181
+ end
182
+
183
+ # sign the given request
184
+ #
185
+ # @param [String] url The url of the request
186
+ # @param [String] secret The shared secret for the signature
187
+ # @param [Hash] opts Options for the signature generation
188
+ #
189
+ # @option opts [String] :nonce ('') The nonce to use in the signature
190
+ # @option opts [String, #strftime] :date (Time.now) The date to use in the signature
191
+ # @option opts [Hash] :headers ({}) A list of optional headers to include in the signature
192
+ # @option opts [String,Symbol] :method ('GET') The HTTP method to use in the signature
193
+ #
194
+ # @option opts [String] :auth_scheme ('HMAC') The name of the authorization scheme used in the Authorization header and to construct various header-names
195
+ # @option opts [String] :auth_param ('auth') The name of the authentication param to use for query based authentication
196
+ # @option opts [Hash] :extra_auth_params ({}) Additional parameters to inject in the auth parameter
197
+ # @option opts [Array<Symbol>] :ignore_params ([]) Params to ignore for signing
198
+ # @option opts [String] :auth_header ('Authorization') The name of the authorization header to use
199
+ # @option opts [String] :auth_header_format ('%{auth_scheme} %{signature}') The format of the authorization header. Will be interpolated with the given options and the signature.
200
+ # @option opts [String] :nonce_header ('X-#{auth_scheme}-Nonce') The header name for the request nonce
201
+ # @option opts [String] :alternate_date_header ('X-#{auth_scheme}-Date') The header name for the alternate date header
202
+ # @option opts [Bool] :query_based (false) Whether to use query based authentication
203
+ # @option opts [Bool] :use_alternate_date_header (false) Use the alternate date header instead of `Date`
204
+ #
205
+ def sign_request(url, secret, opts = {})
206
+ opts = default_opts.merge(opts)
207
+
208
+ uri = parse_url(url)
209
+ headers = opts[:headers] || {}
210
+
211
+ date = opts[:date] || Time.now.gmtime
212
+ date = date.gmtime.strftime('%a, %d %b %Y %T GMT') if date.respond_to? :strftime
213
+
214
+ method = opts[:method] ? opts[:method].to_s.upcase : 'GET'
215
+
216
+ query_values = Rack::Utils.parse_nested_query(uri.query)
217
+
218
+ if query_values
219
+ query_values.delete_if do |k, _v|
220
+ opts[:ignore_params].one? { |param| (k == param) || (k == param.to_s) }
221
+ end
222
+ end
223
+
224
+ signature = generate_signature(secret: secret, method: method, path: uri.path, date: date, nonce: opts[:nonce], query: query_values, headers: opts[:headers], ignore_params: opts[:ignore_params])
225
+
226
+ if opts[:query_based]
227
+ auth_params = opts[:extra_auth_params].merge('date' => date,
228
+ 'signature' => signature)
229
+ auth_params[:nonce] = opts[:nonce] unless opts[:nonce].nil?
230
+
231
+ query_values ||= {}
232
+ query_values[opts[:auth_param]] = auth_params
233
+ uri.query = Rack::Utils.build_nested_query(query_values)
234
+ else
235
+ headers[opts[:auth_header]] = opts[:auth_header_format] % opts.merge(signature: signature)
236
+ headers[opts[:nonce_header]] = opts[:nonce] unless opts[:nonce].nil?
237
+
238
+ if opts[:use_alternate_date_header]
239
+ headers[opts[:alternate_date_header]] = date
240
+ else
241
+ headers['Date'] = date
242
+ end
243
+ end
244
+
245
+ [headers, uri.to_s]
246
+ end
247
+
248
+ private
249
+
250
+ # compares two hashes in a manner that's invulnerable to timing sidechannel attacks (see issue #16)
251
+ # by comparing them characterwise up to the end in all cases, no matter where the mismatch happens
252
+ # short circuits if the length does not match since this does not allow timing sidechannel attacks.
253
+ def compare_hashes(presented, computed)
254
+ if computed.length == presented.length
255
+ computed.chars.zip(presented.chars).map { |x, y| x == y }.all?
256
+ else
257
+ false
258
+ end
259
+ end
260
+
261
+ # parse url if url parameter is string do nothing if parameter is URI
262
+ def parse_url(url)
263
+ return url if url.is_a?(URI)
264
+ URI.parse(url)
265
+ end
266
+ end
267
+ end
268
+ end
metadata ADDED
@@ -0,0 +1,63 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: cyclid-core
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - Kristian Van Der Vliet
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2016-08-15 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rack
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.6'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.6'
27
+ description: Core files (shared between the Client & Server) for Cyclid
28
+ email: vanders@liqwyd.com
29
+ executables: []
30
+ extensions: []
31
+ extra_rdoc_files: []
32
+ files:
33
+ - LICENSE
34
+ - README.md
35
+ - lib/cyclid/constants.rb
36
+ - lib/cyclid/errors.rb
37
+ - lib/cyclid/hmac.rb
38
+ homepage:
39
+ licenses:
40
+ - MIT
41
+ - Apache-2.0
42
+ metadata: {}
43
+ post_install_message:
44
+ rdoc_options: []
45
+ require_paths:
46
+ - lib
47
+ required_ruby_version: !ruby/object:Gem::Requirement
48
+ requirements:
49
+ - - ">="
50
+ - !ruby/object:Gem::Version
51
+ version: '0'
52
+ required_rubygems_version: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - ">="
55
+ - !ruby/object:Gem::Version
56
+ version: '0'
57
+ requirements: []
58
+ rubyforge_project:
59
+ rubygems_version: 2.5.1
60
+ signing_key:
61
+ specification_version: 4
62
+ summary: Core files for Cyclid
63
+ test_files: []