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
11 changes: 6 additions & 5 deletions app/jobs/magic_link_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
class MagicLinkJob < ApplicationJob
queue_as :default

# The raw token travels as a job argument because only its digest is stored on
# the User::MagicLink row. That puts it in the job backend's payload for the
# life of the job; it is deleted with the job record and dies with the link's
# 15-minute expiry regardless. Active Job writes job arguments to the log
# by default, so that is turned off here: the log outlives the job.
# Only the digest of the token is stored on the User::MagicLink row, so the
# raw token travels as a job argument. The caller wraps it in LinkToken,
# which stores it encrypted in the queue row. Active Job also writes job
# arguments to the log by default, so that is turned off here.
self.log_arguments = false

before_enqueue { |job| LinkToken.refuse_plain!(job.arguments) }

def perform(user, token)
MagicLinkMailer.login_link(user, token).deliver_now
end
Expand Down
6 changes: 5 additions & 1 deletion app/jobs/token_mail_delivery_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@
# (MagicLinkMailer, GuardianConsentMailer). Active Job writes job arguments to
# the log by default. A token in the log would let a reader of the log use the
# link, so this job keeps its arguments out. Set it with
# `self.delivery_job = TokenMailDeliveryJob` on such a mailer.
# `self.delivery_job = TokenMailDeliveryJob` on such a mailer, and pass the
# token as `LinkToken.new(token)`, so the queue row holds it encrypted.
class TokenMailDeliveryJob < ActionMailer::MailDeliveryJob
self.log_arguments = false

# The arguments of the mailer action (records and LinkTokens) are in `args`.
before_enqueue { |job| LinkToken.refuse_plain!(job.arguments.last.values_at(:args, :params)) }

end
2 changes: 1 addition & 1 deletion app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -581,7 +581,7 @@ def revoke_oauth_access!
# User::MagicLink for why.
def send_magic_link(requested_ip: nil, return_to: nil)
link = User::MagicLink.issue!(self, requested_ip: requested_ip, return_to: return_to)
MagicLinkJob.perform_later(self, link.token)
MagicLinkJob.perform_later(self, LinkToken.new(link.token))
true
rescue ActiveRecord::RecordInvalid => e
Rails.logger.error "Failed to issue magic link for user #{email}: #{e.record.errors.full_messages.join(', ')}"
Expand Down
6 changes: 3 additions & 3 deletions app/services/guardian_consent_flow.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def request(user, guardian_name:, guardian_email:)
consent = GuardianConsent.issue!(user, guardian_name:, guardian_email:)
return Result.new(consent:, errors: consent.errors.to_hash.transform_values(&:first)) unless consent.persisted?

GuardianConsentMailer.request_consent(consent, consent.token).deliver_later
GuardianConsentMailer.request_consent(consent, LinkToken.new(consent.token)).deliver_later
Result.new(consent:, errors: {})
end

Expand All @@ -31,7 +31,7 @@ def resend(consent)
return false unless consent.pending? && consent.resend_allowed?

consent.reissue!
GuardianConsentMailer.request_consent(consent, consent.token).deliver_later
GuardianConsentMailer.request_consent(consent, LinkToken.new(consent.token)).deliver_later
true
end

Expand All @@ -42,7 +42,7 @@ def grant(consent, token:, signed_name:, ip:, user_agent:, fingerprint: nil)

flag(consent)

GuardianConsentMailer.receipt(consent, token).deliver_later
GuardianConsentMailer.receipt(consent, LinkToken.new(token)).deliver_later
GuardianConsentMailer.granted(consent).deliver_later
true
end
Expand Down
6 changes: 5 additions & 1 deletion config/application.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
require_relative "../lib/credentials_paths"
require_relative "../lib/weave"
require_relative "../lib/link_token_path"
require_relative "../lib/link_token"

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Expand Down Expand Up @@ -34,7 +35,7 @@ class Application < Rails::Application
# Zeitwerk exists. config/initializers/flipper.rb requires feature_flags by
# hand, because an initializer cannot use a reloadable constant. So does
# config/initializers/console_access.rb for console_access.
config.autoload_lib(ignore: %w[assets tasks credentials_paths.rb weave.rb link_token_path.rb feature_flags.rb feature_flags console_access.rb console_access])
config.autoload_lib(ignore: %w[assets tasks credentials_paths.rb weave.rb link_token_path.rb link_token.rb feature_flags.rb feature_flags console_access.rb console_access])

