copy_tuner_client 2.5.1 → 3.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: 629e99af532182c8f167b2a5acd7f5a7561147bfc97a317d13ac0d345910297e
4
- data.tar.gz: 3687a78229935a75a6af2e81567f6db49a215badbf2b09574fa643f8b6ad9a3d
3
+ metadata.gz: 56cadc4d0af47b6c281636ddcb073ff73893286255dd01e5e2dd10cd3ba95d5c
4
+ data.tar.gz: 7d85dbdc9264cf68f1caaa246c3cacd5a3de905bdaa879b546c639f0f39d4f87
5
5
  SHA512:
6
- metadata.gz: 79f2ca4118bc85c447d49f540ce1bfea082d47bb295d82b1b69a481685f7467d7f9afdec7ae87397d482f4953fef0e396116c8899a4ba0866db4d95b4d61d76e
7
- data.tar.gz: 7a4df56a0368c1e0f25478949ebbb48f13582b0b1895fbdcb78bd776bc23edfe4391c59648c254c998a6ebd1327bdb0afb8c654149aa7307ae03b871210736fd
6
+ metadata.gz: 0416246174f3dc6672e59f7ac513466066b2625568ea1b2b7017f02e5390bd1b9aff382c6a0334cfe17190699efcdc8b7366fbd2e09806723afba3a585057532
7
+ data.tar.gz: f0c1f258bcbb60b024b13a9cc0024bc872d17bd3d5e116bda7d55e3dabed5dc6294a13671a786acf8332a11781caf131053d877bd7a1c0f7da6c7dd6e0e59400
data/.rubocop.yml CHANGED
@@ -7,8 +7,7 @@ plugins:
7
7
  - rubocop-rake
8
8
  - rubocop-rspec
9
9
 
10
- # .ruby-version が RuboCop 未対応の新しい Ruby を指すと解析が落ちるため、
11
- # サポート最低バージョンを明示する
10
+ # ローカルの Ruby(mise で latest)ではなく、gemspec のサポート最低バージョンを基準に解析する
12
11
  # rubocop-rails は Rails プロジェクトではないため意図的に読み込まない
13
12
  AllCops:
14
13
  TargetRubyVersion: 3.3
data/README.md CHANGED
@@ -17,6 +17,8 @@ Create config/initializers/copy_tuner.rb
17
17
  CopyTunerClient.configure do |config|
18
18
  config.api_key = 'YOUR-API-KEY'
19
19
  config.project_id = 77
20
+ # 必須。プロジェクト設定画面の「S3パストークン」の値(翻訳の download にのみ使われる)
21
+ config.s3_path_token = 'YOUR-S3-PATH-TOKEN'
20
22
  config.host = 'COPY-TUNER-HOST-NAME'
21
23
 
22
24
  # I18n keys and messages will be sent to server if the locale matches
data/UPGRADING.md CHANGED
@@ -1,3 +1,47 @@
1
+ # v2 から v3 へのアップグレードガイド
2
+
3
+ CopyTuner Ruby クライアント gem を **v2.x 系から v3.0.0** へ上げる際の移行手順です。
4
+
5
+ ## 変更点早見表
6
+
7
+ | 区分 | 設定 / API | 対応 | 影響箇所 |
8
+ | --- | --- | --- | --- |
9
+ | 破壊的変更 | `config.s3_path_token` | **必須化**。未設定(nil / 空文字)だと起動時に `ArgumentError`。`api_key` へのフォールバックはなし | initializer |
10
+ | 破壊的変更 | download 失敗時の例外 | S3 からの download で 403 / 404 になると `InvalidS3PathToken` が発生。`InvalidCredential` で rescue 推奨 | 例外を rescue しているコード(あれば) |
11
+
12
+ ## 1. `config.s3_path_token` が必須になりました
13
+
14
+ 翻訳の download(S3)のパスにだけ `s3_path_token` を使います。upload / deploy は従来どおり `api_key` を使います。
15
+
16
+ ```ruby
17
+ CopyTunerClient.configure do |config|
18
+ config.api_key = 'YOUR-API-KEY'
19
+ config.s3_path_token = 'YOUR-S3-PATH-TOKEN' # プロジェクト設定画面の「S3パストークン」
20
+ config.project_id = 77
21
+ end
22
+ ```
23
+
24
+ 未設定のまま起動すると次の例外で失敗します。
25
+
26
+ ```
27
+ ArgumentError: s3_path_token is required
28
+ ```
29
+
30
+ ## 2. 例外クラスの変更
31
+
32
+ ```
33
+ StandardError
34
+ └─ InvalidCredential ← Poller はこれを rescue してポーリングを中止
35
+ ├─ InvalidApiKey upload / deploy の 404
36
+ └─ InvalidS3PathToken download の 403 / 404
37
+ ```
38
+
39
+ - 本番の S3 / CloudFront は存在しないパスに 403 を返すため、download の 403 / 404 はどちらも `InvalidS3PathToken` になります(従来の download は `ConnectionError` や `InvalidApiKey` になっていました)。
40
+ - `InvalidS3PathToken` のメッセージにトークン値は含まれません(例: `Invalid s3_path_token (403)`)。
41
+ - `InvalidApiKey` を rescue しているコードは、download の失敗も拾うなら `InvalidCredential` に変更してください。
42
+
43
+ ---
44
+
1
45
  # v1 から v2 へのアップグレードガイド
