tanshuku 4.0.2 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 076e5ce40463d17a9fa6361a0e8a317fb15d1428300921e8527b6765a2f62ee8
4
- data.tar.gz: bd412ced4ce541d9b4896ea8382caeaf6ec9a4ea7cd8c33e3f4364c643b93538
3
+ metadata.gz: c1070edf493aaa656a9345d5c64959d27045ff7287235a5bb29d5aa1050b683f
4
+ data.tar.gz: f4d8284eea7a68b08c7b02dada4fc0e17808beaecba9a49a1c7c046156dd747a
5
5
  SHA512:
6
- metadata.gz: 1e1f3ad12c2f5d59c9536ea37a11018502391e455693cf75ea54b94cacee202a0247483978e4192be13886c28ccf67db380d528f6467894204db952858d2fbb5
7
- data.tar.gz: '07801692da343d445145619b9ac9c87895a1c0644c60864ac24bd2721a948558c644ea8354fa4e8ea254fe1b95d4ec8eef0d0fdbc3ab8617c697bebe3e6475d9'
6
+ metadata.gz: 49af2ab27b0e7591fc19a7c782e917b3e21848a9e8393fa47009dbbf501f01908326c76cb5d558f8f244df43ee70104920ea573fb963c6983daeb6561e7c8eef
7
+ data.tar.gz: b24bcfaa56d85865a7fe6687f2fdfc4cc6daab624e6dd947aa85bed598741dcf0ebe11956f2e187120cfffa456929494143d5690d9ce763c09e8e3d1ff13baee
data/README.md CHANGED
@@ -135,6 +135,80 @@ Tanshuku::Url.shorten("https://google.com/", namespace: "a") #=> "https://examp
135
135
  Tanshuku::Url.shorten("https://google.com/", namespace: "a") #=> "https://example.com/t/ab01cd23ef45gh67ij89"
