#pragma once // Service-account credentials (OAuth2 JWT bearer flow, RFC 7523). Reads the // JSON key file Google issues (client_email, private_key, token_uri), signs a // short-lived RS256 JWT with wolfCrypt, exchanges it for an access token and // keeps the token fresh. Needed by every Google API that refuses API keys. // // Env: GOOGLE_APPLICATION_CREDENTIALS = path to the key file (looked up like // every other knob: environment, .env.json.local, .env.json). #include #include #include #include #include "clients/auth.h" namespace molo::google { struct ServiceAccountKey { std::string client_email; std::string private_key_pem; std::string token_uri = "https://oauth2.googleapis.com/token"; std::string project_id; // Informational; from the key file when present. // Throws GoogleError (invalid) when the file is missing, over the cap, // malformed, lacks fields, or names a non-Google token endpoint. static ServiceAccountKey load_file(const std::string& path); static ServiceAccountKey parse(const std::string& json_text); }; // RS256 JWT builder. Pure computation, no network. class JwtSigner { public: explicit JwtSigner(const ServiceAccountKey& key); // header.claims.signature, base64url. exp = iat + lifetime. std::string sign(const std::string& scope, std::int64_t iat, std::chrono::seconds lifetime = std::chrono::seconds(3600)) const; private: ServiceAccountKey key_; }; // clients::Auth that always carries a valid bearer token; refreshes one // minute before expiry. Thread safe. A failed exchange throws GoogleError. class ServiceAccountAuth : public clients::Auth { public: static constexpr const char* kDefaultScope = "https://www.googleapis.com/auth/cloud-platform"; explicit ServiceAccountAuth(ServiceAccountKey key, std::string scope = kDefaultScope); ~ServiceAccountAuth() override; void apply(clients::ClientRequest& request) const override; const char* scheme() const override { return "service-account"; } const ServiceAccountKey& key() const { return key_; } // Env helper: loads GOOGLE_APPLICATION_CREDENTIALS; null when unset. static std::shared_ptr from_env(); private: std::string token() const; ServiceAccountKey key_; std::string scope_; JwtSigner signer_; mutable std::mutex mutex_; mutable std::string token_; mutable std::chrono::steady_clock::time_point expires_{}; }; } // namespace molo::google