blib/script/gcloud-auth.pl untested

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