Skip to content

Commit e674130

Browse files
committed
encryption support for trigger_batch
1 parent 4d24158 commit e674130

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

lib/pusher/client.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -444,7 +444,11 @@ def trigger_batch_params(events)
444444
{
445445
batch: events.map do |event|
446446
event.dup.tap do |e|
447-
e[:data] = encode_data(e[:data])
447+
e[:data] = if e[:channel].match(/^private-encrypted-/) then
448+
encrypt(e[:channel], encode_data(e[:data]))
449+
else
450+
encode_data(e[:data])
451+
end
448452
end
449453
end
450454
}

spec/client_spec.rb

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,55 @@
408408
)
409409
}
410410
end
411+
412+
it "should fail to publish to encrypted channels when missing key" do
413+
@client.encryption_master_key_base64 = nil
414+
expect {
415+
@client.trigger_batch(
416+
{
417+
channel: 'private-encrypted-channel',
418+
name: 'event',
419+
data: {'some' => 'data'},
420+
},
421+
{channel: 'mychannel', name: 'event', data: 'already encoded'},
422+
)
423+
}.to raise_error(Pusher::ConfigurationError)
424+
expect(WebMock).not_to have_requested(:post, @api_path)
425+
end
426+
427+
it "should encrypt publishes to encrypted channels" do
428+
@client.trigger_batch(
429+
{
430+
channel: 'private-encrypted-channel',
431+
name: 'event',
432+
data: {'some' => 'data'},
433+
},
434+
{channel: 'mychannel', name: 'event', data: 'already encoded'},
435+
)
436+
437+
expect(WebMock).to have_requested(:post, @api_path).with { |req|
438+
batch = MultiJson.decode(req.body)["batch"]
439+
expect(batch.length).to eq(2)
440+
441+
expect(batch[0]["channel"]).to eq("private-encrypted-channel")
442+
expect(batch[0]["name"]).to eq("event")
443+
444+
data = MultiJson.decode(batch[0]["data"])
445+
446+
key = RbNaCl::Hash.sha256(
447+
'private-encrypted-channel' + encryption_master_key
448+
)
449+
450+
expect(MultiJson.decode(RbNaCl::SecretBox.new(key).decrypt(
451+
Base64.decode64(data["nonce"]),
452+
Base64.decode64(data["ciphertext"]),
453+
))).to eq({ 'some' => 'data' })
454+
455+
expect(batch[1]["channel"]).to eq("mychannel")
456+
expect(batch[1]["name"]).to eq("event")
457+
expect(batch[1]["data"]).to eq("already encoded")
458+
}
459+
end
411460
end
412461

413462
describe '#trigger_async' do

0 commit comments

Comments
 (0)