haveapi 0.32.0 → 0.32.2

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.
Files changed (91) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +3 -8
  3. data/README.md +3 -422
  4. data/Rakefile +17 -7
  5. data/benchmarks/performance_compare.rb +27 -6
  6. data/doc/cs/client-examples.md +535 -0
  7. data/doc/cs/create-client.md +118 -0
  8. data/doc/cs/json-schema.html +1182 -0
  9. data/doc/cs/protocol.md +595 -0
  10. data/doc/cs/readme.md +432 -0
  11. data/doc/cs/typed-input-validation.md +122 -0
  12. data/doc/{client-examples.md → en/client-examples.md} +20 -10
  13. data/doc/{documentation-oauth.md → en/documentation-oauth.md} +40 -9
  14. data/doc/{documentation-ui.md → en/documentation-ui.md} +42 -6
  15. data/doc/{performance.md → en/performance.md} +20 -2
  16. data/doc/{protocol.md → en/protocol.md} +2 -2
  17. data/doc/en/readme.md +423 -0
  18. data/haveapi.gemspec +2 -2
  19. data/lib/haveapi/client_example.rb +18 -5
  20. data/lib/haveapi/client_examples/curl.rb +5 -5
  21. data/lib/haveapi/client_examples/dynamic_helpers.rb +10 -10
  22. data/lib/haveapi/client_examples/go_client.rb +1 -1
  23. data/lib/haveapi/client_examples/http.rb +4 -4
  24. data/lib/haveapi/client_examples/js_client.rb +10 -10
  25. data/lib/haveapi/client_examples/php_client.rb +24 -25
  26. data/lib/haveapi/client_examples/python_client.rb +11 -11
  27. data/lib/haveapi/client_examples/ruby_cli.rb +6 -9
  28. data/lib/haveapi/client_examples/ruby_client.rb +24 -16
  29. data/lib/haveapi/client_examples/rust_client.rb +1 -1
  30. data/lib/haveapi/client_examples/ts_generated_client.rb +1 -1
  31. data/lib/haveapi/documentation_context.rb +14 -2
  32. data/lib/haveapi/documentation_helpers.rb +92 -15
  33. data/lib/haveapi/documentation_locale.rb +65 -0
  34. data/lib/haveapi/documentation_oauth.rb +26 -14
  35. data/lib/haveapi/documentation_search.rb +5 -5
  36. data/lib/haveapi/documentation_validators.rb +43 -33
  37. data/lib/haveapi/locales/cs.yml +468 -0
  38. data/lib/haveapi/locales/en.yml +467 -0
  39. data/lib/haveapi/public/css/documentation.css +8 -4
  40. data/lib/haveapi/public/js/documentation.js +73 -20
  41. data/lib/haveapi/server.rb +32 -47
  42. data/lib/haveapi/shared_documentation_helpers.rb +53 -5
  43. data/lib/haveapi/version.rb +1 -1
  44. data/lib/haveapi/views/doc_layout.erb +3 -2
  45. data/lib/haveapi/views/doc_sidebars/create-client.erb +10 -10
  46. data/lib/haveapi/views/doc_sidebars/json-schema.erb +2 -2
  47. data/lib/haveapi/views/doc_sidebars/protocol.erb +24 -24
  48. data/lib/haveapi/views/documentation/search_form.erb +5 -4
  49. data/lib/haveapi/views/documentation/search_results.erb +6 -6
  50. data/lib/haveapi/views/index.erb +3 -3
  51. data/lib/haveapi/views/main_layout.erb +4 -4
  52. data/lib/haveapi/views/shared_documentation.erb +8 -5
  53. data/lib/haveapi/views/shared_sidebar.erb +11 -11
  54. data/lib/haveapi/views/version_page/auth_body.erb +7 -7
  55. data/lib/haveapi/views/version_page/client_auth.erb +1 -1
  56. data/lib/haveapi/views/version_page/client_example.erb +1 -1
  57. data/lib/haveapi/views/version_page/client_init.erb +1 -1
  58. data/lib/haveapi/views/version_page/client_overview.erb +7 -5
  59. data/lib/haveapi/views/version_page/example_panels.erb +5 -2
  60. data/lib/haveapi/views/version_page/resource_body.erb +24 -24
  61. data/lib/haveapi/views/version_page/resource_directory.erb +2 -2
  62. data/lib/haveapi/views/version_page/usage.erb +5 -5
  63. data/lib/haveapi/views/version_page.erb +11 -11
  64. data/lib/haveapi/views/version_sidebar/auth_nav.erb +2 -2
  65. data/lib/haveapi/views/version_sidebar/authentication_control.erb +8 -8
  66. data/lib/haveapi/views/version_sidebar/authentication_status.erb +1 -1
  67. data/lib/haveapi/views/version_sidebar/brand.erb +16 -5
  68. data/lib/haveapi/views/version_sidebar.erb +33 -18
  69. data/spec/client_examples/assets/documentation_test.cjs +107 -9
  70. data/spec/client_examples/comment_capture.rb +72 -0
  71. data/spec/client_examples/comments_spec.rb +162 -0
  72. data/spec/client_examples/context_spec.rb +18 -2
  73. data/spec/client_examples/detail_spec.rb +68 -0
  74. data/spec/documentation/client_overview_spec.rb +60 -0
  75. data/spec/documentation/example_selection_spec.rb +192 -0
  76. data/spec/documentation/language_settings_spec.rb +132 -0
  77. data/spec/documentation/locale_spec.rb +367 -0
  78. data/spec/documentation/navigation_spec.rb +61 -3
  79. data/spec/documentation/oauth_spec.rb +194 -6
  80. data/spec/documentation/search_index_routes_spec.rb +8 -4
  81. data/spec/documentation/search_spec.rb +1 -1
  82. data/spec/documentation/shared_pages_spec.rb +63 -2
  83. data/spec/documentation/validators_spec.rb +25 -0
  84. data/spec/extensions/exception_mailer_spec.rb +2 -2
  85. data/spec/packaging_spec.rb +68 -9
  86. data/spec/performance/event_baseline_spec.rb +98 -3
  87. data/spec/performance/source_versions_spec.rb +111 -2
  88. metadata +24 -11
  89. /data/doc/{create-client.md → en/create-client.md} +0 -0
  90. /data/doc/{json-schema.html → en/json-schema.html} +0 -0
  91. /data/doc/{typed-input-validation.md → en/typed-input-validation.md} +0 -0
