PageRenderTime 23ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/google/src/Google/Auth/ComputeEngine.php

https://gitlab.com/unofficial-mirrors/moodle
PHP | 146 lines | 81 code | 15 blank | 50 comment | 10 complexity | cb48a5d14cede8ca98088e58732972a6 MD5 | raw file
  1. <?php
  2. /*
  3. * Copyright 2014 Google Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. if (!class_exists('Google_Client')) {
  18. require_once dirname(__FILE__) . '/../autoload.php';
  19. }
  20. /**
  21. * Authentication via built-in Compute Engine service accounts.
  22. * The instance must be pre-configured with a service account
  23. * and the appropriate scopes.
  24. * @author Jonathan Parrott <jon.wayne.parrott@gmail.com>
  25. */
  26. class Google_Auth_ComputeEngine extends Google_Auth_Abstract
  27. {
  28. const METADATA_AUTH_URL =
  29. 'http://metadata/computeMetadata/v1/instance/service-accounts/default/token';
  30. private $client;
  31. private $token;
  32. public function __construct(Google_Client $client, $config = null)
  33. {
  34. $this->client = $client;
  35. }
  36. /**
  37. * Perform an authenticated / signed apiHttpRequest.
  38. * This function takes the apiHttpRequest, calls apiAuth->sign on it
  39. * (which can modify the request in what ever way fits the auth mechanism)
  40. * and then calls apiCurlIO::makeRequest on the signed request
  41. *
  42. * @param Google_Http_Request $request
  43. * @return Google_Http_Request The resulting HTTP response including the
  44. * responseHttpCode, responseHeaders and responseBody.
  45. */
  46. public function authenticatedRequest(Google_Http_Request $request)
  47. {
  48. $request = $this->sign($request);
  49. return $this->client->getIo()->makeRequest($request);
  50. }
  51. /**
  52. * @param string $token
  53. * @throws Google_Auth_Exception
  54. */
  55. public function setAccessToken($token)
  56. {
  57. $token = json_decode($token, true);
  58. if ($token == null) {
  59. throw new Google_Auth_Exception('Could not json decode the token');
  60. }
  61. if (! isset($token['access_token'])) {
  62. throw new Google_Auth_Exception("Invalid token format");
  63. }
  64. $token['created'] = time();
  65. $this->token = $token;
  66. }
  67. public function getAccessToken()
  68. {
  69. return json_encode($this->token);
  70. }
  71. /**
  72. * Acquires a new access token from the compute engine metadata server.
  73. * @throws Google_Auth_Exception
  74. */
  75. public function acquireAccessToken()
  76. {
  77. $request = new Google_Http_Request(
  78. self::METADATA_AUTH_URL,
  79. 'GET',
  80. array(
  81. 'Metadata-Flavor' => 'Google'
  82. )
  83. );
  84. $request->disableGzip();
  85. $response = $this->client->getIo()->makeRequest($request);
  86. if ($response->getResponseHttpCode() == 200) {
  87. $this->setAccessToken($response->getResponseBody());
  88. $this->token['created'] = time();
  89. return $this->getAccessToken();
  90. } else {
  91. throw new Google_Auth_Exception(
  92. sprintf(
  93. "Error fetching service account access token, message: '%s'",
  94. $response->getResponseBody()
  95. ),
  96. $response->getResponseHttpCode()
  97. );
  98. }
  99. }
  100. /**
  101. * Include an accessToken in a given apiHttpRequest.
  102. * @param Google_Http_Request $request
  103. * @return Google_Http_Request
  104. * @throws Google_Auth_Exception
  105. */
  106. public function sign(Google_Http_Request $request)
  107. {
  108. if ($this->isAccessTokenExpired()) {
  109. $this->acquireAccessToken();
  110. }
  111. $this->client->getLogger()->debug('Compute engine service account authentication');
  112. $request->setRequestHeaders(
  113. array('Authorization' => 'Bearer ' . $this->token['access_token'])
  114. );
  115. return $request;
  116. }
  117. /**
  118. * Returns if the access_token is expired.
  119. * @return bool Returns True if the access_token is expired.
  120. */
  121. public function isAccessTokenExpired()
  122. {
  123. if (!$this->token || !isset($this->token['created'])) {
  124. return true;
  125. }
  126. // If the token is set to expire in the next 30 seconds.
  127. $expired = ($this->token['created']
  128. + ($this->token['expires_in'] - 30)) < time();
  129. return $expired;
  130. }
  131. }