pEpObjCTests/PEPSessionTest.m
author buff <andreas@pep-project.org>
Fri, 10 Jul 2020 18:25:06 +0200
changeset 1684 97c548afe482
parent 1678 cb99213e03d9
permissions -rw-r--r--
merge IOSAD-177
     1 //
     2 //  PEPSessionTest.m
     3 //  pEpObjCAdapterTests
     4 //
     5 //  Created by Andreas Buff on 18.01.18.
     6 //  Copyright © 2018 p≡p. All rights reserved.
     7 //
     8 
     9 #import <XCTest/XCTest.h>
    10 
    11 #import "PEPObjCAdapterFramework.h"
    12 
    13 #import "PEPObjCAdapter.h"
    14 #import "PEPMessage.h"
    15 #import "PEPAttachment.h"
    16 #import "PEPTestUtils.h"
    17 #import "PEPSync.h"
    18 #import "PEPSendMessageDelegate.h"
    19 
    20 #import "PEPSessionTestNotifyHandshakeDelegate.h"
    21 #import "PEPSessionTestSendMessageDelegate.h"
    22 #import "PEPPassphraseCache+Reset.h"
    23 #import "PEPPassphraseProviderMock.h"
    24 
    25 @interface PEPSessionTest : XCTestCase
    26 
    27 @property (nonatomic) PEPSync *sync;
    28 @property (nonatomic) PEPSessionTestSendMessageDelegate *sendMessageDelegate;
    29 @property (nonatomic) PEPSessionTestNotifyHandshakeDelegate *notifyHandshakeDelegate;
    30 
    31 @end
    32 
    33 @implementation PEPSessionTest
    34 
    35 - (void)setUp
    36 {
    37     [super setUp];
    38 
    39     [self pEpCleanUp];
    40 
    41     [PEPObjCAdapter setUnEncryptedSubjectEnabled:NO];
    42 
    43     NSError *error = nil;
    44     XCTAssertTrue([PEPObjCAdapter configurePassphraseForNewKeys:nil error:&error]);
    45     XCTAssertNil(error);
    46 
    47     [PEPPassphraseCache reset];
    48 }
    49 
    50 - (void)tearDown
    51 {
    52     [self shutdownSync];
    53     [self pEpCleanUp];
    54     [super tearDown];
    55 }
    56 
    57 - (void)testTrustWords
    58 {
    59     PEPSession *session = [PEPSession new];
    60 
    61     NSError *error = nil;
    62     NSArray *trustwords = [session
    63                            trustwordsForFingerprint:@"DB47DB47DB47DB47DB47DB47DB47DB47DB47DB47"
    64                            languageID:@"en"
    65                            shortened:false
    66                            error:&error];
    67     XCTAssertNil(error);
    68     XCTAssertEqual([trustwords count], 10);
    69 
    70     for(id word in trustwords)
    71         XCTAssertEqualObjects(word, @"BAPTISMAL");
    72 }
    73 
    74 - (void)testGenKey
    75 {
    76     PEPSession *session = [PEPSession new];
    77 
    78     PEPIdentity *identMe = [[PEPIdentity alloc]
    79                             initWithAddress:@"pep.test.iosgenkey@pep-project.org"
    80                             userID:@"Me"
    81                             userName:@"pEp Test iOS GenKey"
    82                             isOwn:YES];
    83 
    84     NSError *error = nil;
    85     XCTAssertTrue([session mySelf:identMe error:&error]);
    86     XCTAssertNil(error);
    87 
    88     XCTAssertNotNil(identMe.fingerPrint);
    89     XCTAssertNotEqual(identMe.commType, PEPCommTypeUnknown);
    90 
    91     XCTAssertTrue([identMe isPEPUser:session error:&error]);
    92 }
    93 
    94 - (void)testMySelfCommType
    95 {
    96     PEPSession *session = [PEPSession new];
    97 
    98     PEPIdentity *identMe = [[PEPIdentity alloc]
    99                             initWithAddress:@"pep.test.iosgenkey@pep-project.org"
   100                             userID:@"pep.test.iosgenkey@pep-project.org_userID"
   101                             userName:@"pEp Test iOS GenKey"
   102                             isOwn:YES];
   103 
   104     NSError *error = nil;
   105     XCTAssertTrue([session mySelf:identMe error:&error]);
   106     XCTAssertNil(error);
   107 
   108     XCTAssertNotNil(identMe.fingerPrint);
   109     XCTAssertNotEqual(identMe.commType, PEPCommTypeUnknown);
   110 
   111     XCTAssertTrue([identMe isPEPUser:session error:&error]);
   112 
   113     dispatch_queue_t queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0);
   114     dispatch_sync(queue, ^{
   115         NSError *innerError = nil;
   116         PEPSession *session2 = [PEPSession new];
   117 
   118         // Now simulate an update from the app, which usually only caches
   119         // kPepUsername, kPepAddress and optionally kPepUserID.
   120         PEPIdentity *identMe2 = [[PEPIdentity alloc]
   121                                  initWithAddress:identMe.address
   122                                  userID:identMe.userID
   123                                  userName:identMe.userName
   124                                  isOwn:NO];
   125 
   126         XCTAssertTrue([session2 mySelf:identMe2 error:&innerError]);
   127         XCTAssertNil(innerError);
   128 
   129         XCTAssertNotNil(identMe2.fingerPrint);
   130         XCTAssertTrue([identMe2 isPEPUser:session error:&innerError]);
   131         XCTAssertEqualObjects(identMe2.fingerPrint, identMe.fingerPrint);
   132 
   133         // Now pretend the app only knows kPepUsername and kPepAddress
   134         PEPIdentity *identMe3 = [PEPTestUtils foreignPepIdentityWithAddress:identMe.address
   135                                                                    userName:identMe.userName];
   136         XCTAssertTrue([session2 mySelf:identMe3 error:&innerError]);
   137         XCTAssertNil(innerError);
   138 
   139         XCTAssertNotNil(identMe3.fingerPrint);
   140         XCTAssertTrue([identMe3 isPEPUser:session error:&innerError]);
   141         XCTAssertEqualObjects(identMe3.fingerPrint, identMe.fingerPrint);
   142 
   143         XCTAssertEqualObjects(identMe.address, identMe2.address);
   144         XCTAssertEqualObjects(identMe.address, identMe3.address);
   145         XCTAssertEqual(identMe.commType, identMe2.commType);
   146         XCTAssertEqual(identMe.commType, identMe3.commType);
   147     });
   148 }
   149 
   150 - (void)testPartnerWithoutFingerPrint
   151 {
   152     PEPSession *session = [PEPSession new];
   153 
   154     PEPIdentity *identRandom = [[PEPIdentity alloc]
   155                                 initWithAddress:@"does_not_exist@example.com"
   156                                 userID:@"got_out"
   157                                 userName:@"No Way Not Even Alice"
   158                                 isOwn:NO];
   159 
   160     NSError *error = nil;
   161     XCTAssertTrue([session updateIdentity:identRandom error:&error]);
   162     XCTAssertNil(error);
   163     XCTAssertNil(identRandom.fingerPrint);
   164 }
   165 
   166 - (void)testImportPartnerKeys
   167 {
   168     XCTAssertNotNil([self checkImportingKeyFilePath:@"6FF00E97_sec.asc"
   169                                             address:@"pep.test.alice@pep-project.org"
   170                                              userID:@"This Is Alice"
   171                                         fingerPrint:@"4ABE3AAF59AC32CFE4F86500A9411D176FF00E97"
   172                                             session: nil]);
   173 
   174     XCTAssertNotNil([self checkImportingKeyFilePath:@"0xC9C2EE39.asc"
   175                                             address:@"pep.test.bob@pep-project.org"
   176                                              userID:@"This Is Bob"
   177                                         fingerPrint:@"BFCDB7F301DEEEBBF947F29659BFF488C9C2EE39"
   178                                             session: nil]);
   179 }
   180 
   181 - (void)testIdentityRating
   182 {
   183     PEPSession *session = [PEPSession new];
   184 
   185     PEPIdentity *me = [self
   186                        checkMySelfImportingKeyFilePath:@"6FF00E97_sec.asc"
   187                        address:@"pep.test.alice@pep-project.org"
   188                        userID:@"Alice_User_ID"
   189                        fingerPrint:@"4ABE3AAF59AC32CFE4F86500A9411D176FF00E97"
   190                        session:session];
   191     XCTAssertEqual([self ratingForIdentity:me session:session], PEPRatingTrustedAndAnonymized);
   192 
   193     PEPIdentity *alice = [self
   194                           checkImportingKeyFilePath:@"6FF00E97_sec.asc"
   195                           address:@"pep.test.alice@pep-project.org"
   196                           userID:@"This Is Alice"
   197                           fingerPrint:@"4ABE3AAF59AC32CFE4F86500A9411D176FF00E97"
   198                           session: session];
   199     XCTAssertNotNil(alice);
   200     XCTAssertEqual([self ratingForIdentity:alice session:session], PEPRatingReliable);
   201 }
   202 
   203 /** ENGINE-409 */
   204 - (void)testIdentityRatingMistrustReset
   205 {
   206     PEPSession *session = [PEPSession new];
   207 
   208     PEPIdentity *me = [[PEPIdentity alloc]
   209                        initWithAddress:@"me@example.org"
   210                        userID:@"me_myself"
   211                        userName:@"Me Me"
   212                        isOwn:YES];
   213 
   214     NSError *error = nil;
   215     XCTAssertTrue([session mySelf:me error:&error]);
   216     XCTAssertNil(error);
   217 
   218     XCTAssertNotNil(me.fingerPrint);
   219     XCTAssertEqual([self ratingForIdentity:me session:session], PEPRatingTrustedAndAnonymized);
   220 
   221     PEPIdentity *alice = [self
   222                           checkImportingKeyFilePath:@"6FF00E97_sec.asc"
   223                           address:@"pep.test.alice@pep-project.org"
   224                           userID:@"This Is Alice"
   225                           fingerPrint:@"4ABE3AAF59AC32CFE4F86500A9411D176FF00E97"
   226                           session: session];
   227     XCTAssertNotNil(alice);
   228     XCTAssertEqual([self ratingForIdentity:alice session:session], PEPRatingReliable);
   229 
   230     XCTAssertTrue([session keyMistrusted:alice error:&error]);
   231     XCTAssertNil(error);
   232     XCTAssertEqual([self ratingForIdentity:alice session:session], PEPRatingHaveNoKey);
   233 }
   234 
   235 - (void)testIdentityRatingTrustResetMistrustUndo
   236 {
   237     PEPSession *session = [PEPSession new];
   238 
   239     PEPIdentity *me = [[PEPIdentity alloc]
   240                        initWithAddress:@"me@example.org"
   241                        userID:@"me_myself"
   242                        userName:@"Me Me"
   243                        isOwn:YES];
   244 
   245     NSError *error = nil;
   246     XCTAssertTrue([session mySelf:me error:&error]);
   247     XCTAssertNil(error);
   248 
   249     XCTAssertNotNil(me.fingerPrint);
   250     XCTAssertEqual([self ratingForIdentity:me session:session], PEPRatingTrustedAndAnonymized);
   251 
   252     PEPIdentity *alice = [self
   253                           checkImportingKeyFilePath:@"6FF00E97_sec.asc"
   254                           address:@"pep.test.alice@pep-project.org"
   255                           userID:@"This Is Alice"
   256                           fingerPrint:@"4ABE3AAF59AC32CFE4F86500A9411D176FF00E97"
   257                           session: session];
   258     XCTAssertNotNil(alice);
   259     XCTAssertEqual([self ratingForIdentity:alice session:session], PEPRatingReliable);
   260 
   261     XCTAssertTrue([session trustPersonalKey:alice error:&error]);
   262     XCTAssertNil(error);
   263     XCTAssertEqual([self ratingForIdentity:alice session:session], PEPRatingTrusted);
   264 
   265     XCTAssertTrue([session keyResetTrust:alice error:&error]);
   266     XCTAssertNil(error);
   267     XCTAssertEqual([self ratingForIdentity:alice session:session], PEPRatingReliable);
   268 
   269     XCTAssertTrue([session keyMistrusted:alice error:&error]);
   270     XCTAssertNil(error);
   271     XCTAssertEqual([self ratingForIdentity:alice session:session], PEPRatingHaveNoKey);
   272 }
   273 
   274 /** ENGINE-384 */
   275 - (void)testIdentityRatingCrash
   276 {
   277     PEPSession *session = [PEPSession new];
   278 
   279     PEPIdentity *me = [[PEPIdentity alloc]
   280                        initWithAddress:@"me@example.org"
   281                        userID:@"me_myself"
   282                        userName:@"Me Me"
   283                        isOwn:YES];
   284     NSError *error = nil;
   285     XCTAssertTrue([session mySelf:me error:&error]);
   286     XCTAssertNil(error);
   287 
   288     XCTAssertNotNil(me.fingerPrint);
   289     XCTAssertEqual([self ratingForIdentity:me session:session], PEPRatingTrustedAndAnonymized);
   290 
   291     PEPIdentity *alice = [self
   292                           checkImportingKeyFilePath:@"6FF00E97_sec.asc"
   293                           address:@"pep.test.alice@pep-project.org"
   294                           userID:@"This Is Alice"
   295                           fingerPrint:@"4ABE3AAF59AC32CFE4F86500A9411D176FF00E97"
   296                           session: session];
   297     XCTAssertNotNil(alice);
   298     XCTAssertEqual([self ratingForIdentity:alice session:session], PEPRatingReliable);
   299 
   300     XCTAssertTrue([session trustPersonalKey:alice error:&error]);
   301     XCTAssertNil(error);
   302     XCTAssertEqual([self ratingForIdentity:alice session:session], PEPRatingTrusted);
   303 
   304     XCTAssertTrue([session keyResetTrust:alice error:&error]);
   305     XCTAssertNil(error);
   306     XCTAssertEqual([self ratingForIdentity:alice session:session], PEPRatingReliable);
   307 
   308     XCTAssertTrue([session keyMistrusted:alice error:&error]);
   309     XCTAssertNil(error);
   310     XCTAssertEqual([self ratingForIdentity:alice session:session], PEPRatingHaveNoKey);
   311 }
   312 
   313 /**
   314  Try to provoke a SQLITE_BUSY (ENGINE-374)
   315  */
   316 - (void)testIdentityRatingTrustResetMistrustUndoBusy
   317 {
   318     PEPSession *session = [PEPSession new];
   319 
   320     PEPIdentity *me = [[PEPIdentity alloc]
   321                        initWithAddress:@"me@example.org"
   322                        userID:@"me_myself"
   323                        userName:@"Me Me"
   324                        isOwn:YES];
   325     NSError *error = nil;
   326     XCTAssertTrue([session mySelf:me error:&error]);
   327     XCTAssertNil(error);
   328 
   329     XCTAssertNotNil(me.fingerPrint);
   330     XCTAssertEqual([self ratingForIdentity:me session:session], PEPRatingTrustedAndAnonymized);
   331 
   332     PEPIdentity *alice = [self
   333                           checkImportingKeyFilePath:@"6FF00E97_sec.asc"
   334                           address:@"pep.test.alice@pep-project.org"
   335                           userID:@"This Is Alice"
   336                           fingerPrint:@"4ABE3AAF59AC32CFE4F86500A9411D176FF00E97"
   337                           session: session];
   338     XCTAssertNotNil(alice);
   339     XCTAssertEqual([self ratingForIdentity:alice session:session], PEPRatingReliable);
   340 
   341     void (^encryptingBlock)(void) = ^{
   342         PEPSession *innerSession = [PEPSession new];
   343         PEPMessage *msg = [PEPMessage new];
   344         msg.from = me;
   345         msg.to = @[alice];
   346         msg.shortMessage = @"The subject";
   347         msg.longMessage = @"Lots and lots of text";
   348         msg.direction = PEPMsgDirectionIncoming;
   349 
   350         PEPStatus status;
   351         NSError *error = nil;
   352         PEPMessage *encMsg = [innerSession
   353                               encryptMessage:msg
   354                               forSelf:me
   355                               extraKeys:nil
   356                               status:&status error:&error];
   357         XCTAssertEqual(status, PEPStatusOK);
   358         XCTAssertNotNil(encMsg);
   359     };
   360 
   361     dispatch_group_t backgroundGroup = dispatch_group_create();
   362     dispatch_group_async(backgroundGroup,
   363                          dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), encryptingBlock);
   364 
   365     XCTAssertTrue([session trustPersonalKey:alice error:&error]);
   366     XCTAssertNil(error);
   367     XCTAssertEqual([self ratingForIdentity:alice session:session], PEPRatingTrusted);
   368 
   369     XCTAssertTrue([session keyResetTrust:alice error:&error]);
   370     XCTAssertNil(error);
   371     XCTAssertEqual([self ratingForIdentity:alice session:session], PEPRatingReliable);
   372 
   373     XCTAssertTrue([session keyMistrusted:alice error:&error]);
   374     XCTAssertNil(error);
   375     XCTAssertEqual([self ratingForIdentity:alice session:session], PEPRatingHaveNoKey);
   376 }
   377 
   378 - (void)testOutgoingColors
   379 {
   380     PEPSession *session = [PEPSession new];
   381 
   382     // Our test user :
   383     // pEp Test Alice (test key don't use) <pep.test.alice@pep-project.org>
   384     // 4ABE3AAF59AC32CFE4F86500A9411D176FF00E97
   385     XCTAssertTrue([PEPTestUtils importBundledKey:@"6FF00E97_sec.asc" session:session]);
   386 
   387     // Our test user :
   388     PEPIdentity *identAlice = [self
   389                                checkMySelfImportingKeyFilePath:@"6FF00E97_sec.asc"
   390                                address:@"pep.test.alice@pep-project.org"
   391                                userID:@"Alice_User_ID"
   392                                fingerPrint:@"4ABE3AAF59AC32CFE4F86500A9411D176FF00E97"
   393                                session:session];
   394 
   395     //Message
   396 
   397     {
   398         PEPIdentity *identUnknownBob = [[PEPIdentity alloc]
   399                                         initWithAddress:@"pep.test.unknown.bob@pep-project.org"
   400                                         userID:@"4242" userName:@"pEp Test Bob Unknown"
   401                                         isOwn:NO];
   402 
   403         PEPMessage *msgGray = [PEPMessage new];
   404         msgGray.from = identAlice;
   405         msgGray.to = @[identUnknownBob];
   406         msgGray.shortMessage = @"All Gray Test";
   407         msgGray.longMessage = @"This is a text content";
   408         msgGray.direction = PEPMsgDirectionOutgoing;
   409 
   410         NSError *error = nil;
   411 
   412         // Test with unknown Bob
   413         NSNumber *numRating = [self
   414                                testOutgoingRatingForMessage:msgGray
   415                                session:session
   416                                error:&error];
   417         XCTAssertNotNil(numRating);
   418         XCTAssertNil(error);
   419         XCTAssertEqual(numRating.pEpRating, PEPRatingUnencrypted);
   420     }
   421 
   422     PEPIdentity *identBob = [self
   423                              checkImportingKeyFilePath:@"0xC9C2EE39.asc"
   424                              address:@"pep.test.bob@pep-project.org"
   425                              userID:@"42"
   426                              fingerPrint:@"BFCDB7F301DEEEBBF947F29659BFF488C9C2EE39"
   427                              session: session];
   428     XCTAssertNotNil(identBob);
   429 
   430     PEPMessage *msg = [PEPMessage new];
   431     msg.from = identAlice;
   432     msg.to = @[identBob];
   433     msg.shortMessage = @"All Gray Test";
   434     msg.longMessage = @"This is a text content";
   435     msg.direction = PEPMsgDirectionOutgoing;
   436 
   437     NSError *error = nil;
   438 
   439     // Should be yellow, since no handshake happened.
   440     NSNumber *numRating = [self testOutgoingRatingForMessage:msg session:session error:&error];
   441     XCTAssertNotNil(numRating);
   442     XCTAssertNil(error);
   443     XCTAssertEqual(numRating.pEpRating, PEPRatingReliable);
   444 
   445     PEPRating rating = [self ratingForIdentity:identBob session:session];
   446     XCTAssertEqual(rating, PEPRatingReliable);
   447 
   448     // Let' say we got that handshake, set PEP_ct_confirmed in Bob's identity
   449     XCTAssertTrue([session trustPersonalKey:identBob error:&error]);
   450     XCTAssertNil(error);
   451 
   452     // This time it should be green
   453     numRating = [self testOutgoingRatingForMessage:msg session:session error:&error];
   454     XCTAssertNotNil(numRating);
   455     XCTAssertNil(error);
   456     XCTAssertEqual(numRating.pEpRating, PEPRatingTrusted);
   457 
   458     rating = [self ratingForIdentity:identBob session:session];
   459     XCTAssertEqual(rating, PEPRatingTrusted);
   460 
   461     // Let' say we undo handshake
   462     XCTAssertTrue([session keyResetTrust:identBob error:&error]);
   463     XCTAssertNil(error);
   464 
   465     // Yellow ?
   466     numRating = [self testOutgoingRatingForMessage:msg session:session error:&error];
   467     XCTAssertNotNil(numRating);
   468     XCTAssertNil(error);
   469     XCTAssertEqual(numRating.pEpRating, PEPRatingReliable);
   470 
   471     // mistrust Bob
   472     XCTAssertTrue([session keyMistrusted:identBob error:&error]);
   473     XCTAssertNil(error);
   474 
   475     identBob.fingerPrint = nil;
   476     XCTAssertTrue([session updateIdentity:identBob error:&error]);
   477     XCTAssertNil(error);
   478     XCTAssertNil(identBob.fingerPrint);
   479 
   480     // Gray == PEPRatingUnencrypted
   481     numRating = [self testOutgoingRatingForMessage:msg session:session error:&error];
   482     XCTAssertNotNil(numRating);
   483     XCTAssertNil(error);
   484     XCTAssertEqual(numRating.pEpRating, PEPRatingUnencrypted);
   485 }
   486 
   487 
   488 - (void)testOutgoingBccColors
   489 {
   490     PEPSession *session = [PEPSession new];
   491 
   492     // Our test user :
   493     // pEp Test Alice (test key don't use) <pep.test.alice@pep-project.org>
   494     // 4ABE3AAF59AC32CFE4F86500A9411D176FF00E97
   495     XCTAssertTrue([PEPTestUtils importBundledKey:@"6FF00E97_sec.asc" session:session]);
   496 
   497     PEPIdentity *identAlice = [[PEPIdentity alloc]
   498                                initWithAddress:@"pep.test.alice@pep-project.org"
   499                                userID:ownUserId
   500                                userName:@"pEp Test Alice"
   501                                isOwn:YES
   502                                fingerPrint:@"4ABE3AAF59AC32CFE4F86500A9411D176FF00E97"];
   503 
   504     NSError *error = nil;
   505     XCTAssertTrue([session mySelf:identAlice error:&error]);
   506     XCTAssertNil(error);
   507 
   508     PEPMessage *msg = [PEPMessage new];
   509     msg.from = identAlice;
   510     msg.to = @[[[PEPIdentity alloc] initWithAddress:@"pep.test.bob@pep-project.org"
   511                                              userID:@"42" userName:@"pEp Test Bob" isOwn:NO]];
   512     msg.shortMessage = @"All Green Test";
   513     msg.longMessage = @"This is a text content";
   514     msg.direction = PEPMsgDirectionOutgoing;
   515 
   516     // Test with unknown Bob
   517     PEPRating rating;
   518     NSNumber *numRating = [self testOutgoingRatingForMessage:msg session:session error:&error];
   519     XCTAssertNotNil(numRating);
   520     XCTAssertNil(error);
   521     XCTAssertEqual(numRating.pEpRating, PEPRatingUnencrypted);
   522 
   523     // Now let see with bob's pubkey already known
   524     // pEp Test Bob (test key, don't use) <pep.test.bob@pep-project.org>
   525     // BFCDB7F301DEEEBBF947F29659BFF488C9C2EE39
   526     XCTAssertTrue([PEPTestUtils importBundledKey:@"0xC9C2EE39.asc" session:session]);
   527 
   528     PEPIdentity *identBob = [[PEPIdentity alloc]
   529                              initWithAddress:@"pep.test.bob@pep-project.org"
   530                              userID:@"42" userName:@"pEp Test Bob"
   531                              isOwn:NO
   532                              fingerPrint:@"BFCDB7F301DEEEBBF947F29659BFF488C9C2EE39"];
   533 
   534     XCTAssertTrue([session updateIdentity:identBob error:&error]);
   535     XCTAssertNil(error);
   536 
   537     // Should be yellow, since no handshake happened.
   538     numRating = [self testOutgoingRatingForMessage:msg session:session error:&error];
   539     XCTAssertNotNil(numRating);
   540     XCTAssertNil(error);
   541     XCTAssertEqual(numRating.pEpRating, PEPRatingReliable);
   542 
   543     rating = [self ratingForIdentity:identBob session:session];
   544     XCTAssertEqual(rating, PEPRatingReliable);
   545 
   546     // Let' say we got that handshake, set PEP_ct_confirmed in Bob's identity
   547     XCTAssertTrue([session trustPersonalKey:identBob error:&error]);
   548     XCTAssertNil(error);
   549 
   550     // This time it should be green
   551     numRating = [self testOutgoingRatingForMessage:msg session:session error:&error];
   552     XCTAssertNotNil(numRating);
   553     XCTAssertNil(error);
   554     XCTAssertEqual(numRating.pEpRating, PEPRatingTrusted);
   555 
   556     rating = [self ratingForIdentity:identBob session:session];
   557     XCTAssertEqual(rating, PEPRatingTrusted);
   558 
   559     // Now let see if it turns back yellow if we add an unconfirmed folk.
   560     // pEp Test John (test key, don't use) <pep.test.john@pep-project.org>
   561     // AA2E4BEB93E5FE33DEFD8BE1135CD6D170DCF575
   562     XCTAssertTrue([PEPTestUtils importBundledKey:@"0x70DCF575.asc" session:session]);
   563 
   564     PEPIdentity *identJohn = [[PEPIdentity alloc]
   565                               initWithAddress:@"pep.test.john@pep-project.org"
   566                               userID:@"101" userName:@"pEp Test John"
   567                               isOwn:NO
   568                               fingerPrint:@"AA2E4BEB93E5FE33DEFD8BE1135CD6D170DCF575"];
   569 
   570     XCTAssertTrue([session updateIdentity:identJohn error:&error]);
   571     XCTAssertNil(error);
   572 
   573     msg.bcc = @[[[PEPIdentity alloc] initWithAddress:@"pep.test.john@pep-project.org"
   574                                               userID:@"101" userName:@"pEp Test John" isOwn:NO]];
   575 
   576     // Yellow ?
   577     numRating = [self testOutgoingRatingForMessage:msg session:session error:&error];
   578     XCTAssertNotNil(numRating);
   579     XCTAssertNil(error);
   580     XCTAssertEqual(numRating.pEpRating, PEPRatingReliable);
   581 
   582     XCTAssertTrue([session trustPersonalKey:identJohn error:&error]);
   583     XCTAssertNil(error);
   584 
   585     // This time it should be green
   586     numRating = [self testOutgoingRatingForMessage:msg session:session error:&error];
   587     XCTAssertNotNil(numRating);
   588     XCTAssertNil(error);
   589     XCTAssertEqual(numRating.pEpRating, PEPRatingTrusted);
   590 
   591     rating = [self ratingForIdentity:identJohn session:session];
   592     XCTAssertEqual(rating, PEPRatingTrusted);
   593 }
   594 
   595 - (void)testDontEncryptForMistrusted
   596 {
   597     PEPSession *session = [PEPSession new];
   598 
   599     // Our test user :
   600     // pEp Test Alice (test key don't use) <pep.test.alice@pep-project.org>
   601     // 4ABE3AAF59AC32CFE4F86500A9411D176FF00E97
   602     XCTAssertTrue([PEPTestUtils importBundledKey:@"6FF00E97_sec.asc" session:session]);
   603 
   604     PEPIdentity *identAlice = [[PEPIdentity alloc]
   605                                initWithAddress:@"pep.test.alice@pep-project.org"
   606                                userID:ownUserId
   607                                userName:@"pEp Test Alice"
   608                                isOwn:YES
   609                                fingerPrint:@"4ABE3AAF59AC32CFE4F86500A9411D176FF00E97"];
   610 
   611     NSError *error = nil;
   612     XCTAssertTrue([session mySelf:identAlice error:&error]);
   613     XCTAssertNil(error);
   614 
   615     // pEp Test Bob (test key, don't use) <pep.test.bob@pep-project.org>
   616     // BFCDB7F301DEEEBBF947F29659BFF488C9C2EE39
   617     XCTAssertTrue([PEPTestUtils importBundledKey:@"0xC9C2EE39.asc" session:session]);
   618 
   619     PEPIdentity *identBob = [[PEPIdentity alloc]
   620                              initWithAddress:@"pep.test.bob@pep-project.org"
   621                              userID:@"42" userName:@"pEp Test Bob"
   622                              isOwn:NO
   623                              fingerPrint:@"BFCDB7F301DEEEBBF947F29659BFF488C9C2EE39"];
   624 
   625     XCTAssertTrue([session updateIdentity:identBob error:&error]);
   626     XCTAssertNil(error);
   627 
   628     // mistrust Bob
   629     XCTAssertTrue([session keyMistrusted:identBob error:&error]);
   630     XCTAssertNil(error);
   631 
   632     PEPMessage *msg = [PEPMessage new];
   633     msg.from = identAlice;
   634     msg.to = @[[[PEPIdentity alloc] initWithAddress:@"pep.test.bob@pep-project.org" userID:@"42"
   635                                            userName:@"pEp Test Bob" isOwn:NO]];
   636     msg.shortMessage = @"All Green Test";
   637     msg.longMessage = @"This is a text content";
   638     msg.direction = PEPMsgDirectionOutgoing;
   639 
   640     // Gray == PEPRatingUnencrypted
   641     NSNumber *numRating = [self testOutgoingRatingForMessage:msg session:session error:&error];
   642     XCTAssertNotNil(numRating);
   643     XCTAssertNil(error);
   644     XCTAssertEqual(numRating.pEpRating, PEPRatingUnencrypted);
   645 
   646     PEPMessage *encMsg = [session encryptMessage:msg extraKeys:nil status:nil error:&error];
   647     XCTAssertNotNil(encMsg);
   648     XCTAssertNil(error);
   649 
   650     XCTAssertNotEqualObjects(encMsg.attachments[0].mimeType, @"application/pgp-encrypted");
   651 
   652     [self pEpCleanUp];
   653 }
   654 
   655 - (void)testRevoke
   656 {
   657     PEPSession *session = [PEPSession new];
   658 
   659     // Our test user :
   660     // pEp Test Alice (test key don't use) <pep.test.alice@pep-project.org>
   661     // 4ABE3AAF59AC32CFE4F86500A9411D176FF00E97
   662     XCTAssertTrue([PEPTestUtils importBundledKey:@"6FF00E97_sec.asc" session:session]);
   663     NSString *fpr = @"4ABE3AAF59AC32CFE4F86500A9411D176FF00E97";
   664 
   665     PEPIdentity *identAlice = [[PEPIdentity alloc]
   666                                initWithAddress:@"pep.test.alice@pep-project.org"
   667                                userID:ownUserId
   668                                userName:@"pEp Test Alice"
   669                                isOwn:YES
   670                                fingerPrint:fpr];
   671 
   672     NSError *error = nil;
   673     XCTAssertTrue([session mySelf:identAlice error:&error]);
   674     XCTAssertNil(error);
   675 
   676     PEPIdentity *identAlice2 = [identAlice mutableCopy];
   677 
   678     // This will revoke key
   679     XCTAssertTrue([session keyMistrusted:identAlice2 error:&error]);
   680     XCTAssertNil(error);
   681     identAlice2.fingerPrint = nil;
   682 
   683     XCTAssertTrue([session mySelf:identAlice error:&error]);
   684     XCTAssertNil(error);
   685 
   686     // Check fingerprint is different
   687     XCTAssertNotEqualObjects(identAlice2.fingerPrint, fpr);
   688 }
   689 
   690 - (void)testMailToMyself
   691 {
   692     PEPSession *session = [PEPSession new];
   693 
   694     // Our test user :
   695     // pEp Test Alice (test key don't use) <pep.test.alice@pep-project.org>
   696     // 4ABE3AAF59AC32CFE4F86500A9411D176FF00E97
   697     XCTAssertTrue([PEPTestUtils importBundledKey:@"6FF00E97_sec.asc" session:session]);
   698 
   699     PEPIdentity *identAlice = [[PEPIdentity alloc]
   700                                initWithAddress:@"pep.test.alice@pep-project.org"
   701                                userID:ownUserId
   702                                userName:@"pEp Test Alice"
   703                                isOwn:YES
   704                                fingerPrint:@"4ABE3AAF59AC32CFE4F86500A9411D176FF00E97"];
   705 
   706     NSError *error = nil;
   707     XCTAssertTrue([session mySelf:identAlice error:&error]);
   708     XCTAssertNil(error);
   709 
   710     PEPMessage *msg = [PEPMessage new];
   711     msg.from = identAlice;
   712     msg.to = @[identAlice];
   713     msg.shortMessage = @"Mail to Myself";
   714     msg.longMessage = @"This is a text content";
   715     msg.direction = PEPMsgDirectionOutgoing;
   716 
   717     NSNumber *numRating = [self testOutgoingRatingForMessage:msg session:session error:&error];
   718     XCTAssertNotNil(numRating);
   719     XCTAssertNil(error);
   720     XCTAssertEqual(numRating.pEpRating, PEPRatingTrustedAndAnonymized);
   721 
   722     PEPMessage *encMsg = [session encryptMessage:msg extraKeys:nil status:nil error:&error];
   723     XCTAssertNotNil(encMsg);
   724     XCTAssertNil(error);
   725 
   726     NSArray *keys;
   727 
   728     error = nil;
   729     PEPRating rating = PEPRatingUndefined;
   730     PEPMessage *decmsg = [session
   731                           decryptMessage:encMsg
   732                           flags:nil
   733                           rating:&rating
   734                           extraKeys:&keys
   735                           status:nil
   736                           error:&error];
   737     XCTAssertNotNil(decmsg);
   738     XCTAssertNil(error);
   739     XCTAssertEqual(rating, PEPRatingTrustedAndAnonymized);
   740 }
   741 
   742 - (void)testEncryptedMailFromMuttWithReencryption
   743 {
   744     PEPSession *session = [PEPSession new];
   745 
   746     // This is the public key for test001@peptest.ch
   747     XCTAssertTrue([PEPTestUtils importBundledKey:@"A3FC7F0A.asc" session:session]);
   748 
   749     // This is the secret key for test001@peptest.ch
   750     XCTAssertTrue([PEPTestUtils importBundledKey:@"A3FC7F0A_sec.asc" session:session]);
   751 
   752     // Mail from mutt, already processed into message dict by the app.
   753     NSMutableDictionary *msgDict = [[PEPTestUtils
   754                                      unarchiveDictionary:@"msg_to_A3FC7F0A_from_mutt.ser"]
   755                                     mutableCopy];
   756     [PEPTestUtils migrateUnarchivedMessageDictionary:msgDict];
   757     [msgDict removeObjectForKey:kPepLongMessage];
   758     [msgDict removeObjectForKey:kPepLongMessageFormatted];
   759 
   760     // Also extracted "live" from the app.
   761     NSMutableDictionary *accountDict = [[PEPTestUtils
   762                                          unarchiveDictionary:@"account_A3FC7F0A.ser"]
   763                                         mutableCopy];
   764     [accountDict removeObjectForKey:kPepCommType];
   765     [accountDict removeObjectForKey:kPepFingerprint];
   766     PEPIdentity *identMe = [[PEPIdentity alloc] initWithDictionary:accountDict];
   767 
   768     NSError *error = nil;
   769     XCTAssertTrue([session mySelf:identMe error:&error]);
   770     XCTAssertNil(error);
   771 
   772     XCTAssertNotNil(identMe.fingerPrint);
   773 
   774     NSArray* keys;
   775     PEPMessage *msg = [PEPMessage new];
   776     [msg setValuesForKeysWithDictionary:msgDict];
   777     PEPMessage *msgOriginal = [PEPMessage new];
   778     [msgOriginal setValuesForKeysWithDictionary:msgDict];
   779 
   780     XCTAssertEqualObjects(msg, msgOriginal);
   781 
   782     PEPRating rating = PEPRatingUndefined;
   783     PEPDecryptFlags flags = PEPDecryptFlagsUntrustedServer;
   784 
   785     PEPMessage *pepDecryptedMail = [session
   786                                     decryptMessage:msg
   787                                     flags:&flags
   788                                     rating:&rating
   789                                     extraKeys:&keys
   790                                     status:nil
   791                                     error:&error];
   792     XCTAssertNotNil(pepDecryptedMail);
   793     XCTAssertNil(error);
   794 
   795     // Technically, the mail is encrypted, but the signatures don't match
   796     XCTAssertEqual(rating, PEPRatingUnreliable);
   797 
   798     // Since we're requesting re-encryption, src should have been changed
   799     XCTAssertNotEqualObjects(msg, msgOriginal);
   800 
   801     XCTAssertNotNil(pepDecryptedMail.longMessage);
   802 }
   803 
   804 - (void)testOutgoingContactColor
   805 {
   806     PEPSession *session = [PEPSession new];
   807 
   808     PEPIdentity *partner1Orig = [PEPTestUtils foreignPepIdentityWithAddress:@"partner1@dontcare.me"
   809                                                                    userName:@"Partner 1"];
   810     NSString *pubKeyPartner1 = [PEPTestUtils loadResourceByName:@"partner1_F2D281C2789DD7F6_pub.asc"];
   811     XCTAssertNotNil(pubKeyPartner1);
   812 
   813     NSError *error = nil;
   814     XCTAssertTrue([session importKey:pubKeyPartner1 error:&error]);
   815     XCTAssertNil(error);
   816 
   817     PEPRating color = [self ratingForIdentity:partner1Orig session:session];
   818     XCTAssertEqual(color, PEPRatingReliable);
   819 }
   820 
   821 - (void)testGetTrustwords
   822 {
   823     PEPSession *session = [PEPSession new];
   824 
   825     PEPIdentity *partner1Orig = [[PEPIdentity alloc]
   826                                  initWithAddress:@"partner1@dontcare.me" userID:@"partner1"
   827                                  userName:@"partner1"
   828                                  isOwn:NO fingerPrint:@"F0CD3F7B422E5D587ABD885BF2D281C2789DD7F6"];
   829 
   830     PEPIdentity *meOrig = [[PEPIdentity alloc]
   831                            initWithAddress:@"me@dontcare.me" userID:@"me"
   832                            userName:@"me"
   833                            isOwn:NO fingerPrint:@"CC1F73F6FB774BF08B197691E3BFBCA9248FC681"];
   834 
   835     NSString *pubKeyPartner1 = [PEPTestUtils loadResourceByName:@"partner1_F2D281C2789DD7F6_pub.asc"];
   836     XCTAssertNotNil(pubKeyPartner1);
   837     NSString *pubKeyMe = [PEPTestUtils loadResourceByName:@"meATdontcare_E3BFBCA9248FC681_pub.asc"];
   838     XCTAssertNotNil(pubKeyMe);
   839     NSString *secKeyMe = [PEPTestUtils loadResourceByName:@"meATdontcare_E3BFBCA9248FC681_sec.asc"];
   840     XCTAssertNotNil(secKeyMe);
   841 
   842     NSError *error = nil;
   843     NSString *trustwordsFull = [session getTrustwordsIdentity1:meOrig identity2:partner1Orig
   844                                                       language:@"en" full:YES error:&error];
   845     XCTAssertNil(error);
   846     XCTAssertEqualObjects(trustwordsFull,
   847                           @"EMERSON GASPER TOKENISM BOLUS COLLAGE DESPISE BEDDED ENCRYPTION IMAGINE BEDFORD");
   848 
   849     NSString *trustwordsUndefined = [session getTrustwordsIdentity1:meOrig identity2:partner1Orig
   850                                                            language:@"ZZ" full:YES error:&error];
   851     XCTAssertNotNil(error);
   852     XCTAssertNil(trustwordsUndefined);
   853 }
   854 
   855 - (void)testStringToRating
   856 {
   857     PEPSession *session = [PEPSession new];
   858     XCTAssertEqual([session ratingFromString:@"cannot_decrypt"], PEPRatingCannotDecrypt);
   859     XCTAssertEqual([session ratingFromString:@"have_no_key"], PEPRatingHaveNoKey);
   860     XCTAssertEqual([session ratingFromString:@"unencrypted"], PEPRatingUnencrypted);
   861     XCTAssertEqual([session ratingFromString:@"unencrypted_for_some"],
   862                    PEPRatingUnencryptedForSome);
   863     XCTAssertEqual([session ratingFromString:@"unreliable"], PEPRatingUnreliable);
   864     XCTAssertEqual([session ratingFromString:@"reliable"], PEPRatingReliable);
   865     XCTAssertEqual([session ratingFromString:@"trusted"], PEPRatingTrusted);
   866     XCTAssertEqual([session ratingFromString:@"trusted_and_anonymized"],
   867                    PEPRatingTrustedAndAnonymized);
   868     XCTAssertEqual([session ratingFromString:@"fully_anonymous"], PEPRatingFullyAnonymous);
   869     XCTAssertEqual([session ratingFromString:@"mistrust"], PEPRatingMistrust);
   870     XCTAssertEqual([session ratingFromString:@"b0rken"], PEPRatingB0rken);
   871     XCTAssertEqual([session ratingFromString:@"under_attack"], PEPRatingUnderAttack);
   872     XCTAssertEqual([session ratingFromString:@"undefined"], PEPRatingUndefined);
   873     XCTAssertEqual([session ratingFromString:@"does not exist111"], PEPRatingUndefined);
   874 }
   875 
   876 - (void)testRatingToString
   877 {
   878     PEPSession *session = [PEPSession new];
   879     XCTAssertEqualObjects([session stringFromRating:PEPRatingCannotDecrypt], @"cannot_decrypt");
   880     XCTAssertEqualObjects([session stringFromRating:PEPRatingHaveNoKey], @"have_no_key");
   881     XCTAssertEqualObjects([session stringFromRating:PEPRatingUnencrypted], @"unencrypted");
   882     XCTAssertEqualObjects([session stringFromRating:PEPRatingUnencryptedForSome],
   883                           @"unencrypted_for_some");
   884     XCTAssertEqualObjects([session stringFromRating:PEPRatingUnreliable], @"unreliable");
   885     XCTAssertEqualObjects([session stringFromRating:PEPRatingReliable], @"reliable");
   886     XCTAssertEqualObjects([session stringFromRating:PEPRatingTrusted], @"trusted");
   887     XCTAssertEqualObjects([session stringFromRating:PEPRatingTrustedAndAnonymized],
   888                           @"trusted_and_anonymized");
   889     XCTAssertEqualObjects([session stringFromRating:PEPRatingFullyAnonymous],
   890                           @"fully_anonymous");
   891     XCTAssertEqualObjects([session stringFromRating:PEPRatingMistrust], @"mistrust");
   892     XCTAssertEqualObjects([session stringFromRating:PEPRatingB0rken], @"b0rken");
   893     XCTAssertEqualObjects([session stringFromRating:PEPRatingUnderAttack], @"under_attack");
   894     XCTAssertEqualObjects([session stringFromRating:PEPRatingUndefined], @"undefined");
   895     XCTAssertEqualObjects([session stringFromRating:500], @"undefined");
   896 }
   897 
   898 - (void)testIsPEPUser
   899 {
   900     PEPSession *session = [PEPSession new];
   901 
   902     PEPIdentity *identMe = [[PEPIdentity alloc]
   903                             initWithAddress:@"me-myself-and-i@pep-project.org"
   904                             userID:@"me-myself-and-i"
   905                             userName:@"pEp Me"
   906                             isOwn:YES];
   907     NSError *error = nil;
   908     XCTAssertTrue([session mySelf:identMe error:&error]);
   909     XCTAssertNil(error);
   910 
   911     XCTAssertNotNil(identMe.fingerPrint);
   912 
   913     // PEP_CANNOT_FIND_PERSON == 902
   914     XCTAssertTrue([session isPEPUser:identMe error:&error]);
   915 }
   916 
   917 - (void)testXEncStatusForOutgoingEncryptedMail
   918 {
   919     [self helperXEncStatusForOutgoingEncryptdMailToSelf:NO expectedRating:PEPRatingReliable];
   920 }
   921 
   922 - (void)testXEncStatusForOutgoingSelfEncryptedMail
   923 {
   924     [self helperXEncStatusForOutgoingEncryptdMailToSelf:YES
   925                                          expectedRating:PEPRatingTrustedAndAnonymized];
   926 }
   927 
   928 /**
   929  ENGINE-364. Tries to invoke trustPersonalKey on an identity without key,
   930  giving it a fake fingerprint.
   931  */
   932 - (void)testTrustPersonalKey
   933 {
   934     PEPSession *session = [PEPSession new];
   935 
   936     PEPIdentity *identMe = [[PEPIdentity alloc]
   937                             initWithAddress:@"me-myself-and-i@pep-project.org"
   938                             userID:@"me-myself-and-i"
   939                             userName:@"pEp Me"
   940                             isOwn:YES];
   941     NSError *error = nil;
   942     XCTAssertTrue([session mySelf:identMe error:&error]);
   943     XCTAssertNil(error);
   944 
   945     XCTAssertNotNil(identMe.fingerPrint);
   946 
   947     // The fingerprint is definitely wrong, we don't have a key
   948     PEPIdentity *identAlice = [[PEPIdentity alloc]
   949                                initWithAddress:@"alice@pep-project.org"
   950                                userID:@"alice"
   951                                userName:@"pEp Test Alice"
   952                                isOwn:NO
   953                                fingerPrint:@"4ABE3AAF59AC32CFE4F86500A9411D176FF00E97"];
   954 
   955     XCTAssertFalse([session trustPersonalKey:identAlice error:&error]);
   956     XCTAssertNotNil(error);
   957 }
   958 
   959 /**
   960  ENGINE-381
   961  */
   962 - (void)testVolatileIdentityRating
   963 {
   964     PEPSession *session = [PEPSession new];
   965 
   966     PEPIdentity *identMe = [[PEPIdentity alloc]
   967                             initWithAddress:@"me-myself-and-i@pep-project.org"
   968                             userID:@"me-myself-and-i"
   969                             userName:@"pEp Me"
   970                             isOwn:YES];
   971     NSError *error = nil;
   972     XCTAssertTrue([session mySelf:identMe error:&error]);
   973     XCTAssertNil(error);
   974 
   975     XCTAssertNotNil(identMe.fingerPrint);
   976 
   977     PEPIdentity *identAlice = [self
   978                                checkImportingKeyFilePath:@"6FF00E97_sec.asc"
   979                                address:@"pep.test.alice@pep-project.org"
   980                                userID:@"alice_user_id"
   981                                fingerPrint:@"4ABE3AAF59AC32CFE4F86500A9411D176FF00E97"
   982                                session: session];
   983     XCTAssertNotNil(identAlice);
   984 
   985     dispatch_group_t identityRatingGroup = dispatch_group_create();
   986 
   987     void (^ratingBlock)(void) = ^{
   988         PEPSession *innerSession = [PEPSession new];
   989         PEPRating rating = [self ratingForIdentity:identAlice session:innerSession];
   990         XCTAssertEqual(rating, PEPRatingReliable);
   991     };
   992 
   993     for (int i = 0; i < 4; ++i) {
   994         dispatch_group_async(identityRatingGroup,
   995                              dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0),
   996                              ratingBlock);
   997     }
   998 
   999     for (int i = 0; i < 4; ++i) {
  1000         ratingBlock();
  1001     }
  1002 
  1003     dispatch_group_wait(identityRatingGroup, DISPATCH_TIME_FOREVER);
  1004 }
  1005 
  1006 /**
  1007  IOSAD-93, testing for easy error case.
  1008  */
  1009 - (void)testEncryptAndAttachPrivateKeyIllegalValue
  1010 {
  1011     PEPSession *session = [PEPSession new];
  1012 
  1013     PEPIdentity *identMe = [[PEPIdentity alloc]
  1014                             initWithAddress:@"me-myself-and-i@pep-project.org"
  1015                             userID:@"me-myself-and-i"
  1016                             userName:@"pEp Me"
  1017                             isOwn:YES];
  1018     NSError *error = nil;
  1019     XCTAssertTrue([session mySelf:identMe error:&error]);
  1020     XCTAssertNil(error);
  1021 
  1022     XCTAssertNotNil(identMe.fingerPrint);
  1023 
  1024     NSString *fprAlice = @"4ABE3AAF59AC32CFE4F86500A9411D176FF00E97";
  1025     PEPIdentity *identAlice = [self
  1026                                checkImportingKeyFilePath:@"6FF00E97_sec.asc"
  1027                                address:@"pep.test.alice@pep-project.org"
  1028                                userID:@"alice_user_id"
  1029                                fingerPrint:fprAlice
  1030                                session: session];
  1031     XCTAssertNotNil(identAlice);
  1032 
  1033     NSString *shortMessage = @"whatever it may be";
  1034     NSString *longMessage = [NSString stringWithFormat:@"%@ %@", shortMessage, shortMessage];
  1035     PEPMessage *message = [PEPMessage new];
  1036     message.from = identMe;
  1037     message.to = @[identAlice];
  1038     message.shortMessage = shortMessage;
  1039     message.longMessage = longMessage;
  1040 
  1041     PEPStatus status = PEPStatusKeyNotFound;
  1042     error = nil;
  1043     PEPMessage *encrypted = [session
  1044                              encryptMessage:message
  1045                              toFpr:fprAlice
  1046                              encFormat:PEPEncFormatPEP
  1047                              flags:0
  1048                              status:&status error:&error];
  1049     XCTAssertEqual(status, PEPStatusIllegalValue);
  1050     XCTAssertNotNil(error);
  1051     XCTAssertNil(encrypted);
  1052 }
  1053 
  1054 - (void)testSetIdentityFlags
  1055 {
  1056     PEPSession *session = [PEPSession new];
  1057 
  1058     PEPIdentity *me = [PEPTestUtils ownPepIdentityWithAddress:@"me@peptest.ch"
  1059                                                      userName:@"userName"];
  1060     NSError *error = nil;
  1061     XCTAssertTrue([session mySelf:me error:&error]);
  1062     XCTAssertNil(error);
  1063 
  1064     PEPIdentityFlags theFlags[] = {
  1065         PEPIdentityFlagsNotForSync,
  1066         PEPIdentityFlagsList,
  1067         PEPIdentityFlagsDeviceGroup,
  1068         0
  1069     };
  1070 
  1071     for (int i = 0;; ++i) {
  1072         PEPIdentityFlags aFlag = theFlags[i];
  1073         if (aFlag == 0) {
  1074             break;
  1075         }
  1076         error = nil;
  1077         XCTAssertTrue([session setFlags:(PEPIdentityFlags) aFlag forIdentity:me error:&error]);
  1078         XCTAssertNil(error);
  1079 
  1080         XCTAssertTrue(me.flags & theFlags[i]);
  1081     }
  1082 }
  1083 
  1084 - (void)testTrustOwnKey
  1085 {
  1086     PEPSession *session = [PEPSession new];
  1087 
  1088     PEPIdentity *me = [PEPTestUtils ownPepIdentityWithAddress:@"me@peptest.ch"
  1089                                                      userName:@"userName"];
  1090     NSError *error = nil;
  1091     XCTAssertTrue([session mySelf:me error:&error]);
  1092     XCTAssertNil(error);
  1093 
  1094     XCTAssertTrue([session trustOwnKeyIdentity:me error:&error]);
  1095     XCTAssertNil(error);
  1096 }
  1097 
  1098 #pragma mark - configUnencryptedSubject
  1099 
  1100 - (void)testConfigUnencryptedSubject
  1101 {
  1102     // Setup Config to encrypt subject
  1103     [PEPObjCAdapter setUnEncryptedSubjectEnabled:NO];
  1104 
  1105     // Write mail to yourself ...
  1106     PEPMessage *encMessage = [self mailWrittenToMySelf];
  1107 
  1108     // ... and assert subject is encrypted
  1109     XCTAssertEqualObjects(encMessage.shortMessage, @"p≡p", @"Subject should be encrypted");
  1110 }
  1111 
  1112 - (void)testConfigUnencryptedSubjectEncryptedSubjectDisabled
  1113 {
  1114     // Setup Config to not encrypt subject
  1115     [PEPObjCAdapter setUnEncryptedSubjectEnabled:YES];
  1116 
  1117     // Write mail to yourself ...
  1118     PEPMessage *encMessage = [self mailWrittenToMySelf];
  1119 
  1120     // pEp to pEp uses message 2.0, which always encrypts subjects (ENGINE-429)
  1121     XCTAssertEqualObjects(encMessage.shortMessage, @"p≡p", @"Subject should be encrypted");
  1122 }
  1123 
  1124 #pragma mark - Passive mode
  1125 
  1126 - (void)testPassiveMode
  1127 {
  1128     [self testPassiveModeEnabled:NO];
  1129     [self testPassiveModeEnabled:YES];
  1130 }
  1131 
  1132 #pragma mark - Decryption
  1133 
  1134 - (void)testDecryptionOfUnencryptedMessageWithOdtAttachmentContainingSpace
  1135 {
  1136     PEPSession *session = [PEPSession new];
  1137 
  1138     PEPIdentity *me = [PEPTestUtils ownPepIdentityWithAddress:@"me@peptest.ch"
  1139                                                      userName:@"userName"];
  1140     NSError *error = nil;
  1141     XCTAssertTrue([session mySelf:me error:&error]);
  1142     XCTAssertNil(error);
  1143 
  1144     const char *dataString = "blahblah";
  1145     const size_t dataSize = strlen(dataString);
  1146     char *rawData = strndup(dataString, dataSize);
  1147 
  1148     PEPAttachment *attachment = [[PEPAttachment alloc]
  1149                                  initWithData:[NSData
  1150                                                dataWithBytesNoCopy:rawData length:dataSize]];
  1151     attachment.filename = @"Someone andTextIncludingTheSpace.odt";
  1152     attachment.mimeType = @"application/vnd.oasis.opendocument.text";
  1153 
  1154     NSString *shortMessage = @"Subject";
  1155     NSString *longMessage = @"Oh, this is a long body text!";
  1156     PEPMessage *mail = [PEPTestUtils mailFrom:me
  1157                                       toIdent:me
  1158                                  shortMessage:shortMessage
  1159                                   longMessage:longMessage
  1160                                      outgoing:YES];
  1161 
  1162     mail.attachments = @[attachment];
  1163 
  1164     error = nil;
  1165     PEPStringList *keys;
  1166     PEPRating rating = PEPRatingUndefined;
  1167     PEPMessage *decmsg = [session
  1168                           decryptMessage:mail
  1169                           flags:nil
  1170                           rating:&rating
  1171                           extraKeys:&keys
  1172                           status:nil
  1173                           error:&error];
  1174     XCTAssertNotNil(decmsg);
  1175     XCTAssertNil(error);
  1176     XCTAssertEqual(rating, PEPRatingUnencrypted);
  1177 
  1178     PEPAttachment *decryptedAttachment = [decmsg.attachments objectAtIndex:0];
  1179     XCTAssertEqualObjects(decryptedAttachment.mimeType, attachment.mimeType);
  1180     XCTAssertEqualObjects(decryptedAttachment.filename, attachment.filename);
  1181 }
  1182 
  1183 #pragma mark - Sync
  1184 
  1185 /// Prove that mySelf triggers a message to be sent.
  1186 - (void)testBasicSendMessage
  1187 {
  1188     PEPSession *session = [PEPSession new];
  1189     [self testSendMessageOnSession:session];
  1190 }
  1191 
  1192 - (void)testDeliverHandshakeResult
  1193 {
  1194     PEPSession *session = [PEPSession new];
  1195     [self testSendMessageOnSession:session];
  1196 
  1197     PEPSyncHandshakeResult handshakeResults[] = { PEPSyncHandshakeResultCancel,
  1198         PEPSyncHandshakeResultAccepted, PEPSyncHandshakeResultRejected };
  1199 
  1200     PEPIdentity *forSureNotMe = [[PEPIdentity alloc]
  1201                                  initWithAddress:@"someoneelseentirely@pep-project.org"
  1202                                  userID:@"that_someone_else"
  1203                                  userName:@"other"
  1204                                  isOwn:NO];
  1205 
  1206     for (int i = 0;; ++i) {
  1207         NSError *error = nil;
  1208         XCTAssertFalse([session
  1209                         deliverHandshakeResult:handshakeResults[i]
  1210                         identitiesSharing:@[forSureNotMe]
  1211                         error:&error]);
  1212         XCTAssertNotNil(error);
  1213         XCTAssertEqual([error code], PEPStatusIllegalValue);
  1214 
  1215         if (handshakeResults[i] == PEPSyncHandshakeResultRejected) {
  1216             break;
  1217         }
  1218     }
  1219 }
  1220 
  1221 /// Test creating a new own identity with pEp sync disabled.
  1222 - (void)testNoBeaconOnMyself
  1223 {
  1224     PEPSession *session = [PEPSession new];
  1225 
  1226     XCTAssertEqual(self.sendMessageDelegate.messages.count, 0);
  1227     XCTAssertNil(self.sendMessageDelegate.lastMessage);
  1228 
  1229     PEPIdentity *identMe = [[PEPIdentity alloc]
  1230                             initWithAddress:@"me-myself-and-i@pep-project.org"
  1231                             userID:@"me-myself-and-i"
  1232                             userName:@"pEp Me"
  1233                             isOwn:YES];
  1234     identMe.flags |= PEPIdentityFlagsNotForSync;
  1235 
  1236     NSError *error = nil;
  1237     XCTAssertTrue([session mySelf:identMe error:&error]);
  1238     XCTAssertNil(error);
  1239     XCTAssertTrue([session disableSyncForIdentity:identMe error:&error]);
  1240     XCTAssertNil(error);
  1241 
  1242     [self startSync];
  1243 
  1244     [NSThread sleepForTimeInterval:1];
  1245     XCTAssertNil(self.sendMessageDelegate.lastMessage);
  1246 
  1247     XCTAssertEqual(self.sendMessageDelegate.messages.count, 0);
  1248     [self shutdownSync];
  1249 }
  1250 
  1251 /// Test creating a new own identity with pEp sync disabled,
  1252 /// and then creating one with sync enabled, ensuring that
  1253 /// the beacon (on the 2nd identity with sync enabled) gets send out.
  1254 - (void)testMyselfSyncDisabledMyselfSyncEnabled
  1255 {
  1256     PEPSession *session = [PEPSession new];
  1257 
  1258     XCTAssertEqual(self.sendMessageDelegate.messages.count, 0);
  1259     XCTAssertNil(self.sendMessageDelegate.lastMessage);
  1260 
  1261     PEPIdentity *identMeDisabled = [[PEPIdentity alloc]
  1262                                     initWithAddress:@"me-myself-and-i@pep-project.org"
  1263                                     userID:@"me-myself-and-i"
  1264                                     userName:@"pEp Me"
  1265                                     isOwn:YES];
  1266     identMeDisabled.flags |= PEPIdentityFlagsNotForSync;
  1267 
  1268     NSError *error = nil;
  1269     XCTAssertTrue([session mySelf:identMeDisabled error:&error]);
  1270     XCTAssertNil(error);
  1271     XCTAssertTrue([session disableSyncForIdentity:identMeDisabled error:&error]);
  1272     XCTAssertNil(error);
  1273 
  1274     [self startSync];
  1275 
  1276     [NSThread sleepForTimeInterval:1];
  1277     XCTAssertNil(self.sendMessageDelegate.lastMessage);
  1278 
  1279     XCTAssertEqual(self.sendMessageDelegate.messages.count, 0);
  1280 
  1281     PEPIdentity *identMeEnsabled = [[PEPIdentity alloc]
  1282                                     initWithAddress:@"me-myself-and-i_enabled@pep-project.org"
  1283                                     userID:@"me-myself-and-i_enabled"
  1284                                     userName:@"pEp Me_enabled"
  1285                                     isOwn:YES];
  1286 
  1287     error = nil;
  1288     XCTAssertTrue([session mySelf:identMeEnsabled error:&error]);
  1289     XCTAssertNil(error);
  1290 
  1291     XCTKVOExpectation *expHaveMessage1 = [[XCTKVOExpectation alloc]
  1292                                           initWithKeyPath:@"lastMessage"
  1293                                           object:self.sendMessageDelegate];
  1294     [self waitForExpectations:@[expHaveMessage1] timeout:PEPTestInternalSyncTimeout];
  1295     XCTAssertNotNil(self.sendMessageDelegate.lastMessage);
  1296     XCTAssertGreaterThan(self.sendMessageDelegate.messages.count, 0);
  1297 
  1298     XCTAssertEqualObjects(self.sendMessageDelegate.lastMessage.from.address,
  1299                           identMeEnsabled.address);
  1300 
  1301     [self shutdownSync];
  1302 }
  1303 
  1304 /// ENGINE-684
  1305 - (void)testMyselfWithQueryKeySyncEnabledForIdentity
  1306 {
  1307     PEPSession *session = [PEPSession new];
  1308 
  1309     PEPIdentity *identMeEnabled = [[PEPIdentity alloc]
  1310                                    initWithAddress:@"me-myself-and-i-enabled@pep-project.org"
  1311                                    userID:@"me-myself-and-i-enabled"
  1312                                    userName:@"pEp Me Enabled"
  1313                                    isOwn:YES];
  1314 
  1315     PEPIdentity *identMeDisabled = [[PEPIdentity alloc]
  1316                                     initWithAddress:@"me-myself-and-i-disabled@pep-project.org"
  1317                                     userID:@"me-myself-and-i-disabled"
  1318                                     userName:@"pEp Me Disabled"
  1319                                     isOwn:YES];
  1320 
  1321     for (PEPIdentity *ident in @[identMeEnabled, identMeDisabled]) {
  1322         BOOL expectEnabled = ident == identMeEnabled ? YES : NO;
  1323 
  1324         if (!expectEnabled) {
  1325             ident.flags |= PEPIdentityFlagsNotForSync;
  1326         }
  1327 
  1328         NSError *error = nil;
  1329         XCTAssertTrue([session mySelf:ident error:&error]);
  1330         XCTAssertNil(error);
  1331 
  1332         if (!expectEnabled) {
  1333             XCTAssertTrue([session disableSyncForIdentity:ident error:&error]);
  1334             XCTAssertNil(error);
  1335         }
  1336 
  1337         NSNumber *enabledNum = [session queryKeySyncEnabledForIdentity:ident error:&error];
  1338         XCTAssertNotNil(enabledNum);
  1339         XCTAssertNil(error);
  1340 
  1341         XCTAssertEqual([enabledNum boolValue], expectEnabled);
  1342     }
  1343 }
  1344 
  1345 #pragma mark - key_reset_identity
  1346 
  1347 - (void)testKeyResetIdentity
  1348 {
  1349     PEPSession *session = [PEPSession new];
  1350 
  1351     PEPIdentity *me = [PEPTestUtils ownPepIdentityWithAddress:@"me@peptest.ch"
  1352                                                      userName:@"userName"];
  1353 
  1354     NSError *error = nil;
  1355     XCTAssertTrue([session mySelf:me error:&error]);
  1356     XCTAssertNil(error);
  1357 
  1358     NSString *fprOriginal = me.fingerPrint;
  1359     XCTAssertNotNil(fprOriginal);
  1360 
  1361     XCTAssertTrue([session keyReset:me fingerprint:nil error:&error]);
  1362     XCTAssertNil(error);
  1363 
  1364     XCTAssertTrue([session mySelf:me error:&error]);
  1365     XCTAssertNil(error);
  1366 
  1367     NSString *fprAfterReset = me.fingerPrint;
  1368     XCTAssertNotNil(fprAfterReset);
  1369 
  1370     XCTAssertNotEqual(fprOriginal, fprAfterReset);
  1371 }
  1372 
  1373 #pragma mark - leave_device_group
  1374 
  1375 /** Leaving a device group is successful even though none exists. */
  1376 - (void)testSuccessfulLeaveDeviceGroup
  1377 {
  1378     PEPSession *session = [PEPSession new];
  1379 
  1380     PEPIdentity *identMe = [[PEPIdentity alloc]
  1381                             initWithAddress:@"me-myself-and-i@pep-project.org"
  1382                             userID:@"me-myself-and-i"
  1383                             userName:@"pEp Me"
  1384                             isOwn:YES];
  1385     NSError *error = nil;
  1386     XCTAssertTrue([session mySelf:identMe error:&error]);
  1387     XCTAssertNil(error);
  1388 
  1389     [self startSync];
  1390 
  1391     error = nil;
  1392     XCTAssertTrue([session leaveDeviceGroup:&error]);
  1393     XCTAssertNil(error);
  1394 
  1395     // leaving a device group should disable sync
  1396     XCTAssertTrue(self.notifyHandshakeDelegate.engineDidShutdownKeySync);
  1397 
  1398     [self shutdownSync];
  1399 }
  1400 
  1401 #pragma mark - enable/disable sync
  1402 
  1403 - (void)testEnableDisableFailForSyncOnPartnerIdentity
  1404 {
  1405     PEPIdentity *notMe = [[PEPIdentity alloc]
  1406                           initWithAddress:@"notme@pep-project.org"
  1407                           userID:@"notme_ID"
  1408                           userName:@"notme"
  1409                           isOwn:NO];
  1410 
  1411     NSError *error = nil;
  1412     XCTAssertFalse([notMe enableKeySync:&error]);
  1413     XCTAssertNotNil(error);
  1414 
  1415     error = nil;
  1416     XCTAssertFalse([notMe disableKeySync:&error]);
  1417     XCTAssertNotNil(error);
  1418 
  1419     error = nil;
  1420     XCTAssertNil([notMe queryKeySyncEnabled:&error]);
  1421     XCTAssertNotNil(error);
  1422 }
  1423 
  1424 - (void)testEnableDisableSyncOnOwnIdentityWithQuery
  1425 {
  1426     PEPSession *session = [PEPSession new];
  1427 
  1428     PEPIdentity *identMe1 = [[PEPIdentity alloc]
  1429                              initWithAddress:@"me-myself-and-i@pep-project.org"
  1430                              userID:@"me-myself-and-i"
  1431                              userName:@"pEp Me"
  1432                              isOwn:YES];
  1433     NSError *error = nil;
  1434     XCTAssertTrue([session mySelf:identMe1 error:&error]);
  1435     XCTAssertNil(error);
  1436 
  1437     error = nil;
  1438     PEPIdentity *identMe2 = [[PEPIdentity alloc]
  1439                              initWithAddress:@"me-myself-and-i2@pep-project.org"
  1440                              userID:@"me-myself-and-i2"
  1441                              userName:@"pEp Me2"
  1442                              isOwn:YES];
  1443     XCTAssertTrue([session mySelf:identMe2 error:&error]);
  1444     XCTAssertNil(error);
  1445 
  1446     XCTAssertNotEqualObjects(identMe1.fingerPrint, identMe2.fingerPrint);
  1447 
  1448     for (int i = 0; i < 10; ++i) {
  1449         error = nil;
  1450         BOOL enable = i % 2 == 0; // enable keysync on even numbers (roughly)
  1451         if (enable) {
  1452             XCTAssertTrue([session enableSyncForIdentity:identMe1 error:&error]);
  1453             XCTAssertTrue([identMe2 enableKeySync:&error]);
  1454         } else {
  1455             XCTAssertTrue([session disableSyncForIdentity:identMe1 error:&error]);
  1456             XCTAssertTrue([identMe2 disableKeySync:&error]);
  1457         }
  1458         XCTAssertNil(error);
  1459 
  1460         NSNumber *keySyncState1 = [session queryKeySyncEnabledForIdentity:identMe1 error:&error];
  1461         NSNumber *keySyncState2 = [identMe2 queryKeySyncEnabled:&error];
  1462         XCTAssertNil(error);
  1463         XCTAssertNotNil(keySyncState1);
  1464         XCTAssertNotNil(keySyncState2);
  1465         if (enable) {
  1466             XCTAssertTrue([keySyncState1 boolValue]);
  1467         } else {
  1468             XCTAssertFalse([keySyncState1 boolValue]);
  1469         }
  1470         XCTAssertEqualObjects(keySyncState1, keySyncState2);
  1471     }
  1472 }
  1473 
  1474 /**
  1475  ENGINE-604, just in case.
  1476  */
  1477 - (void)testQueryKeySyncOnOwnIdentityInALoop
  1478 {
  1479     PEPSession *session = [PEPSession new];
  1480 
  1481     PEPIdentity *identMe = [[PEPIdentity alloc]
  1482                             initWithAddress:@"me-myself-and-i@pep-project.org"
  1483                             userID:@"me-myself-and-i"
  1484                             userName:@"pEp Me"
  1485                             isOwn:YES];
  1486     NSError *error = nil;
  1487     XCTAssertTrue([session mySelf:identMe error:&error]);
  1488     XCTAssertNil(error);
  1489 
  1490     for (NSNumber *numBool in @[@YES, @NO]) {
  1491         error = nil;
  1492         if ([numBool boolValue]) {
  1493             XCTAssertTrue([session enableSyncForIdentity:identMe error:&error]);
  1494         } else {
  1495             XCTAssertTrue([session disableSyncForIdentity:identMe error:&error]);
  1496         }
  1497         XCTAssertNil(error);
  1498 
  1499         for (int i = 0; i < 10; ++i) {
  1500             NSNumber *numQuery = [session queryKeySyncEnabledForIdentity:identMe error:&error];
  1501             XCTAssertNotNil(numQuery);
  1502             XCTAssertEqualObjects(numBool, numQuery);
  1503             XCTAssertNil(error);
  1504         }
  1505     }
  1506 }
  1507 
  1508 #pragma mark - Basic Passphrases
  1509 
  1510 - (void)testOwnKeyWithPasswordAndEncryptToSelf
  1511 {
  1512     NSString *correctPassphrase = @"passphrase_testOwnKeyWithPasswordAndEncryptToSelf";
  1513 
  1514     NSError *error = nil;
  1515 
  1516     XCTAssertTrue([PEPObjCAdapter configurePassphraseForNewKeys:correctPassphrase error:&error]);
  1517     XCTAssertNil(error);
  1518 
  1519     PEPSession *session = [PEPSession new];
  1520 
  1521     PEPIdentity *identMeWithPassphrase = [[PEPIdentity alloc]
  1522                                           initWithAddress:@"me-myself-and-i@pep-project.org"
  1523                                           userID:@"me-myself-and-i"
  1524                                           userName:@"pEp Me"
  1525                                           isOwn:YES];
  1526 
  1527     XCTAssertTrue([session mySelf:identMeWithPassphrase error:&error]);
  1528     XCTAssertNil(error);
  1529 
  1530     PEPIdentity *receiver1 = [[PEPIdentity alloc]
  1531                               initWithAddress:@"partner1@example.com"
  1532                               userID:@"partner1"
  1533                               userName:@"Partner 1"
  1534                                           isOwn:NO];
  1535 
  1536     PEPMessage *draftMail = [PEPTestUtils
  1537                              mailFrom:identMeWithPassphrase
  1538                              toIdent:receiver1
  1539                              shortMessage:@"hey"
  1540                              longMessage:@"hey hey"
  1541                              outgoing:YES];
  1542 
  1543     error = nil;
  1544     PEPStatus status = PEPStatusOutOfMemory;
  1545 
  1546     XCTAssertTrue([session
  1547                    encryptMessage:draftMail
  1548                    forSelf:identMeWithPassphrase
  1549                    extraKeys:nil
  1550                    status:&status
  1551                    error:&error]);
  1552     XCTAssertNil(error);
  1553 }
  1554 
  1555 - (void)testNotifyHandshakePassphraseNotRequired
  1556 {
  1557     NSString *correctPassphrase = @"passphrase_testOwnKeyWithPasswordSendMessage";
  1558 
  1559     XCTAssertEqual(self.sendMessageDelegate.messages.count, 0);
  1560     XCTAssertNil(self.sendMessageDelegate.lastMessage);
  1561 
  1562     NSError *error = nil;
  1563 
  1564     XCTAssertTrue([PEPObjCAdapter configurePassphraseForNewKeys:correctPassphrase error:&error]);
  1565     XCTAssertNil(error);
  1566     error = nil;
  1567 
  1568     PEPSession *session = [PEPSession new];
  1569 
  1570     PEPIdentity *identMe = [[PEPIdentity alloc]
  1571                             initWithAddress:@"me-myself-and-i@pep-project.org"
  1572                             userID:@"me-myself-and-i"
  1573                             userName:@"pEp Me"
  1574                             isOwn:YES];
  1575 
  1576     XCTAssertTrue([session mySelf:identMe error:&error]);
  1577     XCTAssertNil(error);
  1578 
  1579     [self startSync];
  1580 
  1581     XCTKVOExpectation *expHaveMessage1 = [[XCTKVOExpectation alloc]
  1582                                           initWithKeyPath:@"lastMessage"
  1583                                           object:self.sendMessageDelegate];
  1584     [self waitForExpectations:@[expHaveMessage1] timeout:PEPTestInternalSyncTimeout];
  1585     XCTAssertNotNil(self.sendMessageDelegate.lastMessage);
  1586     XCTAssertGreaterThan(self.sendMessageDelegate.messages.count, 0);
  1587 
  1588     XCTAssertEqualObjects(self.sendMessageDelegate.lastMessage.from.address, identMe.address);
  1589 
  1590     [self shutdownSync];
  1591 }
  1592 
  1593 #pragma mark - Passphrase Cache
  1594 
  1595 /// Use case: No passphrase provider
  1596 - (void)testPassphraseProviderNone
  1597 {
  1598     PEPMessage *draftMail = nil;
  1599     PEPSession *session = nil;
  1600     PEPIdentity *identMe = nil;
  1601 
  1602     [self setupEncryptWithImportedKeySession:&session
  1603                                  ownIdentity:&identMe
  1604                             messageToEncrypt:&draftMail];
  1605 
  1606     NSError *error = nil;
  1607     PEPStatus status = PEPStatusOutOfMemory;
  1608 
  1609     XCTAssertFalse([session
  1610                     encryptMessage:draftMail
  1611                     forSelf:identMe
  1612                     extraKeys:nil
  1613                     status:&status
  1614                     error:&error]);
  1615     XCTAssertNotNil(error);
  1616 
  1617     XCTAssertEqualObjects(error.domain, PEPObjCAdapterEngineStatusErrorDomain);
  1618     XCTAssertEqual(error.code, PEPStatusPassphraseRequired);
  1619 }
  1620 
  1621 /// Use case: Passphrase provider set, but never delivers passphrases
  1622 - (void)testPassphraseProviderEmpty
  1623 {
  1624     PEPMessage *draftMail = nil;
  1625     PEPSession *session = nil;
  1626     PEPIdentity *identMe = nil;
  1627 
  1628     [self setupEncryptWithImportedKeySession:&session
  1629                                  ownIdentity:&identMe
  1630                             messageToEncrypt:&draftMail];
  1631 
  1632     NSError *error = nil;
  1633     PEPStatus status = PEPStatusOutOfMemory;
  1634 
  1635     [PEPObjCAdapter setPassphraseProvider:[[PEPPassphraseProviderMock alloc]
  1636                                            initWithPassphrases:@[]]];
  1637 
  1638     XCTAssertFalse([session
  1639                     encryptMessage:draftMail
  1640                     forSelf:identMe
  1641                     extraKeys:nil
  1642                     status:&status
  1643                     error:&error]);
  1644     XCTAssertNotNil(error);
  1645 
  1646     XCTAssertEqualObjects(error.domain, PEPObjCAdapterEngineStatusErrorDomain);
  1647     XCTAssertEqual(error.code, PEPStatusPassphraseRequired);
  1648 }
  1649 
  1650 /// Use case: Passphrase provider set, only delivers incorrect passphrases
  1651 - (void)testPassphraseProviderWrongPassphrases
  1652 {
  1653     PEPMessage *draftMail = nil;
  1654     PEPSession *session = nil;
  1655     PEPIdentity *identMe = nil;
  1656 
  1657     [self setupEncryptWithImportedKeySession:&session
  1658                                  ownIdentity:&identMe
  1659                             messageToEncrypt:&draftMail];
  1660 
  1661     NSError *error = nil;
  1662     PEPStatus status = PEPStatusOutOfMemory;
  1663 
  1664     NSArray *nonsensePassphrases = @[@"blah1", @"blah2", @"blah3"];
  1665     [PEPObjCAdapter setPassphraseProvider:[[PEPPassphraseProviderMock alloc]
  1666                                            initWithPassphrases:nonsensePassphrases]];
  1667 
  1668     XCTAssertFalse([session
  1669                     encryptMessage:draftMail
  1670                     forSelf:identMe
  1671                     extraKeys:nil
  1672                     status:&status
  1673                     error:&error]);
  1674     XCTAssertNotNil(error);
  1675 
  1676     XCTAssertEqualObjects(error.domain, PEPObjCAdapterEngineStatusErrorDomain);
  1677     XCTAssertEqual(error.code, PEPStatusWrongPassphrase);
  1678 }
  1679 
  1680 /// Use case: 1 Passphrase, but too long
  1681 - (void)testPassphraseProviderPassphraseTooLong
  1682 {
  1683     PEPMessage *draftMail = nil;
  1684     PEPSession *session = nil;
  1685     PEPIdentity *identMe = nil;
  1686 
  1687     [self setupEncryptWithImportedKeySession:&session
  1688                                  ownIdentity:&identMe
  1689                             messageToEncrypt:&draftMail];
  1690 
  1691     NSError *error = nil;
  1692     PEPStatus status = PEPStatusOutOfMemory;
  1693 
  1694     NSString *passphraseBase = @"base";
  1695     NSString *passphraseTooLong = passphraseBase;
  1696     for (NSUInteger i = 0; i < 250; ++i) {
  1697         passphraseTooLong = [passphraseTooLong stringByAppendingString:passphraseBase];
  1698     }
  1699 
  1700     NSArray *onePassphraseThatIsTooLong = @[passphraseTooLong];
  1701     PEPPassphraseProviderMock *passphraseProviderMock1 = [[PEPPassphraseProviderMock
  1702                                                            alloc]
  1703                                                           initWithPassphrases:onePassphraseThatIsTooLong];
  1704     [PEPObjCAdapter setPassphraseProvider:passphraseProviderMock1];
  1705 
  1706     XCTAssertFalse([session
  1707                     encryptMessage:draftMail
  1708                     forSelf:identMe
  1709                     extraKeys:nil
  1710                     status:&status
  1711                     error:&error]);
  1712     XCTAssertNotNil(error);
  1713 
  1714     XCTAssertEqualObjects(error.domain, PEPObjCAdapterEngineStatusErrorDomain);
  1715     XCTAssertEqual(error.code, PEPStatusWrongPassphrase);
  1716     XCTAssertTrue(passphraseProviderMock1.passphraseTooLongWasCalled);
  1717 }
  1718 
  1719 /// Use case: Passphrase provider set, has correct passphrase after 2 unsuccessful attempts
  1720 - (void)testPassphraseProviderCorrectPassphrase
  1721 {
  1722     PEPMessage *draftMail = nil;
  1723     PEPSession *session = nil;
  1724     PEPIdentity *identMe = nil;
  1725 
  1726     [self setupEncryptWithImportedKeySession:&session
  1727                                  ownIdentity:&identMe
  1728                             messageToEncrypt:&draftMail];
  1729 
  1730     NSError *error = nil;
  1731     PEPStatus status = PEPStatusOutOfMemory;
  1732 
  1733     NSString *correctPassphrase = @"uiae";
  1734     NSArray *passphrases = @[@"blah1", @"blah2", correctPassphrase];
  1735     [PEPObjCAdapter setPassphraseProvider:[[PEPPassphraseProviderMock alloc]
  1736                                            initWithPassphrases:passphrases]];
  1737 
  1738     XCTAssertTrue([session
  1739                    encryptMessage:draftMail
  1740                    forSelf:identMe
  1741                    extraKeys:nil
  1742                    status:&status
  1743                    error:&error]);
  1744     XCTAssertNil(error);
  1745 }
  1746 
  1747 #pragma mark - Helpers
  1748 
  1749 - (void)setupEncryptWithImportedKeySession:(PEPSession **)session
  1750                                ownIdentity:(PEPIdentity **)ownIdentity
  1751                           messageToEncrypt:(PEPMessage **)messageToEncrypt
  1752 {
  1753     *session = [PEPSession new];
  1754 
  1755     NSString *fingerprint = [@"9DD8 3053 3B93 988A 9777  52CA 4802 9ADE 43F2 70EC"
  1756                              stringByReplacingOccurrencesOfString:@" " withString:@""];
  1757     fingerprint = [fingerprint stringByReplacingOccurrencesOfString:@"  " withString:@""];
  1758 
  1759     *ownIdentity = [self
  1760                     checkMySelfImportingKeyFilePath:@"Rick Deckard (43F270EC) – Secret.asc"
  1761                     address:@"deckard@example.com"
  1762                     userID:@"deckard_user_id"
  1763                     fingerPrint:fingerprint
  1764                     session:*session];
  1765     XCTAssertNotNil(*ownIdentity);
  1766 
  1767     PEPIdentity *dummyReceiver = [[PEPIdentity alloc]
  1768                                   initWithAddress:@"partner1@example.com"
  1769                                   userID:@"partner1"
  1770                                   userName:@"Partner 1"
  1771                                   isOwn:NO];
  1772 
  1773     *messageToEncrypt = [PEPTestUtils
  1774                          mailFrom:*ownIdentity
  1775                          toIdent:dummyReceiver
  1776                          shortMessage:@"hey"
  1777                          longMessage:@"hey hey"
  1778                          outgoing:YES];
  1779 }
  1780 
  1781 - (void)testSendMessageOnSession:(PEPSession *)session
  1782 {
  1783     XCTAssertEqual(self.sendMessageDelegate.messages.count, 0);
  1784     XCTAssertNil(self.sendMessageDelegate.lastMessage);
  1785 
  1786     PEPIdentity *identMe = [[PEPIdentity alloc]
  1787                             initWithAddress:@"me-myself-and-i@pep-project.org"
  1788                             userID:@"me-myself-and-i"
  1789                             userName:@"pEp Me"
  1790                             isOwn:YES];
  1791 
  1792     NSError *error = nil;
  1793     XCTAssertTrue([session mySelf:identMe error:&error]);
  1794     XCTAssertNil(error);
  1795 
  1796     [self startSync];
  1797 
  1798     XCTKVOExpectation *expHaveMessage = [[XCTKVOExpectation alloc]
  1799                                          initWithKeyPath:@"lastMessage"
  1800                                          object:self.sendMessageDelegate];
  1801 
  1802     XCTAssertNotNil(identMe.fingerPrint);
  1803 
  1804     [self waitForExpectations:@[expHaveMessage] timeout:PEPTestInternalSyncTimeout];
  1805     XCTAssertNotNil(self.sendMessageDelegate.lastMessage);
  1806 
  1807     XCTAssertEqual(self.sendMessageDelegate.messages.count, 1);
  1808     [self shutdownSync];
  1809 }
  1810 
  1811 - (void)startSync
  1812 {
  1813     self.sendMessageDelegate = [PEPSessionTestSendMessageDelegate new];
  1814     self.notifyHandshakeDelegate = [PEPSessionTestNotifyHandshakeDelegate new];
  1815 
  1816     self.sync = [[PEPSync alloc]
  1817                  initWithSendMessageDelegate:self.sendMessageDelegate
  1818                  notifyHandshakeDelegate:self.notifyHandshakeDelegate];
  1819     [self.sync startup];
  1820 }
  1821 
  1822 - (void)shutdownSync
  1823 {
  1824     [self.sync shutdown];
  1825 }
  1826 
  1827 - (NSNumber * _Nullable)testOutgoingRatingForMessage:(PEPMessage * _Nonnull)theMessage
  1828                                              session:(PEPSession *)session
  1829                                                error:(NSError * _Nullable * _Nullable)error
  1830 {
  1831     NSNumber *ratingOriginal = [session outgoingRatingForMessage:theMessage error:error];
  1832     NSNumber *ratingPreview = [session outgoingRatingPreviewForMessage:theMessage error:nil];
  1833     XCTAssertEqual(ratingOriginal, ratingPreview);
  1834     return ratingOriginal;
  1835 }
  1836 
  1837 - (void)testPassiveModeEnabled:(BOOL)passiveModeEnabled
  1838 {
  1839     [PEPObjCAdapter setPassiveModeEnabled:passiveModeEnabled];
  1840     PEPSession *session = [PEPSession new];
  1841 
  1842     PEPIdentity *identMe = [[PEPIdentity alloc]
  1843                             initWithAddress:@"me-myself-and-i@pep-project.org"
  1844                             userID:@"me-myself-and-i"
  1845                             userName:@"pEp Me"
  1846                             isOwn:YES];
  1847     NSError *error = nil;
  1848     XCTAssertTrue([session mySelf:identMe error:&error]);
  1849     XCTAssertNil(error);
  1850 
  1851     XCTAssertNotNil(identMe.fingerPrint);
  1852 
  1853     PEPIdentity *identAlice = [[PEPIdentity alloc]
  1854                                initWithAddress:@"pep.test.alice@pep-project.org"
  1855                                userID:@"alice_user_id"
  1856                                userName:@"Alice"
  1857                                isOwn:NO];
  1858 
  1859     NSString *shortMessage = @"whatever it may be";
  1860     NSString *longMessage = [NSString stringWithFormat:@"%@ %@", shortMessage, shortMessage];
  1861     PEPMessage *message = [PEPMessage new];
  1862     message.direction = PEPMsgDirectionOutgoing;
  1863     message.from = identMe;
  1864     message.to = @[identAlice];
  1865     message.shortMessage = shortMessage;
  1866     message.longMessage = longMessage;
  1867 
  1868     PEPStatus status = PEPStatusKeyNotFound;
  1869     PEPMessage *encryptedMessage =  [session encryptMessage:message
  1870                                                   extraKeys:@[]
  1871                                                      status:&status
  1872                                                       error:&error];
  1873     XCTAssertNil(error);
  1874     XCTAssertEqual(status, PEPStatusUnencrypted);
  1875 
  1876     if (passiveModeEnabled) {
  1877         XCTAssertNil(encryptedMessage.attachments);
  1878     } else {
  1879         XCTAssertEqual(encryptedMessage.attachments.count, 1);
  1880     }
  1881 }
  1882 
  1883 /**
  1884  Determines the rating for the given identity.
  1885  @return PEPRatingUndefined on error
  1886  */
  1887 - (PEPRating)ratingForIdentity:(PEPIdentity *)identity session:(PEPSession *)session
  1888 {
  1889     NSError *error;
  1890     NSNumber *numRating = [session ratingForIdentity:identity error:&error];
  1891     XCTAssertNil(error);
  1892     return numRating.pEpRating;
  1893 }
  1894 
  1895 - (PEPIdentity *)checkImportingKeyFilePath:(NSString *)filePath address:(NSString *)address
  1896                                     userID:(NSString *)userID
  1897                                fingerPrint:(NSString *)fingerPrint
  1898                                    session:(PEPSession *)session
  1899 {
  1900     if (!session) {
  1901         session = [PEPSession new];
  1902     }
  1903 
  1904     BOOL success = [PEPTestUtils importBundledKey:filePath session:session];
  1905     XCTAssertTrue(success);
  1906 
  1907     if (success) {
  1908         // Our test user:
  1909         PEPIdentity *identTest = [[PEPIdentity alloc]
  1910                                   initWithAddress:address
  1911                                   userID:userID
  1912                                   userName:[NSString stringWithFormat:@"Some User Name %@", userID]
  1913                                   isOwn:NO];
  1914 
  1915         NSError *error = nil;
  1916         XCTAssertTrue([session updateIdentity:identTest error:&error]);
  1917         XCTAssertNil(error);
  1918         XCTAssertNotNil(identTest.fingerPrint);
  1919         XCTAssertEqualObjects(identTest.fingerPrint, fingerPrint);
  1920 
  1921         return identTest;
  1922     } else {
  1923         return nil;
  1924     }
  1925 }
  1926 
  1927 - (PEPIdentity *)checkMySelfImportingKeyFilePath:(NSString *)filePath
  1928                                          address:(NSString *)address
  1929                                           userID:(NSString *)userID
  1930                                      fingerPrint:(NSString *)fingerPrint
  1931                                          session:(PEPSession *)session
  1932 {
  1933     XCTAssertTrue([PEPTestUtils importBundledKey:filePath session:session]);
  1934 
  1935     // Our test user:
  1936     PEPIdentity *identTest = [[PEPIdentity alloc]
  1937                               initWithAddress:address
  1938                               userID:userID
  1939                               userName:[NSString stringWithFormat:@"Some User Name %@", userID]
  1940                               isOwn:YES
  1941                               fingerPrint: fingerPrint];
  1942 
  1943     NSError *error;
  1944     XCTAssertTrue([session setOwnKey:identTest fingerprint:fingerPrint error:&error]);
  1945     XCTAssertNil(error);
  1946     XCTAssertNotNil(identTest.fingerPrint);
  1947     XCTAssertEqualObjects(identTest.fingerPrint, fingerPrint);
  1948 
  1949     return identTest;
  1950 }
  1951 
  1952 /**
  1953  Verifies that a partner ID is really a correct Identity.
  1954  Usually used on identities imported as keys, since the engine has problems with them.
  1955  */
  1956 - (void)updateAndVerifyPartnerIdentity:(PEPIdentity *)partnerIdentity session:(PEPSession *)session
  1957 {
  1958     NSError *error = nil;
  1959 
  1960     XCTAssertNotNil(partnerIdentity.fingerPrint);
  1961     XCTAssertTrue([session updateIdentity:partnerIdentity error:&error]);
  1962     XCTAssertNil(error);
  1963     XCTAssertNotNil(partnerIdentity.fingerPrint);
  1964     NSString *fingerprint = partnerIdentity.fingerPrint;
  1965     partnerIdentity.fingerPrint = nil;
  1966     XCTAssertTrue([session updateIdentity:partnerIdentity error:&error]);
  1967     XCTAssertNil(error);
  1968     XCTAssertNotNil(partnerIdentity.fingerPrint);
  1969     XCTAssertEqualObjects(partnerIdentity.fingerPrint, fingerprint);
  1970 }
  1971 
  1972 - (PEPMessage *)mailWrittenToMySelf
  1973 {
  1974     PEPSession *session = [PEPSession new];
  1975 
  1976     // Write a e-mail to yourself ...
  1977     PEPIdentity *me = [PEPTestUtils ownPepIdentityWithAddress:@"me@peptest.ch"
  1978                                                      userName:@"userName"];
  1979     NSError *error = nil;
  1980     XCTAssertTrue([session mySelf:me error:&error]);
  1981     XCTAssertNil(error);
  1982 
  1983     NSString *shortMessage = @"Subject";
  1984     NSString *longMessage = @"Oh, this is a long body text!";
  1985     PEPMessage *mail = [PEPTestUtils mailFrom:me
  1986                                       toIdent:me
  1987                                  shortMessage:shortMessage
  1988                                   longMessage:longMessage
  1989                                      outgoing:YES];
  1990     PEPStatus status = PEPStatusUnknownError;
  1991     PEPMessage *encMessage = [session
  1992                               encryptMessage:mail
  1993                               forSelf:me
  1994                               extraKeys:nil
  1995                               status:&status
  1996                               error:&error];
  1997     XCTAssertNil(error);
  1998 
  1999     return encMessage;
  2000 }
  2001 
  2002 - (PEPMessage *)internalEncryptToMySelfKeys:(PEPStringList **)keys
  2003 {
  2004     PEPSession *session = [PEPSession new];
  2005     
  2006     PEPIdentity *me = [PEPTestUtils ownPepIdentityWithAddress:@"me@peptest.ch"
  2007                                                      userName:@"userName"];
  2008     NSError *error = nil;
  2009     XCTAssertTrue([session mySelf:me error:&error]);
  2010     XCTAssertNil(error);
  2011 
  2012     XCTAssertNotNil(me.fingerPrint);
  2013 
  2014     // Create draft
  2015     NSString *shortMessage = @"Subject";
  2016     NSString *longMessage = @"Oh, this is a long body text!";
  2017     PEPMessage *mail = [PEPTestUtils mailFrom:me toIdent:me shortMessage:shortMessage longMessage:longMessage outgoing:YES];
  2018 
  2019     PEPStatus status;
  2020     PEPMessage *encMessage = [session
  2021                               encryptMessage:mail
  2022                               forSelf:me
  2023                               extraKeys:nil
  2024                               status:&status
  2025                               error:&error];
  2026     XCTAssertEqual(status, 0);
  2027     XCTAssertEqualObjects(encMessage.shortMessage, @"p≡p");
  2028 
  2029     PEPRating rating;
  2030     error = nil;
  2031     PEPMessage *unencDict = [session
  2032                              decryptMessage:encMessage
  2033                              flags:nil
  2034                              rating:&rating
  2035                              extraKeys:keys
  2036                              status:nil
  2037                              error:&error];
  2038     XCTAssertNotNil(unencDict);
  2039     XCTAssertNil(error);
  2040 
  2041     XCTAssertGreaterThanOrEqual(rating, PEPRatingReliable);
  2042 
  2043     XCTAssertEqualObjects(unencDict.shortMessage, shortMessage);
  2044     XCTAssertEqualObjects(unencDict.longMessage, longMessage);
  2045 
  2046     return unencDict;
  2047 }
  2048 
  2049 - (void)pEpCleanUp
  2050 {
  2051     [PEPTestUtils cleanUp];
  2052 }
  2053 
  2054 - (void)helperXEncStatusForOutgoingEncryptdMailToSelf:(BOOL)toSelf
  2055                                        expectedRating:(PEPRating)expectedRating
  2056 {
  2057     PEPSession *session = [PEPSession new];
  2058 
  2059     // Partner pubkey for the test:
  2060     // pEp Test Alice (test key don't use) <pep.test.alice@pep-project.org>
  2061     // 4ABE3AAF59AC32CFE4F86500A9411D176FF00E97
  2062     XCTAssertTrue([PEPTestUtils importBundledKey:@"6FF00E97.asc" session:session]);
  2063 
  2064     PEPIdentity *identAlice = [[PEPIdentity alloc]
  2065                                initWithAddress:@"pep.test.alice@pep-project.org"
  2066                                userID:ownUserId
  2067                                userName:@"pEp Test Alice"
  2068                                isOwn:NO
  2069                                fingerPrint:@"4ABE3AAF59AC32CFE4F86500A9411D176FF00E97"];
  2070     [self updateAndVerifyPartnerIdentity:identAlice session:session];
  2071 
  2072     PEPIdentity *identMe = [[PEPIdentity alloc]
  2073                                initWithAddress:@"me-myself-and-i@pep-project.org"
  2074                                userID:@"me-myself-and-i"
  2075                                userName:@"pEp Me"
  2076                                isOwn:YES];
  2077     NSError *error = nil;
  2078     XCTAssertTrue([session mySelf:identMe error:&error]);
  2079     XCTAssertNil(error);
  2080 
  2081     XCTAssertNotNil(identMe.fingerPrint);
  2082 
  2083     PEPMessage *msg = [PEPMessage new];
  2084     msg.from = identMe;
  2085     msg.to = @[identAlice];
  2086     msg.shortMessage = @"Mail to Alice";
  2087     msg.longMessage = @"Alice?";
  2088     msg.direction = PEPMsgDirectionOutgoing;
  2089 
  2090     NSNumber *numRating = [self testOutgoingRatingForMessage:msg session:session error:&error];
  2091     XCTAssertNotNil(numRating);
  2092     XCTAssertNil(error);
  2093     XCTAssertEqual(numRating.pEpRating, PEPRatingReliable);
  2094 
  2095     PEPMessage *encMsg;
  2096 
  2097     PEPStatus statusEnc = PEPStatusVersionMismatch;
  2098     if (toSelf) {
  2099         encMsg = [session
  2100                   encryptMessage:msg
  2101                   forSelf:identMe
  2102                   extraKeys:nil
  2103                   status:&statusEnc
  2104                   error:&error];
  2105         XCTAssertEqual(statusEnc, PEPStatusOK);
  2106     } else {
  2107         encMsg = [session encryptMessage:msg extraKeys:nil status:nil error:&error];
  2108         XCTAssertNotNil(encMsg);
  2109         XCTAssertNil(error);
  2110     }
  2111     XCTAssertNotNil(encMsg);
  2112 
  2113     PEPStringList *keys;
  2114     PEPRating pEpRating;
  2115     error = nil;
  2116     PEPMessage *decMsg = [session
  2117                           decryptMessage:encMsg
  2118                           flags:nil
  2119                           rating:&pEpRating
  2120                           extraKeys:&keys
  2121                           status:nil
  2122                           error:&error];
  2123     XCTAssertNil(error);
  2124     XCTAssertNotNil(decMsg);
  2125 
  2126     XCTAssertEqual(pEpRating, expectedRating);
  2127 
  2128     NSArray * encStatusField = nil;
  2129     for (NSArray *field in decMsg.optionalFields) {
  2130         NSString *header = [field[0] lowercaseString];
  2131         if ([header isEqualToString:@"x-encstatus"]) {
  2132             encStatusField = field;
  2133         }
  2134     }
  2135     XCTAssertNotNil(encStatusField);
  2136     if (encStatusField) {
  2137         PEPRating outgoingRating = [session ratingFromString:encStatusField[1]];
  2138         XCTAssertEqual(outgoingRating, expectedRating);
  2139     }
  2140 }
  2141 
  2142 @end