Signal-iOS/SignalServiceKit/tests/Messages/MessageDecryptionTest.swift
Evan Hahn 370ff654e7
Change license to AGPL
Change license to AGPL

This commit:

- Updates the `LICENSE` file

- Start every file with something like:

      // Copyright YEAR_FIRST_PUBLISHED Signal Messenger, LLC
      // SPDX-License-Identifier: AGPL-3.0-only

---

First, I removed existing license headers with this Ruby 3.1.2 script:

    require 'set'

    EXTENSIONS_TO_CHECK = Set['.h', '.hpp', '.cpp', '.m', '.mm', '.pch', '.swift']

    same = 0
    different = 0

    all_files = `git ls-files`.lines.map { |line| line.strip }
    all_files.each do |relative_path|
      if relative_path == 'Pods'
        next
      end

      unless EXTENSIONS_TO_CHECK.include? File.extname(relative_path)
        next
      end

      path = File.expand_path(relative_path)

      contents = File.read(path)
      new_contents = contents.sub(/\/\/\n\/\/  Copyright .*\n\/\/\n\n/, '')

      if contents == new_contents
        same += 1
      else
        different += 1
      end

      File.write(path, new_contents)
    end

    puts "updated #{different} file(s), left #{same} untouched"

I'm sure this script could be improved, but it worked well enough.

Then, I created `Scripts/lint/lint-license-headers` and ran it to auto-
fix a lot of files. This changed the mode of some files, but I think
that's actually desirable. For example,
`SignalServiceKit/src/Util/AppContext.m` previously had a mode of
`0755/-rwxr-xr-x`, and it's now `0644/-rw-r--r--`.

Then I fixed some stragglers and updated the precommit script.

See [a similar change in the Desktop app][0].

[0]: 8bfaf598af
2022-10-13 08:25:37 -05:00

200 lines
8.5 KiB
Swift

