1 | <?php
|
---|
2 |
|
---|
3 | /*
|
---|
4 | * Copyright 2022 Google Inc.
|
---|
5 | *
|
---|
6 | * Licensed under the Apache License, Version 2.0 (the "License");
|
---|
7 | * you may not use this file except in compliance with the License.
|
---|
8 | * You may obtain a copy of the License at
|
---|
9 | *
|
---|
10 | * http://www.apache.org/licenses/LICENSE-2.0
|
---|
11 | *
|
---|
12 | * Unless required by applicable law or agreed to in writing, software
|
---|
13 | * distributed under the License is distributed on an "AS IS" BASIS,
|
---|
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
---|
15 | * See the License for the specific language governing permissions and
|
---|
16 | * limitations under the License.
|
---|
17 | */
|
---|
18 |
|
---|
19 | namespace Google\Auth;
|
---|
20 |
|
---|
21 | use Exception;
|
---|
22 | use Google\Auth\HttpHandler\HttpClientCache;
|
---|
23 | use Google\Auth\HttpHandler\HttpHandlerFactory;
|
---|
24 |
|
---|
25 | trait IamSignerTrait
|
---|
26 | {
|
---|
27 | /**
|
---|
28 | * @var Iam|null
|
---|
29 | */
|
---|
30 | private $iam;
|
---|
31 |
|
---|
32 | /**
|
---|
33 | * Sign a string using the default service account private key.
|
---|
34 | *
|
---|
35 | * This implementation uses IAM's signBlob API.
|
---|
36 | *
|
---|
37 | * @see https://cloud.google.com/iam/credentials/reference/rest/v1/projects.serviceAccounts/signBlob SignBlob
|
---|
38 | *
|
---|
39 | * @param string $stringToSign The string to sign.
|
---|
40 | * @param bool $forceOpenSsl [optional] Does not apply to this credentials
|
---|
41 | * type.
|
---|
42 | * @param string $accessToken The access token to use to sign the blob. If
|
---|
43 | * provided, saves a call to the metadata server for a new access
|
---|
44 | * token. **Defaults to** `null`.
|
---|
45 | * @return string
|
---|
46 | * @throws Exception
|
---|
47 | */
|
---|
48 | public function signBlob($stringToSign, $forceOpenSsl = false, $accessToken = null)
|
---|
49 | {
|
---|
50 | $httpHandler = HttpHandlerFactory::build(HttpClientCache::getHttpClient());
|
---|
51 |
|
---|
52 | // Providing a signer is useful for testing, but it's undocumented
|
---|
53 | // because it's not something a user would generally need to do.
|
---|
54 | $signer = $this->iam;
|
---|
55 | if (!$signer) {
|
---|
56 | $signer = $this instanceof GetUniverseDomainInterface
|
---|
57 | ? new Iam($httpHandler, $this->getUniverseDomain())
|
---|
58 | : new Iam($httpHandler);
|
---|
59 | }
|
---|
60 |
|
---|
61 | $email = $this->getClientName($httpHandler);
|
---|
62 |
|
---|
63 | if (is_null($accessToken)) {
|
---|
64 | $previousToken = $this->getLastReceivedToken();
|
---|
65 | $accessToken = $previousToken
|
---|
66 | ? $previousToken['access_token']
|
---|
67 | : $this->fetchAuthToken($httpHandler)['access_token'];
|
---|
68 | }
|
---|
69 |
|
---|
70 | return $signer->signBlob($email, $accessToken, $stringToSign);
|
---|
71 | }
|
---|
72 | }
|
---|