Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat!: allow firebase/php-jwt v6 #391

Merged
merged 20 commits into from
Apr 13, 2022
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
},
"require": {
"php": "^7.1||^8.0",
"firebase/php-jwt": "~5.0",
"firebase/php-jwt": "^5.5||^6.0",
"guzzlehttp/guzzle": "^6.2.1|^7.0",
"guzzlehttp/psr7": "^1.7|^2.0",
"psr/http-message": "^1.0",
Expand Down
73 changes: 56 additions & 17 deletions src/OAuth2.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
namespace Google\Auth;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Google\Auth\HttpHandler\HttpClientCache;
use Google\Auth\HttpHandler\HttpHandlerFactory;
use GuzzleHttp\Psr7\Query;
Expand Down Expand Up @@ -374,17 +375,18 @@ public function __construct(array $config)
* - otherwise returns the payload in the idtoken as a PHP object.
*
* The behavior of this method varies depending on the version of
* `firebase/php-jwt` you are using. In versions lower than 3.0.0, if
* `$publicKey` is null, the key is decoded without being verified. In
* newer versions, if a public key is not given, this method will throw an
* `\InvalidArgumentException`.
* `firebase/php-jwt` you are using. In versions 6.0 and above, you cannot
* provide multiple $allowed_algs, and instead must provide an array of Key
* objects as the $publicKey.
*
* @param string $publicKey The public key to use to authenticate the token
* @param array $allowed_algs List of supported verification algorithms
* @param string|Key|Key[] $publicKey The public key to use to authenticate the token
* @param string|array $allowed_algs algorithm or array of supported verification algorithms.
* Providing more than one algorithm will throw an exception.
* @throws \DomainException if the token is missing an audience.
* @throws \DomainException if the audience does not match the one set in
* the OAuth2 class instance.
* @throws \UnexpectedValueException If the token is invalid
* @throws \InvalidArgumentException If more than one value for allowed_algs is supplied
bshaffer marked this conversation as resolved.
Show resolved Hide resolved
* @throws SignatureInvalidException If the signature is invalid.
* @throws BeforeValidException If the token is not yet valid.
* @throws ExpiredException If the token has expired.
Expand Down Expand Up @@ -455,7 +457,7 @@ public function toJwt(array $config = [])
}
$assertion += $this->getAdditionalClaims();