2
46
 
3
47
  CopyTuner Ruby クライアント gem を **v1.5.0 系から v2.0.0** へ上げる際の移行手順です。
@@ -26,7 +26,8 @@ module CopyTunerClient
26
26
 
27
27
  # Usually instantiated from {Configuration#apply}. Copies options.
28
28
  # @param options [Hash]
29
- # @option options [String] :api_key API key of the project to connect to
29
+ # @option options [String] :api_key API key of the project to connect to (upload / deploy)
30
+ # @option options [String] :s3_path_token token used in the S3 path (download)
30
31
  # @option options [Fixnum] :port the port to connect to
31
32
  # @option options [Boolean] :public whether to download draft or published content
32
33
  # @option options [Fixnum] :http_read_timeout how long to wait before timing out when reading data from the socket
@@ -39,7 +40,7 @@ module CopyTunerClient
39
40
  @downloaded_blurbs = {}
40
41
 
41
42
  %i[
42
- api_key host port public http_read_timeout
43
+ api_key s3_path_token host port public http_read_timeout
43
44
  http_open_timeout secure logger ca_file s3_host download_cache_dir
44
45
  ].each do |option|
45
46
  instance_variable_set("@#{option}", options[option])
@@ -61,12 +62,13 @@ module CopyTunerClient
61
62
  # @raise [ConnectionError] if the connection fails
62
63
  def download(cache_fallback: false)
63
64
  connect(s3_host) do |http|
64
- request = Net::HTTP::Get.new(uri(download_resource))
65
+ request = Net::HTTP::Get.new(download_uri)
65
66
  request['If-None-Match'] = @etag
66
67
  log('Start downloading translations')
67
68
  t = Time.now
68
69
  response = http.request(request)
69
70
  t_ms = ((Time.now - t) * 1000).to_i
71
+ check_s3_path_token(response)
70
72
  downloaded = check(response)
71
73
  if downloaded
72
74
  # NOTE: Net::HTTPではgzipが透過的に扱われるため正確なファイルサイズや速度をログに出すのは難しい
@@ -109,6 +111,7 @@ module CopyTunerClient
109
111
  attr_reader :host,
110
112
  :port,
111
113
  :api_key,
114
+ :s3_path_token,
112
115
  :http_read_timeout,
113
116
  :http_open_timeout,
114
117
  :secure,
@@ -124,6 +127,10 @@ module CopyTunerClient
124
127
  "/api/v2/projects/#{api_key}/#{resource}"
125
128
  end
126
129
 
130
+ def download_uri
131
+ "/api/v2/projects/#{s3_path_token}/#{download_resource}"
132
+ end
133
+
127
134
  def download_resource
128
135
  if public?
129
136
  'published_blurbs.json'
@@ -162,6 +169,13 @@ module CopyTunerClient
162
169
  end
163
170
  end
164
171
 
172
+ # S3/CloudFront は存在しないパスに 403 を返すため 404 と同様に扱う。メッセージにトークン値は含めない
173
+ def check_s3_path_token(response)
174
+ return unless response.is_a?(Net::HTTPNotFound) || response.is_a?(Net::HTTPForbidden)
175
+
176
+ raise InvalidS3PathToken, "Invalid s3_path_token (#{response.code})"
177
+ end
178
+
165
179
  def check(response)
166
180
  case response
167
181
  when Net::HTTPNotFound
@@ -13,7 +13,7 @@ module CopyTunerClient
13
13
  class Configuration # rubocop:disable Metrics/ClassLength
14
14
  # These options will be present in the Hash returned by {#to_hash}.
