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
|
// Copyright Epic Games, Inc. All Rights Reserved.
#include <zenhttp/httpclientauth.h>
#include <zencore/fmtutils.h>
#include <zencore/logging.h>
#include <zencore/process.h>
#include <zencore/scopeguard.h>
#include <zencore/timer.h>
#include <zencore/uid.h>
#include <zenhttp/auth/authmgr.h>
#include <ctime>
ZEN_THIRD_PARTY_INCLUDES_START
#include <cpr/cpr.h>
#include <fmt/format.h>
#include <json11.hpp>
ZEN_THIRD_PARTY_INCLUDES_END
#if ZEN_PLATFORM_WINDOWS
# define timegm _mkgmtime
#endif // ZEN_PLATFORM_WINDOWS
namespace zen { namespace httpclientauth {
using namespace std::literals;
std::function<HttpClientAccessToken()> CreateFromStaticToken(HttpClientAccessToken Token)
{
return [Token]() { return Token; };
}
std::function<HttpClientAccessToken()> CreateFromStaticToken(std::string_view Token)
{
return CreateFromStaticToken(
HttpClientAccessToken{.Value = fmt::format("Bearer {}"sv, Token), .ExpireTime = HttpClientAccessToken::TimePoint::max()});
}
std::function<HttpClientAccessToken()> CreateFromOAuthClientCredentials(const OAuthClientCredentialsParams& Params)
{
OAuthClientCredentialsParams OAuthParams(Params);
return [OAuthParams]() {
using namespace std::chrono;
std::string Body = fmt::format("client_id={}&scope=cache_access&grant_type=client_credentials&client_secret={}"sv,
OAuthParams.ClientId,
OAuthParams.ClientSecret);
cpr::Response Response = cpr::Post(cpr::Url{OAuthParams.Url},
cpr::Header{{"Content-Type", "application/x-www-form-urlencoded"}},
cpr::Body{std::move(Body)});
if (Response.error || Response.status_code != 200)
{
ZEN_WARN("Failed fetching OAuth access token {}. Reason: '{}'", OAuthParams.Url, Response.reason);
return HttpClientAccessToken{};
}
std::string JsonError;
json11::Json Json = json11::Json::parse(Response.text, JsonError);
if (JsonError.empty() == false)
{
ZEN_WARN("Unable to parse OAuth json response from {}. Reason: '{}'", OAuthParams.Url, JsonError);
return HttpClientAccessToken{};
}
std::string Token = Json["access_token"].string_value();
int64_t ExpiresInSeconds = static_cast<int64_t>(Json["expires_in"].int_value());
HttpClientAccessToken::TimePoint ExpireTime = HttpClientAccessToken::Clock::now() + seconds(ExpiresInSeconds);
return HttpClientAccessToken{.Value = fmt::format("Bearer {}"sv, Token), .ExpireTime = ExpireTime};
};
}
std::function<HttpClientAccessToken()> CreateFromOpenIdProvider(AuthMgr& AuthManager, std::string_view OpenIdProvider)
{
return [&AuthManager = AuthManager, OpenIdProvider = std::string(OpenIdProvider)]() {
AuthMgr::OpenIdAccessToken Token = AuthManager.GetOpenIdAccessToken(OpenIdProvider);
return HttpClientAccessToken{.Value = Token.AccessToken, .ExpireTime = Token.ExpireTime};
};
}
std::function<HttpClientAccessToken()> CreateFromDefaultOpenIdProvider(AuthMgr& AuthManager)
{
return CreateFromOpenIdProvider(AuthManager, "Default"sv);
}
static HttpClientAccessToken GetOidcTokenFromExe(const std::filesystem::path& OidcExecutablePath,
std::string_view CloudHost,
bool Unattended,
bool Quiet)
{
Stopwatch Timer;
CreateProcOptions ProcOptions;
if (Quiet)
{
ProcOptions.StdoutFile = std::filesystem::temp_directory_path() / fmt::format(".zen-auth-output-{}", Oid::NewOid());
}
const std::filesystem::path AuthTokenPath(std::filesystem::temp_directory_path() / fmt::format(".zen-auth-{}", Oid::NewOid()));
auto _ = MakeGuard([AuthTokenPath, &ProcOptions]() {
RemoveFile(AuthTokenPath);
if (!ProcOptions.StdoutFile.empty())
{
RemoveFile(ProcOptions.StdoutFile);
}
});
const std::string ProcArgs = fmt::format("{} --AuthConfigUrl {} --OutFile {} --Unattended={}",
OidcExecutablePath,
CloudHost,
AuthTokenPath,
Unattended ? "true"sv : "false"sv);
ZEN_DEBUG("Running: {}", ProcArgs);
ProcessHandle Proc;
Proc.Initialize(CreateProc(OidcExecutablePath, ProcArgs, ProcOptions));
if (!Proc.IsValid())
{
throw std::runtime_error(fmt::format("failed to launch '{}'", OidcExecutablePath));
}
int ExitCode = Proc.WaitExitCode();
auto EndTime = std::chrono::system_clock::now();
if (ExitCode == 0)
{
IoBuffer Body = IoBufferBuilder::MakeFromFile(AuthTokenPath);
std::string JsonText(reinterpret_cast<const char*>(Body.GetData()), Body.GetSize());
std::string JsonError;
json11::Json Json = json11::Json::parse(JsonText, JsonError);
if (JsonError.empty() == false)
{
ZEN_WARN("Unable to parse Oidcs json response from {}. Reason: '{}'", AuthTokenPath, JsonError);
return HttpClientAccessToken{};
}
std::string Token = Json["Token"].string_value();
std::string ExpiresAtUTCString = Json["ExpiresAtUtc"].string_value();
ZEN_ASSERT(!ExpiresAtUTCString.empty());
int Year = 0;
int Month = 0;
int Day = 0;
int Hour = 0;
int Minute = 0;
int Second = 0;
int Millisecond = 0;
sscanf(ExpiresAtUTCString.c_str(), "%d-%d-%dT%d:%d:%d.%dZ", &Year, &Month, &Day, &Hour, &Minute, &Second, &Millisecond);
std::tm Time = {
Second,
Minute,
Hour,
Day,
Month - 1,
Year - 1900,
};
time_t UTCTime = timegm(&Time);
HttpClientAccessToken::TimePoint ExpireTime = std::chrono::system_clock::from_time_t(UTCTime);
ExpireTime += std::chrono::microseconds(Millisecond);
return HttpClientAccessToken{.Value = fmt::format("Bearer {}"sv, Token), .ExpireTime = ExpireTime};
}
else
{
ZEN_WARN("Failed running {} to get auth token, error code {}", OidcExecutablePath, ExitCode);
}
return HttpClientAccessToken{};
}
std::optional<std::function<HttpClientAccessToken()>> CreateFromOidcTokenExecutable(const std::filesystem::path& OidcExecutablePath,
std::string_view CloudHost,
bool Quiet)
{
HttpClientAccessToken InitialToken = GetOidcTokenFromExe(OidcExecutablePath, CloudHost, /* Unattended */ false, Quiet);
if (InitialToken.IsValid())
{
return [OidcExecutablePath = std::filesystem::path(OidcExecutablePath),
CloudHost = std::string(CloudHost),
Quiet,
InitialToken]() mutable {
if (InitialToken.IsValid())
{
HttpClientAccessToken Result = InitialToken;
InitialToken = {};
return Result;
}
return GetOidcTokenFromExe(OidcExecutablePath, CloudHost, /* Unattended */ true, Quiet);
};
}
return {};
}
}} // namespace zen::httpclientauth
|