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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
|
<?php
/**
* SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-only
*/
namespace Tests\Core\Data;
use Exception;
use OC\Authentication\Exceptions\InvalidTokenException;
use OC\Authentication\Token\IProvider;
use OC\Authentication\Token\IToken;
use OC\Core\Data\LoginFlowV2Credentials;
use OC\Core\Data\LoginFlowV2Tokens;
use OC\Core\Db\LoginFlowV2;
use OC\Core\Db\LoginFlowV2Mapper;
use OC\Core\Exception\LoginFlowV2ClientForbiddenException;
use OC\Core\Exception\LoginFlowV2NotFoundException;
use OC\Core\Service\LoginFlowV2Service;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IConfig;
use OCP\Security\ICrypto;
use OCP\Security\ISecureRandom;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
use Test\TestCase;
/**
* Unit tests for \OC\Core\Service\LoginFlowV2Service
*/
class LoginFlowV2ServiceUnitTest extends TestCase {
/** @var IConfig */
private $config;
/** @var ICrypto */
private $crypto;
/** @var LoggerInterface|MockObject */
private $logger;
/** @var LoginFlowV2Mapper */
private $mapper;
/** @var ISecureRandom */
private $secureRandom;
/** @var LoginFlowV2Service */
private $subjectUnderTest;
/** @var ITimeFactory */
private $timeFactory;
/** @var \OC\Authentication\Token\IProvider */
private $tokenProvider;
public function setUp(): void {
parent::setUp();
$this->setupSubjectUnderTest();
}
/**
* Setup subject under test with mocked constructor arguments.
*
* Code was moved to separate function to keep setUp function small and clear.
*/
private function setupSubjectUnderTest(): void {
$this->config = $this->createMock(IConfig::class);
$this->crypto = $this->createMock(ICrypto::class);
$this->mapper = $this->createMock(LoginFlowV2Mapper::class);
$this->logger = $this->createMock(LoggerInterface::class);
$this->tokenProvider = $this->createMock(IProvider::class);
$this->secureRandom = $this->createMock(ISecureRandom::class);
$this->timeFactory = $this->createMock(ITimeFactory::class);
$this->subjectUnderTest = new LoginFlowV2Service(
$this->mapper,
$this->secureRandom,
$this->timeFactory,
$this->config,
$this->crypto,
$this->logger,
$this->tokenProvider
);
}
/**
* Generates for a given password required OpenSSL parts.
*
* @return array Array contains encrypted password, private key and public key.
*/
private function getOpenSSLEncryptedPublicAndPrivateKey(string $appPassword): array {
// Create the private and public key
$res = openssl_pkey_new([
'digest_alg' => 'md5', // take fast algorithm for testing purposes
'private_key_bits' => 512,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
]);
// Extract the private key from $res
openssl_pkey_export($res, $privateKey);
// Extract the public key from $res
$publicKey = openssl_pkey_get_details($res);
$publicKey = $publicKey['key'];
// Encrypt the data to $encrypted using the public key
openssl_public_encrypt($appPassword, $encrypted, $publicKey, OPENSSL_PKCS1_OAEP_PADDING);
return [$encrypted, $privateKey, $publicKey];
}
/*
* Tests for poll
*/
public function testPollPrivateKeyCouldNotBeDecrypted(): void {
$this->expectException(LoginFlowV2NotFoundException::class);
$this->expectExceptionMessage('Apptoken could not be decrypted');
$this->crypto->expects($this->once())
->method('decrypt')
->willThrowException(new \Exception('HMAC mismatch'));
/*
* Cannot be mocked, because functions like getLoginName are magic functions.
* To be able to set internal properties, we have to use the real class here.
*/
$loginFlowV2 = new LoginFlowV2();
$loginFlowV2->setLoginName('test');
$loginFlowV2->setServer('test');
$loginFlowV2->setAppPassword('test');
$loginFlowV2->setPrivateKey('test');
$this->mapper->expects($this->once())
->method('getByPollToken')
->willReturn($loginFlowV2);
$this->subjectUnderTest->poll('');
}
public function testPollApptokenCouldNotBeDecrypted(): void {
$this->expectException(LoginFlowV2NotFoundException::class);
$this->expectExceptionMessage('Apptoken could not be decrypted');
/*
* Cannot be mocked, because functions like getLoginName are magic functions.
* To be able to set internal properties, we have to use the real class here.
*/
[$encrypted, $privateKey,] = $this->getOpenSSLEncryptedPublicAndPrivateKey('test');
$loginFlowV2 = new LoginFlowV2();
$loginFlowV2->setLoginName('test');
$loginFlowV2->setServer('test');
$loginFlowV2->setAppPassword('broken#' . $encrypted);
$loginFlowV2->setPrivateKey('encrypted(test)');
$this->crypto->expects($this->once())
->method('decrypt')
->willReturn($privateKey);
$this->mapper->expects($this->once())
->method('getByPollToken')
->willReturn($loginFlowV2);
$this->subjectUnderTest->poll('test');
}
public function testPollInvalidToken(): void {
$this->expectException(LoginFlowV2NotFoundException::class);
$this->expectExceptionMessage('Invalid token');
$this->mapper->expects($this->once())
->method('getByPollToken')
->willThrowException(new DoesNotExistException(''));
$this->subjectUnderTest->poll('');
}
public function testPollTokenNotYetReady(): void {
$this->expectException(LoginFlowV2NotFoundException::class);
$this->expectExceptionMessage('Token not yet ready');
$this->subjectUnderTest->poll('');
}
public function testPollRemoveDataFromDb(): void {
[$encrypted, $privateKey] = $this->getOpenSSLEncryptedPublicAndPrivateKey('test_pass');
$this->crypto->expects($this->once())
->method('decrypt')
->willReturn($privateKey);
/*
* Cannot be mocked, because functions like getLoginName are magic functions.
* To be able to set internal properties, we have to use the real class here.
*/
$loginFlowV2 = new LoginFlowV2();
$loginFlowV2->setLoginName('test_login');
$loginFlowV2->setServer('test_server');
$loginFlowV2->setAppPassword(base64_encode($encrypted));
$loginFlowV2->setPrivateKey($privateKey);
$this->mapper->expects($this->once())
->method('delete')
->with($this->equalTo($loginFlowV2));
$this->mapper->expects($this->once())
->method('getByPollToken')
->willReturn($loginFlowV2);
$credentials = $this->subjectUnderTest->poll('');
$this->assertTrue($credentials instanceof LoginFlowV2Credentials);
$this->assertEquals(
[
'server' => 'test_server',
'loginName' => 'test_login',
'appPassword' => 'test_pass',
],
$credentials->jsonSerialize()
);
}
/*
* Tests for getByLoginToken
*/
public function testGetByLoginToken(): void {
$loginFlowV2 = new LoginFlowV2();
$loginFlowV2->setLoginName('test_login');
$loginFlowV2->setServer('test_server');
$loginFlowV2->setAppPassword('test');
$this->mapper->expects($this->once())
->method('getByLoginToken')
->willReturn($loginFlowV2);
$result = $this->subjectUnderTest->getByLoginToken('test_token');
$this->assertTrue($result instanceof LoginFlowV2);
$this->assertEquals('test_server', $result->getServer());
$this->assertEquals('test_login', $result->getLoginName());
$this->assertEquals('test', $result->getAppPassword());
}
public function testGetByLoginTokenLoginTokenInvalid(): void {
$this->expectException(LoginFlowV2NotFoundException::class);
$this->expectExceptionMessage('Login token invalid');
$this->mapper->expects($this->once())
->method('getByLoginToken')
->willThrowException(new DoesNotExistException(''));
$this->subjectUnderTest->getByLoginToken('test_token');
}
public function testGetByLoginTokenClientForbidden() {
$this->expectException(LoginFlowV2ClientForbiddenException::class);
$this->expectExceptionMessage('Client not allowed');
$allowedClients = [
'/Custom Allowed Client/i'
];
$this->config->expects($this->exactly(1))
->method('getSystemValue')
->willReturn($this->returnCallback(function ($key) use ($allowedClients) {
// Note: \OCP\IConfig::getSystemValue returns either an array or string.
return $key == 'core.login_flow_v2.allowed_user_agents' ? $allowedClients : '';
}));
$loginFlowV2 = new LoginFlowV2();
$loginFlowV2->setClientName('Rogue Curl Client/1.0');
$this->mapper->expects($this->once())
->method('getByLoginToken')
->willReturn($loginFlowV2);
$this->subjectUnderTest->getByLoginToken('test_token');
}
public function testGetByLoginTokenClientAllowed() {
$allowedClients = [
'/Foo Allowed Client/i',
'/Custom Allowed Client/i'
];
$loginFlowV2 = new LoginFlowV2();
$loginFlowV2->setClientName('Custom Allowed Client Curl Client/1.0');
$this->config->expects($this->exactly(1))
->method('getSystemValue')
->willReturn($this->returnCallback(function ($key) use ($allowedClients) {
// Note: \OCP\IConfig::getSystemValue returns either an array or string.
return $key == 'core.login_flow_v2.allowed_user_agents' ? $allowedClients : '';
}));
$this->mapper->expects($this->once())
->method('getByLoginToken')
->willReturn($loginFlowV2);
$result = $this->subjectUnderTest->getByLoginToken('test_token');
$this->assertTrue($result instanceof LoginFlowV2);
$this->assertEquals('Custom Allowed Client Curl Client/1.0', $result->getClientName());
}
/*
* Tests for startLoginFlow
*/
public function testStartLoginFlow(): void {
$loginFlowV2 = new LoginFlowV2();
$this->mapper->expects($this->once())
->method('getByLoginToken')
->willReturn($loginFlowV2);
$this->mapper->expects($this->once())
->method('update');
$this->assertTrue($this->subjectUnderTest->startLoginFlow('test_token'));
}
public function testStartLoginFlowDoesNotExistException(): void {
$this->mapper->expects($this->once())
->method('getByLoginToken')
->willThrowException(new DoesNotExistException(''));
$this->assertFalse($this->subjectUnderTest->startLoginFlow('test_token'));
}
/**
* If an exception not of type DoesNotExistException is thrown,
* it is expected that it is not being handled by startLoginFlow.
*/
public function testStartLoginFlowException(): void {
$this->expectException(Exception::class);
$this->mapper->expects($this->once())
->method('getByLoginToken')
->willThrowException(new Exception(''));
$this->subjectUnderTest->startLoginFlow('test_token');
}
/*
* Tests for flowDone
*/
public function testFlowDone(): void {
[,, $publicKey] = $this->getOpenSSLEncryptedPublicAndPrivateKey('test_pass');
$loginFlowV2 = new LoginFlowV2();
$loginFlowV2->setPublicKey($publicKey);
$loginFlowV2->setClientName('client_name');
$this->mapper->expects($this->once())
->method('getByLoginToken')
->willReturn($loginFlowV2);
$this->mapper->expects($this->once())
->method('update');
$this->secureRandom->expects($this->once())
->method('generate')
->with(72, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS)
->willReturn('test_pass');
// session token
$sessionToken = $this->getMockBuilder(IToken::class)->disableOriginalConstructor()->getMock();
$sessionToken->expects($this->once())
->method('getLoginName')
->willReturn('login_name');
$this->tokenProvider->expects($this->once())
->method('getPassword')
->willReturn('test_pass');
$this->tokenProvider->expects($this->once())
->method('getToken')
->willReturn($sessionToken);
$this->tokenProvider->expects($this->once())
->method('generateToken')
->with(
'test_pass',
'user_id',
'login_name',
'test_pass',
'client_name',
IToken::PERMANENT_TOKEN,
IToken::DO_NOT_REMEMBER
);
$result = $this->subjectUnderTest->flowDone(
'login_token',
'session_id',
'server',
'user_id'
);
$this->assertTrue($result);
// app password is encrypted and must look like:
// ZACZOOzxTpKz4+KXL5kZ/gCK0xvkaVi/8yzupAn6Ui6+5qCSKvfPKGgeDRKs0sivvSLzk/XSp811SZCZmH0Y3g==
$this->assertMatchesRegularExpression('/[a-zA-Z\/0-9+=]+/', $loginFlowV2->getAppPassword());
$this->assertEquals('server', $loginFlowV2->getServer());
}
public function testFlowDoneDoesNotExistException(): void {
$this->mapper->expects($this->once())
->method('getByLoginToken')
->willThrowException(new DoesNotExistException(''));
$result = $this->subjectUnderTest->flowDone(
'login_token',
'session_id',
'server',
'user_id'
);
$this->assertFalse($result);
}
public function testFlowDonePasswordlessTokenException(): void {
$this->tokenProvider->expects($this->once())
->method('getToken')
->willThrowException(new InvalidTokenException(''));
$result = $this->subjectUnderTest->flowDone(
'login_token',
'session_id',
'server',
'user_id'
);
$this->assertFalse($result);
}
/*
* Tests for createTokens
*/
public function testCreateTokens(): void {
$this->config->expects($this->exactly(2))
->method('getSystemValue')
->willReturn($this->returnCallback(function ($key) {
// Note: \OCP\IConfig::getSystemValue returns either an array or string.
return $key == 'openssl' ? [] : '';
}));
$this->mapper->expects($this->once())
->method('insert');
$this->secureRandom->expects($this->exactly(2))
->method('generate');
$token = $this->subjectUnderTest->createTokens('user_agent');
$this->assertTrue($token instanceof LoginFlowV2Tokens);
}
}
|