ve-tos-ruby-sdk 0.1.0

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: 30e5d9300d235ffbbd406f29793424c09d903c4a720b9015307bf1e56f111665
4
+ data.tar.gz: 7f3aaf5b4880ecc5bd372c7de50a53234a2ede71669f28a6fd74871775667aaf
5
+ SHA512:
6
+ metadata.gz: 2637093b77a69369532f95e01179d3badaccf9ee2199bd65c44f1b3e738185446ce561562a2bfc9302a1d87b8bf8f0b9edeb79267612b81978bcf1430f8938ac
7
+ data.tar.gz: e30a3db93b8c50595f2571a919852c5e3ce0b7c8493b79a04f39135511b2a9675a77447ad8fbbad90c0bbca14db8c1409cecf95bf9b745085fab7e1322ba88bf
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,93 @@
1
+ # ve-tos-ruby-sdk
2
+
3
+ Ruby SDK for [Volcengine TOS](https://www.volcengine.com/docs/6349).
4
+
5
+ - `PutObject`, `GetObject` (with Range), `HeadObject`, `DeleteObject`
6
+ - `DeleteMultipleObjects` (batch)
7
+ - `ListObjectsV2` (with prefix + pagination)
8
+ - Presigned URLs (GET / PUT)
9
+
10
+ Authentication uses `TOS4-HMAC-SHA256` (the TOS variant of AWS SigV4).
11
+
12
+ ## Installation
13
+
14
+ ```ruby
15
+ # Gemfile
16
+ gem "ve-tos-ruby-sdk"
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ```ruby
22
+ client = TOS::Client.new(
23
+ access_key_id: ENV.fetch("TOS_ACCESS_KEY_ID"),
24
+ secret_access_key: ENV.fetch("TOS_SECRET_ACCESS_KEY"),
25
+ region: "cn-beijing"
26
+ # endpoint: "tos-cn-beijing.volces.com" # optional override
27
+ )
28
+
29
+ bucket = client.bucket("my-bucket")
30
+
31
+ # Upload
32
+ bucket.put_object("hello.txt", "world", content_type: "text/plain")
33
+
34
+ # Download (full body)
35
+ res = bucket.get_object("hello.txt")
36
+ res.body # => "world"
37
+
38
+ # Download (streaming)
39
+ File.open("/tmp/out.bin", "wb") do |f|
40
+ bucket.get_object("big.bin") { |chunk| f.write(chunk) }
41
+ end
42
+
43
+ # Range request
44
+ bucket.get_object("big.bin", range: 0..1023) # first 1 KiB
45
+
46
+ # Metadata
47
+ bucket.head_object("hello.txt").header("content-length")
48
+
49
+ # Delete
50
+ bucket.delete_object("hello.txt")
51
+ bucket.delete_multiple_objects(%w[a.txt b.txt c.txt])
52
+
53
+ # List
54
+ page = bucket.list_objects(prefix: "uploads/", max_keys: 100)
55
+ page[:keys] # => ["uploads/foo.png", ...]
56
+
57
+ # Presigned URL (read)
58
+ url = client.presign(method: "GET", bucket: "my-bucket", key: "hello.txt", expires_in: 600)
59
+ ```
60
+
61
+ ## Errors
62
+
63
+ All HTTP errors raise `TOS::ServerError`, which carries `status`, `code`, `request_id`, and `body`. Network failures raise `TOS::NetworkError`. Configuration mistakes raise `TOS::ConfigError`.
64
+
65
+ ```ruby
66
+ begin
67
+ bucket.get_object("missing")
68
+ rescue TOS::ServerError => e
69
+ e.status # => 404
70
+ e.code # => "NoSuchKey"
71
+ e.request_id # => "..."
72
+ end
73
+ ```
74
+
75
+ ## Out of scope
76
+
77
+ This SDK is intentionally narrow. The following are not implemented; if you need them, the `Client#request` method gives you a signed-request escape hatch:
78
+
79
+ - Multipart upload (initiate / upload-part / complete / abort)
80
+ - Bucket-level operations (create, lifecycle, CORS, ACL, tagging)
81
+ - Object copy / append / restore
82
+ - Server-side encryption headers, object tagging
83
+
84
+ ## Development
85
+
86
+ ```
87
+ bundle install
88
+ bundle exec rspec
89
+ ```
90
+
91
+ ## License
92
+
93
+ Apache License 2.0
data/lib/tos/bucket.rb ADDED
@@ -0,0 +1,127 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rexml/document"
4
+
5
+ module TOS
6
+ # All operations are bucket-scoped: get a bucket via `client.bucket(name)`
7
+ # then call put_object / get_object / etc. on it.
8
+ class Bucket
9
+ attr_reader :name, :client
10
+
11
+ def initialize(client:, name:)
12
+ raise ConfigError, "bucket name is required" if name.to_s.empty?
13
+
14
+ @client = client
15
+ @name = name.to_s
16
+ end
17
+
18
+ def put_object(key, body, content_type: nil, content_md5: nil, metadata: {}, headers: {})
19
+ h = headers.dup
20
+ h["Content-Type"] = content_type if content_type
21
+ h["Content-MD5"] = content_md5 if content_md5
22
+ metadata.each { |k, v| h["x-tos-meta-#{k}"] = v.to_s }
23
+
24
+ body_str = body.respond_to?(:read) ? body.read : body.to_s
25
+ client.request(method: :put, host: host, path: path_for(key), headers: h, body: body_str)
26
+ end
27
+
28
+ # Returns the response with the body loaded. For large objects, pass a
29
+ # block which receives streamed chunks.
30
+ def get_object(key, range: nil, headers: {}, &block)
31
+ h = headers.dup
32
+ h["Range"] = format_range(range) if range
33
+
34
+ client.request(method: :get, host: host, path: path_for(key), headers: h, stream: block)
35
+ end
36
+
37
+ def head_object(key, headers: {})
38
+ client.request(method: :head, host: host, path: path_for(key), headers: headers)
39
+ end
40
+
41
+ def delete_object(key)
42
+ client.request(method: :delete, host: host, path: path_for(key))
43
+ end
44
+
45
+ # Lists up to `max_keys` objects under `prefix`. Pass the previous
46
+ # response's `next_continuation_token` to page through results.
47
+ #
48
+ # Returns a Hash:
49
+ # {
50
+ # keys: ["foo/bar.txt", ...],
51
+ # is_truncated: true|false,
52
+ # next_continuation_token: "...",
53
+ # raw: TOS::Response
54
+ # }
55
+ def list_objects(prefix: nil, max_keys: 1000, continuation_token: nil)
56
+ query = { "list-type" => "2", "max-keys" => max_keys.to_s }
57
+ query["prefix"] = prefix if prefix
58
+ query["continuation-token"] = continuation_token if continuation_token
59
+
60
+ res = client.request(method: :get, host: host, path: "/", query: query)
61
+ parse_list_response(res)
62
+ end
63
+
64
+ # Deletes up to 1000 objects in a single request.
65
+ def delete_multiple_objects(keys, quiet: true)
66
+ keys = Array(keys).reject { |k| k.to_s.empty? }
67
+ return [] if keys.empty?
68
+
69
+ body = build_delete_payload(keys, quiet)
70
+ content_md5 = OpenSSL::Digest::MD5.base64digest(body)
71
+
72
+ client.request(
73
+ method: :post,
74
+ host: host,
75
+ path: "/",
76
+ query: { "delete" => "" },
77
+ headers: { "Content-Type" => "application/xml", "Content-MD5" => content_md5 },
78
+ body: body,
79
+ )
80
+ end
81
+
82
+ def host
83
+ client.host_for(name)
84
+ end
85
+
86
+ def path_for(key)
87
+ "/#{client.escape_key(key)}"
88
+ end
89
+
90
+ private
91
+
92
+ def format_range(range)
93
+ first = range.begin
94
+ last = range.exclude_end? ? range.end - 1 : range.end
95
+ "bytes=#{first}-#{last}"
96
+ end
97
+
98
+ def parse_list_response(res)
99
+ doc = REXML::Document.new(res.body)
100
+ root = doc.root
101
+ keys = root.get_elements("Contents/Key").map(&:text)
102
+ truncated = root.elements["IsTruncated"]&.text == "true"
103
+ next_token = root.elements["NextContinuationToken"]&.text
104
+
105
+ {
106
+ keys: keys,
107
+ is_truncated: truncated,
108
+ next_continuation_token: next_token,
109
+ raw: res,
110
+ }
111
+ end
112
+
113
+ def build_delete_payload(keys, quiet)
114
+ doc = REXML::Document.new
115
+ doc.add_element("Delete").tap do |delete|
116
+ delete.add_element("Quiet").text = quiet ? "true" : "false"
117
+ keys.each do |key|
118
+ obj = delete.add_element("Object")
119
+ obj.add_element("Key").text = key
120
+ end
121
+ end
122
+ out = +""
123
+ doc.write(out)
124
+ out
125
+ end
126
+ end
127
+ end
data/lib/tos/client.rb ADDED
@@ -0,0 +1,154 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+ require "rexml/document"
6
+
7
+ module TOS
8
+ # Low-level HTTP client. Holds credentials, region, endpoint resolution, and
9
+ # signs every request via TOS::Signer.
10
+ #
11
+ # Endpoints follow the pattern `tos-{region}.volces.com` by default; pass
12
+ # `endpoint:` to override (e.g. for a private endpoint or a custom domain).
13
+ # When a `bucket` is supplied per-call, it is prepended as a sub-domain:
14
+ # `https://{bucket}.{endpoint}/{key}`.
15
+ class Client
16
+ DEFAULT_OPEN_TIMEOUT = 10
17
+ DEFAULT_READ_TIMEOUT = 120
18
+
19
+ attr_reader :region, :endpoint, :signer
20
+
21
+ def initialize(access_key_id:, secret_access_key:, region:, endpoint: nil,
22
+ security_token: nil, open_timeout: DEFAULT_OPEN_TIMEOUT,
23
+ read_timeout: DEFAULT_READ_TIMEOUT, logger: nil)
24
+ @region = region.to_s
25
+ @endpoint = (endpoint || "tos-#{@region}.volces.com").sub(%r{^https?://}, "")
26
+ @signer = Signer.new(
27
+ credentials: Credentials.new(
28
+ access_key_id: access_key_id,
29
+ secret_access_key: secret_access_key,
30
+ security_token: security_token
31
+ ),
32
+ region: @region
33
+ )
34
+ @open_timeout = open_timeout
35
+ @read_timeout = read_timeout
36
+ @logger = logger
37
+ end
38
+
39
+ def bucket(name)
40
+ Bucket.new(client: self, name: name)
41
+ end
42
+
43
+ # Performs a signed request. `headers` is the caller's view of the
44
+ # request — Authorization/X-Tos-Date/etc. are added automatically.
45
+ def request(method:, host:, path:, query: {}, headers: {}, body: nil, stream: nil)
46
+ uri = URI("https://#{host}#{path}")
47
+ uri.query = signer.send(:encode_query, query) unless query.empty?
48
+
49
+ req = build_request(method, uri, body)
50
+ headers.each { |k, v| req[k] = v }
51
+ req["Host"] = host
52
+ req["Content-Length"] = body ? body.bytesize.to_s : "0"
53
+
54
+ signed = signer.sign_headers(
55
+ method: method, path: path, query: query,
56
+ headers: headers, body: body
57
+ )
58
+ signed.each { |k, v| req[k] = v }
59
+ # Signer-only headers that aren't in the user's `headers` hash.
60
+ %w[Authorization X-Tos-Date X-Tos-Content-Sha256 X-Tos-Security-Token].each do |k|
61
+ req[k] = signed[k] if signed[k]
62
+ end
63
+
64
+ do_request(uri, req, stream: stream)
65
+ end
66
+
67
+ def presign(method:, bucket:, key:, query: {}, expires_in: 3600)
68
+ host = "#{bucket}.#{@endpoint}"
69
+ path = "/#{escape_key(key)}"
70
+ signer.presign(method: method, host: host, path: path, query: query, expires_in: expires_in)
71
+ end
72
+
73
+ def host_for(bucket)
74
+ "#{bucket}.#{@endpoint}"
75
+ end
76
+
77
+ def escape_key(key)
78
+ signer.send(:encode_path, "/#{key}").sub(%r{^/}, "")
79
+ end
80
+
81
+ private
82
+
83
+ def build_request(method, uri, body)
84
+ klass = case method.to_s.upcase
85
+ when "GET" then Net::HTTP::Get
86
+ when "PUT" then Net::HTTP::Put
87
+ when "POST" then Net::HTTP::Post
88
+ when "DELETE" then Net::HTTP::Delete
89
+ when "HEAD" then Net::HTTP::Head
90
+ else raise ArgumentError, "unsupported HTTP method: #{method}"
91
+ end
92
+ req = klass.new(uri.request_uri)
93
+ req.body = body if body
94
+ req
95
+ end
96
+
97
+ def do_request(uri, req, stream:)
98
+ http = Net::HTTP.new(uri.host, uri.port)
99
+ http.use_ssl = uri.scheme == "https"
100
+ http.open_timeout = @open_timeout
101
+ http.read_timeout = @read_timeout
102
+
103
+ @logger&.info("[TOS] #{req.method} #{uri}")
104
+
105
+ if stream
106
+ body_chunks = []
107
+ res = http.request(req) do |response|
108
+ response.read_body do |chunk|
109
+ stream.call(chunk)
110
+ body_chunks << chunk if response.code.to_i >= 400
111
+ end
112
+ end
113
+ validate!(res, body_chunks.join)
114
+ Response.new(status: res.code.to_i, headers: header_hash(res), body: nil)
115
+ else
116
+ res = http.request(req)
117
+ validate!(res, res.body.to_s)
118
+ Response.new(status: res.code.to_i, headers: header_hash(res), body: res.body.to_s)
119
+ end
120
+ rescue Net::OpenTimeout, Net::ReadTimeout, SocketError, Errno::ECONNREFUSED => e
121
+ raise NetworkError, "TOS network error: #{e.class}: #{e.message}"
122
+ end
123
+
124
+ def validate!(res, body)
125
+ code = res.code.to_i
126
+ return if code.between?(200, 299)
127
+
128
+ message, error_code, request_id = parse_error(body, res)
129
+ raise ServerError.new(
130
+ "TOS API error (#{code}): #{message}",
131
+ status: code, code: error_code, request_id: request_id, body: body
132
+ )
133
+ end
134
+
135
+ def parse_error(body, res)
136
+ request_id = res["x-tos-request-id"]
137
+ return [body, nil, request_id] if body.empty?
138
+
139
+ doc = REXML::Document.new(body)
140
+ code = doc.root&.elements&.[]("Code")&.text
141
+ message = doc.root&.elements&.[]("Message")&.text || body
142
+ request_id ||= doc.root&.elements&.[]("RequestId")&.text
143
+ [message, code, request_id]
144
+ rescue REXML::ParseException
145
+ [body, nil, request_id]
146
+ end
147
+
148
+ def header_hash(res)
149
+ {}.tap do |h|
150
+ res.each_header { |k, v| h[k] = v }
151
+ end
152
+ end
153
+ end
154
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TOS
4
+ # Static credentials. STS sessions can be supplied via `security_token`.
5
+ Credentials = Struct.new(:access_key_id, :secret_access_key, :security_token, keyword_init: true) do
6
+ def self.from(value)
7
+ case value
8
+ when Credentials then value
9
+ when Hash then new(**value.transform_keys(&:to_sym))
10
+ else raise ConfigError, "credentials must be a TOS::Credentials or Hash"
11
+ end
12
+ end
13
+
14
+ def valid?
15
+ access_key_id.to_s.length.positive? && secret_access_key.to_s.length.positive?
16
+ end
17
+ end
18
+ end
data/lib/tos/error.rb ADDED
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TOS
4
+ class Error < StandardError
5
+ attr_reader :status, :code, :request_id, :body
6
+
7
+ def initialize(message, status: nil, code: nil, request_id: nil, body: nil)
8
+ super(message)
9
+ @status = status
10
+ @code = code
11
+ @request_id = request_id
12
+ @body = body
13
+ end
14
+ end
15
+
16
+ # Raised when configuration is missing/invalid (no network call attempted).
17
+ class ConfigError < Error; end
18
+
19
+ # Raised when the network call fails before reaching TOS.
20
+ class NetworkError < Error; end
21
+
22
+ # Raised on HTTP 4xx/5xx responses from TOS.
23
+ class ServerError < Error; end
24
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TOS
4
+ # Lightweight wrapper around a Net::HTTPResponse so callers don't have to
5
+ # know which HTTP library produced it.
6
+ class Response
7
+ attr_reader :status, :headers, :body
8
+
9
+ def initialize(status:, headers:, body:)
10
+ @status = status
11
+ @headers = headers
12
+ @body = body
13
+ end
14
+
15
+ def header(name)
16
+ key = headers.keys.find { |k| k.downcase == name.downcase }
17
+ key && headers[key]
18
+ end
19
+
20
+ def request_id
21
+ header("x-tos-request-id") || header("x-tos-id-2")
22
+ end
23
+
24
+ def etag
25
+ header("etag")&.delete('"')
26
+ end
27
+
28
+ def content_length
29
+ header("content-length")&.to_i
30
+ end
31
+
32
+ def content_type
33
+ header("content-type")
34
+ end
35
+ end
36
+ end
data/lib/tos/signer.rb ADDED
@@ -0,0 +1,184 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+ require "time"
5
+ require "uri"
6
+ require "cgi"
7
+
8
+ module TOS
9
+ # Signs HTTP requests for the TOS object service using the
10
+ # TOS4-HMAC-SHA256 scheme (analogous to AWS SigV4, but with the "tos"
11
+ # service name and a slightly different signed-header policy: by default
12
+ # only `content-type` and any `x-tos-*` headers are signed).
13
+ #
14
+ # Reference: https://github.com/volcengine/ve-tos-golang-sdk/blob/master/tos/sign_v4.go
15
+ class Signer
16
+ ALGORITHM = "TOS4-HMAC-SHA256"
17
+ SERVICE = "tos"
18
+ REQUEST = "request"
19
+ EMPTY_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
20
+ UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"
21
+
22
+ attr_reader :credentials, :region
23
+
24
+ def initialize(credentials:, region:)
25
+ @credentials = Credentials.from(credentials)
26
+ raise ConfigError, "TOS credentials are missing access_key_id/secret_access_key" unless @credentials.valid?
27
+ raise ConfigError, "TOS region is required" if region.to_s.empty?
28
+
29
+ @region = region.to_s
30
+ end
31
+
32
+ # Sign a request and return a Hash of headers to add (Authorization,
33
+ # X-Tos-Date, X-Tos-Content-Sha256, plus X-Tos-Security-Token when STS
34
+ # credentials are used).
35
+ #
36
+ # @param method [String] HTTP method, uppercased (e.g. "PUT")
37
+ # @param path [String] URI path starting with "/" (e.g. "/bucket/key")
38
+ # @param query [Hash{String=>String,Array<String>}] query params
39
+ # @param headers [Hash] existing request headers (case-insensitive keys)
40
+ # @param body [String, nil] request body — may be nil for GET/HEAD/DELETE
41
+ # @param now [Time] override for testing
42
+ def sign_headers(method:, path:, query: {}, headers: {}, body: nil, now: Time.now.utc)
43
+ datetime = now.strftime("%Y%m%dT%H%M%SZ")
44
+ date = datetime[0, 8]
45
+ content_sha = body ? sha256_hex(body) : EMPTY_SHA256
46
+
47
+ working_headers = headers.dup
48
+ working_headers["X-Tos-Date"] = datetime
49
+ working_headers["X-Tos-Content-Sha256"] = content_sha
50
+ working_headers["X-Tos-Security-Token"] = @credentials.security_token if @credentials.security_token
51
+
52
+ signed_headers = filter_signed_headers(working_headers)
53
+
54
+ canonical_request = build_canonical_request(
55
+ method: method.to_s.upcase,
56
+ path: path,
57
+ query: query,
58
+ signed_headers: signed_headers,
59
+ content_sha: content_sha
60
+ )
61
+
62
+ credential_scope = "#{date}/#{@region}/#{SERVICE}/#{REQUEST}"
63
+ string_to_sign = [ALGORITHM, datetime, credential_scope, sha256_hex(canonical_request)].join("\n")
64
+
65
+ signing_key = derive_signing_key(date)
66
+ signature = hmac_hex(signing_key, string_to_sign)
67
+
68
+ authorization = build_authorization_header(signed_headers, credential_scope, signature)
69
+ working_headers["Authorization"] = authorization
70
+
71
+ working_headers
72
+ end
73
+
74
+ # Build a presigned URL with all signing material in the query string.
75
+ # Returns a fully-qualified URL.
76
+ def presign(method:, host:, path:, query: {}, expires_in: 3600, now: Time.now.utc)
77
+ datetime = now.strftime("%Y%m%dT%H%M%SZ")
78
+ date = datetime[0, 8]
79
+ credential_scope = "#{date}/#{@region}/#{SERVICE}/#{REQUEST}"
80
+
81
+ query_with_sig = query.dup
82
+ query_with_sig["X-Tos-Algorithm"] = ALGORITHM
83
+ query_with_sig["X-Tos-Credential"] = "#{@credentials.access_key_id}/#{credential_scope}"
84
+ query_with_sig["X-Tos-Date"] = datetime
85
+ query_with_sig["X-Tos-Expires"] = expires_in.to_s
86
+ query_with_sig["X-Tos-SignedHeaders"] = ""
87
+ query_with_sig["X-Tos-Security-Token"] = @credentials.security_token if @credentials.security_token
88
+
89
+ canonical_request = build_canonical_request(
90
+ method: method.to_s.upcase,
91
+ path: path,
92
+ query: query_with_sig,
93
+ signed_headers: [],
94
+ content_sha: UNSIGNED_PAYLOAD
95
+ )
96
+
97
+ string_to_sign = [ALGORITHM, datetime, credential_scope, sha256_hex(canonical_request)].join("\n")
98
+ signing_key = derive_signing_key(date)
99
+ query_with_sig["X-Tos-Signature"] = hmac_hex(signing_key, string_to_sign)
100
+
101
+ "https://#{host}#{path}?#{encode_query(query_with_sig)}"
102
+ end
103
+
104
+ private
105
+
106
+ # Default policy mirrors the Go SDK: only `content-type` (lower-case) and
107
+ # any `x-tos-*` header is signed. `host` is intentionally NOT signed.
108
+ def filter_signed_headers(headers)
109
+ headers.each_with_object([]) do |(name, value), acc|
110
+ key = name.to_s.downcase
111
+ next unless key == "content-type" || key.start_with?("x-tos-")
112
+
113
+ acc << [key, normalize_value(value)]
114
+ end.sort_by(&:first)
115
+ end
116
+
117
+ def build_canonical_request(method:, path:, query:, signed_headers:, content_sha:)
118
+ canonical_headers = signed_headers.map { |k, v| "#{k}:#{v}\n" }.join
119
+ header_list = signed_headers.map(&:first).join(";")
120
+
121
+ [
122
+ method,
123
+ encode_path(path),
124
+ encode_query(query),
125
+ canonical_headers,
126
+ header_list,
127
+ content_sha
128
+ ].join("\n")
129
+ end
130
+
131
+ def build_authorization_header(signed_headers, credential_scope, signature)
132
+ header_list = signed_headers.map(&:first).join(";")
133
+ "#{ALGORITHM} Credential=#{@credentials.access_key_id}/#{credential_scope}," \
134
+ "SignedHeaders=#{header_list},Signature=#{signature}"
135
+ end
136
+
137
+ def derive_signing_key(date)
138
+ k_date = hmac(@credentials.secret_access_key, date)
139
+ k_region = hmac(k_date, @region)
140
+ k_service = hmac(k_region, SERVICE)
141
+ hmac(k_service, REQUEST)
142
+ end
143
+
144
+ def normalize_value(value)
145
+ Array(value).map { |v| v.to_s.split(/\s+/).join(" ") }.join(",")
146
+ end
147
+
148
+ # RFC 3986 percent-encoding for the URI path. Slashes are preserved.
149
+ def encode_path(path)
150
+ path.split("/", -1).map { |segment| uri_escape(segment) }.join("/")
151
+ end
152
+
153
+ # Sort by key, then by value, encode and join with `&`.
154
+ def encode_query(query)
155
+ pairs = []
156
+ query.each do |key, values|
157
+ Array(values).each do |value|
158
+ pairs << [uri_escape(key.to_s), uri_escape(value.to_s)]
159
+ end
160
+ end
161
+ pairs.sort.map { |k, v| "#{k}=#{v}" }.join("&")
162
+ end
163
+
164
+ def uri_escape(str)
165
+ # URI.encode_www_form_component encodes space as "+", which is wrong for
166
+ # SigV4. Use a manual escape that matches Go's url.QueryEscape rules
167
+ # (which percent-encodes everything except unreserved chars), but preserve
168
+ # nothing else.
169
+ str.b.gsub(/([^A-Za-z0-9\-_.~])/) { format("%%%02X", $1.ord) }
170
+ end
171
+
172
+ def sha256_hex(data)
173
+ OpenSSL::Digest::SHA256.hexdigest(data.to_s)
174
+ end
175
+
176
+ def hmac(key, data)
177
+ OpenSSL::HMAC.digest("SHA256", key, data)
178
+ end
179
+
180
+ def hmac_hex(key, data)
181
+ OpenSSL::HMAC.hexdigest("SHA256", key, data)
182
+ end
183
+ end
184
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TOS
4
+ VERSION = "0.1.0"
5
+ end
data/lib/tos.rb ADDED
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+
5
+ require_relative "tos/version"
6
+ require_relative "tos/error"
7
+ require_relative "tos/credentials"
8
+ require_relative "tos/signer"
9
+ require_relative "tos/response"
10
+ require_relative "tos/client"
11
+ require_relative "tos/bucket"
12
+
13
+ # A minimal Ruby SDK for Volcengine TOS (Torch Object Storage).
14
+ #
15
+ # client = TOS::Client.new(
16
+ # access_key_id: ENV["TOS_ACCESS_KEY_ID"],
17
+ # secret_access_key: ENV["TOS_SECRET_ACCESS_KEY"],
18
+ # region: "cn-beijing"
19
+ # )
20
+ # bucket = client.bucket("my-bucket")
21
+ # bucket.put_object("hello.txt", "world", content_type: "text/plain")
22
+ module TOS
23
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/tos/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "ve-tos-ruby-sdk"
7
+ spec.version = TOS::VERSION
8
+ spec.authors = ["Renny"]
9
+ spec.summary = "Ruby SDK for Volcengine TOS (Torch Object Storage)"
10
+ spec.description = "Ruby SDK for Volcengine TOS object storage. " \
11
+ "PutObject, GetObject (range), HeadObject, DeleteObject, " \
12
+ "DeleteMultipleObjects, ListObjectsV2, and presigned URLs."
13
+ spec.license = "Apache-2.0"
14
+ spec.required_ruby_version = ">= 2.7.0"
15
+
16
+ spec.files = Dir["lib/**/*.rb", "README.md", "LICENSE", "ve-tos-ruby-sdk.gemspec"]
17
+ spec.require_paths = ["lib"]
18
+
19
+ # rexml is no longer a default gem under Bundler-managed contexts.
20
+ spec.add_dependency "rexml", ">= 3.2"
21
+
22
+ spec.add_development_dependency "rspec", "~> 3.12"
23
+ spec.add_development_dependency "webmock", "~> 3.18"
24
+ end
metadata ADDED
@@ -0,0 +1,91 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ve-tos-ruby-sdk
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Renny
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: rexml
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '3.2'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '3.2'
26
+ - !ruby/object:Gem::Dependency
27
+ name: rspec
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - "~>"
31
+ - !ruby/object:Gem::Version
32
+ version: '3.12'
33
+ type: :development
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '3.12'
40
+ - !ruby/object:Gem::Dependency
41
+ name: webmock
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - "~>"
45
+ - !ruby/object:Gem::Version
46
+ version: '3.18'
47
+ type: :development
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - "~>"
52
+ - !ruby/object:Gem::Version
53
+ version: '3.18'
54
+ description: Ruby SDK for Volcengine TOS object storage. PutObject, GetObject (range),
55
+ HeadObject, DeleteObject, DeleteMultipleObjects, ListObjectsV2, and presigned URLs.
56
+ executables: []
57
+ extensions: []
58
+ extra_rdoc_files: []
59
+ files:
60
+ - LICENSE
61
+ - README.md
62
+ - lib/tos.rb
63
+ - lib/tos/bucket.rb
64
+ - lib/tos/client.rb
65
+ - lib/tos/credentials.rb
66
+ - lib/tos/error.rb
67
+ - lib/tos/response.rb
68
+ - lib/tos/signer.rb
69
+ - lib/tos/version.rb
70
+ - ve-tos-ruby-sdk.gemspec
71
+ licenses:
72
+ - Apache-2.0
73
+ metadata: {}
74
+ rdoc_options: []
75
+ require_paths:
76
+ - lib
77
+ required_ruby_version: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - ">="
80
+ - !ruby/object:Gem::Version
81
+ version: 2.7.0
82
+ required_rubygems_version: !ruby/object:Gem::Requirement
83
+ requirements:
84
+ - - ">="
85
+ - !ruby/object:Gem::Version
86
+ version: '0'
87
+ requirements: []
88
+ rubygems_version: 4.0.11
89
+ specification_version: 4
90
+ summary: Ruby SDK for Volcengine TOS (Torch Object Storage)
91
+ test_files: []