return $this->jwtEncode(
return JWT::encode(
$assertion,
$this->getSigningKey(),
$this->getSigningAlgorithm(),
Expand Down Expand Up @@ -1376,23 +1378,60 @@ private function coerceUri($uri)

/**
* @param string $idToken
* @param string|array|null $publicKey
* @param array $allowedAlgs
* @param Key|Key[]|string|array|null $publicKey
bshaffer marked this conversation as resolved.
Show resolved Hide resolved
* @param string|array $allowedAlg
bshaffer marked this conversation as resolved.
Show resolved Hide resolved
* @return object
*/
private function jwtDecode($idToken, $publicKey, $allowedAlgs)
{
return JWT::decode($idToken, $publicKey, $allowedAlgs);
$keys = $this->getFirebaseJwtKeys($publicKey, $allowedAlgs);

// Default exception if none are caught
bshaffer marked this conversation as resolved.
Show resolved Hide resolved
$e = new \InvalidArgumentException('Key may not be empty');
bshaffer marked this conversation as resolved.
Show resolved Hide resolved
foreach ($keys as $key) {
try {
return JWT::decode($idToken, $key);
} catch (\Exception $e) {
// try next alg
}
}
throw $e;
}

private function jwtEncode($assertion, $signingKey, $signingAlgorithm, $signingKeyId = null)
/**
* @return Keys[]
bshaffer marked this conversation as resolved.
Show resolved Hide resolved
*/
private function getFirebaseJwtKeys($publicKey, $allowedAlgs)
{
return JWT::encode(
$assertion,
$signingKey,
$signingAlgorithm,
$signingKeyId
);
// If $allowedAlgs is empty, assume $publicKey is Key or Key[].
if (empty($allowedAlgs)) {
return (array) $publicKey;
}

if (is_string($allowedAlgs)) {
bshaffer marked this conversation as resolved.
Show resolved Hide resolved
$allowedAlg = $allowedAlg;
} elseif (is_array($allowedAlgs)) {
if (count($allowedAlgs) > 1) {
throw new \InvalidArgumentException(
'To have multiple allowed algorithms, You must provide an'
. ' array of Firebase\JWT\Key objects.'
. ' See https://github.com/firebase/php-jwt for more information.');
}
$allowedAlg = array_pop($allowedAlgs);
} else {
throw new \InvalidArgumentException('$allowedAlgs must be a string or array.');
}

if (is_array($publicKey)) {
// When publicKey is greater than 1, create keys with the single alg.
$keys = [];
foreach ($publicKey as $kid => $pubkey) {
$keys[$kid] = new Key($pubkey, $allowedAlg);
}
return $keys;
}

return [new Key($publicKey, $allowedAlg)];
}

/**
Expand Down
4 changes: 2 additions & 2 deletions tests/Credentials/ServiceAccountCredentialsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

use DomainException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Google\Auth\ApplicationDefaultCredentials;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Credentials\ServiceAccountJwtAccessCredentials;
Expand Down Expand Up @@ -799,8 +800,7 @@ public function testJwtAccessFromApplicationDefault()
$this->assertArrayHasKey('authorization', $metadata);
$token = str_replace('Bearer ', '', $metadata['authorization'][0]);
$key = file_get_contents(__DIR__ . '/../fixtures3/key.pub');

$result = JWT::decode($token, $key, ['RS256']);
$result = JWT::decode($token, new Key($key, 'RS256'));

$this->assertEquals($authUri, $result->aud);
}
Expand Down
33 changes: 17 additions & 16 deletions tests/OAuth2Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

use DomainException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Google\Auth\OAuth2;
use GuzzleHttp\Psr7\Query;
use GuzzleHttp\Psr7\Utils;
Expand Down Expand Up @@ -442,15 +443,15 @@ public function testFailsWithMissingSigningAlgorithm()
public function testCanHS256EncodeAValidPayloadWithSigningKeyId()
{
$testConfig = $this->signingMinimal;
$keys = array(
'example_key_id1' => 'example_key1',
'example_key_id2' => 'example_key2'
);
$testConfig['signingKey'] = $keys['example_key_id2'];
$keys = [
'example_key_id1' => new Key('example_key1', 'HS256'),
'example_key_id2' => new Key('example_key2', 'HS256'),
];
$testConfig['signingKey'] = $keys['example_key_id2']->getKeyMaterial();
$testConfig['signingKeyId'] = 'example_key_id2';
$o = new OAuth2($testConfig);
$payload = $o->toJwt();
$roundTrip = JWT::decode($payload, $keys, array('HS256'));
$roundTrip = JWT::decode($payload, $keys);
$this->assertEquals($roundTrip->iss, $testConfig['issuer']);
$this->assertEquals($roundTrip->aud, $testConfig['audience']);
$this->assertEquals($roundTrip->scope, $testConfig['scope']);
Expand All @@ -459,16 +460,16 @@ public function testCanHS256EncodeAValidPayloadWithSigningKeyId()
public function testFailDecodeWithoutSigningKeyId()
{
$testConfig = $this->signingMinimal;
$keys = array(
'example_key_id1' => 'example_key1',
'example_key_id2' => 'example_key2'
);
$testConfig['signingKey'] = $keys['example_key_id2'];
$keys = [
'example_key_id1' => new Key('example_key1', 'HS256'),
'example_key_id2' => new Key('example_key2', 'HS256'),
];
$testConfig['signingKey'] = $keys['example_key_id2']->getKeyMaterial();
$o = new OAuth2($testConfig);
$payload = $o->toJwt();

try {
JWT::decode($payload, $keys, array('HS256'));
JWT::decode($payload, $keys);
} catch (\Exception $e) {
// Workaround: In old JWT versions throws DomainException
$this->assertTrue(
Expand All @@ -485,7 +486,7 @@ public function testCanHS256EncodeAValidPayload()
$testConfig = $this->signingMinimal;
$o = new OAuth2($testConfig);
$payload = $o->toJwt();
$roundTrip = JWT::decode($payload, $testConfig['signingKey'], array('HS256'));
$roundTrip = JWT::decode($payload, new Key($testConfig['signingKey'], 'HS256'));
$this->assertEquals($roundTrip->iss, $testConfig['issuer']);
$this->assertEquals($roundTrip->aud, $testConfig['audience']);
$this->assertEquals($roundTrip->scope, $testConfig['scope']);
Expand All @@ -500,7 +501,7 @@ public function testCanRS256EncodeAValidPayload()
$o->setSigningAlgorithm('RS256');
$o->setSigningKey($privateKey);
$payload = $o->toJwt();
$roundTrip = JWT::decode($payload, $publicKey, array('RS256'));
$roundTrip = JWT::decode($payload, new Key($publicKey, 'RS256'));
$this->assertEquals($roundTrip->iss, $testConfig['issuer']);
$this->assertEquals($roundTrip->aud, $testConfig['audience']);
$this->assertEquals($roundTrip->scope, $testConfig['scope']);
Expand All @@ -517,7 +518,7 @@ public function testCanHaveAdditionalClaims()
$o->setSigningAlgorithm('RS256');
$o->setSigningKey($privateKey);
$payload = $o->toJwt();
$roundTrip = JWT::decode($payload, $publicKey, array('RS256'));
$roundTrip = JWT::decode($payload, new Key($publicKey, 'RS256'));
$this->assertEquals($roundTrip->target_audience, $targetAud);
}
}
Expand Down Expand Up @@ -907,7 +908,7 @@ public function testFailsIfIdTokenIsInvalid()
$not_a_jwt = 'not a jot';
$o = new OAuth2($testConfig);
$o->setIdToken($not_a_jwt);
$o->verifyIdToken($this->publicKey);
$o->verifyIdToken($this->publicKey, ['RS256']);
}

public function testFailsIfAudienceIsMissing()
Expand Down