Skip to content

feat: add support for phpseclib/phpseclib v4 - #9747

Open
achretien wants to merge 3 commits into
googleapis:mainfrom
sagacorp:feat-phpseclib4-support
Open

achretien wants to merge 3 commits into
googleapis:mainfrom
sagacorp:feat-phpseclib4-support

Conversation

@achretien

Copy link
Copy Markdown

Summary

phpseclib 4.0 moved to the phpseclib4\ namespace. This PR lets the library work with either v3 or v4, in the same spirit as the existing v2/v3 fallback in Storage\EncryptionTrait.

Every call site that used phpseclib 3 now prefers v4 and falls back to v3 (and to v2 / OpenSSL where that chain already existed). Only one major can be installed at a time, so the class_exists() branch simply picks whichever is present. The v4 API surface used here (PublicKeyLoader::load(), RSA::createKey(), RSA::loadPrivateKey(), withPadding(), withHash(), sign(), verify(), BigInteger) is unchanged from v3.

Touched call sites:

  • Google\Cloud\Storage\EncryptionTrait::signString()
  • Google\Cloud\Core\Testing\KeyPairGenerateTrait::getKeyPair()
  • Google\Auth\ServiceAccountSignerTrait::signBlob()
  • Google\Auth\AccessToken::checkAndInitializePhpsec() / loadPhpsecPublicKey()
  • Firebase\JWT\JWT::signPS256() / verifyPS256()

require-dev constraints in the root, Auth, Jwt and Storage composer.json now allow ^4.0.1. The suggest entries still said "Please require version ^2", so they have been refreshed to ^3 or ^4, along with the matching notes in Jwt/README.md and the PubSub\Subscription docblock.

Drive-by bug fix

ServiceAccountSignerTrait guarded on class_exists(phpseclib3\Crypt\RSA::class). That is a relative name inside namespace Google\Auth, so it resolved to Google\Auth\phpseclib3\Crypt\RSA and was never true — signBlob() always fell through to OpenSSL, even with phpseclib installed. It now uses the imported aliases.

This is a behavior change (phpseclib is actually used when present), but the produced signature is byte-identical to the OpenSSL path; see the verification table below.

CI

  • New Unit Test + phpseclib 4 leg in the test matrix, which pins phpseclib/phpseclib:^4.0.1 before composer update. Other legs are untouched — the step is gated on a matrix key they do not define.
  • New Package Tests (phpseclib 4) job, scoped to Auth Jwt Storage so it costs a fraction of a full package-test run.
  • run-package-tests.sh gains an optional PHPSECLIB env var. When set, components that declare phpseclib/phpseclib in require-dev get that constraint pinned in their composer-local.json before Composer resolves. When unset the script behaves exactly as before.

Verification

Each affected path was exercised against both majors installed side by side, comparing output to the OpenSSL path:

phpseclib 3 phpseclib 4
JWT::encode/decode PS256 roundtrip pass pass
EncryptionTrait::signString vs OpenSSL identical identical
ServiceAccountSignerTrait::signBlob vs OpenSSL identical identical
AccessToken::loadPhpsecPublicKey vs OpenSSL public key identical identical

The package-test script changes were dry-run with a stubbed Composer to confirm the pin is applied to Auth, Jwt and Storage only, that components without the dependency are skipped, that the committed composer.json files are left untouched, and that an unset PHPSECLIB is a no-op.

Note

phpseclib 4 requires PHP >= 8.1. Jwt/composer.json still allows PHP ^8.0, where Composer will simply resolve to v3 — no conflict.