//
// Copyright 2022 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
//
import XCTest
@testable import SignalServiceKit
import LibSignalClient
class MessageDecryptionTest: SSKBaseTestSwift {
let localE164Identifier = "+13235551234"
let localAci = UUID()
let localPni = UUID()
let remoteE164Identifier = "+14715355555"
lazy var remoteClient: TestSignalClient = FakeSignalClient.generate(e164Identifier: remoteE164Identifier)
let localClient = LocalSignalClient()
let localPniClient = LocalSignalClient(identity: .pni)
let runner = TestProtocolRunner()
let sealedSenderTrustRoot = Curve25519.generateKeyPair()
// MARK: - Hooks
override func setUp() {
super.setUp()
// ensure local client has necessary "registered" state
identityManager.generateNewIdentityKey(for: .aci)
identityManager.generateNewIdentityKey(for: .pni)
tsAccountManager.registerForTests(withLocalNumber: localE164Identifier, uuid: localAci, pni: localPni)
(notificationsManager as! NoopNotificationsManager).expectErrors = true
(udManager as! OWSUDManagerImpl).trustRoot = try! sealedSenderTrustRoot.ecPublicKey()
}
// MARK: - Tests
private let message = "abc"
private func generateAndDecrypt(type: SSKProtoEnvelopeType,
destinationIdentity: OWSIdentity?,
destinationUuid: UUID? = nil,
handleResult: (Result<OWSMessageDecryptResult, Error>, SSKProtoEnvelope) -> Void) {
write { transaction in
let localClient: TestSignalClient
if destinationIdentity == .pni {
localClient = self.localPniClient
} else {
localClient = self.localClient
}
switch type {
case .ciphertext:
try! runner.initialize(senderClient: remoteClient,
recipientClient: localClient,
transaction: transaction)
case .prekeyBundle, .unidentifiedSender:
try! runner.initializePreKeys(senderClient: remoteClient,
recipientClient: localClient,
transaction: transaction)
default:
XCTFail("unsupported envelope type for this test: \(type)")
return
}
let ciphertext = try! runner.encrypt(message.data(using: .utf8)!,
senderClient: remoteClient,
recipient: localClient.protocolAddress,
context: transaction)
let envelopeBuilder = SSKProtoEnvelope.builder(timestamp: Date.ows_millisecondTimestamp())
envelopeBuilder.setType(type)
if let destinationUuid = destinationUuid {
envelopeBuilder.setDestinationUuid(destinationUuid.uuidString)
} else if destinationIdentity != nil {
envelopeBuilder.setDestinationUuid(localClient.uuidIdentifier)
} else {
XCTFail("Envelope that lacks a destination UUID")
return
}
if type == .unidentifiedSender {
let senderCert = SMKSecretSessionCipherTest.createCertificateFor(
trustRoot: sealedSenderTrustRoot.identityKeyPair,
senderAddress: try! SealedSenderAddress(e164: remoteClient.e164Identifier,
uuidString: remoteClient.uuidIdentifier,
deviceId: remoteClient.deviceId),
identityKey: remoteClient.identityKeyPair.identityKeyPair.publicKey,
expirationTimestamp: 13337)
let usmc = try! UnidentifiedSenderMessageContent(ciphertext,
from: senderCert,
contentHint: .default,
groupId: [])
envelopeBuilder.setContent(Data(try! sealedSenderEncrypt(usmc,
for: localClient.protocolAddress,
identityStore: remoteClient.identityKeyStore,
context: transaction)))
envelopeBuilder.setServerTimestamp(13336)
} else {
envelopeBuilder.setSourceUuid(remoteClient.uuidIdentifier)
envelopeBuilder.setSourceDevice(remoteClient.deviceId)
envelopeBuilder.setContent(Data(ciphertext.serialize()))
}
let envelope = try! envelopeBuilder.build()
handleResult(messageDecrypter.decryptEnvelope(envelope, envelopeData: nil, transaction: transaction),
envelope)
}
}
private func expectDecryptsSuccessfully(type: SSKProtoEnvelopeType, destinationIdentity: OWSIdentity) {
generateAndDecrypt(type: type, destinationIdentity: destinationIdentity) { result, originalEnvelope in
let decrypted = try! result.get()
XCTAssertNil(decrypted.envelopeData)
XCTAssertEqual(decrypted.identity, destinationIdentity)
XCTAssertNotNil(decrypted.plaintextData)
XCTAssertEqual(String(data: decrypted.plaintextData!, encoding: .utf8), message)
if type == .unidentifiedSender {
XCTAssertNotIdentical(decrypted.envelope, originalEnvelope)
} else {
XCTAssertIdentical(decrypted.envelope, originalEnvelope)
}
}
}
private func expectDecryptionFailure(type: SSKProtoEnvelopeType,
destinationIdentity: OWSIdentity,
destinationUuid: UUID? = nil,
isExpectedError: (Error) -> Bool) {
generateAndDecrypt(type: type,
destinationIdentity: destinationIdentity,
destinationUuid: destinationUuid) { result, _ in
switch result {
case .success:
XCTFail("should not have decrypted successfully")
case .failure(let error):
XCTAssert(isExpectedError(error), "unexpected error: \(error)")
}
}
}
func testDecryptWhisperExplicitAci() {
expectDecryptsSuccessfully(type: .ciphertext, destinationIdentity: .aci)
}
func testDecryptWhisperPni() {
expectDecryptionFailure(type: .ciphertext, destinationIdentity: .pni) { error in
if case MessageProcessingError.invalidMessageTypeForDestinationUuid = error {
return true
}
return false
}
}
func testDecryptPreKeyExplicitAci() {
expectDecryptsSuccessfully(type: .prekeyBundle, destinationIdentity: .aci)
}
func testDecryptPreKeyPni() {
expectDecryptsSuccessfully(type: .prekeyBundle, destinationIdentity: .pni)
}
func testDecryptPreKeyPniWithAciDestinationUuid() {
expectDecryptionFailure(type: .prekeyBundle,
destinationIdentity: .pni,
destinationUuid: localClient.uuid) { error in
if let error = error as? OWSError {
let underlyingError = error.errorUserInfo[NSUnderlyingErrorKey]
if case SSKSignedPreKeyStore.Error.noPreKeyWithId(_)? = underlyingError {
return true
}
}
return false
}
}
func testDecryptPreKeyPniWithWrongDestinationUuid() {
expectDecryptionFailure(type: .prekeyBundle,
destinationIdentity: .pni,
destinationUuid: UUID()) { error in
if case MessageProcessingError.wrongDestinationUuid = error {
return true
}
return false
}
}
func testDecryptSealedSenderPreKeyPni() {
expectDecryptionFailure(type: .unidentifiedSender, destinationIdentity: .pni) { error in
if case MessageProcessingError.invalidMessageTypeForDestinationUuid = error {
return true
}
return false
}
}
}