Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
6 changes: 3 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,14 @@
"require-dev": {
"guzzlehttp/promises": "^2.0",
"squizlabs/php_codesniffer": "^4.0",
"phpunit/phpunit": "^9.6",
"phpunit/phpunit": "^9.6.34",
"phpspec/prophecy-phpunit": "^2.1",
"sebastian/comparator": ">=1.2.3",
"phpseclib/phpseclib": "^3.0.35",
"kelvinmo/simplejwt": "^1.1.0",
"webmozart/assert": "^1.11||^2.0",
"symfony/process": "^6.0||^7.0",
"symfony/filesystem": "^6.3||^7.3"
"symfony/process": "^6.4.41||^7.0",
"symfony/filesystem": "^6.4.39||^7.3"
},
"suggest": {
"phpseclib/phpseclib": "May be used in place of OpenSSL for signing strings or for token management. Please require version ^2."
Expand Down
136 changes: 136 additions & 0 deletions src/CredentialSource/X509Source.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
<?php
/**
* Copyright 2026 Google Inc.
*
* 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.
*/
namespace Google\Auth\CredentialSource;

use Google\Auth\ExternalAccountCredentialSourceInterface;
use InvalidArgumentException;
use RuntimeException;

/**
* A credential source for x509 client certificates.
*
* This class implements a non-standard mTLS flow where the client certificate
* and chain are sent in a custom-formatted `subject_token` in the request body,
* in addition to being used for the mTLS handshake at the transport layer.
*
* @internal
*/
class X509Source implements ExternalAccountCredentialSourceInterface
{
private const BEGIN_CERT = '-----BEGIN CERTIFICATE-----';
private const END_CERT = '-----END CERTIFICATE-----';

private string $keyPath;
private string $certPath;

public function __construct(
string $certificateConfigLocation,
private string|null $trustChainPath,
) {
if (!file_exists($certificateConfigLocation)) {
throw new InvalidArgumentException('Certificate config file does not exist');
}
$config = json_decode((string) file_get_contents($certificateConfigLocation), true);
if (!isset($config['cert_configs']['workload']['key_path'])
|| !isset($config['cert_configs']['workload']['cert_path'])
) {
throw new InvalidArgumentException('Certificate config is invalid');
}

$this->keyPath = $config['cert_configs']['workload']['key_path'];
$this->certPath = $config['cert_configs']['workload']['cert_path'];

if (!file_exists($this->certPath)) {
throw new InvalidArgumentException('cert_path file does not exist: ' . $this->certPath);
}
if (!file_exists($this->keyPath)) {
throw new InvalidArgumentException('key_path file does not exist: ' . $this->keyPath);
}
if ($this->trustChainPath && !file_exists($this->trustChainPath)) {
throw new InvalidArgumentException('Trust chain path is invalid');
}
}

/**
* Implements the custom subject token generation from the user's script.
*
* The subject token is a JSON array containing the base64-encoded DER
* representation of the leaf and intermediate certs.
*/
public function fetchSubjectToken(?callable $httpHandler = null): string
{
$certsB64Der = [];

$leafCert = file_get_contents($this->certPath);
if ($leafCert === false) {
throw new InvalidArgumentException('Unable to read leaf certificate file.');
}
$certsB64Der[] = $this->pemToDerB64($leafCert);

if ($this->trustChainPath && file_exists($this->trustChainPath)) {
$intermediates = file_get_contents($this->trustChainPath);
if ($intermediates === false) {
throw new InvalidArgumentException('Unable to read intermediate certificate file.');
}
// The regex captures the full PEM blocks
preg_match_all(
'/' . self::BEGIN_CERT . '[\s\S]+?' . self::END_CERT . '/',
$intermediates,
$matches
);

foreach ($matches[0] as $pem) {
$certsB64Der[] = $this->pemToDerB64($pem);
}
}

$jsonCertArray = json_encode($certsB64Der);
if ($jsonCertArray === false) {
throw new RuntimeException('Failed to encode certificate array to JSON.');
}
return $jsonCertArray;
}

public function getCacheKey(): ?string
{
return null;
}

public function getCertPath(): string
{
return $this->certPath;
}

public function getKeyPath(): string
{
return $this->keyPath;
}

private function pemToDerB64(string $pem): string
{
$pattern = '/' . self::BEGIN_CERT . '\s*(.*?)\s*' . self::END_CERT . '/s';
if (preg_match($pattern, $pem, $matches)) {
$base64 = str_replace(["\n", "\r"], '', $matches[1]);
$der = base64_decode($base64);
if ($der === false) {
throw new RuntimeException('Failed to base64-decode the certificate content.');
}
return base64_encode($der);
}
throw new RuntimeException('Failed to parse PEM certificate.');
}
}
13 changes: 13 additions & 0 deletions src/Credentials/ExternalAccountCredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use Google\Auth\CredentialSource\ExecutableSource;
use Google\Auth\CredentialSource\FileSource;
use Google\Auth\CredentialSource\UrlSource;
use Google\Auth\CredentialSource\X509Source;
use Google\Auth\ExecutableHandler\ExecutableHandler;
use Google\Auth\ExternalAccountCredentialSourceInterface;
use Google\Auth\FetchAuthTokenInterface;
Expand Down Expand Up @@ -217,6 +218,18 @@ private static function buildCredentialSource(array $jsonKey): ExternalAccountCr
);
}

