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
|
#include "iam.h"
#include <cloud/bitbucket/public-api/yandex/cloud/iam/v1/iam_token_service.pb.h>
#include <cloud/bitbucket/public-api/yandex/cloud/iam/v1/iam_token_service.grpc.pb.h>
#include <cloud/bitbucket/private-api/yandex/cloud/priv/iam/v1/iam_token_service.pb.h>
#include <cloud/bitbucket/private-api/yandex/cloud/priv/iam/v1/iam_token_service.grpc.pb.h>
#include <library/cpp/grpc/client/grpc_client_low.h>
#include <library/cpp/threading/atomic/bool.h>
#include <library/cpp/threading/future/core/future.h>
#include <library/cpp/json/json_reader.h>
#include <library/cpp/http/simple/http_client.h>
#include <util/system/spinlock.h>
#include <util/stream/file.h>
#include <util/string/builder.h>
#include <chrono>
using namespace yandex::cloud::iam::v1;
using namespace NGrpc;
namespace NYdb {
constexpr TDuration BACKOFF_START = TDuration::MilliSeconds(50);
constexpr TDuration BACKOFF_MAX = TDuration::Seconds(10);
class TIAMCredentialsProvider : public ICredentialsProvider {
public:
TIAMCredentialsProvider(const TIamHost& params)
: HttpClient_(TSimpleHttpClient(params.Host, params.Port))
, Request_("/computeMetadata/v1/instance/service-accounts/default/token")
, NextTicketUpdate_(TInstant::Zero())
, RefreshPeriod_(params.RefreshPeriod)
{
GetTicket();
}
TStringType GetAuthInfo() const override {
if (TInstant::Now() >= NextTicketUpdate_) {
GetTicket();
}
return Ticket_;
}
bool IsValid() const override {
return true;
}
private:
TSimpleHttpClient HttpClient_;
TStringType Request_;
mutable TStringType Ticket_;
mutable TInstant NextTicketUpdate_;
TDuration RefreshPeriod_;
void GetTicket() const {
try {
TStringStream out;
TSimpleHttpClient::THeaders headers;
headers["Metadata-Flavor"] = "Google";
HttpClient_.DoGet(Request_, &out, headers);
NJson::TJsonValue resp;
NJson::ReadJsonTree(&out, &resp, true);
auto respMap = resp.GetMap();
if (auto it = respMap.find("access_token"); it == respMap.end())
ythrow yexception() << "Result doesn't contain access_token";
else if (TString ticket = it->second.GetStringSafe(); ticket.empty())
ythrow yexception() << "Got empty ticket";
else
Ticket_ = std::move(ticket);
if (auto it = respMap.find("expires_in"); it == respMap.end())
ythrow yexception() << "Result doesn't contain expires_in";
else {
const TDuration expiresIn = TDuration::Seconds(it->second.GetUInteger());
NextTicketUpdate_ = TInstant::Now() + std::max(expiresIn, RefreshPeriod_);
}
} catch (...) {
}
}
};
template<typename TRequest, typename TResponse, typename TService>
class TGrpcIamCredentialsProvider : public ICredentialsProvider {
protected:
using TRequestFiller = std::function<void(TRequest&)>;
private:
class TImpl : public std::enable_shared_from_this<TGrpcIamCredentialsProvider<TRequest, TResponse, TService>::TImpl> {
public:
TImpl(const TIamEndpoint& iamEndpoint, const TRequestFiller& requestFiller)
: Client(MakeHolder<NGrpc::TGRpcClientLow>())
, Connection_(nullptr)
, Ticket_("")
, NextTicketUpdate_(TInstant::Zero())
, IamEndpoint_(iamEndpoint)
, RequestFiller_(requestFiller)
, RequestInflight_(false)
, LastRequestError_("")
, NeedStop_(false)
, BackoffTimeout_(BACKOFF_START)
, Lock_()
{
TGRpcClientConfig grpcConf;
grpcConf.Locator = IamEndpoint_.Endpoint;
grpcConf.EnableSsl = true;
Connection_ = THolder<TServiceConnection<TService>>(Client->CreateGRpcServiceConnection<TService>(grpcConf).release());
}
void UpdateTicket(bool sync = false) {
with_lock(Lock_) {
if (NeedStop_ || RequestInflight_) {
return;
}
RequestInflight_ = true;
}
auto resultPromise = NThreading::NewPromise();
std::shared_ptr<TImpl> self = TGrpcIamCredentialsProvider<TRequest, TResponse, TService>::TImpl::shared_from_this();
auto cb = [self, resultPromise, sync](
NGrpc::TGrpcStatus&& status, TResponse&& result) mutable {
self->ProcessIamResponse(std::move(status), std::move(result), sync);
resultPromise.SetValue();
};
TRequest req;
RequestFiller_(req);
Connection_->template DoRequest<TRequest, TResponse>(
std::move(req),
std::move(cb),
&TService::Stub::AsyncCreate,
{ {}, {}, IamEndpoint_.RequestTimeout }
);
if (sync) {
resultPromise.GetFuture().Wait(2 * IamEndpoint_.RequestTimeout);
}
}
TStringType GetTicket() {
TInstant nextTicketUpdate;
TString ticket;
with_lock(Lock_) {
ticket = Ticket_;
nextTicketUpdate = NextTicketUpdate_;
if (ticket.empty())
ythrow yexception() << "IAM-token not ready yet. " << LastRequestError_;
}
if (TInstant::Now() >= nextTicketUpdate) {
UpdateTicket();
}
return ticket;
}
void Stop() {
with_lock(Lock_) {
if (NeedStop_) {
return;
}
NeedStop_ = true;
}
Client.Reset(); // Will trigger destroy
}
private:
void ProcessIamResponse(NGrpc::TGrpcStatus&& status, TResponse&& result, bool sync) {
if (!status.Ok()) {
TDuration sleepDuration;
with_lock(Lock_) {
LastRequestError_ = TStringBuilder()
<< "Last request error was at " << TInstant::Now()
<< ". GrpcStatusCode: " << status.GRpcStatusCode
<< " Message: \"" << status.Msg
<< "\" internal: " << status.InternalError
<< " iam-endpoint: \"" << IamEndpoint_.Endpoint << "\"";
RequestInflight_ = false;
sleepDuration = std::min(BackoffTimeout_, BACKOFF_MAX);
BackoffTimeout_ *= 2;
}
Sleep(sleepDuration);
UpdateTicket(sync);
} else {
with_lock(Lock_) {
LastRequestError_ = "";
Ticket_ = result.iam_token();
RequestInflight_ = false;
BackoffTimeout_ = BACKOFF_START;
const auto now = Now();
NextTicketUpdate_ = std::min(
now + IamEndpoint_.RefreshPeriod,
TInstant::Seconds(result.expires_at().seconds())
) - IamEndpoint_.RequestTimeout;
NextTicketUpdate_ = std::max(NextTicketUpdate_, now + TDuration::MilliSeconds(100));
}
}
}
private:
THolder<TGRpcClientLow> Client;
THolder<TServiceConnection<TService>> Connection_;
TStringType Ticket_;
TInstant NextTicketUpdate_;
const TIamEndpoint IamEndpoint_;
const TRequestFiller RequestFiller_;
bool RequestInflight_;
TStringType LastRequestError_;
bool NeedStop_;
TDuration BackoffTimeout_;
TAdaptiveLock Lock_;
};
public:
TGrpcIamCredentialsProvider(const TIamEndpoint& endpoint, const TRequestFiller& requestFiller)
: Impl_(std::make_shared<TImpl>(endpoint, requestFiller))
{
Impl_->UpdateTicket(true);
}
~TGrpcIamCredentialsProvider() {
Impl_->Stop();
}
TStringType GetAuthInfo() const override {
return Impl_->GetTicket();
}
bool IsValid() const override {
return true;
}
private:
std::shared_ptr<TImpl> Impl_;
};
struct TIamJwtParams : TIamEndpoint {
TJwtParams JwtParams;
};
template<typename TRequest, typename TResponse, typename TService>
class TIamJwtCredentialsProvider : public TGrpcIamCredentialsProvider<TRequest, TResponse, TService> {
public:
TIamJwtCredentialsProvider(const TIamJwtParams& params)
: TGrpcIamCredentialsProvider<TRequest, TResponse, TService>(params,
[jwtParams = params.JwtParams](TRequest& req) {
req.set_jwt(MakeSignedJwt(jwtParams));
}) {}
};
class TIamOAuthCredentialsProvider : public TGrpcIamCredentialsProvider<CreateIamTokenRequest, CreateIamTokenResponse, IamTokenService> {
public:
TIamOAuthCredentialsProvider(const TIamOAuth& params)
: TGrpcIamCredentialsProvider(params,
[token = params.OAuthToken](CreateIamTokenRequest& req) {
req.set_yandex_passport_oauth_token(token);
}) {}
};
TJwtParams ReadJwtKeyFile(const TString& filename) {
return ParseJwtParams(TFileInput(filename).ReadAll());
}
class TIamCredentialsProviderFactory : public ICredentialsProviderFactory {
public:
TIamCredentialsProviderFactory(const TIamHost& params): Params_(params) {}
TCredentialsProviderPtr CreateProvider() const final {
return std::make_shared<TIAMCredentialsProvider>(Params_);
}
TStringType GetClientIdentity() const final {
return "IAM_PROVIDER" + ToString((ui64)this);
}
private:
TIamHost Params_;
};
template<typename TRequest, typename TResponse, typename TService>
class TIamJwtCredentialsProviderFactory : public ICredentialsProviderFactory {
public:
TIamJwtCredentialsProviderFactory(const TIamJwtParams& params): Params_(params) {}
TCredentialsProviderPtr CreateProvider() const final {
return std::make_shared<TIamJwtCredentialsProvider<TRequest, TResponse, TService>>(Params_);
}
TStringType GetClientIdentity() const final {
return "IAM_JWT_PROVIDER" + ToString((ui64)this);
}
private:
TIamJwtParams Params_;
};
class TIamOAuthCredentialsProviderFactory : public ICredentialsProviderFactory {
public:
TIamOAuthCredentialsProviderFactory(const TIamOAuth& params): Params_(params) {}
TCredentialsProviderPtr CreateProvider() const final {
return std::make_shared<TIamOAuthCredentialsProvider>(Params_);
}
TStringType GetClientIdentity() const final {
return "IAM_OAUTH_PROVIDER" + ToString((ui64)this);
}
private:
TIamOAuth Params_;
};
TCredentialsProviderFactoryPtr CreateIamCredentialsProviderFactory(const TIamHost& params) {
return std::make_shared<TIamCredentialsProviderFactory>(params);
}
TCredentialsProviderFactoryPtr CreateIamJwtCredentialsProviderFactoryImpl(TIamJwtParams&& jwtParams, bool usePrivateApi) {
if (usePrivateApi) {
return std::make_shared<TIamJwtCredentialsProviderFactory<
yandex::cloud::priv::iam::v1::CreateIamTokenRequest,
yandex::cloud::priv::iam::v1::CreateIamTokenResponse,
yandex::cloud::priv::iam::v1::IamTokenService
>>(std::move(jwtParams));
}
return std::make_shared<TIamJwtCredentialsProviderFactory<CreateIamTokenRequest,
CreateIamTokenResponse,
IamTokenService>>(std::move(jwtParams));
}
TCredentialsProviderFactoryPtr CreateIamJwtFileCredentialsProviderFactory(const TIamJwtFilename& params, bool usePrivateApi) {
TIamJwtParams jwtParams = { params, ReadJwtKeyFile(params.JwtFilename) };
return CreateIamJwtCredentialsProviderFactoryImpl(std::move(jwtParams), usePrivateApi);
}
TCredentialsProviderFactoryPtr CreateIamJwtParamsCredentialsProviderFactory(const TIamJwtContent& params, bool usePrivateApi) {
TIamJwtParams jwtParams = { params, ParseJwtParams(params.JwtContent) };
return CreateIamJwtCredentialsProviderFactoryImpl(std::move(jwtParams), usePrivateApi);
}
TCredentialsProviderFactoryPtr CreateIamOAuthCredentialsProviderFactory(const TIamOAuth& params) {
return std::make_shared<TIamOAuthCredentialsProviderFactory>(params);
}
} // namespace NYdb
|