diff --git a/example/app/google/WorkspaceDemo.cpp b/example/app/google/WorkspaceDemo.cpp index 00c4a0b..0210a91 100644 --- a/example/app/google/WorkspaceDemo.cpp +++ b/example/app/google/WorkspaceDemo.cpp @@ -1,13 +1,384 @@ #include "../GoogleDemos.hpp" +#include +#include + + #include "../../fw/Router.hpp" +#include "../../fw/Templates.hpp" +#include "google/credentials.h" +#include "google/workspace/calls.h" +#include "google/workspace/caps.h" +#include "google/workspace/workspace_client.h" namespace molo::example::app { -// Gmail, Drive, Calendar, Sheets, Docs, Slides, Forms, Tasks, Chat, Meet, People, YouTube. Stub: the package agent fills this in. +// Google Workspace (Gmail, Drive, Calendar, Sheets, Docs, Slides, Forms, Tasks, +// Chat, Meet, People, Keep, Classroom, YouTube Data / Analytics / Reporting, +// Admin SDK Directory and Reports, Groups Settings, Vault) over the real +// src/google/workspace part. Every Discovery method is reachable through +// POST /google/workspace/call. GET routes need no credential. Reads answer 503 +// google_not_configured without one, 422 on bad input (validated first). +// Writes, deletes and sends are dry runs unless the body says "confirm":true; +// Workspace data belongs to humans, so the page never defaults it. + +namespace { + +namespace ws = google::workspace; +using Json = clients::body::Json; + +constexpr std::size_t kMaxBody = 512 * 1024; +constexpr std::size_t kMaxCallsShown = 300; +constexpr std::size_t kMaxClients = 40; + +const char kPage[] = R"WORKSPACE({% extends "base.html" %} +{% block content %} +

Google Workspace

+

Twenty Workspace APIs, 714 calls from Google's Discovery documents. +Reads run at once; writes, deletes and sends are dry runs until you tick confirm.

+

Checking credentials...

+
+ + + +

+ + + +
+ + +
+ +

