-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathAuthOauth2.cc
454 lines (379 loc) · 15.8 KB
/
AuthOauth2.cc
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
#include "AuthOauth2.h"
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <sstream>
#include <stdexcept>
#include "InitialAuthData.h"
#include "lib/Base64Utils.h"
#include "lib/CurlWrapper.h"
#include "lib/LogUtils.h"
DECLARE_LOG_OBJECT()
namespace pulsar {
// AuthDataOauth2
AuthDataOauth2::AuthDataOauth2(const std::string& accessToken) { accessToken_ = accessToken; }
AuthDataOauth2::~AuthDataOauth2() {}
bool AuthDataOauth2::hasDataForHttp() { return true; }
std::string AuthDataOauth2::getHttpHeaders() { return "Authorization: Bearer " + accessToken_; }
bool AuthDataOauth2::hasDataFromCommand() { return true; }
std::string AuthDataOauth2::getCommandData() { return accessToken_; }
// Oauth2TokenResult
Oauth2TokenResult::Oauth2TokenResult() { expiresIn_ = undefined_expiration; }
Oauth2TokenResult::~Oauth2TokenResult() {}
Oauth2TokenResult& Oauth2TokenResult::setAccessToken(const std::string& accessToken) {
accessToken_ = accessToken;
return *this;
}
Oauth2TokenResult& Oauth2TokenResult::setIdToken(const std::string& idToken) {
idToken_ = idToken;
return *this;
}
Oauth2TokenResult& Oauth2TokenResult::setRefreshToken(const std::string& refreshToken) {
refreshToken_ = refreshToken;
return *this;
}
Oauth2TokenResult& Oauth2TokenResult::setExpiresIn(const int64_t expiresIn) {
expiresIn_ = expiresIn;
return *this;
}
const std::string& Oauth2TokenResult::getAccessToken() const { return accessToken_; }
const std::string& Oauth2TokenResult::getIdToken() const { return idToken_; }
const std::string& Oauth2TokenResult::getRefreshToken() const { return refreshToken_; }
int64_t Oauth2TokenResult::getExpiresIn() const { return expiresIn_; }
// CachedToken
CachedToken::CachedToken() {}
CachedToken::~CachedToken() {}
// Oauth2CachedToken
Oauth2CachedToken::Oauth2CachedToken(Oauth2TokenResultPtr token) {
latest_ = token;
int64_t expiredIn = token->getExpiresIn();
if (expiredIn > 0) {
expiresAt_ = Clock::now() + std::chrono::seconds(expiredIn);
} else {
throw std::runtime_error("ExpiresIn in Oauth2TokenResult invalid value: " +
std::to_string(expiredIn));
}
authData_ = AuthenticationDataPtr(new AuthDataOauth2(token->getAccessToken()));
}
AuthenticationDataPtr Oauth2CachedToken::getAuthData() { return authData_; }
Oauth2CachedToken::~Oauth2CachedToken() {}
bool Oauth2CachedToken::isExpired() { return expiresAt_ < Clock::now(); }
// OauthFlow
Oauth2Flow::Oauth2Flow() {}
Oauth2Flow::~Oauth2Flow() {}
KeyFile KeyFile::fromParamMap(ParamMap& params) {
const auto it = params.find("private_key");
if (it == params.cend()) {
return {params["client_id"], params["client_secret"]};
}
const std::string& url = it->second;
size_t startPos = 0;
auto getPrefix = [&url, &startPos](char separator) -> std::string {
const size_t endPos = url.find(separator, startPos);
if (endPos == std::string::npos) {
return "";
}
const auto prefix = url.substr(startPos, endPos - startPos);
startPos = endPos + 1;
return prefix;
};
const auto protocol = getPrefix(':');
// If the private key is not a URL, treat it as the file path
if (protocol.empty()) {
return fromFile(it->second);
}
if (protocol == "file") {
// URL is "file://..." or "file:..."
if (url.size() > startPos + 2 && url[startPos + 1] == '/' && url[startPos + 2] == '/') {
return fromFile(url.substr(startPos + 2));
} else {
return fromFile(url.substr(startPos));
}
} else if (protocol == "data") {
// Only support base64 encoded data from a JSON string. The URL should be:
// "data:application/json;base64,..."
const auto contentType = getPrefix(';');
if (contentType != "application/json") {
LOG_ERROR("Unsupported content type: " << contentType);
return {};
}
const auto encodingType = getPrefix(',');
if (encodingType != "base64") {
LOG_ERROR("Unsupported encoding type: " << encodingType);
return {};
}
return fromBase64(url.substr(startPos));
} else {
LOG_ERROR("Unsupported protocol: " << protocol);
return {};
}
}
// read clientId/clientSecret from passed in `credentialsFilePath`
KeyFile KeyFile::fromFile(const std::string& credentialsFilePath) {
boost::property_tree::ptree loadPtreeRoot;
try {
boost::property_tree::read_json(credentialsFilePath, loadPtreeRoot);
} catch (const boost::property_tree::json_parser_error& e) {
LOG_ERROR("Failed to parse json input file for credentialsFilePath: " << credentialsFilePath << ": "
<< e.what());
return {};
}
try {
return {loadPtreeRoot.get<std::string>("client_id"), loadPtreeRoot.get<std::string>("client_secret")};
} catch (const boost::property_tree::ptree_error& e) {
LOG_ERROR("Failed to get client_id or client_secret in " << credentialsFilePath << ": " << e.what());
return {};
}
}
KeyFile KeyFile::fromBase64(const std::string& encoded) {
boost::property_tree::ptree root;
std::stringstream stream;
stream << base64::decode(encoded);
try {
boost::property_tree::read_json(stream, root);
} catch (const boost::property_tree::json_parser_error& e) {
LOG_ERROR("Failed to parse credentials from " << stream.str());
return {};
}
try {
return {root.get<std::string>("client_id"), root.get<std::string>("client_secret")};
} catch (const boost::property_tree::ptree_error& e) {
LOG_ERROR("Failed to get client_id or client_secret in " << stream.str() << ": " << e.what());
return {};
}
}
ClientCredentialFlow::ClientCredentialFlow(ParamMap& params)
: issuerUrl_(params["issuer_url"]),
keyFile_(KeyFile::fromParamMap(params)),
audience_(params["audience"]),
scope_(params["scope"]) {}
std::string ClientCredentialFlow::getTokenEndPoint() const { return tokenEndPoint_; }
void ClientCredentialFlow::initialize() {
if (issuerUrl_.empty()) {
LOG_ERROR("Failed to initialize ClientCredentialFlow: issuer_url is not set");
return;
}
if (!keyFile_.isValid()) {
return;
}
// set URL: well-know endpoint
std::string wellKnownUrl = issuerUrl_;
if (wellKnownUrl.back() == '/') {
wellKnownUrl.pop_back();
}
wellKnownUrl.append("/.well-known/openid-configuration");
CurlWrapper curl;
if (!curl.init()) {
LOG_ERROR("Failed to initialize curl");
return;
}
std::unique_ptr<CurlWrapper::TlsContext> tlsContext;
if (!tlsTrustCertsFilePath_.empty()) {
tlsContext.reset(new CurlWrapper::TlsContext);
tlsContext->trustCertsFilePath = tlsTrustCertsFilePath_;
}
auto result = curl.get(wellKnownUrl, "Accept: application/json", {}, tlsContext.get());
if (!result.error.empty()) {
LOG_ERROR("Failed to get the well-known configuration " << issuerUrl_ << ": " << result.error);
return;
}
const auto res = result.code;
const auto response_code = result.responseCode;
const auto& responseData = result.responseData;
const auto& errorBuffer = result.serverError;
switch (res) {
case CURLE_OK:
LOG_DEBUG("Received well-known configuration data " << issuerUrl_ << " code " << response_code);
if (response_code == 200) {
boost::property_tree::ptree root;
std::stringstream stream;
stream << responseData;
try {
boost::property_tree::read_json(stream, root);
} catch (boost::property_tree::json_parser_error& e) {
LOG_ERROR("Failed to parse well-known configuration data response: "
<< e.what() << "\nInput Json = " << responseData);
break;
}
this->tokenEndPoint_ = root.get<std::string>("token_endpoint");
LOG_DEBUG("Get token endpoint: " << this->tokenEndPoint_);
} else {
LOG_ERROR("Response failed for getting the well-known configuration "
<< issuerUrl_ << ". response Code " << response_code);
}
break;
default:
LOG_ERROR("Response failed for getting the well-known configuration "
<< issuerUrl_ << ". Error Code " << res << ": " << errorBuffer);
break;
}
}
void ClientCredentialFlow::close() {}
ParamMap ClientCredentialFlow::generateParamMap() const {
if (!keyFile_.isValid()) {
return {};
}
ParamMap params;
params.emplace("grant_type", "client_credentials");
params.emplace("client_id", keyFile_.getClientId());
params.emplace("client_secret", keyFile_.getClientSecret());
params.emplace("audience", audience_);
if (!scope_.empty()) {
params.emplace("scope", scope_);
}
return params;
}
static std::string buildClientCredentialsBody(CurlWrapper& curl, const ParamMap& params) {
std::ostringstream oss;
bool addSeparater = false;
for (const auto& kv : params) {
if (addSeparater) {
oss << "&";
} else {
addSeparater = true;
}
char* encodedKey = curl.escape(kv.first);
if (!encodedKey) {
LOG_ERROR("curl_easy_escape for " << kv.first << " failed");
continue;
}
char* encodedValue = curl.escape(kv.second);
if (!encodedValue) {
LOG_ERROR("curl_easy_escape for " << kv.second << " failed");
continue;
}
oss << encodedKey << "=" << encodedValue;
curl_free(encodedKey);
curl_free(encodedValue);
}
return oss.str();
}
Oauth2TokenResultPtr ClientCredentialFlow::authenticate() {
std::call_once(initializeOnce_, &ClientCredentialFlow::initialize, this);
Oauth2TokenResultPtr resultPtr = Oauth2TokenResultPtr(new Oauth2TokenResult());
if (tokenEndPoint_.empty()) {
return resultPtr;
}
CurlWrapper curl;
if (!curl.init()) {
LOG_ERROR("Failed to initialize curl");
return resultPtr;
}
auto postData = buildClientCredentialsBody(curl, generateParamMap());
if (postData.empty()) {
return resultPtr;
}
LOG_DEBUG("Generate URL encoded body for ClientCredentialFlow: " << postData);
CurlWrapper::Options options;
options.postFields = std::move(postData);
auto result =
curl.get(tokenEndPoint_, "Content-Type: application/x-www-form-urlencoded", options, nullptr);
if (!result.error.empty()) {
LOG_ERROR("Failed to get the well-known configuration " << issuerUrl_ << ": " << result.error);
return resultPtr;
}
const auto res = result.code;
const auto response_code = result.responseCode;
const auto& responseData = result.responseData;
const auto& errorBuffer = result.serverError;
switch (res) {
case CURLE_OK:
LOG_DEBUG("Response received for issuerurl " << issuerUrl_ << " code " << response_code);
if (response_code == 200) {
boost::property_tree::ptree root;
std::stringstream stream;
stream << responseData;
try {
boost::property_tree::read_json(stream, root);
} catch (boost::property_tree::json_parser_error& e) {
LOG_ERROR("Failed to parse json of Oauth2 response: "
<< e.what() << "\nInput Json = " << responseData << " passedin: " << postData);
break;
}
resultPtr->setAccessToken(root.get<std::string>("access_token", ""));
resultPtr->setExpiresIn(
root.get<uint32_t>("expires_in", Oauth2TokenResult::undefined_expiration));
resultPtr->setRefreshToken(root.get<std::string>("refresh_token", ""));
resultPtr->setIdToken(root.get<std::string>("id_token", ""));
if (!resultPtr->getAccessToken().empty()) {
LOG_DEBUG("access_token: " << resultPtr->getAccessToken()
<< " expires_in: " << resultPtr->getExpiresIn());
} else {
LOG_ERROR("Response doesn't contain access_token, the response is: " << responseData);
}
} else {
LOG_ERROR("Response failed for issuerurl " << issuerUrl_ << ". response Code "
<< response_code << " passedin: " << postData);
}
break;
default:
LOG_ERROR("Response failed for issuerurl " << issuerUrl_ << ". ErrorCode " << res << ": "
<< errorBuffer << " passedin: " << postData);
break;
}
return resultPtr;
}
// AuthOauth2
AuthOauth2::AuthOauth2(ParamMap& params) : flowPtr_(new ClientCredentialFlow(params)) {}
AuthOauth2::~AuthOauth2() {}
ParamMap parseJsonAuthParamsString(const std::string& authParamsString) {
ParamMap params;
if (!authParamsString.empty()) {
boost::property_tree::ptree root;
std::stringstream stream;
stream << authParamsString;
try {
boost::property_tree::read_json(stream, root);
for (const auto& item : root) {
params[item.first] = item.second.get_value<std::string>();
}
} catch (boost::property_tree::json_parser_error& e) {
LOG_ERROR("Invalid String Error: " << e.what());
}
}
return params;
}
AuthenticationPtr AuthOauth2::create(const std::string& authParamsString) {
ParamMap params = parseJsonAuthParamsString(authParamsString);
return create(params);
}
AuthenticationPtr AuthOauth2::create(ParamMap& params) { return AuthenticationPtr(new AuthOauth2(params)); }
const std::string AuthOauth2::getAuthMethodName() const { return "token"; }
Result AuthOauth2::getAuthData(AuthenticationDataPtr& authDataContent) {
auto initialAuthData = std::dynamic_pointer_cast<InitialAuthData>(authDataContent);
if (initialAuthData) {
auto flowPtr = std::dynamic_pointer_cast<ClientCredentialFlow>(flowPtr_);
if (!flowPtr_) {
throw std::invalid_argument("AuthOauth2::flowPtr_ is not a ClientCredentialFlow");
}
flowPtr->setTlsTrustCertsFilePath(initialAuthData->tlsTrustCertsFilePath_);
}
if (cachedTokenPtr_ == nullptr || cachedTokenPtr_->isExpired()) {
try {
cachedTokenPtr_ = CachedTokenPtr(new Oauth2CachedToken(flowPtr_->authenticate()));
} catch (const std::runtime_error& e) {
// The real error logs have already been printed in authenticate()
return ResultAuthenticationError;
}
}
authDataContent = cachedTokenPtr_->getAuthData();
return ResultOk;
}
} // namespace pulsar