|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace ChadicusTest\Psr\Http\ServerMiddleware\Hmac; |
|
4
|
|
|
|
|
5
|
|
|
use Chadicus\Psr\Http\ServerMiddleware\AuthenticationException; |
|
6
|
|
|
use Chadicus\Psr\Http\ServerMiddleware\Hmac\AuthorizationHeaderExtractor; |
|
7
|
|
|
use PHPUnit\Framework\TestCase; |
|
8
|
|
|
use Zend\Diactoros\ServerRequest; |
|
9
|
|
|
use Zend\Diactoros\Stream; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* @coversDefaultClass \Chadicus\Psr\Http\ServerMiddleware\Hmac\AuthorizationHeaderExtractor |
|
13
|
|
|
* @covers ::__construct |
|
14
|
|
|
*/ |
|
15
|
|
|
final class AuthorizationHeaderExtractorTest extends TestCase |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* @test |
|
19
|
|
|
* @covers ::extract |
|
20
|
|
|
* |
|
21
|
|
|
* @return void |
|
22
|
|
|
*/ |
|
23
|
|
|
public function extract() |
|
24
|
|
|
{ |
|
25
|
|
|
$json = json_encode(['foo' => 'bar', 'abc' => '123']); |
|
26
|
|
|
$stream = fopen('php://memory', 'r+'); |
|
27
|
|
|
fwrite($stream, $json); |
|
28
|
|
|
rewind($stream); |
|
29
|
|
|
|
|
30
|
|
|
$privateKey = md5(microtime(true)); |
|
31
|
|
|
$uri = 'https://example.com/foos'; |
|
32
|
|
|
$now = time(); |
|
33
|
|
|
$nonce = (string)rand(); |
|
34
|
|
|
$base64 = base64_encode($json); |
|
35
|
|
|
$data = "{$privateKey}POST{$uri}{$now}{$nonce}{$base64}"; |
|
36
|
|
|
$signature = hash('sha256', $data); |
|
37
|
|
|
$publicKey = md5(microtime()); |
|
38
|
|
|
|
|
39
|
|
|
$headers = ['Authorization' => "hmac {$publicKey}:{$signature}:{$nonce}:{$now}"]; |
|
40
|
|
|
|
|
41
|
|
|
$request = new ServerRequest([], [], $uri, 'POST', $stream, $headers); |
|
42
|
|
|
|
|
43
|
|
|
$extractor = new AuthorizationHeaderExtractor(); |
|
44
|
|
|
|
|
45
|
|
|
$token = $extractor->extract($request); |
|
46
|
|
|
|
|
47
|
|
|
$this->assertSame($publicKey, $token->getPublicKey()); |
|
48
|
|
|
$this->assertSame($signature, $token->getSignature()); |
|
49
|
|
|
$this->assertSame($nonce, $token->getNonce()); |
|
50
|
|
|
$this->assertSame($now, $token->getTimestamp()); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* @test |
|
55
|
|
|
* @covers ::extract |
|
56
|
|
|
* |
|
57
|
|
|
* @return void |
|
58
|
|
|
*/ |
|
59
|
|
|
public function extractInvalidHeader() |
|
60
|
|
|
{ |
|
61
|
|
|
$headers = ['Authorization' => 'This isnt:exactly:right']; |
|
62
|
|
|
$request = new ServerRequest([], [], 'http://localhost', 'POST', 'php://input', $headers); |
|
63
|
|
|
|
|
64
|
|
|
$extractor = new AuthorizationHeaderExtractor(); |
|
65
|
|
|
try { |
|
66
|
|
|
$extractor->extract($request); |
|
67
|
|
|
$this->fail('No exception thrown'); |
|
68
|
|
|
} catch (AuthenticationException $e) { |
|
69
|
|
|
$this->assertSame(400, $e->getStatusCode()); |
|
70
|
|
|
$this->assertSame('Bad Request', $e->getReasonPhrase()); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|