if (isset($credentialSource['certificate'])) {
if (!array_key_exists('certificate_config_location', $credentialSource['certificate'])) {
throw new InvalidArgumentException(
'x509 source requires a certificate_config_location to be set in the JSON file.'
);
}
return new X509Source(
$credentialSource['certificate']['certificate_config_location'],
$credentialSource['certificate']['trust_chain_path'] ?? null,
);
}

throw new InvalidArgumentException('Unable to determine credential source from json key.');
}

Expand Down
28 changes: 25 additions & 3 deletions src/OAuth2.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Google\Auth\CredentialSource\X509Source;
use Google\Auth\HttpHandler\HttpClientCache;
use Google\Auth\HttpHandler\HttpHandlerFactory;
use GuzzleHttp\Psr7\Query;
Expand All @@ -42,7 +43,8 @@ class OAuth2 implements FetchAuthTokenInterface
const DEFAULT_SKEW_SECONDS = 60; // 1 minute
const JWT_URN = 'urn:ietf:params:oauth:grant-type:jwt-bearer';
const STS_URN = 'urn:ietf:params:oauth:grant-type:token-exchange';
private const STS_REQUESTED_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';
private const TOKEN_TYPE_ACCESS_TOKEN = 'urn:ietf:params:oauth:token-type:access_token';
private const TOKEN_TYPE_MTLS = 'urn:ietf:params:oauth:token-type:mtls';

/**
* TODO: determine known methods from the keys of JWT::methods.
Expand Down Expand Up @@ -627,7 +629,7 @@ public function generateCredentialsRequest(?callable $httpHandler = null, array
'resource' => $this->resource,
'audience' => $this->audience,
'scope' => $this->getScope(),
'requested_token_type' => self::STS_REQUESTED_TOKEN_TYPE,
'requested_token_type' => self::TOKEN_TYPE_ACCESS_TOKEN,
'actor_token' => $this->actorToken,
'actor_token_type' => $this->actorTokenType,
]);
Expand Down Expand Up @@ -661,6 +663,23 @@ public function generateCredentialsRequest(?callable $httpHandler = null, array
);
}

/**
* @return array{cert?: string, ssl_key?: string}
*/
private function generateCredentialsRequestOptions(): array
{
if ($this->subjectTokenType === self::TOKEN_TYPE_MTLS
&& $this->subjectTokenFetcher instanceof X509Source
) {
return [
'cert' => $this->subjectTokenFetcher->getCertPath(),
'ssl_key' => $this->subjectTokenFetcher->getKeyPath(),
];
}

return [];
}

/**
* Fetches the auth tokens based on the current state.
*
Expand All @@ -675,7 +694,10 @@ public function fetchAuthToken(?callable $httpHandler = null, array $headers = [
$httpHandler = HttpHandlerFactory::build(HttpClientCache::getHttpClient());
}

$response = $httpHandler($this->generateCredentialsRequest($httpHandler, $headers));
$response = $httpHandler(
$this->generateCredentialsRequest($httpHandler, $headers),
$this->generateCredentialsRequestOptions()
);
$credentials = $this->parseTokenResponse($response);
$this->updateToken($credentials);
if (isset($credentials['scope'])) {
Expand Down
Loading
Loading