15
15
  OPTIONS = %i[
16
- api_key development_environments environment_name host
16
+ api_key s3_path_token development_environments environment_name host
17
17
  http_open_timeout http_read_timeout client_name client_url
18
18
  client_version port protocol proxy_host proxy_pass
19
19
  proxy_port proxy_user secure polling_delay sync_interval
@@ -156,6 +156,9 @@ module CopyTunerClient
156
156
  # @return [Integer] The project id
157
157
  attr_accessor :project_id
158
158
 
159
+ # @return [String] The token used in the S3 path when downloading translations (required)
160
+ attr_accessor :s3_path_token
161
+
159
162
  # @return [Pathname] The directory to cache downloaded files
160
163
  attr_accessor :download_cache_dir
161
164
 
@@ -183,6 +186,7 @@ module CopyTunerClient
183
186
  self.ignored_key_handler = ->(e) { raise e }
184
187
  self.local_first_key_regexp = nil
185
188
  self.project_id = nil
189
+ self.s3_path_token = nil
186
190
  self.download_cache_dir = Pathname.new(Dir.pwd).join('tmp', 'cache', 'copy_tuner_client')
187
191
  self.middleware_position = default_middleware_position
188
192
 
@@ -258,6 +262,7 @@ module CopyTunerClient
258
262
  def apply # rubocop:disable Metrics/AbcSize
259
263
  # NOTE: project_id は必須。未設定なら apply 時点で明示的に失敗させる
260
264
  validate_project_id!
265
+ validate_s3_path_token!
261
266
 
262
267
  self.locales ||= default_locales
263
268
 
@@ -422,6 +427,12 @@ module CopyTunerClient
422
427
  raise ArgumentError, 'project_id is required' if project_id.nil?
423
428
  end
424
429
 
430
+ # s3_path_token は必須。api_key へのフォールバックはしない
431
+ # (設定漏れを gem 更新時に起動で検知し、api_key のローテーションと独立に扱えるようにするため)。
432
+ def validate_s3_path_token!
433
+ raise ArgumentError, 's3_path_token is required' if s3_path_token.nil? || s3_path_token.empty?
434
+ end
435
+
425
436
  def default_port
426
437
  if secure?
427
438
  443
@@ -7,6 +7,31 @@ module CopyTunerClient
7
7
  # 「この描画の出力が middleware を通るか」で判定するため、middleware が env にこの印を立てる。
8
8
  ENV_KEY = 'copy_tuner.copyray_injectable'.freeze
9
9
 
10
+ # NOTE: HTML 以外の経路(メール本文・render :json・CSV/PDF など)ではマーカーが文字列として
11
+ # 出力に混入するため注入しない。判定には controller.request.format を使い、@current_template.format /
12
+ # lookup_context.formats のような ActionView の内部実装には依存させない(Rails バージョン間で壊れうるため)。
13
+ def self.injectable?(controller)
14
+ return false if CopyTunerClient.configuration.disable_copyray_comment_injection
15
+ return false if controller.nil?
16
+
17
+ # NOTE: mailer は request を持たず request.format で判定できない。かつメール本文への
18
+ # マーカー混入は実害が大きいため、controller の型で明示除外する。
19
+ return false if defined?(ActionMailer::Base) && controller.is_a?(ActionMailer::Base)
20
+
21
+ rewritable_request?(controller.request)
22
+ end
23
+
24
+ def self.rewritable_request?(request)
25
+ # NOTE: format が html でも出力が CopyrayMiddleware を通らない経路(ApplicationController.renderer や
26
+ # render_to_string)ではマーカーが除去されずに残るため、middleware が立てた印がある場合に限り注入する。
27
+ return false unless request&.env&.[](ENV_KEY)
28
+
29
+ # NOTE: middleware を通っても render json: などは rewritable? に弾かれ書き換えられないため、
30
+ # format が html でない経路には注入しない。
31
+ request.format&.html? || false
32
+ end
33
+ private_class_method :rewritable_request?
34
+
10
35
  # This:
11
36
  # message
12
37
  # Becomes:
@@ -84,7 +84,7 @@ module CopyTunerClient
84
84
  end
85
85
 
86
86
  def rewritable?(status, headers)
87
- # NOTE: マーカーの注入側(copyray_injectable?)はステータスを見ないので、除去側もステータスで絞らない
87
+ # NOTE: マーカーの注入側(Copyray.injectable?)はステータスを見ないので、除去側もステータスで絞らない
88
88
  # (絞るとリダイレクトやエラーページ(429 など)でマーカーが画面に露出する)。
89
89
  # ボディを持たないステータスは書き換えで Content-Length が付くと Rack の仕様違反になるので除外する。
90
90
  !Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.key?(status) &&
@@ -5,9 +5,16 @@ module CopyTunerClient
5
5
  class ConnectionError < StandardError
6
6
  end
7
7
 
8
- # Raised when the client is configured with an api key that the CopyTuner
9
- # server does not recognize. Polling is aborted when this error is raised.
10
- class InvalidApiKey < StandardError
8
+ # 設定された認証情報(api_key / s3_path_token)が拒否されたことを表す例外の基底クラス
9
+ class InvalidCredential < StandardError
10
+ end
11
+
12
+ # upload / deploy で api_key が CopyTuner サーバに認識されなかったときの例外
13
+ class InvalidApiKey < InvalidCredential
14
+ end
15
+
16
+ # download で s3_path_token のパスに S3 の JSON が見つからなかったときの例外
17
+ class InvalidS3PathToken < InvalidCredential
11
18
  end
12
19
 
13
20
  class IgnoredKey < StandardError
@@ -23,13 +23,9 @@ module CopyTunerClient
23
23
  # 使われる。HTML 以外の経路(メール本文・render :json・CSV/PDF など)ではコメントが文字列として
24
24
  # 出力に混入してしまうため、それらの経路には注入しない。default 引数による初期値登録は維持する
25
25
  # 必要があるため、このガードは初期値登録(上の I18n.t 呼び出し)より後に置く。
26
- return source unless copyray_injectable?
26
+ return source unless CopyTunerClient::Copyray.injectable?(controller)
27
27
 
28
- if CopyTunerClient.configuration.disable_copyray_comment_injection
29
- source
30
- else
31
- CopyTunerClient::Copyray.augment_template(source, copyray_scope_key(key, options))
32
- end
28
+ CopyTunerClient::Copyray.augment_template(source, copyray_scope_key(key, options))
33
29
  end
34
30
 
35
31
  def copyray_scope_key(key, options)
@@ -40,33 +36,6 @@ module CopyTunerClient
40
36
  I18n.normalize_keys(nil, key, options[:scope], separator).compact.join(separator)
41
37
  end
42
38
  private :copyray_scope_key
43
-
44
- # NOTE: HTML 以外の経路(メール本文・render :json・CSV/PDF など)ではマーカーが文字列として
45
- # 出力に混入するため注入しない。判定には controller.request.format を使い、@current_template.format /
46
- # lookup_context.formats のような ActionView の内部実装には依存させない(Rails バージョン間で壊れうるため)。
47
- def copyray_injectable?
48
- current_controller = controller
49
- return false if current_controller.nil?
50
-
51
- # NOTE: mailer は request を持たず request.format で判定できない。かつメール本文への
52
- # マーカー混入は実害が大きいため、controller の型で明示除外する。
53
- return false if defined?(ActionMailer::Base) && current_controller.is_a?(ActionMailer::Base)
54
-
55
- request = current_controller.request
56
- return false unless passes_copyray_middleware?(request)
57
-
58
- # NOTE: middleware を通っても render json: などは rewritable? に弾かれ書き換えられないため、
59
- # format が html でない経路には注入しない。
60
- request.format&.html? || false
61
- end
62
- private :copyray_injectable?
63
-
64
- # NOTE: format が html でも出力が CopyrayMiddleware を通らない経路(ApplicationController.renderer や
65
- # render_to_string)ではマーカーが除去されずに残るため、middleware が立てた印がある場合に限り注入する。
66
- def passes_copyray_middleware?(request)
67
- request&.env&.[](CopyTunerClient::Copyray::ENV_KEY)
68
- end
69
- private :passes_copyray_middleware?
70
39
  end
71
40
  private_constant :CopyrayCommentInjection
72
41
 
@@ -85,8 +85,10 @@ module CopyTunerClient
85
85
  timeout = polling_delay
86
86
  end
87
87
  logger.info 'stop poller thread'
88
- rescue InvalidApiKey => e
89
- # キーが不正なら張り直しても同じ結果になるので、以後の再開を止める
88
+ rescue InvalidCredential => e
89
+ # キーが不正なら張り直しても同じ結果になるので、以後の再開を止める。
90
+ # S3 の 403/404(InvalidS3PathToken)も同様に扱う: サーバはプロジェクト作成直後に JSON を書き出し、
91
+ # 削除するのはアーカイブ時だけなので、正しいトークンで再試行して回復するケースは実運用上ない
90
92
  @aborted = true
91
93
  logger.error(e.message)
92
94
  rescue StandardError => e
@@ -14,7 +14,9 @@ if defined?(SimpleForm)
14
14
  def label_translation_with_copyray_comment
15
15
  source = label_translation_without_copyray_comment
16
16
 
17
- if !CopyTunerClient.configuration.disable_copyray_comment_injection && object.class.respond_to?(:lookup_ancestors)
17
+ # NOTE: translate と同じ Copyray.injectable? で注入可否を決める。jQuery で画面を差し替える JS 応答などは
18
+ # CopyrayMiddleware の書き換え対象外で、注入するとマーカーが除去されずに画面に出るため。
19
+ if object.class.respond_to?(:lookup_ancestors) && CopyTunerClient::Copyray.injectable?(template.controller)
18
20
  attributes_scope = "#{object.class.i18n_scope}.attributes"
19
21
  defaults =
20
22
  object.class.lookup_ancestors.map do |klass|
@@ -1,6 +1,6 @@
1
1
  module CopyTunerClient
2
2
  # Client version
3
- VERSION = '2.5.1'.freeze
3
+ VERSION = '3.0.1'.freeze
4
4
 
5
5
  # API version being used to communicate with the server
6
6
  API_VERSION = '2.0'.freeze
@@ -48,6 +48,7 @@ module CopyTunerClient
48
48
  # @example
49
49
  # CopyTunerClient.configure do |config|
50
50
  # config.api_key = '1234567890abcdef'
51
+ # config.s3_path_token = 'abcdef1234567890' # required
51
52
  # config.host = 'your-copy-tuner-server.herokuapp.com'
52
53
  # config.secure = true
53
54
  # end
data/mise.toml CHANGED
@@ -1,3 +1,4 @@
1
1
  [tools]
2
+ ruby = "latest"
2
3
  node = "24"
3
4
  pnpm = "11.9.0"
@@ -10,6 +10,8 @@ describe 'CopyTunerClient' do
10
10
  def build_client(config = {})
11
11
  config[:logger] ||= FakeLogger.new
12
12
  config[:download_cache_dir] = download_cache_dir
13
+ # FakeCopyTunerApp.add_project は既定で api_key と同値の s3_path_token で登録するので、明示指定がなければ揃える
14
+ config[:s3_path_token] ||= config[:api_key]
13
15
  default_config = CopyTunerClient::Configuration.new.to_hash
14
16
  default_config[:s3_host] = 'copy-tuner.com'
15
17
  CopyTunerClient::Client.new(default_config.update(config))
@@ -99,15 +101,21 @@ describe 'CopyTunerClient' do
99
101
  expect { client.upload({}) }.to raise_error(CopyTunerClient::ConnectionError)
100
102
  end
101
103
 
102
- it 'ダウンロード時に404エラーが発生した場合はInvalidApiKeyになること' do
103
- client = build_client(api_key: 'bogus')
104
+ it 'ダウンロード時に存在しないパスで403エラーが発生した場合はトークン値を含まないInvalidS3PathTokenになること' do
105
+ client = build_client(api_key: 'xyz123', s3_path_token: 'bogus')
106
+ expect { client.download {} }
107
+ .to raise_error(CopyTunerClient::InvalidS3PathToken, 'Invalid s3_path_token (403)')
108
+ end
109
+
110
+ it 'ダウンロード時に404エラーが発生した場合もInvalidS3PathTokenになること' do
111
+ client = build_client(api_key: 'xyz123', s3_path_token: 'not_found')
104
112
  expect { client.download {} }
105
- .to raise_error(CopyTunerClient::InvalidApiKey)
113
+ .to raise_error(CopyTunerClient::InvalidS3PathToken, 'Invalid s3_path_token (404)')
106
114
  end
107
115
 
108
116
  it 'アップロード時に404エラーが発生した場合はInvalidApiKeyになること' do
109
117
  client = build_client(api_key: 'bogus')
110
- expect { client.upload({}) }.to raise_error(CopyTunerClient::InvalidApiKey)
118
+ expect { client.upload({}) }.to raise_error(CopyTunerClient::InvalidApiKey, 'Invalid API key: bogus')
111
119
  end
112
120
  end
113
121
 
@@ -240,6 +248,33 @@ describe 'CopyTunerClient' do
240
248
  expect(logger).to have_entry(:info, 'Deployed')
241
249
  end
242
250
 
251
+ describe 'api_key と s3_path_token が別値のプロジェクト' do
252
+ let!(:project) do
253
+ FakeCopyTunerApp.add_project('api-key-1', s3_path_token: 's3-token-1').tap do |p|
254
+ p.update('draft' => { 'key.one' => 'draft one' }, 'published' => { 'key.one' => 'published one' })
255
+ end
256
+ end
257
+
258
+ it 'ダウンロードは s3_path_token のパスから取得すること' do
259
+ client = build_client(api_key: 'api-key-1', s3_path_token: 's3-token-1')
260
+ downloaded = nil
261
+ client.download { |blurbs| downloaded = blurbs }
262
+ expect(downloaded).to eq('key.one' => 'published one')
263
+ end
264
+
265
+ it 'アップロードは s3_path_token を設定していても api_key のパスを使うこと' do
266
+ client = build_client(api_key: 'api-key-1', s3_path_token: 's3-token-1')
267
+ client.upload('key.two' => 'uploaded')
268
+ expect(project.reload.draft).to include('key.two' => 'uploaded')
269
+ end
270
+
271
+ it 'deploy は s3_path_token を設定していても api_key のパスを使うこと' do
272
+ client = build_client(api_key: 'api-key-1', s3_path_token: 's3-token-1')
273
+ client.deploy
274
+ expect(project.reload.published).to eq('key.one' => 'draft one')
275
+ end
276
+ end
277
+
243
278
  it 'deploy時にエラーが発生した場合は例外が発生すること' do
244
279
  expect { build_client.deploy }.to raise_error(CopyTunerClient::InvalidApiKey)
245
280
  end
@@ -19,6 +19,7 @@ shared_context 'stubbed configuration' do
19
19
  # NOTE: apply は project_id 必須になったため、未設定だと raise する。applied 系テストは
20
20
  # project_id 自体を検証しないので適当な値を補っておく
21
21
  configuration.project_id ||= 1
22
+ configuration.s3_path_token ||= 'token'
22
23
  apply
23
24
  end
24
25
  end
@@ -93,6 +94,7 @@ describe CopyTunerClient::Configuration do
93
94
  it { is_expected.to have_config_option(:port).overridable }
94
95
  it { is_expected.to have_config_option(:development_environments).overridable }
95
96
  it { is_expected.to have_config_option(:api_key).overridable }
97
+ it { is_expected.to have_config_option(:s3_path_token).overridable.default(nil) }
96
98
  it { is_expected.to have_config_option(:polling_delay).overridable.default(300) }
97
99
  it { is_expected.to have_config_option(:framework).overridable }
98
100
  it { is_expected.to have_config_option(:middleware).overridable }
@@ -330,6 +332,34 @@ describe CopyTunerClient::Configuration do
330
332
  end
331
333
  end
332
334
 
335
+ describe 's3_path_token の必須化' do
336
+ let(:config) do
337
+ config = described_class.new
338
+ config.api_key = 'abc123'
339
+ config.project_id = 1
340
+ config
341
+ end
342
+
343
+ it 's3_path_token が nil のとき apply が ArgumentError を出すこと' do
344
+ config.s3_path_token = nil
345
+ expect { config.apply }.to raise_error(ArgumentError, 's3_path_token is required')
346
+ end
347
+
348
+ it 's3_path_token が空文字のとき apply が ArgumentError を出すこと' do
349
+ config.s3_path_token = ''
350
+ expect { config.apply }.to raise_error(ArgumentError, 's3_path_token is required')
351
+ end
352
+
353
+ it 'api_key が設定されていても s3_path_token へフォールバックしないこと' do
354
+ expect(config.s3_path_token).to be_nil
355
+ end
356
+
357
+ it 's3_path_token が to_hash に含まれること' do
358
+ config.s3_path_token = 'token'
359
+ expect(config.to_hash[:s3_path_token]).to eq('token')
360
+ end
361
+ end
362
+
333
363
  context 'applied when testing' do
334
364
  it_behaves_like 'applied configuration' do
335
365
  it 'does not start the process guard' do
@@ -2,6 +2,68 @@ require 'spec_helper'
2
2
  require 'copy_tuner_client/copyray'
3
3
 
4
4
  describe CopyTunerClient::Copyray do
5
+ # NOTE: request.format で描画フォーマットを判定するため、format を差し替えられる
6
+ # 最小のフェイク request / controller を用意する。mailer 判定は controller の型で行う。
7
+ let(:format_class) do
8
+ Struct.new(:type) do
9
+ def html?
10
+ type == :html
11
+ end
12
+ end
13
+ end
14
+ let(:request_class) { Struct.new(:format, :env) }
15
+ let(:controller_class) { Struct.new(:request) }
16
+
17
+ # NOTE: CopyrayMiddleware を通るリクエストを再現するため、フラグ付きの env を持つ request を作る。
18
+ def injectable_request(format = :html)
19
+ request_class.new(format_class.new(format), { described_class::ENV_KEY => true })
20
+ end
21
+
22
+ describe '.injectable?' do
23
+ it 'request.format が html のとき true を返す' do
24
+ expect(described_class.injectable?(controller_class.new(injectable_request))).to be true
25
+ end
26
+
27
+ %i[json text csv pdf].each do |format|
28
+ it "request.format が :#{format} のとき false を返す" do
29
+ expect(described_class.injectable?(controller_class.new(injectable_request(format)))).to be false
30
+ end
31
+ end
32
+
33
+ it 'disable_copyray_comment_injection が有効なとき false を返す' do
34
+ CopyTunerClient.configuration.disable_copyray_comment_injection = true
35
+ expect(described_class.injectable?(controller_class.new(injectable_request))).to be false
36
+ end
37
+
38
+ it 'format が html でも env にフラグが無ければ false を返す' do
39
+ controller = controller_class.new(request_class.new(format_class.new(:html), {}))
40
+ expect(described_class.injectable?(controller)).to be false
41
+ end
42
+
43
+ it 'request.env が nil でも落ちずに false を返す' do
44
+ controller = controller_class.new(request_class.new(format_class.new(:html), nil))
45
+ expect(described_class.injectable?(controller)).to be false
46
+ end
47
+
48
+ it 'mailer から描画されたとき false を返す' do
49
+ stub_const('ActionMailer::Base', Class.new)
50
+ expect(described_class.injectable?(ActionMailer::Base.new)).to be false
51
+ end
52
+
53
+ it 'controller が nil のとき false を返す' do
54
+ expect(described_class.injectable?(nil)).to be false
55
+ end
56
+
57
+ it 'controller が request を持たないとき false を返す' do
58
+ expect(described_class.injectable?(controller_class.new(nil))).to be false
59
+ end
60
+
61
+ it 'ActionMailer が未ロードでも落ちない' do
62
+ hide_const('ActionMailer::Base') if defined?(ActionMailer::Base)
63
+ expect { described_class.injectable?(controller_class.new(injectable_request)) }.not_to raise_error
64
+ end
65
+ end
66
+
5
67
  describe '.augment_template' do
6
68
  subject(:augmented) { described_class.augment_template(source, key) }
7
69
 
@@ -82,51 +82,18 @@ describe CopyTunerClient::HelperExtension do
82
82
  expect(view.translate('views.foo', name: 'World')).to eq 'Hello, World'
83
83
  end
84
84
 
85
- context 'injection guard by rendering context' do
86
- it 'injects the marker when request.format is :html' do
85
+ # NOTE: 注入可否の判定そのものは Copyray.injectable? の spec で検証済みなので、
86
+ # ここでは translate がその結果に従うことだけを見る。
87
+ context '注入ガード' do
88
+ it 'Copyray.injectable? が true のときマーカーを注入する' do
89
+ allow(CopyTunerClient::Copyray).to receive(:injectable?).with(view.controller).and_return(true)
87
90
  expect(view.translate('some.key', name: 'World')).to eq '⟦CT:some.key⟧Hello, World'
88
91
  end
89
92
 
90
- %i[json text csv pdf].each do |format|
91
- it "does not inject the marker when request.format is :#{format}" do
92
- view.controller = controller_class.new(injectable_request(format))
93
- expect(view.translate('some.key', name: 'World')).to eq 'Hello, World'
94
- end
95
- end
96
-
97
- it 'format が html でも env にフラグが無ければ注入しない' do
98
- view.controller = controller_class.new(request_class.new(format_class.new(:html), {}))
99
- expect(view.translate('some.key', name: 'World')).to eq 'Hello, World'
100
- end
101
-
102
- it 'request.env が nil でも落ちずに注入しない' do
103
- view.controller = controller_class.new(request_class.new(format_class.new(:html), nil))
104
- expect(view.translate('some.key', name: 'World')).to eq 'Hello, World'
105
- end
106
- end
107
-
108
- context 'injection guard by controller' do
109
- it 'does not inject the marker when rendered by a mailer' do
110
- stub_const('ActionMailer::Base', Class.new)
111
- view.controller = ActionMailer::Base.new
93
+ it 'Copyray.injectable? が false のときマーカーを注入しない' do
94
+ allow(CopyTunerClient::Copyray).to receive(:injectable?).with(view.controller).and_return(false)
112
95
  expect(view.translate('some.key', name: 'World')).to eq 'Hello, World'
113
96
  end
114
-
115
- it 'does not inject the marker when controller is nil' do
116
- view.controller = nil
117
- expect(view.translate('some.key', name: 'World')).to eq 'Hello, World'
118
- end
119
-
120
- it 'does not inject the marker when the controller has no request' do
121
- view.controller = controller_class.new(nil)
122
- expect(view.translate('some.key', name: 'World')).to eq 'Hello, World'
123
- end
124
-
125
- it 'does not raise when ActionMailer is not loaded' do
126
- hide_const('ActionMailer::Base') if defined?(ActionMailer::Base)
127
- view.controller = controller_class.new(injectable_request)
128
- expect { view.translate('some.key', name: 'World') }.not_to raise_error
129
- end
130
97
  end
131
98
 
132
99
  # NOTE: マーカー注入を抑止する非 HTML 経路でも、default 引数による初期値登録(I18n.t 呼び出し)は
@@ -57,6 +57,21 @@ describe CopyTunerClient::Poller do
57
57
  expect(cache['test.key']).to be_nil
58
58
  end
59
59
 
60
+ it 's3_path_token が不正な場合はポーリングを停止すること' do
61
+ failure = 'Invalid s3_path_token (403)'
62
+ logger = FakeLogger.new
63
+
64
+ allow(cache).to receive(:download).and_raise(CopyTunerClient::InvalidS3PathToken.new(failure))
65
+ poller = build_poller(logger:)
66
+
67
+ cache['upload.key'] = 'upload'
68
+ poller.start
69
+ wait_for_next_sync
70
+
71
+ expect(logger).to have_entry(:error, failure)
72
+ expect(poller.stop).to be false
73
+ end
74
+
60
75
  it 'stops polling with an invalid api key' do
61
76
  failure = 'server is napping'
62
77
  logger = FakeLogger.new
@@ -0,0 +1,61 @@
1
+ require 'spec_helper'
2
+ require 'active_model'
3
+ require 'copy_tuner_client/copyray'
4
+
5
+ # NOTE: simple_form は開発依存に含めていないため、ラベル生成部品(SimpleForm::Components::Labels)を
6
+ # 最小のフェイクで用意し、そこへ拡張を読み込ませて注入ガードだけを検証する。
7
+ describe 'SimpleForm::Components::Labels の Copyray 拡張' do # rubocop:disable RSpec/DescribeClass
8
+ let(:labels_module) do
9
+ Module.new do
10
+ def label_translation
11
+ '体温'
12
+ end
13
+ end
14
+ end
15
+
16
+ let(:model_class) do
17
+ Class.new do
18
+ include ActiveModel::Model
19
+
20
+ def self.name
21
+ 'BodyTemperatureRecord'
22
+ end
23
+ end
24
+ end
25
+
26
+ let(:input_class) do
27
+ labels = labels_module
28
+ Struct.new(:object, :template) do
29
+ include labels
30
+
31
+ def reflection_or_attribute_name
32
+ :value
33
+ end
34
+ end
35
+ end
36
+
37
+ let(:controller) { Object.new }
38
+ let(:template) { Struct.new(:controller).new(controller) }
39
+
40
+ # NOTE: 注入可否の判定そのものは Copyray.injectable? の spec で検証済みなので、
41
+ # ここではその結果に従うことだけを見る。
42
+ def label_for
43
+ input_class.new(model_class.new, template).__send__(:label_translation)
44
+ end
45
+
46
+ before do
47
+ stub_const('SimpleForm::Components::Labels', labels_module)
48
+ allow(CopyTunerClient.configuration).to receive(:enable_middleware?).and_return(true)
49
+ load File.join(PROJECT_ROOT, 'lib', 'copy_tuner_client', 'simple_form_extention.rb')
50
+ end
51
+
52
+ it 'Copyray.injectable? が true のときはラベルにマーカーを注入する' do
53
+ allow(CopyTunerClient::Copyray).to receive(:injectable?).with(controller).and_return(true)
54
+ expect(label_for).to eq '⟦CT:activemodel.attributes.body_temperature_record.value⟧体温'
55
+ end
56
+
57
+ it 'Copyray.injectable? が false のとき(JS 応答など)はラベルにマーカーを注入しない' do
58
+ allow(CopyTunerClient::Copyray).to receive(:injectable?).with(controller).and_return(false)
59
+ expect(label_for).to eq '体温'
60
+ end
61
+ end
@@ -3,6 +3,7 @@ module ClientSpecHelpers
3
3
  CopyTunerClient.configuration = nil
4
4
  CopyTunerClient.configure(apply: false) do |config|
5
5
  config.api_key = 'abc123'
6
+ config.s3_path_token = 'token123'
6
7
  config.s3_host = 'copy-tuner.com'
7
8
  end
8
9
  end
@@ -21,8 +21,8 @@ class FakeCopyTunerApp < Sinatra::Base
21
21
  ENV.fetch('COPY_TUNER_PORT', 3002).to_i
22
22
  end
23
23
 
24
- def self.add_project(api_key)
25
- Project.create api_key
24
+ def self.add_project(api_key, s3_path_token: api_key)
25
+ Project.create api_key, s3_path_token:
26
26
  end
27
27
 
28
28
  def self.reset
@@ -33,25 +33,31 @@ class FakeCopyTunerApp < Sinatra::Base
33
33
  Project.find api_key
34
34
  end
35
35
 
36
- def with_project(api_key)
37
- if api_key == 'raise_error'
38
- halt 500, { error: 'Blah ha' }.to_json
39
- elsif (project = Project.find(api_key))
40
- yield project
41
- else
42
- halt 404, { error: 'No such project' }.to_json
36
+ def with_project(key, finder: :find, missing_status: 404)
37
+ case key
38
+ when 'raise_error' then halt 500, { error: 'Blah ha' }.to_json
39
+ when 'not_found' then halt 404, { error: 'No such project' }.to_json
43
40
  end
41
+
42
+ project = Project.public_send(finder, key)
43
+ halt missing_status, { error: 'No such project' }.to_json unless project
44
+ yield project
44
45
  end
45
46
 
46
- get '/api/v2/projects/:api_key/published_blurbs.json' do |api_key|
47
- with_project(api_key) do |project|
47
+ # 本番の S3/CloudFront は存在しないパスに 404 ではなく 403 を返すので合わせる
48
+ def with_project_by_s3_path_token(s3_path_token, &)
49
+ with_project(s3_path_token, finder: :find_by_s3_path_token, missing_status: 403, &)
50
+ end
51
+
52
+ get '/api/v2/projects/:s3_path_token/published_blurbs.json' do |s3_path_token|
53
+ with_project_by_s3_path_token(s3_path_token) do |project|
48
54
  etag project.etag
49
55
  project.published.to_json
50
56
  end
51
57
  end
52
58
 
53
- get '/api/v2/projects/:api_key/draft_blurbs.json' do |api_key|
54
- with_project(api_key) do |project|
59
+ get '/api/v2/projects/:s3_path_token/draft_blurbs.json' do |s3_path_token|
60
+ with_project_by_s3_path_token(s3_path_token) do |project|
55
61
  etag project.etag
56
62
  project.draft.to_json
57
63
  end
@@ -82,19 +88,27 @@ class FakeCopyTunerApp < Sinatra::Base
82
88
  end
83
89
 
84
90
  class Project
85
- attr_reader :draft, :published, :api_key
91
+ attr_reader :draft, :published, :api_key, :s3_path_token
86
92
 
87
93
  MUTEX = Mutex.new
88
94
 
89
- def self.create(api_key)
90
- project = Project.new('api_key' => api_key)
95
+ def self.create(api_key, s3_path_token: api_key)
96
+ project = Project.new('api_key' => api_key, 's3_path_token' => s3_path_token)
91
97
  save project
92
98
  project
93
99
  end
94
100
 
95
101
  def self.find(api_key)
102
+ find_by { |data| data[api_key] }
103
+ end
104
+
105
+ def self.find_by_s3_path_token(s3_path_token)
106
+ find_by { |data| data.values.find { |h| h['s3_path_token'] == s3_path_token } }
107
+ end
108
+
109
+ def self.find_by
96
110
  open_project_data do |data|
97
- if (project_hash = data[api_key])
111
+ if (project_hash = yield(data))
98
112
  Project.new project_hash.dup
99
113
  end
100
114
  end
@@ -132,6 +146,7 @@ class FakeCopyTunerApp < Sinatra::Base
132
146
 
133
147
  def initialize(attrs)
134
148
  @api_key = attrs['api_key']
149
+ @s3_path_token = attrs['s3_path_token']
135
150
  @draft = attrs.fetch('draft', {})
136
151
  @etag = attrs.fetch('etag', 1)
137
152
  @published = attrs.fetch('published', {})
@@ -140,6 +155,7 @@ class FakeCopyTunerApp < Sinatra::Base
140
155
  def to_hash
141
156
  {
142
157
  'api_key' => @api_key,
158
+ 's3_path_token' => @s3_path_token,
143
159
  'etag' => @etag,
144
160
  'draft' => @draft,
145
161
  'published' => @published,
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: copy_tuner_client
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.5.1
4
+ version: 3.0.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - SonicGarden
@@ -188,7 +188,6 @@ files:
188
188
  - ".gitignore"
189
189
  - ".rspec"
190
190
  - ".rubocop.yml"
191
- - ".ruby-version"
192
191
  - ".vscode/settings.json"
193
192
  - CHANGELOG.md
194
193
  - CLAUDE.md
@@ -261,6 +260,7 @@ files:
261
260
  - spec/copy_tuner_client/process_guard_spec.rb
262
261
  - spec/copy_tuner_client/queue_with_timeout_spec.rb
263
262
  - spec/copy_tuner_client/request_sync_spec.rb
263
+ - spec/copy_tuner_client/simple_form_extention_spec.rb
264
264
  - spec/copy_tuner_client/translation_log_spec.rb
265
265
  - spec/copy_tuner_client/warden_integration_spec.rb
266
266
  - spec/copy_tuner_client_spec.rb
@@ -307,7 +307,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
307
307
  - !ruby/object:Gem::Version
308
308
  version: '0'
309
309
  requirements: []
310
- rubygems_version: 4.0.10
310
+ rubygems_version: 4.0.20
311
311
  specification_version: 4
312
312
  summary: Client for the CopyTuner copy management service
313
313
  test_files: []
data/.ruby-version DELETED
@@ -1 +0,0 @@
1
- 4.0.5