/
ArtisanRequest.php
198 lines (170 loc) · 5.18 KB
/
ArtisanRequest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
<?php
namespace Firevel\Artisan\Http\Requests;
use Exception;
use Firebase\JWT\JWK;
use Firebase\JWT\JWT;
use Illuminate\Foundation\Http\FormRequest;
use Google\Auth\AccessToken;
class ArtisanRequest extends FormRequest
{
const GOOGLE_OAUTH_CERTS = 'https://www.googleapis.com/oauth2/v3/certs';
/**
* AppEngine IPs.
*
* Ref.: https://cloud.google.com/appengine/docs/flexible/nodejs/scheduling-jobs-with-cron-yaml#validating_cron_requests
*
* @var array
*/
protected $appengineCronIPs = [
'0.1.0.2',
'0.1.0.1', // older gcloud versions (earlier than 326.0.0)
];
/**
* List of Google Cloud permissions required to execute task.
*
* Only one permission is required so its "or" list.
*
* @var array
*/
protected $requiredPermissions = [
'cloudscheduler.jobs.run',
'appengine.runtimes.actAsAdmin',
];
/**
* AppEngine cron header.
*
* Ref.: https://cloud.google.com/appengine/docs/flexible/nodejs/scheduling-jobs-with-cron-yaml#validating_cron_requests
*
* @var string
*/
protected $appEngineCronHeader = 'x-appengine-cron';
/**
* Project resource manager endpoint.
*
* @var string
*/
protected $resourceManagerEndpoint = 'https://cloudresourcemanager.googleapis.com/v3/projects/';
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
// Check if service is running inside AppEngine
if (! empty($_SERVER['GAE_SERVICE'])) {
// Check called from App Engine cron.
if (
$this->hasHeader($this->appEngineCronHeader) &&
in_array($this->header('x-appengine-user-ip'), $this->appengineCronIPs)
) {
return true;
}
// Check if call was initiated by cloud scheduler.
if (
$this->hasHeader('x-cloudscheduler') &&
$this->hasHeader('x-google-internal-skipadmincheck')
) {
return true;
}
}
$token = $this->getToken();
if (empty($token)) {
return false;
}
// Check if token is JWT.
if ($this->isValidJwt($token)) {
return $this->verifyJwtToken($token);
}
// If not AppEngine Cron or Cloud Scheduler - proceed with Access Token Verification
return $this->verifyAccessToken($this->getToken());
}
/**
* Veritfy if JWT token is authorized.
*
* @param string $token
* @return bool
*/
public function verifyJwtToken($token)
{
// Fetch Google's public keys
$publicKeysJson = file_get_contents(self::GOOGLE_OAUTH_CERTS);
$publicKeys = JWK::parseKeySet(json_decode($publicKeysJson, true));
// Verify the ID token
try {
$decodedToken = JWT::decode($token, $publicKeys, ['RS256']);
$email = $decodedToken->email;
if (empty($email)) {
return false;
}
return in_array($email, config('artisan.authorized_service_accounts', []));
} catch (Exception $e) {
return false;
}
}
/**
* Is string a valid Jwt.
*
* @param string $jwtString
* @return boolean
*/
public function isValidJwt($jwtString) {
$jwtParts = explode('.', $jwtString);
if (count($jwtParts) !== 3) {
return false;
}
try {
$header = JWT::urlsafeB64Decode($jwtParts[0]);
$payload = JWT::urlsafeB64Decode($jwtParts[1]);
$headerDecoded = json_decode($header);
$payloadDecoded = json_decode($payload);
return $headerDecoded !== null && $payloadDecoded !== null;
} catch (Exception $e) {
return false;
}
}
/**
* Verify if Google Access Token generated with "gcloud auth print-access-token" got permissions to execute call.
*
* @return bool
*/
public function verifyAccessToken($token)
{
$client = new \GuzzleHttp\Client();
$response = $client->request(
'POST',
$this->resourceManagerEndpoint . env('GOOGLE_CLOUD_PROJECT') . ':testIamPermissions',
[
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token,
],
'json' => (object) ["permissions" => $this->requiredPermissions],
]
);
return ! empty(json_decode($response->getBody(), true));
}
/**
* Get identity token.
*
* @return string
*/
public function getToken()
{
if (config('artisan.authorization_header') == 'Authorization' && ! empty($this->bearerToken())) {
return $this->bearerToken();
}
return $this->header(config('artisan.authorization_header'));
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//
];
}
}