blib/script/gcloud-auth.pl untested

filter: Statementstmt 0.0% 0 / 339 Branchbran 0.0% 0 / 98 Conditioncond 0.0% 0 / 42 MC/DCmcdc 0.0% 0 / 24 Subroutinesub 0.0% 0 / 33 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 544 CC 49 SCAR 43.7
CC
49
Cov
0%
do_adc_login
210.0
run
132.0
do_login
132.0
CRAP 79.0
1 #!/usr/local/bin/perl
2 # Copyright 2026 Google LLC and contributors
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15  
16 use strict;
17 use warnings;
18 use Getopt::Long;
19 use Pod::Usage;
20 use File::Spec;
21 use JSON::MaybeXS qw(encode_json decode_json);
22 use Log::Any qw($log);
23 use IO::Socket::INET;
24 use IO::Select;
25 use URI;
26  
27 use Google::Auth;
28 use Google::Auth::ClientId;
29 use Google::Auth::UserAuthorizer;
30 use Google::Auth::Stores::FileTokenStore;
31 use Google::Auth::Exceptions;
32  
33 my $VERSION = '0.01';
34  
35 # Default Scopes for GCP
36 my @DEFAULT_SCOPES = (
37 'openid',
38 'https://www.googleapis.com/auth/userinfo.email',
39 'https://www.googleapis.com/auth/cloud-platform',
40 'https://www.googleapis.com/auth/appengine.admin',
41 'https://www.googleapis.com/auth/sqlservice.login',
42 'https://www.googleapis.com/auth/compute',
43 'https://www.googleapis.com/auth/accounts.reauth'
44 );
45  
46 unless (caller) {
47 run(@ARGV);
48 }
49  
50 sub run {
51 my @args = @_;
52  
53 my $help = 0;
54 my $man = 0;
55 my $verbose = 0;
56 my $client_id_file;
57 my $store_dir =
58 File::Spec->catdir($ENV{HOME} // '.', '.google-auth-perl', 'tokens');
59 my $port = 0; # Default auto-assign
60 my $timeout = 300; # Default 5 minutes for human interaction
61 my $no_browser = 0;
62  
63 local @ARGV = @args;
64  
65 GetOptions(
66 'help|?' => \$help,
67 'man' => \$man,
68 'verbose|v' => \$verbose,
69 'client-id-file=s' => \$client_id_file,
70 'store-dir=s' => \$store_dir,
71 'port=i' => \$port,
72 'timeout=i' => \$timeout,
73 'no-browser' => \$no_browser,
74 ) or pod2usage(2);
75  
76 if ($verbose) {
77 require Log::Any::Adapter;
78 Log::Any::Adapter->set('Stderr', min_level => 'trace');
79 }
80  
81 pod2usage(1) if $help;
82 pod2usage(-verbose => 2) if $man;
83  
84 my $command = shift @ARGV;
85  
86 unless ($command) {
87 pod2usage(1);
88 }
89  
90 if ($command eq 'login') {
91 do_login(
92 client_id_file => $client_id_file,
93 store_dir => $store_dir,
94 port => $port,
95 timeout => $timeout,
96 no_browser => $no_browser,
97 );
98 } elsif ($command eq 'application-default') {
99 my $subcommand = shift @ARGV;
100 unless ($subcommand) {
101 die "Error: application-default requires a subcommand (e.g., login)\n";
102 }
103 if ($subcommand eq 'login') {
104 do_adc_login(
105 client_id_file => $client_id_file,
106 store_dir => $store_dir,
107 port => $port,
108 timeout => $timeout,
109 no_browser => $no_browser,
110 );
111 } else {
112 die "Unsupported application-default subcommand: $subcommand\n";
113 }
114 } elsif ($command eq 'print-access-token') {
115 do_print_access_token(store_dir => $store_dir,);
116 } elsif ($command eq 'revoke') {
117 do_revoke(store_dir => $store_dir,);
118 } else {
119 die "Unsupported command: $command\n";
120 }
121 }
122  
123 sub _start_listener {
124 my ($port) = @_;
125 my $listener = IO::Socket::INET->new(
126 LocalHost => '127.0.0.1',
127 LocalPort => $port || 0, # Auto-assign if 0
128 Proto => 'tcp',
129 Listen => 1,
130 ReuseAddr => 1,
131 );
132 unless ($listener) {
133 $log->errorf('Failed to start loopback listener: %s', $!);
134 die "Error: Failed to start loopback listener: $!\n";
135 }
136 return $listener;
137 }
138  
139 sub _wait_for_code {
140 my ($listener, $timeout) = @_;
141 $timeout //= 5; # Fallback default
142  
143 my $select = IO::Select->new($listener);
144 my $client;
145  
146 if ($select->can_read($timeout)) {
147 $client = $listener->accept();
148 } else {
149 $log->error('Timeout waiting for authorization code');
150 close $listener;
151 die "Error: Timeout waiting for authorization code.\n";
152 }
153  
154 unless ($client) {
155 $log->errorf('Failed to accept connection: %s', $!);
156 close $listener;
157 die "Error: Failed to accept connection: $!\n";
158 }
159  
160 my $request = '';
161 while (<$client>) {
162 $request .= $_;
163 last if $_ =~ /^\r\n$/; # End of headers
164 }
165  
166 $log->tracef('Received request: %s', $request);
167  
168 my $code;
169 if ($request =~ /^GET\s+([^\s]+)/) {
170 my $uri = URI->new("http://127.0.0.1$1");
171 my %params = $uri->query_form;
172 $code = $params{code};
173 }
174  
175 if ($code) {
176 $log->info('Authorization code received successfully');
177 print $client
178 "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: text/plain\r\n\r\nSuccess! You can close this window.\r\n";
179 close $client;
180 close $listener;
181 return $code;
182 } else {
183 $log->error('Failed to get authorization code from callback');
184 print $client
185 "HTTP/1.1 400 Bad Request\r\nConnection: close\r\nContent-Type: text/plain\r\n\r\nError: No code received.\r\n";
186 close $client;
187 close $listener;
188 die "Error: Failed to get authorization code.\n";
189 }
190 }
191  
192 sub do_login {
193 my (%options) = @_;
194 $log->info('Command: login initiated');
195 $log->trace('Entering do_login');
196  
197 my $client_id_file = $options{client_id_file};
198 my $store_dir = $options{store_dir};
199  
200 my $client_id;
201 if ($client_id_file && -f $client_id_file) {
202 $client_id = Google::Auth::ClientId->from_file($client_id_file);
203 } else {
204 $log->info('Using default Gcloud Client ID');
205 $client_id = Google::Auth::ClientId->new(
206 id => '32555940559.apps.googleusercontent.com',
207 secret => 'ZmssLNjJy2998hD4CTg2ejr2',
208 );
209 }
210 my $token_store =
211 Google::Auth::Stores::FileTokenStore->new(store_dir => $store_dir);
212  
213 my $listener;
214 my $redirect_uri;
215  
216 my $use_oob = $options{no_browser};
217 unless ($use_oob || $options{port}) {
218 if ($^O eq 'linux' && !$ENV{DISPLAY} && !$ENV{WAYLAND_DISPLAY}) {
219 $log->info(
220 'No DISPLAY detected on Linux, defaulting to out-of-band flow');
221 $use_oob = 1;
222 }
223 }
224  
225 my $code_verifier;
226 if ($use_oob) {
227 $redirect_uri = 'https://sdk.cloud.google.com/authcode.html';
228 my @chars = ('A' .. 'Z', 'a' .. 'z', '0' .. '9', '-', '.', '_', '~');
229 $code_verifier = join('', map { $chars[rand @chars] } 1 .. 64);
230 } else {
231 $listener = _start_listener($options{port});
232 my $port = $listener->sockport();
233 $log->debugf('Loopback listener started on port %d', $port);
234 $redirect_uri = "http://127.0.0.1:$port/";
235 }
236  
237 my %auth_args = (
238 client_id => $client_id,
239 scope => \@DEFAULT_SCOPES,
240 token_store => $token_store,
241 callback_uri => $redirect_uri,
242 );
243 $auth_args{code_verifier} = $code_verifier if $code_verifier;
244  
245 my $auth = Google::Auth::UserAuthorizer->new(%auth_args);
246  
247 my %auth_options;
248 $auth_options{additional_parameters} = {token_usage => 'remote'}
249 if $use_oob;
250  
251 my @state_chars = ('A' .. 'Z', 'a' .. 'z', '0' .. '9');
252 my $state = join('', map { $state_chars[rand @state_chars] } 1 .. 32);
253 $auth_options{state} = $state;
254  
255 my $auth_url = $auth->get_authorization_url(%auth_options);
256  
257 print "\nGo to the following link in your browser:\n\n $auth_url\n\n";
258  
259 my $code;
260 if ($use_oob) {
261 print "Enter authorization code: ";
262 $code = <STDIN>;
263 chomp $code if $code;
264 } else {
265 $log->info('Waiting for authorization code...');
266 $code = _wait_for_code($listener, $options{timeout});
267 }
268  
269 if ($code) {
270 $log->info('Exchanging code for credentials...');
271  
272 my $user_id = 'default'; # TODO: use email if available
273  
274 eval {
275 $auth->get_and_store_credentials_from_code(
276 user_id => $user_id,
277 code => $code,
278 base_url => $redirect_uri,
279 );
280 };
281 if ($@) {
282 $log->errorf('Failed to exchange code: %s', $@);
283 die "Error: Failed to exchange code: $@\n";
284 }
285  
286 $log->info('Login successful. Credentials saved.');
287 print "Login successful.\n";
288 }
289  
290 $log->trace('Leaving do_login');
291 }
292  
293 sub do_adc_login {
294 my (%options) = @_;
295 $log->info('Command: application-default login initiated');
296 $log->trace('Entering do_adc_login');
297  
298 my $client_id_file = $options{client_id_file};
299 my $store_dir = $options{store_dir};
300  
301 my $client_id;
302 if ($client_id_file && -f $client_id_file) {
303 $client_id = Google::Auth::ClientId->from_file($client_id_file);
304 } else {
305 $log->info('Using default ADC Client ID');
306 $client_id = Google::Auth::ClientId->new(
307 id =>
308 '764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com',
309 secret => 'd-FL95Q19q7MQmFpd7hHD0Ty',
310 );
311 }
312 my $token_store =
313 Google::Auth::Stores::FileTokenStore->new(store_dir => $store_dir);
314  
315 my $listener;
316 my $redirect_uri;
317  
318 my $use_oob = $options{no_browser};
319 unless ($use_oob || $options{port}) {
320 if ($^O eq 'linux' && !$ENV{DISPLAY} && !$ENV{WAYLAND_DISPLAY}) {
321 $log->info(
322 'No DISPLAY detected on Linux, defaulting to out-of-band flow');
323 $use_oob = 1;
324 }
325 }
326  
327 my $code_verifier;
328 if ($use_oob) {
329 $redirect_uri =
330 'https://sdk.cloud.google.com/applicationdefaultauthcode.html';
331 my @chars = ('A' .. 'Z', 'a' .. 'z', '0' .. '9', '-', '.', '_', '~');
332 $code_verifier = join('', map { $chars[rand @chars] } 1 .. 64);
333 } else {
334 $listener = _start_listener($options{port});
335 my $port = $listener->sockport();
336 $log->debugf('Loopback listener started on port %d', $port);
337 $redirect_uri = "http://127.0.0.1:$port/";
338 }
339  
340 my %auth_args = (
341 client_id => $client_id,
342 scope => \@DEFAULT_SCOPES,
343 token_store => $token_store,
344 callback_uri => $redirect_uri,
345 );
346 $auth_args{code_verifier} = $code_verifier if $code_verifier;
347  
348 my $auth = Google::Auth::UserAuthorizer->new(%auth_args);
349  
350 my %auth_options;
351 $auth_options{additional_parameters} = {token_usage => 'remote'}
352 if $use_oob;
353  
354 my @state_chars = ('A' .. 'Z', 'a' .. 'z', '0' .. '9');
355 my $state = join('', map { $state_chars[rand @state_chars] } 1 .. 32);
356 $auth_options{state} = $state;
357  
358 my $auth_url = $auth->get_authorization_url(%auth_options);
359  
360 print "\nGo to the following link in your browser:\n\n $auth_url\n\n";
361  
362 my $code;
363 if ($use_oob) {
364 print "Enter authorization code: ";
365 $code = <STDIN>;
366 chomp $code if $code;
367 } else {
368 $log->info('Waiting for authorization code...');
369 $code = _wait_for_code($listener, $options{timeout});
370 }
371  
372 if ($code) {
373 $log->info('Exchanging code for credentials...');
374  
375 my $creds;
376 eval {
377 $creds = $auth->get_credentials_from_code(
378 code => $code,
379 base_url => $redirect_uri,
380 );
381 };
382 if ($@) {
383 $log->errorf('Failed to exchange code: %s', $@);
384 die "Error: Failed to exchange code: $@\n";
385 }
386  
387 $log->info('Code exchanged successfully.');
388  
389 my $adc_path = _get_adc_path();
390 unless ($adc_path) {
391 $log->error('Failed to determine ADC path');
392 die "Error: Failed to determine ADC path (HOME or APPDATA not set?)\n";
393 }
394  
395 $log->debugf('Target ADC path: %s', $adc_path);
396  
397 my $adc_data = {
398 type => 'authorized_user',
399 client_id => $creds->client_id,
400 client_secret => $creds->client_secret,
401 refresh_token => $creds->refresh_token,
402 };
403  
404 my ($volume, $directories, $file) = File::Spec->splitpath($adc_path);
405 my $adc_dir = File::Spec->catpath($volume, $directories, '');
406 if (!-d $adc_dir) {
407 require File::Path;
408 eval { File::Path::make_path($adc_dir) };
409 if ($@) {
410 $log->errorf('Failed to create ADC directory %s: %s', $adc_dir, $@);
411 die "Error: Failed to create ADC directory: $@\n";
412 }
413 }
414  
415 require Fcntl;
416 sysopen(my $fh, $adc_path,
417 Fcntl::O_CREAT() | Fcntl::O_WRONLY() | Fcntl::O_TRUNC(), 0600)
418 or die "Error: Failed to write to $adc_path: $!\n";
419  
420 print $fh encode_json($adc_data);
421 close($fh) or die "Error: Failed to close $adc_path: $!\n";
422  
423 $log->info('ADC Login successful. Credentials saved to ' . $adc_path);
424 print "Application Default Credentials saved to $adc_path\n";
425 }
426  
427 $log->trace('Leaving do_adc_login');
428 }
429  
430 sub _get_adc_path {
431 require Google::Auth::EnvironmentVars;
432 my $env = Google::Auth::EnvironmentVars->new();
433  
434 my $home = $ENV{HOME};
435 if ($^O eq 'MSWin32') {
436 $home = $ENV{APPDATA};
437 }
438  
439 return unless $home;
440  
441 if ($^O eq 'MSWin32') {
442 return File::Spec->catfile($home, 'gcloud',
443 'application_default_credentials.json');
444 } else {
445 my $config_dir =
446 $env->CLOUD_SDK_CONFIG_DIR || File::Spec->catdir($home, '.config');
447 return File::Spec->catfile($config_dir, 'gcloud',
448 'application_default_credentials.json');
449 }
450 }
451  
452 sub do_print_access_token {
453 my (%options) = @_;
454 $log->info('Command: print-access-token initiated');
455 $log->trace('Entering do_print_access_token');
456  
457 my $store_dir = $options{store_dir};
458 my $user_id = 'default'; # TODO: allow specifying user/account
459  
460 require Google::Auth::Stores::FileTokenStore;
461 my $token_store =
462 Google::Auth::Stores::FileTokenStore->new(store_dir => $store_dir);
463  
464 my $json = $token_store->load($user_id);
465 unless ($json) {
466 $log->error("No credentials found for user $user_id");
467 die "Error: No credentials found. Please run 'login' first.\n";
468 }
469  
470 require JSON::MaybeXS;
471 my $creds_data = JSON::MaybeXS::decode_json($json);
472  
473 require Google::Auth::UserRefreshCredentials;
474 my $creds = Google::Auth::UserRefreshCredentials->new(
475 client_id => $creds_data->{client_id},
476 client_secret => $creds_data->{client_secret},
477 refresh_token => $creds_data->{refresh_token},
478 );
479  
480 my $token;
481 eval { $token = $creds->get_token(); };
482 if ($@) {
483 $log->errorf('Failed to fetch access token: %s', $@);
484 die "Error: Failed to fetch access token: $@\n";
485 }
486  
487 if ($token) {
488 print "$token\n";
489 $log->info('Access token printed successfully');
490 } else {
491 $log->error('Failed to obtain access token (empty)');
492 die "Error: Failed to obtain access token.\n";
493 }
494  
495 $log->trace('Leaving do_print_access_token');
496 }
497  
498 sub do_revoke {
499 my (%options) = @_;
500 $log->info('Command: revoke initiated');
501 $log->trace('Entering do_revoke');
502  
503 my $store_dir = $options{store_dir};
504 my $user_id = 'default'; # TODO: allow specifying user/account
505  
506 require Google::Auth::Stores::FileTokenStore;
507 my $token_store =
508 Google::Auth::Stores::FileTokenStore->new(store_dir => $store_dir);
509  
510 my $json = $token_store->load($user_id);
511 unless ($json) {
512 $log->warn("No credentials found for user $user_id to revoke");
513 print "No credentials found to revoke.\n";
514 return;
515 }
516  
517 require JSON::MaybeXS;
518 my $creds_data = JSON::MaybeXS::decode_json($json);
519  
520 my $refresh_token = $creds_data->{refresh_token};
521  
522 if ($refresh_token) {
523 $log->info('Revoking refresh token...');
524  
525 # Google revocation endpoint
526 my $revoke_uri = $ENV{GOOGLE_AUTH_REVOKE_URI}
527 // 'https://oauth2.googleapis.com/revoke';
528  
529 # We need an LWP::UserAgent or similar.
530 # Let's see if we can use Google::Auth::UserRefreshCredentials->ua or just LWP directly.
531 # UserRefreshCredentials doesn't expose UA easily without instance.
532 # Let's check Google::Auth::RetryHelper or invent one.
533  
534 require LWP::UserAgent;
535 my $ua = LWP::UserAgent->new();
536  
537 my $res = $ua->post($revoke_uri, {token => $refresh_token});
538  
539 if ($res->is_success) {
540 $log->info('Token revocation request successful');
541 } else {
542 $log->warnf('Token revocation request failed: %s', $res->status_line);
543  
544 # We proceed to delete locally anyway? Yes, common practice.
545 }
546 }
547  
548 $log->info('Deleting local credentials...');
549 $token_store->delete($user_id);
550  
551 print "Credentials revoked.\n";
552  
553 $log->trace('Leaving do_revoke');
554 }
555  
556 __END__