# Keep the credentials file and the key that opens it in lockstep; Rails
# resolves them independently and will otherwise pair a per-environment
Expand Down Expand Up @@ -65,6 +66,9 @@ class Application < Rails::Application
# config.time_zone = "Central Time (US & Canada)"
# config.eager_load_paths << Rails.root.join("extras")

# Store a link token encrypted in the job arguments (see lib/link_token.rb).
config.active_job.custom_serializers << LinkToken::Serializer

# How long a finished job row stays (see clear_finished_jobs in
# config/recurring.yml). The row holds the job arguments.
config.solid_queue.clear_finished_jobs_after = 1.day
Expand Down
67 changes: 67 additions & 0 deletions lib/link_token.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# frozen_string_literal: true

# A raw link token (magic link, guardian consent) on its way to a job.
#
# A job argument is stored as plain text in the queue table until the row is
# deleted, and /admin/jobs shows it. A token wrapped in LinkToken is stored
# encrypted, so a queue row never holds a usable link. A failed job can thus
# stay for a retry with no time limit.
#
# Wrap the token where the job or the mail is enqueued:
#
# MagicLinkJob.perform_later(user, LinkToken.new(token))
# GuardianConsentMailer.receipt(consent, LinkToken.new(token)).deliver_later
#
# A URL helper reads it through to_param, like a String, so a mailer takes
# both. Jobs that were queued before this class existed hold a String.
class LinkToken
attr_reader :raw

def initialize(raw)
@raw = raw.is_a?(LinkToken) ? raw.raw : raw.to_s
raise ArgumentError, "a link token cannot be blank" if @raw.empty?
end

# A job that enqueues a token calls this in before_enqueue, so a caller
# that forgets to wrap the token fails at once, not in the queue table.
# A job that is already in the queue with a plain token still runs.
def self.refuse_plain!(*values)
return unless values.flatten.any?(String)

raise ArgumentError, "pass a link token to a job as LinkToken.new(token), not as a String"
end

def to_param = raw

def ==(other) = other.is_a?(LinkToken) && other.raw == raw
alias eql? ==

delegate :hash, to: :raw

def inspect = "#<LinkToken [FILTERED]>"

def as_json(*) = "[FILTERED]"

# The key comes from secret_key_base. After a rotation of that secret, a
# job that is still in the queue cannot be read and fails.
def self.encryptor
@encryptor ||= ActiveSupport::MessageEncryptor.new(
Rails.application.key_generator.generate_key("LinkToken job argument", ActiveSupport::MessageEncryptor.key_len)
)
end

# Registered in config/application.rb.
class Serializer < ActiveJob::Serializers::ObjectSerializer
def serialize(token)
super("value" => LinkToken.encryptor.encrypt_and_sign(token.raw))
end

def deserialize(hash)
LinkToken.new(LinkToken.encryptor.decrypt_and_verify(hash["value"]))
end

def klass = LinkToken

end

end
92 changes: 92 additions & 0 deletions spec/jobs/link_token_job_arguments_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# frozen_string_literal: true

require "rails_helper"

# The queue table stores job arguments as text, and /admin/jobs shows them. A
# link token must be stored encrypted (LinkToken), and the mail must still
# hold the link that works.
RSpec.describe "Link tokens in job arguments", type: :job do
include ActiveJob::TestHelper

# What the queue adapter writes to the queue table.
def stored_arguments = enqueued_jobs.map { |job| job[:args].to_json }.join("\n")

it "stores the magic link token encrypted, and mails the link that works" do
user = create(:user)

user.send_magic_link
stored = stored_arguments
perform_enqueued_jobs
token = ActionMailer::Base.deliveries.last.body.encoded[/\/auth\/magic_link\/([\w-]+)/, 1]

