#include "google/workspace/workspace_client.h" #include #include #include "clients/transports/http_transport.h" #include "google/credentials.h" #include "google/errors.h" #include "google/workspace/caps.h" namespace molo::google::workspace { namespace { std::vector words(const char* text) { std::vector out; std::istringstream in(text); std::string w; while (in >> w) out.push_back(w); return out; } const ApiSpec& need(const std::string& api) { const ApiSpec* spec = find_api(api); if (!spec) throw GoogleError::invalid("unknown Workspace API " + api); return *spec; } std::string subject_of(const WorkspaceOptions& o) { if (o.delegation.active()) return o.delegation.subject; return Credentials::env("GOOGLE_WORKSPACE_SUBJECT"); } } // namespace std::vector Scopes::all_of(const std::string& api) { return words(need(api).scopes); } std::vector Scopes::readonly_of(const std::string& api) { auto ro = words(need(api).readonly_scopes); return ro.empty() ? all_of(api) : ro; } std::vector Scopes::for_apis(const std::vector& apis, bool readonly) { if (apis.empty()) throw GoogleError::invalid("name at least one API"); std::vector out; std::set seen; for (const auto& a : apis) for (const auto& s : readonly ? readonly_of(a) : all_of(a)) if (seen.insert(s).second) out.push_back(s); if (out.size() > WorkspaceCaps::kMaxScopes) throw GoogleError::invalid("these APIs need over 40 scopes together; name fewer APIs"); return out; } std::string WorkspaceAuth::mode_from_env(const WorkspaceOptions& options) { if (!subject_of(options).empty()) return "delegated"; if (!Credentials::env("GOOGLE_ACCESS_TOKEN").empty()) return "user-token"; if (!Credentials::env("GOOGLE_APPLICATION_CREDENTIALS").empty()) return "service-account"; return "none"; } std::shared_ptr WorkspaceAuth::from_env(const WorkspaceOptions& options) { options.delegation.validate(); std::string subject = subject_of(options); std::string mode = mode_from_env(options); if (mode == "user-token") return Credentials::bearer(Credentials::env("GOOGLE_ACCESS_TOKEN")); if (mode == "none") return nullptr; std::string path = Credentials::env("GOOGLE_APPLICATION_CREDENTIALS"); if (path.empty()) throw GoogleError::invalid("a delegation subject needs GOOGLE_APPLICATION_CREDENTIALS"); Delegation d{subject}; return std::make_shared(ServiceAccountKey::load_file(path), Scopes::for_apis(options.apis, options.readonly), d); } std::shared_ptr make_workspace_client(const WorkspaceOptions& options) { return std::make_shared(std::make_unique(), nullptr, WorkspaceAuth::from_env(options)); } Workspace::Workspace(std::shared_ptr client) : client_(std::move(client)) {} std::vector Workspace::api_names() { std::vector out; for (std::size_t i = 0; i < kApiTableSize; ++i) out.push_back(kApiTable[i].name); return out; } } // namespace molo::google::workspace