phpseclib 4 moved to the `phpseclib4\` namespace. Every call site that used
phpseclib 3 now prefers v4 and falls back to v3 (and to v2 / OpenSSL where
that chain already existed), so either major works.

- Storage\EncryptionTrait::signString
- Core\Testing\KeyPairGenerateTrait::getKeyPair
- Auth\ServiceAccountSignerTrait::signBlob
- Auth\AccessToken::checkAndInitializePhpsec / loadPhpsecPublicKey
- Firebase\JWT\JWT::signPS256 / verifyPS256

Widen the require-dev constraints to allow ^4.0.1 and refresh the suggest
texts, which still pointed at version ^2.

Also fix the phpseclib guard in ServiceAccountSignerTrait: the check used a
relative class name, which resolved to `Google\Auth\phpseclib3\Crypt\RSA` and
was therefore never true, so signBlob() always fell through to OpenSSL. The
signature output is unchanged.

CI gains a "Unit Test + phpseclib 4" matrix leg and a "Package Tests
(phpseclib 4)" job, both pinning phpseclib to ^4.0.1 before Composer resolves.
@achretien
achretien requested review from a team as code owners September 30, 2026 09:31
@google-cla

google-cla Bot commented Sep 30, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@achretien

Copy link
Copy Markdown
Author

CLA as been signed

@bshaffer bshaffer left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hello! First of all, THANK YOU for this submission! It's great.

However, I think we should revert all the changes made in .github. If we support both PHPSecLib 3 and PHPSecLib 4, and our dependencies can resolve them, then there's no need for additional logic to test them. You could add a unit test to confirm that phpseclib4 is installed when --prefer-lowest ISNT used, if you like (or just confirm locally once), but what we have here seems overkill

Comment thread .github/workflows/unit-tests.yaml Resolved
Comment thread .github/workflows/unit-tests.yaml Resolved
Comment thread .github/run-package-tests.sh Resolved
@bshaffer

bshaffer commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

We are getting the following PHPStan errors because of the two separate versions. We may need to mark some classes/methods as ignore or surround them in class_exists/method_exists:

Error: Class phpseclib3\Crypt\PublicKeyLoader not found.
Error: Class phpseclib3\Math\BigInteger not found.
Error: Instantiated class phpseclib3\Math\BigInteger not found.
Error: Instantiated class phpseclib3\Math\BigInteger not found.
Error: Call to an undefined method phpseclib4\Crypt\Common\AsymmetricKey::withPadding().
Error: Call to static method load() on an unknown class phpseclib3\Crypt\PublicKeyLoader.
Error: Call to an undefined method phpseclib4\Crypt\Common\AsymmetricKey::withPadding().
Error: Call to static method load() on an unknown class phpseclib3\Crypt\PublicKeyLoader.

@bshaffer

bshaffer commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

In CI, composer update installs phpseclib/phpseclib v4 (phpseclib3 is not installed), and Auth / Jwt run PHPStan at level: 7. Using the same dynamic namespace resolution pattern you used in Jwt/src/JWT.php (widened to string so PHPStan doesn't treat it as a literal union and report class.notFound on the uninstalled major version) will fix the PHPStan errors cleanly across all three files:

  1. Auth/src/AccessToken.php:
    Remove the PublicKeyLoader* and BigInteger* imports and resolve the classes dynamically:
    private function loadPhpsecPublicKey(string $modulus, string $exponent): string
    {
        /** @var string $phpseclib */
        $phpseclib = class_exists(RSA4::class) ? 'phpseclib4' : 'phpseclib3';
        $publicKeyLoader = $phpseclib . '\\Crypt\\PublicKeyLoader';
        $bigInteger = $phpseclib . '\\Math\\BigInteger';

        $key = $publicKeyLoader::load([
            'n' => new $bigInteger($this->callJwtStatic('urlsafeB64Decode', [
                $modulus,
            ]), 256),
            'e' => new $bigInteger($this->callJwtStatic('urlsafeB64Decode', [
                $exponent
            ]), 256),
        ]);
  1. Auth/src/ServiceAccountSignerTrait.php:
    Remove the PublicKeyLoader* imports and combine the RSA4 / RSA3 branches:
        $signedString = '';
        /** @var string|null $phpseclib */
        $phpseclib = match (true) {
            class_exists(RSA4::class) => 'phpseclib4',
            class_exists(RSA3::class) => 'phpseclib3',
            default => null,
        };
        if ($phpseclib && !$forceOpenssl) {
            $publicKeyLoader = $phpseclib . '\\Crypt\\PublicKeyLoader';
            $rsaClass = $phpseclib . '\\Crypt\\RSA';
            $key = $publicKeyLoader::load($privateKey);
            $rsa = $key->withHash('sha256')->withPadding($rsaClass::SIGNATURE_PKCS1);

            $signedString = $rsa->sign($stringToSign);
        } elseif (extension_loaded('openssl')) {
  1. Jwt/src/JWT.php:
    Remove the two leftover @var \phpseclib3\... annotations on lines 791 and 830, which will otherwise fail Jwt PHPStan once Auth passes:
-        /** @var \phpseclib3\Crypt\RSA\PrivateKey $rsa */
         $rsa = $publicKeyLoader::load($key);
-        /** @var \phpseclib3\Crypt\RSA\PublicKey $rsa */
         $rsa = $publicKeyLoader::load($key);

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants