Skip to content
Closed
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
5 changes: 4 additions & 1 deletion lib/rpush/daemon/google_credential_cache.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ def access_token(scope, json_key)
private

def fetch_fresh_token(scope, json_key)
json_key_io = json_key ? StringIO.new(json_key) : nil
# A caller's json_key attribute may come back as an already-parsed Hash
# (e.g. from a native json/jsonb DB column, which ActiveRecord deserializes
# on read) rather than the raw JSON text StringIO requires.
json_key_io = json_key ? StringIO.new(json_key.is_a?(String) ? json_key : json_key.to_json) : nil
log_debug("FCM - Obtaining access token.")
authorizer = Google::Auth::ServiceAccountCredentials.make_creds(scope: scope, json_key_io: json_key_io)
authorizer.fetch_access_token
Expand Down
45 changes: 45 additions & 0 deletions spec/unit/daemon/google_credential_cache_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
require 'unit_spec_helper'

describe Rpush::Daemon::GoogleCredentialCache do
subject { described_class.instance }

let(:scope) { 'https://www.googleapis.com/auth/firebase.messaging' }
let(:json_key_hash) do
{
'type' => 'service_account',
'project_id' => 'curry-pizza-house',
'private_key' => "-----BEGIN PRIVATE KEY-----\nfake\n-----END PRIVATE KEY-----\n",
'client_email' => 'fcm-push-sender@thanx-shared-infra.iam.gserviceaccount.com',
'token_uri' => 'https://oauth2.googleapis.com/token'
}
end
let(:authorizer) { double(fetch_access_token: { 'access_token' => 'fake-token' }) }

before do
subject.instance_variable_set(:@credentials_cache, {})
end

describe '#access_token' do
context 'when json_key is a Hash (matches production: rpush_apps.json_key is a native json column, which ActiveRecord deserializes to a Hash on read)' do
it 'builds the credential stream from it instead of raising' do
expect(Google::Auth::ServiceAccountCredentials).to receive(:make_creds) do |scope:, json_key_io:|
expect(JSON.parse(json_key_io.read)).to eq(json_key_hash)
authorizer
end

expect(subject.access_token(scope, json_key_hash)).to eq('access_token' => 'fake-token')
end
end

context 'when json_key is already a String' do
it 'still builds the credential stream correctly' do
expect(Google::Auth::ServiceAccountCredentials).to receive(:make_creds) do |scope:, json_key_io:|
expect(JSON.parse(json_key_io.read)).to eq(json_key_hash)
authorizer
end

expect(subject.access_token(scope, json_key_hash.to_json)).to eq('access_token' => 'fake-token')
end
end
end
end
Loading