Merge pull request #8 from rubensayshi/guzzle-v6

Guzzle6 (using PSR7)
This commit is contained in:
Adrian Palmer 2016-10-17 09:27:32 +11:00 committed by GitHub
commit 33d3488ce2
10 changed files with 229 additions and 207 deletions

View File

@ -1,9 +1,8 @@
language: php language: php
php: php:
- 5.6
- 5.5 - 5.5
- 5.4 - 5.6
- 7.0 - 7.0
- 7.1 - 7.1
- hhvm - hhvm
@ -13,19 +12,6 @@ install: composer require --no-update guzzlehttp/guzzle $GUZZLE_VERSION; compose
script: vendor/bin/phpunit script: vendor/bin/phpunit
env: env:
- GUZZLE_VERSION: 4.2 - GUZZLE_VERSION: 6.0
- GUZZLE_VERSION: 5.0 - GUZZLE_VERSION: 6.2
- GUZZLE_VERSION: 5.2 - GUZZLE_VERSION: 6.*
- GUZZLE_VERSION: 5.3
- GUZZLE_VERSION: 5.3.1
matrix:
exclude:
- php: 7.1
env: GUZZLE_VERSION=4.2
- php: 7.1
env: GUZZLE_VERSION=5.0
- php: 7.1
env: GUZZLE_VERSION=5.2
- php: 7.1
env: GUZZLE_VERSION=5.3

View File

