aboutsummaryrefslogtreecommitdiffhomepage
path: root/Example/Messaging/Tests/FIRMessagingSecureSocketTest.m
blob: b86592c4e765812dc00013a4ee8796d9743d6df7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/*
 * Copyright 2017 Google
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#import <XCTest/XCTest.h>

#import <OCMock/OCMock.h>

#import "Protos/GtalkCore.pbobjc.h"

#import "FIRMessagingConnection.h"
#import "FIRMessagingFakeSocket.h"
#import "FIRMessagingSecureSocket.h"
#import "FIRMessagingUtilities.h"

@interface FIRMessagingConnection ()

+ (GtalkLoginRequest *)loginRequestWithToken:(NSString *)token authID:(NSString *)authID;

@end

@interface FIRMessagingSecureSocket() <NSStreamDelegate>

@property(nonatomic, readwrite, assign) FIRMessagingSecureSocketState state;
@property(nonatomic, readwrite, strong) NSInputStream *inStream;
@property(nonatomic, readwrite, strong) NSOutputStream *outStream;

@property(nonatomic, readwrite, assign) BOOL isVersionSent;
@property(nonatomic, readwrite, assign) BOOL isVersionReceived;
@property(nonatomic, readwrite, assign) BOOL isInStreamOpen;
@property(nonatomic, readwrite, assign) BOOL isOutStreamOpen;

@property(nonatomic, readwrite, strong) NSRunLoop *runLoop;

- (BOOL)performRead;

@end

typedef void(^FIRMessagingTestSocketDisconnectHandler)(void);
typedef void(^FIRMessagingTestSocketConnectHandler)(void);

@interface FIRMessagingSecureSocketTest : XCTestCase <FIRMessagingSecureSocketDelegate>

@property(nonatomic, readwrite, strong) FIRMessagingFakeSocket *socket;
@property(nonatomic, readwrite, strong) id mockSocket;
@property(nonatomic, readwrite, strong) NSError *protoParseError;
@property(nonatomic, readwrite, strong) GPBMessage *protoReceived;
@property(nonatomic, readwrite, assign) int8_t protoTagReceived;

@property(nonatomic, readwrite, copy) FIRMessagingTestSocketDisconnectHandler disconnectHandler;
@property(nonatomic, readwrite, copy) FIRMessagingTestSocketConnectHandler connectHandler;

@end

static BOOL isSafeToDisconnectSocket = NO;

@implementation FIRMessagingSecureSocketTest

- (void)setUp {
  [super setUp];
  isSafeToDisconnectSocket = NO;
  self.protoParseError = nil;
  self.protoReceived = nil;
  self.protoTagReceived = 0;
}

- (void)tearDown {
  self.disconnectHandler = nil;
  self.connectHandler = nil;
  isSafeToDisconnectSocket = YES;
  [self.socket disconnect];
  [super tearDown];
}

#pragma mark - Test Reading

- (void)testSendingVersion {
  // read as soon as 1 byte is written
  [self createAndConnectSocketWithBufferSize:1];
  uint8_t versionByte = 40;
  [self.socket.outStream write:&versionByte maxLength:1];

  [[[self.mockSocket stub] andDo:^(NSInvocation *invocation) {
      XCTAssertTrue(isSafeToDisconnectSocket,
                    @"Should not disconnect socket now");
  }] disconnect];
  XCTestExpectation *shouldAcceptVersionExpectation =
      [self expectationWithDescription:@"Socket should accept version"];
  dispatch_time_t delay =
      dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC));
  dispatch_after(delay, dispatch_get_main_queue(), ^{
      XCTAssertTrue(self.socket.isVersionReceived);
      [shouldAcceptVersionExpectation fulfill];
  });

  [self waitForExpectationsWithTimeout:3.0
                               handler:^(NSError *error) {
                                   XCTAssertNil(error);
                               }];
}

- (void)testReceivingDataMessage {
  [self createAndConnectSocketWithBufferSize:61];
  [self writeVersionToOutStream];
  GtalkDataMessageStanza *message = [[GtalkDataMessageStanza alloc] init];
  [message setCategory:@"socket-test-category"];
  [message setFrom:@"socket-test-from"];
  FIRMessagingSetLastStreamId(message, 2);
  FIRMessagingSetRmq2Id(message, @"socket-test-rmq");

  XCTestExpectation *dataExpectation = [self
      expectationWithDescription:@"FIRMessaging socket should receive data message"];
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)),
                 dispatch_get_main_queue(), ^{
      [self.socket sendData:[message data]
                    withTag:kFIRMessagingProtoTagDataMessageStanza
                      rmqId:FIRMessagingGetRmq2Id(message)];
  });

  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)),
                 dispatch_get_main_queue(), ^{
      XCTAssertEqual(self.protoTagReceived, kFIRMessagingProtoTagDataMessageStanza);
      [dataExpectation fulfill];
  });

  [self waitForExpectationsWithTimeout:5.0
                               handler:^(NSError *error) {
                                   XCTAssertNil(error);
                               }];
}

#pragma mark - Writing

- (void)testLoginRequest {
  [self createAndConnectSocketWithBufferSize:99];

  XCTestExpectation *loginExpectation =
      [self expectationWithDescription:@"Socket send valid login proto"];
  [self writeVersionToOutStream];
  GtalkLoginRequest *loginRequest =
      [FIRMessagingConnection loginRequestWithToken:@"gcmtoken" authID:@"gcmauthid"];
  FIRMessagingSetLastStreamId(loginRequest, 1);

  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)),
                 dispatch_get_main_queue(), ^{
      [self.socket sendData:[loginRequest data]
                    withTag:FIRMessagingGetTagForProto(loginRequest)
                      rmqId:FIRMessagingGetRmq2Id(loginRequest)];
  });

  dispatch_time_t delay =
      dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC));
  dispatch_after(delay, dispatch_get_main_queue(), ^{
      XCTAssertTrue(self.socket.isVersionReceived);
      XCTAssertEqual(self.protoTagReceived, kFIRMessagingProtoTagLoginRequest);
      [loginExpectation fulfill];
  });

  [self waitForExpectationsWithTimeout:6.0
                               handler:^(NSError *error) {
                                   XCTAssertNil(error);
                               }];
}

- (void)testSendingImproperData {
  [self createAndConnectSocketWithBufferSize:124];
  [self writeVersionToOutStream];

  NSString *randomString = @"some random data string";
  NSData *randomData = [randomString dataUsingEncoding:NSUTF8StringEncoding];

  XCTestExpectation *parseErrorExpectation =
      [self expectationWithDescription:@"Sending improper data results in a parse error"];

  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)),
                 dispatch_get_main_queue(), ^{
                   [self.socket sendData:randomData withTag:3 rmqId:@"some-random-rmq-id"];
                 });

  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)),
                 dispatch_get_main_queue(), ^{
                   if (self.protoParseError != nil) {
                     [parseErrorExpectation fulfill];
                   }
                 });

  [self waitForExpectationsWithTimeout:3.0 handler:nil];
}

- (void)testSendingDataWithImproperTag {
  [self createAndConnectSocketWithBufferSize:124];
  [self writeVersionToOutStream];
  const char dataString[] = { 0x02, 0x02, 0x11, 0x11, 0x11, 0x11 }; // tag 10, random data
  NSData *randomData = [NSData dataWithBytes:dataString length:6];

  // Create an expectation for a method which should not be invoked during this test.
  // This is required to allow us to wait for the socket stream to be read and
  // processed by FIRMessagingSecureSocket
  OCMExpect([self.mockSocket disconnect]);

  NSTimeInterval sendDelay = 2.0;
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(sendDelay * NSEC_PER_SEC)),
                 dispatch_get_main_queue(), ^{
                   [self.socket sendData:randomData withTag:10 rmqId:@"some-random-rmq-id"];
                 });

  @try {
    // While waiting to verify this call, an exception should be thrown
    // trying to parse the random data in our delegate.
    // Wait slightly longer than the sendDelay, to allow for the parsing
    OCMVerifyAllWithDelay(self.mockSocket, sendDelay+0.25);
    XCTFail(@"Invalid data being read should have thrown an exception.");
  }
  @catch (NSException *exception) {
    XCTAssertNotNil(exception);
  }
  @finally { }
}

- (void)testDisconnect {
  [self createAndConnectSocketWithBufferSize:1];
  [self writeVersionToOutStream];
  // version read and written let's disconnect
  XCTestExpectation *disconnectExpectation =
      [self expectationWithDescription:@"socket should disconnect properly"];
  self.disconnectHandler = ^{
      [disconnectExpectation fulfill];
  };

  [self.socket disconnect];

  [self waitForExpectationsWithTimeout:5.0
                               handler:^(NSError *error) {
                                   XCTAssertNil(error);
                               }];

  XCTAssertNil(self.socket.inStream);
  XCTAssertNil(self.socket.outStream);
  XCTAssertEqual(self.socket.state, kFIRMessagingSecureSocketClosed);
}

- (void)testSocketOpening {
  XCTestExpectation *openSocketExpectation =
      [self expectationWithDescription:@"Socket should open properly"];
  self.connectHandler = ^{
      [openSocketExpectation fulfill];
  };
  [self createAndConnectSocketWithBufferSize:1];
  [self writeVersionToOutStream];

  [self waitForExpectationsWithTimeout:10.0
                               handler:^(NSError *error) {
                                   XCTAssertNil(error);
                               }];

  XCTAssertTrue(self.socket.isInStreamOpen);
  XCTAssertTrue(self.socket.isOutStreamOpen);
}

#pragma mark - FIRMessagingSecureSocketDelegate protocol

- (void)secureSocket:(FIRMessagingSecureSocket *)socket
      didReceiveData:(NSData *)data
             withTag:(int8_t)tag {
  NSError *error;
  GPBMessage *proto =
      [FIRMessagingGetClassForTag((FIRMessagingProtoTag)tag) parseFromData:data
                                                                     error:&error];
  self.protoParseError = error;
  self.protoReceived = proto;
  self.protoTagReceived = tag;
}

- (void)secureSocket:(FIRMessagingSecureSocket *)socket
 didSendProtoWithTag:(int8_t)tag
               rmqId:(NSString *)rmqId {
  // do nothing
}

- (void)secureSocketDidConnect:(FIRMessagingSecureSocket *)socket {
  if (self.connectHandler) {
    self.connectHandler();
  }
}

- (void)didDisconnectWithSecureSocket:(FIRMessagingSecureSocket *)socket {
  if (self.disconnectHandler) {
    self.disconnectHandler();
  }
}

#pragma mark - Private Helpers

- (void)createAndConnectSocketWithBufferSize:(uint8_t)bufferSize {
  self.socket = [[FIRMessagingFakeSocket alloc] initWithBufferSize:bufferSize];
  self.mockSocket = OCMPartialMock(self.socket);
  self.socket.delegate = self;

  [self.socket connectToHost:@"localhost"
                        port:6234
                   onRunLoop:[NSRunLoop mainRunLoop]];
}

- (void)writeVersionToOutStream {
  uint8_t versionByte = 40;
  [self.socket.outStream write:&versionByte maxLength:1];
  // don't resend the version
  self.socket.isVersionSent = YES;
}

@end