expect(User::MagicLink.find_by(token_digest: User::MagicLink.digest_for(token)).user).to eq(user)
expect(stored).to include("LinkToken::Serializer")
expect(stored).not_to include(token)
end

it "stores the guardian consent request token encrypted, and mails the link that works" do
member = create(:user, :verified, :minor)

consent = GuardianConsentFlow.request(member, guardian_name: "Pat Parent", guardian_email: "[email protected]").consent
stored = stored_arguments
perform_enqueued_jobs

expect(stored).not_to include(consent.token)
expect(ActionMailer::Base.deliveries.last.body.encoded).to include("/guardian/#{consent.token}")
expect(GuardianConsent.for_token(consent.token)).to eq(consent)
end

it "stores the token of the guardian receipt encrypted, and mails the revoke link" do
consent = create(:guardian_consent, raw_token: "receipt-raw-token-0123456789")

GuardianConsentFlow.grant(consent, token: "receipt-raw-token-0123456789", signed_name: "Pat Parent",
ip: "203.0.113.5", user_agent: "Spec")
stored = stored_arguments
perform_enqueued_jobs

expect(stored).not_to include("receipt-raw-token-0123456789")
receipt = ActionMailer::Base.deliveries.find { |mail| mail.to == [consent.guardian_email] }
expect(receipt.body.encoded).to include("/guardian/receipt-raw-token-0123456789")
end

it "still runs a job that was queued with a plain token before the change" do
user = create(:user)

MagicLinkJob.perform_now(user, "plain-token-from-an-old-job")

expect(ActionMailer::Base.deliveries.last.body.encoded).to include("/auth/magic_link/plain-token-from-an-old-job")
end

it "refuses a stored token that was changed" do
stored = LinkToken::Serializer.serialize(LinkToken.new("raw"))

expect { LinkToken::Serializer.deserialize(stored.merge("value" => "#{stored['value']}x")) }
.to raise_error(ActiveSupport::MessageEncryptor::InvalidMessage)
end

it "refuses to enqueue a plain token" do
user = create(:user)
consent = create(:guardian_consent)

expect { MagicLinkJob.perform_later(user, "plain-token") }.to raise_error(ArgumentError, /LinkToken/)
expect { GuardianConsentMailer.receipt(consent, "plain-token").deliver_later }.to raise_error(ArgumentError, /LinkToken/)
expect(enqueued_jobs).to be_empty
end

it "still enqueues the guardian mails that have no token" do
consent = create(:guardian_consent, :granted)

expect { GuardianConsentMailer.granted(consent).deliver_later }.to have_enqueued_mail(GuardianConsentMailer, :granted)
end

it "does not show the token when it is inspected or written as JSON" do
token = LinkToken.new("raw-secret")

expect(token.inspect).not_to include("raw-secret")
expect({ arguments: [token] }.to_json).not_to include("raw-secret")
end

it "does not wrap a token two times" do
expect(LinkToken.new(LinkToken.new("raw-secret")).to_param).to eq("raw-secret")
end
end
6 changes: 3 additions & 3 deletions spec/jobs/token_job_logging_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
it "keeps the magic link token out of the job log" do
user = create(:user)

perform_enqueued_jobs { MagicLinkJob.perform_later(user, "raw-magic-token") }
perform_enqueued_jobs { MagicLinkJob.perform_later(user, LinkToken.new("raw-magic-token")) }

expect(log.string).to include("MagicLinkJob")
expect(log.string).not_to include("raw-magic-token")
Expand All @@ -31,8 +31,8 @@
consent = create(:guardian_consent)

perform_enqueued_jobs do
GuardianConsentMailer.request_consent(consent, "raw-consent-token").deliver_later
GuardianConsentMailer.receipt(consent, "raw-receipt-token").deliver_later
GuardianConsentMailer.request_consent(consent, LinkToken.new("raw-consent-token")).deliver_later
GuardianConsentMailer.receipt(consent, LinkToken.new("raw-receipt-token")).deliver_later
end

expect(log.string).to include("TokenMailDeliveryJob")
Expand Down
Loading