@ -1,38 +1,78 @@
HTTP Signatures Guzzle 4 HTTP Signatures Guzzle 6
======================== ========================
Guzzle 4 support for 99designs http-signatures library Guzzle 6 support for 99designs http-signatures library
[![Build Status](https://travis-ci.org/99designs/http-signatures-guzzlehttp.svg)](https://travis-ci.org/99designs/http-signatures-guzzlehttp) [![Build Status](https://travis-ci.org/99designs/http-signatures-guzzlehttp.svg)](https://travis-ci.org/99designs/http-signatures-guzzlehttp)
Adds [99designs/http-signatures][99signatures] support to Guzzle 4. Adds [99designs/http-signatures][99signatures] support to Guzzle 6.
Older Guzzle Versions
---------------------
For Guzzle 4 & 5 use the `v1.x` release of this repo.
For Guzzle 3 see the [99designs/http-signatures-guzzle][99signatures-guzzle] repo. For Guzzle 3 see the [99designs/http-signatures-guzzle][99signatures-guzzle] repo.
Signing with Guzzle 4
Signing with Guzzle 6
--------------------- ---------------------
This library includes support for automatically signing Guzzle requests using an event subscriber. This library includes support for automatically signing Guzzle requests using Middleware.
You can use `GuzzleHttpSignatures::defaultHandlerFromContext` to easily create the default Guzzle handler with the
middleware added to sign every request.
```php ```php
use GuzzleHttp\Client;
use HttpSignatures\Context; use HttpSignatures\Context;
use HttpSignatures\GuzzleHttp\RequestSubscriber; use HttpSignatures\GuzzleHttpSignatures;
$context = new Context(array( require __DIR__ . "/../vendor/autoload.php";
'keys' => array('examplekey' => 'secret-key-here'),
'algorithm' => 'hmac-sha256',
'headers' => array('(request-target)', 'Date', 'Accept'),
));
$client = new \Guzzle\Http\Client('http://example.org'); $context = new Context([
$client->getEmitter()->attach(new RequestSubscriber($context)); 'keys' => ['examplekey' => 'secret-key-here'],
'algorithm' => 'hmac-sha256',
'headers' => ['(request-target)', 'date'],
]);
$handlerStack = GuzzleHttpSignatures::defaultHandlerFromContext($context);
$client = new Client(['handler' => $handlerStack]);
// The below will now send a signed request to: http://example.org/path?query=123 // The below will now send a signed request to: http://example.org/path?query=123
$client->get('/path?query=123', array( $response = $client->get("http://www.example.com/path?query=123", ['headers' => ['date' => 'today']]);
'Date' => 'Wed, 30 Jul 2014 16:40:19 -0700',
'Accept' => 'llamas',
));
``` ```
Or if you're creating a custom `HandlerStack` you can add the Middleware yourself:
```php
<?php
use GuzzleHttp\Client;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use HttpSignatures\Context;
use HttpSignatures\GuzzleHttpSignatures;
require __DIR__ . "/../vendor/autoload.php";
$context = new Context([
'keys' => ['examplekey' => 'secret-key-here'],
'algorithm' => 'hmac-sha256',
'headers' => ['(request-target)', 'date'],
]);
$handlerStack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(GuzzleHttpSignatures::middlewareFromContext($this->context));
$stack->push(Middleware::history($this->history));
$client = new Client(['handler' => $handlerStack]);
// The below will now send a signed request to: http://example.org/path?query=123
$response = $client->get("http://www.example.com/path?query=123", ['headers' => ['date' => 'today']]);
```
## Contributing ## Contributing
Pull Requests are welcome. Pull Requests are welcome.

View File

@ -1,8 +1,8 @@
{ {
"name": "99designs/http-signatures-guzzlehttp", "name": "99designs/http-signatures-guzzlehttp",
"description": "Sign and verify HTTP messages with Guzzle 4", "description": "Sign and verify HTTP messages with Guzzle 6",
"homepage": "https://github.com/99designs/http-signatures-guzzlehttp", "homepage": "https://github.com/99designs/http-signatures-guzzlehttp",
"keywords": ["http", "https", "signing", "signed", "signature", "hmac", "guzzle 4"], "keywords": ["http", "https", "signing", "signed", "signature", "hmac", "guzzle 6"],
"license": "MIT", "license": "MIT",
"authors": [ "authors": [
{ {
@ -11,7 +11,7 @@
}, },
{ {
"name": "Ruben de Vries", "name": "Ruben de Vries",
"email": "ruben@blocktrail.com" "email": "ruben@rubensayshi.com"
} }
], ],
"autoload": { "autoload": {
@ -20,9 +20,9 @@
} }
}, },
"require": { "require": {
"php": ">=5.4.0", "php": ">=5.5.0",
"99designs/http-signatures": ">=1.1.0 <3.0.0", "99designs/http-signatures": ">=3.0.0 <4.0.0",
"guzzlehttp/guzzle": ">=4.2.0 <=5.3.1" "guzzlehttp/guzzle": ">=6.0 <7.0.0"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "~4.1" "phpunit/phpunit": "~4.1"

View File

@ -0,0 +1,19 @@
<?php
use GuzzleHttp\Client;
use HttpSignatures\Context;
use HttpSignatures\GuzzleHttpSignatures;
require __DIR__ . "/../vendor/autoload.php";
$context = new Context([
'keys' => ['examplekey' => 'secret-key-here'],
'algorithm' => 'hmac-sha256',
'headers' => ['(request-target)', 'date'],
]);
$handlerStack = GuzzleHttpSignatures::defaultHandlerFromContext($context);
$client = new Client(['handler' => $handlerStack]);
// The below will now send a signed request to: http://example.org/path?query=123
$response = $client->get("http://www.example.com/path?query=123", ['headers' => ['date' => 'today']]);

View File

@ -0,0 +1,25 @@
<?php
use GuzzleHttp\Client;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use HttpSignatures\Context;
use HttpSignatures\GuzzleHttpSignatures;
require __DIR__ . "/../vendor/autoload.php";
$context = new Context([
'keys' => ['examplekey' => 'secret-key-here'],
'algorithm' => 'hmac-sha256',
'headers' => ['(request-target)', 'date'],
]);
$handlerStack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(GuzzleHttpSignatures::middlewareFromContext($this->context));
$stack->push(Middleware::history($this->history));
$client = new Client(['handler' => $handlerStack]);
// The below will now send a signed request to: http://example.org/path?query=123
$response = $client->get("http://www.example.com/path?query=123", ['headers' => ['date' => 'today']]);

View File

@ -1,47 +0,0 @@
<?php
namespace HttpSignatures\GuzzleHttp;
use GuzzleHttp\Message\RequestInterface;
/**
* Class RequestMessage
*
* wrapper around the Guzzle Request instance to have a consistent API for the HttpSignatures classes to consume
*
* @package HttpSignatures\Guzzle
*/
class Message
{
/**
* @var RequestInterface
*/
private $request;
/**
* @var MessageHeaders
*/
public $headers;
public function __construct(RequestInterface $request)
{
$this->request = $request;
$this->headers = new MessageHeaders($request);
}
public function getQueryString()
{
$qs = $this->request->getQuery();
return $qs->count() ? $qs : null;
}
public function getMethod()
{
return $this->request->getMethod();
}
public function getPathInfo()
{
return $this->request->getPath();
}
}

View File

@ -1,40 +0,0 @@
<?php
namespace HttpSignatures\GuzzleHttp;
use GuzzleHttp\Message\MessageInterface;
/**
* Class MessageHeaders
*
* wrapper around the Guzzle Request instance to have a consistent API for the HttpSignatures classes to consume
*
* @package HttpSignatures\Guzzle
*/
class MessageHeaders
{
/**
* @var MessageInterface
*/
private $request;
public function __construct(MessageInterface $request)
{
$this->request = $request;
}
public function has($header)
{
return $this->request->hasHeader($header);
}
public function get($header)
{
return $this->request->getHeader($header);
}
public function set($header, $value)
{
$this->request->setHeader($header, $value);
}
}

View File

@ -1,32 +0,0 @@
<?php
namespace HttpSignatures\GuzzleHttp;
use GuzzleHttp\Event\BeforeEvent;
use GuzzleHttp\Event\RequestEvents;
use GuzzleHttp\Event\SubscriberInterface;
use HttpSignatures\Context;
class RequestSubscriber implements SubscriberInterface
{
/**
* @var \HttpSignatures\Context
*/
private $context;
public function __construct(Context $context)
{
$this->context = $context;
}
public function getEvents()
{
return ['before' => ['onBefore', RequestEvents::SIGN_REQUEST]];
}
public function onBefore(BeforeEvent $event)
{
$request = $event->getRequest();
$this->context->signer()->sign(new Message($request));
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace HttpSignatures;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Request;
class GuzzleHttpSignatures
{
/**
* @param Context $context
* @return HandlerStack
*/
public static function defaultHandlerFromContext(Context $context)
{
$stack = HandlerStack::create();
$stack->push(self::middlewareFromContext($context));
return $stack;
}
/**
* @param Context $context
* @return \Closure
*/
public static function middlewareFromContext(Context $context)
{
return function (callable $handler) use ($context)
{
return function (
Request $request,
array $options
) use ($handler, $context)
{
$request = $context->signer()->sign($request);
return $handler($request, $options);
};
};
}
}

View File

@ -3,12 +3,14 @@
namespace HttpSignatures\Test; namespace HttpSignatures\Test;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Message\Response; use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Subscriber\History; use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\Subscriber\Mock; use GuzzleHttp\HandlerStack;
use HttpSignatures\GuzzleHttp\Message; use GuzzleHttp\Middleware;
use HttpSignatures\GuzzleHttp\RequestSubscriber; use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use HttpSignatures\Context; use HttpSignatures\Context;
use HttpSignatures\GuzzleHttpSignatures;
class GuzzleHttpSignerTest extends \PHPUnit_Framework_TestCase class GuzzleHttpSignerTest extends \PHPUnit_Framework_TestCase
{ {
@ -22,26 +24,26 @@ class GuzzleHttpSignerTest extends \PHPUnit_Framework_TestCase
*/ */
private $client; private $client;
/**
* @var
*/
private $history = [];
public function setUp() public function setUp()
{ {
$this->context = new Context(array( $this->context = new Context([
'keys' => array('pda' => 'secret'), 'keys' => ['pda' => 'secret'],
'algorithm' => 'hmac-sha256', 'algorithm' => 'hmac-sha256',
'headers' => array('(request-target)', 'date'), 'headers' => ['(request-target)', 'date'],
));
$this->client = new Client();
$mock = new Mock([
new Response(200)
]); ]);
$this->client->getEmitter()->attach($mock); $stack = new HandlerStack();
$stack->setHandler(new MockHandler([
$this->history = new History(); new Response(200, ['Content-Length' => 0]),
$this->client->getEmitter()->attach($this->history); ]));
$stack->push(GuzzleHttpSignatures::middlewareFromContext($this->context));
$this->client->getEmitter()->attach(new RequestSubscriber($this->context)); $stack->push(Middleware::history($this->history));
$this->client = new Client(['handler' => $stack]);
} }
/** /**
@ -49,29 +51,35 @@ class GuzzleHttpSignerTest extends \PHPUnit_Framework_TestCase
*/ */
public function testGuzzleRequestHasExpectedHeaders() public function testGuzzleRequestHasExpectedHeaders()
{ {
$this->client->get('/path?query=123', array( $this->client->get('/path?query=123', [
'headers' => array('date' => 'today', 'accept' => 'llamas') 'headers' => ['date' => 'today', 'accept' => 'llamas']
)); ]);
$message = $this->history->getLastRequest();
// get last request
$message = end($this->history);
/** @var Request $request */
$request = $message['request'];
/** @var Response $response */
$response = $message['request'];
$expectedString = implode( $expectedString = implode(
',', ',',
array( [
'keyId="pda"', 'keyId="pda"',
'algorithm="hmac-sha256"', 'algorithm="hmac-sha256"',
'headers="(request-target) date"', 'headers="(request-target) date"',
'signature="SFlytCGpsqb/9qYaKCQklGDvwgmrwfIERFnwt+yqPJw="', 'signature="SFlytCGpsqb/9qYaKCQklGDvwgmrwfIERFnwt+yqPJw="',
) ]
); );
$this->assertEquals( $this->assertEquals(
$expectedString, [$expectedString],
(string) $message->getHeader('Signature') $request->getHeader('Signature')
); );
$this->assertEquals( $this->assertEquals(
'Signature ' . $expectedString, ['Signature ' . $expectedString],
(string) $message->getHeader('Authorization') $request->getHeader('Authorization')
); );
} }
@ -80,39 +88,62 @@ class GuzzleHttpSignerTest extends \PHPUnit_Framework_TestCase
*/ */
public function testGuzzleRequestHasExpectedHeaders2() public function testGuzzleRequestHasExpectedHeaders2()
{ {
$this->client->get('/path', array( $this->client->get('/path', [
'headers' => array('date' => 'today', 'accept' => 'llamas') 'headers' => ['date' => 'today', 'accept' => 'llamas']
)); ]);
$message = $this->history->getLastRequest();
// get last request
$message = end($this->history);
/** @var Request $request */
$request = $message['request'];
/** @var Response $response */
$response = $message['request'];
$expectedString = implode( $expectedString = implode(
',', ',',
array( [
'keyId="pda"', 'keyId="pda"',
'algorithm="hmac-sha256"', 'algorithm="hmac-sha256"',
'headers="(request-target) date"', 'headers="(request-target) date"',
'signature="DAtF133khP05pS5Gh8f+zF/UF7mVUojMj7iJZO3Xk4o="', 'signature="DAtF133khP05pS5Gh8f+zF/UF7mVUojMj7iJZO3Xk4o="',
) ]
); );
$this->assertEquals( $this->assertEquals(
$expectedString, [$expectedString],
(string) $message->getHeader('Signature') $request->getHeader('Signature')
); );
$this->assertEquals( $this->assertEquals(
'Signature ' . $expectedString, ['Signature ' . $expectedString],
(string) $message->getHeader('Authorization') $request->getHeader('Authorization')
); );
} }
public function testVerifyGuzzleRequest() public function getVerifyGuzzleRequestVectors() {
{ return [
$this->client->get('/path?query=123', array( /* path, headers */
'headers' => array('date' => 'today', 'accept' => 'llamas') ['/path?query=123', ['date' => 'today', 'accept' => 'llamas']],
)); ['/path?z=zebra&a=antelope', ['date' => 'today']],
$message = $this->history->getLastRequest(); ];
}
$this->assertTrue($this->context->verifier()->isValid(new Message($message))); /**
* @dataProvider getVerifyGuzzleRequestVectors
* @param string $path
* @param array $headers
*/
public function testVerifyGuzzleRequest($path, $headers)
{
$this->client->get($path, ['headers' => $headers]);
// get last request
$message = end($this->history);
/** @var Request $request */
$request = $message['request'];
/** @var Response $response */
$response = $message['request'];
$this->assertTrue($this->context->verifier()->isValid($request));
} }
} }