@@ -31,6 +31,27 @@ module DocumentationOAuthSpec
31
31
  User.new('basic-reader') if username == 'basic-reader' && password == 'basic-password'
32
32
  end
33
33
  end
34
+
35
+ class SharedSSOProvider
36
+ def initialize
37
+ @authorizations = %w[PRIVATE_ACCESS_TOKEN OTHER_ACCESS_TOKEN]
38
+ @sso_active = true
39
+ end
40
+
41
+ def revoke(parameters)
42
+ @authorizations.delete(parameters.fetch('token'))
43
+ @sso_active = false if @authorizations.empty? || parameters['end_shared_session'] == '1'
44
+ ''
45
+ end
46
+
47
+ def valid_token?(token)
48
+ @authorizations.include?(token)
49
+ end
50
+
51
+ def fresh_authorization_identity
52
+ 'admin' if @sso_active
53
+ end
54
+ end
34
55
  end
35
56
 
36
57
  describe HaveAPI::DocumentationOAuth do
@@ -116,6 +137,25 @@ describe HaveAPI::DocumentationOAuth do
116
137
  authorization
117
138
  end
118
139
 
140
+ it 'localizes failed browser sign-in without saving a detected language or leaking the thread locale' do
141
+ previous = ::I18n.locale
142
+ get 'https://docs.example/api/_documentation/oauth/callback', {}, 'HTTP_ACCEPT_LANGUAGE' => 'cs-CZ'
143
+ expect(last_response.status).to eq(400)
144
+ expect(last_response.body).to include(::I18n.t('haveapi.documentation.oauth.sign_in_failed', locale: :cs))
145
+ expect(cookie_headers).not_to include('haveapi.docs.locale')
146
+ expect(::I18n.locale).to eq(previous)
147
+ end
148
+
149
+ it 'localizes expired-session notices after authentication resolves the API locale' do
150
+ set_cookie 'haveapi.docs.locale=cs; path=/api/', URI('https://docs.example/api/')
151
+ sign_in
152
+ DocumentationOAuthSpec::Config.users = {}
153
+ get 'https://docs.example/api/v1/'
154
+ expect(last_response.status).to eq(200)
155
+ expect(last_response.body).to include(::I18n.t('haveapi.documentation.oauth.session_ended', locale: :cs))
156
+ expect(last_response.body).not_to include('PRIVATE_ACCESS_TOKEN')
157
+ end
158
+
119
159
  def cookie_headers
120
160
  Array(last_response.headers['set-cookie']).join("\n")
121
161
  end
@@ -242,8 +282,31 @@ describe HaveAPI::DocumentationOAuth do
242
282
  end
243
283
  end
244
284
 
285
+ it 'keeps only the protected sign-out form when switching is unavailable' do
286
+ sign_in
287
+ get 'https://docs.example/api/v1/'
288
+ forms = last_response.body.scan(%r{<form method="post" action="https://docs.example/api/_documentation/oauth/logout">(.*?)</form>}m).flatten
289
+ expect(forms.length).to eq(1)
290
+ expect(forms.first).to include('>Sign out</button>')
291
+ expect(forms.first).to match(/name="csrf" value="[\w-]{43}"/)
292
+ expect(forms.first).not_to include('name="switch_user"', '>Switch user</button>')
293
+ end
294
+
245
295
  context 'with valid session CSRF and a switch-capable client' do
246
- let(:oauth_options) { super().merge(switch_user: true) }
296
+ let(:oauth_options) { super().merge(switch_user: true, switch_user_revoke_params: { 'end_shared_session' => '1' }) }
297
+
298
+ it 'places the native switch-user form before sign-out without changing their protected fields' do
299
+ sign_in
300
+ get 'https://docs.example/api/v1/'
301
+ forms = last_response.body.scan(%r{<form method="post" action="https://docs.example/api/_documentation/oauth/logout">(.*?)</form>}m).flatten
302
+ expect(forms.length).to eq(2)
303
+ expect(forms.first).to include('name="switch_user" value="1"', '>Switch user</button>')
304
+ expect(forms.last).to include('>Sign out</button>')
305
+ expect(forms.last).not_to include('name="switch_user"')
306
+ csrf_fields = forms.map { |form| form[/name="csrf" value="([^"]+)"/, 1] }
307
+ expect(csrf_fields.first).to match(/\A[\w-]{43}\z/)
308
+ expect(csrf_fields.last).to eq(csrf_fields.first)
309
+ end
247
310
 
