Files
moloapp/src/google/service_account.cpp
T

198 lines
7.3 KiB
C++
Raw Normal View History

#include "google/service_account.h"
#include <wolfssl/options.h>
#include <wolfssl/wolfcrypt/asn.h>
#include <wolfssl/wolfcrypt/error-crypt.h>
#include <wolfssl/wolfcrypt/random.h>
#include <wolfssl/wolfcrypt/rsa.h>
#include <wolfssl/wolfcrypt/signature.h>
#include <ctime>
#include <fstream>
#include <memory>
#include <sstream>
#include "clients/body/json.h"
#include "clients/client.h"
#include "clients/transports/http_transport.h"
#include "google/credentials.h"
#include "google/errors.h"
#include "security/crypto/Base64.h"
namespace molo::google {
using clients::body::Json;
using security::crypto::Base64;
namespace {
constexpr std::size_t kMaxKeyFileBytes = 64 * 1024;
constexpr auto kRefreshMargin = std::chrono::seconds(60);
std::string str(const Json& doc, const char* key) {
const Json* v = doc.is_object() ? doc.find(key) : nullptr;
return v && v->is_string() ? v->as_string() : "";
}
// Tokens may only be requested from a Google host over https: the key file
// is trusted, but a typo or a swapped file must not send a signed assertion
// to an arbitrary server.
bool google_https(const std::string& uri) {
const std::string scheme = "https://";
if (uri.rfind(scheme, 0) != 0) return false;
std::string host = uri.substr(scheme.size(), uri.find('/', scheme.size()) - scheme.size());
const std::string suffix = ".googleapis.com";
return host.size() > suffix.size() &&
host.compare(host.size() - suffix.size(), suffix.size(), suffix) == 0;
}
std::string pem_to_der(const std::string& pem) {
std::string body;
std::istringstream in(pem);
std::string line;
while (std::getline(in, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
if (line.rfind("-----", 0) == 0 || line.empty()) continue;
body += line;
}
std::string der;
if (!Base64::decode(body, der) || der.empty())
throw GoogleError::invalid("private_key is not valid PEM");
return der;
}
class RsaKeyGuard {
public:
RsaKeyGuard() { wc_InitRsaKey(&key, nullptr); }
~RsaKeyGuard() { wc_FreeRsaKey(&key); }
RsaKeyGuard(const RsaKeyGuard&) = delete;
RsaKeyGuard& operator=(const RsaKeyGuard&) = delete;
RsaKey key;
};
} // namespace
ServiceAccountKey ServiceAccountKey::parse(const std::string& json_text) {
Json doc;
try {
doc = Json::parse(json_text);
} catch (const std::exception&) {
throw GoogleError::invalid("service account key is not valid JSON");
}
ServiceAccountKey key;
if (str(doc, "type") != "service_account")
throw GoogleError::invalid("key file type is not service_account");
key.client_email = str(doc, "client_email");
key.private_key_pem = str(doc, "private_key");
std::string uri = str(doc, "token_uri");
if (!uri.empty()) key.token_uri = uri;
key.project_id = str(doc, "project_id");
if (key.client_email.empty() || key.private_key_pem.empty())
throw GoogleError::invalid("key file lacks client_email or private_key");
if (!google_https(key.token_uri))
throw GoogleError::invalid("token_uri must be https on googleapis.com");
return key;
}
ServiceAccountKey ServiceAccountKey::load_file(const std::string& path) {
std::ifstream in(path, std::ios::binary);
if (!in) throw GoogleError::invalid("cannot read service account key file");
std::ostringstream text;
text << in.rdbuf();
if (text.str().size() > kMaxKeyFileBytes)
throw GoogleError::invalid("service account key file over the size cap");
return parse(text.str());
}
JwtSigner::JwtSigner(const ServiceAccountKey& key) : key_(key) {}
std::string JwtSigner::sign(const std::string& scope, std::int64_t iat,
std::chrono::seconds lifetime) const {
Json header = Json::object();
header.set("alg", Json("RS256"));
header.set("typ", Json("JWT"));
Json claims = Json::object();
claims.set("iss", Json(key_.client_email));
claims.set("scope", Json(scope));
claims.set("aud", Json(key_.token_uri));
claims.set("iat", Json(static_cast<double>(iat)));
claims.set("exp", Json(static_cast<double>(iat + lifetime.count())));
std::string signing_input = Base64::encode_url(header.dump()) + "." +
Base64::encode_url(claims.dump());
std::string der = pem_to_der(key_.private_key_pem);
RsaKeyGuard rsa;
word32 idx = 0;
int off = wc_GetPkcs8TraditionalOffset(
reinterpret_cast<byte*>(der.data()), &idx, static_cast<word32>(der.size()));
if (off < 0) idx = 0; // Already traditional PKCS#1.
if (wc_RsaPrivateKeyDecode(reinterpret_cast<const byte*>(der.data()), &idx,
&rsa.key, static_cast<word32>(der.size())) != 0)
throw GoogleError::invalid("private_key is not a usable RSA key");
WC_RNG rng;
if (wc_InitRng(&rng) != 0) throw GoogleError(500, "INTERNAL", "rng init failed");
word32 sig_len = static_cast<word32>(
wc_SignatureGetSize(WC_SIGNATURE_TYPE_RSA_W_ENC, &rsa.key, sizeof(rsa.key)));
std::string sig(sig_len, '\0');
int rc = wc_SignatureGenerate(
WC_HASH_TYPE_SHA256, WC_SIGNATURE_TYPE_RSA_W_ENC,
reinterpret_cast<const byte*>(signing_input.data()),
static_cast<word32>(signing_input.size()), reinterpret_cast<byte*>(sig.data()),
&sig_len, &rsa.key, sizeof(rsa.key), &rng);
wc_FreeRng(&rng);
if (rc != 0) throw GoogleError(500, "INTERNAL", "JWT signing failed");
sig.resize(sig_len);
return signing_input + "." + Base64::encode_url(sig);
}
ServiceAccountAuth::ServiceAccountAuth(ServiceAccountKey key, std::string scope)
: key_(std::move(key)), scope_(std::move(scope)), signer_(key_) {}
ServiceAccountAuth::~ServiceAccountAuth() = default;
std::string ServiceAccountAuth::token() const {
std::lock_guard<std::mutex> lock(mutex_);
auto now = std::chrono::steady_clock::now();
if (!token_.empty() && now + kRefreshMargin < expires_) return token_;
std::string assertion =
signer_.sign(scope_, static_cast<std::int64_t>(std::time(nullptr)));
clients::Client http(std::make_unique<clients::transports::HttpTransport>());
clients::ClientRequest req = clients::ClientRequest::post(key_.token_uri);
req.form("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer"
"&assertion=" + assertion);
clients::ClientResponse resp = http.send_blocking(std::move(req));
Json doc;
try {
doc = resp.json();
} catch (const std::exception&) {
throw GoogleError(502, "BAD_RESPONSE", "token endpoint returned non-JSON", "oauth2");
}
if (!resp.is_success()) {
std::string msg = str(doc, "error_description");
throw GoogleError(resp.status() == 400 ? 401 : resp.status(),
str(doc, "error").empty() ? "UNAUTHENTICATED" : str(doc, "error"),
msg.empty() ? "token exchange failed" : msg, "oauth2");
}
token_ = str(doc, "access_token");
const Json* ttl = doc.find("expires_in");
long seconds = ttl && ttl->is_number() ? ttl->as_int() : 3600;
if (token_.empty())
throw GoogleError(502, "BAD_RESPONSE", "token endpoint returned no access_token", "oauth2");
expires_ = now + std::chrono::seconds(seconds);
return token_;
}
void ServiceAccountAuth::apply(clients::ClientRequest& request) const {
request.bearer(token());
}
std::shared_ptr<ServiceAccountAuth> ServiceAccountAuth::from_env() {
std::string path = Credentials::env("GOOGLE_APPLICATION_CREDENTIALS");
if (path.empty()) return nullptr;
return std::make_shared<ServiceAccountAuth>(ServiceAccountKey::load_file(path));
}
} // namespace molo::google