Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
45 changes: 7 additions & 38 deletions app/lib/api/alexandria/book_uploader.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,69 +2,38 @@

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)
new(book).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(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
Expand Down
91 changes: 9 additions & 82 deletions app/lib/api/alexandria/content_module_uploader.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
54 changes: 12 additions & 42 deletions app/lib/api/betamax/video_course_uploader.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,79 +4,49 @@ 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)
new(video_course).upload
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
Expand Down
28 changes: 22 additions & 6 deletions app/lib/api/v2_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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 %<service>s: %<name>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 " \
'%<name>s_STAGING or %<name>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
Expand All @@ -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?
Expand Down
4 changes: 2 additions & 2 deletions config/initialisers/alexandria.rb
Original file line number Diff line number Diff line change
@@ -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)
Loading
Loading