248
311
  [nil, 'null', 'https://foreign.example', 'http://docs.example', 'https://docs.example:444'].each do |origin|
249
312
  [false, true].each do |switch_user|
@@ -269,7 +332,10 @@ describe HaveAPI::DocumentationOAuth do
269
332
  expect(last_response.headers).to include('Cache-Control' => 'private, no-store', 'Referrer-Policy' => 'no-referrer')
270
333
  expect(last_response.location).to eq('https://docs.example/api/_documentation/oauth/login?version=1')
271
334
  expect(cookie_headers).to include('_session=', '_pending=', 'max-age=0')
272
- expect(transport).to have_received(:post).with(have_attributes(path: '/api/_auth/oauth2/revoke'), hash_including('token' => 'PRIVATE_ACCESS_TOKEN'))
335
+ expect(transport).to have_received(:post).with(have_attributes(path: '/api/_auth/oauth2/revoke'),
336
+ 'client_id' => 'docs-client', 'client_secret' => oauth_options[:client_secret],
337
+ 'token' => 'PRIVATE_ACCESS_TOKEN', 'token_type_hint' => 'access_token',
338
+ 'end_shared_session' => '1')
273
339
  end
274
340
  end
275
341
 
@@ -668,8 +734,122 @@ describe HaveAPI::DocumentationOAuth do
668
734
  expect { described_class.new(**oauth_options, switch_user: false) }.not_to raise_error
669
735
  end
670
736
 
737
+ it 'requires static string keys and values for switch-user revoke parameters' do
738
+ [nil, [], 'PRIVATE_VALUE', { end_shared_session: 'PRIVATE_VALUE' }, { 'extra' => nil },
739
+ { 'extra' => true }, { 'extra' => 1 }, { 'extra' => [] }, { 'extra' => { 'nested' => 'PRIVATE_VALUE' } }].each do |value|
740
+ expect { described_class.new(**oauth_options, switch_user_revoke_params: value) }
741
+ .to raise_error(described_class::Invalid, 'Invalid documentation OAuth switch-user revoke parameters')
742
+ end
743
+ end
744
+
745
+ %w[client_id client_secret token token_type_hint].each do |field|
746
+ it "rejects overriding required revoke field #{field} in configuration" do
747
+ expect { described_class.new(**oauth_options, switch_user_revoke_params: { field => 'PRIVATE_VALUE' }) }
748
+ .to raise_error(described_class::Invalid, 'Invalid documentation OAuth switch-user revoke parameters')
749
+ end
750
+ end
751
+
752
+ it 'keeps configured switch-user revoke parameters inert when switching is disabled' do
753
+ oauth_options[:switch_user_revoke_params] = { 'end_shared_session' => '1' }
754
+ sign_in
755
+ controls = capture_controls
756
+ csrf = session_csrf
757
+ expect(controls.last).not_to have_key(:switch_user)
758
+ cookie = rack_mock_session.cookie_jar.to_hash.find { |name, _| name.end_with?('_session') }
759
+ expect_switch_refused(cookie, '', URI.encode_www_form(csrf:, switch_user: '1'))
760
+ post 'https://docs.example/api/_documentation/oauth/logout', { csrf: }, 'HTTP_ORIGIN' => 'https://docs.example'
761
+ expect(last_response.status).to eq(303)
762
+ expect(transport).to have_received(:post).with(have_attributes(path: '/api/_auth/oauth2/revoke'),
763
+ 'client_id' => 'docs-client', 'client_secret' => oauth_options[:client_secret],
764
+ 'token' => 'PRIVATE_ACCESS_TOKEN', 'token_type_hint' => 'access_token')
765
+ end
766
+
767
+ [false, true].each do |configured|
768
+ context "with shared SSO and #{configured ? 'configured' : 'default'} switch-user revoke parameters" do
769
+ let(:oauth_options) do
770
+ super().merge(switch_user: true).tap do |options|
771
+ options[:switch_user_revoke_params] = { 'end_shared_session' => '1' } if configured
772
+ end
773
+ end
774
+
775
+ it 'revokes only the documentation token and lets the provider decide whether fresh authorization reuses SSO' do
776
+ provider = DocumentationOAuthSpec::SharedSSOProvider.new
777
+ allow(transport).to receive(:post).with(have_attributes(path: '/api/_auth/oauth2/revoke'), anything) do |_, parameters|
778
+ provider.revoke(parameters)
779
+ end
780
+ sign_in
781
+ csrf = session_csrf
782
+ post 'https://docs.example/api/_documentation/oauth/logout', { csrf:, switch_user: '1' }, 'HTTP_ORIGIN' => 'https://docs.example'
783
+ expect(last_response.status).to eq(303)
784
+ fields = { 'client_id' => 'docs-client', 'client_secret' => oauth_options[:client_secret],
785
+ 'token' => 'PRIVATE_ACCESS_TOKEN', 'token_type_hint' => 'access_token' }
786
+ fields['end_shared_session'] = '1' if configured
787
+ expect(transport).to have_received(:post).with(have_attributes(path: '/api/_auth/oauth2/revoke'), fields)
788
+ expect(provider.valid_token?('PRIVATE_ACCESS_TOKEN')).to be(false)
789
+ expect(provider.valid_token?('OTHER_ACCESS_TOKEN')).to be(true)
790
+ get last_response.location
791
+ expect(last_response.status).to eq(302)
792
+ expect(provider.fresh_authorization_identity).to eq(configured ? nil : 'admin')
793
+ end
794
+ end
795
+ end
796
+
671
797
  context 'with user switching enabled' do
