diff --git a/.env.sample b/.env.sample index a47b18a..8b3e062 100644 --- a/.env.sample +++ b/.env.sample @@ -2,7 +2,7 @@ # No trailing slash ALEXANDRIA_BASE_URL= ALEXANDRIA_SERVICE_API_TOKEN= -# A kst_ token is robles's API v2 token and publishes through /api/v2 (WEB-8205, WEB-8208); anything else is the shared token and uses v1 +# Must be robles's API v2 token, which starts with kst_ (WEB-8205, WEB-8208); any other value is refused (WEB-8371) # Integration with betamax # No trailing slash diff --git a/app/lib/api/alexandria/book_uploader.rb b/app/lib/api/alexandria/book_uploader.rb index 8240cff..50506fe 100644 --- a/app/lib/api/alexandria/book_uploader.rb +++ b/app/lib/api/alexandria/book_uploader.rb @@ -2,13 +2,10 @@ module Api module Alexandria - # Allow uploading of books to alexandria + # Allow uploading of books to alexandria, through API v2 class BookUploader - include Util::Logging - attr_reader :book - PUBLISH_URL = '/api/editions/publish' V2_PUBLISH_PATH = '/api/v2/editions/publish' def self.upload(book) @@ -16,55 +13,27 @@ def self.upload(book) end # In a real run `token` is always ALEXANDRIA_SERVICE_API_TOKEN. The - # keywords let the tests choose a path. + # keywords let the tests supply a token and a client. def initialize(book, token: ALEXANDRIA_SERVICE_API_TOKEN, client: nil) @book = book @token = token @client = client end + # Refuses any token but robles's kst_ token before a request is made + # (WEB-8371). The body is the one v1 took (WEB-8205). def upload - return upload_with_api_v2 if Api::V2Client.service_token?(@token) - - conn.post do |req| - req.url api_uri - req.body = payload - end + Api::V2Client.require_service_token!(@token, name: 'ALEXANDRIA_SERVICE_API_TOKEN', service: 'alexandria') + client.post(V2_PUBLISH_PATH, payload) end private - # Sends v1's payload, so both paths send the same bytes (WEB-8205) - def upload_with_api_v2 - client.post(V2_PUBLISH_PATH, payload) - end - - # Built lazily, so the v1 path never builds it + # Built lazily, after the token check def client @client ||= Api::V2Client.new(base_url: ALEXANDRIA_BASE_URL, token: @token) end - def api_uri - path = [ - ALEXANDRIA_BASE_URL, - PUBLISH_URL - ].join - - URI(path) - end - - def conn - @conn ||= Faraday.new(headers: { 'Content-Type' => 'application/json' }) do |faraday| - faraday.response(:logger, logger) do |logger| - logger.filter(/(Token token=\\")(\w+)/, '\1[REMOVED]') - end - faraday.response(:raise_error) - faraday.adapter(Faraday.default_adapter) - faraday.request(:authorization, 'Bearer', ALEXANDRIA_SERVICE_API_TOKEN) - faraday.request(:retry) - end - end - def payload { book: }.to_json end diff --git a/app/lib/api/alexandria/content_module_uploader.rb b/app/lib/api/alexandria/content_module_uploader.rb index 9f2f16a..df0ff4c 100644 --- a/app/lib/api/alexandria/content_module_uploader.rb +++ b/app/lib/api/alexandria/content_module_uploader.rb @@ -2,115 +2,42 @@ module Api module Alexandria - # Allow uploading of content_modules to alexandria + # Allow uploading of content_modules to alexandria, through API v2 class ContentModuleUploader include Util::Logging attr_reader :content_module - PUBLISH_URL = '/api/content_modules/publish' V2_PUBLISH_PATH = '/api/v2/content_modules/publish' - # Seconds to wait when establishing the connection to Alexandria. - OPEN_TIMEOUT = 10 - # Seconds to wait for Alexandria to accept the publish. Generous, because - # publishing a whole module can be slow, but bounded so a hung Alexandria - # fails (and is logged) instead of hanging CI indefinitely. - READ_TIMEOUT = 120 - def self.upload(content_module) new(content_module).upload end # In a real run `token` is always ALEXANDRIA_SERVICE_API_TOKEN. The - # keywords let the tests choose a path. + # keywords let the tests supply a token and a client. def initialize(content_module, token: ALEXANDRIA_SERVICE_API_TOKEN, client: nil) @content_module = content_module @token = token @client = client end + # Refuses any token but robles's kst_ token before a request is made + # (WEB-8371). The body is the one v1 took (WEB-8205), and the client + # logs the status and the time. def upload - # Api::V2Client never raises a Faraday::Error, so the rescue below - # never sees a v2 failure. - return upload_with_api_v2 if Api::V2Client.service_token?(@token) - - started_at = monotonic_now - log_upload_start - response = conn.post do |req| - req.url api_uri - req.body = payload - end - log_upload_success(response, started_at) - response - rescue Faraday::Error => e - log_upload_failure(e, started_at) - raise - end - - private - - # Sends v1's payload, so both paths send the same bytes (WEB-8205). The - # client logs the status and the time. - def upload_with_api_v2 + Api::V2Client.require_service_token!(@token, name: 'ALEXANDRIA_SERVICE_API_TOKEN', service: 'alexandria') logger.info("Publishing content module '#{content_module.shortcode}' to Alexandria API v2 (#{payload.bytesize} bytes)") client.post(V2_PUBLISH_PATH, payload) end - # Built lazily, so the v1 path never builds it + private + + # Built lazily, after the token check def client @client ||= Api::V2Client.new(base_url: ALEXANDRIA_BASE_URL, token: @token) end - def log_upload_start - logger.info("Publishing content module '#{content_module.shortcode}' to Alexandria at #{api_uri} (#{payload.bytesize} bytes)") - end - - def log_upload_success(response, started_at) - logger.info("Alexandria accepted content module '#{content_module.shortcode}' (HTTP #{response.status}) in #{elapsed_since(started_at)}s") - end - - def log_upload_failure(error, started_at) - logger.error("Alexandria publish failed for content module '#{content_module.shortcode}' after #{elapsed_since(started_at)}s: #{error.class} (HTTP #{error.response_status || 'none'})") - logger.error("Alexandria response body: #{error.response_body}") if error.response_body.present? - end - - def monotonic_now - Process.clock_gettime(Process::CLOCK_MONOTONIC) - end - - def elapsed_since(started_at) - (monotonic_now - started_at).round(1) - end - - def api_uri - path = [ - ALEXANDRIA_BASE_URL, - PUBLISH_URL - ].join - - URI(path) - end - - def conn - @conn ||= Faraday.new( - headers: { 'Content-Type' => 'application/json' }, - request: { open_timeout: OPEN_TIMEOUT, timeout: READ_TIMEOUT } - ) do |faraday| - faraday.response(:logger, logger) do |filter| - filter.filter(/(Token token=\\")(\w+)/, '\1[REMOVED]') - end - faraday.response(:raise_error) - faraday.adapter(Faraday.default_adapter) - faraday.request(:authorization, 'Bearer', ALEXANDRIA_SERVICE_API_TOKEN) - # NOTE: faraday-retry's default `methods` excludes POST, so this does - # not actually retry the publish. Left as-is to avoid silently - # introducing (non-idempotent) publish retries; the timeouts above are - # what stop a hung Alexandria from blocking CI forever. - faraday.request(:retry) - end - end - def payload @payload ||= { content_module: }.to_json end diff --git a/app/lib/api/betamax/video_course_uploader.rb b/app/lib/api/betamax/video_course_uploader.rb index ad6e900..71d6adf 100644 --- a/app/lib/api/betamax/video_course_uploader.rb +++ b/app/lib/api/betamax/video_course_uploader.rb @@ -4,19 +4,18 @@ module Api module Betamax # Allow uploading of video courses to betamax. # - # WEB-8206: when BETAMAX_SERVICE_API_TOKEN is a service token (it starts - # with `kst_`), the upload goes to betamax's API v2 endpoint, + # WEB-8206: uploads go to betamax's API v2 endpoint, # POST /api/v2/collections/upload, which needs the `content:write` scope. - # Any other token, or none, uses the v1 endpoint as before. + # Since WEB-8371, BETAMAX_SERVICE_API_TOKEN must be robles's `kst_` token: + # any other token, or none, is refused before a request is made. class VideoCourseUploader include Util::Logging attr_reader :video_course - UPLOAD_URL = '/api/v1/collections/upload' V2_UPLOAD_PATH = '/api/v2/collections/upload' - # Net::HTTP's default read timeout, which v1 has always had: storing a - # big course takes a while. + # Net::HTTP's default read timeout, which uploads have always had: + # storing a big course takes a while. V2_TIMEOUT = 60 def self.upload(video_course) @@ -24,59 +23,30 @@ def self.upload(video_course) end # In a real run `token` is always BETAMAX_SERVICE_API_TOKEN. The keywords - # let the tests choose a path. + # let the tests supply a token and a client. def initialize(video_course, token: BETAMAX_SERVICE_API_TOKEN, client: nil) @video_course = video_course @token = token @client = client end + # The body is the one v1 took. Errors aren't rescued: the runner reports + # them to Slack and fails the step. def upload - return upload_with_api_v2 if Api::V2Client.service_token?(@token) - - conn.post do |req| - req.url api_uri - req.body = payload - end - end - - private - - # Sends v1's payload, so both paths send the same bytes. Errors aren't - # rescued: the runner reports them to Slack and fails the step. - def upload_with_api_v2 + Api::V2Client.require_service_token!(@token, name: 'BETAMAX_SERVICE_API_TOKEN', service: 'betamax') response = client.post(V2_UPLOAD_PATH, payload) collection_id = response.data['id'] if response.data.is_a?(Hash) logger.info("Uploaded video course #{video_course.shortcode} #{video_course.version} to betamax API v2: collection #{collection_id}") response end - # Built lazily, so the v1 path never builds it + private + + # Built lazily, after the token check def client @client ||= Api::V2Client.new(base_url: BETAMAX_BASE_URL, token: @token, timeout: V2_TIMEOUT) end - def api_uri - path = [ - BETAMAX_BASE_URL, - UPLOAD_URL - ].join - - URI(path) - end - - def conn - @conn ||= Faraday.new(headers: { 'Content-Type' => 'application/json' }) do |faraday| - faraday.response(:logger, logger) do |logger| - logger.filter(/(Token token=\\")(\w+)/, '\1[REMOVED]') - end - faraday.response(:raise_error) - faraday.adapter(Faraday.default_adapter) - faraday.request(:authorization, 'Bearer', BETAMAX_SERVICE_API_TOKEN) - faraday.request(:retry) - end - end - def payload { video_course: }.to_json end diff --git a/app/lib/api/v2_client.rb b/app/lib/api/v2_client.rb index f0ad2f5..5b788ff 100644 --- a/app/lib/api/v2_client.rb +++ b/app/lib/api/v2_client.rb @@ -9,16 +9,31 @@ module Api class V2Client include Util::Logging - # The switch for WEB-8205 and WEB-8206. A content repo turns API v2 on by - # storing robles's `kst_robles_` token in its existing secret, and off by - # writing the shared token back (WEB-8208). It's the same prefix test - # guardpost_rails uses to tell a service token apart. + # robles's API v2 token starts with this. It's the same prefix test + # guardpost_rails uses to tell a service token apart. API v2 is the only + # upload path, so any other token is refused before a request (WEB-8371). TOKEN_PREFIX = 'kst_' + # Never includes the token, and names no people, channels or hosts, + # because robles is public. It shows in the Actions log and in Slack. + TOKEN_MESSAGE = "Can't publish to %s: %s is empty or isn't robles's API v2 token, " \ + 'which starts with "kst_". The old shared token no longer works. ' \ + "Ask Kodeco engineering for robles's kst_ token, and save it in this repo's " \ + '%s_STAGING or %s_PRODUCTION Actions secret.' + + # Raised before any request, so it isn't an Error + class TokenError < StandardError; end + def self.service_token?(token) token.is_a?(String) && token.start_with?(TOKEN_PREFIX) end + def self.require_service_token!(token, name:, service:) + return if service_token?(token) + + raise TokenError, format(TOKEN_MESSAGE, name:, service:) + end + Response = Data.define(:status, :data, :meta) class Error < StandardError @@ -34,8 +49,9 @@ def initialize(message, status: nil, code: nil, details: nil) attr_reader :base_url - # The timeouts match content_module_uploader.rb, because a publish can be - # slow. WEB-8206 passes its own `timeout:`. + # Generous timeouts, because publishing a whole module can be slow, but + # bounded so a hung service fails instead of hanging CI. WEB-8206 passes + # its own `timeout:`. def initialize(base_url:, token:, open_timeout: 10, timeout: 120, adapter: Faraday.default_adapter) raise ArgumentError, 'base_url is required' if base_url.blank? raise ArgumentError, 'token is required' if token.blank? diff --git a/config/initialisers/alexandria.rb b/config/initialisers/alexandria.rb index d0d1535..8336772 100644 --- a/config/initialisers/alexandria.rb +++ b/config/initialisers/alexandria.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true ALEXANDRIA_BASE_URL = ENV.fetch('ALEXANDRIA_BASE_URL', nil) -# A value that starts with `kst_` is robles's API v2 token and publishes through -# /api/v2 (WEB-8205, WEB-8208). Anything else is the shared token and uses v1. +# robles's API v2 token, which starts with `kst_` (WEB-8205, WEB-8208). Any other +# value is refused before a publish (WEB-8371). ALEXANDRIA_SERVICE_API_TOKEN = ENV.fetch('ALEXANDRIA_SERVICE_API_TOKEN', nil) diff --git a/test/api/alexandria/book_uploader_test.rb b/test/api/alexandria/book_uploader_test.rb index c47e3fc..9e8ba32 100644 --- a/test/api/alexandria/book_uploader_test.rb +++ b/test/api/alexandria/book_uploader_test.rb @@ -10,14 +10,15 @@ class BookUploaderTest < Minitest::Test include TestHelpers include V2ClientStubs - # Stands in for Api::V2Client on the v1 path, where it must never be used + # Stands in for Api::V2Client when the token is refused, and fails the + # test if it's called class UnusedClient def initialize(test) @test = test end def post(*) - @test.flunk('the v1 path called the API v2 client') + @test.flunk('a refused token called the API v2 client') end end @@ -41,41 +42,15 @@ def edition_fixture alexandria_api_v2_fixture('edition_publish.json') end - # v1's `conn` is memoised and robles has no stubbing library, so the tests - # hand it a connection on Faraday's test adapter through @conn. - def stub_v1(uploader) - @v1_requests = [] - stubs = Faraday::Adapter::Test::Stubs.new do |stub| - stub.post(/.*/) do |env| - @v1_requests << env - [200, JSON_HEADERS, '{}'] - end - end - uploader.instance_variable_set(:@conn, Faraday.new { |faraday| faraday.adapter(:test, stubs) }) - uploader - end - - def test_shared_token_uses_v1 - uploader = stub_v1(BookUploader.new(book, token: SHARED_TOKEN, client: UnusedClient.new(self))) - uploader.upload + def test_shared_token_is_refused + uploader = BookUploader.new(book, token: SHARED_TOKEN, client: UnusedClient.new(self)) - assert_equal 1, @v1_requests.size - assert_equal '/api/editions/publish', @v1_requests.first.url.path + assert_token_refused('ALEXANDRIA_SERVICE_API_TOKEN', SHARED_TOKEN) { uploader.upload } end - def test_no_token_uses_v1 - uploader = stub_v1(BookUploader.new(book, token: nil, client: UnusedClient.new(self))) - uploader.upload - - assert_equal 1, @v1_requests.size - assert_equal '/api/editions/publish', @v1_requests.first.url.path - end - - def test_default_token_in_tests_uses_v1 - uploader = stub_v1(BookUploader.new(book)) - uploader.upload - - assert_equal '/api/editions/publish', @v1_requests.first.url.path + # The test env sets no ALEXANDRIA_SERVICE_API_TOKEN + def test_no_token_is_refused + assert_token_refused('ALEXANDRIA_SERVICE_API_TOKEN', nil) { BookUploader.new(book).upload } end def test_kst_token_uses_v2 @@ -90,13 +65,6 @@ def test_kst_token_uses_v2 assert_equal uploader.send(:payload), request.request_body end - def test_kst_token_never_builds_v1 - uploader = BookUploader.new(book, token: KST_TOKEN, client: v2_test_client { [201, JSON_HEADERS, edition_fixture] }) - uploader.upload - - assert_nil uploader.instance_variable_get(:@conn) - end - def test_kst_token_validation_failed uploader = BookUploader.new(book, token: KST_TOKEN, client: v2_test_client { [422, JSON_HEADERS, VALIDATION_FAILED_BODY] }) error = assert_raises(Api::V2Client::Error) { uploader.upload } diff --git a/test/api/alexandria/content_module_uploader_test.rb b/test/api/alexandria/content_module_uploader_test.rb index 8dd36c0..57169bd 100644 --- a/test/api/alexandria/content_module_uploader_test.rb +++ b/test/api/alexandria/content_module_uploader_test.rb @@ -10,14 +10,15 @@ class ContentModuleUploaderTest < Minitest::Test include TestHelpers include V2ClientStubs - # Stands in for Api::V2Client on the v1 path, where it must never be used + # Stands in for Api::V2Client when the token is refused, and fails the + # test if it's called class UnusedClient def initialize(test) @test = test end def post(*) - @test.flunk('the v1 path called the API v2 client') + @test.flunk('a refused token called the API v2 client') end end @@ -43,42 +44,16 @@ def content_module_fixture alexandria_api_v2_fixture('content_module_publish.json') end - # v1's `conn` is memoised and robles has no stubbing library, so the tests - # hand it a connection on Faraday's test adapter through @conn. - def stub_v1(uploader) - @v1_requests = [] - stubs = Faraday::Adapter::Test::Stubs.new do |stub| - stub.post(/.*/) do |env| - @v1_requests << env - [200, JSON_HEADERS, '{}'] - end - end - uploader.instance_variable_set(:@conn, Faraday.new { |faraday| faraday.adapter(:test, stubs) }) - uploader - end + def test_shared_token_is_refused + uploader = ContentModuleUploader.new(content_module, token: SHARED_TOKEN, client: UnusedClient.new(self)) - def test_shared_token_uses_v1 - uploader = stub_v1(ContentModuleUploader.new(content_module, token: SHARED_TOKEN, client: UnusedClient.new(self))) - uploader.upload - - assert_equal 1, @v1_requests.size - assert_equal '/api/content_modules/publish', @v1_requests.first.url.path - refute_includes @log.string, 'Api::V2Client' + assert_token_refused('ALEXANDRIA_SERVICE_API_TOKEN', SHARED_TOKEN) { uploader.upload } + refute_includes @log.string, 'Publishing content module' end - def test_no_token_uses_v1 - uploader = stub_v1(ContentModuleUploader.new(content_module, token: nil, client: UnusedClient.new(self))) - uploader.upload - - assert_equal 1, @v1_requests.size - assert_equal '/api/content_modules/publish', @v1_requests.first.url.path - end - - def test_default_token_in_tests_uses_v1 - uploader = stub_v1(ContentModuleUploader.new(content_module)) - uploader.upload - - assert_equal '/api/content_modules/publish', @v1_requests.first.url.path + # The test env sets no ALEXANDRIA_SERVICE_API_TOKEN + def test_no_token_is_refused + assert_token_refused('ALEXANDRIA_SERVICE_API_TOKEN', nil) { ContentModuleUploader.new(content_module).upload } end def test_kst_token_uses_v2 @@ -100,13 +75,6 @@ def test_kst_token_logs_api_v2 assert_includes @log.string, 'Api::V2Client POST /api/v2/content_modules/publish 201' end - def test_kst_token_never_builds_v1 - uploader = ContentModuleUploader.new(content_module, token: KST_TOKEN, client: v2_test_client { [201, JSON_HEADERS, content_module_fixture] }) - uploader.upload - - assert_nil uploader.instance_variable_get(:@conn) - end - def test_kst_token_validation_failed uploader = ContentModuleUploader.new(content_module, token: KST_TOKEN, client: v2_test_client { [422, JSON_HEADERS, VALIDATION_FAILED_BODY] }) error = assert_raises(Api::V2Client::Error) { uploader.upload } @@ -121,13 +89,12 @@ def test_kst_token_server_error assert_equal 1, @requests.size end - # v1's rescue logs "Alexandria publish failed"; its absence shows a v2 - # failure never goes through it. - def test_kst_token_timeout_skips_v1_rescue + def test_kst_token_timeout uploader = ContentModuleUploader.new(content_module, token: KST_TOKEN, client: v2_test_client { raise Faraday::TimeoutError, 'execution expired' }) - assert_raises(Api::V2Client::Error) { uploader.upload } + error = assert_raises(Api::V2Client::Error) { uploader.upload } - refute_includes @log.string, 'Alexandria publish failed' + refute_kind_of Faraday::Error, error + assert_includes error.message, 'Faraday::TimeoutError' end # The test env sets no ALEXANDRIA_BASE_URL, so the real client refuses to diff --git a/test/api/betamax/video_course_uploader_test.rb b/test/api/betamax/video_course_uploader_test.rb index dd7021d..ac28d84 100644 --- a/test/api/betamax/video_course_uploader_test.rb +++ b/test/api/betamax/video_course_uploader_test.rb @@ -22,14 +22,15 @@ class VideoCourseUploaderTest < Minitest::Test # route returns NOT_FOUND = '{"status":404,"error":"Fixture: not found"}' - # Stands in for Api::V2Client on the v1 path, where it must never be used + # Stands in for Api::V2Client when the token is refused, and fails the + # test if it's called class UnusedClient def initialize(test) @test = test end def post(*) - @test.flunk('the v1 path called the API v2 client') + @test.flunk('a refused token called the API v2 client') end end @@ -50,7 +51,7 @@ def course @course ||= VideoCourse.new(shortcode: 'ios101', version: '1.0', title: 'iOS 101 with Swift') end - def v1_body + def upload_body { video_course: course }.to_json end @@ -65,39 +66,15 @@ def uploader_answering(status, body) VideoCourseUploader.new(course, token: KST_TOKEN, client: v2_test_client { [status, JSON_HEADERS, body] }) end - # v1's `conn` is memoised and robles has no stubbing library, so the tests - # hand it a connection on Faraday's test adapter through @conn. - def stub_v1(uploader) - @v1_requests = [] - stubs = Faraday::Adapter::Test::Stubs.new do |stub| - stub.post(/.*/) do |env| - @v1_requests << env - [200, JSON_HEADERS, '{}'] - end - end - uploader.instance_variable_set(:@conn, Faraday.new { |faraday| faraday.adapter(:test, stubs) }) - uploader - end - - def assert_v1_upload - assert_equal 1, @v1_requests.size - request = @v1_requests.first - assert_equal :post, request.method - assert_equal '/api/v1/collections/upload', request.url.path - assert_equal v1_body, request.request_body - end - - def test_shared_token_uses_v1 - stub_v1(VideoCourseUploader.new(course, token: SHARED_TOKEN, client: UnusedClient.new(self))).upload + def test_shared_token_is_refused + uploader = VideoCourseUploader.new(course, token: SHARED_TOKEN, client: UnusedClient.new(self)) - assert_v1_upload + assert_token_refused('BETAMAX_SERVICE_API_TOKEN', SHARED_TOKEN) { uploader.upload } end - # The test environment sets no BETAMAX_SERVICE_API_TOKEN - def test_no_token_uses_v1 - stub_v1(VideoCourseUploader.new(course, client: UnusedClient.new(self))).upload - - assert_v1_upload + # The test env sets no BETAMAX_SERVICE_API_TOKEN + def test_no_token_is_refused + assert_token_refused('BETAMAX_SERVICE_API_TOKEN', nil) { VideoCourseUploader.new(course).upload } end def test_kst_token_uploads_to_v2 @@ -110,16 +87,14 @@ def test_kst_token_uploads_to_v2 assert_equal :post, request.method assert_equal V2_PATH, request.url.path assert_equal "Bearer #{KST_TOKEN}", request.request_headers['Authorization'] - assert_equal v1_body, request.request_body + assert_equal upload_body, request.request_body end - def test_kst_token_logs_and_never_builds_v1 - uploader = uploader_answering(201, betamax_fixture('collection_upload.json')) - uploader.upload + def test_kst_token_logs + uploader_answering(201, betamax_fixture('collection_upload.json')).upload assert_includes @log.string, 'ios101 1.0' assert_includes @log.string, 'collection 301' - assert_nil uploader.instance_variable_get(:@conn) end def test_kst_token_returns_nested_data diff --git a/test/api/v2_client_test.rb b/test/api/v2_client_test.rb index 67650a4..15a333f 100644 --- a/test/api/v2_client_test.rb +++ b/test/api/v2_client_test.rb @@ -41,6 +41,18 @@ def test_service_token refute Api::V2Client.service_token?("KST_robles_#{'a' * 43}") end + def test_require_service_token + assert_nil Api::V2Client.require_service_token!(KST_TOKEN, name: 'ALEXANDRIA_SERVICE_API_TOKEN', service: 'alexandria') + + [nil, '', SHARED_TOKEN, "KST_robles_#{'a' * 43}"].each do |token| + error = assert_token_refused('ALEXANDRIA_SERVICE_API_TOKEN', token) do + Api::V2Client.require_service_token!(token, name: 'ALEXANDRIA_SERVICE_API_TOKEN', service: 'alexandria') + end + assert error.message.start_with?("Can't publish to alexandria: ALEXANDRIA_SERVICE_API_TOKEN is empty") + refute_kind_of Api::V2Client::Error, error + end + end + def test_created_returns_data response = client_answering(201, edition_fixture).post(PATH, BODY) diff --git a/test/support/v2_client_stubs.rb b/test/support/v2_client_stubs.rb index 2518375..3175429 100644 --- a/test/support/v2_client_stubs.rb +++ b/test/support/v2_client_stubs.rb @@ -31,6 +31,18 @@ def v2_test_client(&handler) Api::V2Client.new(base_url: 'https://alexandria.test', token: KST_TOKEN, adapter: [:test, stubs]) end + # WEB-8371: a refused token raises Api::V2Client::TokenError, whose message + # names the variable and its two Actions secrets and never holds the token + def assert_token_refused(name, token, &) + error = assert_raises(Api::V2Client::TokenError, &) + + assert_includes error.message, name + assert_includes error.message, "#{name}_STAGING" + assert_includes error.message, "#{name}_PRODUCTION" + refute_includes error.message, token if token.present? + error + end + def alexandria_api_v2_fixture(name) File.read(File.expand_path("../fixtures/alexandria_api_v2/#{name}", __dir__)) end