diff --git a/src/google/google.mk b/src/google/google.mk index aaddf8a..eb6330a 100644 --- a/src/google/google.mk +++ b/src/google/google.mk @@ -28,7 +28,13 @@ GOOGLE_OBJS := $(patsubst $(ROOT)/%.cpp,$(GOOGLE_OBJDIR)/%.o,$(GOOGLE_SRCS)) # layout corrupts the heap). -include $(GOOGLE_OBJS:.o=.d) -.PHONY: google google-test google-clean +.PHONY: google google-test google-clean google-token + +# Dev tool: prints a service-account access token (see tools/google_sa_token.cpp). +google-token: build/google/sa-token +build/google/sa-token: $(ROOT)/tools/google_sa_token.cpp $(GOOGLE_LIB) $(CLIENTS_LIB) $(OPERABILITY_LIB) + @mkdir -p $(dir $@) + $(CXX) $(GOOGLE_CXXFLAGS) -I$(ROOT)/src $< $(GOOGLE_LIB) $(CLIENTS_LIB) $(OPERABILITY_LIB) -lwolfssl -o $@ google: $(GOOGLE_LIB) diff --git a/tools/google_sa_token.cpp b/tools/google_sa_token.cpp new file mode 100644 index 0000000..5c61acf --- /dev/null +++ b/tools/google_sa_token.cpp @@ -0,0 +1,33 @@ +// Prints a fresh OAuth2 access token for the configured service account +// (GOOGLE_APPLICATION_CREDENTIALS via env, .env.json.local or .env.json), +// like `gcloud auth print-access-token`. Use only inside command +// substitution so the token never lands in a log: +// export GOOGLE_ACCESS_TOKEN=$(./build/google/sa-token) +#include + +#include "clients/client.h" +#include "clients/transports/http_transport.h" +#include "google/errors.h" +#include "google/service_account.h" + +int main() { + try { + auto auth = molo::google::ServiceAccountAuth::from_env(); + if (!auth) { + std::cerr << "sa-token: GOOGLE_APPLICATION_CREDENTIALS is not set\n"; + return 2; + } + molo::clients::ClientRequest req = molo::clients::ClientRequest::get("https://example.invalid/"); + auth->apply(req); + std::string header = req.headers().get_or("Authorization", ""); + if (header.rfind("Bearer ", 0) != 0) { + std::cerr << "sa-token: no bearer produced\n"; + return 1; + } + std::cout << header.substr(7) << "\n"; + return 0; + } catch (const molo::google::GoogleError& e) { + std::cerr << "sa-token: " << e.status() << ": " << e.message() << "\n"; + return 1; + } +}