672
- let(:oauth_options) { super().merge(switch_user: true) }
798
+ let(:oauth_options) { super().merge(switch_user: true, switch_user_revoke_params: { 'end_shared_session' => '1' }) }
799
+
800
+ it 'requires an authenticated documentation session before switching' do
801
+ post 'https://docs.example/api/_documentation/oauth/logout', { csrf: 'x' * 43, switch_user: '1' },
802
+ 'HTTP_ORIGIN' => 'https://docs.example'
803
+ expect(last_response.status).to eq(403)
804
+ expect(cookie_headers).to be_empty
805
+ expect(transport).not_to have_received(:post)
806
+ end
807
+
808
+ it 'requires the configured HTTPS origin before switching' do
809
+ sign_in
810
+ csrf = session_csrf
811
+ name, value = rack_mock_session.cookie_jar.to_hash.find { |key, _| key.end_with?('_session') }
812
+ %w[http://docs.example https://foreign.example].each do |origin|
813
+ post "#{origin}/api/_documentation/oauth/logout", { csrf:, switch_user: '1' },
814
+ 'HTTP_ORIGIN' => 'https://docs.example', 'HTTP_COOKIE' => "#{name}=#{Rack::Utils.escape(value)}"
815
+ expect(last_response.status).to eq(400)
816
+ expect(cookie_headers).to be_empty
817
+ end
818
+ expect(transport).to have_received(:post).once
819
+ end
820
+
821
+ it 'copies configured revoke fields before the caller mutates its hash, keys or values' do
822
+ key = +'end_shared_session'
823
+ value = +'1'
824
+ parameters = {}.compare_by_identity
825
+ parameters[key] = value
826
+ oauth_options[:switch_user_revoke_params] = parameters
827
+ app
828
+ key.replace('changed')
829
+ value.replace('changed')
830
+ parameters.clear
831
+ parameters['token'] = 'BROWSER_TOKEN'
832
+ sign_in
833
+ csrf = session_csrf
834
+ post 'https://docs.example/api/_documentation/oauth/logout', { csrf:, switch_user: '1' }, 'HTTP_ORIGIN' => 'https://docs.example'
835
+ expect(last_response.status).to eq(303)
836
+ expect(transport).to have_received(:post).with(have_attributes(path: '/api/_auth/oauth2/revoke'),
837
+ 'client_id' => 'docs-client', 'client_secret' => oauth_options[:client_secret],
838
+ 'token' => 'PRIVATE_ACCESS_TOKEN', 'token_type_hint' => 'access_token',
839
+ 'end_shared_session' => '1')
840
+ end
841
+
842
+ it 'sends the original revoke form on ordinary sign-out even if the browser supplies extra fields' do
843
+ sign_in
844
+ csrf = session_csrf
845
+ post 'https://docs.example/api/_documentation/oauth/logout', { csrf:, end_shared_session: '1', token: 'BROWSER_TOKEN' },
846
+ 'HTTP_ORIGIN' => 'https://docs.example'
847
+ expect(last_response.status).to eq(303)
848
+ expect(last_response.location).to eq('https://docs.example/api/v1/')
849
+ expect(transport).to have_received(:post).with(have_attributes(path: '/api/_auth/oauth2/revoke'),
850
+ 'client_id' => 'docs-client', 'client_secret' => oauth_options[:client_secret],
851
+ 'token' => 'PRIVATE_ACCESS_TOKEN', 'token_type_hint' => 'access_token')
852
+ end
673
853
 
674
854
  it 'offers switching only after validated documentation-cookie authentication' do
675
855
  controls = capture_controls
@@ -688,21 +868,29 @@ describe HaveAPI::DocumentationOAuth do
688
868
 
689
869
  it 'revokes and clears the old session before starting fresh state and PKCE at the fixed login' do
690
870
  original = sign_in
871
+ expect(original).not_to have_key('end_shared_session')
872
+ expect(transport).to have_received(:post).with(have_attributes(path: '/api/_auth/oauth2/token'),
873
+ hash_excluding('end_shared_session'))
691
874
  csrf = session_csrf
692
875
  post 'https://docs.example/api/_documentation/oauth/logout',
693
- { csrf:, switch_user: '1', version: '2', return: 'https://foreign.example/', scope: 'other' },
876
+ { csrf:, switch_user: '1', version: '2', return: 'https://foreign.example/', scope: 'other',
877
+ client_id: 'BROWSER_CLIENT', client_secret: 'BROWSER_SECRET', token: 'BROWSER_TOKEN',
878
+ token_type_hint: 'refresh_token', end_shared_session: '0', unexpected: 'BROWSER_EXTRA' },
694
879
  'HTTP_ORIGIN' => 'https://docs.example'
695
880
  expect(last_response.status).to eq(303)
696
881
  expect(last_response.location).to eq('https://docs.example/api/_documentation/oauth/login?version=1')
697
882
  expect(cookie_headers).to include('_session=', '_pending=', 'max-age=0')
698
- expect(transport).to have_received(:post).with(have_attributes(path: '/api/_auth/oauth2/revoke'), hash_including('token' => 'PRIVATE_ACCESS_TOKEN'))
883
+ expect(transport).to have_received(:post).with(have_attributes(path: '/api/_auth/oauth2/revoke'),
884
+ 'client_id' => 'docs-client', 'client_secret' => oauth_options[:client_secret],
885
+ 'token' => 'PRIVATE_ACCESS_TOKEN', 'token_type_hint' => 'access_token',
886
+ 'end_shared_session' => '1')
699
887
  get last_response.location
700
888
  expect(last_response.status).to eq(302)
701
889
  fresh = URI.decode_www_form(URI(last_response.location).query).to_h
702
890
  expect(fresh).to include('scope' => 'all', 'code_challenge_method' => 'S256')
703
891
  expect(fresh['state']).not_to eq(original['state'])
704
892
  expect(fresh['code_challenge']).not_to eq(original['code_challenge'])
705
- expect(fresh.keys & %w[prompt select_account]).to be_empty
893
+ expect(fresh.keys & %w[prompt select_account end_shared_session]).to be_empty
706
894
  get 'https://docs.example/api/_documentation/oauth/callback', error: 'access_denied', state: fresh.fetch('state')
707
895
  expect(last_response.status).to eq(400)
708
896
  DocumentationOAuthSpec::Config.lookups.clear
@@ -86,7 +86,7 @@ RSpec.describe HaveAPI::DocumentationSearch::Helpers do
86
86
  expect(response.content_type).to match(%r{\Atext/html;\s*charset=utf-8\z})
87
87
  expect(response['cache-control']).to eq('private, max-age=86400, immutable')
88
88
  expect(response['etag']).to eq(%("#{key}"))
89
- expect(response['vary'].split(/,\s*/)).to contain_exactly('X-Language', 'Cookie', 'Authorization')
89
+ expect(response['vary'].split(/,\s*/)).to contain_exactly('X-Language', 'Accept-Language', 'Cookie', 'Authorization')
90
90
  expect(envelope(response)).to include('key' => key)
91
91
  expect(response.body).to include('\\u003c/script\\u003e', '\\u0026')
92
92
  expect(response.body).not_to include('<!DOCTYPE', 'docs-sidebar', '<script src=', 'fixture')
@@ -139,10 +139,14 @@ RSpec.describe HaveAPI::DocumentationSearch::Helpers do
139
139
  expect(envelope(current)['index']).to include('version' => '1', 'base_path' => '/api/v1/')
140
140
  end
141
141
 
142
- it 'binds the projection to resolved locale and canonical Rack/API mounts' do
142
+ it 'binds the projection to the documentation browser locale independently of the API header and Rack/API mounts' do
143
143
  server.available_locales = %i[en cs]
144
- english = envelope(request('?page=resources&search_index=current', 'HTTP_X_LANGUAGE' => 'en'))
145
- czech = envelope(request('?page=resources&search_index=current', 'HTTP_X_LANGUAGE' => 'cs'))
144
+ english = envelope(request('?page=resources&search_index=current', 'HTTP_ACCEPT_LANGUAGE' => 'en', 'HTTP_X_LANGUAGE' => 'cs'))
145
+ czech = envelope(request('?page=resources&search_index=current', 'HTTP_ACCEPT_LANGUAGE' => 'cs', 'HTTP_X_LANGUAGE' => 'en'))
146
+ custom_header = envelope(request('?page=resources&search_index=current', 'HTTP_X_LANGUAGE' => 'cs'))
147
+ expect(english['index']['locale']).to eq('en')
148
+ expect(custom_header['index']['locale']).to eq('en')
149
+ expect(custom_header['key']).to eq(english['key'])
146
150
  expect(english['key']).not_to eq(czech['key'])
147
151
  expect(czech['index']['locale']).to eq('cs')
148
152
  mounted = envelope(request('?page=resources&search_index=current', 'SCRIPT_NAME' => '/rack'))
@@ -12,7 +12,7 @@ RSpec.describe HaveAPI::DocumentationSearch do
12
12
  { resources: { widget: { actions: { renew: action }, resources: {} } },
13
13
  authentication: { token: { resources: { token: { actions: { request: action }, resources: {} } } } } }
14
14
  end
15
- let(:presentation) { Object.new.extend(described_class::Helpers) }
15
+ let(:presentation) { Object.new.extend(HaveAPI::DocumentationLocale).extend(described_class::Helpers) }
16
16
 
17
17
  def search(query, source = description)
18
18
  index = described_class::Index.new(description: source, base_path: '/v1/', version: '1', locale: 'en', visibility: 'anonymous')
@@ -1,5 +1,7 @@
1
1
  require 'spec_helper'
2
2
  require 'rack/mock'
3
+ require 'cgi'
4
+ require 'ripper'
3
5
 
4
6
  RSpec.describe HaveAPI::SharedDocumentationHelpers do
5
7
  api do
@@ -90,7 +92,7 @@ RSpec.describe HaveAPI::SharedDocumentationHelpers do
90
92
  expect(last_response.body).to include(heading, 'aria-label="Breadcrumb"',
91
93
  'href="/"', 'href="/doc"', 'href="/v1/?page=resources"')
92
94
  expect_neutral_shell(last_response.body, 'guide')
93
- breadcrumb = last_response.body.match(%r{<nav aria-label="Breadcrumb">(.*?)</nav>}m)[1]
95
+ breadcrumb = last_response.body.match(%r{<nav class="docs-breadcrumb"[^>]*>(.*?)</nav>}m)[1]
94
96
  expect(breadcrumb).to include('API versions', 'HaveAPI internals')
95
97
  expect(breadcrumb.scan(/<li\b/).length).to eq(path.match?(%r{\A/doc(?:/(?:index(?:\.md)?|readme))?\z}) ? 2 : 3)
96
98
  expect(server).not_to have_received(:describe)
@@ -121,6 +123,65 @@ RSpec.describe HaveAPI::SharedDocumentationHelpers do
121
123
  expect(pages.uniq.length).to eq(1)
122
124
  end
123
125
 
126
+ def article_samples(body)
127
+ body.scan(%r{<pre><code(?: class="([^"]*)")?>(.*?)</code></pre>}m).map do |language, source|
128
+ code = CGI.unescapeHTML(source)
129
+ if language == 'ruby'
130
+ Ripper.lex(code).reject { |(_, type, _, _)| %i[on_sp on_nl on_ignored_nl on_comment].include?(type) }
131
+ .map { |(_, type, token, _)| [type, token] }
132
+ else
133
+ code.lines.reject { |line| line.lstrip.start_with?('#', '//') }.join.strip
134
+ end
135
+ end
136
+ end
137
+
138
+ {
139
+ 'readme' => 'Serverová implementace',
140
+ 'protocol' => 'Definice protokolu',
141
+ 'create-client' => 'Definice klienta',
142
+ 'typed-input-validation' => 'Validace typovaných vstupů',
143
+ 'client-examples' => 'Klientské příklady'
144
+ }.each do |article, heading|
145
+ it "translates #{article} while preserving its English anchors and noncomment samples" do
146
+ get "/doc/#{article}", {}, 'HTTP_ACCEPT_LANGUAGE' => 'en'
147
+ english = last_response.body
148
+ expect(last_response).to be_ok
149
+ get "/doc/#{article}", {}, 'HTTP_ACCEPT_LANGUAGE' => 'cs-CZ'
150
+ czech = last_response.body
151
+ expect(last_response).to be_ok
152
+ expect(czech).to include('lang="cs"', heading)
153
+ expect(czech.scan(/<h[1-6]\b[^>]*\bid="([^"]+)"/).flatten)
154
+ .to eq(english.scan(/<h[1-6]\b[^>]*\bid="([^"]+)"/).flatten)
155
+ expect(article_samples(czech)).not_to be_empty
156
+ expect(article_samples(czech)).to eq(article_samples(english))
157
+ end
158
+ end
159
+
160
+ it 'uses identical schema code for the English and Czech presentations' do
161
+ get '/doc/json-schema', {}, 'HTTP_ACCEPT_LANGUAGE' => 'en'
162
+ english = last_response.body
163
+ get '/doc/json-schema', {}, 'HTTP_ACCEPT_LANGUAGE' => 'cs'
164
+ expect(last_response).to be_ok
165
+ expect(last_response.body).to include('<h1 id="envelope">Obálka</h1>')
166
+ expect(article_samples(last_response.body)).to eq(article_samples(english))
167
+ end
168
+
169
+ it 'keeps translated article and shared asset links mounted under Rack and API prefixes' do
170
+ server = HaveAPI::Server.new(get_opt(:api_module))
171
+ server.use_version(1)
172
+ server.mount('/api/')
173
+ request = Rack::MockRequest.new(server.app)
174
+ response = request.get('/api/doc/protocol', 'HTTP_HOST' => 'example.test',
175
+ 'SCRIPT_NAME' => '/rack', 'HTTP_ACCEPT_LANGUAGE' => 'cs')
176
+ expect(response.status).to eq(200)
177
+ expect(response.body).to include('href="/rack/api/doc/typed-input-validation"',
178
+ 'src="/rack/api/doc/protocol.png"')
179
+ response = request.get('/api/doc/client-examples', 'HTTP_HOST' => 'example.test',
180
+ 'SCRIPT_NAME' => '/rack', 'HTTP_ACCEPT_LANGUAGE' => 'cs')
181
+ expect(response.body).to include('href="/rack/api/doc/documentation-ui"',
182
+ 'href="/rack/api/doc/documentation-oauth"')
183
+ end
184
+
124
185
  it 'uses configured escaped identity or the actual host and port in neutral titles and brand' do
125
186
  server = HaveAPI::Server.new(get_opt(:api_module))
126
187
  server.use_version(1)
@@ -191,7 +252,7 @@ RSpec.describe HaveAPI::SharedDocumentationHelpers do
191
252
  expect(response['Cache-Control']).to eq('private, no-store')
192
253
  expect(response.body).to include('href="/rack/api/"', 'href="/rack/api/doc"',
193
254
  'href="/rack/api/v1/"', 'href="/rack/api/v1/?page=resources"',
194
- 'src="/rack/js/documentation.js"')
255
+ "src=\"/rack/js/documentation.js?v=#{HaveAPI::DocumentationHelpers::ASSET_DIGESTS.fetch('js/documentation.js')}\"")
195
256
  expect(response.body).not_to include('href="/doc"', 'href="/v1/"')
196
257
  end
197
258
  end
@@ -120,4 +120,29 @@ describe HaveAPI::DocumentationValidators do
120
120
  expect(render(payload, { 'extra' => payload })).to include('<th scope="row">&lt;script&gt;&amp;&quot;</th>')
121
121
  expect(Marshal.dump(options)).to eq(before)
122
122
  end
123
+
124
+ it 'localizes framework presentation while preserving metadata and machine values' do
125
+ validators = {
126
+ present: { empty: false }, include: { values: { 'ready' => 'Application label' } },
127
+ number: { min: 2, step: 3, even: true }, length: { min: 2, max: 8 },
128
+ custom: 'Application rule', extension: { 'supplied' => 'Untranslated metadata' }
129
+ }
130
+ before = Marshal.dump(validators)
131
+ html = I18n.with_locale(:cs) { described_class.render(validators, type: 'String') }
132
+
133
+ expect(html).to include('<caption>Validační pravidla</caption>', '<th scope="col">Pravidlo</th>',
134
+ '<th scope="col">Podrobnosti</th>', 'Musí být uvedeno', 'Povolené hodnoty',
135
+ '<code>ready</code>: Application label', 'Application rule', 'Untranslated metadata')
136
+ expect(html).not_to include('Validation rules', 'Allowed values', 'Minimum length:')
137
+ expect(Marshal.dump(validators)).to eq(before)
138
+ end
139
+
140
+ it 'escapes translated text and interpolated metadata independently' do
141
+ html = I18n.with_locale(:cs) do
142
+ render(:confirm, { parameter: '<script>&', equal: false })
143
+ end
144
+
145
+ expect(html).to include('Musí se lišit od parametru <code>&lt;script&gt;&amp;</code>.')
146
+ expect(html).not_to include('<script>', '&amp;lt;')
147
+ end
123
148
  end
@@ -125,7 +125,7 @@ describe HaveAPI::Extensions::ExceptionMailer do
125
125
  it 'does not mail a missing JSON schema documentation file' do
126
126
  mailer = new_mailer
127
127
  calls = collect_mail_calls(mailer)
128
- doc_path = File.join(app.settings.root, '../../doc/json-schema.html')
128
+ doc_path = File.expand_path('../../doc/en/json-schema.html', app.settings.root)
129
129
  allow(File).to receive(:read).and_call_original
130
130
  allow(File).to receive(:read).with(doc_path).and_raise(Errno::ENOENT, doc_path)
131
131
 
@@ -142,7 +142,7 @@ describe HaveAPI::Extensions::ExceptionMailer do
142
142
  calls = collect_mail_calls(mailer)
143
143
  app.set :raise_errors, false
144
144
  app.set :show_exceptions, false
145
- doc_path = File.join(app.settings.root, '../../doc/json-schema.html')
145
+ doc_path = File.expand_path('../../doc/en/json-schema.html', app.settings.root)
146
146
  allow(File).to receive(:read).and_call_original
147
147
  allow(File).to receive(:read).with(doc_path).and_raise(Errno::EACCES, doc_path)
148
148
 
@@ -9,7 +9,12 @@ require 'tmpdir'
9
9
 
10
10
  describe HaveAPI::Server do
11
11
  def required_docs
12
- %w[json-schema.html protocol.md create-client.md typed-input-validation.md client-examples.md protocol.png]
12
+ %w[protocol.png en/documentation-ui.md en/documentation-oauth.md en/performance.md] +
13
+ %w[en cs].flat_map do |locale|
14
+ %w[readme.md protocol.md create-client.md typed-input-validation.md client-examples.md json-schema.html].map do |name|
15
+ "#{locale}/#{name}"
16
+ end
17
+ end
13
18
  end
14
19
 
15
20
  before(:context) do
@@ -22,14 +27,15 @@ describe HaveAPI::Server do
22
27
  Rake::Task[:build].invoke
23
28
  end
24
29
 
25
- %i[missing empty].each do |condition|
26
- it "rejects a direct build with #{condition} shared documentation" do
30
+ %w[en/json-schema.html cs/json-schema.html cs/protocol.md].product(%i[missing empty]).each do |document, condition|
31
+ it "rejects a direct build with #{condition} #{document}" do
27
32
  Dir.mktmpdir('haveapi-doc-check') do |dir|
28
33
  FileUtils.mkdir_p(File.join(dir, 'doc'))
29
34
  required_docs.each do |name|
30
- next if name == 'json-schema.html' && condition == :missing
35
+ next if name == document && condition == :missing
31
36
 
32
- content = name == 'json-schema.html' && condition == :empty ? '' : 'document'
37
+ content = name == document && condition == :empty ? '' : 'document'
38
+ FileUtils.mkdir_p(File.dirname(File.join(dir, 'doc', name)))
33
39
  File.write(File.join(dir, 'doc', name), content)
34
40
  end
35
41
 
@@ -38,12 +44,42 @@ describe HaveAPI::Server do
38
44
  expect { invoke_build }.to raise_error(SystemExit) do |error|
39
45
  expect(error.status).to eq(1)
40
46
  end
41
- end.to output(/json-schema.html.*Run `make doc`/).to_stderr
47
+ end.to output(/#{Regexp.escape(document)}.*Run `make doc`/).to_stderr
42
48
  end
43
49
  end
44
50
  end
45
51
  end
46
52
 
53
+ it 'copies localized schema documentation without application gems or Bundler' do
54
+ root = File.expand_path('../../..', __dir__)
55
+ Dir.mktmpdir('haveapi-copydoc') do |dir|
56
+ destination = File.join(dir, 'server')
57
+ empty_gems = File.join(dir, 'empty-gems')
58
+ FileUtils.mkdir_p(empty_gems)
59
+ environment = {
60
+ 'GEM_HOME' => empty_gems,
61
+ 'GEM_PATH' => empty_gems,
62
+ 'RUBYLIB' => nil,
63
+ 'RUBYOPT' => nil,
64
+ 'RUBYGEMS_GEMDEPS' => nil
65
+ }
66
+ stdout, stderr, status = Bundler.with_unbundled_env do
67
+ Open3.capture3(environment, File.join(root, 'utils/copydoc.sh'), destination, chdir: root)
68
+ end
69
+ expect(status.success?).to be(true), "Isolated documentation copy failed: #{stdout}#{stderr}"
70
+
71
+ schemas = %w[en cs].map do |locale|
72
+ body = File.read(File.join(destination, 'doc', locale, 'json-schema.html'))
73
+ heading = ::I18n.t('haveapi.documentation.schema.envelope', locale:, raise: true)
74
+ expect(body).to include(%(<h1 id="envelope">#{ERB::Util.html_escape(heading)}</h1>))
75
+ code = body.scan(%r{<pre><code>(.*?)</code></pre>}m).flatten
76
+ expect(code.length).to eq(4)
77
+ code
78
+ end
79
+ expect(schemas[0]).to eq(schemas[1])
80
+ end
81
+ end
82
+
47
83
  it 'ships and serves shared documentation from the built gem' do
48
84
  invoke_build
49
85
  gem_path = File.expand_path("../pkg/haveapi-#{HaveAPI::VERSION}.gem", __dir__)
@@ -85,13 +121,18 @@ describe HaveAPI::Server do
85
121
  server.use_version(1)
86
122
  server.mount('/')
87
123
  request = Rack::MockRequest.new(server.app)
88
- responses = %w[/ /doc /doc/index /doc/index.md /doc/readme /doc/json-schema /doc/protocol.md /doc/create-client.md /doc/client-examples.md /js/highlight-LICENSE].to_h do |path|
89
- response = request.get(path, 'HTTP_HOST' => 'localhost')
124
+ responses = %w[/ /doc /doc/index /doc/index.md /doc/readme /doc/json-schema /doc/protocol.md /doc/create-client.md /doc/client-examples.md /doc/typed-input-validation /js/highlight-LICENSE].to_h do |path|
125
+ response = request.get(path, 'HTTP_HOST' => 'localhost', 'HTTP_ACCEPT_LANGUAGE' => 'en')
90
126
  [path, { status: response.status, type: response.content_type, cache_control: response['Cache-Control'], body: response.body }]
91
127
  end
128
+ translated = %w[/doc /doc/index /doc/index.md /doc/readme /doc/protocol.md /doc/create-client.md /doc/typed-input-validation /doc/client-examples.md /doc/json-schema /doc/documentation-ui].to_h do |path|
129
+ response = request.get(path, 'HTTP_HOST' => 'localhost', 'HTTP_ACCEPT_LANGUAGE' => 'cs-CZ')
130
+ [path, { status: response.status, body: response.body }]
131
+ end
92
132
  puts JSON.generate({
93
133
  framework: HaveAPI::Server.instance_method(:mount).source_location.first,
94
- responses: responses
134
+ responses: responses,
135
+ translated: translated
95
136
  })
96
137
  RUBY
97
138
 
@@ -128,6 +169,7 @@ describe HaveAPI::Server do
128
169
  '/doc/protocol.md' => 'Protocol definition',
129
170
  '/doc/create-client.md' => 'Client definition',
130
171
  '/doc/client-examples.md' => 'Client examples',
172
+ '/doc/typed-input-validation' => 'Typed input validation',
131
173
  '/js/highlight-LICENSE' => 'Copyright'
132
174
  }.each do |path, heading|
133
175
  response = result.fetch('responses').fetch(path)
@@ -140,6 +182,23 @@ describe HaveAPI::Server do
140
182
  expect(response.fetch('body')).to include('data-docs', '/js/documentation.js', '/css/documentation.css')
141
183
  expect(response.fetch('body')).not_to include('/js/main.js', '/css/bootstrap')
142
184
  end
185
+ {
186
+ '/doc' => 'Serverová implementace',
187
+ '/doc/index' => 'Serverová implementace',
188
+ '/doc/index.md' => 'Serverová implementace',
189
+ '/doc/readme' => 'Serverová implementace',
190
+ '/doc/protocol.md' => 'Definice protokolu',
191
+ '/doc/create-client.md' => 'Definice klienta',
192
+ '/doc/typed-input-validation' => 'Validace typovaných vstupů',
193
+ '/doc/client-examples.md' => 'Klientské příklady',
194
+ '/doc/json-schema' => 'Obálka',
195
+ '/doc/documentation-ui' => 'Browsing API documentation'
196
+ }.each do |path, heading|
197
+ response = result.fetch('translated').fetch(path)
198
+ expect(response.fetch('status')).to eq(200), "Packaged Czech route failed: #{path}"
199
+ expect(response.fetch('body')).to include('lang="cs"', heading)
200
+ end
201
+ expect(result.fetch('translated').fetch('/doc/documentation-ui').fetch('body')).to include('lang="en"')
143
202
  %w[/doc /doc/index /doc/index.md /doc/readme].each do |path|
144
203
  body = result.fetch('responses').fetch(path).fetch('body')
145
204
  expect(body).to include('<title>HaveAPI internals · ', 'Server framework features',