+
+ + +{% endblock %} +)WORKSPACE"; + +fw::Response json_out(const Json& j, int status = 200) { + fw::Response res = fw::JsonResponse(j.dump(), status); + res.headers.set("Cache-Control", "no-store"); + return res; +} + +[[noreturn]] void bad(const std::string& why) { throw fw::HttpError(422, "validation_error", why); } + +[[noreturn]] void rethrow(const google::GoogleError& e) { + if (e.http_status() == 503 && e.status() == "NOT_CONFIGURED") + throw fw::HttpError(503, "google_not_configured", e.message()); + if (e.status() == "INVALID_ARGUMENT" && e.http_status() == 400 && e.service().empty()) + throw fw::HttpError(422, "validation_error", e.message()); + throw fw::HttpError(502, "google_error", + std::to_string(e.http_status()) + " " + e.status() + ": " + e.message()); +} + +template +auto guarded(F&& f) -> decltype(f()) { + try { + return f(); + } catch (const google::GoogleError& e) { + rethrow(e); + } +} + +Json parse_body(const fw::Request& req) { + if (req.body.size() > kMaxBody) throw fw::HttpError(413, "payload_too_large", "body too large"); + if (req.body.empty()) return Json::object(); + try { + Json j = Json::parse(req.body); + if (!j.is_object()) bad("body must be a JSON object"); + return j; + } catch (const clients::body::JsonError&) { + bad("body is not valid JSON"); + } +} + +std::string text(const Json& body, const char* key, bool required) { + const Json* v = body.find(key); + if (!v || v->is_null()) { + if (required) bad(std::string(key) + " is required"); + return ""; + } + if (!v->is_string()) bad(std::string(key) + " must be a string"); + return v->as_string(); +} + +bool flag(const Json& body, const char* key) { + const Json* v = body.find(key); + if (!v || v->is_null()) return false; + if (!v->is_bool()) bad(std::string(key) + " must be true or false"); + return v->as_bool(); +} + +Json object_field(const Json& body, const char* key) { + const Json* v = body.find(key); + if (!v || v->is_null()) return Json::object(); + if (!v->is_object()) bad(std::string(key) + " must be a JSON object"); + return *v; +} + +std::vector split_csv(const std::string& s) { + std::vector out; + std::string cur; + for (char c : s) { + if (c == ',') { + if (!cur.empty()) out.push_back(cur); + cur.clear(); + } else { + cur += c; + } + } + if (!cur.empty()) out.push_back(cur); + return out; +} + +const char* kind_word(ws::Kind k) { + switch (k) { + case ws::Kind::kRead: return "read"; + case ws::Kind::kWrite: return "write"; + case ws::Kind::kDestroy: return "destroy"; + case ws::Kind::kSend: return "send"; + } + return "?"; +} + +// One object per route family: owns the client policy. An injected client +// (services.google) is used as is; otherwise a client is built per API and +// access level from the environment, because Workspace needs per-API scopes. +class WorkspaceRoutes { + public: + explicit WorkspaceRoutes(std::shared_ptr injected) + : injected_(std::move(injected)) {} + + std::shared_ptr client_for(const std::string& api, bool readonly) { + if (injected_) return injected_; + std::lock_guard lock(mutex_); + std::string key = api + (readonly ? ":ro" : ":rw"); + auto it = clients_.find(key); + if (it != clients_.end()) return it->second; + if (clients_.size() >= kMaxClients) clients_.clear(); + ws::WorkspaceOptions o; + o.apis = {api}; + o.readonly = readonly; + auto c = ws::make_workspace_client(o); + clients_[key] = c; + return c; + } + + std::string mode() const { + if (injected_) return injected_->configured() ? "injected" : "none"; + return ws::WorkspaceAuth::mode_from_env(ws::WorkspaceOptions{}); + } + + const ws::CallSpec& call_of(const Json& body) const { + std::string api = text(body, "api", true), id = text(body, "id", true); + if (!ws::find_api(api)) bad("unknown api " + api); + const ws::CallSpec* spec = ws::find_call_in(api, id); + if (!spec) bad("unknown call " + id + " in " + api); + return *spec; + } + + fw::Response call(const fw::Request& req) { + Json body = parse_body(req); + const ws::CallSpec& spec = call_of(body); + Json params = object_field(body, "params"); + const Json* payload = body.find("body"); + if (payload && payload->is_null()) payload = nullptr; + bool confirm = flag(body, "confirm"); + ws::Kind kind = ws::kind_of(spec); + std::string api = spec.api; + return guarded([&] { + // Validate with a client-free API object first: 422 before any credential check. + auto probe = ws::WorkspaceApi(client_for(api, true), api); + ws::PreparedCall prepared = probe.prepare(spec.id, params, payload); + if (kind != ws::Kind::kRead && !confirm) { + Json o = Json::object(); + o.set("dry_run", Json(true)); + o.set("kind", Json(kind_word(kind))); + o.set("http", Json(spec.http)); + o.set("path", Json(prepared.path)); + o.set("hint", Json("send confirm:true to run it")); + return json_out(o); + } + auto client = client_for(api, kind == ws::Kind::kRead); + ws::WorkspaceApi real(client, api); + switch (kind) { + case ws::Kind::kRead: return json_out(real.read(spec.id, params, payload)); + case ws::Kind::kWrite: return json_out(real.write(spec.id, params, payload, true)); + case ws::Kind::kDestroy: return json_out(real.destroy(spec.id, params, true)); + case ws::Kind::kSend: return json_out(real.send(spec.id, params, payload, true)); + } + bad("unknown kind"); + }); + } + + fw::Response list(const fw::Request& req) { + Json body = parse_body(req); + const ws::CallSpec& spec = call_of(body); + Json params = object_field(body, "params"); + int pages = 1; + if (const Json* p = body.find("maxPages")) { + if (!p->is_number()) bad("maxPages must be a number"); + pages = static_cast(p->as_int()); + if (pages < 1 || pages > 5) bad("maxPages must be 1..5"); + } + std::string api = spec.api; + return guarded([&] { + ws::WorkspaceApi real(client_for(api, true), api); + real.prepare(spec.id, params); + if (ws::kind_of(spec) != ws::Kind::kRead) bad(std::string(spec.id) + " is not a read call"); + if (!*spec.items_key) bad(std::string(spec.id) + " has no single items array"); + ws::Listing l = real.list(spec.id, params, pages); + Json items = Json::array(); + for (const Json& i : l.items) items.push(i); + Json o = Json::object(); + o.set("items", items); + o.set("count", Json(static_cast(l.items.size()))); + o.set("pages", Json(l.pages)); + o.set("truncated", Json(l.truncated)); + if (!l.next_page_token.empty()) o.set("nextPageToken", Json(l.next_page_token)); + return json_out(o); + }); + } + + private: + std::shared_ptr injected_; + std::mutex mutex_; + std::map> clients_; +}; + +} // namespace + void register_google_workspace_demo(fw::Router& router, Services& services) { - (void)router; - (void)services; + auto routes = std::make_shared(services.google); + fw::Environment* env = services.templates.get(); + services.templates->add_template("google_workspace.html", kPage); + services.add_feature("google-workspace", "/google/workspace"); + + router.get("/google/workspace", "google-workspace-page", [env](fw::Request req) { + (void)req; + fw::TemplateCtx ctx; + ctx["title"] = std::string("Google Workspace"); + return fw::Response(200, env->render("google_workspace.html", ctx), "text/html; charset=utf-8"); + }); + + router.get("/google/workspace/status", "google-workspace-status", [routes](fw::Request req) { + (void)req; + std::string mode = routes->mode(); + Json o = Json::object(); + o.set("configured", Json(mode != "none")); + o.set("mode", Json(mode)); + o.set("apis", Json(static_cast(ws::kApiTableSize))); + o.set("calls", Json(static_cast(ws::kCallTableSize))); + o.set("subject_set", + Json(!google::Credentials::env("GOOGLE_WORKSPACE_SUBJECT").empty())); + o.set("max_pages", Json(5)); + return json_out(o); + }); + + router.get("/google/workspace/apis", "google-workspace-apis", [](fw::Request req) { + (void)req; + Json arr = Json::array(); + for (std::size_t i = 0; i < ws::kApiTableSize; ++i) { + const ws::ApiSpec& a = ws::kApiTable[i]; + Json row = Json::object(); + row.set("name", Json(a.name)); + row.set("discovery", Json(a.discovery_id)); + row.set("revision", Json(a.revision)); + row.set("base_url", Json(a.base_url)); + row.set("service", Json(a.service)); + row.set("calls", Json(static_cast(ws::calls_of(a.name).size()))); + row.set("scopes", Json(static_cast(ws::Scopes::all_of(a.name).size()))); + row.set("readonly_scopes", Json(static_cast(ws::Scopes::readonly_of(a.name).size()))); + arr.push(row); + } + Json o = Json::object(); + o.set("apis", arr); + return json_out(o); + }); + + // The discovery-checked call table, filtered: ?api=gmail&kind=r + router.get("/google/workspace/calls", "google-workspace-calls", [](fw::Request req) { + std::string api = req.query_or("api", ""), kind = req.query_or("kind", ""); + if (!api.empty() && !ws::find_api(api)) bad("unknown api " + api); + if (kind.size() > 1 || (!kind.empty() && std::string("rwds").find(kind[0]) == std::string::npos)) + bad("kind must be one of r w d s"); + Json arr = Json::array(); + bool more = false; + for (std::size_t i = 0; i < ws::kCallTableSize; ++i) { + const ws::CallSpec& c = ws::kCallTable[i]; + if (!api.empty() && api != c.api) continue; + if (!kind.empty() && kind[0] != c.kind[0]) continue; + if (arr.as_array().size() >= kMaxCallsShown) { + more = true; + break; + } + Json row = Json::object(); + row.set("id", Json(c.id)); + row.set("api", Json(c.api)); + row.set("http", Json(c.http)); + row.set("path", Json(c.path)); + row.set("kind", Json(kind_word(ws::kind_of(c)))); + row.set("params", Json(c.params)); + row.set("body", Json(c.body)); + arr.push(row); + } + Json o = Json::object(); + o.set("calls", arr); + o.set("truncated", Json(more)); + return json_out(o); + }); + + // Scopes of the named APIs: ?apis=gmail,drive&readonly=true + router.get("/google/workspace/scopes", "google-workspace-scopes", [](fw::Request req) { + std::string ro = req.query_or("readonly", "true"); + if (ro != "true" && ro != "false") bad("readonly must be true or false"); + return guarded([&] { + Json arr = Json::array(); + for (const auto& s : ws::Scopes::for_apis(split_csv(req.query_or("apis", "")), ro == "true")) + arr.push(Json(s)); + Json o = Json::object(); + o.set("scopes", arr); + o.set("readonly", Json(ro == "true")); + return json_out(o); + }); + }); + + // Domain-wide delegation: validates the subject and scope set locally, + // nothing is sent to Google. + router.post("/google/workspace/delegation", "google-workspace-delegation", [](fw::Request req) { + Json body = parse_body(req); + std::string subject = text(body, "subject", false); + std::string apis = text(body, "apis", true); + bool readonly = body.find("readonly") ? flag(body, "readonly") : true; + return guarded([&] { + ws::Delegation d{subject}; + d.validate(); + Json scopes = Json::array(); + for (const auto& s : ws::Scopes::for_apis(split_csv(apis), readonly)) scopes.push(Json(s)); + Json o = Json::object(); + o.set("subject", Json(subject)); + o.set("impersonating", Json(d.active())); + o.set("scopes", scopes); + o.set("grant_at", Json("Admin console > Security > API controls > Domain-wide delegation")); + return json_out(o); + }); + }); + + router.post("/google/workspace/call", "google-workspace-call", + [routes](fw::Request req) { return routes->call(req); }); + router.post("/google/workspace/list", "google-workspace-list", + [routes](fw::Request req) { return routes->list(req); }); } } // namespace molo::example::app diff --git a/example/assets/google_workspace.js b/example/assets/google_workspace.js new file mode 100644 index 0000000..80e9be0 --- /dev/null +++ b/example/assets/google_workspace.js @@ -0,0 +1,69 @@ +// Google Workspace page: thin client over /google/workspace/* (all limits server side). +(function () { + "use strict"; + var $ = function (id) { return document.getElementById(id); }; + var out = $("ws-out"), err = $("ws-error"), calls = []; + + function show(res) { + return res.text().then(function (t) { + var j; + try { j = JSON.parse(t); } catch (e) { j = { message: t }; } + if (!res.ok) { err.textContent = j.message || ("HTTP " + res.status); out.textContent = ""; } + else { out.textContent = JSON.stringify(j, null, 2); } + return j; + }); + } + function send(path, extra) { + err.textContent = ""; + var params, body; + try { params = JSON.parse($("ws-params").value || "{}"); } catch (e) { err.textContent = "Parameters are not valid JSON"; return; } + var payload = { + api: $("ws-api").value, id: $("ws-call").value, params: params, + confirm: $("ws-confirm").checked + }; + var raw = $("ws-body").value.trim(); + if (raw) { try { payload.body = JSON.parse(raw); } catch (e2) { err.textContent = "Body is not valid JSON"; return; } } + for (var k in extra) payload[k] = extra[k]; + out.textContent = "..."; + fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) }) + .then(show).catch(function (e) { err.textContent = String(e); out.textContent = ""; }); + } + function loadCalls() { + var q = "?api=" + encodeURIComponent($("ws-api").value) + "&kind=" + encodeURIComponent($("ws-kind").value); + fetch("/google/workspace/calls" + q).then(function (r) { return r.json(); }).then(function (j) { + calls = j.calls || []; + var sel = $("ws-call"); + sel.innerHTML = ""; + calls.forEach(function (c) { + var o = document.createElement("option"); + o.value = c.id; o.textContent = c.id + " [" + c.kind + "]"; + sel.appendChild(o); + }); + sig(); + }); + } + function sig() { + var c = calls.filter(function (x) { return x.id === $("ws-call").value; })[0]; + $("ws-sig").textContent = c ? (c.http + " " + c.path + " params: " + (c.params || "none") + (c.body ? " body: " + c.body : "")) : ""; + } + + fetch("/google/workspace/status").then(function (r) { return r.json(); }).then(function (s) { + $("ws-config").textContent = s.configured + ? "Credential mode: " + s.mode + (s.subject_set ? " (impersonating a user)." : ".") + : "No Google credential: calls answer 503 until one is configured."; + }); + fetch("/google/workspace/apis").then(function (r) { return r.json(); }).then(function (j) { + var sel = $("ws-api"); + j.apis.forEach(function (a) { + var o = document.createElement("option"); + o.value = a.name; o.textContent = a.name + " (" + a.calls + ")"; + sel.appendChild(o); + }); + loadCalls(); + }); + $("ws-api").onchange = loadCalls; + $("ws-kind").onchange = loadCalls; + $("ws-call").onchange = sig; + $("ws-run").onclick = function () { send("/google/workspace/call", {}); }; + $("ws-list").onclick = function () { send("/google/workspace/list", { maxPages: 2 }); }; +})(); diff --git a/src/google/workspace/SPEC.md b/src/google/workspace/SPEC.md new file mode 100644 index 0000000..70de053 --- /dev/null +++ b/src/google/workspace/SPEC.md @@ -0,0 +1,212 @@ +# Google Workspace - Specification + +Owned directory: `src/google/workspace/`. Namespace `molo::google::workspace`. +Depends on the `src/google` foundation (`GoogleClient`, `Service`, +`ServiceAccountKey`, `Credentials`). Plan: `plans/18-breadth.md` section 1. + +## 1. Scope + +Twenty Workspace APIs, every Discovery method (714 calls, generated, not typed +by hand): Gmail, Drive, Calendar, Sheets, Docs, Slides, Forms, Tasks, Chat, +Meet, People, Keep, Classroom, YouTube Data, YouTube Analytics, YouTube +Reporting, Admin SDK Directory, Admin SDK Reports, Groups Settings, Vault. +`WorkspaceApi` reaches any call by its Discovery method id; typed classes +(`Gmail`, `Drive`, ...) add read helpers for common questions. Domain-wide +delegation (service-account `sub` claim) is a typed option (`Delegation`). + +Workspace data belongs to humans. Every call has a `Kind` (read, write, +destroy, send) and the library method that runs it must match: `read`, +`write`, `destroy`, `send`. The last three take an explicit `confirm` with no +default; false throws before any traffic. The example never sends, writes or +deletes without `"confirm":true`. Live checks here are reads only. + +## 2. Module map + +| File | Concern | +|---|---| +| `caps.h` | Static ceilings (`WorkspaceCaps`) | +| `calls.h/.cpp` | `ApiSpec`, `CallSpec`, `Kind`, lookups (`find_call_in`, `params_of`, `body_fields_of`) | +| `call_table.cpp` | GENERATED: the one table of apis, calls and request schemas | +| `prepared_call.h/.cpp` | `PreparedCall::build`: validation, path and query rendering from the table | +| `workspace_api.h/.cpp` | `WorkspaceApi : Service`: read / write / destroy / send / pages / list | +| `services.h/.cpp` | Typed read helpers, one class per API | +| `delegation.h/.cpp` | `Delegation`, `DelegatedAuth` (RS256 JWT with optional `sub`) | +| `workspace_client.h/.cpp` | `Scopes`, `WorkspaceOptions`, `WorkspaceAuth`, `make_workspace_client`, `Workspace` facade | +| `tools/gen_calls.py` | Regenerates `call_table.cpp` from Discovery | +| `tools/check_discovery.py` | Proves the table against Discovery | + +## 3. Static caps + +| Knob | Value | +|---|---| +| parameters per call | 40 | +| query value / path value | 2048 / 512 chars | +| repeated parameter values | 100 | +| request body | 2 MiB serialized | +| `fields` selector | 1024 chars | +| pages walked / items collected | 20 (typed helpers and example: 1 to 5) / 2000 | +| delegation subject | 254 chars, one `@`, no whitespace | +| scopes per token | 40, 4096 chars joined | + +## 4. Contracts + +- Every URL comes from the table. Path values are percent-encoded; `{+x}` + placeholders keep `/`, no `..` segment anywhere. Unknown parameters and + unknown top-level body fields are rejected (`GoogleError` 400 + `INVALID_ARGUMENT`) before any network traffic. No credential: + `NotConfiguredError` (503). +- Method ids are unique per API, not across APIs (`admin.channels.stop` is in + both Directory and Reports): lookups take the API. +- Calls whose response is bytes (`drive.files.export`, media downloads; flag + `b`) are refused, as are media uploads (flag `u` rows send the JSON metadata + only). Groups Settings gets `alt=json` (default is Atom XML). +- Kind rule (`gen_calls.py`): GET is read; DELETE, `*delete*`, `trash`, + `clear`, `emptyTrash`, `signOut`, `makeAdmin`, device `action`, matter + `close` are destroy; calls that reach other people (mail send, Chat message + and space setup, Calendar event writes, Drive permission create/update, + Classroom invitations and posts, YouTube comments) are send; the three + read-only POSTs (`calendar.freebusy.query`, Sheets `getByDataFilter`, + `values.batchGetByDataFilter`) are reads; every other POST/PUT/PATCH is write. + `check_discovery.py` enforces the GET/DELETE/allowlist part. +- Credential choice (`WorkspaceAuth::from_env`): delegation subject + (option or `GOOGLE_WORKSPACE_SUBJECT`) with the key file in + `GOOGLE_APPLICATION_CREDENTIALS` -> `DelegatedAuth`; else + `GOOGLE_ACCESS_TOKEN` (a user's OAuth token, used as is); else the key file + without subject (acts as the service account, which owns no Workspace data); + else none. +- Delegation: the foundation `JwtSigner` cannot add `sub`, so `DelegatedAuth` + signs its own assertion (same wolfCrypt RS256, key parsed by the + foundation's `ServiceAccountKey`) and refreshes 60 s before expiry. + Foundation gap, not edited: `JwtSigner::sign` / `ServiceAccountAuth` have no + subject parameter. The admin must grant the service account's client id the + scopes in Admin console > Security > API controls > Domain-wide delegation. + +## 5. Scopes per service + +Workspace APIs refuse `cloud-platform`. `Scopes::all_of(api)` returns every +OAuth scope Discovery lists; `Scopes::readonly_of(api)` the `*.readonly` / +`*.metadata` subset (Groups Settings has none: its single scope stands in). +`GET /google/workspace/scopes?apis=gmail,drive&readonly=true` prints them. +Read-only scopes that cover the typed helpers: + +| API | Read-only scope (full list in `call_table.cpp`, `kApiTable`) | +|---|---| +| gmail | `gmail.readonly` (or `gmail.metadata`) | +| drive | `drive.readonly` (or `drive.metadata.readonly`) | +| calendar | `calendar.readonly` | +| sheets | `spreadsheets.readonly` | +| docs | `documents.readonly` | +| slides | `presentations.readonly` | +| forms | `forms.body.readonly`, `forms.responses.readonly` | +| tasks | `tasks.readonly` | +| chat | `chat.spaces.readonly`, `chat.messages.readonly` | +| meet | `meetings.space.readonly` | +| people | `contacts.readonly` (profile: `userinfo.profile`) | +| keep | `keep.readonly` | +| classroom | `classroom.courses.readonly` and sibling `*.readonly` | +| youtube | `youtube.readonly` | +| youtubeanalytics / youtubereporting | `yt-analytics.readonly` | +| directory | `admin.directory.user.readonly`, `.group.readonly`, ... | +| reports | `admin.reports.audit.readonly` | +| groupssettings | `apps.groups.settings` (no readonly scope exists) | +| vault | `ediscovery.readonly` | + +## 6. Example routes (`/google/workspace`) + +GET `/` (page), `/status`, `/apis`, `/calls?api=&kind=`, `/scopes?apis=&readonly=`. +POST `/call` (`api`, `id`, `params`, `body`, `confirm`), `/list` (`api`, `id`, +`params`, `maxPages` 1..5), `/delegation` (`subject`, `apis`, `readonly`; +local preview, nothing sent). Validation first (422), then dry run for +write/destroy/send unless `"confirm":true`, then the credential (503 +`google_not_configured`). With no injected client the example builds one per +API and access level from the environment (read-only scopes for reads). + +## Required APIs + +Enable these on the project (placeholder project `example-214512124`; one +`gcloud services enable` line in `src/google/APIS.md` once the owner adds them). +A disabled API answers 403 `PERMISSION_DENIED` ("has not been used"). + +- `gmail.googleapis.com`: https://console.developers.google.com/apis/api/gmail.googleapis.com/overview?project=example-214512124 +- `drive.googleapis.com`: https://console.developers.google.com/apis/api/drive.googleapis.com/overview?project=example-214512124 +- `calendar-json.googleapis.com`: https://console.developers.google.com/apis/api/calendar-json.googleapis.com/overview?project=example-214512124 +- `sheets.googleapis.com`: https://console.developers.google.com/apis/api/sheets.googleapis.com/overview?project=example-214512124 +- `docs.googleapis.com`: https://console.developers.google.com/apis/api/docs.googleapis.com/overview?project=example-214512124 +- `slides.googleapis.com`: https://console.developers.google.com/apis/api/slides.googleapis.com/overview?project=example-214512124 +- `forms.googleapis.com`: https://console.developers.google.com/apis/api/forms.googleapis.com/overview?project=example-214512124 +- `tasks.googleapis.com`: https://console.developers.google.com/apis/api/tasks.googleapis.com/overview?project=example-214512124 +- `chat.googleapis.com`: https://console.developers.google.com/apis/api/chat.googleapis.com/overview?project=example-214512124 +- `meet.googleapis.com`: https://console.developers.google.com/apis/api/meet.googleapis.com/overview?project=example-214512124 +- `people.googleapis.com`: https://console.developers.google.com/apis/api/people.googleapis.com/overview?project=example-214512124 +- `keep.googleapis.com`: https://console.developers.google.com/apis/api/keep.googleapis.com/overview?project=example-214512124 +- `classroom.googleapis.com`: https://console.developers.google.com/apis/api/classroom.googleapis.com/overview?project=example-214512124 +- `youtube.googleapis.com`: https://console.developers.google.com/apis/api/youtube.googleapis.com/overview?project=example-214512124 +- `youtubeanalytics.googleapis.com`: https://console.developers.google.com/apis/api/youtubeanalytics.googleapis.com/overview?project=example-214512124 +- `youtubereporting.googleapis.com`: https://console.developers.google.com/apis/api/youtubereporting.googleapis.com/overview?project=example-214512124 +- `admin.googleapis.com` (Directory and Reports): https://console.developers.google.com/apis/api/admin.googleapis.com/overview?project=example-214512124 +- `groupssettings.googleapis.com`: https://console.developers.google.com/apis/api/groupssettings.googleapis.com/overview?project=example-214512124 +- `vault.googleapis.com`: https://console.developers.google.com/apis/api/vault.googleapis.com/overview?project=example-214512124 + +## Sources + +- Discovery documents, fetched 2026-10-25 (directory: + `https://discovery.googleapis.com/discovery/v1/apis`; the URLs are in + `tools/gen_calls.py`). Revisions: gmail 20261019, drive 20261020, calendar + 20261021, sheets 20261019, docs 20261019, slides 20261019, forms 20261022, + tasks 20261020, chat 20261019, meet 20261020, people 20261021, keep + 20261019, classroom 20261020, youtube 20261022, youtubeAnalytics 20261021, + youtubereporting 20261021, directory 20261021, reports 20261021, + groupssettings 20220614, vault 20261015. +- OAuth 2.0 for service accounts with domain-wide delegation (RFC 7523 JWT + bearer, `sub` claim). + +## Verified against discovery + +`python3 -I src/google/workspace/tools/check_discovery.py`, run 2026-10-25: +`discovery ok: 20 apis, 714 calls, 201 request schemas`. Checks per row: HTTP +method, path, parameter names, location, required, number / boolean / repeated, +request schema, its top-level fields, items key is an array, media flags, base +URL, scope list; every Discovery method has a row; GET is read, DELETE is +destroy, non-GET reads are on the allowlist. + +## Verified live + +Project `lisa-448004`, service account, reads only, 2026-10-25 +(`make google-live`, opt-in tests `workspace_live.*`): + +- Token with Workspace read-only scopes and no `sub`: 200 (Google issues it). +- Same SA with `sub=nobody@example.com`: token endpoint 401 `invalid_grant` + "Invalid email or User ID". This proves the `sub` claim reaches Google; a + real user without a domain-wide delegation grant would answer + `unauthorized_client`. A successful delegated call is Unverified (no + Workspace domain with a delegation grant is available). +- `cloud-platform` bearer (sa-token) against 19 services: 403 + PERMISSION_DENIED "Request had insufficient authentication scopes" (Directory + 403 API not enabled). +- Scoped SA token, no `sub`: 403 PERMISSION_DENIED **API NOT ENABLED** on + project 474586702855 for Drive, Calendar, Tasks, Gmail, Sheets, Docs, Slides, + Forms, Chat, Meet, Keep, Classroom, YouTube Data, YouTube Reporting, Vault, + Admin SDK (Directory and Reports), Groups Settings. People: 403 "requires + scope profile". YouTube Analytics was not probed (needs a channel id). + Enable these in the console to see the real 401/403/empty answers. + +## Unverified + +- Any successful call: no Workspace data is reachable from the test project. + Response parsing in the typed helpers (items keys) is checked against the + Discovery response schemas only. +- Delegated token success, Workspace error shapes for missing delegation + (`unauthorized_client`) and per-call scope sufficiency. +- Writes, deletes and sends (by design never run live). +- `list()` pagination across several pages (no list returned data). + +## Gaps + +- Media upload and download (bytes) are not implemented: flagged rows `u` + send metadata only, rows `b` are refused (`src/google/workspace/calls.h`). +- Batch HTTP endpoints, push-notification channels (`watch`/`stop`) are + callable as ordinary rows but no receiver exists. +- Foundation: `ServiceAccountAuth` / `JwtSigner` lack a subject parameter + (`src/google/service_account.h`); worked around in `delegation.cpp`. +- Services to add to `api_catalog.*` / `APIS.md` by the owner: the 19 service + names under Required APIs. diff --git a/src/google/workspace/call_table.cpp b/src/google/workspace/call_table.cpp new file mode 100644 index 0000000..0c66c5a --- /dev/null +++ b/src/google/workspace/call_table.cpp @@ -0,0 +1,960 @@ +// GENERATED by tools/gen_calls.py from Google Discovery documents. Do not edit. +// Checked against Google by tools/check_discovery.py. +#include "google/workspace/calls.h" + +namespace molo::google::workspace { + +// APIS-BEGIN +const ApiSpec kApiTable[] = { + {"gmail", "gmail:v1", "https://gmail.googleapis.com/$discovery/rest?version=v1", "https://gmail.googleapis.com", "gmail.googleapis.com", "https://www.googleapis.com/auth/gmail.settings.basic https://www.googleapis.com/auth/gmail.send https://www.googleapis.com/auth/gmail.settings.sharing https://www.googleapis.com/auth/gmail.insert https://www.googleapis.com/auth/gmail.addons.current.message.action https://www.googleapis.com/auth/gmail.modify https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/gmail.addons.current.action.compose https://www.googleapis.com/auth/gmail.addons.current.message.metadata https://mail.google.com/ https://www.googleapis.com/auth/gmail.compose https://www.googleapis.com/auth/gmail.labels https://www.googleapis.com/auth/gmail.metadata https://www.googleapis.com/auth/gmail.addons.current.message.readonly", "https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/gmail.addons.current.message.metadata https://www.googleapis.com/auth/gmail.metadata https://www.googleapis.com/auth/gmail.addons.current.message.readonly", "20261019"}, + {"drive", "drive:v3", "https://www.googleapis.com/discovery/v1/apis/drive/v3/rest", "https://www.googleapis.com/drive/v3", "drive.googleapis.com", "https://www.googleapis.com/auth/drive.appdata https://www.googleapis.com/auth/drive.metadata https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.meet.readonly https://www.googleapis.com/auth/drive.scripts https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.apps.readonly https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/drive.photos.readonly", "https://www.googleapis.com/auth/drive.metadata https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/drive.meet.readonly https://www.googleapis.com/auth/drive.apps.readonly https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/drive.photos.readonly", "20261020"}, + {"calendar", "calendar:v3", "https://calendar-json.googleapis.com/$discovery/rest?version=v3", "https://www.googleapis.com/calendar/v3", "calendar-json.googleapis.com", "https://www.googleapis.com/auth/calendar.events.readonly https://www.googleapis.com/auth/calendar.events.owned.readonly https://www.googleapis.com/auth/calendar.calendarlist https://www.googleapis.com/auth/calendar.settings.readonly https://www.googleapis.com/auth/calendar.calendars.readonly https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/calendar.calendars https://www.googleapis.com/auth/calendar.events.owned https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.events https://www.googleapis.com/auth/calendar.calendarlist.readonly https://www.googleapis.com/auth/calendar.settings https://www.googleapis.com/auth/calendar.app.created https://www.googleapis.com/auth/calendar.freebusy https://www.googleapis.com/auth/calendar.acls.readonly https://www.googleapis.com/auth/calendar.events.freebusy https://www.googleapis.com/auth/calendar.acls https://www.googleapis.com/auth/calendar.events.public.readonly", "https://www.googleapis.com/auth/calendar.events.readonly https://www.googleapis.com/auth/calendar.events.owned.readonly https://www.googleapis.com/auth/calendar.settings.readonly https://www.googleapis.com/auth/calendar.calendars.readonly https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/calendar.calendarlist.readonly https://www.googleapis.com/auth/calendar.acls.readonly https://www.googleapis.com/auth/calendar.events.public.readonly", "20261021"}, + {"sheets", "sheets:v4", "https://sheets.googleapis.com/$discovery/rest?version=v4", "https://sheets.googleapis.com", "sheets.googleapis.com", "https://www.googleapis.com/auth/spreadsheets.readonly https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/spreadsheets.readonly https://www.googleapis.com/auth/drive.readonly", "20261019"}, + {"docs", "docs:v1", "https://docs.googleapis.com/$discovery/rest?version=v1", "https://docs.googleapis.com", "docs.googleapis.com", "https://www.googleapis.com/auth/documents.readonly https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/documents https://www.googleapis.com/auth/drive.readonly", "https://www.googleapis.com/auth/documents.readonly https://www.googleapis.com/auth/drive.readonly", "20261019"}, + {"slides", "slides:v1", "https://slides.googleapis.com/$discovery/rest?version=v1", "https://slides.googleapis.com", "slides.googleapis.com", "https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/presentations.readonly https://www.googleapis.com/auth/spreadsheets.readonly https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/presentations https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/presentations.readonly https://www.googleapis.com/auth/spreadsheets.readonly https://www.googleapis.com/auth/drive.readonly", "20261019"}, + {"forms", "forms:v1", "https://forms.googleapis.com/$discovery/rest?version=v1", "https://forms.googleapis.com", "forms.googleapis.com", "https://www.googleapis.com/auth/forms.responses.readonly https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/forms.body https://www.googleapis.com/auth/forms.body.readonly https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/forms.responses.readonly https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/forms.body.readonly", "20261022"}, + {"tasks", "tasks:v1", "https://tasks.googleapis.com/$discovery/rest?version=v1", "https://tasks.googleapis.com", "tasks.googleapis.com", "https://www.googleapis.com/auth/tasks https://www.googleapis.com/auth/tasks.readonly", "https://www.googleapis.com/auth/tasks.readonly", "20261020"}, + {"chat", "chat:v1", "https://chat.googleapis.com/$discovery/rest?version=v1", "https://chat.googleapis.com", "chat.googleapis.com", "https://www.googleapis.com/auth/chat.app.spaces.readonly https://www.googleapis.com/auth/chat.app.spaces https://www.googleapis.com/auth/chat.app.messages.readonly https://www.googleapis.com/auth/chat.customemojis https://www.googleapis.com/auth/chat.memberships.readonly https://www.googleapis.com/auth/chat.memberships.app https://www.googleapis.com/auth/chat.spaces https://www.googleapis.com/auth/chat.users.readstate https://www.googleapis.com/auth/chat.messages.reactions.readonly https://www.googleapis.com/auth/chat.memberships https://www.googleapis.com/auth/chat.app.memberships https://www.googleapis.com/auth/chat.users.availability https://www.googleapis.com/auth/chat.users.spacesettings https://www.googleapis.com/auth/chat.spaces.pins https://www.googleapis.com/auth/chat.messages.reactions.create https://www.googleapis.com/auth/chat.app.memberships.readonly https://www.googleapis.com/auth/chat.users.sections.readonly https://www.googleapis.com/auth/chat.admin.delete https://www.googleapis.com/auth/chat.app.all.spaces.readonly https://www.googleapis.com/auth/chat.app.all.messages.readonly https://www.googleapis.com/auth/chat.messages.readonly https://www.googleapis.com/auth/chat.spaces.readonly https://www.googleapis.com/auth/chat.messages.reactions https://www.googleapis.com/auth/chat.messages.create https://www.googleapis.com/auth/chat.app.delete https://www.googleapis.com/auth/chat.messages https://www.googleapis.com/auth/chat.spaces.pins.readonly https://www.googleapis.com/auth/chat.app.all.memberships.readonly https://www.googleapis.com/auth/chat.users.readstate.readonly https://www.googleapis.com/auth/chat.users.availability.readonly https://www.googleapis.com/auth/chat.app.spaces.create https://www.googleapis.com/auth/chat.customemojis.readonly https://www.googleapis.com/auth/chat.admin.spaces https://www.googleapis.com/auth/chat.admin.spaces.readonly https://www.googleapis.com/auth/chat.admin.memberships https://www.googleapis.com/auth/chat.delete https://www.googleapis.com/auth/chat.users.sections https://www.googleapis.com/auth/chat.bot https://www.googleapis.com/auth/chat.spaces.create https://www.googleapis.com/auth/chat.import https://www.googleapis.com/auth/chat.admin.memberships.readonly", "https://www.googleapis.com/auth/chat.app.spaces.readonly https://www.googleapis.com/auth/chat.app.messages.readonly https://www.googleapis.com/auth/chat.memberships.readonly https://www.googleapis.com/auth/chat.messages.reactions.readonly https://www.googleapis.com/auth/chat.app.memberships.readonly https://www.googleapis.com/auth/chat.users.sections.readonly https://www.googleapis.com/auth/chat.app.all.spaces.readonly https://www.googleapis.com/auth/chat.app.all.messages.readonly https://www.googleapis.com/auth/chat.messages.readonly https://www.googleapis.com/auth/chat.spaces.readonly https://www.googleapis.com/auth/chat.spaces.pins.readonly https://www.googleapis.com/auth/chat.app.all.memberships.readonly https://www.googleapis.com/auth/chat.users.readstate.readonly https://www.googleapis.com/auth/chat.users.availability.readonly https://www.googleapis.com/auth/chat.customemojis.readonly https://www.googleapis.com/auth/chat.admin.spaces.readonly https://www.googleapis.com/auth/chat.admin.memberships.readonly", "20261019"}, + {"meet", "meet:v2", "https://meet.googleapis.com/$discovery/rest?version=v2", "https://meet.googleapis.com", "meet.googleapis.com", "https://www.googleapis.com/auth/meetings.space.created https://www.googleapis.com/auth/meetings.space.readonly https://www.googleapis.com/auth/meetings.space.settings", "https://www.googleapis.com/auth/meetings.space.readonly", "20261020"}, + {"people", "people:v1", "https://people.googleapis.com/$discovery/rest?version=v1", "https://people.googleapis.com", "people.googleapis.com", "https://www.googleapis.com/auth/contacts.other.readonly https://www.googleapis.com/auth/user.phonenumbers.read https://www.googleapis.com/auth/user.birthday.read https://www.googleapis.com/auth/user.addresses.read https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/contacts https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/user.organization.read https://www.googleapis.com/auth/contacts.readonly https://www.googleapis.com/auth/user.gender.read https://www.googleapis.com/auth/user.emails.read https://www.googleapis.com/auth/directory.readonly", "https://www.googleapis.com/auth/contacts.other.readonly https://www.googleapis.com/auth/contacts.readonly https://www.googleapis.com/auth/directory.readonly", "20261021"}, + {"keep", "keep:v1", "https://keep.googleapis.com/$discovery/rest?version=v1", "https://keep.googleapis.com", "keep.googleapis.com", "https://www.googleapis.com/auth/keep https://www.googleapis.com/auth/keep.readonly", "https://www.googleapis.com/auth/keep.readonly", "20261019"}, + {"classroom", "classroom:v1", "https://classroom.googleapis.com/$discovery/rest?version=v1", "https://classroom.googleapis.com", "classroom.googleapis.com", "https://www.googleapis.com/auth/classroom.student-submissions.me.readonly https://www.googleapis.com/auth/classroom.profile.emails https://www.googleapis.com/auth/classroom.student-submissions.students.readonly https://www.googleapis.com/auth/classroom.rosters https://www.googleapis.com/auth/classroom.coursework.me https://www.googleapis.com/auth/classroom.courses https://www.googleapis.com/auth/classroom.announcements https://www.googleapis.com/auth/classroom.guardianlinks.students.readonly https://www.googleapis.com/auth/classroom.coursework.students.readonly https://www.googleapis.com/auth/classroom.guardianlinks.me.readonly https://www.googleapis.com/auth/classroom.courses.readonly https://www.googleapis.com/auth/classroom.push-notifications https://www.googleapis.com/auth/classroom.topics https://www.googleapis.com/auth/classroom.courseworkmaterials.readonly https://www.googleapis.com/auth/classroom.addons.teacher https://www.googleapis.com/auth/classroom.profile.photos https://www.googleapis.com/auth/classroom.coursework.me.readonly https://www.googleapis.com/auth/classroom.announcements.readonly https://www.googleapis.com/auth/classroom.addons.student https://www.googleapis.com/auth/classroom.topics.readonly https://www.googleapis.com/auth/classroom.guardianlinks.students https://www.googleapis.com/auth/classroom.coursework.students https://www.googleapis.com/auth/classroom.rosters.readonly https://www.googleapis.com/auth/classroom.courseworkmaterials", "https://www.googleapis.com/auth/classroom.student-submissions.me.readonly https://www.googleapis.com/auth/classroom.student-submissions.students.readonly https://www.googleapis.com/auth/classroom.guardianlinks.students.readonly https://www.googleapis.com/auth/classroom.coursework.students.readonly https://www.googleapis.com/auth/classroom.guardianlinks.me.readonly https://www.googleapis.com/auth/classroom.courses.readonly https://www.googleapis.com/auth/classroom.courseworkmaterials.readonly https://www.googleapis.com/auth/classroom.coursework.me.readonly https://www.googleapis.com/auth/classroom.announcements.readonly https://www.googleapis.com/auth/classroom.topics.readonly https://www.googleapis.com/auth/classroom.rosters.readonly", "20261020"}, + {"youtube", "youtube:v3", "https://youtube.googleapis.com/$discovery/rest?version=v3", "https://youtube.googleapis.com", "youtube.googleapis.com", "https://www.googleapis.com/auth/youtube.upload https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.force-ssl https://www.googleapis.com/auth/youtube.channel-memberships.creator https://www.googleapis.com/auth/youtubepartner-channel-audit https://www.googleapis.com/auth/youtube.readonly https://www.googleapis.com/auth/youtubepartner", "https://www.googleapis.com/auth/youtube.readonly", "20261022"}, + {"youtubeanalytics", "youtubeAnalytics:v2", "https://youtubeanalytics.googleapis.com/$discovery/rest?version=v2", "https://youtubeanalytics.googleapis.com", "youtubeanalytics.googleapis.com", "https://www.googleapis.com/auth/yt-analytics-monetary.readonly https://www.googleapis.com/auth/youtube.readonly https://www.googleapis.com/auth/yt-analytics.readonly https://www.googleapis.com/auth/youtubepartner https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/yt-analytics-monetary.readonly https://www.googleapis.com/auth/youtube.readonly https://www.googleapis.com/auth/yt-analytics.readonly", "20261021"}, + {"youtubereporting", "youtubereporting:v1", "https://youtubereporting.googleapis.com/$discovery/rest?version=v1", "https://youtubereporting.googleapis.com", "youtubereporting.googleapis.com", "https://www.googleapis.com/auth/yt-analytics-monetary.readonly https://www.googleapis.com/auth/yt-analytics.readonly", "https://www.googleapis.com/auth/yt-analytics-monetary.readonly https://www.googleapis.com/auth/yt-analytics.readonly", "20261021"}, + {"directory", "admin:directory_v1", "https://admin.googleapis.com/$discovery/rest?version=directory_v1", "https://admin.googleapis.com", "admin.googleapis.com", "https://www.googleapis.com/auth/admin.directory.orgunit https://www.googleapis.com/auth/admin.directory.device.mobile.action https://www.googleapis.com/auth/admin.directory.resource.calendar https://www.googleapis.com/auth/admin.directory.customer https://www.googleapis.com/auth/admin.directory.group https://www.googleapis.com/auth/admin.directory.userschema.readonly https://www.googleapis.com/auth/admin.directory.group.readonly https://www.googleapis.com/auth/admin.directory.device.mobile.readonly https://www.googleapis.com/auth/admin.directory.customer.readonly https://www.googleapis.com/auth/admin.directory.domain https://www.googleapis.com/auth/admin.directory.rolemanagement https://www.googleapis.com/auth/admin.directory.user.alias https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/admin.directory.user.readonly https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly https://www.googleapis.com/auth/admin.directory.group.member https://www.googleapis.com/auth/admin.directory.user.security https://www.googleapis.com/auth/admin.chrome.printers https://www.googleapis.com/auth/admin.directory.user https://www.googleapis.com/auth/admin.directory.user.alias.readonly https://www.googleapis.com/auth/admin.directory.userschema https://www.googleapis.com/auth/admin.chrome.printers.readonly https://www.googleapis.com/auth/admin.directory.device.chromeos https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly https://www.googleapis.com/auth/admin.directory.group.member.readonly https://www.googleapis.com/auth/admin.directory.orgunit.readonly https://www.googleapis.com/auth/admin.directory.device.mobile https://www.googleapis.com/auth/admin.directory.domain.readonly", "https://www.googleapis.com/auth/admin.directory.userschema.readonly https://www.googleapis.com/auth/admin.directory.group.readonly https://www.googleapis.com/auth/admin.directory.device.mobile.readonly https://www.googleapis.com/auth/admin.directory.customer.readonly https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly https://www.googleapis.com/auth/admin.directory.user.readonly https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly https://www.googleapis.com/auth/admin.directory.user.alias.readonly https://www.googleapis.com/auth/admin.chrome.printers.readonly https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly https://www.googleapis.com/auth/admin.directory.group.member.readonly https://www.googleapis.com/auth/admin.directory.orgunit.readonly https://www.googleapis.com/auth/admin.directory.domain.readonly", "20261021"}, + {"reports", "admin:reports_v1", "https://admin.googleapis.com/$discovery/rest?version=reports_v1", "https://admin.googleapis.com", "admin.googleapis.com", "https://www.googleapis.com/auth/admin.reports.audit.readonly https://www.googleapis.com/auth/admin.reports.usage.readonly", "https://www.googleapis.com/auth/admin.reports.audit.readonly https://www.googleapis.com/auth/admin.reports.usage.readonly", "20261021"}, + {"groupssettings", "groupssettings:v1", "https://groupssettings.googleapis.com/$discovery/rest?version=v1", "https://www.googleapis.com/groups/v1/groups", "groupssettings.googleapis.com", "https://www.googleapis.com/auth/apps.groups.settings", "", "20220614"}, + {"vault", "vault:v1", "https://vault.googleapis.com/$discovery/rest?version=v1", "https://vault.googleapis.com", "vault.googleapis.com", "https://www.googleapis.com/auth/ediscovery https://www.googleapis.com/auth/ediscovery.readonly", "https://www.googleapis.com/auth/ediscovery.readonly", "20261015"}, +}; +// APIS-END +const std::size_t kApiTableSize = sizeof(kApiTable) / sizeof(kApiTable[0]); + +// CALLS-BEGIN (one row per Discovery method; parsed by tools/check_discovery.py) +const CallSpec kCallTable[] = { + {"gmail.users.drafts.create", "gmail", "POST", "gmail/v1/users/{userId}/drafts", "userId@", "Draft", "", "w", "u"}, + {"gmail.users.drafts.delete", "gmail", "DELETE", "gmail/v1/users/{userId}/drafts/{id}", "id@,userId@", "", "", "d", ""}, + {"gmail.users.drafts.get", "gmail", "GET", "gmail/v1/users/{userId}/drafts/{id}", "id@,userId@,format", "", "", "r", ""}, + {"gmail.users.drafts.list", "gmail", "GET", "gmail/v1/users/{userId}/drafts", "userId@,includeSpamTrash?,maxResults#,pageToken,q", "", "drafts", "r", ""}, + {"gmail.users.drafts.send", "gmail", "POST", "gmail/v1/users/{userId}/drafts/send", "userId@", "Draft", "", "s", "u"}, + {"gmail.users.drafts.update", "gmail", "PUT", "gmail/v1/users/{userId}/drafts/{id}", "id@,userId@", "Draft", "", "w", "u"}, + {"gmail.users.getProfile", "gmail", "GET", "gmail/v1/users/{userId}/profile", "userId@", "", "", "r", ""}, + {"gmail.users.history.list", "gmail", "GET", "gmail/v1/users/{userId}/history", "userId@,historyTypes*,labelId,maxResults#,pageToken,startHistoryId", "", "history", "r", ""}, + {"gmail.users.labels.create", "gmail", "POST", "gmail/v1/users/{userId}/labels", "userId@", "Label", "", "w", ""}, + {"gmail.users.labels.delete", "gmail", "DELETE", "gmail/v1/users/{userId}/labels/{id}", "userId@,id@", "", "", "d", ""}, + {"gmail.users.labels.get", "gmail", "GET", "gmail/v1/users/{userId}/labels/{id}", "id@,userId@", "", "", "r", ""}, + {"gmail.users.labels.list", "gmail", "GET", "gmail/v1/users/{userId}/labels", "userId@", "", "", "r", ""}, + {"gmail.users.labels.patch", "gmail", "PATCH", "gmail/v1/users/{userId}/labels/{id}", "id@,userId@", "Label", "", "w", ""}, + {"gmail.users.labels.update", "gmail", "PUT", "gmail/v1/users/{userId}/labels/{id}", "userId@,id@", "Label", "", "w", ""}, + {"gmail.users.messages.attachments.get", "gmail", "GET", "gmail/v1/users/{userId}/messages/{messageId}/attachments/{id}", "messageId@,userId@,id@", "", "", "r", ""}, + {"gmail.users.messages.batchDelete", "gmail", "POST", "gmail/v1/users/{userId}/messages/batchDelete", "userId@", "BatchDeleteMessagesRequest", "", "d", ""}, + {"gmail.users.messages.batchModify", "gmail", "POST", "gmail/v1/users/{userId}/messages/batchModify", "userId@", "BatchModifyMessagesRequest", "", "w", ""}, + {"gmail.users.messages.delete", "gmail", "DELETE", "gmail/v1/users/{userId}/messages/{id}", "id@,userId@", "", "", "d", ""}, + {"gmail.users.messages.get", "gmail", "GET", "gmail/v1/users/{userId}/messages/{id}", "userId@,id@,format,metadataHeaders*", "", "", "r", ""}, + {"gmail.users.messages.import", "gmail", "POST", "gmail/v1/users/{userId}/messages/import", "userId@,deleted?,internalDateSource,neverMarkSpam?,processForCalendar?", "Message", "", "w", "u"}, + {"gmail.users.messages.insert", "gmail", "POST", "gmail/v1/users/{userId}/messages", "userId@,deleted?,internalDateSource", "Message", "", "w", "u"}, + {"gmail.users.messages.list", "gmail", "GET", "gmail/v1/users/{userId}/messages", "userId@,includeSpamTrash?,labelIds*,maxResults#,pageToken,q", "", "messages", "r", ""}, + {"gmail.users.messages.modify", "gmail", "POST", "gmail/v1/users/{userId}/messages/{id}/modify", "userId@,id@", "ModifyMessageRequest", "", "w", ""}, + {"gmail.users.messages.send", "gmail", "POST", "gmail/v1/users/{userId}/messages/send", "userId@", "Message", "", "s", "u"}, + {"gmail.users.messages.trash", "gmail", "POST", "gmail/v1/users/{userId}/messages/{id}/trash", "id@,userId@", "", "", "d", ""}, + {"gmail.users.messages.untrash", "gmail", "POST", "gmail/v1/users/{userId}/messages/{id}/untrash", "id@,userId@", "", "", "w", ""}, + {"gmail.users.settings.cse.identities.create", "gmail", "POST", "gmail/v1/users/{userId}/settings/cse/identities", "userId@", "CseIdentity", "", "w", ""}, + {"gmail.users.settings.cse.identities.delete", "gmail", "DELETE", "gmail/v1/users/{userId}/settings/cse/identities/{cseEmailAddress}", "userId@,cseEmailAddress@", "", "", "d", ""}, + {"gmail.users.settings.cse.identities.get", "gmail", "GET", "gmail/v1/users/{userId}/settings/cse/identities/{cseEmailAddress}", "cseEmailAddress@,userId@", "", "", "r", ""}, + {"gmail.users.settings.cse.identities.list", "gmail", "GET", "gmail/v1/users/{userId}/settings/cse/identities", "userId@,pageSize#,pageToken", "", "cseIdentities", "r", ""}, + {"gmail.users.settings.cse.identities.patch", "gmail", "PATCH", "gmail/v1/users/{userId}/settings/cse/identities/{emailAddress}", "userId@,emailAddress@", "CseIdentity", "", "w", ""}, + {"gmail.users.settings.cse.keypairs.create", "gmail", "POST", "gmail/v1/users/{userId}/settings/cse/keypairs", "userId@,chainValidation", "CseKeyPair", "", "w", ""}, + {"gmail.users.settings.cse.keypairs.disable", "gmail", "POST", "gmail/v1/users/{userId}/settings/cse/keypairs/{keyPairId}:disable", "userId@,keyPairId@", "DisableCseKeyPairRequest", "", "w", ""}, + {"gmail.users.settings.cse.keypairs.enable", "gmail", "POST", "gmail/v1/users/{userId}/settings/cse/keypairs/{keyPairId}:enable", "userId@,keyPairId@", "EnableCseKeyPairRequest", "", "w", ""}, + {"gmail.users.settings.cse.keypairs.get", "gmail", "GET", "gmail/v1/users/{userId}/settings/cse/keypairs/{keyPairId}", "keyPairId@,userId@", "", "", "r", ""}, + {"gmail.users.settings.cse.keypairs.list", "gmail", "GET", "gmail/v1/users/{userId}/settings/cse/keypairs", "userId@,pageSize#,pageToken", "", "cseKeyPairs", "r", ""}, + {"gmail.users.settings.cse.keypairs.obliterate", "gmail", "POST", "gmail/v1/users/{userId}/settings/cse/keypairs/{keyPairId}:obliterate", "keyPairId@,userId@", "ObliterateCseKeyPairRequest", "", "w", ""}, + {"gmail.users.settings.delegates.create", "gmail", "POST", "gmail/v1/users/{userId}/settings/delegates", "userId@", "Delegate", "", "w", ""}, + {"gmail.users.settings.delegates.delete", "gmail", "DELETE", "gmail/v1/users/{userId}/settings/delegates/{delegateEmail}", "delegateEmail@,userId@", "", "", "d", ""}, + {"gmail.users.settings.delegates.get", "gmail", "GET", "gmail/v1/users/{userId}/settings/delegates/{delegateEmail}", "userId@,delegateEmail@", "", "", "r", ""}, + {"gmail.users.settings.delegates.list", "gmail", "GET", "gmail/v1/users/{userId}/settings/delegates", "userId@", "", "", "r", ""}, + {"gmail.users.settings.filters.create", "gmail", "POST", "gmail/v1/users/{userId}/settings/filters", "userId@", "Filter", "", "w", ""}, + {"gmail.users.settings.filters.delete", "gmail", "DELETE", "gmail/v1/users/{userId}/settings/filters/{id}", "id@,userId@", "", "", "d", ""}, + {"gmail.users.settings.filters.get", "gmail", "GET", "gmail/v1/users/{userId}/settings/filters/{id}", "userId@,id@", "", "", "r", ""}, + {"gmail.users.settings.filters.list", "gmail", "GET", "gmail/v1/users/{userId}/settings/filters", "userId@", "", "", "r", ""}, + {"gmail.users.settings.forwardingAddresses.create", "gmail", "POST", "gmail/v1/users/{userId}/settings/forwardingAddresses", "userId@", "ForwardingAddress", "", "w", ""}, + {"gmail.users.settings.forwardingAddresses.delete", "gmail", "DELETE", "gmail/v1/users/{userId}/settings/forwardingAddresses/{forwardingEmail}", "userId@,forwardingEmail@", "", "", "d", ""}, + {"gmail.users.settings.forwardingAddresses.get", "gmail", "GET", "gmail/v1/users/{userId}/settings/forwardingAddresses/{forwardingEmail}", "userId@,forwardingEmail@", "", "", "r", ""}, + {"gmail.users.settings.forwardingAddresses.list", "gmail", "GET", "gmail/v1/users/{userId}/settings/forwardingAddresses", "userId@", "", "", "r", ""}, + {"gmail.users.settings.getAutoForwarding", "gmail", "GET", "gmail/v1/users/{userId}/settings/autoForwarding", "userId@", "", "", "r", ""}, + {"gmail.users.settings.getImap", "gmail", "GET", "gmail/v1/users/{userId}/settings/imap", "userId@", "", "", "r", ""}, + {"gmail.users.settings.getLanguage", "gmail", "GET", "gmail/v1/users/{userId}/settings/language", "userId@", "", "", "r", ""}, + {"gmail.users.settings.getPop", "gmail", "GET", "gmail/v1/users/{userId}/settings/pop", "userId@", "", "", "r", ""}, + {"gmail.users.settings.getVacation", "gmail", "GET", "gmail/v1/users/{userId}/settings/vacation", "userId@", "", "", "r", ""}, + {"gmail.users.settings.sendAs.create", "gmail", "POST", "gmail/v1/users/{userId}/settings/sendAs", "userId@", "SendAs", "", "w", ""}, + {"gmail.users.settings.sendAs.delete", "gmail", "DELETE", "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}", "sendAsEmail@,userId@", "", "", "d", ""}, + {"gmail.users.settings.sendAs.get", "gmail", "GET", "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}", "userId@,sendAsEmail@", "", "", "r", ""}, + {"gmail.users.settings.sendAs.list", "gmail", "GET", "gmail/v1/users/{userId}/settings/sendAs", "userId@", "", "", "r", ""}, + {"gmail.users.settings.sendAs.patch", "gmail", "PATCH", "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}", "sendAsEmail@,userId@", "SendAs", "", "w", ""}, + {"gmail.users.settings.sendAs.smimeInfo.delete", "gmail", "DELETE", "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}/smimeInfo/{id}", "id@,sendAsEmail@,userId@", "", "", "d", ""}, + {"gmail.users.settings.sendAs.smimeInfo.get", "gmail", "GET", "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}/smimeInfo/{id}", "userId@,id@,sendAsEmail@", "", "", "r", ""}, + {"gmail.users.settings.sendAs.smimeInfo.insert", "gmail", "POST", "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}/smimeInfo", "sendAsEmail@,userId@", "SmimeInfo", "", "w", ""}, + {"gmail.users.settings.sendAs.smimeInfo.list", "gmail", "GET", "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}/smimeInfo", "userId@,sendAsEmail@", "", "", "r", ""}, + {"gmail.users.settings.sendAs.smimeInfo.setDefault", "gmail", "POST", "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}/smimeInfo/{id}/setDefault", "sendAsEmail@,id@,userId@", "", "", "w", ""}, + {"gmail.users.settings.sendAs.update", "gmail", "PUT", "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}", "sendAsEmail@,userId@", "SendAs", "", "w", ""}, + {"gmail.users.settings.sendAs.verify", "gmail", "POST", "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}/verify", "sendAsEmail@,userId@", "", "", "w", ""}, + {"gmail.users.settings.updateAutoForwarding", "gmail", "PUT", "gmail/v1/users/{userId}/settings/autoForwarding", "userId@", "AutoForwarding", "", "w", ""}, + {"gmail.users.settings.updateImap", "gmail", "PUT", "gmail/v1/users/{userId}/settings/imap", "userId@", "ImapSettings", "", "w", ""}, + {"gmail.users.settings.updateLanguage", "gmail", "PUT", "gmail/v1/users/{userId}/settings/language", "userId@", "LanguageSettings", "", "w", ""}, + {"gmail.users.settings.updatePop", "gmail", "PUT", "gmail/v1/users/{userId}/settings/pop", "userId@", "PopSettings", "", "w", ""}, + {"gmail.users.settings.updateVacation", "gmail", "PUT", "gmail/v1/users/{userId}/settings/vacation", "userId@", "VacationSettings", "", "w", ""}, + {"gmail.users.stop", "gmail", "POST", "gmail/v1/users/{userId}/stop", "userId@", "", "", "w", ""}, + {"gmail.users.threads.delete", "gmail", "DELETE", "gmail/v1/users/{userId}/threads/{id}", "userId@,id@", "", "", "d", ""}, + {"gmail.users.threads.get", "gmail", "GET", "gmail/v1/users/{userId}/threads/{id}", "userId@,id@,format,metadataHeaders*", "", "", "r", ""}, + {"gmail.users.threads.list", "gmail", "GET", "gmail/v1/users/{userId}/threads", "userId@,includeSpamTrash?,labelIds*,maxResults#,pageToken,q", "", "threads", "r", ""}, + {"gmail.users.threads.modify", "gmail", "POST", "gmail/v1/users/{userId}/threads/{id}/modify", "userId@,id@", "ModifyThreadRequest", "", "w", ""}, + {"gmail.users.threads.trash", "gmail", "POST", "gmail/v1/users/{userId}/threads/{id}/trash", "userId@,id@", "", "", "d", ""}, + {"gmail.users.threads.untrash", "gmail", "POST", "gmail/v1/users/{userId}/threads/{id}/untrash", "id@,userId@", "", "", "w", ""}, + {"gmail.users.watch", "gmail", "POST", "gmail/v1/users/{userId}/watch", "userId@", "WatchRequest", "", "w", ""}, + {"drive.about.get", "drive", "GET", "about", "", "", "", "r", ""}, + {"drive.accessproposals.get", "drive", "GET", "files/{fileId}/accessproposals/{proposalId}", "fileId@,proposalId@", "", "", "r", ""}, + {"drive.accessproposals.list", "drive", "GET", "files/{fileId}/accessproposals", "fileId@,pageSize#,pageToken", "", "accessProposals", "r", ""}, + {"drive.accessproposals.resolve", "drive", "POST", "files/{fileId}/accessproposals/{proposalId}:resolve", "fileId@,proposalId@", "ResolveAccessProposalRequest", "", "w", ""}, + {"drive.approvals.approve", "drive", "POST", "files/{fileId}/approvals/{approvalId}:approve", "approvalId@,fileId@", "ApproveApprovalRequest", "", "w", ""}, + {"drive.approvals.cancel", "drive", "POST", "files/{fileId}/approvals/{approvalId}:cancel", "approvalId@,fileId@", "CancelApprovalRequest", "", "w", ""}, + {"drive.approvals.comment", "drive", "POST", "files/{fileId}/approvals/{approvalId}:comment", "fileId@,approvalId@", "CommentApprovalRequest", "", "w", ""}, + {"drive.approvals.decline", "drive", "POST", "files/{fileId}/approvals/{approvalId}:decline", "fileId@,approvalId@", "DeclineApprovalRequest", "", "w", ""}, + {"drive.approvals.get", "drive", "GET", "files/{fileId}/approvals/{approvalId}", "approvalId@,fileId@", "", "", "r", ""}, + {"drive.approvals.list", "drive", "GET", "files/{fileId}/approvals", "fileId@,pageSize#,pageToken", "", "items", "r", ""}, + {"drive.approvals.reassign", "drive", "POST", "files/{fileId}/approvals/{approvalId}:reassign", "approvalId@,fileId@", "ReassignApprovalRequest", "", "w", ""}, + {"drive.approvals.start", "drive", "POST", "files/{fileId}/approvals:start", "fileId@", "StartApprovalRequest", "", "w", ""}, + {"drive.apps.get", "drive", "GET", "apps/{appId}", "appId@", "", "", "r", ""}, + {"drive.apps.list", "drive", "GET", "apps", "appFilterExtensions,appFilterMimeTypes,languageCode", "", "", "r", ""}, + {"drive.changes.getStartPageToken", "drive", "GET", "changes/startPageToken", "driveId,supportsAllDrives?,supportsTeamDrives?,teamDriveId", "", "", "r", ""}, + {"drive.changes.list", "drive", "GET", "changes", "driveId,includeCorpusRemovals?,includeItemsFromAllDrives?,includeLabels,includePermissionsForView,includeRemoved?,includeTeamDriveItems?,pageSize#,pageToken!,restrictToMyDrive?,spaces,supportsAllDrives?,supportsTeamDrives?,teamDriveId", "", "changes", "r", ""}, + {"drive.changes.watch", "drive", "POST", "changes/watch", "driveId,includeCorpusRemovals?,includeItemsFromAllDrives?,includeLabels,includePermissionsForView,includeRemoved?,includeTeamDriveItems?,pageSize#,pageToken!,restrictToMyDrive?,spaces,supportsAllDrives?,supportsTeamDrives?,teamDriveId", "Channel", "", "w", ""}, + {"drive.channels.stop", "drive", "POST", "channels/stop", "", "Channel", "", "w", ""}, + {"drive.comments.create", "drive", "POST", "files/{fileId}/comments", "fileId@", "Comment", "", "w", ""}, + {"drive.comments.delete", "drive", "DELETE", "files/{fileId}/comments/{commentId}", "fileId@,commentId@", "", "", "d", ""}, + {"drive.comments.get", "drive", "GET", "files/{fileId}/comments/{commentId}", "commentId@,fileId@,includeDeleted?", "", "", "r", ""}, + {"drive.comments.list", "drive", "GET", "files/{fileId}/comments", "fileId@,includeDeleted?,pageSize#,pageToken,startModifiedTime", "", "comments", "r", ""}, + {"drive.comments.update", "drive", "PATCH", "files/{fileId}/comments/{commentId}", "fileId@,commentId@", "Comment", "", "w", ""}, + {"drive.drives.create", "drive", "POST", "drives", "requestId!", "Drive", "", "w", ""}, + {"drive.drives.delete", "drive", "DELETE", "drives/{driveId}", "driveId@,allowItemDeletion?,useDomainAdminAccess?", "", "", "d", ""}, + {"drive.drives.get", "drive", "GET", "drives/{driveId}", "driveId@,useDomainAdminAccess?", "", "", "r", ""}, + {"drive.drives.hide", "drive", "POST", "drives/{driveId}/hide", "driveId@", "", "", "w", ""}, + {"drive.drives.list", "drive", "GET", "drives", "pageSize#,pageToken,q,useDomainAdminAccess?", "", "drives", "r", ""}, + {"drive.drives.unhide", "drive", "POST", "drives/{driveId}/unhide", "driveId@", "", "", "w", ""}, + {"drive.drives.update", "drive", "PATCH", "drives/{driveId}", "driveId@,useDomainAdminAccess?", "Drive", "", "w", ""}, + {"drive.files.copy", "drive", "POST", "files/{fileId}/copy", "fileId@,copyComments?,enforceSingleParent?,ignoreDefaultVisibility?,includeLabels,includePermissionsForView,keepRevisionForever?,ocrLanguage,supportsAllDrives?,supportsTeamDrives?", "File", "", "w", ""}, + {"drive.files.create", "drive", "POST", "files", "enforceSingleParent?,ignoreDefaultVisibility?,includeLabels,includePermissionsForView,keepRevisionForever?,ocrLanguage,supportsAllDrives?,supportsTeamDrives?,useContentAsIndexableText?", "File", "", "w", "u"}, + {"drive.files.delete", "drive", "DELETE", "files/{fileId}", "fileId@,enforceSingleParent?,supportsAllDrives?,supportsTeamDrives?", "", "", "d", ""}, + {"drive.files.download", "drive", "POST", "files/{fileId}/download", "fileId@,mimeType,revisionId", "", "", "w", ""}, + {"drive.files.emptyTrash", "drive", "DELETE", "files/trash", "driveId,enforceSingleParent?", "", "", "d", ""}, + {"drive.files.export", "drive", "GET", "files/{fileId}/export", "fileId@,mimeType!", "", "", "r", "db"}, + {"drive.files.generateCseToken", "drive", "GET", "files/generateCseToken", "fileId,parent", "", "", "r", ""}, + {"drive.files.generateIds", "drive", "GET", "files/generateIds", "count#,space,type", "", "", "r", ""}, + {"drive.files.get", "drive", "GET", "files/{fileId}", "fileId@,acknowledgeAbuse?,includeLabels,includePermissionsForView,supportsAllDrives?,supportsTeamDrives?", "", "", "r", "d"}, + {"drive.files.list", "drive", "GET", "files", "corpora,corpus,driveId,includeItemsFromAllDrives?,includeLabels,includePermissionsForView,includeTeamDriveItems?,orderBy,pageSize#,pageToken,q,spaces,supportsAllDrives?,supportsTeamDrives?,teamDriveId", "", "files", "r", ""}, + {"drive.files.listLabels", "drive", "GET", "files/{fileId}/listLabels", "fileId@,maxResults#,pageToken", "", "labels", "r", ""}, + {"drive.files.modifyLabels", "drive", "POST", "files/{fileId}/modifyLabels", "fileId@", "ModifyLabelsRequest", "", "w", ""}, + {"drive.files.update", "drive", "PATCH", "files/{fileId}", "fileId@,addParents,enforceSingleParent?,includeLabels,includePermissionsForView,keepRevisionForever?,ocrLanguage,removeParents,supportsAllDrives?,supportsTeamDrives?,useContentAsIndexableText?", "File", "", "w", "u"}, + {"drive.files.watch", "drive", "POST", "files/{fileId}/watch", "fileId@,acknowledgeAbuse?,includeLabels,includePermissionsForView,supportsAllDrives?,supportsTeamDrives?", "Channel", "", "w", ""}, + {"drive.operations.get", "drive", "GET", "operations/{name}", "name@", "", "", "r", ""}, + {"drive.permissions.create", "drive", "POST", "files/{fileId}/permissions", "fileId@,emailMessage,enforceExpansiveAccess?,enforceSingleParent?,moveToNewOwnersRoot?,sendNotificationEmail?,supportsAllDrives?,supportsTeamDrives?,transferOwnership?,useDomainAdminAccess?", "Permission", "", "s", ""}, + {"drive.permissions.delete", "drive", "DELETE", "files/{fileId}/permissions/{permissionId}", "permissionId@,fileId@,enforceExpansiveAccess?,supportsAllDrives?,supportsTeamDrives?,useDomainAdminAccess?", "", "", "d", ""}, + {"drive.permissions.get", "drive", "GET", "files/{fileId}/permissions/{permissionId}", "permissionId@,fileId@,supportsAllDrives?,supportsTeamDrives?,useDomainAdminAccess?", "", "", "r", ""}, + {"drive.permissions.list", "drive", "GET", "files/{fileId}/permissions", "fileId@,includePermissionsForView,pageSize#,pageToken,supportsAllDrives?,supportsTeamDrives?,useDomainAdminAccess?", "", "permissions", "r", ""}, + {"drive.permissions.update", "drive", "PATCH", "files/{fileId}/permissions/{permissionId}", "fileId@,permissionId@,enforceExpansiveAccess?,removeExpiration?,supportsAllDrives?,supportsTeamDrives?,transferOwnership?,useDomainAdminAccess?", "Permission", "", "s", ""}, + {"drive.replies.create", "drive", "POST", "files/{fileId}/comments/{commentId}/replies", "commentId@,fileId@", "Reply", "", "w", ""}, + {"drive.replies.delete", "drive", "DELETE", "files/{fileId}/comments/{commentId}/replies/{replyId}", "fileId@,commentId@,replyId@", "", "", "d", ""}, + {"drive.replies.get", "drive", "GET", "files/{fileId}/comments/{commentId}/replies/{replyId}", "fileId@,replyId@,commentId@,includeDeleted?", "", "", "r", ""}, + {"drive.replies.list", "drive", "GET", "files/{fileId}/comments/{commentId}/replies", "commentId@,fileId@,includeDeleted?,pageSize#,pageToken", "", "replies", "r", ""}, + {"drive.replies.update", "drive", "PATCH", "files/{fileId}/comments/{commentId}/replies/{replyId}", "commentId@,replyId@,fileId@", "Reply", "", "w", ""}, + {"drive.revisions.delete", "drive", "DELETE", "files/{fileId}/revisions/{revisionId}", "fileId@,revisionId@", "", "", "d", ""}, + {"drive.revisions.get", "drive", "GET", "files/{fileId}/revisions/{revisionId}", "fileId@,revisionId@,acknowledgeAbuse?", "", "", "r", "d"}, + {"drive.revisions.list", "drive", "GET", "files/{fileId}/revisions", "fileId@,pageSize#,pageToken", "", "revisions", "r", ""}, + {"drive.revisions.update", "drive", "PATCH", "files/{fileId}/revisions/{revisionId}", "fileId@,revisionId@", "Revision", "", "w", ""}, + {"drive.teamdrives.create", "drive", "POST", "teamdrives", "requestId!", "TeamDrive", "", "w", ""}, + {"drive.teamdrives.delete", "drive", "DELETE", "teamdrives/{teamDriveId}", "teamDriveId@", "", "", "d", ""}, + {"drive.teamdrives.get", "drive", "GET", "teamdrives/{teamDriveId}", "teamDriveId@,useDomainAdminAccess?", "", "", "r", ""}, + {"drive.teamdrives.list", "drive", "GET", "teamdrives", "pageSize#,pageToken,q,useDomainAdminAccess?", "", "teamDrives", "r", ""}, + {"drive.teamdrives.update", "drive", "PATCH", "teamdrives/{teamDriveId}", "teamDriveId@,useDomainAdminAccess?", "TeamDrive", "", "w", ""}, + {"calendar.acl.delete", "calendar", "DELETE", "calendars/{calendarId}/acl/{ruleId}", "ruleId@,calendarId@", "", "", "d", ""}, + {"calendar.acl.get", "calendar", "GET", "calendars/{calendarId}/acl/{ruleId}", "ruleId@,calendarId@", "", "", "r", ""}, + {"calendar.acl.insert", "calendar", "POST", "calendars/{calendarId}/acl", "calendarId@,sendNotifications?", "AclRule", "", "s", ""}, + {"calendar.acl.list", "calendar", "GET", "calendars/{calendarId}/acl", "calendarId@,maxResults#,pageToken,showDeleted?,syncToken", "", "items", "r", ""}, + {"calendar.acl.patch", "calendar", "PATCH", "calendars/{calendarId}/acl/{ruleId}", "calendarId@,ruleId@,sendNotifications?", "AclRule", "", "w", ""}, + {"calendar.acl.update", "calendar", "PUT", "calendars/{calendarId}/acl/{ruleId}", "ruleId@,calendarId@,sendNotifications?", "AclRule", "", "w", ""}, + {"calendar.acl.watch", "calendar", "POST", "calendars/{calendarId}/acl/watch", "calendarId@,maxResults#,pageToken,showDeleted?,syncToken", "Channel", "", "w", ""}, + {"calendar.calendarList.delete", "calendar", "DELETE", "users/me/calendarList/{calendarId}", "calendarId@", "", "", "d", ""}, + {"calendar.calendarList.get", "calendar", "GET", "users/me/calendarList/{calendarId}", "calendarId@", "", "", "r", ""}, + {"calendar.calendarList.insert", "calendar", "POST", "users/me/calendarList", "colorRgbFormat?", "CalendarListEntry", "", "w", ""}, + {"calendar.calendarList.list", "calendar", "GET", "users/me/calendarList", "maxResults#,minAccessRole,pageToken,showDeleted?,showHidden?,showOwnOrganizationOnly?,syncToken", "", "items", "r", ""}, + {"calendar.calendarList.patch", "calendar", "PATCH", "users/me/calendarList/{calendarId}", "calendarId@,colorRgbFormat?", "CalendarListEntry", "", "w", ""}, + {"calendar.calendarList.update", "calendar", "PUT", "users/me/calendarList/{calendarId}", "calendarId@,colorRgbFormat?", "CalendarListEntry", "", "w", ""}, + {"calendar.calendarList.watch", "calendar", "POST", "users/me/calendarList/watch", "maxResults#,minAccessRole,pageToken,showDeleted?,showHidden?,showOwnOrganizationOnly?,syncToken", "Channel", "", "w", ""}, + {"calendar.calendars.clear", "calendar", "POST", "calendars/{calendarId}/clear", "calendarId@", "", "", "d", ""}, + {"calendar.calendars.delete", "calendar", "DELETE", "calendars/{calendarId}", "calendarId@", "", "", "d", ""}, + {"calendar.calendars.get", "calendar", "GET", "calendars/{calendarId}", "calendarId@", "", "", "r", ""}, + {"calendar.calendars.insert", "calendar", "POST", "calendars", "", "Calendar", "", "w", ""}, + {"calendar.calendars.patch", "calendar", "PATCH", "calendars/{calendarId}", "calendarId@", "Calendar", "", "w", ""}, + {"calendar.calendars.transferOwnership", "calendar", "POST", "calendars/{calendarId}/transferOwnership", "calendarId@,newDataOwner!,useAdminAccess!?", "", "", "w", ""}, + {"calendar.calendars.update", "calendar", "PUT", "calendars/{calendarId}", "calendarId@", "Calendar", "", "w", ""}, + {"calendar.channels.stop", "calendar", "POST", "channels/stop", "", "Channel", "", "w", ""}, + {"calendar.colors.get", "calendar", "GET", "colors", "", "", "", "r", ""}, + {"calendar.events.delete", "calendar", "DELETE", "calendars/{calendarId}/events/{eventId}", "calendarId@,eventId@,sendNotifications?,sendUpdates", "", "", "d", ""}, + {"calendar.events.get", "calendar", "GET", "calendars/{calendarId}/events/{eventId}", "calendarId@,eventId@,alwaysIncludeEmail?,maxAttendees#,timeZone", "", "", "r", ""}, + {"calendar.events.import", "calendar", "POST", "calendars/{calendarId}/events/import", "calendarId@,conferenceDataVersion#,eventLabelVersion#,supportsAttachments?", "Event", "", "s", ""}, + {"calendar.events.insert", "calendar", "POST", "calendars/{calendarId}/events", "calendarId@,conferenceDataVersion#,eventLabelVersion#,maxAttendees#,sendNotifications?,sendUpdates,supportsAttachments?", "Event", "", "s", ""}, + {"calendar.events.instances", "calendar", "GET", "calendars/{calendarId}/events/{eventId}/instances", "eventId@,calendarId@,alwaysIncludeEmail?,maxAttendees#,maxResults#,originalStart,pageToken,showDeleted?,timeMax,timeMin,timeZone", "", "", "r", ""}, + {"calendar.events.list", "calendar", "GET", "calendars/{calendarId}/events", "calendarId@,alwaysIncludeEmail?,eventTypes*,iCalUID,maxAttendees#,maxResults#,orderBy,pageToken,privateExtendedProperty*,q,sharedExtendedProperty*,showDeleted?,showHiddenInvitations?,singleEvents?,syncToken,timeMax,timeMin,timeZone,updatedMin", "", "", "r", ""}, + {"calendar.events.move", "calendar", "POST", "calendars/{calendarId}/events/{eventId}/move", "eventId@,calendarId@,destination!,sendNotifications?,sendUpdates", "", "", "s", ""}, + {"calendar.events.patch", "calendar", "PATCH", "calendars/{calendarId}/events/{eventId}", "calendarId@,eventId@,alwaysIncludeEmail?,conferenceDataVersion#,eventLabelVersion#,maxAttendees#,sendNotifications?,sendUpdates,supportsAttachments?", "Event", "", "s", ""}, + {"calendar.events.quickAdd", "calendar", "POST", "calendars/{calendarId}/events/quickAdd", "calendarId@,sendNotifications?,sendUpdates,text!", "", "", "s", ""}, + {"calendar.events.update", "calendar", "PUT", "calendars/{calendarId}/events/{eventId}", "calendarId@,eventId@,alwaysIncludeEmail?,conferenceDataVersion#,eventLabelVersion#,maxAttendees#,sendNotifications?,sendUpdates,supportsAttachments?", "Event", "", "s", ""}, + {"calendar.events.watch", "calendar", "POST", "calendars/{calendarId}/events/watch", "calendarId@,alwaysIncludeEmail?,eventTypes*,iCalUID,maxAttendees#,maxResults#,orderBy,pageToken,privateExtendedProperty*,q,sharedExtendedProperty*,showDeleted?,showHiddenInvitations?,singleEvents?,syncToken,timeMax,timeMin,timeZone,updatedMin", "Channel", "", "w", ""}, + {"calendar.freebusy.query", "calendar", "POST", "freeBusy", "", "FreeBusyRequest", "", "r", ""}, + {"calendar.settings.get", "calendar", "GET", "users/me/settings/{setting}", "setting@", "", "", "r", ""}, + {"calendar.settings.list", "calendar", "GET", "users/me/settings", "maxResults#,pageToken,syncToken", "", "items", "r", ""}, + {"calendar.settings.watch", "calendar", "POST", "users/me/settings/watch", "maxResults#,pageToken,syncToken", "Channel", "", "w", ""}, + {"sheets.spreadsheets.batchUpdate", "sheets", "POST", "v4/spreadsheets/{spreadsheetId}:batchUpdate", "spreadsheetId@", "BatchUpdateSpreadsheetRequest", "", "w", ""}, + {"sheets.spreadsheets.create", "sheets", "POST", "v4/spreadsheets", "", "Spreadsheet", "", "w", ""}, + {"sheets.spreadsheets.developerMetadata.get", "sheets", "GET", "v4/spreadsheets/{spreadsheetId}/developerMetadata/{metadataId}", "spreadsheetId@,metadataId@#", "", "", "r", ""}, + {"sheets.spreadsheets.developerMetadata.search", "sheets", "POST", "v4/spreadsheets/{spreadsheetId}/developerMetadata:search", "spreadsheetId@", "SearchDeveloperMetadataRequest", "", "w", ""}, + {"sheets.spreadsheets.get", "sheets", "GET", "v4/spreadsheets/{spreadsheetId}", "spreadsheetId@,commentsViewMode,excludeTablesInBandedRanges?,includeGridData?,ranges*", "", "", "r", ""}, + {"sheets.spreadsheets.getByDataFilter", "sheets", "POST", "v4/spreadsheets/{spreadsheetId}:getByDataFilter", "spreadsheetId@", "GetSpreadsheetByDataFilterRequest", "", "r", ""}, + {"sheets.spreadsheets.sheets.copyTo", "sheets", "POST", "v4/spreadsheets/{spreadsheetId}/sheets/{sheetId}:copyTo", "sheetId@#,spreadsheetId@", "CopySheetToAnotherSpreadsheetRequest", "", "w", ""}, + {"sheets.spreadsheets.values.append", "sheets", "POST", "v4/spreadsheets/{spreadsheetId}/values/{range}:append", "range@,spreadsheetId@,includeValuesInResponse?,insertDataOption,responseDateTimeRenderOption,responseValueRenderOption,valueInputOption", "ValueRange", "", "w", ""}, + {"sheets.spreadsheets.values.batchClear", "sheets", "POST", "v4/spreadsheets/{spreadsheetId}/values:batchClear", "spreadsheetId@", "BatchClearValuesRequest", "", "d", ""}, + {"sheets.spreadsheets.values.batchClearByDataFilter", "sheets", "POST", "v4/spreadsheets/{spreadsheetId}/values:batchClearByDataFilter", "spreadsheetId@", "BatchClearValuesByDataFilterRequest", "", "d", ""}, + {"sheets.spreadsheets.values.batchGet", "sheets", "GET", "v4/spreadsheets/{spreadsheetId}/values:batchGet", "spreadsheetId@,dateTimeRenderOption,majorDimension,ranges*,valueRenderOption", "", "", "r", ""}, + {"sheets.spreadsheets.values.batchGetByDataFilter", "sheets", "POST", "v4/spreadsheets/{spreadsheetId}/values:batchGetByDataFilter", "spreadsheetId@", "BatchGetValuesByDataFilterRequest", "", "r", ""}, + {"sheets.spreadsheets.values.batchUpdate", "sheets", "POST", "v4/spreadsheets/{spreadsheetId}/values:batchUpdate", "spreadsheetId@", "BatchUpdateValuesRequest", "", "w", ""}, + {"sheets.spreadsheets.values.batchUpdateByDataFilter", "sheets", "POST", "v4/spreadsheets/{spreadsheetId}/values:batchUpdateByDataFilter", "spreadsheetId@", "BatchUpdateValuesByDataFilterRequest", "", "w", ""}, + {"sheets.spreadsheets.values.clear", "sheets", "POST", "v4/spreadsheets/{spreadsheetId}/values/{range}:clear", "spreadsheetId@,range@", "ClearValuesRequest", "", "d", ""}, + {"sheets.spreadsheets.values.get", "sheets", "GET", "v4/spreadsheets/{spreadsheetId}/values/{range}", "spreadsheetId@,range@,dateTimeRenderOption,majorDimension,valueRenderOption", "", "", "r", ""}, + {"sheets.spreadsheets.values.update", "sheets", "PUT", "v4/spreadsheets/{spreadsheetId}/values/{range}", "range@,spreadsheetId@,includeValuesInResponse?,responseDateTimeRenderOption,responseValueRenderOption,valueInputOption", "ValueRange", "", "w", ""}, + {"docs.documents.batchUpdate", "docs", "POST", "v1/documents/{documentId}:batchUpdate", "documentId@", "BatchUpdateDocumentRequest", "", "w", ""}, + {"docs.documents.create", "docs", "POST", "v1/documents", "", "Document", "", "w", ""}, + {"docs.documents.get", "docs", "GET", "v1/documents/{documentId}", "documentId@,commentsViewMode,includeTabsContent?,suggestionsViewMode", "", "", "r", ""}, + {"slides.presentations.batchUpdate", "slides", "POST", "v1/presentations/{presentationId}:batchUpdate", "presentationId@", "BatchUpdatePresentationRequest", "", "w", ""}, + {"slides.presentations.create", "slides", "POST", "v1/presentations", "", "Presentation", "", "w", ""}, + {"slides.presentations.get", "slides", "GET", "v1/presentations/{+presentationId}", "presentationId@,commentsViewMode", "", "", "r", ""}, + {"slides.presentations.pages.get", "slides", "GET", "v1/presentations/{presentationId}/pages/{pageObjectId}", "presentationId@,pageObjectId@,commentsViewMode", "", "", "r", ""}, + {"slides.presentations.pages.getThumbnail", "slides", "GET", "v1/presentations/{presentationId}/pages/{pageObjectId}/thumbnail", "pageObjectId@,presentationId@,thumbnailProperties.mimeType,thumbnailProperties.thumbnailSize", "", "", "r", ""}, + {"forms.forms.batchUpdate", "forms", "POST", "v1/forms/{formId}:batchUpdate", "formId@", "BatchUpdateFormRequest", "", "w", ""}, + {"forms.forms.create", "forms", "POST", "v1/forms", "unpublished?", "Form", "", "w", ""}, + {"forms.forms.get", "forms", "GET", "v1/forms/{formId}", "formId@", "", "", "r", ""}, + {"forms.forms.responses.get", "forms", "GET", "v1/forms/{formId}/responses/{responseId}", "responseId@,formId@", "", "", "r", ""}, + {"forms.forms.responses.list", "forms", "GET", "v1/forms/{formId}/responses", "formId@,filter,pageSize#,pageToken", "", "responses", "r", ""}, + {"forms.forms.setPublishSettings", "forms", "POST", "v1/forms/{formId}:setPublishSettings", "formId@", "SetPublishSettingsRequest", "", "w", ""}, + {"forms.forms.watches.create", "forms", "POST", "v1/forms/{formId}/watches", "formId@", "CreateWatchRequest", "", "w", ""}, + {"forms.forms.watches.delete", "forms", "DELETE", "v1/forms/{formId}/watches/{watchId}", "formId@,watchId@", "", "", "d", ""}, + {"forms.forms.watches.list", "forms", "GET", "v1/forms/{formId}/watches", "formId@", "", "", "r", ""}, + {"forms.forms.watches.renew", "forms", "POST", "v1/forms/{formId}/watches/{watchId}:renew", "watchId@,formId@", "RenewWatchRequest", "", "w", ""}, + {"tasks.tasklists.delete", "tasks", "DELETE", "tasks/v1/users/@me/lists/{tasklist}", "tasklist@", "", "", "d", ""}, + {"tasks.tasklists.get", "tasks", "GET", "tasks/v1/users/@me/lists/{tasklist}", "tasklist@", "", "", "r", ""}, + {"tasks.tasklists.insert", "tasks", "POST", "tasks/v1/users/@me/lists", "", "TaskList", "", "w", ""}, + {"tasks.tasklists.list", "tasks", "GET", "tasks/v1/users/@me/lists", "maxResults#,pageToken", "", "items", "r", ""}, + {"tasks.tasklists.patch", "tasks", "PATCH", "tasks/v1/users/@me/lists/{tasklist}", "tasklist@", "TaskList", "", "w", ""}, + {"tasks.tasklists.update", "tasks", "PUT", "tasks/v1/users/@me/lists/{tasklist}", "tasklist@", "TaskList", "", "w", ""}, + {"tasks.tasks.clear", "tasks", "POST", "tasks/v1/lists/{tasklist}/clear", "tasklist@", "", "", "d", ""}, + {"tasks.tasks.delete", "tasks", "DELETE", "tasks/v1/lists/{tasklist}/tasks/{task}", "tasklist@,task@", "", "", "d", ""}, + {"tasks.tasks.get", "tasks", "GET", "tasks/v1/lists/{tasklist}/tasks/{task}", "task@,tasklist@", "", "", "r", ""}, + {"tasks.tasks.insert", "tasks", "POST", "tasks/v1/lists/{tasklist}/tasks", "tasklist@,parent,previous", "Task", "", "w", ""}, + {"tasks.tasks.list", "tasks", "GET", "tasks/v1/lists/{tasklist}/tasks", "tasklist@,completedMax,completedMin,dueMax,dueMin,maxResults#,pageToken,showAssigned?,showCompleted?,showDeleted?,showHidden?,updatedMin", "", "items", "r", ""}, + {"tasks.tasks.move", "tasks", "POST", "tasks/v1/lists/{tasklist}/tasks/{task}/move", "task@,tasklist@,destinationTasklist,parent,previous", "", "", "w", ""}, + {"tasks.tasks.patch", "tasks", "PATCH", "tasks/v1/lists/{tasklist}/tasks/{task}", "tasklist@,task@", "Task", "", "w", ""}, + {"tasks.tasks.update", "tasks", "PUT", "tasks/v1/lists/{tasklist}/tasks/{task}", "task@,tasklist@", "Task", "", "w", ""}, + {"chat.customEmojis.create", "chat", "POST", "v1/customEmojis", "", "CustomEmoji", "", "w", ""}, + {"chat.customEmojis.delete", "chat", "DELETE", "v1/{+name}", "name@", "", "", "d", ""}, + {"chat.customEmojis.get", "chat", "GET", "v1/{+name}", "name@", "", "", "r", ""}, + {"chat.customEmojis.list", "chat", "GET", "v1/customEmojis", "filter,pageSize#,pageToken", "", "customEmojis", "r", ""}, + {"chat.media.download", "chat", "GET", "v1/media/{+resourceName}", "resourceName@", "", "", "r", "d"}, + {"chat.media.upload", "chat", "POST", "v1/{+parent}/attachments:upload", "parent@", "UploadAttachmentRequest", "", "s", "u"}, + {"chat.spaces.completeImport", "chat", "POST", "v1/{+name}:completeImport", "name@", "CompleteImportSpaceRequest", "", "w", ""}, + {"chat.spaces.create", "chat", "POST", "v1/spaces", "requestId", "Space", "", "w", ""}, + {"chat.spaces.delete", "chat", "DELETE", "v1/{+name}", "name@,useAdminAccess?", "", "", "d", ""}, + {"chat.spaces.findDirectMessage", "chat", "GET", "v1/spaces:findDirectMessage", "name", "", "", "r", ""}, + {"chat.spaces.findGroupChats", "chat", "GET", "v1/spaces:findGroupChats", "pageSize#,pageToken,spaceView,users*", "", "spaces", "r", ""}, + {"chat.spaces.get", "chat", "GET", "v1/{+name}", "name@,useAdminAccess?", "", "", "r", ""}, + {"chat.spaces.list", "chat", "GET", "v1/spaces", "filter,pageSize#,pageToken", "", "spaces", "r", ""}, + {"chat.spaces.members.create", "chat", "POST", "v1/{+parent}/members", "parent@,useAdminAccess?", "Membership", "", "s", ""}, + {"chat.spaces.members.delete", "chat", "DELETE", "v1/{+name}", "name@,useAdminAccess?", "", "", "d", ""}, + {"chat.spaces.members.get", "chat", "GET", "v1/{+name}", "name@,useAdminAccess?", "", "", "r", ""}, + {"chat.spaces.members.list", "chat", "GET", "v1/{+parent}/members", "parent@,filter,pageSize#,pageToken,showGroups?,showInvited?,useAdminAccess?", "", "memberships", "r", ""}, + {"chat.spaces.members.patch", "chat", "PATCH", "v1/{+name}", "name@,updateMask,useAdminAccess?", "Membership", "", "w", ""}, + {"chat.spaces.messagePins.create", "chat", "POST", "v1/{+parent}/messagePins", "parent@", "MessagePin", "", "w", ""}, + {"chat.spaces.messagePins.delete", "chat", "DELETE", "v1/{+name}", "name@", "", "", "d", ""}, + {"chat.spaces.messagePins.list", "chat", "GET", "v1/{+parent}/messagePins", "parent@,pageSize#,pageToken", "", "messagePins", "r", ""}, + {"chat.spaces.messages.attachments.get", "chat", "GET", "v1/{+name}", "name@", "", "", "r", ""}, + {"chat.spaces.messages.create", "chat", "POST", "v1/{+parent}/messages", "parent@,createMessageNotificationOptions.notificationType,messageId,messageReplyOption,requestId,threadKey", "Message", "", "s", ""}, + {"chat.spaces.messages.delete", "chat", "DELETE", "v1/{+name}", "name@,force?", "", "", "d", ""}, + {"chat.spaces.messages.get", "chat", "GET", "v1/{+name}", "name@,markupSyntax", "", "", "r", ""}, + {"chat.spaces.messages.list", "chat", "GET", "v1/{+parent}/messages", "parent@,filter,markupSyntax,orderBy,pageSize#,pageToken,showDeleted?", "", "messages", "r", ""}, + {"chat.spaces.messages.patch", "chat", "PATCH", "v1/{+name}", "name@,allowMissing?,updateMask", "Message", "", "w", ""}, + {"chat.spaces.messages.reactions.create", "chat", "POST", "v1/{+parent}/reactions", "parent@", "Reaction", "", "w", ""}, + {"chat.spaces.messages.reactions.delete", "chat", "DELETE", "v1/{+name}", "name@", "", "", "d", ""}, + {"chat.spaces.messages.reactions.list", "chat", "GET", "v1/{+parent}/reactions", "parent@,filter,pageSize#,pageToken", "", "reactions", "r", ""}, + {"chat.spaces.messages.replaceCards", "chat", "POST", "v1/{+name}:replaceCards", "name@", "ReplaceMessageCardsRequest", "", "w", ""}, + {"chat.spaces.messages.search", "chat", "POST", "v1/{+parent}/messages:search", "parent@", "SearchMessagesRequest", "", "w", ""}, + {"chat.spaces.messages.update", "chat", "PUT", "v1/{+name}", "name@,allowMissing?,updateMask", "Message", "", "w", ""}, + {"chat.spaces.patch", "chat", "PATCH", "v1/{+name}", "name@,updateMask,useAdminAccess?", "Space", "", "w", ""}, + {"chat.spaces.search", "chat", "GET", "v1/spaces:search", "orderBy,pageSize#,pageToken,query,useAdminAccess?", "", "", "r", ""}, + {"chat.spaces.setup", "chat", "POST", "v1/spaces:setup", "", "SetUpSpaceRequest", "", "s", ""}, + {"chat.spaces.spaceEvents.get", "chat", "GET", "v1/{+name}", "name@", "", "", "r", ""}, + {"chat.spaces.spaceEvents.list", "chat", "GET", "v1/{+parent}/spaceEvents", "parent@,filter,pageSize#,pageToken", "", "spaceEvents", "r", ""}, + {"chat.users.availability.get", "chat", "GET", "v1/{+name}", "name@", "", "", "r", ""}, + {"chat.users.availability.markAsActive", "chat", "POST", "v1/{+name}:markAsActive", "name@", "MarkAsActiveRequest", "", "w", ""}, + {"chat.users.availability.markAsAway", "chat", "POST", "v1/{+name}:markAsAway", "name@", "MarkAsAwayRequest", "", "w", ""}, + {"chat.users.availability.markAsDoNotDisturb", "chat", "POST", "v1/{+name}:markAsDoNotDisturb", "name@", "MarkAsDoNotDisturbRequest", "", "w", ""}, + {"chat.users.availability.patch", "chat", "PATCH", "v1/{+name}", "name@,updateMask", "Availability", "", "w", ""}, + {"chat.users.sections.create", "chat", "POST", "v1/{+parent}/sections", "parent@", "GoogleChatV1Section", "", "w", ""}, + {"chat.users.sections.delete", "chat", "DELETE", "v1/{+name}", "name@", "", "", "d", ""}, + {"chat.users.sections.items.list", "chat", "GET", "v1/{+parent}/items", "parent@,filter,pageSize#,pageToken", "", "sectionItems", "r", ""}, + {"chat.users.sections.items.move", "chat", "POST", "v1/{+name}:move", "name@", "MoveSectionItemRequest", "", "w", ""}, + {"chat.users.sections.list", "chat", "GET", "v1/{+parent}/sections", "parent@,pageSize#,pageToken", "", "sections", "r", ""}, + {"chat.users.sections.patch", "chat", "PATCH", "v1/{+name}", "name@,updateMask", "GoogleChatV1Section", "", "w", ""}, + {"chat.users.sections.position", "chat", "POST", "v1/{+name}:position", "name@", "PositionSectionRequest", "", "w", ""}, + {"chat.users.spaces.getSpaceReadState", "chat", "GET", "v1/{+name}", "name@", "", "", "r", ""}, + {"chat.users.spaces.spaceNotificationSetting.get", "chat", "GET", "v1/{+name}", "name@", "", "", "r", ""}, + {"chat.users.spaces.spaceNotificationSetting.patch", "chat", "PATCH", "v1/{+name}", "name@,updateMask", "SpaceNotificationSetting", "", "w", ""}, + {"chat.users.spaces.threads.getThreadReadState", "chat", "GET", "v1/{+name}", "name@", "", "", "r", ""}, + {"chat.users.spaces.updateSpaceReadState", "chat", "PATCH", "v1/{+name}", "name@,updateMask", "SpaceReadState", "", "w", ""}, + {"meet.conferenceRecords.get", "meet", "GET", "v2/{+name}", "name@", "", "", "r", ""}, + {"meet.conferenceRecords.list", "meet", "GET", "v2/conferenceRecords", "filter,pageSize#,pageToken", "", "conferenceRecords", "r", ""}, + {"meet.conferenceRecords.participants.get", "meet", "GET", "v2/{+name}", "name@", "", "", "r", ""}, + {"meet.conferenceRecords.participants.list", "meet", "GET", "v2/{+parent}/participants", "parent@,filter,pageSize#,pageToken", "", "participants", "r", ""}, + {"meet.conferenceRecords.participants.participantSessions.get", "meet", "GET", "v2/{+name}", "name@", "", "", "r", ""}, + {"meet.conferenceRecords.participants.participantSessions.list", "meet", "GET", "v2/{+parent}/participantSessions", "parent@,filter,pageSize#,pageToken", "", "participantSessions", "r", ""}, + {"meet.conferenceRecords.recordings.get", "meet", "GET", "v2/{+name}", "name@", "", "", "r", ""}, + {"meet.conferenceRecords.recordings.list", "meet", "GET", "v2/{+parent}/recordings", "parent@,pageSize#,pageToken", "", "recordings", "r", ""}, + {"meet.conferenceRecords.smartNotes.get", "meet", "GET", "v2/{+name}", "name@", "", "", "r", ""}, + {"meet.conferenceRecords.smartNotes.list", "meet", "GET", "v2/{+parent}/smartNotes", "parent@,pageSize#,pageToken", "", "smartNotes", "r", ""}, + {"meet.conferenceRecords.transcripts.entries.get", "meet", "GET", "v2/{+name}", "name@", "", "", "r", ""}, + {"meet.conferenceRecords.transcripts.entries.list", "meet", "GET", "v2/{+parent}/entries", "parent@,pageSize#,pageToken", "", "transcriptEntries", "r", ""}, + {"meet.conferenceRecords.transcripts.get", "meet", "GET", "v2/{+name}", "name@", "", "", "r", ""}, + {"meet.conferenceRecords.transcripts.list", "meet", "GET", "v2/{+parent}/transcripts", "parent@,pageSize#,pageToken", "", "transcripts", "r", ""}, + {"meet.spaces.create", "meet", "POST", "v2/spaces", "", "Space", "", "w", ""}, + {"meet.spaces.endActiveConference", "meet", "POST", "v2/{+name}:endActiveConference", "name@", "EndActiveConferenceRequest", "", "w", ""}, + {"meet.spaces.get", "meet", "GET", "v2/{+name}", "name@", "", "", "r", ""}, + {"meet.spaces.members.batchUpdate", "meet", "POST", "v2/{+parent}/members:batchUpdate", "parent@", "BatchUpdateMembersRequest", "", "w", ""}, + {"meet.spaces.members.create", "meet", "POST", "v2/{+parent}/members", "parent@", "Member", "", "w", ""}, + {"meet.spaces.members.delete", "meet", "DELETE", "v2/{+name}", "name@", "", "", "d", ""}, + {"meet.spaces.members.get", "meet", "GET", "v2/{+name}", "name@", "", "", "r", ""}, + {"meet.spaces.members.list", "meet", "GET", "v2/{+parent}/members", "parent@,pageSize#,pageToken", "", "members", "r", ""}, + {"meet.spaces.members.patch", "meet", "PATCH", "v2/{+name}", "name@,updateMask", "Member", "", "w", ""}, + {"meet.spaces.patch", "meet", "PATCH", "v2/{+name}", "name@,updateMask", "Space", "", "w", ""}, + {"people.contactGroups.batchGet", "people", "GET", "v1/contactGroups:batchGet", "groupFields,maxMembers#,resourceNames*", "", "", "r", ""}, + {"people.contactGroups.create", "people", "POST", "v1/contactGroups", "", "CreateContactGroupRequest", "", "w", ""}, + {"people.contactGroups.delete", "people", "DELETE", "v1/{+resourceName}", "resourceName@,deleteContacts?", "", "", "d", ""}, + {"people.contactGroups.get", "people", "GET", "v1/{+resourceName}", "resourceName@,groupFields,maxMembers#", "", "", "r", ""}, + {"people.contactGroups.list", "people", "GET", "v1/contactGroups", "groupFields,pageSize#,pageToken,syncToken", "", "contactGroups", "r", ""}, + {"people.contactGroups.members.modify", "people", "POST", "v1/{+resourceName}/members:modify", "resourceName@", "ModifyContactGroupMembersRequest", "", "w", ""}, + {"people.contactGroups.update", "people", "PUT", "v1/{+resourceName}", "resourceName@", "UpdateContactGroupRequest", "", "w", ""}, + {"people.otherContacts.copyOtherContactToMyContactsGroup", "people", "POST", "v1/{+resourceName}:copyOtherContactToMyContactsGroup", "resourceName@", "CopyOtherContactToMyContactsGroupRequest", "", "w", ""}, + {"people.otherContacts.list", "people", "GET", "v1/otherContacts", "pageSize#,pageToken,readMask,requestSyncToken?,sources*,syncToken", "", "otherContacts", "r", ""}, + {"people.otherContacts.search", "people", "GET", "v1/otherContacts:search", "pageSize#,query,readMask", "", "", "r", ""}, + {"people.people.batchCreateContacts", "people", "POST", "v1/people:batchCreateContacts", "", "BatchCreateContactsRequest", "", "w", ""}, + {"people.people.batchDeleteContacts", "people", "POST", "v1/people:batchDeleteContacts", "", "BatchDeleteContactsRequest", "", "d", ""}, + {"people.people.batchUpdateContacts", "people", "POST", "v1/people:batchUpdateContacts", "", "BatchUpdateContactsRequest", "", "w", ""}, + {"people.people.connections.list", "people", "GET", "v1/{+resourceName}/connections", "resourceName@,pageSize#,pageToken,personFields,requestMask.includeField,requestSyncToken?,sortOrder,sources*,syncToken", "", "connections", "r", ""}, + {"people.people.createContact", "people", "POST", "v1/people:createContact", "personFields,sources*", "Person", "", "w", ""}, + {"people.people.deleteContact", "people", "DELETE", "v1/{+resourceName}:deleteContact", "resourceName@", "", "", "d", ""}, + {"people.people.deleteContactPhoto", "people", "DELETE", "v1/{+resourceName}:deleteContactPhoto", "resourceName@,personFields,sources*", "", "", "d", ""}, + {"people.people.get", "people", "GET", "v1/{+resourceName}", "resourceName@,personFields,requestMask.includeField,sources*", "", "", "r", ""}, + {"people.people.getBatchGet", "people", "GET", "v1/people:batchGet", "personFields,requestMask.includeField,resourceNames*,sources*", "", "", "r", ""}, + {"people.people.listDirectoryPeople", "people", "GET", "v1/people:listDirectoryPeople", "mergeSources*,pageSize#,pageToken,readMask,requestSyncToken?,sources*,syncToken", "", "people", "r", ""}, + {"people.people.searchContacts", "people", "GET", "v1/people:searchContacts", "pageSize#,query,readMask,sources*", "", "", "r", ""}, + {"people.people.searchDirectoryPeople", "people", "GET", "v1/people:searchDirectoryPeople", "mergeSources*,pageSize#,pageToken,query,readMask,sources*", "", "people", "r", ""}, + {"people.people.updateContact", "people", "PATCH", "v1/{+resourceName}:updateContact", "resourceName@,personFields,sources*,updatePersonFields", "Person", "", "w", ""}, + {"people.people.updateContactPhoto", "people", "PATCH", "v1/{+resourceName}:updateContactPhoto", "resourceName@", "UpdateContactPhotoRequest", "", "w", ""}, + {"keep.media.download", "keep", "GET", "v1/{+name}", "name@,mimeType", "", "", "r", "d"}, + {"keep.notes.create", "keep", "POST", "v1/notes", "", "Note", "", "w", ""}, + {"keep.notes.delete", "keep", "DELETE", "v1/{+name}", "name@", "", "", "d", ""}, + {"keep.notes.get", "keep", "GET", "v1/{+name}", "name@", "", "", "r", ""}, + {"keep.notes.list", "keep", "GET", "v1/notes", "filter,pageSize#,pageToken", "", "notes", "r", ""}, + {"keep.notes.permissions.batchCreate", "keep", "POST", "v1/{+parent}/permissions:batchCreate", "parent@", "BatchCreatePermissionsRequest", "", "w", ""}, + {"keep.notes.permissions.batchDelete", "keep", "POST", "v1/{+parent}/permissions:batchDelete", "parent@", "BatchDeletePermissionsRequest", "", "d", ""}, + {"classroom.courses.aliases.create", "classroom", "POST", "v1/courses/{courseId}/aliases", "courseId@", "CourseAlias", "", "w", ""}, + {"classroom.courses.aliases.delete", "classroom", "DELETE", "v1/courses/{courseId}/aliases/{alias}", "alias@,courseId@", "", "", "d", ""}, + {"classroom.courses.aliases.list", "classroom", "GET", "v1/courses/{courseId}/aliases", "courseId@,pageSize#,pageToken", "", "aliases", "r", ""}, + {"classroom.courses.announcements.addOnAttachments.create", "classroom", "POST", "v1/courses/{courseId}/announcements/{itemId}/addOnAttachments", "itemId@,courseId@,addOnToken,postId", "AddOnAttachment", "", "w", ""}, + {"classroom.courses.announcements.addOnAttachments.delete", "classroom", "DELETE", "v1/courses/{courseId}/announcements/{itemId}/addOnAttachments/{attachmentId}", "attachmentId@,courseId@,itemId@,postId", "", "", "d", ""}, + {"classroom.courses.announcements.addOnAttachments.get", "classroom", "GET", "v1/courses/{courseId}/announcements/{itemId}/addOnAttachments/{attachmentId}", "itemId@,courseId@,attachmentId@,postId", "", "", "r", ""}, + {"classroom.courses.announcements.addOnAttachments.list", "classroom", "GET", "v1/courses/{courseId}/announcements/{itemId}/addOnAttachments", "courseId@,itemId@,pageSize#,pageToken,postId", "", "addOnAttachments", "r", ""}, + {"classroom.courses.announcements.addOnAttachments.patch", "classroom", "PATCH", "v1/courses/{courseId}/announcements/{itemId}/addOnAttachments/{attachmentId}", "courseId@,attachmentId@,itemId@,postId,updateMask", "AddOnAttachment", "", "w", ""}, + {"classroom.courses.announcements.create", "classroom", "POST", "v1/courses/{courseId}/announcements", "courseId@", "Announcement", "", "s", ""}, + {"classroom.courses.announcements.delete", "classroom", "DELETE", "v1/courses/{courseId}/announcements/{id}", "courseId@,id@", "", "", "d", ""}, + {"classroom.courses.announcements.get", "classroom", "GET", "v1/courses/{courseId}/announcements/{id}", "courseId@,id@", "", "", "r", ""}, + {"classroom.courses.announcements.getAddOnContext", "classroom", "GET", "v1/courses/{courseId}/announcements/{itemId}/addOnContext", "courseId@,itemId@,addOnToken,attachmentId,postId", "", "", "r", ""}, + {"classroom.courses.announcements.list", "classroom", "GET", "v1/courses/{courseId}/announcements", "courseId@,announcementStates*,orderBy,pageSize#,pageToken", "", "announcements", "r", ""}, + {"classroom.courses.announcements.modifyAssignees", "classroom", "POST", "v1/courses/{courseId}/announcements/{id}:modifyAssignees", "courseId@,id@", "ModifyAnnouncementAssigneesRequest", "", "w", ""}, + {"classroom.courses.announcements.patch", "classroom", "PATCH", "v1/courses/{courseId}/announcements/{id}", "id@,courseId@,updateMask", "Announcement", "", "w", ""}, + {"classroom.courses.courseWork.addOnAttachments.create", "classroom", "POST", "v1/courses/{courseId}/courseWork/{itemId}/addOnAttachments", "courseId@,itemId@,addOnToken,postId", "AddOnAttachment", "", "w", ""}, + {"classroom.courses.courseWork.addOnAttachments.delete", "classroom", "DELETE", "v1/courses/{courseId}/courseWork/{itemId}/addOnAttachments/{attachmentId}", "itemId@,courseId@,attachmentId@,postId", "", "", "d", ""}, + {"classroom.courses.courseWork.addOnAttachments.get", "classroom", "GET", "v1/courses/{courseId}/courseWork/{itemId}/addOnAttachments/{attachmentId}", "itemId@,courseId@,attachmentId@,postId", "", "", "r", ""}, + {"classroom.courses.courseWork.addOnAttachments.list", "classroom", "GET", "v1/courses/{courseId}/courseWork/{itemId}/addOnAttachments", "courseId@,itemId@,pageSize#,pageToken,postId", "", "addOnAttachments", "r", ""}, + {"classroom.courses.courseWork.addOnAttachments.patch", "classroom", "PATCH", "v1/courses/{courseId}/courseWork/{itemId}/addOnAttachments/{attachmentId}", "attachmentId@,courseId@,itemId@,postId,updateMask", "AddOnAttachment", "", "w", ""}, + {"classroom.courses.courseWork.addOnAttachments.studentSubmissions.get", "classroom", "GET", "v1/courses/{courseId}/courseWork/{itemId}/addOnAttachments/{attachmentId}/studentSubmissions/{submissionId}", "courseId@,submissionId@,attachmentId@,itemId@,postId", "", "", "r", ""}, + {"classroom.courses.courseWork.addOnAttachments.studentSubmissions.list", "classroom", "GET", "v1/courses/{courseId}/courseWork/{itemId}/addOnAttachments/{attachmentId}/studentSubmissions", "courseId@,attachmentId@,itemId@,pageSize#,pageToken", "", "addOnAttachmentStudentSubmissions", "r", ""}, + {"classroom.courses.courseWork.addOnAttachments.studentSubmissions.patch", "classroom", "PATCH", "v1/courses/{courseId}/courseWork/{itemId}/addOnAttachments/{attachmentId}/studentSubmissions/{submissionId}", "attachmentId@,submissionId@,itemId@,courseId@,postId,updateMask", "AddOnAttachmentStudentSubmission", "", "w", ""}, + {"classroom.courses.courseWork.create", "classroom", "POST", "v1/courses/{courseId}/courseWork", "courseId@", "CourseWork", "", "s", ""}, + {"classroom.courses.courseWork.delete", "classroom", "DELETE", "v1/courses/{courseId}/courseWork/{id}", "id@,courseId@", "", "", "d", ""}, + {"classroom.courses.courseWork.get", "classroom", "GET", "v1/courses/{courseId}/courseWork/{id}", "courseId@,id@", "", "", "r", ""}, + {"classroom.courses.courseWork.getAddOnContext", "classroom", "GET", "v1/courses/{courseId}/courseWork/{itemId}/addOnContext", "courseId@,itemId@,addOnToken,attachmentId,postId", "", "", "r", ""}, + {"classroom.courses.courseWork.list", "classroom", "GET", "v1/courses/{courseId}/courseWork", "courseId@,courseWorkStates*,orderBy,pageSize#,pageToken", "", "courseWork", "r", ""}, + {"classroom.courses.courseWork.modifyAssignees", "classroom", "POST", "v1/courses/{courseId}/courseWork/{id}:modifyAssignees", "courseId@,id@", "ModifyCourseWorkAssigneesRequest", "", "w", ""}, + {"classroom.courses.courseWork.patch", "classroom", "PATCH", "v1/courses/{courseId}/courseWork/{id}", "courseId@,id@,updateMask", "CourseWork", "", "w", ""}, + {"classroom.courses.courseWork.rubrics.create", "classroom", "POST", "v1/courses/{courseId}/courseWork/{courseWorkId}/rubrics", "courseId@,courseWorkId@", "Rubric", "", "w", ""}, + {"classroom.courses.courseWork.rubrics.delete", "classroom", "DELETE", "v1/courses/{courseId}/courseWork/{courseWorkId}/rubrics/{id}", "courseWorkId@,id@,courseId@", "", "", "d", ""}, + {"classroom.courses.courseWork.rubrics.get", "classroom", "GET", "v1/courses/{courseId}/courseWork/{courseWorkId}/rubrics/{id}", "courseId@,courseWorkId@,id@", "", "", "r", ""}, + {"classroom.courses.courseWork.rubrics.list", "classroom", "GET", "v1/courses/{courseId}/courseWork/{courseWorkId}/rubrics", "courseWorkId@,courseId@,pageSize#,pageToken", "", "rubrics", "r", ""}, + {"classroom.courses.courseWork.rubrics.patch", "classroom", "PATCH", "v1/courses/{courseId}/courseWork/{courseWorkId}/rubrics/{id}", "courseWorkId@,id@,courseId@,updateMask", "Rubric", "", "w", ""}, + {"classroom.courses.courseWork.studentSubmissions.get", "classroom", "GET", "v1/courses/{courseId}/courseWork/{courseWorkId}/studentSubmissions/{id}", "id@,courseId@,courseWorkId@", "", "", "r", ""}, + {"classroom.courses.courseWork.studentSubmissions.list", "classroom", "GET", "v1/courses/{courseId}/courseWork/{courseWorkId}/studentSubmissions", "courseId@,courseWorkId@,late,pageSize#,pageToken,states*,userId", "", "studentSubmissions", "r", ""}, + {"classroom.courses.courseWork.studentSubmissions.modifyAttachments", "classroom", "POST", "v1/courses/{courseId}/courseWork/{courseWorkId}/studentSubmissions/{id}:modifyAttachments", "courseWorkId@,id@,courseId@", "ModifyAttachmentsRequest", "", "w", ""}, + {"classroom.courses.courseWork.studentSubmissions.patch", "classroom", "PATCH", "v1/courses/{courseId}/courseWork/{courseWorkId}/studentSubmissions/{id}", "id@,courseId@,courseWorkId@,updateMask", "StudentSubmission", "", "w", ""}, + {"classroom.courses.courseWork.studentSubmissions.reclaim", "classroom", "POST", "v1/courses/{courseId}/courseWork/{courseWorkId}/studentSubmissions/{id}:reclaim", "courseWorkId@,courseId@,id@", "ReclaimStudentSubmissionRequest", "", "w", ""}, + {"classroom.courses.courseWork.studentSubmissions.return", "classroom", "POST", "v1/courses/{courseId}/courseWork/{courseWorkId}/studentSubmissions/{id}:return", "courseWorkId@,courseId@,id@", "ReturnStudentSubmissionRequest", "", "w", ""}, + {"classroom.courses.courseWork.studentSubmissions.turnIn", "classroom", "POST", "v1/courses/{courseId}/courseWork/{courseWorkId}/studentSubmissions/{id}:turnIn", "id@,courseWorkId@,courseId@", "TurnInStudentSubmissionRequest", "", "w", ""}, + {"classroom.courses.courseWork.updateRubric", "classroom", "PATCH", "v1/courses/{courseId}/courseWork/{courseWorkId}/rubric", "courseId@,courseWorkId@,id,updateMask", "Rubric", "", "w", ""}, + {"classroom.courses.courseWorkMaterials.addOnAttachments.create", "classroom", "POST", "v1/courses/{courseId}/courseWorkMaterials/{itemId}/addOnAttachments", "itemId@,courseId@,addOnToken,postId", "AddOnAttachment", "", "w", ""}, + {"classroom.courses.courseWorkMaterials.addOnAttachments.delete", "classroom", "DELETE", "v1/courses/{courseId}/courseWorkMaterials/{itemId}/addOnAttachments/{attachmentId}", "attachmentId@,itemId@,courseId@,postId", "", "", "d", ""}, + {"classroom.courses.courseWorkMaterials.addOnAttachments.get", "classroom", "GET", "v1/courses/{courseId}/courseWorkMaterials/{itemId}/addOnAttachments/{attachmentId}", "itemId@,attachmentId@,courseId@,postId", "", "", "r", ""}, + {"classroom.courses.courseWorkMaterials.addOnAttachments.list", "classroom", "GET", "v1/courses/{courseId}/courseWorkMaterials/{itemId}/addOnAttachments", "itemId@,courseId@,pageSize#,pageToken,postId", "", "addOnAttachments", "r", ""}, + {"classroom.courses.courseWorkMaterials.addOnAttachments.patch", "classroom", "PATCH", "v1/courses/{courseId}/courseWorkMaterials/{itemId}/addOnAttachments/{attachmentId}", "attachmentId@,courseId@,itemId@,postId,updateMask", "AddOnAttachment", "", "w", ""}, + {"classroom.courses.courseWorkMaterials.create", "classroom", "POST", "v1/courses/{courseId}/courseWorkMaterials", "courseId@", "CourseWorkMaterial", "", "s", ""}, + {"classroom.courses.courseWorkMaterials.delete", "classroom", "DELETE", "v1/courses/{courseId}/courseWorkMaterials/{id}", "courseId@,id@", "", "", "d", ""}, + {"classroom.courses.courseWorkMaterials.get", "classroom", "GET", "v1/courses/{courseId}/courseWorkMaterials/{id}", "id@,courseId@", "", "", "r", ""}, + {"classroom.courses.courseWorkMaterials.getAddOnContext", "classroom", "GET", "v1/courses/{courseId}/courseWorkMaterials/{itemId}/addOnContext", "itemId@,courseId@,addOnToken,attachmentId,postId", "", "", "r", ""}, + {"classroom.courses.courseWorkMaterials.list", "classroom", "GET", "v1/courses/{courseId}/courseWorkMaterials", "courseId@,courseWorkMaterialStates*,materialDriveId,materialLink,orderBy,pageSize#,pageToken", "", "courseWorkMaterial", "r", ""}, + {"classroom.courses.courseWorkMaterials.patch", "classroom", "PATCH", "v1/courses/{courseId}/courseWorkMaterials/{id}", "courseId@,id@,updateMask", "CourseWorkMaterial", "", "w", ""}, + {"classroom.courses.create", "classroom", "POST", "v1/courses", "", "Course", "", "w", ""}, + {"classroom.courses.delete", "classroom", "DELETE", "v1/courses/{id}", "id@", "", "", "d", ""}, + {"classroom.courses.get", "classroom", "GET", "v1/courses/{id}", "id@", "", "", "r", ""}, + {"classroom.courses.getGradingPeriodSettings", "classroom", "GET", "v1/courses/{courseId}/gradingPeriodSettings", "courseId@", "", "", "r", ""}, + {"classroom.courses.list", "classroom", "GET", "v1/courses", "courseStates*,pageSize#,pageToken,studentId,teacherId", "", "courses", "r", ""}, + {"classroom.courses.patch", "classroom", "PATCH", "v1/courses/{id}", "id@,updateMask", "Course", "", "w", ""}, + {"classroom.courses.posts.addOnAttachments.create", "classroom", "POST", "v1/courses/{courseId}/posts/{postId}/addOnAttachments", "postId@,courseId@,addOnToken,itemId", "AddOnAttachment", "", "w", ""}, + {"classroom.courses.posts.addOnAttachments.delete", "classroom", "DELETE", "v1/courses/{courseId}/posts/{postId}/addOnAttachments/{attachmentId}", "attachmentId@,courseId@,postId@,itemId", "", "", "d", ""}, + {"classroom.courses.posts.addOnAttachments.get", "classroom", "GET", "v1/courses/{courseId}/posts/{postId}/addOnAttachments/{attachmentId}", "attachmentId@,postId@,courseId@,itemId", "", "", "r", ""}, + {"classroom.courses.posts.addOnAttachments.list", "classroom", "GET", "v1/courses/{courseId}/posts/{postId}/addOnAttachments", "postId@,courseId@,itemId,pageSize#,pageToken", "", "addOnAttachments", "r", ""}, + {"classroom.courses.posts.addOnAttachments.patch", "classroom", "PATCH", "v1/courses/{courseId}/posts/{postId}/addOnAttachments/{attachmentId}", "postId@,attachmentId@,courseId@,itemId,updateMask", "AddOnAttachment", "", "w", ""}, + {"classroom.courses.posts.addOnAttachments.studentSubmissions.get", "classroom", "GET", "v1/courses/{courseId}/posts/{postId}/addOnAttachments/{attachmentId}/studentSubmissions/{submissionId}", "postId@,courseId@,submissionId@,attachmentId@,itemId", "", "", "r", ""}, + {"classroom.courses.posts.addOnAttachments.studentSubmissions.patch", "classroom", "PATCH", "v1/courses/{courseId}/posts/{postId}/addOnAttachments/{attachmentId}/studentSubmissions/{submissionId}", "postId@,courseId@,submissionId@,attachmentId@,itemId,updateMask", "AddOnAttachmentStudentSubmission", "", "w", ""}, + {"classroom.courses.posts.getAddOnContext", "classroom", "GET", "v1/courses/{courseId}/posts/{postId}/addOnContext", "courseId@,postId@,addOnToken,attachmentId,itemId", "", "", "r", ""}, + {"classroom.courses.studentGroups.create", "classroom", "POST", "v1/courses/{courseId}/studentGroups", "courseId@", "StudentGroup", "", "w", ""}, + {"classroom.courses.studentGroups.delete", "classroom", "DELETE", "v1/courses/{courseId}/studentGroups/{id}", "id@,courseId@", "", "", "d", ""}, + {"classroom.courses.studentGroups.list", "classroom", "GET", "v1/courses/{courseId}/studentGroups", "courseId@,pageSize#,pageToken", "", "studentGroups", "r", ""}, + {"classroom.courses.studentGroups.patch", "classroom", "PATCH", "v1/courses/{courseId}/studentGroups/{id}", "id@,courseId@,updateMask", "StudentGroup", "", "w", ""}, + {"classroom.courses.studentGroups.studentGroupMembers.create", "classroom", "POST", "v1/courses/{courseId}/studentGroups/{studentGroupId}/studentGroupMembers", "courseId@,studentGroupId@", "StudentGroupMember", "", "w", ""}, + {"classroom.courses.studentGroups.studentGroupMembers.delete", "classroom", "DELETE", "v1/courses/{courseId}/studentGroups/{studentGroupId}/studentGroupMembers/{userId}", "courseId@,studentGroupId@,userId@", "", "", "d", ""}, + {"classroom.courses.studentGroups.studentGroupMembers.list", "classroom", "GET", "v1/courses/{courseId}/studentGroups/{studentGroupId}/studentGroupMembers", "studentGroupId@,courseId@,pageSize#,pageToken", "", "studentGroupMembers", "r", ""}, + {"classroom.courses.students.create", "classroom", "POST", "v1/courses/{courseId}/students", "courseId@,enrollmentCode", "Student", "", "s", ""}, + {"classroom.courses.students.delete", "classroom", "DELETE", "v1/courses/{courseId}/students/{userId}", "userId@,courseId@", "", "", "d", ""}, + {"classroom.courses.students.get", "classroom", "GET", "v1/courses/{courseId}/students/{userId}", "courseId@,userId@", "", "", "r", ""}, + {"classroom.courses.students.list", "classroom", "GET", "v1/courses/{courseId}/students", "courseId@,pageSize#,pageToken", "", "students", "r", ""}, + {"classroom.courses.teachers.create", "classroom", "POST", "v1/courses/{courseId}/teachers", "courseId@", "Teacher", "", "s", ""}, + {"classroom.courses.teachers.delete", "classroom", "DELETE", "v1/courses/{courseId}/teachers/{userId}", "userId@,courseId@", "", "", "d", ""}, + {"classroom.courses.teachers.get", "classroom", "GET", "v1/courses/{courseId}/teachers/{userId}", "courseId@,userId@", "", "", "r", ""}, + {"classroom.courses.teachers.list", "classroom", "GET", "v1/courses/{courseId}/teachers", "courseId@,pageSize#,pageToken", "", "teachers", "r", ""}, + {"classroom.courses.topics.create", "classroom", "POST", "v1/courses/{courseId}/topics", "courseId@", "Topic", "", "w", ""}, + {"classroom.courses.topics.delete", "classroom", "DELETE", "v1/courses/{courseId}/topics/{id}", "courseId@,id@", "", "", "d", ""}, + {"classroom.courses.topics.get", "classroom", "GET", "v1/courses/{courseId}/topics/{id}", "id@,courseId@", "", "", "r", ""}, + {"classroom.courses.topics.list", "classroom", "GET", "v1/courses/{courseId}/topics", "courseId@,pageSize#,pageToken", "", "topic", "r", ""}, + {"classroom.courses.topics.patch", "classroom", "PATCH", "v1/courses/{courseId}/topics/{id}", "id@,courseId@,updateMask", "Topic", "", "w", ""}, + {"classroom.courses.update", "classroom", "PUT", "v1/courses/{id}", "id@", "Course", "", "w", ""}, + {"classroom.courses.updateGradingPeriodSettings", "classroom", "PATCH", "v1/courses/{courseId}/gradingPeriodSettings", "courseId@,updateMask", "GradingPeriodSettings", "", "w", ""}, + {"classroom.invitations.accept", "classroom", "POST", "v1/invitations/{id}:accept", "id@", "", "", "w", ""}, + {"classroom.invitations.create", "classroom", "POST", "v1/invitations", "", "Invitation", "", "s", ""}, + {"classroom.invitations.delete", "classroom", "DELETE", "v1/invitations/{id}", "id@", "", "", "d", ""}, + {"classroom.invitations.get", "classroom", "GET", "v1/invitations/{id}", "id@", "", "", "r", ""}, + {"classroom.invitations.list", "classroom", "GET", "v1/invitations", "courseId,pageSize#,pageToken,userId", "", "invitations", "r", ""}, + {"classroom.registrations.create", "classroom", "POST", "v1/registrations", "", "Registration", "", "w", ""}, + {"classroom.registrations.delete", "classroom", "DELETE", "v1/registrations/{registrationId}", "registrationId@", "", "", "d", ""}, + {"classroom.userProfiles.get", "classroom", "GET", "v1/userProfiles/{userId}", "userId@", "", "", "r", ""}, + {"classroom.userProfiles.guardianInvitations.create", "classroom", "POST", "v1/userProfiles/{studentId}/guardianInvitations", "studentId@", "GuardianInvitation", "", "w", ""}, + {"classroom.userProfiles.guardianInvitations.get", "classroom", "GET", "v1/userProfiles/{studentId}/guardianInvitations/{invitationId}", "studentId@,invitationId@", "", "", "r", ""}, + {"classroom.userProfiles.guardianInvitations.list", "classroom", "GET", "v1/userProfiles/{studentId}/guardianInvitations", "studentId@,invitedEmailAddress,pageSize#,pageToken,states*", "", "guardianInvitations", "r", ""}, + {"classroom.userProfiles.guardianInvitations.patch", "classroom", "PATCH", "v1/userProfiles/{studentId}/guardianInvitations/{invitationId}", "studentId@,invitationId@,updateMask", "GuardianInvitation", "", "w", ""}, + {"classroom.userProfiles.guardians.delete", "classroom", "DELETE", "v1/userProfiles/{studentId}/guardians/{guardianId}", "guardianId@,studentId@", "", "", "d", ""}, + {"classroom.userProfiles.guardians.get", "classroom", "GET", "v1/userProfiles/{studentId}/guardians/{guardianId}", "guardianId@,studentId@", "", "", "r", ""}, + {"classroom.userProfiles.guardians.list", "classroom", "GET", "v1/userProfiles/{studentId}/guardians", "studentId@,invitedEmailAddress,pageSize#,pageToken", "", "guardians", "r", ""}, + {"youtube.abuseReports.insert", "youtube", "POST", "youtube/v3/abuseReports", "part!*", "AbuseReport", "", "w", ""}, + {"youtube.activities.list", "youtube", "GET", "youtube/v3/activities", "channelId,home?,maxResults#,mine?,pageToken,part!*,publishedAfter,publishedBefore,regionCode", "", "items", "r", ""}, + {"youtube.captions.delete", "youtube", "DELETE", "youtube/v3/captions", "id!,onBehalfOf,onBehalfOfContentOwner", "", "", "d", ""}, + {"youtube.captions.download", "youtube", "GET", "youtube/v3/captions/{id}", "id@,onBehalfOf,onBehalfOfContentOwner,tfmt,tlang", "", "", "r", "db"}, + {"youtube.captions.insert", "youtube", "POST", "youtube/v3/captions", "onBehalfOf,onBehalfOfContentOwner,part!*,sync?", "Caption", "", "w", "u"}, + {"youtube.captions.list", "youtube", "GET", "youtube/v3/captions", "id*,onBehalfOf,onBehalfOfContentOwner,part!*,videoId!", "", "", "r", ""}, + {"youtube.captions.update", "youtube", "PUT", "youtube/v3/captions", "onBehalfOf,onBehalfOfContentOwner,part!*,sync?", "Caption", "", "w", "u"}, + {"youtube.channelBanners.insert", "youtube", "POST", "youtube/v3/channelBanners/insert", "channelId,onBehalfOfContentOwner,onBehalfOfContentOwnerChannel", "ChannelBannerResource", "", "w", "u"}, + {"youtube.channelSections.delete", "youtube", "DELETE", "youtube/v3/channelSections", "id!,onBehalfOfContentOwner", "", "", "d", ""}, + {"youtube.channelSections.insert", "youtube", "POST", "youtube/v3/channelSections", "onBehalfOfContentOwner,onBehalfOfContentOwnerChannel,part!*", "ChannelSection", "", "w", ""}, + {"youtube.channelSections.list", "youtube", "GET", "youtube/v3/channelSections", "channelId,hl,id*,mine?,onBehalfOfContentOwner,part!*", "", "", "r", ""}, + {"youtube.channelSections.update", "youtube", "PUT", "youtube/v3/channelSections", "onBehalfOfContentOwner,part!*", "ChannelSection", "", "w", ""}, + {"youtube.channels.list", "youtube", "GET", "youtube/v3/channels", "categoryId,forHandle,forUsername,hl,id*,managedByMe?,maxResults#,mine?,mySubscribers?,onBehalfOfContentOwner,pageToken,part!*", "", "items", "r", ""}, + {"youtube.channels.update", "youtube", "PUT", "youtube/v3/channels", "onBehalfOfContentOwner,part!*", "Channel", "", "w", ""}, + {"youtube.commentThreads.insert", "youtube", "POST", "youtube/v3/commentThreads", "part!*", "CommentThread", "", "s", ""}, + {"youtube.commentThreads.list", "youtube", "GET", "youtube/v3/commentThreads", "allThreadsRelatedToChannelId,channelId,id*,maxResults#,moderationStatus,order,pageToken,part!*,searchTerms,textFormat,videoId", "", "items", "r", ""}, + {"youtube.comments.delete", "youtube", "DELETE", "youtube/v3/comments", "id!", "", "", "d", ""}, + {"youtube.comments.insert", "youtube", "POST", "youtube/v3/comments", "part!*", "Comment", "", "s", ""}, + {"youtube.comments.list", "youtube", "GET", "youtube/v3/comments", "id*,maxResults#,pageToken,parentId,part!*,textFormat", "", "items", "r", ""}, + {"youtube.comments.markAsSpam", "youtube", "POST", "youtube/v3/comments/markAsSpam", "id!*", "", "", "w", ""}, + {"youtube.comments.setModerationStatus", "youtube", "POST", "youtube/v3/comments/setModerationStatus", "banAuthor?,id!*,moderationStatus!", "", "", "s", ""}, + {"youtube.comments.update", "youtube", "PUT", "youtube/v3/comments", "part!*", "Comment", "", "w", ""}, + {"youtube.i18nLanguages.list", "youtube", "GET", "youtube/v3/i18nLanguages", "hl,part!*", "", "", "r", ""}, + {"youtube.i18nRegions.list", "youtube", "GET", "youtube/v3/i18nRegions", "hl,part!*", "", "", "r", ""}, + {"youtube.liveBroadcasts.bind", "youtube", "POST", "youtube/v3/liveBroadcasts/bind", "id!,onBehalfOfContentOwner,onBehalfOfContentOwnerChannel,part!*,streamId", "", "", "w", ""}, + {"youtube.liveBroadcasts.delete", "youtube", "DELETE", "youtube/v3/liveBroadcasts", "id!,onBehalfOfContentOwner,onBehalfOfContentOwnerChannel", "", "", "d", ""}, + {"youtube.liveBroadcasts.insert", "youtube", "POST", "youtube/v3/liveBroadcasts", "onBehalfOfContentOwner,onBehalfOfContentOwnerChannel,part!*", "LiveBroadcast", "", "w", ""}, + {"youtube.liveBroadcasts.insertCuepoint", "youtube", "POST", "youtube/v3/liveBroadcasts/cuepoint", "id,onBehalfOfContentOwner,onBehalfOfContentOwnerChannel,part*", "Cuepoint", "", "w", ""}, + {"youtube.liveBroadcasts.list", "youtube", "GET", "youtube/v3/liveBroadcasts", "broadcastStatus,broadcastType,id*,maxResults#,mine?,onBehalfOfContentOwner,onBehalfOfContentOwnerChannel,pageToken,part!*", "", "items", "r", ""}, + {"youtube.liveBroadcasts.transition", "youtube", "POST", "youtube/v3/liveBroadcasts/transition", "broadcastStatus!,id!,onBehalfOfContentOwner,onBehalfOfContentOwnerChannel,part!*", "", "", "w", ""}, + {"youtube.liveBroadcasts.update", "youtube", "PUT", "youtube/v3/liveBroadcasts", "onBehalfOfContentOwner,onBehalfOfContentOwnerChannel,part!*", "LiveBroadcast", "", "w", ""}, + {"youtube.liveChatBans.delete", "youtube", "DELETE", "youtube/v3/liveChat/bans", "id!", "", "", "d", ""}, + {"youtube.liveChatBans.insert", "youtube", "POST", "youtube/v3/liveChat/bans", "part!*", "LiveChatBan", "", "w", ""}, + {"youtube.liveChatMessages.delete", "youtube", "DELETE", "youtube/v3/liveChat/messages", "id!", "", "", "d", ""}, + {"youtube.liveChatMessages.insert", "youtube", "POST", "youtube/v3/liveChat/messages", "part!*", "LiveChatMessage", "", "w", ""}, + {"youtube.liveChatMessages.list", "youtube", "GET", "youtube/v3/liveChat/messages", "hl,liveChatId!,maxResults#,pageToken,part!*,profileImageSize#", "", "items", "r", ""}, + {"youtube.liveChatMessages.transition", "youtube", "POST", "youtube/v3/liveChat/messages/transition", "id,status", "", "", "w", ""}, + {"youtube.liveChatModerators.delete", "youtube", "DELETE", "youtube/v3/liveChat/moderators", "id!", "", "", "d", ""}, + {"youtube.liveChatModerators.insert", "youtube", "POST", "youtube/v3/liveChat/moderators", "part!*", "LiveChatModerator", "", "w", ""}, + {"youtube.liveChatModerators.list", "youtube", "GET", "youtube/v3/liveChat/moderators", "liveChatId!,maxResults#,pageToken,part!*", "", "items", "r", ""}, + {"youtube.liveStreams.delete", "youtube", "DELETE", "youtube/v3/liveStreams", "id!,onBehalfOfContentOwner,onBehalfOfContentOwnerChannel", "", "", "d", ""}, + {"youtube.liveStreams.insert", "youtube", "POST", "youtube/v3/liveStreams", "onBehalfOfContentOwner,onBehalfOfContentOwnerChannel,part!*", "LiveStream", "", "w", ""}, + {"youtube.liveStreams.list", "youtube", "GET", "youtube/v3/liveStreams", "id*,maxResults#,mine?,onBehalfOfContentOwner,onBehalfOfContentOwnerChannel,pageToken,part!*", "", "items", "r", ""}, + {"youtube.liveStreams.update", "youtube", "PUT", "youtube/v3/liveStreams", "onBehalfOfContentOwner,onBehalfOfContentOwnerChannel,part!*", "LiveStream", "", "w", ""}, + {"youtube.members.list", "youtube", "GET", "youtube/v3/members", "filterByMemberChannelId,hasAccessToLevel,maxResults#,mode,pageToken,part!*", "", "items", "r", ""}, + {"youtube.membershipsLevels.list", "youtube", "GET", "youtube/v3/membershipsLevels", "part!*", "", "", "r", ""}, + {"youtube.playlistImages.delete", "youtube", "DELETE", "youtube/v3/playlistImages", "id,onBehalfOfContentOwner", "", "", "d", ""}, + {"youtube.playlistImages.insert", "youtube", "POST", "youtube/v3/playlistImages", "onBehalfOfContentOwner,onBehalfOfContentOwnerChannel,part*", "PlaylistImage", "", "w", "u"}, + {"youtube.playlistImages.list", "youtube", "GET", "youtube/v3/playlistImages", "maxResults#,onBehalfOfContentOwner,onBehalfOfContentOwnerChannel,pageToken,parent,part*", "", "items", "r", ""}, + {"youtube.playlistImages.update", "youtube", "PUT", "youtube/v3/playlistImages", "onBehalfOfContentOwner,part*", "PlaylistImage", "", "w", "u"}, + {"youtube.playlistItems.delete", "youtube", "DELETE", "youtube/v3/playlistItems", "id!,onBehalfOfContentOwner", "", "", "d", ""}, + {"youtube.playlistItems.insert", "youtube", "POST", "youtube/v3/playlistItems", "onBehalfOfContentOwner,part!*", "PlaylistItem", "", "w", ""}, + {"youtube.playlistItems.list", "youtube", "GET", "youtube/v3/playlistItems", "id*,maxResults#,onBehalfOfContentOwner,pageToken,part!*,playlistId,videoId", "", "items", "r", ""}, + {"youtube.playlistItems.update", "youtube", "PUT", "youtube/v3/playlistItems", "onBehalfOfContentOwner,part!*", "PlaylistItem", "", "w", ""}, + {"youtube.playlists.delete", "youtube", "DELETE", "youtube/v3/playlists", "id!,onBehalfOfContentOwner", "", "", "d", ""}, + {"youtube.playlists.insert", "youtube", "POST", "youtube/v3/playlists", "onBehalfOfContentOwner,onBehalfOfContentOwnerChannel,part!*", "Playlist", "", "w", ""}, + {"youtube.playlists.list", "youtube", "GET", "youtube/v3/playlists", "channelId,hl,id*,maxResults#,mine?,onBehalfOfContentOwner,onBehalfOfContentOwnerChannel,pageToken,part!*", "", "items", "r", ""}, + {"youtube.playlists.update", "youtube", "PUT", "youtube/v3/playlists", "onBehalfOfContentOwner,part!*", "Playlist", "", "w", ""}, + {"youtube.search.list", "youtube", "GET", "youtube/v3/search", "channelId,channelType,eventType,forContentOwner?,forDeveloper?,forMine?,location,locationRadius,maxResults#,onBehalfOfContentOwner,order,pageToken,part!*,publishedAfter,publishedBefore,q,regionCode,relevanceLanguage,safeSearch,topicId,type*,videoCaption,videoCategoryId,videoDefinition,videoDimension,videoDuration,videoEmbeddable,videoLicense,videoPaidProductPlacement,videoSyndicated,videoType", "", "items", "r", ""}, + {"youtube.subscriptions.delete", "youtube", "DELETE", "youtube/v3/subscriptions", "id!", "", "", "d", ""}, + {"youtube.subscriptions.insert", "youtube", "POST", "youtube/v3/subscriptions", "part!*", "Subscription", "", "w", ""}, + {"youtube.subscriptions.list", "youtube", "GET", "youtube/v3/subscriptions", "channelId,forChannelId,id*,maxResults#,mine?,myRecentSubscribers?,mySubscribers?,onBehalfOfContentOwner,onBehalfOfContentOwnerChannel,order,pageToken,part!*", "", "items", "r", ""}, + {"youtube.superChatEvents.list", "youtube", "GET", "youtube/v3/superChatEvents", "hl,maxResults#,pageToken,part!*", "", "items", "r", ""}, + {"youtube.tests.insert", "youtube", "POST", "youtube/v3/tests", "externalChannelId,onBehalfOfContentOwnerChannel,part!*", "TestItem", "", "w", ""}, + {"youtube.thirdPartyLinks.delete", "youtube", "DELETE", "youtube/v3/thirdPartyLinks", "externalChannelId,linkingToken!,part*,type!", "", "", "d", ""}, + {"youtube.thirdPartyLinks.insert", "youtube", "POST", "youtube/v3/thirdPartyLinks", "externalChannelId,part!*", "ThirdPartyLink", "", "w", ""}, + {"youtube.thirdPartyLinks.list", "youtube", "GET", "youtube/v3/thirdPartyLinks", "externalChannelId,linkingToken,part!*,type", "", "", "r", ""}, + {"youtube.thirdPartyLinks.update", "youtube", "PUT", "youtube/v3/thirdPartyLinks", "externalChannelId,part!*", "ThirdPartyLink", "", "w", ""}, + {"youtube.thumbnails.set", "youtube", "POST", "youtube/v3/thumbnails/set", "onBehalfOfContentOwner,videoId!", "", "", "w", "u"}, + {"youtube.videoAbuseReportReasons.list", "youtube", "GET", "youtube/v3/videoAbuseReportReasons", "hl,part!*", "", "", "r", ""}, + {"youtube.videoCategories.list", "youtube", "GET", "youtube/v3/videoCategories", "hl,id*,part!*,regionCode", "", "", "r", ""}, + {"youtube.videoTrainability.get", "youtube", "GET", "youtube/v3/videoTrainability", "id", "", "", "r", ""}, + {"youtube.videos.batchGetStats", "youtube", "GET", "youtube/v3/videos:batchGetStats", "id*,onBehalfOfContentOwner,part*", "", "", "r", ""}, + {"youtube.videos.delete", "youtube", "DELETE", "youtube/v3/videos", "id!,onBehalfOfContentOwner", "", "", "d", ""}, + {"youtube.videos.getRating", "youtube", "GET", "youtube/v3/videos/getRating", "id!*,onBehalfOfContentOwner", "", "", "r", ""}, + {"youtube.videos.insert", "youtube", "POST", "youtube/v3/videos", "autoLevels?,notifySubscribers?,onBehalfOfContentOwner,onBehalfOfContentOwnerChannel,part!*,stabilize?", "Video", "", "w", "u"}, + {"youtube.videos.list", "youtube", "GET", "youtube/v3/videos", "chart,hl,id*,locale,maxHeight#,maxResults#,maxWidth#,myRating,onBehalfOfContentOwner,pageToken,part!*,regionCode,videoCategoryId", "", "items", "r", ""}, + {"youtube.videos.rate", "youtube", "POST", "youtube/v3/videos/rate", "id!,rating!", "", "", "w", ""}, + {"youtube.videos.reportAbuse", "youtube", "POST", "youtube/v3/videos/reportAbuse", "onBehalfOfContentOwner", "VideoAbuseReport", "", "w", ""}, + {"youtube.videos.update", "youtube", "PUT", "youtube/v3/videos", "onBehalfOfContentOwner,part!*", "Video", "", "w", ""}, + {"youtube.watermarks.set", "youtube", "POST", "youtube/v3/watermarks/set", "channelId!,onBehalfOfContentOwner", "InvideoBranding", "", "w", "u"}, + {"youtube.watermarks.unset", "youtube", "POST", "youtube/v3/watermarks/unset", "channelId!,onBehalfOfContentOwner", "", "", "w", ""}, + {"youtube.youtube.v3.liveChat.messages.stream", "youtube", "GET", "youtube/v3/liveChat/messages/stream", "hl,liveChatId,maxResults#,pageToken,part*,profileImageSize#", "", "items", "r", ""}, + {"youtubeAnalytics.groupItems.delete", "youtubeanalytics", "DELETE", "v2/groupItems", "id,onBehalfOfContentOwner", "", "", "d", ""}, + {"youtubeAnalytics.groupItems.insert", "youtubeanalytics", "POST", "v2/groupItems", "onBehalfOfContentOwner", "GroupItem", "", "w", ""}, + {"youtubeAnalytics.groupItems.list", "youtubeanalytics", "GET", "v2/groupItems", "groupId,onBehalfOfContentOwner", "", "", "r", ""}, + {"youtubeAnalytics.groups.delete", "youtubeanalytics", "DELETE", "v2/groups", "id,onBehalfOfContentOwner", "", "", "d", ""}, + {"youtubeAnalytics.groups.insert", "youtubeanalytics", "POST", "v2/groups", "onBehalfOfContentOwner", "Group", "", "w", ""}, + {"youtubeAnalytics.groups.list", "youtubeanalytics", "GET", "v2/groups", "id,mine?,onBehalfOfContentOwner,pageToken", "", "items", "r", ""}, + {"youtubeAnalytics.groups.update", "youtubeanalytics", "PUT", "v2/groups", "onBehalfOfContentOwner", "Group", "", "w", ""}, + {"youtubeAnalytics.reports.query", "youtubeanalytics", "GET", "v2/reports", "currency,dimensions,endDate,filters,ids,includeHistoricalChannelData?,maxResults#,metrics,sort,startDate,startIndex#", "", "", "r", ""}, + {"youtubereporting.jobs.create", "youtubereporting", "POST", "v1/jobs", "onBehalfOfContentOwner", "Job", "", "w", ""}, + {"youtubereporting.jobs.delete", "youtubereporting", "DELETE", "v1/jobs/{jobId}", "jobId@,onBehalfOfContentOwner", "", "", "d", ""}, + {"youtubereporting.jobs.get", "youtubereporting", "GET", "v1/jobs/{jobId}", "jobId@,onBehalfOfContentOwner", "", "", "r", ""}, + {"youtubereporting.jobs.list", "youtubereporting", "GET", "v1/jobs", "includeSystemManaged?,onBehalfOfContentOwner,pageSize#,pageToken", "", "jobs", "r", ""}, + {"youtubereporting.jobs.reports.get", "youtubereporting", "GET", "v1/jobs/{jobId}/reports/{reportId}", "jobId@,reportId@,onBehalfOfContentOwner", "", "", "r", ""}, + {"youtubereporting.jobs.reports.list", "youtubereporting", "GET", "v1/jobs/{jobId}/reports", "jobId@,createdAfter,onBehalfOfContentOwner,pageSize#,pageToken,startTimeAtOrAfter,startTimeBefore", "", "reports", "r", ""}, + {"youtubereporting.media.download", "youtubereporting", "GET", "v1/media/{+resourceName}", "resourceName@", "", "", "r", "d"}, + {"youtubereporting.reportTypes.list", "youtubereporting", "GET", "v1/reportTypes", "includeSystemManaged?,onBehalfOfContentOwner,pageSize#,pageToken", "", "reportTypes", "r", ""}, + {"admin.channels.stop", "directory", "POST", "admin/directory_v1/channels/stop", "", "Channel", "", "w", ""}, + {"admin.customer.devices.chromeos.batchChangeStatus", "directory", "POST", "admin/directory/v1/customer/{customerId}/devices/chromeos:batchChangeStatus", "customerId@", "BatchChangeChromeOsDeviceStatusRequest", "", "w", ""}, + {"admin.customer.devices.chromeos.commands.get", "directory", "GET", "admin/directory/v1/customer/{customerId}/devices/chromeos/{deviceId}/commands/{commandId}", "customerId@,commandId@,deviceId@", "", "", "r", ""}, + {"admin.customer.devices.chromeos.countChromeOsDevices", "directory", "GET", "admin/directory/v1/customer/{customerId}/devices/chromeos:countChromeOsDevices", "customerId@,filter,includeChildOrgunits?,orgUnitPath", "", "", "r", ""}, + {"admin.customer.devices.chromeos.issueCommand", "directory", "POST", "admin/directory/v1/customer/{customerId}/devices/chromeos/{deviceId}:issueCommand", "customerId@,deviceId@", "DirectoryChromeosdevicesIssueCommandRequest", "", "w", ""}, + {"admin.customers.chrome.printServers.batchCreatePrintServers", "directory", "POST", "admin/directory/v1/{+parent}/chrome/printServers:batchCreatePrintServers", "parent@", "BatchCreatePrintServersRequest", "", "w", ""}, + {"admin.customers.chrome.printServers.batchDeletePrintServers", "directory", "POST", "admin/directory/v1/{+parent}/chrome/printServers:batchDeletePrintServers", "parent@", "BatchDeletePrintServersRequest", "", "d", ""}, + {"admin.customers.chrome.printServers.create", "directory", "POST", "admin/directory/v1/{+parent}/chrome/printServers", "parent@", "PrintServer", "", "w", ""}, + {"admin.customers.chrome.printServers.delete", "directory", "DELETE", "admin/directory/v1/{+name}", "name@", "", "", "d", ""}, + {"admin.customers.chrome.printServers.get", "directory", "GET", "admin/directory/v1/{+name}", "name@", "", "", "r", ""}, + {"admin.customers.chrome.printServers.list", "directory", "GET", "admin/directory/v1/{+parent}/chrome/printServers", "parent@,filter,orderBy,orgUnitId,pageSize#,pageToken", "", "printServers", "r", ""}, + {"admin.customers.chrome.printServers.patch", "directory", "PATCH", "admin/directory/v1/{+name}", "name@,updateMask", "PrintServer", "", "w", ""}, + {"admin.customers.chrome.printers.batchCreatePrinters", "directory", "POST", "admin/directory/v1/{+parent}/chrome/printers:batchCreatePrinters", "parent@", "BatchCreatePrintersRequest", "", "w", ""}, + {"admin.customers.chrome.printers.batchDeletePrinters", "directory", "POST", "admin/directory/v1/{+parent}/chrome/printers:batchDeletePrinters", "parent@", "BatchDeletePrintersRequest", "", "d", ""}, + {"admin.customers.chrome.printers.create", "directory", "POST", "admin/directory/v1/{+parent}/chrome/printers", "parent@", "Printer", "", "w", ""}, + {"admin.customers.chrome.printers.delete", "directory", "DELETE", "admin/directory/v1/{+name}", "name@", "", "", "d", ""}, + {"admin.customers.chrome.printers.get", "directory", "GET", "admin/directory/v1/{+name}", "name@", "", "", "r", ""}, + {"admin.customers.chrome.printers.list", "directory", "GET", "admin/directory/v1/{+parent}/chrome/printers", "parent@,filter,orderBy,orgUnitId,pageSize#,pageToken", "", "printers", "r", ""}, + {"admin.customers.chrome.printers.listPrinterModels", "directory", "GET", "admin/directory/v1/{+parent}/chrome/printers:listPrinterModels", "parent@,filter,pageSize#,pageToken", "", "printerModels", "r", ""}, + {"admin.customers.chrome.printers.patch", "directory", "PATCH", "admin/directory/v1/{+name}", "name@,clearMask,updateMask", "Printer", "", "w", ""}, + {"directory.asps.delete", "directory", "DELETE", "admin/directory/v1/users/{userKey}/asps/{codeId}", "userKey@,codeId@#", "", "", "d", ""}, + {"directory.asps.get", "directory", "GET", "admin/directory/v1/users/{userKey}/asps/{codeId}", "userKey@,codeId@#", "", "", "r", ""}, + {"directory.asps.list", "directory", "GET", "admin/directory/v1/users/{userKey}/asps", "userKey@", "", "", "r", ""}, + {"directory.chromeosdevices.action", "directory", "POST", "admin/directory/v1/customer/{customerId}/devices/chromeos/{resourceId}/action", "resourceId@,customerId@", "ChromeOsDeviceAction", "", "d", ""}, + {"directory.chromeosdevices.get", "directory", "GET", "admin/directory/v1/customer/{customerId}/devices/chromeos/{deviceId}", "deviceId@,customerId@,projection", "", "", "r", ""}, + {"directory.chromeosdevices.list", "directory", "GET", "admin/directory/v1/customer/{customerId}/devices/chromeos", "customerId@,includeChildOrgunits?,maxResults#,orderBy,orgUnitPath,pageToken,projection,query,sortOrder", "", "chromeosdevices", "r", ""}, + {"directory.chromeosdevices.moveDevicesToOu", "directory", "POST", "admin/directory/v1/customer/{customerId}/devices/chromeos/moveDevicesToOu", "customerId@,orgUnitPath!", "ChromeOsMoveDevicesToOu", "", "w", ""}, + {"directory.chromeosdevices.patch", "directory", "PATCH", "admin/directory/v1/customer/{customerId}/devices/chromeos/{deviceId}", "customerId@,deviceId@,projection", "ChromeOsDevice", "", "w", ""}, + {"directory.chromeosdevices.update", "directory", "PUT", "admin/directory/v1/customer/{customerId}/devices/chromeos/{deviceId}", "deviceId@,customerId@,projection", "ChromeOsDevice", "", "w", ""}, + {"directory.customers.get", "directory", "GET", "admin/directory/v1/customers/{customerKey}", "customerKey@", "", "", "r", ""}, + {"directory.customers.patch", "directory", "PATCH", "admin/directory/v1/customers/{customerKey}", "customerKey@", "Customer", "", "w", ""}, + {"directory.customers.update", "directory", "PUT", "admin/directory/v1/customers/{customerKey}", "customerKey@", "Customer", "", "w", ""}, + {"directory.domainAliases.delete", "directory", "DELETE", "admin/directory/v1/customer/{customer}/domainaliases/{domainAliasName}", "customer@,domainAliasName@", "", "", "d", ""}, + {"directory.domainAliases.get", "directory", "GET", "admin/directory/v1/customer/{customer}/domainaliases/{domainAliasName}", "domainAliasName@,customer@", "", "", "r", ""}, + {"directory.domainAliases.insert", "directory", "POST", "admin/directory/v1/customer/{customer}/domainaliases", "customer@", "DomainAlias", "", "w", ""}, + {"directory.domainAliases.list", "directory", "GET", "admin/directory/v1/customer/{customer}/domainaliases", "customer@,parentDomainName", "", "", "r", ""}, + {"directory.domains.delete", "directory", "DELETE", "admin/directory/v1/customer/{customer}/domains/{domainName}", "domainName@,customer@", "", "", "d", ""}, + {"directory.domains.get", "directory", "GET", "admin/directory/v1/customer/{customer}/domains/{domainName}", "domainName@,customer@", "", "", "r", ""}, + {"directory.domains.insert", "directory", "POST", "admin/directory/v1/customer/{customer}/domains", "customer@", "Domains", "", "w", ""}, + {"directory.domains.list", "directory", "GET", "admin/directory/v1/customer/{customer}/domains", "customer@", "", "", "r", ""}, + {"directory.groups.aliases.delete", "directory", "DELETE", "admin/directory/v1/groups/{groupKey}/aliases/{alias}", "groupKey@,alias@", "", "", "d", ""}, + {"directory.groups.aliases.insert", "directory", "POST", "admin/directory/v1/groups/{groupKey}/aliases", "groupKey@", "Alias", "", "w", ""}, + {"directory.groups.aliases.list", "directory", "GET", "admin/directory/v1/groups/{groupKey}/aliases", "groupKey@", "", "", "r", ""}, + {"directory.groups.delete", "directory", "DELETE", "admin/directory/v1/groups/{groupKey}", "groupKey@", "", "", "d", ""}, + {"directory.groups.get", "directory", "GET", "admin/directory/v1/groups/{groupKey}", "groupKey@", "", "", "r", ""}, + {"directory.groups.insert", "directory", "POST", "admin/directory/v1/groups", "", "Group", "", "w", ""}, + {"directory.groups.list", "directory", "GET", "admin/directory/v1/groups", "customer,domain,maxResults#,orderBy,pageToken,query,sortOrder,userKey", "", "groups", "r", ""}, + {"directory.groups.patch", "directory", "PATCH", "admin/directory/v1/groups/{groupKey}", "groupKey@", "Group", "", "w", ""}, + {"directory.groups.update", "directory", "PUT", "admin/directory/v1/groups/{groupKey}", "groupKey@", "Group", "", "w", ""}, + {"directory.members.delete", "directory", "DELETE", "admin/directory/v1/groups/{groupKey}/members/{memberKey}", "groupKey@,memberKey@", "", "", "d", ""}, + {"directory.members.get", "directory", "GET", "admin/directory/v1/groups/{groupKey}/members/{memberKey}", "groupKey@,memberKey@", "", "", "r", ""}, + {"directory.members.hasMember", "directory", "GET", "admin/directory/v1/groups/{groupKey}/hasMember/{memberKey}", "groupKey@,memberKey@", "", "", "r", ""}, + {"directory.members.insert", "directory", "POST", "admin/directory/v1/groups/{groupKey}/members", "groupKey@", "Member", "", "w", ""}, + {"directory.members.list", "directory", "GET", "admin/directory/v1/groups/{groupKey}/members", "groupKey@,includeDerivedMembership?,maxResults#,pageToken,roles", "", "members", "r", ""}, + {"directory.members.patch", "directory", "PATCH", "admin/directory/v1/groups/{groupKey}/members/{memberKey}", "groupKey@,memberKey@", "Member", "", "w", ""}, + {"directory.members.update", "directory", "PUT", "admin/directory/v1/groups/{groupKey}/members/{memberKey}", "groupKey@,memberKey@", "Member", "", "w", ""}, + {"directory.mobiledevices.action", "directory", "POST", "admin/directory/v1/customer/{customerId}/devices/mobile/{resourceId}/action", "resourceId@,customerId@", "MobileDeviceAction", "", "d", ""}, + {"directory.mobiledevices.delete", "directory", "DELETE", "admin/directory/v1/customer/{customerId}/devices/mobile/{resourceId}", "customerId@,resourceId@", "", "", "d", ""}, + {"directory.mobiledevices.get", "directory", "GET", "admin/directory/v1/customer/{customerId}/devices/mobile/{resourceId}", "customerId@,resourceId@,projection", "", "", "r", ""}, + {"directory.mobiledevices.list", "directory", "GET", "admin/directory/v1/customer/{customerId}/devices/mobile", "customerId@,maxResults#,orderBy,pageToken,projection,query,sortOrder", "", "mobiledevices", "r", ""}, + {"directory.orgunits.delete", "directory", "DELETE", "admin/directory/v1/customer/{customerId}/orgunits/{+orgUnitPath}", "customerId@,orgUnitPath@", "", "", "d", ""}, + {"directory.orgunits.get", "directory", "GET", "admin/directory/v1/customer/{customerId}/orgunits/{+orgUnitPath}", "orgUnitPath@,customerId@", "", "", "r", ""}, + {"directory.orgunits.insert", "directory", "POST", "admin/directory/v1/customer/{customerId}/orgunits", "customerId@", "OrgUnit", "", "w", ""}, + {"directory.orgunits.list", "directory", "GET", "admin/directory/v1/customer/{customerId}/orgunits", "customerId@,orgUnitPath,type", "", "", "r", ""}, + {"directory.orgunits.patch", "directory", "PATCH", "admin/directory/v1/customer/{customerId}/orgunits/{+orgUnitPath}", "customerId@,orgUnitPath@", "OrgUnit", "", "w", ""}, + {"directory.orgunits.update", "directory", "PUT", "admin/directory/v1/customer/{customerId}/orgunits/{+orgUnitPath}", "orgUnitPath@,customerId@", "OrgUnit", "", "w", ""}, + {"directory.privileges.list", "directory", "GET", "admin/directory/v1/customer/{customer}/roles/ALL/privileges", "customer@", "", "", "r", ""}, + {"directory.resources.buildings.delete", "directory", "DELETE", "admin/directory/v1/customer/{customer}/resources/buildings/{buildingId}", "buildingId@,customer@", "", "", "d", ""}, + {"directory.resources.buildings.get", "directory", "GET", "admin/directory/v1/customer/{customer}/resources/buildings/{buildingId}", "customer@,buildingId@", "", "", "r", ""}, + {"directory.resources.buildings.insert", "directory", "POST", "admin/directory/v1/customer/{customer}/resources/buildings", "customer@,coordinatesSource", "Building", "", "w", ""}, + {"directory.resources.buildings.list", "directory", "GET", "admin/directory/v1/customer/{customer}/resources/buildings", "customer@,maxResults#,pageToken", "", "buildings", "r", ""}, + {"directory.resources.buildings.patch", "directory", "PATCH", "admin/directory/v1/customer/{customer}/resources/buildings/{buildingId}", "customer@,buildingId@,coordinatesSource", "Building", "", "w", ""}, + {"directory.resources.buildings.update", "directory", "PUT", "admin/directory/v1/customer/{customer}/resources/buildings/{buildingId}", "customer@,buildingId@,coordinatesSource", "Building", "", "w", ""}, + {"directory.resources.calendars.delete", "directory", "DELETE", "admin/directory/v1/customer/{customer}/resources/calendars/{calendarResourceId}", "calendarResourceId@,customer@", "", "", "d", ""}, + {"directory.resources.calendars.get", "directory", "GET", "admin/directory/v1/customer/{customer}/resources/calendars/{calendarResourceId}", "calendarResourceId@,customer@", "", "", "r", ""}, + {"directory.resources.calendars.insert", "directory", "POST", "admin/directory/v1/customer/{customer}/resources/calendars", "customer@", "CalendarResource", "", "w", ""}, + {"directory.resources.calendars.list", "directory", "GET", "admin/directory/v1/customer/{customer}/resources/calendars", "customer@,maxResults#,orderBy,pageToken,query", "", "items", "r", ""}, + {"directory.resources.calendars.patch", "directory", "PATCH", "admin/directory/v1/customer/{customer}/resources/calendars/{calendarResourceId}", "calendarResourceId@,customer@", "CalendarResource", "", "w", ""}, + {"directory.resources.calendars.update", "directory", "PUT", "admin/directory/v1/customer/{customer}/resources/calendars/{calendarResourceId}", "customer@,calendarResourceId@", "CalendarResource", "", "w", ""}, + {"directory.resources.features.delete", "directory", "DELETE", "admin/directory/v1/customer/{customer}/resources/features/{featureKey}", "customer@,featureKey@", "", "", "d", ""}, + {"directory.resources.features.get", "directory", "GET", "admin/directory/v1/customer/{customer}/resources/features/{featureKey}", "featureKey@,customer@", "", "", "r", ""}, + {"directory.resources.features.insert", "directory", "POST", "admin/directory/v1/customer/{customer}/resources/features", "customer@", "Feature", "", "w", ""}, + {"directory.resources.features.list", "directory", "GET", "admin/directory/v1/customer/{customer}/resources/features", "customer@,maxResults#,pageToken", "", "features", "r", ""}, + {"directory.resources.features.patch", "directory", "PATCH", "admin/directory/v1/customer/{customer}/resources/features/{featureKey}", "customer@,featureKey@", "Feature", "", "w", ""}, + {"directory.resources.features.rename", "directory", "POST", "admin/directory/v1/customer/{customer}/resources/features/{oldName}/rename", "customer@,oldName@", "FeatureRename", "", "w", ""}, + {"directory.resources.features.update", "directory", "PUT", "admin/directory/v1/customer/{customer}/resources/features/{featureKey}", "customer@,featureKey@", "Feature", "", "w", ""}, + {"directory.roleAssignments.delete", "directory", "DELETE", "admin/directory/v1/customer/{customer}/roleassignments/{roleAssignmentId}", "customer@,roleAssignmentId@", "", "", "d", ""}, + {"directory.roleAssignments.get", "directory", "GET", "admin/directory/v1/customer/{customer}/roleassignments/{roleAssignmentId}", "roleAssignmentId@,customer@", "", "", "r", ""}, + {"directory.roleAssignments.insert", "directory", "POST", "admin/directory/v1/customer/{customer}/roleassignments", "customer@", "RoleAssignment", "", "w", ""}, + {"directory.roleAssignments.list", "directory", "GET", "admin/directory/v1/customer/{customer}/roleassignments", "customer@,includeIndirectRoleAssignments?,maxResults#,pageToken,roleId,userKey", "", "items", "r", ""}, + {"directory.roles.delete", "directory", "DELETE", "admin/directory/v1/customer/{customer}/roles/{roleId}", "customer@,roleId@", "", "", "d", ""}, + {"directory.roles.get", "directory", "GET", "admin/directory/v1/customer/{customer}/roles/{roleId}", "customer@,roleId@", "", "", "r", ""}, + {"directory.roles.insert", "directory", "POST", "admin/directory/v1/customer/{customer}/roles", "customer@", "Role", "", "w", ""}, + {"directory.roles.list", "directory", "GET", "admin/directory/v1/customer/{customer}/roles", "customer@,maxResults#,pageToken", "", "items", "r", ""}, + {"directory.roles.patch", "directory", "PATCH", "admin/directory/v1/customer/{customer}/roles/{roleId}", "roleId@,customer@", "Role", "", "w", ""}, + {"directory.roles.update", "directory", "PUT", "admin/directory/v1/customer/{customer}/roles/{roleId}", "customer@,roleId@", "Role", "", "w", ""}, + {"directory.schemas.delete", "directory", "DELETE", "admin/directory/v1/customer/{customerId}/schemas/{schemaKey}", "customerId@,schemaKey@", "", "", "d", ""}, + {"directory.schemas.get", "directory", "GET", "admin/directory/v1/customer/{customerId}/schemas/{schemaKey}", "customerId@,schemaKey@", "", "", "r", ""}, + {"directory.schemas.insert", "directory", "POST", "admin/directory/v1/customer/{customerId}/schemas", "customerId@", "Schema", "", "w", ""}, + {"directory.schemas.list", "directory", "GET", "admin/directory/v1/customer/{customerId}/schemas", "customerId@", "", "", "r", ""}, + {"directory.schemas.patch", "directory", "PATCH", "admin/directory/v1/customer/{customerId}/schemas/{schemaKey}", "customerId@,schemaKey@", "Schema", "", "w", ""}, + {"directory.schemas.update", "directory", "PUT", "admin/directory/v1/customer/{customerId}/schemas/{schemaKey}", "customerId@,schemaKey@", "Schema", "", "w", ""}, + {"directory.tokens.delete", "directory", "DELETE", "admin/directory/v1/users/{userKey}/tokens/{clientId}", "clientId@,userKey@", "", "", "d", ""}, + {"directory.tokens.get", "directory", "GET", "admin/directory/v1/users/{userKey}/tokens/{clientId}", "clientId@,userKey@", "", "", "r", ""}, + {"directory.tokens.list", "directory", "GET", "admin/directory/v1/users/{userKey}/tokens", "userKey@", "", "", "r", ""}, + {"directory.twoStepVerification.turnOff", "directory", "POST", "admin/directory/v1/users/{userKey}/twoStepVerification/turnOff", "userKey@", "", "", "w", ""}, + {"directory.users.aliases.delete", "directory", "DELETE", "admin/directory/v1/users/{userKey}/aliases/{alias}", "userKey@,alias@", "", "", "d", ""}, + {"directory.users.aliases.insert", "directory", "POST", "admin/directory/v1/users/{userKey}/aliases", "userKey@", "Alias", "", "w", ""}, + {"directory.users.aliases.list", "directory", "GET", "admin/directory/v1/users/{userKey}/aliases", "userKey@,event", "", "", "r", ""}, + {"directory.users.aliases.watch", "directory", "POST", "admin/directory/v1/users/{userKey}/aliases/watch", "userKey@,event", "Channel", "", "w", ""}, + {"directory.users.createGuest", "directory", "POST", "admin/directory/v1/users:createGuest", "", "DirectoryUsersCreateGuestRequest", "", "w", ""}, + {"directory.users.delete", "directory", "DELETE", "admin/directory/v1/users/{userKey}", "userKey@", "", "", "d", ""}, + {"directory.users.get", "directory", "GET", "admin/directory/v1/users/{userKey}", "userKey@,customFieldMask,projection,viewType", "", "", "r", ""}, + {"directory.users.insert", "directory", "POST", "admin/directory/v1/users", "resolveConflictAccount?", "User", "", "w", ""}, + {"directory.users.list", "directory", "GET", "admin/directory/v1/users", "customFieldMask,customer,domain,event,maxResults#,orderBy,pageToken,projection,query,showDeleted,sortOrder,viewType", "", "users", "r", ""}, + {"directory.users.makeAdmin", "directory", "POST", "admin/directory/v1/users/{userKey}/makeAdmin", "userKey@", "UserMakeAdmin", "", "d", ""}, + {"directory.users.patch", "directory", "PATCH", "admin/directory/v1/users/{userKey}", "userKey@", "User", "", "w", ""}, + {"directory.users.photos.delete", "directory", "DELETE", "admin/directory/v1/users/{userKey}/photos/thumbnail", "userKey@", "", "", "d", ""}, + {"directory.users.photos.get", "directory", "GET", "admin/directory/v1/users/{userKey}/photos/thumbnail", "userKey@", "", "", "r", ""}, + {"directory.users.photos.patch", "directory", "PATCH", "admin/directory/v1/users/{userKey}/photos/thumbnail", "userKey@", "UserPhoto", "", "w", ""}, + {"directory.users.photos.update", "directory", "PUT", "admin/directory/v1/users/{userKey}/photos/thumbnail", "userKey@", "UserPhoto", "", "w", ""}, + {"directory.users.signOut", "directory", "POST", "admin/directory/v1/users/{userKey}/signOut", "userKey@", "", "", "d", ""}, + {"directory.users.undelete", "directory", "POST", "admin/directory/v1/users/{userKey}/undelete", "userKey@", "UserUndelete", "", "w", ""}, + {"directory.users.update", "directory", "PUT", "admin/directory/v1/users/{userKey}", "userKey@", "User", "", "w", ""}, + {"directory.users.watch", "directory", "POST", "admin/directory/v1/users/watch", "customFieldMask,customer,domain,event,maxResults#,orderBy,pageToken,projection,query,showDeleted,sortOrder,viewType", "Channel", "", "w", ""}, + {"directory.verificationCodes.generate", "directory", "POST", "admin/directory/v1/users/{userKey}/verificationCodes/generate", "userKey@", "", "", "w", ""}, + {"directory.verificationCodes.invalidate", "directory", "POST", "admin/directory/v1/users/{userKey}/verificationCodes/invalidate", "userKey@", "", "", "w", ""}, + {"directory.verificationCodes.list", "directory", "GET", "admin/directory/v1/users/{userKey}/verificationCodes", "userKey@", "", "", "r", ""}, + {"admin.channels.stop", "reports", "POST", "admin/reports_v1/channels/stop", "", "Channel", "", "w", ""}, + {"reports.activities.list", "reports", "GET", "admin/reports/v1/activity/users/{userKey}/applications/{applicationName}", "userKey@,applicationName@,actorIpAddress,agentInfoFilter,applicationInfoFilter,customerId,deviceFilter,endTime,eventName,filters,groupIdFilter,includeSensitiveData?,maxResults#,networkInfoFilter,orgUnitID,pageToken,resourceDetailsFilter,startTime,statusFilter", "", "items", "r", ""}, + {"reports.activities.watch", "reports", "POST", "admin/reports/v1/activity/users/{userKey}/applications/{applicationName}/watch", "userKey@,applicationName@,actorIpAddress,customerId,endTime,eventName,filters,groupIdFilter,maxResults#,orgUnitID,pageToken,startTime", "Channel", "", "w", ""}, + {"reports.customerUsageReports.get", "reports", "GET", "admin/reports/v1/usage/dates/{date}", "date@,customerId,pageToken,parameters", "", "", "r", ""}, + {"reports.entityUsageReports.get", "reports", "GET", "admin/reports/v1/usage/{entityType}/{entityKey}/dates/{date}", "entityType@,date@,entityKey@,customerId,filters,maxResults#,pageToken,parameters", "", "", "r", ""}, + {"reports.userUsageReport.get", "reports", "GET", "admin/reports/v1/usage/users/{userKey}/dates/{date}", "date@,userKey@,customerId,filters,groupIdFilter,maxResults#,orgUnitID,pageToken,parameters", "", "", "r", ""}, + {"groupsSettings.groups.get", "groupssettings", "GET", "{groupUniqueId}", "groupUniqueId@", "", "", "r", ""}, + {"groupsSettings.groups.patch", "groupssettings", "PATCH", "{groupUniqueId}", "groupUniqueId@", "Groups", "", "w", ""}, + {"groupsSettings.groups.update", "groupssettings", "PUT", "{groupUniqueId}", "groupUniqueId@", "Groups", "", "w", ""}, + {"vault.matters.addPermissions", "vault", "POST", "v1/matters/{matterId}:addPermissions", "matterId@", "AddMatterPermissionsRequest", "", "w", ""}, + {"vault.matters.close", "vault", "POST", "v1/matters/{matterId}:close", "matterId@", "CloseMatterRequest", "", "d", ""}, + {"vault.matters.count", "vault", "POST", "v1/matters/{matterId}:count", "matterId@", "CountArtifactsRequest", "", "w", ""}, + {"vault.matters.create", "vault", "POST", "v1/matters", "", "Matter", "", "w", ""}, + {"vault.matters.delete", "vault", "DELETE", "v1/matters/{matterId}", "matterId@", "", "", "d", ""}, + {"vault.matters.exports.create", "vault", "POST", "v1/matters/{matterId}/exports", "matterId@", "Export", "", "w", ""}, + {"vault.matters.exports.delete", "vault", "DELETE", "v1/matters/{matterId}/exports/{exportId}", "matterId@,exportId@", "", "", "d", ""}, + {"vault.matters.exports.get", "vault", "GET", "v1/matters/{matterId}/exports/{exportId}", "exportId@,matterId@", "", "", "r", ""}, + {"vault.matters.exports.list", "vault", "GET", "v1/matters/{matterId}/exports", "matterId@,pageSize#,pageToken", "", "exports", "r", ""}, + {"vault.matters.get", "vault", "GET", "v1/matters/{matterId}", "matterId@,view", "", "", "r", ""}, + {"vault.matters.holds.accounts.create", "vault", "POST", "v1/matters/{matterId}/holds/{holdId}/accounts", "matterId@,holdId@", "HeldAccount", "", "w", ""}, + {"vault.matters.holds.accounts.delete", "vault", "DELETE", "v1/matters/{matterId}/holds/{holdId}/accounts/{accountId}", "holdId@,accountId@,matterId@", "", "", "d", ""}, + {"vault.matters.holds.accounts.list", "vault", "GET", "v1/matters/{matterId}/holds/{holdId}/accounts", "holdId@,matterId@", "", "", "r", ""}, + {"vault.matters.holds.addHeldAccounts", "vault", "POST", "v1/matters/{matterId}/holds/{holdId}:addHeldAccounts", "matterId@,holdId@", "AddHeldAccountsRequest", "", "w", ""}, + {"vault.matters.holds.create", "vault", "POST", "v1/matters/{matterId}/holds", "matterId@", "Hold", "", "w", ""}, + {"vault.matters.holds.delete", "vault", "DELETE", "v1/matters/{matterId}/holds/{holdId}", "matterId@,holdId@", "", "", "d", ""}, + {"vault.matters.holds.get", "vault", "GET", "v1/matters/{matterId}/holds/{holdId}", "matterId@,holdId@,view", "", "", "r", ""}, + {"vault.matters.holds.list", "vault", "GET", "v1/matters/{matterId}/holds", "matterId@,pageSize#,pageToken,view", "", "holds", "r", ""}, + {"vault.matters.holds.removeHeldAccounts", "vault", "POST", "v1/matters/{matterId}/holds/{holdId}:removeHeldAccounts", "matterId@,holdId@", "RemoveHeldAccountsRequest", "", "d", ""}, + {"vault.matters.holds.update", "vault", "PUT", "v1/matters/{matterId}/holds/{holdId}", "holdId@,matterId@", "Hold", "", "w", ""}, + {"vault.matters.list", "vault", "GET", "v1/matters", "pageSize#,pageToken,state,view", "", "matters", "r", ""}, + {"vault.matters.removePermissions", "vault", "POST", "v1/matters/{matterId}:removePermissions", "matterId@", "RemoveMatterPermissionsRequest", "", "d", ""}, + {"vault.matters.reopen", "vault", "POST", "v1/matters/{matterId}:reopen", "matterId@", "ReopenMatterRequest", "", "w", ""}, + {"vault.matters.savedQueries.create", "vault", "POST", "v1/matters/{matterId}/savedQueries", "matterId@", "SavedQuery", "", "w", ""}, + {"vault.matters.savedQueries.delete", "vault", "DELETE", "v1/matters/{matterId}/savedQueries/{savedQueryId}", "matterId@,savedQueryId@", "", "", "d", ""}, + {"vault.matters.savedQueries.get", "vault", "GET", "v1/matters/{matterId}/savedQueries/{savedQueryId}", "savedQueryId@,matterId@", "", "", "r", ""}, + {"vault.matters.savedQueries.list", "vault", "GET", "v1/matters/{matterId}/savedQueries", "matterId@,pageSize#,pageToken", "", "savedQueries", "r", ""}, + {"vault.matters.undelete", "vault", "POST", "v1/matters/{matterId}:undelete", "matterId@", "UndeleteMatterRequest", "", "w", ""}, + {"vault.matters.update", "vault", "PUT", "v1/matters/{matterId}", "matterId@", "Matter", "", "w", ""}, + {"vault.operations.cancel", "vault", "POST", "v1/{+name}:cancel", "name@", "CancelOperationRequest", "", "w", ""}, + {"vault.operations.delete", "vault", "DELETE", "v1/{+name}", "name@", "", "", "d", ""}, + {"vault.operations.get", "vault", "GET", "v1/{+name}", "name@", "", "", "r", ""}, + {"vault.operations.list", "vault", "GET", "v1/{+name}", "name@,filter,pageSize#,pageToken,returnPartialSuccess?", "", "", "r", ""}, +}; +// CALLS-END +const std::size_t kCallTableSize = sizeof(kCallTable) / sizeof(kCallTable[0]); + +// SCHEMAS-BEGIN (top-level fields of every request body schema) +const SchemaSpec kSchemaTable[] = { + {"calendar", "AclRule", "etag,id,kind,role,scope"}, + {"calendar", "Calendar", "autoAcceptInvitations,conferenceProperties,dataOwner,description,etag,id,kind,labelProperties,location,summary,timeZone"}, + {"calendar", "CalendarListEntry", "accessRole,autoAcceptInvitations,backgroundColor,colorId,conferenceProperties,dataOwner,defaultReminders,deleted,description,etag,foregroundColor,hidden,id,kind,location,notificationSettings,primary,selected,summary,summaryOverride,timeZone"}, + {"calendar", "Channel", "address,expiration,id,kind,params,payload,resourceId,resourceUri,token,type"}, + {"calendar", "Event", "anyoneCanAddSelf,attachments,attendees,attendeesOmitted,birthdayProperties,colorId,conferenceData,created,creator,description,end,endTimeUnspecified,etag,eventLabelId,eventType,extendedProperties,focusTimeProperties,gadget,guestsCanInviteOthers,guestsCanModify,guestsCanSeeOtherGuests,hangoutLink,htmlLink,iCalUID,id,kind,location,locked,organizer,originalStartTime,outOfOfficeProperties,privateCopy,recurrence,recurringEventId,reminders,sequence,source,start,status,summary,transparency,updated,visibility,workingLocationProperties"}, + {"calendar", "FreeBusyRequest", "calendarExpansionMax,groupExpansionMax,items,timeMax,timeMin,timeZone"}, + {"chat", "Availability", "customStatus,doNotDisturbMetadata,name,state"}, + {"chat", "CompleteImportSpaceRequest", ""}, + {"chat", "CustomEmoji", "emojiName,name,payload,temporaryImageUri,uid"}, + {"chat", "GoogleChatV1Section", "displayName,name,sortOrder,type"}, + {"chat", "MarkAsActiveRequest", "expireTime,ttl"}, + {"chat", "MarkAsAwayRequest", ""}, + {"chat", "MarkAsDoNotDisturbRequest", "expireTime,ttl"}, + {"chat", "Membership", "affiliation,createTime,deleteTime,groupMember,member,name,role,state"}, + {"chat", "Message", "accessoryWidgets,actionResponse,annotations,argumentText,attachedGifs,attachment,cards,cardsV2,clientAssignedMessageId,createTime,deleteTime,deletionMetadata,emojiReactionSummaries,fallbackText,formattedText,lastUpdateTime,markupSyntax,matchedUrl,name,privateMessageViewer,quotedMessageMetadata,sender,silent,slashCommand,space,text,thread,threadReply"}, + {"chat", "MessagePin", "message,name"}, + {"chat", "MoveSectionItemRequest", "targetSection"}, + {"chat", "PositionSectionRequest", "relativePosition,sortOrder"}, + {"chat", "Reaction", "emoji,name,user"}, + {"chat", "ReplaceMessageCardsRequest", "cardsV2"}, + {"chat", "SearchMessagesRequest", "filter,markupSyntax,orderBy,pageSize,pageToken,view"}, + {"chat", "SetUpSpaceRequest", "memberships,requestId,space"}, + {"chat", "Space", "accessSettings,adminInstalled,createTime,customer,displayName,externalUserAllowed,importMode,importModeExpireTime,lastActiveTime,membershipCount,name,permissionSettings,predefinedPermissionSettings,singleUserBotDm,spaceDetails,spaceHistoryState,spaceThreadingState,spaceType,spaceUri,threaded,type"}, + {"chat", "SpaceNotificationSetting", "muteSetting,name,notificationSetting"}, + {"chat", "SpaceReadState", "lastReadTime,name"}, + {"chat", "UploadAttachmentRequest", "filename"}, + {"classroom", "AddOnAttachment", "copyHistory,courseId,dueDate,dueTime,id,itemId,maxPoints,postId,studentViewUri,studentWorkReviewUri,teacherViewUri,title"}, + {"classroom", "AddOnAttachmentStudentSubmission", "courseWorkSubmissionId,id,pointsEarned,postSubmissionState,userId"}, + {"classroom", "Announcement", "alternateLink,assigneeMode,courseId,creationTime,creatorUserId,id,individualStudentsOptions,materials,scheduledTime,state,text,updateTime"}, + {"classroom", "Course", "alternateLink,calendarId,courseGroupEmail,courseMaterialSets,courseState,creationTime,description,descriptionHeading,enrollmentCode,gradebookSettings,guardiansEnabled,id,levels,name,ownerId,room,section,subject,teacherFolder,teacherGroupEmail,updateTime"}, + {"classroom", "CourseAlias", "alias"}, + {"classroom", "CourseWork", "alternateLink,assigneeMode,assignment,associatedWithDeveloper,courseId,creationTime,creatorUserId,description,dueDate,dueTime,gradeCategory,gradingPeriodId,id,individualStudentsOptions,materials,maxPoints,multipleChoiceQuestion,scheduledTime,state,submissionModificationMode,title,topicId,updateTime,workType"}, + {"classroom", "CourseWorkMaterial", "alternateLink,assigneeMode,courseId,creationTime,creatorUserId,description,id,individualStudentsOptions,materials,scheduledTime,state,title,topicId,updateTime"}, + {"classroom", "GradingPeriodSettings", "applyToExistingCoursework,gradingPeriods"}, + {"classroom", "GuardianInvitation", "creationTime,invitationId,invitedEmailAddress,state,studentId"}, + {"classroom", "Invitation", "courseId,id,role,userId"}, + {"classroom", "ModifyAnnouncementAssigneesRequest", "assigneeMode,modifyIndividualStudentsOptions"}, + {"classroom", "ModifyAttachmentsRequest", "addAttachments"}, + {"classroom", "ModifyCourseWorkAssigneesRequest", "assigneeMode,modifyIndividualStudentsOptions"}, + {"classroom", "ReclaimStudentSubmissionRequest", ""}, + {"classroom", "Registration", "cloudPubsubTopic,expiryTime,feed,registrationId"}, + {"classroom", "ReturnStudentSubmissionRequest", ""}, + {"classroom", "Rubric", "courseId,courseWorkId,creationTime,criteria,id,sourceSpreadsheetId,updateTime"}, + {"classroom", "Student", "courseId,profile,studentWorkFolder,userId"}, + {"classroom", "StudentGroup", "courseId,id,title"}, + {"classroom", "StudentGroupMember", "courseId,studentGroupId,userId"}, + {"classroom", "StudentSubmission", "alternateLink,assignedGrade,assignedRubricGrades,assignmentSubmission,associatedWithDeveloper,courseId,courseWorkId,courseWorkType,creationTime,draftGrade,draftRubricGrades,id,late,multipleChoiceSubmission,shortAnswerSubmission,state,submissionHistory,updateTime,userId"}, + {"classroom", "Teacher", "courseId,profile,userId"}, + {"classroom", "Topic", "courseId,name,topicId,updateTime"}, + {"classroom", "TurnInStudentSubmissionRequest", ""}, + {"directory", "Alias", "alias,etag,id,kind,primaryEmail"}, + {"directory", "BatchChangeChromeOsDeviceStatusRequest", "changeChromeOsDeviceStatusAction,deprovisionReason,deviceIds"}, + {"directory", "BatchCreatePrintServersRequest", "requests"}, + {"directory", "BatchCreatePrintersRequest", "requests"}, + {"directory", "BatchDeletePrintServersRequest", "printServerIds"}, + {"directory", "BatchDeletePrintersRequest", "printerIds"}, + {"directory", "Building", "address,buildingId,buildingName,coordinates,description,etags,floorNames,kind"}, + {"directory", "CalendarResource", "buildingId,capacity,etags,featureInstances,floorName,floorSection,generatedResourceName,kind,resourceCategory,resourceDescription,resourceEmail,resourceId,resourceName,resourceType,userVisibleDescription"}, + {"directory", "Channel", "address,expiration,id,kind,params,payload,resourceId,resourceUri,token,type"}, + {"directory", "ChromeOsDevice", "activeTimeRanges,annotatedAssetId,annotatedLocation,annotatedUser,autoUpdateExpiration,autoUpdateThrough,backlightInfo,bluetoothAdapterInfo,bootMode,chromeOsType,cpuInfo,cpuStatusReports,deprovisionReason,deviceFiles,deviceId,deviceLicenseType,diskSpaceUsage,diskVolumeReports,dockMacAddress,etag,ethernetMacAddress,ethernetMacAddress0,extendedSupportEligible,extendedSupportEnabled,extendedSupportStart,fanInfo,firmwareVersion,firstEnrollmentTime,kind,lastDeprovisionTimestamp,lastEnrollmentTime,lastKnownNetwork,lastSync,macAddress,manufactureDate,meid,model,notes,orderNumber,orgUnitId,orgUnitPath,osUpdateStatus,osVersion,osVersionCompliance,platformVersion,recentUsers,screenshotFiles,serialNumber,status,supportEndDate,systemRamFreeReports,systemRamTotal,tpmVersionInfo,willAutoRenew"}, + {"directory", "ChromeOsDeviceAction", "action,deprovisionReason"}, + {"directory", "ChromeOsMoveDevicesToOu", "deviceIds"}, + {"directory", "Customer", "alternateEmail,customerCreationTime,customerDomain,etag,id,kind,language,phoneNumber,postalAddress"}, + {"directory", "DirectoryChromeosdevicesIssueCommandRequest", "commandType,payload"}, + {"directory", "DirectoryUsersCreateGuestRequest", "customer,primaryGuestEmail"}, + {"directory", "DomainAlias", "creationTime,domainAliasName,etag,kind,parentDomainName,verified"}, + {"directory", "Domains", "creationTime,domainAliases,domainName,etag,isPrimary,kind,verified"}, + {"directory", "Feature", "etags,kind,name"}, + {"directory", "FeatureRename", "newName"}, + {"directory", "Group", "adminCreated,aliases,description,directMembersCount,email,etag,externalIds,id,kind,name,nonEditableAliases"}, + {"directory", "Member", "delivery_settings,email,etag,id,kind,role,status,type"}, + {"directory", "MobileDeviceAction", "action"}, + {"directory", "OrgUnit", "blockInheritance,description,etag,kind,name,orgUnitId,orgUnitPath,parentOrgUnitId,parentOrgUnitPath"}, + {"directory", "PrintServer", "createTime,description,displayName,id,name,orgUnitId,uri"}, + {"directory", "Printer", "auxiliaryMessages,createTime,description,displayName,id,makeAndModel,name,orgUnitId,uri,useDriverlessConfig"}, + {"directory", "Role", "etag,isSuperAdminRole,isSystemRole,kind,roleDescription,roleId,roleName,rolePrivileges"}, + {"directory", "RoleAssignment", "assignedTo,assigneeType,condition,etag,expirationDetails,kind,orgUnitId,roleAssignmentId,roleId,scopeType"}, + {"directory", "Schema", "displayName,etag,fields,kind,schemaId,schemaName"}, + {"directory", "User", "addresses,agreedToTerms,aliases,archivalTime,archived,changePasswordAtNextLogin,creationTime,customSchemas,customerId,deletionTime,emails,etag,externalIds,gender,guestAccountInfo,hashFunction,id,ims,includeInGlobalAddressList,ipWhitelisted,isAdmin,isDelegatedAdmin,isEnforcedIn2Sv,isEnrolledIn2Sv,isGuestUser,isMailboxSetup,keywords,kind,languages,lastLoginTime,locations,name,nonEditableAliases,notes,orgUnitPath,organizations,password,phones,posixAccounts,primaryEmail,recoveryEmail,recoveryPhone,relations,sshPublicKeys,suspended,suspensionReason,suspensionTime,thumbnailPhotoEtag,thumbnailPhotoUrl,websites"}, + {"directory", "UserMakeAdmin", "status"}, + {"directory", "UserPhoto", "etag,height,id,kind,mimeType,photoData,primaryEmail,width"}, + {"directory", "UserUndelete", "orgUnitPath"}, + {"docs", "BatchUpdateDocumentRequest", "requests,writeControl"}, + {"docs", "Document", "body,comments,commentsViewMode,documentId,documentStyle,footers,footnotes,headers,inlineObjects,lists,namedRanges,namedStyles,positionedObjects,revisionId,suggestedDocumentStyleChanges,suggestedNamedStylesChanges,suggestions,suggestionsViewMode,tabs,title"}, + {"drive", "ApproveApprovalRequest", "message"}, + {"drive", "CancelApprovalRequest", "message"}, + {"drive", "Channel", "address,expiration,id,kind,params,payload,resourceId,resourceUri,token,type"}, + {"drive", "Comment", "anchor,assigneeEmailAddress,author,content,createdTime,deleted,htmlContent,id,kind,mentionedEmailAddresses,modifiedTime,quotedFileContent,replies,resolved"}, + {"drive", "CommentApprovalRequest", "message"}, + {"drive", "DeclineApprovalRequest", "message"}, + {"drive", "Drive", "backgroundImageFile,backgroundImageLink,capabilities,colorRgb,createdTime,hidden,id,kind,name,orgUnitId,restrictions,themeId"}, + {"drive", "File", "appProperties,capabilities,clientEncryptionDetails,contentHints,contentRestrictions,copyRequiresWriterPermission,createdTime,description,downloadRestrictions,driveId,explicitlyTrashed,exportLinks,fileExtension,folderColorRgb,fullFileExtension,hasAugmentedPermissions,hasThumbnail,headRevisionId,iconLink,id,imageMediaMetadata,inheritedPermissionsDisabled,isAppAuthorized,kind,labelInfo,lastModifyingUser,linkShareMetadata,md5Checksum,mimeType,modifiedByMe,modifiedByMeTime,modifiedTime,name,originalFilename,ownedByMe,owners,parents,permissionIds,permissions,properties,quotaBytesUsed,resourceKey,sha1Checksum,sha256Checksum,shared,sharedWithMeTime,sharingUser,shortcutDetails,size,spaces,starred,teamDriveId,thumbnailLink,thumbnailVersion,trashed,trashedTime,trashingUser,version,videoMediaMetadata,viewedByMe,viewedByMeTime,viewersCanCopyContent,webContentLink,webViewLink,writersCanShare"}, + {"drive", "ModifyLabelsRequest", "kind,labelModifications"}, + {"drive", "Permission", "allowFileDiscovery,deleted,displayName,domain,emailAddress,expirationTime,id,inheritedPermissionsDisabled,kind,pendingOwner,permissionDetails,photoLink,role,teamDrivePermissionDetails,type,view"}, + {"drive", "ReassignApprovalRequest", "addReviewers,message,replaceReviewers"}, + {"drive", "Reply", "action,assigneeEmailAddress,author,content,createdTime,deleted,htmlContent,id,kind,mentionedEmailAddresses,modifiedTime"}, + {"drive", "ResolveAccessProposalRequest", "action,role,sendNotification,view"}, + {"drive", "Revision", "exportLinks,id,keepForever,kind,lastModifyingUser,md5Checksum,mimeType,modifiedTime,originalFilename,publishAuto,published,publishedLink,publishedOutsideDomain,size"}, + {"drive", "StartApprovalRequest", "dueTime,fileContentChangeBehavior,lockFile,message,reviewerEmails"}, + {"drive", "TeamDrive", "backgroundImageFile,backgroundImageLink,capabilities,colorRgb,createdTime,id,kind,name,orgUnitId,restrictions,themeId"}, + {"forms", "BatchUpdateFormRequest", "includeFormInResponse,requests,writeControl"}, + {"forms", "CreateWatchRequest", "watch,watchId"}, + {"forms", "Form", "formId,info,items,linkedSheetId,publishSettings,responderUri,revisionId,settings"}, + {"forms", "RenewWatchRequest", ""}, + {"forms", "SetPublishSettingsRequest", "publishSettings,updateMask"}, + {"gmail", "AutoForwarding", "disposition,emailAddress,enabled"}, + {"gmail", "BatchDeleteMessagesRequest", "ids"}, + {"gmail", "BatchModifyMessagesRequest", "addClassificationLabels,addLabelIds,ids,removeClassificationLabelIds,removeLabelIds"}, + {"gmail", "CseIdentity", "emailAddress,primaryKeyPairId,signAndEncryptKeyPairs"}, + {"gmail", "CseKeyPair", "disableTime,enablementState,keyPairId,pem,pkcs7,privateKeyMetadata,subjectEmailAddresses"}, + {"gmail", "Delegate", "delegateEmail,verificationStatus"}, + {"gmail", "DisableCseKeyPairRequest", ""}, + {"gmail", "Draft", "id,message"}, + {"gmail", "EnableCseKeyPairRequest", ""}, + {"gmail", "Filter", "action,criteria,id"}, + {"gmail", "ForwardingAddress", "forwardingEmail,verificationStatus"}, + {"gmail", "ImapSettings", "autoExpunge,enabled,expungeBehavior,maxFolderSize"}, + {"gmail", "Label", "color,id,labelListVisibility,messageListVisibility,messagesTotal,messagesUnread,name,threadsTotal,threadsUnread,type"}, + {"gmail", "LanguageSettings", "displayLanguage"}, + {"gmail", "Message", "classificationLabelValues,historyId,id,internalDate,labelIds,payload,raw,sizeEstimate,snippet,threadId"}, + {"gmail", "ModifyMessageRequest", "addClassificationLabels,addLabelIds,removeClassificationLabelIds,removeLabelIds"}, + {"gmail", "ModifyThreadRequest", "addLabelIds,removeLabelIds"}, + {"gmail", "ObliterateCseKeyPairRequest", ""}, + {"gmail", "PopSettings", "accessWindow,disposition"}, + {"gmail", "SendAs", "displayName,isDefault,isPrimary,replyToAddress,sendAsEmail,signature,smtpMsa,treatAsAlias,verificationStatus"}, + {"gmail", "SmimeInfo", "encryptedKeyPassword,expiration,id,isDefault,issuerCn,pem,pkcs12"}, + {"gmail", "VacationSettings", "enableAutoReply,endTime,responseBodyHtml,responseBodyPlainText,responseSubject,restrictToContacts,restrictToDomain,startTime"}, + {"gmail", "WatchRequest", "labelFilterAction,labelFilterBehavior,labelIds,topicName"}, + {"groupssettings", "Groups", "allowExternalMembers,allowGoogleCommunication,allowWebPosting,archiveOnly,customFooterText,customReplyTo,customRolesEnabledForSettingsToBeMerged,defaultMessageDenyNotificationText,default_sender,description,email,enableCollaborativeInbox,favoriteRepliesOnTop,includeCustomFooter,includeInGlobalAddressList,isArchived,kind,maxMessageBytes,membersCanPostAsTheGroup,messageDisplayFont,messageModerationLevel,name,primaryLanguage,replyTo,sendMessageDenyNotification,showInGroupDirectory,spamModerationLevel,whoCanAdd,whoCanAddExternalMembers,whoCanAddReferences,whoCanApproveMembers,whoCanApproveMessages,whoCanAssignTopics,whoCanAssistContent,whoCanBanUsers,whoCanContactOwner,whoCanDeleteAnyPost,whoCanDeleteTopics,whoCanDiscoverGroup,whoCanEnterFreeFormTags,whoCanHideAbuse,whoCanInvite,whoCanJoin,whoCanLeaveGroup,whoCanLockTopics,whoCanMakeTopicsSticky,whoCanMarkDuplicate,whoCanMarkFavoriteReplyOnAnyTopic,whoCanMarkFavoriteReplyOnOwnTopic,whoCanMarkNoResponseNeeded,whoCanModerateContent,whoCanModerateMembers,whoCanModifyMembers,whoCanModifyTagsAndCategories,whoCanMoveTopicsIn,whoCanMoveTopicsOut,whoCanPostAnnouncements,whoCanPostMessage,whoCanTakeTopics,whoCanUnassignTopic,whoCanUnmarkFavoriteReplyOnAnyTopic,whoCanViewGroup,whoCanViewMembership"}, + {"keep", "BatchCreatePermissionsRequest", "requests"}, + {"keep", "BatchDeletePermissionsRequest", "names"}, + {"keep", "Note", "attachments,body,createTime,name,permissions,title,trashTime,trashed,updateTime"}, + {"meet", "BatchUpdateMembersRequest", "requests,updateMask"}, + {"meet", "EndActiveConferenceRequest", ""}, + {"meet", "Member", "email,name,role"}, + {"meet", "Space", "activeConference,config,gatewaySipAccess,meetingCode,meetingUri,name,phoneAccess"}, + {"people", "BatchCreateContactsRequest", "contacts,readMask,sources"}, + {"people", "BatchDeleteContactsRequest", "resourceNames"}, + {"people", "BatchUpdateContactsRequest", "contacts,readMask,sources,updateMask"}, + {"people", "CopyOtherContactToMyContactsGroupRequest", "copyMask,readMask,sources"}, + {"people", "CreateContactGroupRequest", "contactGroup,readGroupFields"}, + {"people", "ModifyContactGroupMembersRequest", "resourceNamesToAdd,resourceNamesToRemove"}, + {"people", "Person", "addresses,ageRange,ageRanges,biographies,birthdays,braggingRights,calendarUrls,clientData,coverPhotos,emailAddresses,etag,events,externalIds,fileAses,genders,imClients,interests,locales,locations,memberships,metadata,miscKeywords,names,nicknames,occupations,organizations,phoneNumbers,photos,relations,relationshipInterests,relationshipStatuses,residences,resourceName,sipAddresses,skills,taglines,urls,userDefined"}, + {"people", "UpdateContactGroupRequest", "contactGroup,readGroupFields,updateGroupFields"}, + {"people", "UpdateContactPhotoRequest", "personFields,photoBytes,sources"}, + {"reports", "Channel", "address,expiration,id,kind,params,payload,resourceId,resourceUri,token,type"}, + {"sheets", "BatchClearValuesByDataFilterRequest", "dataFilters"}, + {"sheets", "BatchClearValuesRequest", "ranges"}, + {"sheets", "BatchGetValuesByDataFilterRequest", "dataFilters,dateTimeRenderOption,majorDimension,valueRenderOption"}, + {"sheets", "BatchUpdateSpreadsheetRequest", "commentsViewMode,includeSpreadsheetInResponse,requests,responseIncludeGridData,responseRanges"}, + {"sheets", "BatchUpdateValuesByDataFilterRequest", "data,includeValuesInResponse,responseDateTimeRenderOption,responseValueRenderOption,valueInputOption"}, + {"sheets", "BatchUpdateValuesRequest", "data,includeValuesInResponse,responseDateTimeRenderOption,responseValueRenderOption,valueInputOption"}, + {"sheets", "ClearValuesRequest", ""}, + {"sheets", "CopySheetToAnotherSpreadsheetRequest", "destinationSpreadsheetId"}, + {"sheets", "GetSpreadsheetByDataFilterRequest", "commentsViewMode,dataFilters,excludeTablesInBandedRanges,includeGridData"}, + {"sheets", "SearchDeveloperMetadataRequest", "dataFilters"}, + {"sheets", "Spreadsheet", "comments,commentsViewMode,dataSourceSchedules,dataSources,developerMetadata,namedRanges,properties,sheets,spreadsheetId,spreadsheetUrl"}, + {"sheets", "ValueRange", "majorDimension,range,values"}, + {"slides", "BatchUpdatePresentationRequest", "requests,writeControl"}, + {"slides", "Presentation", "comments,commentsViewMode,layouts,locale,masters,notesMaster,pageSize,presentationId,revisionId,slides,title"}, + {"tasks", "Task", "assignmentInfo,completed,deleted,due,etag,hidden,id,kind,links,notes,parent,position,selfLink,status,title,updated,webViewLink"}, + {"tasks", "TaskList", "etag,id,kind,selfLink,title,updated"}, + {"vault", "AddHeldAccountsRequest", "accountIds,emails"}, + {"vault", "AddMatterPermissionsRequest", "ccMe,matterPermission,sendEmails"}, + {"vault", "CancelOperationRequest", ""}, + {"vault", "CloseMatterRequest", ""}, + {"vault", "CountArtifactsRequest", "query,view"}, + {"vault", "Export", "cloudStorageSink,createTime,exportOptions,id,matterId,name,parentExportId,query,requester,stats,status"}, + {"vault", "HeldAccount", "accountId,email,firstName,holdTime,lastName"}, + {"vault", "Hold", "accounts,corpus,holdId,name,orgUnit,query,updateTime"}, + {"vault", "Matter", "description,matterId,matterPermissions,matterRegion,name,state"}, + {"vault", "RemoveHeldAccountsRequest", "accountIds"}, + {"vault", "RemoveMatterPermissionsRequest", "accountId"}, + {"vault", "ReopenMatterRequest", ""}, + {"vault", "SavedQuery", "createTime,displayName,matterId,query,savedQueryId"}, + {"vault", "UndeleteMatterRequest", ""}, + {"youtube", "AbuseReport", "abuseTypes,description,relatedEntities,subject"}, + {"youtube", "Caption", "etag,id,kind,snippet"}, + {"youtube", "Channel", "auditDetails,brandingSettings,contentDetails,contentOwnerDetails,conversionPings,etag,id,kind,localizations,snippet,statistics,status,topicDetails"}, + {"youtube", "ChannelBannerResource", "etag,kind,url"}, + {"youtube", "ChannelSection", "contentDetails,etag,id,kind,localizations,snippet,targeting"}, + {"youtube", "Comment", "etag,id,kind,snippet"}, + {"youtube", "CommentThread", "etag,id,kind,replies,snippet"}, + {"youtube", "Cuepoint", "cueType,durationSecs,etag,id,insertionOffsetTimeMs,walltimeMs"}, + {"youtube", "InvideoBranding", "imageBytes,imageUrl,position,targetChannelId,timing"}, + {"youtube", "LiveBroadcast", "contentDetails,etag,id,kind,monetizationDetails,snippet,statistics,status"}, + {"youtube", "LiveChatBan", "etag,id,kind,snippet"}, + {"youtube", "LiveChatMessage", "authorDetails,etag,id,kind,snippet"}, + {"youtube", "LiveChatModerator", "etag,id,kind,snippet"}, + {"youtube", "LiveStream", "cdn,contentDetails,etag,id,kind,snippet,status"}, + {"youtube", "Playlist", "contentDetails,etag,id,kind,localizations,player,snippet,status"}, + {"youtube", "PlaylistImage", "id,kind,snippet"}, + {"youtube", "PlaylistItem", "contentDetails,etag,id,kind,snippet,status"}, + {"youtube", "Subscription", "contentDetails,etag,id,kind,snippet,subscriberSnippet"}, + {"youtube", "TestItem", "etag,featuredPart,gaia,id,snippet"}, + {"youtube", "ThirdPartyLink", "etag,kind,linkingToken,snippet,status"}, + {"youtube", "Video", "ageGating,brandPartner,contentDetails,etag,fileDetails,id,kind,liveStreamingDetails,localizations,monetizationDetails,paidProductPlacementDetails,player,processingDetails,projectDetails,recordingDetails,snippet,statistics,status,suggestions,topicDetails"}, + {"youtube", "VideoAbuseReport", "comments,language,reasonId,secondaryReasonId,videoId"}, + {"youtubeanalytics", "Group", "contentDetails,errors,etag,id,kind,snippet"}, + {"youtubeanalytics", "GroupItem", "errors,etag,groupId,id,kind,resource"}, + {"youtubereporting", "Job", "createTime,expireTime,id,name,reportTypeId,systemManaged"}, +}; +// SCHEMAS-END +const std::size_t kSchemaTableSize = sizeof(kSchemaTable) / sizeof(kSchemaTable[0]); + +} // namespace molo::google::workspace diff --git a/src/google/workspace/calls.cpp b/src/google/workspace/calls.cpp new file mode 100644 index 0000000..f5cd38f --- /dev/null +++ b/src/google/workspace/calls.cpp @@ -0,0 +1,90 @@ +#include "google/workspace/calls.h" + +#include +#include + +namespace molo::google::workspace { + +namespace { + +std::vector split(const char* text, char sep) { + std::vector out; + std::string cur; + for (const char* p = text; *p; ++p) { + if (*p == sep) { + if (!cur.empty()) out.push_back(cur); + cur.clear(); + } else { + cur += *p; + } + } + if (!cur.empty()) out.push_back(cur); + return out; +} + +} // namespace + +std::vector params_of(const CallSpec& call) { + std::vector out; + for (const std::string& item : split(call.params, ',')) { + ParamInfo p; + std::size_t end = item.find_first_of("@!#?*"); + p.name = item.substr(0, end); + for (std::size_t i = end; i != std::string::npos && i < item.size(); ++i) { + switch (item[i]) { + case '@': p.path = true; p.required = true; break; + case '!': p.required = true; break; + case '#': p.number = true; break; + case '?': p.boolean = true; break; + case '*': p.repeated = true; break; + default: break; + } + } + out.push_back(std::move(p)); + } + return out; +} + +Kind kind_of(const CallSpec& call) { return static_cast(call.kind[0]); } + +bool has_flag(const CallSpec& call, char flag) { return std::strchr(call.flags, flag) != nullptr; } + +const ApiSpec* find_api(const std::string& name) { + for (std::size_t i = 0; i < kApiTableSize; ++i) + if (name == kApiTable[i].name) return &kApiTable[i]; + return nullptr; +} + +const CallSpec* find_call(const std::string& id) { + static const std::unordered_map index = [] { + std::unordered_map m; + for (std::size_t i = 0; i < kCallTableSize; ++i) m.emplace(kCallTable[i].id, &kCallTable[i]); + return m; + }(); + auto it = index.find(id); + return it == index.end() ? nullptr : it->second; +} + +const CallSpec* find_call_in(const std::string& api, const std::string& id) { + for (std::size_t i = 0; i < kCallTableSize; ++i) + if (api == kCallTable[i].api && id == kCallTable[i].id) return &kCallTable[i]; + return nullptr; +} + +std::vector body_fields_of(const CallSpec& call) { + if (!*call.body) return {}; + for (std::size_t i = 0; i < kSchemaTableSize; ++i) + if (std::strcmp(kSchemaTable[i].api, call.api) == 0 && + std::strcmp(kSchemaTable[i].schema, call.body) == 0) + return split(kSchemaTable[i].fields, ','); + return {}; +} + +std::vector calls_of(const std::string& api) { + std::vector out; + for (std::size_t i = 0; i < kCallTableSize; ++i) + if (api == kCallTable[i].api) out.push_back(&kCallTable[i]); + return out; +} + +} // namespace molo::google::workspace diff --git a/src/google/workspace/calls.h b/src/google/workspace/calls.h new file mode 100644 index 0000000..4f5f0ea --- /dev/null +++ b/src/google/workspace/calls.h @@ -0,0 +1,83 @@ +#pragma once + +// The ONE table of Workspace REST calls: every method of twenty Discovery +// documents (call_table.cpp, generated by tools/gen_calls.py, proven by +// tools/check_discovery.py). Code builds every URL from this table. + +#include +#include +#include + +namespace molo::google::workspace { + +// One Workspace API (one Discovery document). +struct ApiSpec { + const char* name; // gmail, drive, directory, ... + const char* discovery_id; // gmail:v1 + const char* discovery_url; + const char* base_url; // rootUrl + servicePath, no trailing slash + const char* service; // API to enable: gmail.googleapis.com + const char* scopes; // space separated, every OAuth scope of the API + const char* readonly_scopes; // subset ending in readonly / metadata + const char* revision; +}; + +// What a call does to the world. Decides which library method may run it. +enum class Kind : char { + kRead = 'r', // no side effect + kWrite = 'w', // changes data of a human or organization + kDestroy = 'd', // deletes, trashes, clears, signs out, wipes + kSend = 's', // reaches other people (mail, chat, invites, shares) +}; + +struct CallSpec { + const char* id; // gmail.users.messages.list + const char* api; // ApiSpec::name + const char* http; // GET POST PUT PATCH DELETE + const char* path; // Discovery path, relative to the base URL + const char* params; // "userId@,maxResults#,labelIds*,q" (see ParamInfo) + const char* body; // request schema name, "" when none + const char* items_key; // array property of the list response, "" if none + const char* kind; // one char of Kind + const char* flags; // u media upload, d media download, b bytes response +}; + +struct SchemaSpec { + const char* api; + const char* schema; + const char* fields; // comma list of top-level properties +}; + +extern const ApiSpec kApiTable[]; +extern const std::size_t kApiTableSize; +extern const CallSpec kCallTable[]; +extern const std::size_t kCallTableSize; +extern const SchemaSpec kSchemaTable[]; +extern const std::size_t kSchemaTableSize; + +// One parameter of a call, decoded from CallSpec::params. Markers after the +// name: @ path, ! required query, # number, ? boolean, * repeated. +struct ParamInfo { + std::string name; + bool path = false; + bool required = false; + bool number = false; + bool boolean = false; + bool repeated = false; +}; + +std::vector params_of(const CallSpec& call); +Kind kind_of(const CallSpec& call); +bool has_flag(const CallSpec& call, char flag); + +const ApiSpec* find_api(const std::string& name); +// Method ids are unique per API, not across APIs (admin.channels.stop exists +// in both directory and reports): find_call returns the first row with the id, +// find_call_in the row of the named API. +const CallSpec* find_call(const std::string& id); +const CallSpec* find_call_in(const std::string& api, const std::string& id); +// Top-level request body fields for the call, empty when it has no body. +std::vector body_fields_of(const CallSpec& call); +std::vector calls_of(const std::string& api); + +} // namespace molo::google::workspace diff --git a/src/google/workspace/caps.h b/src/google/workspace/caps.h new file mode 100644 index 0000000..6a04b4b --- /dev/null +++ b/src/google/workspace/caps.h @@ -0,0 +1,23 @@ +#pragma once + +// Static ceilings for the Workspace package. Never autotuned. + +#include + +namespace molo::google::workspace { + +struct WorkspaceCaps { + static constexpr std::size_t kMaxParams = 40; // path + query parameters per call + static constexpr std::size_t kMaxParamChars = 2048; // one query value + static constexpr std::size_t kMaxPathValueChars = 512; // one path value + static constexpr std::size_t kMaxRepeated = 100; // values of one repeated parameter + static constexpr std::size_t kMaxBodyBytes = 2 * 1024 * 1024; // serialized request body + static constexpr std::size_t kMaxFieldsChars = 1024; // the `fields` selector + static constexpr int kMaxPages = 20; // pages walked by pages() + static constexpr std::size_t kMaxItems = 2000; // items collected by list() + static constexpr std::size_t kMaxSubjectChars = 254; // delegated user e-mail + static constexpr std::size_t kMaxScopes = 40; // scopes in one token + static constexpr std::size_t kMaxScopeChars = 4096; // joined scope string +}; + +} // namespace molo::google::workspace diff --git a/src/google/workspace/delegation.cpp b/src/google/workspace/delegation.cpp new file mode 100644 index 0000000..044cd05 --- /dev/null +++ b/src/google/workspace/delegation.cpp @@ -0,0 +1,173 @@ +#include "google/workspace/delegation.h" + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "clients/body/json.h" +#include "clients/client.h" +#include "clients/transports/http_transport.h" +#include "google/errors.h" +#include "google/workspace/caps.h" +#include "security/crypto/Base64.h" + +namespace molo::google::workspace { + +using clients::body::Json; +using security::crypto::Base64; + +namespace { + +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() : ""; +} + +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; +} + +struct RsaGuard { + RsaGuard() { wc_InitRsaKey(&key, nullptr); } + ~RsaGuard() { wc_FreeRsaKey(&key); } + RsaGuard(const RsaGuard&) = delete; + RsaGuard& operator=(const RsaGuard&) = delete; + RsaKey key; +}; + +} // namespace + +void Delegation::validate() const { + if (subject.empty()) return; + if (subject.size() > WorkspaceCaps::kMaxSubjectChars) + throw GoogleError::invalid("delegation subject is too long"); + std::size_t at = subject.find('@'); + if (at == std::string::npos || at == 0 || at + 1 >= subject.size() || + subject.find('@', at + 1) != std::string::npos) + throw GoogleError::invalid("delegation subject must be an e-mail address"); + for (unsigned char c : subject) + if (c <= 0x20 || c == 0x7f) + throw GoogleError::invalid("delegation subject holds whitespace or a control character"); +} + +DelegatedAuth::DelegatedAuth(ServiceAccountKey key, std::vector scopes, + Delegation delegation) + : key_(std::move(key)), delegation_(std::move(delegation)) { + delegation_.validate(); + if (scopes.empty() || scopes.size() > WorkspaceCaps::kMaxScopes) + throw GoogleError::invalid("scopes must hold 1 to 40 entries"); + for (const auto& s : scopes) { + if (s.rfind("https://", 0) != 0 || s.find(' ') != std::string::npos) + throw GoogleError::invalid("scope must be an https URL without spaces"); + scope_ += (scope_.empty() ? "" : " ") + s; + } + if (scope_.size() > WorkspaceCaps::kMaxScopeChars) + throw GoogleError::invalid("scope string is over the size cap"); +} + +DelegatedAuth::~DelegatedAuth() = default; + +std::string DelegatedAuth::assertion(const ServiceAccountKey& key, const std::string& scope, + const Delegation& delegation, std::int64_t iat, + std::chrono::seconds lifetime) { + delegation.validate(); + 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(iat))); + claims.set("exp", Json(static_cast(iat + lifetime.count()))); + if (delegation.active()) claims.set("sub", Json(delegation.subject)); + std::string signing_input = Base64::encode_url(header.dump()) + "." + + Base64::encode_url(claims.dump()); + + std::string der = pem_to_der(key.private_key_pem); + RsaGuard rsa; + word32 idx = 0; + int off = wc_GetPkcs8TraditionalOffset(reinterpret_cast(der.data()), &idx, + static_cast(der.size())); + if (off < 0) idx = 0; + if (wc_RsaPrivateKeyDecode(reinterpret_cast(der.data()), &idx, &rsa.key, + static_cast(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( + 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(signing_input.data()), + static_cast(signing_input.size()), + reinterpret_cast(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); +} + +std::string DelegatedAuth::fetch_token() const { + std::string jwt = assertion(key_, scope_, delegation_, static_cast(std::time(nullptr))); + clients::Client http(std::make_unique()); + clients::ClientRequest req = clients::ClientRequest::post(key_.token_uri); + req.form("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=" + jwt); + 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"); + std::string err = str(doc, "error"); + throw GoogleError(resp.status() == 400 ? 401 : resp.status(), + err.empty() ? "UNAUTHENTICATED" : err, + msg.empty() ? "token exchange failed" : msg, "oauth2"); + } + std::string tok = str(doc, "access_token"); + if (tok.empty()) + throw GoogleError(502, "BAD_RESPONSE", "token endpoint returned no access_token", "oauth2"); + const Json* ttl = doc.find("expires_in"); + long seconds = ttl && ttl->is_number() ? ttl->as_int() : 3600; + std::lock_guard lock(mutex_); + token_ = tok; + expires_ = std::chrono::steady_clock::now() + std::chrono::seconds(seconds); + return tok; +} + +std::string DelegatedAuth::token() const { + { + std::lock_guard lock(mutex_); + if (!token_.empty() && std::chrono::steady_clock::now() + kRefreshMargin < expires_) + return token_; + } + return fetch_token(); +} + +void DelegatedAuth::apply(clients::ClientRequest& request) const { request.bearer(token()); } + +} // namespace molo::google::workspace diff --git a/src/google/workspace/delegation.h b/src/google/workspace/delegation.h new file mode 100644 index 0000000..e3c9b49 --- /dev/null +++ b/src/google/workspace/delegation.h @@ -0,0 +1,67 @@ +#pragma once + +// Domain-wide delegation for Workspace. The foundation ServiceAccountAuth +// cannot carry the JWT `sub` claim, so this package signs its own assertion +// (same RS256 / wolfCrypt method, key file parsed by the foundation's +// ServiceAccountKey) and keeps the token fresh. +// +// Typed option: Delegation{subject}. With a subject the token acts as that +// human (the admin must have granted the service account's client id the +// scopes in Admin console > Security > API controls > Domain-wide delegation). +// Without it the token acts as the service account itself, which owns no mail, +// drive or calendar data: Workspace APIs then answer 400/401/403 or empty lists. +// +// Env: GOOGLE_WORKSPACE_SUBJECT (looked up like every Google knob), +// GOOGLE_APPLICATION_CREDENTIALS (key file), GOOGLE_ACCESS_TOKEN (a user's +// OAuth token, used as is). + +#include +#include +#include +#include +#include + +#include "clients/auth.h" +#include "google/service_account.h" + +namespace molo::google::workspace { + +struct Delegation { + std::string subject; // e-mail of the user to impersonate; empty: none + bool active() const { return !subject.empty(); } + // Throws GoogleError (invalid) unless empty or a plausible e-mail address + // (one @, no whitespace or control characters, at most 254 characters). + void validate() const; +}; + +class DelegatedAuth : public clients::Auth { + public: + DelegatedAuth(ServiceAccountKey key, std::vector scopes, Delegation delegation = {}); + ~DelegatedAuth() override; + + void apply(clients::ClientRequest& request) const override; + const char* scheme() const override { return "service-account-delegated"; } + const Delegation& delegation() const { return delegation_; } + const std::string& scope_string() const { return scope_; } + + // Pure computation, no network: the signed JWT assertion with iss, scope, + // aud, iat, exp and (when active) sub. + static std::string assertion(const ServiceAccountKey& key, const std::string& scope, + const Delegation& delegation, std::int64_t iat, + std::chrono::seconds lifetime = std::chrono::seconds(3600)); + // One token exchange with Google; throws GoogleError on refusal. Public so a + // live check can show the exact refusal (unauthorized_client without DWD). + std::string fetch_token() const; + + private: + std::string token() const; + + ServiceAccountKey key_; + std::string scope_; + Delegation delegation_; + mutable std::mutex mutex_; + mutable std::string token_; + mutable std::chrono::steady_clock::time_point expires_{}; +}; + +} // namespace molo::google::workspace diff --git a/src/google/workspace/prepared_call.cpp b/src/google/workspace/prepared_call.cpp new file mode 100644 index 0000000..7947815 --- /dev/null +++ b/src/google/workspace/prepared_call.cpp @@ -0,0 +1,183 @@ +#include "google/workspace/prepared_call.h" + +#include +#include +#include + +#include "google/errors.h" +#include "google/workspace/caps.h" + +namespace molo::google::workspace { + +using clients::body::Json; + +namespace { + +[[noreturn]] void bad(const std::string& why) { throw GoogleError::invalid(why); } + +bool control(unsigned char c) { return c < 0x20 || c == 0x7f; } + +void check_text(const std::string& name, const std::string& v, std::size_t cap) { + if (v.size() > cap) bad(name + " is over " + std::to_string(cap) + " characters"); + for (unsigned char c : v) + if (control(c)) bad(name + " holds a control character"); +} + +std::string number_text(const std::string& name, const Json& v) { + if (v.is_number()) { + double d = v.as_number(); + if (!std::isfinite(d)) bad(name + " must be a finite number"); + char buf[64]; + if (d == std::floor(d) && std::fabs(d) < 1e15) + std::snprintf(buf, sizeof buf, "%lld", static_cast(d)); + else + std::snprintf(buf, sizeof buf, "%.15g", d); + return buf; + } + if (v.is_string()) { + const std::string& s = v.as_string(); + std::size_t used = 0; + try { + std::stod(s, &used); + } catch (const std::exception&) { + bad(name + " must be a number"); + } + if (used != s.size()) bad(name + " must be a number"); + return s; + } + bad(name + " must be a number"); +} + +std::string scalar_text(const ParamInfo& p, const Json& v) { + if (p.number) return number_text(p.name, v); + if (p.boolean) { + if (v.is_bool()) return v.as_bool() ? "true" : "false"; + if (v.is_string() && (v.as_string() == "true" || v.as_string() == "false")) return v.as_string(); + bad(p.name + " must be true or false"); + } + if (!v.is_string()) bad(p.name + " must be a string"); + check_text(p.name, v.as_string(), WorkspaceCaps::kMaxParamChars); + return v.as_string(); +} + +} // namespace + +std::string PreparedCall::encode(const std::string& value, bool keep_slash) { + static const char* hex = "0123456789ABCDEF"; + std::string out; + for (unsigned char c : value) { + bool plain = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || + c == '-' || c == '.' || c == '_' || c == '~' || (keep_slash && c == '/'); + if (plain) { + out += static_cast(c); + } else { + out += '%'; + out += hex[c >> 4]; + out += hex[c & 15]; + } + } + return out; +} + +PreparedCall PreparedCall::build(const CallSpec& spec, const Json& params, const Json* body) { + if (!params.is_object()) bad("params must be a JSON object"); + std::vector infos = params_of(spec); + std::set known; + for (const auto& p : infos) known.insert(p.name); + if (params.as_object().size() > WorkspaceCaps::kMaxParams) bad("too many parameters"); + for (const auto& [name, v] : params.as_object()) { + (void)v; + if (name != "fields" && !known.count(name)) + bad("unknown parameter " + name + " for " + spec.id); + } + + PreparedCall out; + out.spec = &spec; + const std::string http = spec.http; + out.method = http == "GET" ? clients::Method::kGet + : http == "POST" ? clients::Method::kPost + : http == "PUT" ? clients::Method::kPut + : http == "PATCH" ? clients::Method::kPatch + : clients::Method::kDelete; + + // Path template: {name} or {+name}; everything else is copied. + std::string rendered = "/"; + const std::string tmpl = spec.path; + for (std::size_t i = 0; i < tmpl.size();) { + if (tmpl[i] != '{') { + rendered += tmpl[i++]; + continue; + } + std::size_t close = tmpl.find('}', i); + if (close == std::string::npos) bad("broken path template"); + std::string name = tmpl.substr(i + 1, close - i - 1); + bool plus = !name.empty() && name[0] == '+'; + if (plus) name.erase(0, 1); + const Json* v = params.find(name); + if (!v || !v->is_string() || v->as_string().empty()) bad(name + " is required (string)"); + const std::string& s = v->as_string(); + check_text(name, s, WorkspaceCaps::kMaxPathValueChars); + std::string seg; + for (std::size_t k = 0; k <= s.size(); ++k) { + if (k == s.size() || s[k] == '/') { + if (seg == "..") bad(name + " must not contain .."); + seg.clear(); + } else { + seg += s[k]; + } + } + if (!plus && s.find('/') != std::string::npos) bad(name + " must not contain /"); + rendered += encode(s, plus); + i = close + 1; + } + + std::string query; + auto add = [&](const std::string& k, const std::string& v) { + query += (query.empty() ? "?" : "&") + encode(k, false) + "=" + encode(v, false); + }; + for (const auto& p : infos) { + if (p.path) continue; + const Json* v = params.find(p.name); + if (!v || v->is_null()) { + if (p.required) bad(p.name + " is required"); + continue; + } + if (p.repeated) { + if (!v->is_array()) bad(p.name + " must be an array"); + if (v->as_array().size() > WorkspaceCaps::kMaxRepeated) bad(p.name + " has too many values"); + for (const Json& e : v->as_array()) add(p.name, scalar_text(p, e)); + } else { + add(p.name, scalar_text(p, *v)); + } + } + if (const Json* f = params.find("fields")) { + if (!f->is_string()) bad("fields must be a string"); + check_text("fields", f->as_string(), WorkspaceCaps::kMaxFieldsChars); + add("fields", f->as_string()); + } + // Groups Settings answers Atom XML unless asked for JSON. + if (std::string(spec.api) == "groupssettings") add("alt", "json"); + out.path = rendered + query; + + if (body && !body->is_null()) { + if (!*spec.body) bad(std::string(spec.id) + " takes no request body"); + if (!body->is_object()) bad("body must be a JSON object"); + if (body->dump().size() > WorkspaceCaps::kMaxBodyBytes) bad("body is over the size cap"); + std::vector fields = body_fields_of(spec); + for (const auto& [k, v] : body->as_object()) { + (void)v; + bool ok = false; + for (const auto& f : fields) ok = ok || f == k; + if (!ok) bad("unknown body field " + k + " for " + spec.body); + } + out.body = *body; + out.has_body = true; + } + return out; +} + +std::string PreparedCall::path_with_token(const std::string& token) const { + return path + (path.find('?') == std::string::npos ? "?" : "&") + "pageToken=" + encode(token, false); +} + +} // namespace molo::google::workspace diff --git a/src/google/workspace/prepared_call.h b/src/google/workspace/prepared_call.h new file mode 100644 index 0000000..c3ffb43 --- /dev/null +++ b/src/google/workspace/prepared_call.h @@ -0,0 +1,32 @@ +#pragma once + +// PreparedCall: a validated request, ready to send. Built from the call table +// and the caller's parameters; nothing reaches the network before it passes. +// Parameters are one flat Json object: path and query names side by side. + +#include + +#include "clients/body/json.h" +#include "clients/request.h" +#include "google/workspace/calls.h" + +namespace molo::google::workspace { + +struct PreparedCall { + const CallSpec* spec = nullptr; + clients::Method method = clients::Method::kGet; + std::string path; // under the API base URL, with query string + clients::body::Json body; + bool has_body = false; + + // Throws GoogleError (invalid): unknown or missing parameter, wrong type, + // oversize value, unknown body field, body on a bodyless call. + static PreparedCall build(const CallSpec& spec, const clients::body::Json& params, + const clients::body::Json* body); + // The same with a page token appended (pagination). + std::string path_with_token(const std::string& token) const; + + static std::string encode(const std::string& value, bool keep_slash); +}; + +} // namespace molo::google::workspace diff --git a/src/google/workspace/services.cpp b/src/google/workspace/services.cpp new file mode 100644 index 0000000..d33a73a --- /dev/null +++ b/src/google/workspace/services.cpp @@ -0,0 +1,182 @@ +#include "google/workspace/services.h" + +namespace molo::google::workspace { + +namespace { +Json strs(std::initializer_list v) { + Json a = Json::array(); + for (const char* s : v) a.push(Json(s)); + return a; +} +Json csv(const std::string& list) { + Json a = Json::array(); + std::string cur; + for (char c : list) { + if (c == ',') { if (!cur.empty()) a.push(Json(cur)); cur.clear(); } + else cur += c; + } + if (!cur.empty()) a.push(Json(cur)); + return a; +} +void opt(ParamList& p, const char* k, const std::string& v) { + if (!v.empty()) p.emplace_back(k, Json(v)); +} +} // namespace + +// --- Gmail ------------------------------------------------------------- +Json Gmail::profile(const std::string& user) const { + return read("gmail.users.getProfile", make_params({{"userId", Json(user)}})); +} +Json Gmail::labels(const std::string& user) const { + return read("gmail.users.labels.list", make_params({{"userId", Json(user)}})); +} +Listing Gmail::messages(const std::string& user, const std::string& query, int max) const { + ParamList p{{"userId", Json(user)}, {"maxResults", Json(max)}}; + opt(p, "q", query); + return list("gmail.users.messages.list", make_params(p), 1); +} +Json Gmail::message(const std::string& user, const std::string& id, const std::string& format) const { + return read("gmail.users.messages.get", + make_params({{"userId", Json(user)}, {"id", Json(id)}, {"format", Json(format)}})); +} +Listing Gmail::threads(const std::string& user, const std::string& query, int max) const { + ParamList p{{"userId", Json(user)}, {"maxResults", Json(max)}}; + opt(p, "q", query); + return list("gmail.users.threads.list", make_params(p), 1); +} + +// --- Drive ------------------------------------------------------------- +Json Drive::about(const std::string& fields) const { + return read("drive.about.get", make_params({{"fields", Json(fields)}})); +} +Listing Drive::files(const std::string& query, int page_size) const { + ParamList p{{"pageSize", Json(page_size)}}; + opt(p, "q", query); + return list("drive.files.list", make_params(p), 1); +} +Json Drive::file(const std::string& id, const std::string& fields) const { + return read("drive.files.get", make_params({{"fileId", Json(id)}, {"fields", Json(fields)}})); +} + +// --- Calendar ---------------------------------------------------------- +Listing Calendar::calendars() const { return list("calendar.calendarList.list", Json::object(), 1); } +Listing Calendar::events(const std::string& calendar_id, const std::string& time_min, + const std::string& time_max, int max) const { + ParamList p{{"calendarId", Json(calendar_id)}, {"maxResults", Json(max)}, {"singleEvents", Json(true)}}; + opt(p, "timeMin", time_min); + opt(p, "timeMax", time_max); + return list("calendar.events.list", make_params(p), 1); +} +Json Calendar::free_busy(const Json& request) const { + return read("calendar.freebusy.query", Json::object(), &request); +} + +// --- Sheets / Docs / Slides / Forms --------------------------------------- +Json Sheets::spreadsheet(const std::string& id, bool grid) const { + return read("sheets.spreadsheets.get", + make_params({{"spreadsheetId", Json(id)}, {"includeGridData", Json(grid)}})); +} +Json Sheets::values(const std::string& id, const std::string& range) const { + return read("sheets.spreadsheets.values.get", + make_params({{"spreadsheetId", Json(id)}, {"range", Json(range)}})); +} +Json Docs::document(const std::string& id) const { + return read("docs.documents.get", make_params({{"documentId", Json(id)}})); +} +Json Slides::presentation(const std::string& id) const { + return read("slides.presentations.get", make_params({{"presentationId", Json(id)}})); +} +Json Slides::page(const std::string& id, const std::string& page_id) const { + return read("slides.presentations.pages.get", + make_params({{"presentationId", Json(id)}, {"pageObjectId", Json(page_id)}})); +} +Json Forms::form(const std::string& id) const { + return read("forms.forms.get", make_params({{"formId", Json(id)}})); +} +Listing Forms::responses(const std::string& id, int page_size) const { + return list("forms.forms.responses.list", + make_params({{"formId", Json(id)}, {"pageSize", Json(page_size)}}), 1); +} + +// --- Tasks / Chat / Meet / People / Keep / Classroom ------------------------ +Listing Tasks::task_lists() const { return list("tasks.tasklists.list", Json::object(), 1); } +Listing Tasks::tasks(const std::string& list_id) const { + return list("tasks.tasks.list", make_params({{"tasklist", Json(list_id)}}), 1); +} +Listing Chat::spaces() const { return list("chat.spaces.list", Json::object(), 1); } +Listing Chat::messages(const std::string& space) const { + return list("chat.spaces.messages.list", make_params({{"parent", Json(space)}}), 1); +} +Listing Meet::conference_records() const { return list("meet.conferenceRecords.list", Json::object(), 1); } +Json Meet::space(const std::string& name) const { + return read("meet.spaces.get", make_params({{"name", Json(name)}})); +} +Json People::me(const std::string& fields) const { + return read("people.people.get", + make_params({{"resourceName", Json("people/me")}, {"personFields", Json(fields)}})); +} +Listing People::connections(const std::string& fields, int page_size) const { + return list("people.people.connections.list", + make_params({{"resourceName", Json("people/me")}, {"personFields", Json(fields)}, + {"pageSize", Json(page_size)}}), 1); +} +Listing Keep::notes(const std::string& filter) const { + ParamList p; + opt(p, "filter", filter); + return list("keep.notes.list", make_params(p), 1); +} +Listing Classroom::courses(int page_size) const { + return list("classroom.courses.list", make_params({{"pageSize", Json(page_size)}}), 1); +} +Json Classroom::course(const std::string& id) const { + return read("classroom.courses.get", make_params({{"id", Json(id)}})); +} + +// --- YouTube ----------------------------------------------------------- +Json YouTube::my_channel(const std::string& part) const { + return read("youtube.channels.list", make_params({{"part", csv(part)}, {"mine", Json(true)}})); +} +Json YouTube::search(const std::string& query, int max) const { + return read("youtube.search.list", + make_params({{"part", strs({"snippet"})}, {"q", Json(query)}, {"maxResults", Json(max)}})); +} +Json YouTube::videos(const std::string& ids, const std::string& part) const { + return read("youtube.videos.list", make_params({{"part", csv(part)}, {"id", csv(ids)}})); +} +Json YouTubeAnalytics::report(const std::string& ids, const std::string& start, const std::string& end, + const std::string& metrics, const std::string& dimensions) const { + ParamList p{{"ids", Json(ids)}, {"startDate", Json(start)}, {"endDate", Json(end)}, + {"metrics", Json(metrics)}}; + opt(p, "dimensions", dimensions); + return read("youtubeAnalytics.reports.query", make_params(p)); +} +Listing YouTubeReporting::report_types() const { + return list("youtubereporting.reportTypes.list", Json::object(), 1); +} +Listing YouTubeReporting::jobs() const { return list("youtubereporting.jobs.list", Json::object(), 1); } + +// --- Admin SDK / Groups settings / Vault ----------------------------------- +Listing Directory::users(const std::string& customer, int max) const { + return list("directory.users.list", + make_params({{"customer", Json(customer)}, {"maxResults", Json(max)}}), 1); +} +Listing Directory::groups(const std::string& customer, int max) const { + return list("directory.groups.list", + make_params({{"customer", Json(customer)}, {"maxResults", Json(max)}}), 1); +} +Json Directory::org_units(const std::string& customer) const { + return read("directory.orgunits.list", make_params({{"customerId", Json(customer)}})); +} +Listing Reports::activities(const std::string& user_key, const std::string& application, int max) const { + return list("reports.activities.list", + make_params({{"userKey", Json(user_key)}, {"applicationName", Json(application)}, + {"maxResults", Json(max)}}), 1); +} +Json GroupsSettings::group(const std::string& email) const { + return read("groupsSettings.groups.get", make_params({{"groupUniqueId", Json(email)}})); +} +Listing Vault::matters(int page_size) const { + return list("vault.matters.list", make_params({{"pageSize", Json(page_size)}}), 1); +} + +} // namespace molo::google::workspace diff --git a/src/google/workspace/services.h b/src/google/workspace/services.h new file mode 100644 index 0000000..f5480b0 --- /dev/null +++ b/src/google/workspace/services.h @@ -0,0 +1,162 @@ +#pragma once + +// One typed class per Workspace API. Each adds read helpers for the common +// questions (profile, list, get) on top of WorkspaceApi, which still reaches +// every other call of the API by its Discovery method id. Helpers are reads +// only: writes, deletes and sends stay explicit calls on WorkspaceApi. + +#include + +#include "google/workspace/workspace_api.h" + +namespace molo::google::workspace { + +class Gmail : public WorkspaceApi { + public: + explicit Gmail(std::shared_ptr c) : WorkspaceApi(std::move(c), "gmail") {} + Json profile(const std::string& user = "me") const; + Json labels(const std::string& user = "me") const; + Listing messages(const std::string& user, const std::string& query, int max_results = 20) const; + Json message(const std::string& user, const std::string& id, const std::string& format = "metadata") const; + Listing threads(const std::string& user, const std::string& query, int max_results = 20) const; +}; + +class Drive : public WorkspaceApi { + public: + explicit Drive(std::shared_ptr c) : WorkspaceApi(std::move(c), "drive") {} + Json about(const std::string& fields = "user,storageQuota") const; + Listing files(const std::string& query, int page_size = 20) const; + Json file(const std::string& id, const std::string& fields = "id,name,mimeType,modifiedTime") const; +}; + +class Calendar : public WorkspaceApi { + public: + explicit Calendar(std::shared_ptr c) : WorkspaceApi(std::move(c), "calendar") {} + Listing calendars() const; + Listing events(const std::string& calendar_id, const std::string& time_min, + const std::string& time_max, int max_results = 20) const; + Json free_busy(const Json& request) const; // read: a POST that changes nothing +}; + +class Sheets : public WorkspaceApi { + public: + explicit Sheets(std::shared_ptr c) : WorkspaceApi(std::move(c), "sheets") {} + Json spreadsheet(const std::string& id, bool grid_data = false) const; + Json values(const std::string& id, const std::string& range) const; +}; + +class Docs : public WorkspaceApi { + public: + explicit Docs(std::shared_ptr c) : WorkspaceApi(std::move(c), "docs") {} + Json document(const std::string& id) const; +}; + +class Slides : public WorkspaceApi { + public: + explicit Slides(std::shared_ptr c) : WorkspaceApi(std::move(c), "slides") {} + Json presentation(const std::string& id) const; + Json page(const std::string& id, const std::string& page_id) const; +}; + +class Forms : public WorkspaceApi { + public: + explicit Forms(std::shared_ptr c) : WorkspaceApi(std::move(c), "forms") {} + Json form(const std::string& id) const; + Listing responses(const std::string& id, int page_size = 50) const; +}; + +class Tasks : public WorkspaceApi { + public: + explicit Tasks(std::shared_ptr c) : WorkspaceApi(std::move(c), "tasks") {} + Listing task_lists() const; + Listing tasks(const std::string& list_id) const; +}; + +class Chat : public WorkspaceApi { + public: + explicit Chat(std::shared_ptr c) : WorkspaceApi(std::move(c), "chat") {} + Listing spaces() const; + Listing messages(const std::string& space) const; // "spaces/AAAA" +}; + +class Meet : public WorkspaceApi { + public: + explicit Meet(std::shared_ptr c) : WorkspaceApi(std::move(c), "meet") {} + Listing conference_records() const; + Json space(const std::string& name) const; // "spaces/abc" +}; + +class People : public WorkspaceApi { + public: + explicit People(std::shared_ptr c) : WorkspaceApi(std::move(c), "people") {} + Json me(const std::string& person_fields = "names,emailAddresses") const; + Listing connections(const std::string& person_fields = "names,emailAddresses", int page_size = 50) const; +}; + +class Keep : public WorkspaceApi { + public: + explicit Keep(std::shared_ptr c) : WorkspaceApi(std::move(c), "keep") {} + Listing notes(const std::string& filter = "") const; +}; + +class Classroom : public WorkspaceApi { + public: + explicit Classroom(std::shared_ptr c) : WorkspaceApi(std::move(c), "classroom") {} + Listing courses(int page_size = 20) const; + Json course(const std::string& id) const; +}; + +class YouTube : public WorkspaceApi { + public: + explicit YouTube(std::shared_ptr c) : WorkspaceApi(std::move(c), "youtube") {} + Json my_channel(const std::string& part = "snippet,statistics") const; + // Costs 100 quota units per call. + Json search(const std::string& query, int max_results = 5) const; + Json videos(const std::string& ids, const std::string& part = "snippet,statistics") const; +}; + +class YouTubeAnalytics : public WorkspaceApi { + public: + explicit YouTubeAnalytics(std::shared_ptr c) + : WorkspaceApi(std::move(c), "youtubeanalytics") {} + Json report(const std::string& ids, const std::string& start_date, const std::string& end_date, + const std::string& metrics, const std::string& dimensions = "") const; +}; + +class YouTubeReporting : public WorkspaceApi { + public: + explicit YouTubeReporting(std::shared_ptr c) + : WorkspaceApi(std::move(c), "youtubereporting") {} + Listing report_types() const; + Listing jobs() const; +}; + +class Directory : public WorkspaceApi { + public: + explicit Directory(std::shared_ptr c) : WorkspaceApi(std::move(c), "directory") {} + Listing users(const std::string& customer = "my_customer", int max_results = 50) const; + Listing groups(const std::string& customer = "my_customer", int max_results = 50) const; + Json org_units(const std::string& customer = "my_customer") const; +}; + +class Reports : public WorkspaceApi { + public: + explicit Reports(std::shared_ptr c) : WorkspaceApi(std::move(c), "reports") {} + Listing activities(const std::string& user_key, const std::string& application, + int max_results = 50) const; +}; + +class GroupsSettings : public WorkspaceApi { + public: + explicit GroupsSettings(std::shared_ptr c) + : WorkspaceApi(std::move(c), "groupssettings") {} + Json group(const std::string& group_email) const; +}; + +class Vault : public WorkspaceApi { + public: + explicit Vault(std::shared_ptr c) : WorkspaceApi(std::move(c), "vault") {} + Listing matters(int page_size = 20) const; +}; + +} // namespace molo::google::workspace diff --git a/src/google/workspace/tools/check_discovery.py b/src/google/workspace/tools/check_discovery.py new file mode 100644 index 0000000..98159a3 --- /dev/null +++ b/src/google/workspace/tools/check_discovery.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""Check src/google/workspace/call_table.cpp against Google's Discovery documents. + +Fails (exit 1) when a row is absent from Discovery, a Discovery method has no +row, or method, path, parameter (name, location, required, type, repeated), +request schema, schema field, items key, media flag, base URL or scope list +differ. Kind sanity: every GET is a read, every DELETE is destructive, a +read that is not a GET is on the explicit allowlist. Python 3 stdlib only. + + python3 -I src/google/workspace/tools/check_discovery.py +""" +import json +import os +import re +import sys +import urllib.request + +HERE = os.path.dirname(os.path.abspath(__file__)) +TABLE = os.path.join(HERE, "..", "call_table.cpp") +STR = re.compile(r'"((?:[^"\\]|\\.)*)"') +POST_READS = {"calendar.freebusy.query", "sheets.spreadsheets.getByDataFilter", + "sheets.spreadsheets.values.batchGetByDataFilter"} + + +def block(text, begin, end): + a, b = text.index(begin), text.index(end) + rows = [] + for line in text[a:b].splitlines()[1:]: + s = line.strip() + if s.startswith("{") and s.endswith("},"): + rows.append([x.replace('\\"', '"').replace("\\\\", "\\") for x in STR.findall(s)]) + return rows + + +def fetch(url): + with urllib.request.urlopen(url, timeout=60) as r: + return json.load(r) + + +def methods(node, out): + for m in node.get("methods", {}).values(): + out[m["id"]] = m + for child in node.get("resources", {}).values(): + methods(child, out) + + +def decode(spec): + out = {} + for item in filter(None, spec.split(",")): + name = re.split(r"[@!#?*]", item, maxsplit=1)[0] + out[name] = item[len(name):] + return out + + +def main(): + text = open(TABLE).read() + apis = {r[0]: r for r in block(text, "// APIS-BEGIN", "// APIS-END")} + calls = block(text, "// CALLS-BEGIN", "// CALLS-END") + schemas = {(r[0], r[1]): r[2] for r in block(text, "// SCHEMAS-BEGIN", "// SCHEMAS-END")} + bad = [] + rows_by_api = {} + for r in calls: + rows_by_api.setdefault(r[1], {})[r[0]] = r + total = 0 + for name, (_, did, url, base, service, scopes, readonly, revision) in apis.items(): + doc = fetch(url) + index = {} + methods(doc, index) + if (doc["rootUrl"] + doc["servicePath"]).rstrip("/") != base: + bad.append("%s: base url differs" % name) + want_scopes = set(doc.get("auth", {}).get("oauth2", {}).get("scopes", {})) + if set(scopes.split()) != want_scopes: + bad.append("%s: scope list differs (%s)" % (name, sorted(want_scopes ^ set(scopes.split())))) + if not set(readonly.split()) <= want_scopes: + bad.append("%s: readonly scope not in Discovery" % name) + rows = rows_by_api.get(name, {}) + for rid in index: + if rid not in rows: + bad.append("%s: Discovery method %s has no row" % (name, rid)) + for rid, (_, api, http, path, params, body, items, kind, flags) in rows.items(): + total += 1 + m = index.get(rid) + if not m: + bad.append("missing rpc " + rid) + continue + if m["httpMethod"] != http: + bad.append("%s: http %s != %s" % (rid, http, m["httpMethod"])) + if m["path"] != path: + bad.append("%s: path %s != %s" % (rid, path, m["path"])) + have = m.get("parameters", {}) + mine = decode(params) + if set(have) != set(mine): + bad.append("%s: parameter names differ %s" % (rid, sorted(set(have) ^ set(mine)))) + for pn, mark in mine.items(): + p = have.get(pn) + if not p: + continue + if ("@" in mark) != (p.get("location") == "path"): + bad.append("%s: %s location" % (rid, pn)) + if p.get("location") != "path" and ("!" in mark) != bool(p.get("required")): + bad.append("%s: %s required" % (rid, pn)) + if ("#" in mark) != (p.get("type") in ("integer", "number")): + bad.append("%s: %s number" % (rid, pn)) + if ("?" in mark) != (p.get("type") == "boolean"): + bad.append("%s: %s boolean" % (rid, pn)) + if ("*" in mark) != bool(p.get("repeated")): + bad.append("%s: %s repeated" % (rid, pn)) + ref = m.get("request", {}).get("$ref", "") + if ref != body: + bad.append("%s: request schema %r != %r" % (rid, body, ref)) + if body: + props = ",".join(sorted(doc["schemas"][body].get("properties", {}))) + if schemas.get((name, body)) != props: + bad.append("%s: schema %s fields differ" % (rid, body)) + if items: + rprops = doc["schemas"].get(m.get("response", {}).get("$ref"), {}).get("properties", {}) + if rprops.get(items, {}).get("type") != "array": + bad.append("%s: items key %s is not an array" % (rid, items)) + f = "" + if m.get("supportsMediaUpload"): + f += "u" + if m.get("supportsMediaDownload"): + f += "d" + if "response" not in m: + f += "b" + if f != flags: + bad.append("%s: flags %r != %r" % (rid, flags, f)) + if http == "GET" and kind != "r": + bad.append("%s: GET must be a read" % rid) + if http == "DELETE" and kind != "d": + bad.append("%s: DELETE must be destructive" % rid) + if kind == "r" and http != "GET" and rid not in POST_READS: + bad.append("%s: non-GET read not on the allowlist" % rid) + if bad: + print("\n".join(bad)) + print("discovery MISMATCH: %d findings" % len(bad)) + return 1 + print("discovery ok: %d apis, %d calls, %d request schemas" % (len(apis), total, len(schemas))) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/google/workspace/tools/gen_calls.py b/src/google/workspace/tools/gen_calls.py new file mode 100644 index 0000000..18342d8 --- /dev/null +++ b/src/google/workspace/tools/gen_calls.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""Generate src/google/workspace/call_table.cpp from Google's Discovery documents. + +Every Discovery method of the twenty Workspace APIs becomes one row; nothing is +typed by hand. Python 3 stdlib only, no credentials. + + python3 -I src/google/workspace/tools/gen_calls.py # rewrite the table + python3 -I src/google/workspace/tools/gen_calls.py --list # print kind per row + +tools/check_discovery.py then proves the committed table still matches Google. +""" +import json +import os +import sys +import urllib.request + +HERE = os.path.dirname(os.path.abspath(__file__)) +OUT = os.path.join(HERE, "..", "call_table.cpp") + +# api name -> (Discovery id, Discovery URL, API service name to enable) +APIS = [ + ("gmail", "gmail:v1", "https://gmail.googleapis.com/$discovery/rest?version=v1", "gmail.googleapis.com"), + ("drive", "drive:v3", "https://www.googleapis.com/discovery/v1/apis/drive/v3/rest", "drive.googleapis.com"), + ("calendar", "calendar:v3", "https://calendar-json.googleapis.com/$discovery/rest?version=v3", "calendar-json.googleapis.com"), + ("sheets", "sheets:v4", "https://sheets.googleapis.com/$discovery/rest?version=v4", "sheets.googleapis.com"), + ("docs", "docs:v1", "https://docs.googleapis.com/$discovery/rest?version=v1", "docs.googleapis.com"), + ("slides", "slides:v1", "https://slides.googleapis.com/$discovery/rest?version=v1", "slides.googleapis.com"), + ("forms", "forms:v1", "https://forms.googleapis.com/$discovery/rest?version=v1", "forms.googleapis.com"), + ("tasks", "tasks:v1", "https://tasks.googleapis.com/$discovery/rest?version=v1", "tasks.googleapis.com"), + ("chat", "chat:v1", "https://chat.googleapis.com/$discovery/rest?version=v1", "chat.googleapis.com"), + ("meet", "meet:v2", "https://meet.googleapis.com/$discovery/rest?version=v2", "meet.googleapis.com"), + ("people", "people:v1", "https://people.googleapis.com/$discovery/rest?version=v1", "people.googleapis.com"), + ("keep", "keep:v1", "https://keep.googleapis.com/$discovery/rest?version=v1", "keep.googleapis.com"), + ("classroom", "classroom:v1", "https://classroom.googleapis.com/$discovery/rest?version=v1", "classroom.googleapis.com"), + ("youtube", "youtube:v3", "https://youtube.googleapis.com/$discovery/rest?version=v3", "youtube.googleapis.com"), + ("youtubeanalytics", "youtubeAnalytics:v2", "https://youtubeanalytics.googleapis.com/$discovery/rest?version=v2", "youtubeanalytics.googleapis.com"), + ("youtubereporting", "youtubereporting:v1", "https://youtubereporting.googleapis.com/$discovery/rest?version=v1", "youtubereporting.googleapis.com"), + ("directory", "admin:directory_v1", "https://admin.googleapis.com/$discovery/rest?version=directory_v1", "admin.googleapis.com"), + ("reports", "admin:reports_v1", "https://admin.googleapis.com/$discovery/rest?version=reports_v1", "admin.googleapis.com"), + ("groupssettings", "groupssettings:v1", "https://groupssettings.googleapis.com/$discovery/rest?version=v1", "groupssettings.googleapis.com"), + ("vault", "vault:v1", "https://vault.googleapis.com/$discovery/rest?version=v1", "vault.googleapis.com"), +] + +# Row kinds: r read, w write, d destructive, s send (reaches other people). +# Explicit lists, so a reviewer can read what each kind means. +POST_READS = { + "calendar.freebusy.query", + "sheets.spreadsheets.getByDataFilter", + "sheets.spreadsheets.values.batchGetByDataFilter", +} +SENDS = { + "gmail.users.messages.send", "gmail.users.drafts.send", + "chat.spaces.messages.create", "chat.spaces.setup", "chat.spaces.members.create", + "chat.media.upload", + "classroom.invitations.create", "classroom.courses.announcements.create", + "classroom.courses.courseWork.create", "classroom.courses.courseWorkMaterials.create", + "classroom.courses.students.create", "classroom.courses.teachers.create", + "calendar.events.insert", "calendar.events.quickAdd", "calendar.events.import", + "calendar.events.update", "calendar.events.patch", "calendar.events.move", + "calendar.acl.insert", + "drive.permissions.create", "drive.permissions.update", + "youtube.comments.insert", "youtube.commentThreads.insert", "youtube.comments.setModerationStatus", +} +DESTROY_WORDS = ("delete", "batchDelete", "emptyTrash", "remove", "purge", "clear", "reject", "wipe") +DESTROY_IDS = { + "gmail.users.messages.trash", "gmail.users.threads.trash", + "directory.chromeosdevices.action", "directory.mobiledevices.action", + "directory.users.signOut", "directory.users.makeAdmin", + "vault.matters.close", "vault.matters.holds.removeHeldAccounts", + "vault.matters.holds.accounts.delete", + "sheets.spreadsheets.values.clear", "sheets.spreadsheets.values.batchClear", + "sheets.spreadsheets.values.batchClearByDataFilter", + "tasks.tasks.clear", +} + + +def methods(node, out): + for m in node.get("methods", {}).values(): + out.append(m) + for child in node.get("resources", {}).values(): + methods(child, out) + + +def kind_of(m): + rid = m["id"] + if rid in SENDS: + return "s" + last = rid.rsplit(".", 1)[1] + if m["httpMethod"] == "DELETE" or rid in DESTROY_IDS or any( + last == w or (last.startswith(w) and last[len(w):][:1].isupper()) for w in DESTROY_WORDS): + return "d" + if m["httpMethod"] == "GET" or rid in POST_READS: + return "r" + return "w" + + +def param_spec(m): + path_names, query = [], [] + for name, p in m.get("parameters", {}).items(): + t = p.get("type", "string") + mark = "" + if p.get("location") == "path": + mark += "@" + elif p.get("required"): + mark += "!" + if t in ("integer", "number"): + mark += "#" + elif t == "boolean": + mark += "?" + if p.get("repeated"): + mark += "*" + (path_names if p.get("location") == "path" else query).append(name + mark) + return ",".join(path_names + sorted(query)) + + +def items_key(doc, m): + ref = m.get("response", {}).get("$ref") + if not ref or "pageToken" not in m.get("parameters", {}): + return "" + props = doc["schemas"].get(ref, {}).get("properties", {}) + arrays = [k for k, v in props.items() if v.get("type") == "array"] + return arrays[0] if len(arrays) == 1 else "" + + +def flags_of(m): + f = "" + if m.get("supportsMediaUpload"): + f += "u" + if m.get("supportsMediaDownload"): + f += "d" + if "response" not in m: + f += "b" # no JSON response: the body is bytes (export, download) + return f + + +def cstr(s): + return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"' + + +def fetch(url): + with urllib.request.urlopen(url, timeout=60) as r: + return json.load(r) + + +def main(): + listing = "--list" in sys.argv + apis, rows, schemas = [], [], {} + for name, did, url, service in APIS: + doc = fetch(url) + scopes = list(doc.get("auth", {}).get("oauth2", {}).get("scopes", {}).keys()) + readonly = [s for s in scopes if "readonly" in s or s.endswith(".metadata")] + base = (doc["rootUrl"] + doc["servicePath"]).rstrip("/") + apis.append((name, did, url, base, service, " ".join(scopes), " ".join(readonly), doc["revision"])) + ms = [] + methods(doc, ms) + for m in sorted(ms, key=lambda x: x["id"]): + body = m.get("request", {}).get("$ref", "") + rows.append((m["id"], name, m["httpMethod"], m["path"], param_spec(m), body, + items_key(doc, m), kind_of(m), flags_of(m))) + if body: + schemas[(name, body)] = ",".join(sorted(doc["schemas"][body].get("properties", {}).keys())) + if listing: + print(kind_of(m), m["id"]) + if listing: + return + lines = ['// GENERATED by tools/gen_calls.py from Google Discovery documents. Do not edit.', + '// Checked against Google by tools/check_discovery.py.', + '#include "google/workspace/calls.h"', '', + 'namespace molo::google::workspace {', '', + '// APIS-BEGIN', + 'const ApiSpec kApiTable[] = {'] + for a in apis: + lines.append(" {" + ", ".join(cstr(x) for x in a) + "},") + lines += ['};', '// APIS-END', 'const std::size_t kApiTableSize = sizeof(kApiTable) / sizeof(kApiTable[0]);', '', + '// CALLS-BEGIN (one row per Discovery method; parsed by tools/check_discovery.py)', + 'const CallSpec kCallTable[] = {'] + for r in rows: + lines.append(" {" + ", ".join(cstr(x) for x in r) + "},") + lines += ['};', '// CALLS-END', + 'const std::size_t kCallTableSize = sizeof(kCallTable) / sizeof(kCallTable[0]);', '', + '// SCHEMAS-BEGIN (top-level fields of every request body schema)', + 'const SchemaSpec kSchemaTable[] = {'] + for (api, ref), fields in sorted(schemas.items()): + lines.append(" {" + ", ".join(cstr(x) for x in (api, ref, fields)) + "},") + lines += ['};', '// SCHEMAS-END', + 'const std::size_t kSchemaTableSize = sizeof(kSchemaTable) / sizeof(kSchemaTable[0]);', '', + '} // namespace molo::google::workspace', ''] + with open(OUT, "w") as f: + f.write("\n".join(lines)) + print("wrote %d apis, %d calls" % (len(apis), len(rows))) + + +if __name__ == "__main__": + main() diff --git a/src/google/workspace/workspace_api.cpp b/src/google/workspace/workspace_api.cpp new file mode 100644 index 0000000..a8b9911 --- /dev/null +++ b/src/google/workspace/workspace_api.cpp @@ -0,0 +1,135 @@ +#include "google/workspace/workspace_api.h" + +#include "google/errors.h" +#include "google/workspace/caps.h" + +namespace molo::google::workspace { + +namespace { + +ServiceEndpoint endpoint_for(const std::string& api) { + const ApiSpec* spec = find_api(api); + if (!spec) throw GoogleError::invalid("unknown Workspace API " + api); + return ServiceEndpoint{spec->name, spec->base_url, false}; +} + +const char* kind_name(Kind k) { + switch (k) { + case Kind::kRead: return "read"; + case Kind::kWrite: return "write"; + case Kind::kDestroy: return "destroy"; + case Kind::kSend: return "send"; + } + return "?"; +} + +Json without_token(const Json& params) { + Json out = Json::object(); + for (const auto& [k, v] : params.as_object()) + if (k != "pageToken") out.set(k, v); + return out; +} + +} // namespace + +WorkspaceApi::WorkspaceApi(std::shared_ptr client, const std::string& api) + : Service(std::move(client), endpoint_for(api)), api_(find_api(api)) {} + +Json WorkspaceApi::make_params(const ParamList& list) { + Json out = Json::object(); + for (const auto& [k, v] : list) out.set(k, v); + return out; +} + +PreparedCall WorkspaceApi::prepare(const std::string& id, const Json& params, + const Json* body) const { + const CallSpec* spec = find_call_in(api_->name, id); + if (!spec) { + const CallSpec* other = find_call(id); + if (other) throw GoogleError::invalid(id + " belongs to " + other->api + ", not " + api_->name); + throw GoogleError::invalid("unknown call " + id); + } + if (has_flag(*spec, 'b')) + throw GoogleError::invalid(id + " answers bytes, not JSON; not supported"); + return PreparedCall::build(*spec, params, body); +} + +Json WorkspaceApi::run(const std::string& id, Kind want, const Json& params, + const Json* body) const { + PreparedCall call = prepare(id, params, body); + Kind have = kind_of(*call.spec); + if (have != want) + throw GoogleError::invalid(id + " is a " + kind_name(have) + " call, use " + kind_name(have) + "()"); + return client_->request(call.method, endpoint_, call.path, call.has_body ? &call.body : nullptr); +} + +Json WorkspaceApi::read(const std::string& id, const Json& params, const Json* body) const { + return run(id, Kind::kRead, params, body); +} + +Json WorkspaceApi::write(const std::string& id, const Json& params, const Json* body, + bool confirm) const { + prepare(id, params, body); // validation errors first + if (!confirm) throw GoogleError::invalid("write " + id + " needs confirm=true"); + return run(id, Kind::kWrite, params, body); +} + +Json WorkspaceApi::destroy(const std::string& id, const Json& params, bool confirm) const { + prepare(id, params, nullptr); + if (!confirm) throw GoogleError::invalid("destroy " + id + " needs confirm=true"); + return run(id, Kind::kDestroy, params, nullptr); +} + +Json WorkspaceApi::send(const std::string& id, const Json& params, const Json* body, + bool confirm) const { + prepare(id, params, body); + if (!confirm) throw GoogleError::invalid("send " + id + " needs confirm=true"); + return run(id, Kind::kSend, params, body); +} + +std::vector WorkspaceApi::pages(const std::string& id, const Json& params, + int max_pages) const { + if (max_pages < 1 || max_pages > WorkspaceCaps::kMaxPages) + throw GoogleError::invalid("max_pages must be 1 to 20"); + if (!params.is_object()) throw GoogleError::invalid("params must be a JSON object"); + PreparedCall first = prepare(id, without_token(params)); + if (kind_of(*first.spec) != Kind::kRead) + throw GoogleError::invalid(id + " is not a read call, pages() walks reads only"); + const Json* start = params.find("pageToken"); + std::vector out; + std::string token = start && start->is_string() ? start->as_string() : ""; + for (int i = 0; i < max_pages; ++i) { + std::string path = token.empty() ? first.path : first.path_with_token(token); + out.push_back(client_->request(first.method, endpoint_, path, nullptr)); + const Json* next = out.back().find("nextPageToken"); + if (!next || !next->is_string() || next->as_string().empty()) break; + token = next->as_string(); + } + return out; +} + +Listing WorkspaceApi::list(const std::string& id, const Json& params, int max_pages) const { + const CallSpec* spec = find_call_in(api_->name, id); + if (!spec) throw GoogleError::invalid("unknown call " + id); + if (!*spec->items_key) throw GoogleError::invalid(id + " has no single items array"); + Listing out; + std::vector docs = pages(id, params, max_pages); + for (const Json& doc : docs) { + ++out.pages; + const Json* arr = doc.find(spec->items_key); + if (arr && arr->is_array()) + for (const Json& item : arr->as_array()) { + if (out.items.size() >= WorkspaceCaps::kMaxItems) { + out.truncated = true; + break; + } + out.items.push_back(item); + } + const Json* next = doc.find("nextPageToken"); + out.next_page_token = next && next->is_string() ? next->as_string() : ""; + } + if (!out.next_page_token.empty()) out.truncated = true; + return out; +} + +} // namespace molo::google::workspace diff --git a/src/google/workspace/workspace_api.h b/src/google/workspace/workspace_api.h new file mode 100644 index 0000000..6771afd --- /dev/null +++ b/src/google/workspace/workspace_api.h @@ -0,0 +1,62 @@ +#pragma once + +// WorkspaceApi: one Workspace API (Gmail, Drive, ...) over the call table. +// Every call of the API is reachable by its Discovery method id. The method +// that runs it must match the call's kind, so a write never hides inside a +// read: read / write / destroy / send. The three side-effecting forms take an +// explicit `confirm` with no default; false throws before any traffic. + +#include +#include +#include +#include + +#include "google/service.h" +#include "google/workspace/calls.h" +#include "google/workspace/prepared_call.h" + +namespace molo::google::workspace { + +using Json = clients::body::Json; +using ParamList = std::vector>; + +struct Listing { + std::vector items; + std::string next_page_token; // set when the walk stopped at a cap + int pages = 0; + bool truncated = false; +}; + +class WorkspaceApi : public Service { + public: + // Throws GoogleError (invalid) for an unknown API name. + WorkspaceApi(std::shared_ptr client, const std::string& api); + + const ApiSpec& api() const { return *api_; } + // Validate only: what would be sent. Throws for an unknown id, an id of + // another API, or any invalid parameter or body field. + PreparedCall prepare(const std::string& id, const Json& params = Json::object(), + const Json* body = nullptr) const; + + Json read(const std::string& id, const Json& params = Json::object(), + const Json* body = nullptr) const; + Json write(const std::string& id, const Json& params, const Json* body, bool confirm) const; + Json destroy(const std::string& id, const Json& params, bool confirm) const; + Json send(const std::string& id, const Json& params, const Json* body, bool confirm) const; + + // Walks nextPageToken of a read call: at most max_pages pages (cap 20). + std::vector pages(const std::string& id, const Json& params = Json::object(), + int max_pages = 5) const; + // The same, collecting the response's array (CallSpec::items_key), at most + // 2000 items. Throws (invalid) when the call has no single items array. + Listing list(const std::string& id, const Json& params = Json::object(), + int max_pages = 5) const; + + static Json make_params(const ParamList& list); + + private: + Json run(const std::string& id, Kind want, const Json& params, const Json* body) const; + const ApiSpec* api_; +}; + +} // namespace molo::google::workspace diff --git a/src/google/workspace/workspace_client.cpp b/src/google/workspace/workspace_client.cpp new file mode 100644 index 0000000..94fc99c --- /dev/null +++ b/src/google/workspace/workspace_client.cpp @@ -0,0 +1,89 @@ +#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 diff --git a/src/google/workspace/workspace_client.h b/src/google/workspace/workspace_client.h new file mode 100644 index 0000000..2fb7aed --- /dev/null +++ b/src/google/workspace/workspace_client.h @@ -0,0 +1,90 @@ +#pragma once + +// Credentials and client wiring for Workspace, and the Workspace facade. +// +// Scopes: Workspace APIs refuse the cloud-platform scope; each API has its own +// (see ApiSpec::scopes, full list per API in SPEC.md). `Scopes` selects the +// read-only subset by default. +// +// Credential choice (WorkspaceAuth::from_env), first match wins: +// 1. a delegation subject (option or GOOGLE_WORKSPACE_SUBJECT): the service +// account key in GOOGLE_APPLICATION_CREDENTIALS impersonates that user +// (domain-wide delegation). No key: GoogleError invalid. +// 2. GOOGLE_ACCESS_TOKEN: a user's OAuth token, used as is (its scopes were +// fixed when the user consented). +// 3. GOOGLE_APPLICATION_CREDENTIALS without subject: the service account +// itself (it owns no Workspace data; expect empty lists or 403). +// 4. nothing: null, every call throws NotConfiguredError. + +#include +#include +#include +#include + +#include "clients/auth.h" +#include "google/client.h" +#include "google/workspace/delegation.h" +#include "google/workspace/services.h" + +namespace molo::google::workspace { + +class Scopes { + public: + // Scope URLs of the named APIs. readonly: the read-only subset; an API + // without one (groupssettings) contributes its full scope. + // Throws GoogleError (invalid) for an unknown API, no API, or over 40 scopes. + static std::vector for_apis(const std::vector& apis, bool readonly); + static std::vector all_of(const std::string& api); + static std::vector readonly_of(const std::string& api); +}; + +struct WorkspaceOptions { + std::vector apis; // which APIs the token must cover + bool readonly = true; + Delegation delegation; // typed `sub` option; empty: env, then none +}; + +class WorkspaceAuth { + public: + static std::shared_ptr from_env(const WorkspaceOptions& options); + // "delegated", "user-token", "service-account" or "none": for status pages. + static std::string mode_from_env(const WorkspaceOptions& options); +}; + +// GoogleClient over HttpTransport with the credential above. +std::shared_ptr make_workspace_client(const WorkspaceOptions& options); + +// All twenty services over one client. +class Workspace { + public: + explicit Workspace(std::shared_ptr client); + // Any API by name (see api_names()). + WorkspaceApi api(const std::string& name) const { return WorkspaceApi(client_, name); } + static std::vector api_names(); + + Gmail gmail() const { return Gmail(client_); } + Drive drive() const { return Drive(client_); } + Calendar calendar() const { return Calendar(client_); } + Sheets sheets() const { return Sheets(client_); } + Docs docs() const { return Docs(client_); } + Slides slides() const { return Slides(client_); } + Forms forms() const { return Forms(client_); } + Tasks tasks() const { return Tasks(client_); } + Chat chat() const { return Chat(client_); } + Meet meet() const { return Meet(client_); } + People people() const { return People(client_); } + Keep keep() const { return Keep(client_); } + Classroom classroom() const { return Classroom(client_); } + YouTube youtube() const { return YouTube(client_); } + YouTubeAnalytics youtube_analytics() const { return YouTubeAnalytics(client_); } + YouTubeReporting youtube_reporting() const { return YouTubeReporting(client_); } + Directory directory() const { return Directory(client_); } + Reports reports() const { return Reports(client_); } + GroupsSettings groups_settings() const { return GroupsSettings(client_); } + Vault vault() const { return Vault(client_); } + + private: + std::shared_ptr client_; +}; + +} // namespace molo::google::workspace diff --git a/tests/example/google/workspace/call_test.cpp b/tests/example/google/workspace/call_test.cpp new file mode 100644 index 0000000..daadd96 --- /dev/null +++ b/tests/example/google/workspace/call_test.cpp @@ -0,0 +1,62 @@ +// Routes: POST /google/workspace/call, /list, /delegation +// Reads: 422 on bad input, 503 google_not_configured without a credential. +// Writes, deletes and sends: dry run unless confirm:true. Nothing reaches Google. +#include "support/GoogleRig.hpp" + +using namespace molo::example::test; + +int main() { + GoogleRig rig(false); + Fixture f(rig.client); + const char* json = "application/json"; + auto post = [&](const char* path, const std::string& body) { return f.client->post(path, body, json); }; + + auto read = post("/google/workspace/call", "{\"api\":\"gmail\",\"id\":\"gmail.users.getProfile\",\"params\":{\"userId\":\"me\"}}"); + check(read.status == 503 && contains(read.body, "google_not_configured"), "valid read without credential is 503"); + + check(post("/google/workspace/call", "{}").status == 422, "api and id required"); + check(post("/google/workspace/call", "{\"api\":\"nope\",\"id\":\"x\"}").status == 422, "unknown api is 422"); + check(post("/google/workspace/call", "{\"api\":\"gmail\",\"id\":\"drive.files.list\"}").status == 422, "id of another api is 422"); + check(post("/google/workspace/call", "{\"api\":\"gmail\",\"id\":\"gmail.users.getProfile\",\"params\":{}}").status == 422, "missing path param is 422"); + check(post("/google/workspace/call", "{\"api\":\"gmail\",\"id\":\"gmail.users.getProfile\",\"params\":{\"userId\":\"me\",\"x\":1}}").status == 422, "unknown param is 422"); + check(post("/google/workspace/call", "{\"api\":\"gmail\",\"id\":\"gmail.users.getProfile\",\"params\":[]}").status == 422, "params must be an object"); + check(post("/google/workspace/call", "{\"api\":\"gmail\",\"id\":\"gmail.users.getProfile\",\"params\":{\"userId\":\"me\"},\"confirm\":\"yes\"}").status == 422, "confirm must be a bool"); + check(post("/google/workspace/call", "not json").status == 422, "bad json is 422"); + check(post("/google/workspace/call", "{\"api\":\"drive\",\"id\":\"drive.files.export\",\"params\":{\"fileId\":\"1\",\"mimeType\":\"text/plain\"}}").status == 422, "bytes responses are refused"); + + // sends, writes and deletes are dry runs by default, even without a credential + auto send = post("/google/workspace/call", "{\"api\":\"gmail\",\"id\":\"gmail.users.messages.send\",\"params\":{\"userId\":\"me\"},\"body\":{\"raw\":\"AAAA\"}}"); + check(send.status == 200 && contains(send.body, "\"dry_run\":true") && contains(send.body, "\"kind\":\"send\"") && + contains(send.body, "/gmail/v1/users/me/messages/send"), + "send is a dry run"); + auto del = post("/google/workspace/call", "{\"api\":\"drive\",\"id\":\"drive.files.delete\",\"params\":{\"fileId\":\"abc\"}}"); + check(del.status == 200 && contains(del.body, "\"dry_run\":true") && contains(del.body, "\"kind\":\"destroy\""), "delete is a dry run"); + auto wr = post("/google/workspace/call", "{\"api\":\"sheets\",\"id\":\"sheets.spreadsheets.values.update\",\"params\":{\"spreadsheetId\":\"s\",\"range\":\"A1\",\"valueInputOption\":\"RAW\"},\"body\":{\"values\":[[1]]}}"); + check(wr.status == 200 && contains(wr.body, "\"kind\":\"write\""), "write is a dry run"); + check(post("/google/workspace/call", "{\"api\":\"gmail\",\"id\":\"gmail.users.messages.send\",\"params\":{\"userId\":\"me\"},\"body\":{\"nonsense\":1}}").status == 422, "unknown body field is 422 even for a dry run"); + auto confirmed = post("/google/workspace/call", "{\"api\":\"gmail\",\"id\":\"gmail.users.messages.send\",\"params\":{\"userId\":\"me\"},\"body\":{\"raw\":\"AAAA\"},\"confirm\":true}"); + check(confirmed.status == 503 && contains(confirmed.body, "google_not_configured"), "confirmed send without credential is 503"); + + // list + check(post("/google/workspace/list", "{\"api\":\"drive\",\"id\":\"drive.files.list\"}").status == 503, "list without credential is 503"); + check(post("/google/workspace/list", "{\"api\":\"drive\",\"id\":\"drive.files.list\",\"maxPages\":9}").status == 422, "maxPages over 5 is 422"); + check(post("/google/workspace/list", "{\"api\":\"gmail\",\"id\":\"gmail.users.getProfile\",\"params\":{\"userId\":\"me\"}}").status == 422, "no items array is 422"); + check(post("/google/workspace/list", "{\"api\":\"gmail\",\"id\":\"gmail.users.messages.send\",\"params\":{\"userId\":\"me\"}}").status == 422, "list of a send is 422"); + + // delegation: local validation only + auto del_ok = post("/google/workspace/delegation", "{\"subject\":\"admin@example.com\",\"apis\":\"gmail,drive\"}"); + check(del_ok.status == 200 && contains(del_ok.body, "\"impersonating\":true") && contains(del_ok.body, "gmail.readonly"), "delegation preview"); + check(post("/google/workspace/delegation", "{\"subject\":\"not-an-email\",\"apis\":\"gmail\"}").status == 422, "bad subject is 422"); + check(post("/google/workspace/delegation", "{\"apis\":\"nope\"}").status == 422, "unknown api is 422"); + check(post("/google/workspace/delegation", "{}").status == 422, "apis required"); + + check(f.client->get("/google/workspace/call").status == 405, "get is 405"); + check(f.client->get("/google/workspace/list").status == 405, "get list is 405"); + check(rig.mock->send_count() == 0, "nothing reached Google"); + + // environment-built client (no injection): same contract + Fixture g; + auto env_read = g.client->post("/google/workspace/call", "{\"api\":\"calendar\",\"id\":\"calendar.calendarList.list\"}", json); + check(env_read.status == 503 && contains(env_read.body, "google_not_configured"), "env client without credential is 503"); + return finish("google/workspace/call"); +} diff --git a/tests/example/google/workspace/page_test.cpp b/tests/example/google/workspace/page_test.cpp new file mode 100644 index 0000000..0519278 --- /dev/null +++ b/tests/example/google/workspace/page_test.cpp @@ -0,0 +1,18 @@ +// Route: GET /google/workspace (page, no credential needed) +#include "support/GoogleRig.hpp" + +using namespace molo::example::test; + +int main() { + GoogleRig rig(false); + Fixture f(rig.client); + auto res = f.client->get("/google/workspace"); + check(res.status == 200, "status 200"); + check(contains(res.headers.get("Content-Type"), "text/html"), "html"); + check(contains(res.body, "Google Workspace") && contains(res.body, "viewport"), "page and mobile viewport"); + check(contains(res.body, "/embedded/google_workspace.js"), "script wired"); + check(contains(res.body, "post("/google/workspace", "{}", "application/json").status == 405, "post is 405"); + check(rig.mock->send_count() == 0, "no network"); + return finish("google/workspace"); +} diff --git a/tests/example/google/workspace/status_test.cpp b/tests/example/google/workspace/status_test.cpp new file mode 100644 index 0000000..c804270 --- /dev/null +++ b/tests/example/google/workspace/status_test.cpp @@ -0,0 +1,34 @@ +// Routes: GET /google/workspace/{status,apis,calls,scopes} +#include "support/GoogleRig.hpp" + +using namespace molo::example::test; + +int main() { + GoogleRig rig(false); + Fixture f(rig.client); + auto st = f.client->get("/google/workspace/status"); + check(st.status == 200 && contains(st.body, "\"configured\":false"), "status without credential"); + check(contains(st.body, "\"apis\":20"), "twenty apis"); + auto apis = f.client->get("/google/workspace/apis"); + check(apis.status == 200 && contains(apis.body, "\"name\":\"gmail\"") && + contains(apis.body, "\"name\":\"vault\"") && contains(apis.body, "\"name\":\"directory\""), + "apis listed"); + check(contains(apis.body, "gmail.googleapis.com"), "service to enable shown"); + auto calls = f.client->get("/google/workspace/calls?api=gmail&kind=s"); + check(calls.status == 200 && contains(calls.body, "gmail.users.messages.send") && + !contains(calls.body, "gmail.users.messages.list"), + "calls filtered by api and kind"); + check(f.client->get("/google/workspace/calls?api=nope").status == 422, "unknown api is 422"); + check(f.client->get("/google/workspace/calls?kind=x").status == 422, "unknown kind is 422"); + auto all = f.client->get("/google/workspace/calls"); + check(all.status == 200 && contains(all.body, "\"truncated\":true"), "unfiltered listing is capped"); + auto scopes = f.client->get("/google/workspace/scopes?apis=gmail,drive&readonly=true"); + check(scopes.status == 200 && contains(scopes.body, "gmail.readonly") && contains(scopes.body, "drive.readonly"), + "readonly scopes"); + check(!contains(scopes.body, "auth/gmail.send"), "no write scope in the readonly set"); + check(f.client->get("/google/workspace/scopes").status == 422, "apis required"); + check(f.client->get("/google/workspace/scopes?apis=gmail&readonly=maybe").status == 422, "readonly must be a bool"); + check(f.client->post("/google/workspace/status", "{}", "application/json").status == 405, "post is 405"); + check(rig.mock->send_count() == 0, "no network"); + return finish("google/workspace/status"); +} diff --git a/tests/src/google/workspace/test_workspace.cpp b/tests/src/google/workspace/test_workspace.cpp new file mode 100644 index 0000000..2e31d86 --- /dev/null +++ b/tests/src/google/workspace/test_workspace.cpp @@ -0,0 +1,377 @@ +// Workspace: deterministic local tests (call table, request building, +// validation, caps, kinds, scopes, delegation claims) plus opt-in live +// read-only checks (test_workspace_live.cpp). No scripted Google replies: +// shapes are proven against Discovery by tools/check_discovery.py. +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "framework.h" +#include "clients/transports/mock_transport.h" +#include "google/errors.h" +#include "google/workspace/calls.h" +#include "google/workspace/caps.h" +#include "google/workspace/delegation.h" +#include "google/workspace/prepared_call.h" +#include "google/workspace/workspace_client.h" +#include "security/crypto/Base64.h" + +using namespace molo::google; +using namespace molo::google::workspace; +using molo::clients::Method; +using molo::clients::body::Json; +using molo::clients::transports::MockTransport; +using molo::security::crypto::Base64; + +namespace { + +struct Rig { + MockTransport* mock; + std::shared_ptr client; + Rig() { + auto t = std::make_unique(); + mock = t.get(); + client = std::make_shared(std::move(t), nullptr); + } +}; + +Json obj(std::initializer_list> kv) { + Json o = Json::object(); + for (const auto& [k, v] : kv) o.set(k, v); + return o; +} + +std::string pem_key(RsaKey& key, WC_RNG& rng) { + wc_InitRng(&rng); + wc_InitRsaKey(&key, nullptr); + if (wc_MakeRsaKey(&key, 2048, 65537, &rng) != 0) FAIL("key generation failed"); + std::string der(4096, '\0'); + int n = wc_RsaKeyToDer(&key, reinterpret_cast(der.data()), der.size()); + if (n <= 0) FAIL("key export failed"); + der.resize(n); + std::string pem(8192, '\0'); + int p = wc_DerToPem(reinterpret_cast(der.data()), der.size(), + reinterpret_cast(pem.data()), pem.size(), PRIVATEKEY_TYPE); + if (p <= 0) FAIL("pem export failed"); + pem.resize(p); + return pem; +} + +ServiceAccountKey make_key(const std::string& pem) { + Json j = obj({{"type", Json("service_account")}, + {"client_email", Json("sa@p-1.iam.gserviceaccount.com")}, + {"private_key", Json(pem)}}); + return ServiceAccountKey::parse(j.dump()); +} + +std::vector dots(const std::string& s) { + std::vector out; + std::size_t pos = 0, d; + while ((d = s.find('.', pos)) != std::string::npos) { + out.push_back(s.substr(pos, d - pos)); + pos = d + 1; + } + out.push_back(s.substr(pos)); + return out; +} + +} // namespace + +TEST(workspace_table, covers_twenty_apis_and_every_call_is_well_formed) { + ASSERT_EQ(kApiTableSize, 20u); + ASSERT_TRUE(kCallTableSize >= 700); + std::set ids; + for (std::size_t i = 0; i < kCallTableSize; ++i) { + const CallSpec& c = kCallTable[i]; + ASSERT_TRUE(ids.insert(std::string(c.api) + "/" + c.id).second); // unique per API + ASSERT_TRUE(find_api(c.api) != nullptr); + ASSERT_TRUE(std::string("rwds").find(c.kind[0]) != std::string::npos); + ASSERT_EQ(std::string(c.kind).size(), 1u); + if (std::string(c.http) == "GET") ASSERT_TRUE(kind_of(c) == Kind::kRead); + if (std::string(c.http) == "DELETE") ASSERT_TRUE(kind_of(c) == Kind::kDestroy); + // every path placeholder has a path parameter + std::set path_params; + for (const auto& p : params_of(c)) + if (p.path) path_params.insert(p.name); + std::string t = c.path; + std::size_t placeholders = 0; + for (std::size_t k = t.find('{'); k != std::string::npos; k = t.find('{', k + 1)) { + std::size_t e = t.find('}', k); + std::string n = t.substr(k + 1, e - k - 1); + if (!n.empty() && n[0] == '+') n.erase(0, 1); + ASSERT_TRUE(path_params.count(n) == 1); + ++placeholders; + } + ASSERT_EQ(placeholders, path_params.size()); + } + for (const char* api : {"gmail", "drive", "calendar", "sheets", "docs", "slides", "forms", "tasks", + "chat", "meet", "people", "keep", "classroom", "youtube", + "youtubeanalytics", "youtubereporting", "directory", "reports", + "groupssettings", "vault"}) + ASSERT_TRUE(!calls_of(api).empty()); +} + +TEST(workspace_table, kinds_of_named_calls) { + ASSERT_TRUE(kind_of(*find_call("gmail.users.messages.send")) == Kind::kSend); + ASSERT_TRUE(kind_of(*find_call("chat.spaces.messages.create")) == Kind::kSend); + ASSERT_TRUE(kind_of(*find_call("gmail.users.messages.list")) == Kind::kRead); + ASSERT_TRUE(kind_of(*find_call("calendar.freebusy.query")) == Kind::kRead); + ASSERT_TRUE(kind_of(*find_call("drive.files.delete")) == Kind::kDestroy); + ASSERT_TRUE(kind_of(*find_call("directory.users.signOut")) == Kind::kDestroy); + ASSERT_TRUE(kind_of(*find_call("sheets.spreadsheets.values.update")) == Kind::kWrite); + ASSERT_TRUE(kind_of(*find_call("docs.documents.batchUpdate")) == Kind::kWrite); + ASSERT_TRUE(has_flag(*find_call("drive.files.export"), 'b')); + ASSERT_TRUE(find_call("nope.nothing") == nullptr); +} + +TEST(workspace_request, path_and_query_are_encoded_from_the_table) { + const CallSpec& c = *find_call("gmail.users.messages.list"); + Json p = obj({{"userId", Json("me")}, {"q", Json("from:a@b.c is:unread")}, {"maxResults", Json(5)}}); + Json labels = Json::array(); + labels.push(Json("INBOX")); + labels.push(Json("UNREAD")); + p.set("labelIds", labels); + p.set("includeSpamTrash", Json(false)); + PreparedCall call = PreparedCall::build(c, p, nullptr); + ASSERT_TRUE(call.method == Method::kGet); + ASSERT_EQ(call.path, + "/gmail/v1/users/me/messages?includeSpamTrash=false&labelIds=INBOX&labelIds=UNREAD" + "&maxResults=5&q=from%3Aa%40b.c%20is%3Aunread"); +} + +TEST(workspace_request, plus_params_keep_slashes_and_plain_ones_do_not) { + PreparedCall chat = PreparedCall::build(*find_call("chat.spaces.messages.list"), + obj({{"parent", Json("spaces/AAAA")}}), nullptr); + ASSERT_EQ(chat.path, "/v1/spaces/AAAA/messages"); + ASSERT_THROW(PreparedCall::build(*find_call("gmail.users.getProfile"), + obj({{"userId", Json("a/b")}}), nullptr), GoogleError); + ASSERT_THROW(PreparedCall::build(*find_call("chat.spaces.messages.list"), + obj({{"parent", Json("spaces/../x")}}), nullptr), GoogleError); + PreparedCall cal = PreparedCall::build(*find_call("calendar.events.list"), + obj({{"calendarId", Json("en.usa#holiday@group.v.calendar.google.com")}}), + nullptr); + ASSERT_EQ(cal.path, "/calendars/en.usa%23holiday%40group.v.calendar.google.com/events"); + PreparedCall sheet = PreparedCall::build(*find_call("sheets.spreadsheets.values.get"), + obj({{"spreadsheetId", Json("abc")}, {"range", Json("Sheet1!A1:B2")}}), + nullptr); + ASSERT_EQ(sheet.path, "/v4/spreadsheets/abc/values/Sheet1%21A1%3AB2"); +} + +TEST(workspace_request, validation_rejects_before_any_traffic) { + const CallSpec& list = *find_call("gmail.users.messages.list"); + ASSERT_THROW(PreparedCall::build(list, obj({}), nullptr), GoogleError); // userId missing + ASSERT_THROW(PreparedCall::build(list, obj({{"userId", Json("me")}, {"bogus", Json("x")}}), nullptr), GoogleError); + ASSERT_THROW(PreparedCall::build(list, obj({{"userId", Json("me")}, {"maxResults", Json("abc")}}), nullptr), GoogleError); + ASSERT_THROW(PreparedCall::build(list, obj({{"userId", Json("me")}, {"includeSpamTrash", Json("yes")}}), nullptr), GoogleError); + ASSERT_THROW(PreparedCall::build(list, obj({{"userId", Json("me")}, {"labelIds", Json("INBOX")}}), nullptr), GoogleError); + ASSERT_THROW(PreparedCall::build(list, obj({{"userId", Json(std::string(600, 'a'))}}), nullptr), GoogleError); + ASSERT_THROW(PreparedCall::build(list, obj({{"userId", Json("me")}, {"q", Json(std::string(3000, 'a'))}}), nullptr), GoogleError); + ASSERT_THROW(PreparedCall::build(list, obj({{"userId", Json("m\ne")}}), nullptr), GoogleError); + Json body = obj({{"x", Json(1)}}); + ASSERT_THROW(PreparedCall::build(list, obj({{"userId", Json("me")}}), &body), GoogleError); // no body + // required query parameter (youtube part) + ASSERT_THROW(PreparedCall::build(*find_call("youtube.channels.list"), obj({{"mine", Json(true)}}), nullptr), GoogleError); + // unknown body field + Json bad = obj({{"nonsense", Json(1)}}); + ASSERT_THROW(PreparedCall::build(*find_call("gmail.users.messages.send"), obj({{"userId", Json("me")}}), &bad), GoogleError); + Json good = obj({{"raw", Json("AAAA")}}); + PreparedCall ok = PreparedCall::build(*find_call("gmail.users.messages.send"), obj({{"userId", Json("me")}}), &good); + ASSERT_TRUE(ok.method == Method::kPost && ok.has_body); + Json huge = obj({{"raw", Json(std::string(WorkspaceCaps::kMaxBodyBytes + 1, 'a'))}}); + ASSERT_THROW(PreparedCall::build(*find_call("gmail.users.messages.send"), obj({{"userId", Json("me")}}), &huge), GoogleError); + // fields selector is allowed on every call, capped + PreparedCall f = PreparedCall::build(*find_call("drive.about.get"), obj({{"fields", Json("user")}}), nullptr); + ASSERT_EQ(f.path, "/about?fields=user"); + ASSERT_THROW(PreparedCall::build(*find_call("drive.about.get"), obj({{"fields", Json(std::string(2000, 'a'))}}), nullptr), GoogleError); +} + +TEST(workspace_request, groups_settings_asks_for_json) { + PreparedCall c = PreparedCall::build(*find_call("groupsSettings.groups.get"), + obj({{"groupUniqueId", Json("g@example.com")}}), nullptr); + ASSERT_EQ(c.path, "/g%40example.com?alt=json"); + Rig rig; + WorkspaceApi api(rig.client, "groupssettings"); + ASSERT_EQ(api.endpoint().base_url, "https://www.googleapis.com/groups/v1/groups"); +} + +TEST(workspace_api, kinds_gate_the_methods_and_confirm_has_no_default) { + Rig rig; + WorkspaceApi gmail(rig.client, "gmail"); + Json user = obj({{"userId", Json("me")}}); + Json raw = obj({{"raw", Json("AAAA")}}); + // read() refuses a send, send() refuses without confirm, both before traffic + ASSERT_THROW(gmail.read("gmail.users.messages.send", user, &raw), GoogleError); + try { + gmail.send("gmail.users.messages.send", user, &raw, false); + FAIL("send without confirm must throw"); + } catch (const GoogleError& e) { + ASSERT_EQ(e.http_status(), 400); + ASSERT_EQ(e.status(), "INVALID_ARGUMENT"); + } + ASSERT_THROW(gmail.write("gmail.users.messages.send", user, &raw, true), GoogleError); // wrong kind + ASSERT_THROW(gmail.destroy("gmail.users.messages.delete", + obj({{"userId", Json("me")}, {"id", Json("1")}}), false), GoogleError); + // confirmed and valid: only now does it reach the credential check + ASSERT_THROW(gmail.send("gmail.users.messages.send", user, &raw, true), NotConfiguredError); + ASSERT_THROW(gmail.read("drive.files.list"), GoogleError); // another API's call + ASSERT_THROW(gmail.read("drive.files.export"), GoogleError); + WorkspaceApi drive(rig.client, "drive"); + ASSERT_THROW(drive.read("drive.files.export", obj({{"fileId", Json("1")}, {"mimeType", Json("text/plain")}})), GoogleError); // bytes + ASSERT_THROW(WorkspaceApi(rig.client, "nope"), GoogleError); + ASSERT_EQ(rig.mock->send_count(), 0u); +} + +TEST(workspace_api, no_credential_is_loud_for_every_typed_service) { + Rig rig; + Workspace ws(rig.client); + ASSERT_THROW(ws.gmail().profile(), NotConfiguredError); + ASSERT_THROW(ws.drive().about(), NotConfiguredError); + ASSERT_THROW(ws.calendar().calendars(), NotConfiguredError); + ASSERT_THROW(ws.sheets().spreadsheet("abc"), NotConfiguredError); + ASSERT_THROW(ws.docs().document("abc"), NotConfiguredError); + ASSERT_THROW(ws.slides().presentation("abc"), NotConfiguredError); + ASSERT_THROW(ws.forms().form("abc"), NotConfiguredError); + ASSERT_THROW(ws.tasks().task_lists(), NotConfiguredError); + ASSERT_THROW(ws.chat().spaces(), NotConfiguredError); + ASSERT_THROW(ws.meet().conference_records(), NotConfiguredError); + ASSERT_THROW(ws.people().me(), NotConfiguredError); + ASSERT_THROW(ws.keep().notes(), NotConfiguredError); + ASSERT_THROW(ws.classroom().courses(), NotConfiguredError); + ASSERT_THROW(ws.youtube().my_channel(), NotConfiguredError); + ASSERT_THROW(ws.youtube_analytics().report("channel==MINE", "2026-01-01", "2026-01-31", "views"), NotConfiguredError); + ASSERT_THROW(ws.youtube_reporting().jobs(), NotConfiguredError); + ASSERT_THROW(ws.directory().users(), NotConfiguredError); + ASSERT_THROW(ws.reports().activities("all", "login"), NotConfiguredError); + ASSERT_THROW(ws.groups_settings().group("g@example.com"), NotConfiguredError); + ASSERT_THROW(ws.vault().matters(), NotConfiguredError); + ASSERT_EQ(Workspace::api_names().size(), 20u); + ASSERT_EQ(rig.mock->send_count(), 0u); +} + +TEST(workspace_api, page_walk_caps) { + Rig rig; + WorkspaceApi gmail(rig.client, "gmail"); + Json p = obj({{"userId", Json("me")}}); + ASSERT_THROW(gmail.pages("gmail.users.messages.list", p, 0), GoogleError); + ASSERT_THROW(gmail.pages("gmail.users.messages.list", p, WorkspaceCaps::kMaxPages + 1), GoogleError); + ASSERT_THROW(gmail.pages("gmail.users.messages.send", p, 1), GoogleError); // not a read + ASSERT_THROW(gmail.list("gmail.users.getProfile", p, 1), GoogleError); // no items array +} + +TEST(workspace_scopes, per_api_scopes_and_readonly_subsets) { + auto gm = Scopes::all_of("gmail"); + ASSERT_TRUE(gm.size() >= 5); + for (const auto& s : Scopes::readonly_of("gmail")) ASSERT_TRUE(s.find("readonly") != std::string::npos || s.find("metadata") != std::string::npos); + // groupssettings has no readonly scope: its full scope stands in + ASSERT_EQ(Scopes::readonly_of("groupssettings").size(), 1u); + auto mix = Scopes::for_apis({"gmail", "drive", "calendar"}, true); + ASSERT_TRUE(mix.size() >= 3 && mix.size() <= 40); + std::set uniq(mix.begin(), mix.end()); + ASSERT_EQ(uniq.size(), mix.size()); + ASSERT_THROW(Scopes::for_apis({}, true), GoogleError); + ASSERT_THROW(Scopes::for_apis({"nope"}, true), GoogleError); + for (std::size_t i = 0; i < kApiTableSize; ++i) { + ASSERT_TRUE(Scopes::all_of(kApiTable[i].name).size() >= 1); + for (const auto& s : Scopes::all_of(kApiTable[i].name)) ASSERT_TRUE(s.rfind("https://", 0) == 0); + } +} + +TEST(workspace_delegation, assertion_carries_sub_and_verifies) { + RsaKey key; + WC_RNG rng; + std::string pem = pem_key(key, rng); + ServiceAccountKey sak = make_key(pem); + Delegation d{"admin@example.com"}; + std::string jwt = DelegatedAuth::assertion(sak, "https://www.googleapis.com/auth/gmail.readonly", d, 1700000000); + auto parts = dots(jwt); + ASSERT_EQ(parts.size(), 3u); + std::string hdr, claims, sig; + ASSERT_TRUE(Base64::decode_url(parts[0], hdr)); + ASSERT_TRUE(Base64::decode_url(parts[1], claims)); + ASSERT_TRUE(Base64::decode_url(parts[2], sig)); + Json c = Json::parse(claims); + ASSERT_EQ(c.find("sub")->as_string(), "admin@example.com"); + ASSERT_EQ(c.find("iss")->as_string(), "sa@p-1.iam.gserviceaccount.com"); + ASSERT_EQ(c.find("scope")->as_string(), "https://www.googleapis.com/auth/gmail.readonly"); + ASSERT_EQ(c.find("exp")->as_int(), 1700003600L); + std::string input = parts[0] + "." + parts[1]; + ASSERT_EQ(wc_SignatureVerify(WC_HASH_TYPE_SHA256, WC_SIGNATURE_TYPE_RSA_W_ENC, + reinterpret_cast(input.data()), input.size(), + reinterpret_cast(sig.data()), sig.size(), &key, sizeof(key)), 0); + // without a subject the claim is absent: the token acts as the service account + std::string plain = DelegatedAuth::assertion(sak, "s", Delegation{}, 1700000000); + std::string pc; + ASSERT_TRUE(Base64::decode_url(dots(plain)[1], pc)); + ASSERT_TRUE(Json::parse(pc).find("sub") == nullptr); + wc_FreeRsaKey(&key); + wc_FreeRng(&rng); +} + +TEST(workspace_delegation, subject_and_scope_validation) { + for (const char* bad : {"nobody", "@x.com", "a@", "a@b@c", "a b@c.com", "a\n@c.com"}) + ASSERT_THROW(Delegation{bad}.validate(), GoogleError); + ASSERT_THROW(Delegation{std::string(300, 'a') + "@x.com"}.validate(), GoogleError); + Delegation{}.validate(); + Delegation{"a@b.com"}.validate(); + RsaKey key; + WC_RNG rng; + ServiceAccountKey sak = make_key(pem_key(key, rng)); + ASSERT_THROW(DelegatedAuth(sak, {}, Delegation{}), GoogleError); + ASSERT_THROW(DelegatedAuth(sak, {"not-a-url"}, Delegation{}), GoogleError); + ASSERT_THROW(DelegatedAuth(sak, {"https://x/a b"}, Delegation{}), GoogleError); + ASSERT_THROW(DelegatedAuth(sak, {"https://x/a"}, Delegation{"bad"}), GoogleError); + DelegatedAuth ok(sak, {"https://www.googleapis.com/auth/drive.readonly", "https://www.googleapis.com/auth/gmail.readonly"}, + Delegation{"u@example.com"}); + ASSERT_EQ(ok.scope_string(), "https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/gmail.readonly"); + ASSERT_EQ(ok.delegation().subject, "u@example.com"); + wc_FreeRsaKey(&key); + wc_FreeRng(&rng); +} + +TEST(workspace_delegation, credential_mode_follows_the_documented_order) { + // Credentials::env may cache and the live tests need the real environment: + // this test owns the environment only in the offline run. + if (std::getenv("MOLO_LIVE_NET")) { + std::cout << "SKIP workspace_delegation.credential_mode (offline test; unset MOLO_LIVE_NET)\n"; + return; + } + // The process environment is shared with the live tests: save and restore. + auto save = [](const char* n) { const char* v = std::getenv(n); return v ? std::string(v) : std::string(); }; + const std::string old_env_files = save("MOLO_ENV_FILES"), old_token = save("GOOGLE_ACCESS_TOKEN"), + old_key = save("GOOGLE_APPLICATION_CREDENTIALS"), old_sub = save("GOOGLE_WORKSPACE_SUBJECT"); + struct Restore { + std::vector> vars; + ~Restore() { + for (auto& [n, v] : vars) v.empty() ? unsetenv(n) : setenv(n, v.c_str(), 1); + } + } restore{{{"MOLO_ENV_FILES", old_env_files}, {"GOOGLE_ACCESS_TOKEN", old_token}, + {"GOOGLE_APPLICATION_CREDENTIALS", old_key}, {"GOOGLE_WORKSPACE_SUBJECT", old_sub}}}; + setenv("MOLO_ENV_FILES", "off", 1); + unsetenv("GOOGLE_WORKSPACE_SUBJECT"); + unsetenv("GOOGLE_ACCESS_TOKEN"); + unsetenv("GOOGLE_APPLICATION_CREDENTIALS"); + WorkspaceOptions o; + o.apis = {"gmail"}; + ASSERT_EQ(WorkspaceAuth::mode_from_env(o), "none"); + ASSERT_TRUE(WorkspaceAuth::from_env(o) == nullptr); + setenv("GOOGLE_APPLICATION_CREDENTIALS", "/nonexistent/key.json", 1); + ASSERT_EQ(WorkspaceAuth::mode_from_env(o), "service-account"); + setenv("GOOGLE_ACCESS_TOKEN", "tok", 1); + ASSERT_EQ(WorkspaceAuth::mode_from_env(o), "user-token"); + ASSERT_TRUE(WorkspaceAuth::from_env(o) != nullptr); + o.delegation = Delegation{"admin@example.com"}; + ASSERT_EQ(WorkspaceAuth::mode_from_env(o), "delegated"); + ASSERT_THROW(WorkspaceAuth::from_env(o), GoogleError); // key file unreadable + unsetenv("GOOGLE_APPLICATION_CREDENTIALS"); + ASSERT_THROW(WorkspaceAuth::from_env(o), GoogleError); // subject without key + o.delegation = Delegation{"bad"}; + ASSERT_THROW(WorkspaceAuth::from_env(o), GoogleError); + unsetenv("GOOGLE_ACCESS_TOKEN"); +} diff --git a/tests/src/google/workspace/test_workspace_live.cpp b/tests/src/google/workspace/test_workspace_live.cpp new file mode 100644 index 0000000..5037090 --- /dev/null +++ b/tests/src/google/workspace/test_workspace_live.cpp @@ -0,0 +1,135 @@ +// Opt-in live, read-only checks (MOLO_LIVE_NET=1). Nothing is sent, created, +// changed or deleted. Workspace data belongs to humans: the service account of +// the test project has none and no domain-wide delegation, so the expected +// answers are 400/401/403 or empty lists. Each probe prints what Google said; +// a disabled API is reported loudly as "API NOT ENABLED". +#include +#include + +#include "framework.h" +#include "google/credentials.h" +#include "google/errors.h" +#include "clients/transports/http_transport.h" +#include "google/workspace/workspace_client.h" + +using namespace molo::google; +using namespace molo::google::workspace; + +namespace { + +bool net() { return std::getenv("MOLO_LIVE_NET") != nullptr; } + +// Other suites in this binary unset GOOGLE_ACCESS_TOKEN, so it is captured +// before main() runs. +const std::string kStartToken = [] { + const char* v = std::getenv("GOOGLE_ACCESS_TOKEN"); + return v ? std::string(v) : std::string(); +}(); + +std::string clip(const std::string& s) { return s.size() > 140 ? s.substr(0, 140) + "..." : s; } + +// Runs one read, prints the outcome, returns the HTTP status (200 on success, +// 0 for an unexpected local failure). Fails the test on a transport failure. +template +int probe(const char* name, F&& f) { + try { + f(); + std::cout << " " << name << ": 200 OK\n"; + return 200; + } catch (const GoogleError& e) { + bool disabled = e.status() == "SERVICE_DISABLED" || + e.message().find("has not been used") != std::string::npos || + e.message().find("is not enabled") != std::string::npos; + std::cout << " " << name << ": " << e.http_status() << " " << e.status() + << (disabled ? " API NOT ENABLED" : "") << " | " << clip(e.message()) << "\n"; + if (e.status() == "UNAVAILABLE") FAIL(std::string(name) + ": transport failure " + e.message()); + return e.http_status(); + } +} + +} // namespace + +TEST(workspace_live, reads_with_the_cloud_platform_token) { + if (!net() || kStartToken.empty()) { + std::cout << "SKIP workspace_live.reads_with_the_cloud_platform_token (set MOLO_LIVE_NET=1 and GOOGLE_ACCESS_TOKEN)\n"; + return; + } + Workspace ws(std::make_shared( + std::make_unique(), nullptr, + Credentials::bearer(kStartToken))); + std::cout << " mode: user-token (cloud-platform scope of the test service account)\n"; + probe("gmail.getProfile", [&] { ws.gmail().profile(); }); + probe("drive.about", [&] { ws.drive().about(); }); + probe("calendar.calendarList", [&] { ws.calendar().calendars(); }); + probe("sheets.get(unknown)", [&] { ws.sheets().spreadsheet("1x"); }); + probe("docs.get(unknown)", [&] { ws.docs().document("1x"); }); + probe("slides.get(unknown)", [&] { ws.slides().presentation("1x"); }); + probe("forms.get(unknown)", [&] { ws.forms().form("1x"); }); + probe("tasks.tasklists", [&] { ws.tasks().task_lists(); }); + probe("chat.spaces", [&] { ws.chat().spaces(); }); + probe("meet.conferenceRecords", [&] { ws.meet().conference_records(); }); + probe("people.me", [&] { ws.people().me(); }); + probe("keep.notes", [&] { ws.keep().notes(); }); + probe("classroom.courses", [&] { ws.classroom().courses(); }); + probe("youtube.channels(mine)", [&] { ws.youtube().my_channel(); }); + probe("youtubereporting.reportTypes", [&] { ws.youtube_reporting().report_types(); }); + probe("directory.users", [&] { ws.directory().users(); }); + probe("reports.activities", [&] { ws.reports().activities("all", "login", 1); }); + probe("groupssettings.get", [&] { ws.groups_settings().group("nobody@example.com"); }); + probe("vault.matters", [&] { ws.vault().matters(); }); +} + +TEST(workspace_live, scoped_service_account_token_without_and_with_a_subject) { + std::string key_path = Credentials::env("GOOGLE_APPLICATION_CREDENTIALS"); + if (!net() || key_path.empty()) { + std::cout << "SKIP workspace_live.scoped_service_account_token_without_and_with_a_subject " + "(set MOLO_LIVE_NET=1 and GOOGLE_APPLICATION_CREDENTIALS)\n"; + return; + } + ServiceAccountKey key = ServiceAccountKey::load_file(key_path); + std::vector scopes = Scopes::for_apis({"drive", "calendar", "tasks", "people"}, true); + + // No subject: the token acts as the service account itself (its own, empty, data). + auto plain = std::make_shared(key, scopes); + int token = probe("token without sub", [&] { plain->fetch_token(); }); + ASSERT_EQ(token, 200); + auto client = std::make_shared( + std::make_unique(), nullptr, plain); + Workspace ws(client); + probe("drive.about (own)", [&] { ws.drive().about(); }); + probe("drive.files.list (own)", [&] { ws.drive().files("", 5); }); + probe("calendar.calendarList (own)", [&] { ws.calendar().calendars(); }); + probe("tasks.tasklists (own)", [&] { ws.tasks().task_lists(); }); + + // The other APIs with their own read-only scopes (still no subject). + auto client_for = [&](const std::vector& apis) { + auto auth = std::make_shared(key, Scopes::for_apis(apis, true)); + return std::make_shared( + std::make_unique(), nullptr, auth); + }; + Workspace a(client_for({"gmail", "sheets", "docs", "slides", "forms"})); + probe("gmail.getProfile (sa, no sub)", [&] { a.gmail().profile(); }); + probe("sheets.get unknown (sa)", [&] { a.sheets().spreadsheet("1x"); }); + probe("docs.get unknown (sa)", [&] { a.docs().document("1x"); }); + probe("slides.get unknown (sa)", [&] { a.slides().presentation("1x"); }); + probe("forms.get unknown (sa)", [&] { a.forms().form("1x"); }); + Workspace b(client_for({"chat", "meet", "people", "keep", "classroom"})); + probe("chat.spaces (sa)", [&] { b.chat().spaces(); }); + probe("meet.conferenceRecords (sa)", [&] { b.meet().conference_records(); }); + probe("people.me (sa)", [&] { b.people().me(); }); + probe("keep.notes (sa)", [&] { b.keep().notes(); }); + probe("classroom.courses (sa)", [&] { b.classroom().courses(); }); + Workspace c(client_for({"youtube", "youtubereporting", "vault", "directory", "reports", "groupssettings"})); + probe("youtube.channels mine (sa)", [&] { c.youtube().my_channel(); }); + probe("youtubereporting.reportTypes (sa)", [&] { c.youtube_reporting().report_types(); }); + probe("vault.matters (sa)", [&] { c.vault().matters(); }); + probe("directory.users (sa)", [&] { c.directory().users(); }); + probe("reports.activities (sa)", [&] { c.reports().activities("all", "login", 1); }); + probe("groupssettings.get (sa)", [&] { c.groups_settings().group("nobody@example.com"); }); + + // With a subject but no domain-wide delegation grant: Google must refuse + // the exchange (unauthorized_client). This proves the `sub` claim is sent. + auto delegated = std::make_shared(key, scopes, Delegation{"nobody@example.com"}); + int refused = probe("token with sub (no DWD grant)", [&] { delegated->fetch_token(); }); + ASSERT_TRUE(refused == 401 || refused == 400 || refused == 403); +}