136
136
  ```
137
137
 
138
+ #### Security considerations
139
+
140
+ ##### Shortening URLs that contain secrets
141
+
142
+ You can shorten URLs that contain secrets such as access tokens, but be aware of the following risks.
143
+
144
+ - Original URLs are stored in the `tanshuku_urls` table as plain text. Anyone who can read the database or its backups can see the secrets.
145
+ - Anyone who knows a shortened URL can access its original URL. Shortened URLs tend to spread through sharing and forwarding.
146
+ - When shortening a URL fails, the default [`config.exception_reporter`](https://kg8m.github.io/tanshuku/Tanshuku/Configuration.html#exception_reporter-instance_method) logs the original URL as is.
147
+
148
+ If you want to keep secrets out of your logs, configure `config.exception_reporter`. The following example filters query parameters of the original URL with your app’s `config.filter_parameters` and removes its fragment before logging it. If the URL can’t be parsed, it removes the query and the fragment instead.
149
+
150
+ ```rb
151
+ # config/initializers/tanshuku.rb
152
+ Tanshuku.configure do |config|
153
+ config.exception_reporter =
154
+ lambda { |exception:, original_url:|
155
+ filtered_url =
156
+ begin
157
+ parameter_filter = ActiveSupport::ParameterFilter.new(Rails.application.config.filter_parameters)
158
+ uri = Addressable::URI.parse(original_url)
159
+
160
+ if uri.query
161
+ params = parameter_filter.filter(Rack::Utils.parse_nested_query(uri.query))
162
+ uri.query = Rack::Utils.build_nested_query(params)
163
+ end
164
+
165
+ # Fragments might also contain secrets, e.g., `#access_token=...`.
166
+ uri.fragment = nil
167
+ uri.to_s
168
+ # Shortening a URL often fails because the URL is invalid.
169
+ rescue StandardError
170
+ original_url&.sub(/[?#].*/m, "")
171
+ end
172
+
173
+ # Log only the exception’s class because its message might contain the original URL.
174
+ Rails.logger.warn("Failed to shorten a URL: #{exception.class} for #{filtered_url.inspect}")
175
+ }
176
+ end
177
+ ```
178
+
179
+ ##### Shortening URLs from user input
180
+
181
+ Tanshuku redirects users to original URLs without checking their hosts, i.e., it redirects to any host. [`config.url_pattern`](https://kg8m.github.io/tanshuku/Tanshuku/Configuration.html#url_pattern-instance_method) only checks the format of URLs and doesn’t ensure that their destinations are safe. For example, both `https://evil.example/` and `//evil.example/` match the default pattern.
182
+
183
+ So if you shorten URLs from user input, check them in your Rails app, e.g., with an allowlist of hosts. Otherwise, the following risks arise.
184
+
185
+ - Attackers can abuse your shortened URLs as open redirects. They can lead users to phishing sites with URLs of your trusted domain.
186
+ - Your domain might be added to blocklists of spam filters or safe browsing services. Then emails containing your legitimate shortened URLs might not be delivered, and browsers might show warnings when users access them.
187
+
188
+ The following example shortens a URL only if it is an absolute path in your app, or if its scheme is HTTP(S) and its host is allowed.
189
+
190
+ ```rb
191
+ # Checks whether a URL can be shortened.
192
+ module ShortenableUrl
193
+ ALLOWED_HOSTS = %w[example.com www.example.com].freeze
194
+
195
+ # Returns true if the URL is an absolute path or an HTTP(S) URL with an allowed host.
196
+ def self.allowed?(url)
197
+ uri = Addressable::URI.parse(url)
198
+
199
+ if uri.host
200
+ %w[http https].include?(uri.normalized_scheme) && ALLOWED_HOSTS.include?(uri.normalized_host)
201
+ else
202
+ uri.scheme.nil? && uri.path.start_with?("/")
203
+ end
204
+ rescue Addressable::URI::InvalidURIError
205
+ false
206
+ end
207
+ end
208
+
209
+ Tanshuku::Url.shorten(user_input) if ShortenableUrl.allowed?(user_input)
210
+ ```
211
+
138
212
  #### More information
139
213
 
140
214
  cf. [`Tanshuku::Url.shorten`’s API documentation](https://kg8m.github.io/tanshuku/Tanshuku/Url.html#shorten-class_method)
@@ -197,4 +271,5 @@ A. Does Tanshuku have some missing features? Please [create an issue](https://gi
197
271
  1. Make your repository fresh
198
272
  1. `bump current` and confirm the current version
199
273
  1. `bump patch`, `bump minor`, or `bump major`
200
- 1. `rake release`
274
+ 1. `gem_push=no rake release` to create a tag and push it with the branch
275
+ 1. Approve the triggered [“Create a Release” workflow](.github/workflows/create-release.yml), which pushes the gem to RubyGems.org and creates a GitHub Release
@@ -1,15 +1,15 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Tanshuku
4
- # A Rails controller class for finding a {Tanshuku::Url} record and redirecting to its shortened URL.
4
+ # A Rails controller class for finding a {Tanshuku::Url} record and redirecting to its original URL.
5
5
  class UrlsController < ActionController::API
6
- # Finds a {Tanshuku::Url} record from the given +key+ parameter and redirects to its shortened URL.
6
+ # Finds a {Tanshuku::Url} record from the given +key+ parameter and redirects to its original URL.
7
7
  #
8
8
  # @return [void]
9
9
  #
10
- # @raise [ActiveRecord::NotFound] If no {Tanshuku::Url} record is found for the given +key+.
10
+ # @raise [ActiveRecord::RecordNotFound] If no {Tanshuku::Url} record is found for the given +key+.
11
11
  def show
12
- url = Url.find_by!(key: params[:key])
12
+ url = Url.find_by!(key: params.expect(:key))
13
13
  redirect_to url.url, status: :moved_permanently, allow_other_host: true
14
14
  end
15
15
  end
@@ -7,7 +7,7 @@ require "rack"
7
7
  module Tanshuku
8
8
  # rubocop:disable Rails/ApplicationRecord
9
9
  #
10
- # An +ActiveRecord::Base+ inherited class for a shortened URL. This class also have some logics for shortening URLs.
10
+ # An +ActiveRecord::Base+ inherited class for a shortened URL. This class also has some logic for shortening URLs.
11
11
  class Url < ActiveRecord::Base
12
12
  # @!attribute [rw] url
13
13
  # @return [String] Original, i.e., non-shortened, URL of the record.
@@ -29,6 +29,10 @@ module Tanshuku
29
29
  validates :url, length: { maximum: proc { Tanshuku.config.max_url_length } }
30
30
  validates :url, format: { with: proc { Tanshuku.config.url_pattern } }, allow_blank: true
31
31
 
32
+ # Don’t allow dots in keys because a dot in a path is treated as a separator of the format by the routing, e.g.,
33
+ # `/t/abc.json` is routed to the key `abc` with the format `json`.
34
+ validates :key, format: { without: /\./ }, allow_blank: true
35
+
32
36
  # Don’t validate uniqueness of unique attributes. Raise ActiveRecord::RecordNotUnique instead if the attributes get
33
37
  # duplicated. Then rescue the exception and try to retry.
34
38
  # validates :url, :hashed_url, :key, uniqueness: true
@@ -44,7 +48,7 @@ module Tanshuku
44
48
  # +shorten("https://google.com")+ have the same result.
45
49
  #
46
50
  # @param original_url [String] The original, i.e., non-shortened, URL.
47
- # @param namespace [String] A namespace for shorteting URL. Shortened URLs are unique in namespaces.
51
+ # @param namespace [String] A namespace for shortening the URL. Shortened URLs are unique in namespaces.
48
52
  # @param url_options [Hash] An option for Rails’ +url_for+.
49
53
  #
50
54
  # @return [String] A shortened URL if succeeded to shorten the original URL.
@@ -81,14 +85,17 @@ module Tanshuku
81
85
 
82
86
  begin
83
87
  transaction do
88
+ # Find an existing record first because the URL is often already shortened. Otherwise, try to create a new
89
+ # record. It also handles the race condition of creating records for the same URL.
84
90
  record =
85
- create_or_find_by!(hashed_url: hash_url(url, namespace:)) do |r|
91
+ find_or_create_by!(hashed_url: hash_url(url, namespace:)) do |r|
86
92
  r.attributes = { url:, key: generate_key }
87
93
  end
88
94
 
89
95
  record.shortened_url(url_options)
90
96
  end
91
- # ActiveRecord::RecordNotFound is raised when the key is duplicated.
97
+ # ActiveRecord::RecordNotFound is raised when the key is duplicated: creating a record raises
98
+ # ActiveRecord::RecordNotUnique, and then no record is found for the hashed URL.
92
99
  rescue ActiveRecord::RecordNotFound => e
93
100
  if retries < 10
94
101
  retries += 1
@@ -169,9 +176,11 @@ module Tanshuku
169
176
  # @return [String] A shortened URL.
170
177
  #
171
178
  # @note
172
- # In Rails 8.0 or later, this method loads the routes before calling +url_for+ as Tanshuku depends on them.
179
+ # This method loads the routes before calling +url_for+ as Tanshuku depends on them.
173
180
  # cf. https://github.com/rails/rails/pull/52353
174
181
  def shortened_url(url_options = {})
182
+ Rails.application.reload_routes_unless_loaded
183
+
175
184
  url_options = url_options.symbolize_keys
176
185
  url_options[:controller] = "tanshuku/urls"
177
186
  url_options[:action] = :show
@@ -179,25 +188,6 @@ module Tanshuku
179
188
 
180
189
  Tanshuku::Engine.routes.url_for(url_options)
181
190
  end
182
-
183
- case Gem::Version.new(Rails.version)
184
- when "7.0"..."8.0"
185
- # Don’t define `#shortened_url` in this branch because YARD doesn’t recognize the method.
186
- else
187
- # Overwrite the `#shortened_url` in Rails 8.0 or later.
188
- # rubocop:disable Lint/DuplicateMethods
189
- def shortened_url(url_options = {})
190
- Rails.application.reload_routes_unless_loaded
191
-
192
- url_options = url_options.symbolize_keys
193
- url_options[:controller] = "tanshuku/urls"
194
- url_options[:action] = :show
195
- url_options[:key] = key
196
-
197
- Tanshuku::Engine.routes.url_for(url_options)
198
- end
199
- # rubocop:enable Lint/DuplicateMethods
200
- end
201
191
  end
202
192
  # rubocop:enable Rails/ApplicationRecord
203
193
  end
@@ -6,6 +6,8 @@ en:
6
6
  attributes:
7
7
  url:
8
8
  invalid: should start with https://, http://, or /
9
+ key:
10
+ invalid: should not contain dots (.)
9
11
  models:
10
12
  tanshuku/url: Shortened URL
11
13
  attributes:
@@ -6,6 +6,8 @@ ja:
6
6
  attributes:
7
7
  url:
8
8
  invalid: は https://、 http://、 / のいずれかで始まる必要があります
9
+ key:
10
+ invalid: に .(ドット)を含めることはできません
9
11
  models:
10
12
  tanshuku/url: 短縮URL
11
13
  attributes:
@@ -31,9 +31,8 @@ module Tanshuku
31
31
 
32
32
  copy_file old_filepath, new_filepath
33
33
 
34
- # rubocop:disable Lint/NumberConversion
34
+ # rubocop:disable-next Lint/NumberConversion
35
35
  gsub_file new_filepath, "Rails::VERSION::STRING.to_f", Rails::VERSION::STRING.to_f.to_s
36
- # rubocop:enable Lint/NumberConversion
37
36
  end
38
37
  end
39
38
  end
@@ -140,6 +140,10 @@ module Tanshuku
140
140
  # A class, module, or object that responds to +#call+ without any arguments.
141
141
  # @return [void] If you set an invalid object.
142
142
  #
143
+ # @note
144
+ # Generated keys should not contain dots (+.+) because a dot in a path is treated as a separator of the format,
145
+ # e.g., +/t/abc.json+ is routed to the key +abc+. Shortening a URL fails if a generated key contains dots.
146
+ #
143
147
  # @note The example below means that unique keys for shortened URLs are generated by +SecureRandom.uuid+.
144
148
  #
145
149
  # @example
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Tanshuku
4
- VERSION = "4.0.2"
4
+ VERSION = "5.0.1"
5
5
  end
data/lib/tanshuku.rb CHANGED
@@ -15,9 +15,8 @@ module Tanshuku
15
15
  # {Tanshuku.configure} for configuration.
16
16
  def self.config
17
17
  # Disable this cop but use `Tanshuku::Configuration#configure` for thread-safety.
18
- # rubocop:disable ThreadSafety/ClassInstanceVariable
18
+ # rubocop:disable-next ThreadSafety/ClassInstanceVariable
19
19
  @config ||= Configuration.new
20
- # rubocop:enable ThreadSafety/ClassInstanceVariable
21
20
  end
22
21
 
23
22
  # Configures Tanshuku.
@@ -1,5 +1,5 @@
1
1
  module Tanshuku
2
2
  class UrlsController < ActionController::API
3
- def show: -> void
3
+ def show: () -> void
4
4
  end
5
5
  end
@@ -107,7 +107,7 @@ module Tanshuku
107
107
  def self.find_by_url: (String url, ?namespace: String) -> Tanshuku::Url?
108
108
  def self.normalize_url: (String url) -> String
109
109
  def self.hash_url: (String url, ?namespace: String) -> String
110
- def self.generate_key: -> String
110
+ def self.generate_key: () -> String
111
111
  def self.report_exception: (exception: Exception, original_url: String) -> void
112
112
  def shortened_url: (?Hash[String | Symbol, untyped] url_options) -> String
113
113
  end
@@ -1,2 +1,3 @@
1
- class CreateTanshukuUrls < ActiveRecord::Migration::Compatibility::V7_0
1
+ class CreateTanshukuUrls < ActiveRecord::Migration::Current
2
+ def change: () -> void
2
3
  end
@@ -1,4 +1,6 @@
1
1
  module Tanshuku
2
2
  class InstallGenerator < Rails::Generators::Base
3
+ def copy_initializer_file: () -> void
4
+ def copy_migration_file: () -> void
3
5
  end
4
6
  end
@@ -5,7 +5,7 @@ module Tanshuku
5
5
  end
6
6
 
7
7
  interface _KeyGenerator
8
- def call: -> String
8
+ def call: () -> String
9
9
  end
10
10
 
11
11
  interface _ExceptionReporter
@@ -25,7 +25,7 @@ module Tanshuku
25
25
  attr_accessor exception_reporter (): _ExceptionReporter
26
26
 
27
27
  def initialize: (*bot noname) -> void
28
- def configure: { (Configuration) -> void } -> void
28
+ def configure: () { (Configuration) -> void } -> void
29
29
 
30
30
  module DefaultUrlHasher
31
31
  extend _UrlHasher
data/sig/lib/tanshuku.rbs CHANGED
@@ -1,6 +1,6 @@
1
1
  module Tanshuku
2
2
  self.@config: Configuration
3
3
 
4
- def self.config: -> Configuration
5
- def self.configure: { (Configuration config) -> void } -> void
4
+ def self.config: () -> Configuration
5
+ def self.configure: () { (Configuration config) -> void } -> void
6
6
  end
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: tanshuku
3
3
  version: !ruby/object:Gem::Version
4
- version: 4.0.2
4
+ version: 5.0.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - kg8m
8
8
  bindir: bin
9
9
  cert_chain: []
10
- date: 2024-12-28 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
13
  name: addressable
@@ -15,28 +15,28 @@ dependencies:
15
15
  requirements:
16
16
  - - ">="
17
17
  - !ruby/object:Gem::Version
18
- version: '2.4'
18
+ version: '2.8'
19
19
  type: :runtime
20
20
  prerelease: false
21
21
  version_requirements: !ruby/object:Gem::Requirement
22
22
  requirements:
23
23
  - - ">="
24
24
  - !ruby/object:Gem::Version
25
- version: '2.4'
25
+ version: '2.8'
26
26
  - !ruby/object:Gem::Dependency
27
27
  name: rails
28
28
  requirement: !ruby/object:Gem::Requirement
29
29
  requirements:
30
30
  - - ">="
31
31
  - !ruby/object:Gem::Version
32
- version: '7.0'
32
+ version: '8.0'
33
33
  type: :runtime
34
34
  prerelease: false
35
35
  version_requirements: !ruby/object:Gem::Requirement
36
36
  requirements:
37
37
  - - ">="
38
38
  - !ruby/object:Gem::Version
39
- version: '7.0'
39
+ version: '8.0'
40
40
  description: Tanshuku is a simple and performance aware Rails engine for shortening
41
41
  URLs. Tanshuku generates a shortened URL per a normalized original URL. Tanshuku
42
42
  redirects from a shortened URL to its corresponding original URL.
@@ -84,14 +84,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
84
84
  requirements:
85
85
  - - ">="
86
86
  - !ruby/object:Gem::Version
87
- version: '3.2'
87
+ version: '3.3'
88
88
  required_rubygems_version: !ruby/object:Gem::Requirement
89
89
  requirements:
90
90
  - - ">="
91
91
  - !ruby/object:Gem::Version
92
92
  version: '0'
93
93
  requirements: []
94
- rubygems_version: 3.6.2
94
+ rubygems_version: 4.0.20
95
95
  specification_version: 4
96
96
  summary: Tanshuku is a simple and performance aware Rails engine for shortening URLs.
97
97
  test_files: []