Google-Auth

 view release on metacpan or  search on metacpan

lib/Google/Auth/ServiceAccountCredentials.pm  view on Meta::CPAN

# Copyright 2026 Google LLC and contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

package Google::Auth::ServiceAccountCredentials;

use strict;
use warnings;

use Moo;
extends 'Google::Auth::Credentials';

use JSON::PP;
use MIME::Base64 qw(encode_base64url);
use LWP::UserAgent;
use Google::Auth;
use Google::Auth::Exceptions;
use Google::Auth::RetryHelper;
use Log::Any qw($log);

has json_key => (
  is       => 'ro',
  required => 0,
);

has private_key_id => (
  is       => 'ro',
  required => 0,
);

has private_key => (
  is       => 'ro',
  required => 0,
);

has client_email => (
  is       => 'ro',
  required => 0,
);

has client_id => (
  is       => 'ro',
  required => 0,
);

has auth_uri => (
  is       => 'ro',
  required => 0,
);

has token_uri => (
  is       => 'ro',
  required => 0,
  default  => sub {
    $ENV{GOOGLE_AUTH_TOKEN_URI} // 'https://oauth2.googleapis.com/token';
  },
);

has auth_provider_x509_cert_url => (
  is       => 'ro',
  required => 0,
);

has client_x509_cert_url => (
  is       => 'ro',
  required => 0,
);

has scope => (
  is       => 'ro',
  required => 0,
);

has ua => (
  is      => 'ro',
  default => sub {
    my $ua = LWP::UserAgent->new(timeout => 10);
    $ua->env_proxy;
    return $ua;
  },
);

around BUILDARGS => sub {
  my ($orig, $class, @args) = @_;
  my $args = $class->$orig(@args);

  if (my $json = $args->{json_key}) {
    $args->{project_id}     //= $json->{project_id};
    $args->{private_key_id} //= $json->{private_key_id};
    $args->{private_key}    //= $json->{private_key};
    $args->{client_email}   //= $json->{client_email};
    $args->{client_id}      //= $json->{client_id};
    $args->{auth_uri}       //= $json->{auth_uri};
    $args->{token_uri}      //= $json->{token_uri};
    $args->{auth_provider_x509_cert_url} //=
      $json->{auth_provider_x509_cert_url};
    $args->{client_x509_cert_url} //= $json->{client_x509_cert_url};
  }

  return $args;
};

sub _encode_base64url {
  my ($data) = @_;
  my $s = MIME::Base64::encode_base64url($data);
  $s =~ s/=+$//;
  return $s;
}

sub fetch_access_token {
  my ($self, %options) = @_;

  my $private_key  = $self->private_key;
  my $client_email = $self->client_email;
  my $token_uri    = $self->token_uri;

  $self->_validate_url($token_uri, 'token_uri');

  if (!defined $private_key || !defined $client_email) {
    $log->errorf(
'Missing private_key or client_email for ServiceAccountCredentials token exchange'
    );
    Google::Auth::Error->throw(
      'Missing private_key or client_email to sign and fetch token');
  }

  my $now    = time();
  my $header = {
    alg => 'RS256',
    typ => 'JWT',
  };
  $header->{kid} = $self->private_key_id if defined $self->private_key_id;

  my $scope = $self->scope;
  if (ref($scope) eq 'ARRAY') {
    $scope = join(' ', @$scope);
  }

  my $payload = {
    iss => $client_email,
    sub => $client_email,
    aud => $token_uri,
    exp => $now + 3600,
    iat => $now,
  };
  $payload->{scope} = $scope if defined $scope;

  my $header_b64  = _encode_base64url(encode_json($header));
  my $payload_b64 = _encode_base64url(encode_json($payload));
  my $message     = $header_b64 . '.' . $payload_b64;

  $log->tracef('Signing JWT assertion for service account %s (key ID: %s)...',
    $client_email, $self->private_key_id // 'N/A');
  my $signature_raw = Google::Auth::rsa_sign_sha256($private_key, $message);
  if (!defined $signature_raw) {
    $log->errorf('Failed to sign JWT assertion for service account %s',
      $client_email);
    Google::Auth::Error->throw(
      'Failed to sign JWT assertion using private key');
  }
  my $signature_b64 = _encode_base64url($signature_raw);
  my $assertion     = $message . '.' . $signature_b64;

  my $ua        = $self->ua;
  my $post_body = {
    grant_type => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
    assertion  => $assertion,
  };

  require URI;
  my $u = URI->new('http:');
  $u->query_form(%$post_body);
  my $encoded_body = $u->query;

  $log->infof('Exchanging signed JWT assertion for access token at %s...',
    $token_uri);
  my $response_body = Google::Auth::RetryHelper->execute_with_retry(
    sub {
      my $future = $self->transport->request(
        method  => 'POST',
        url     => $token_uri,
        headers => {'Content-Type' => 'application/x-www-form-urlencoded'},
        body    => $encoded_body,
      );

      my ($body, $headers);
      my $future_res = eval { ($body, $headers) = $future->get(); 1 };

      if (!$future_res) {
        my ($err_msg, $cat, $details) = $future->failure;
        my $code       = 0;
        my $error_body = '';
        if (ref($details) eq 'HASH') {
          $code       = $details->{code} // 0;
          $error_body = $details->{body} // '';
        } elsif (eval { $details->can('code') }) {
          $code       = $details->code // 0;
          $error_body = $details->decoded_content // $details->content // '';
        }
        $log->warnf('Service account token request failed at %s: status %s',
          $token_uri, $code);
        Google::Auth::Error->throw(
          'HTTP request failed with status ' . $code . ': ' . $error_body);
      }
      return $body;
    },
    %options
  );

  my $res_data = decode_json($response_body);
  my $token    = $res_data->{access_token};
  my $expires  = $res_data->{expires_in} // 3600;

  $self->access_token($token);
  $self->expires_at($now + $expires);

  return $token;
}

1;

__END__

=encoding UTF-8

=head1 NAME

Google::Auth::ServiceAccountCredentials - OAuth 2.0 JWT credentials for Google Cloud service account JSON keys

=head1 SYNOPSIS

    use Google::Auth::ServiceAccountCredentials;

    my $creds = Google::Auth::ServiceAccountCredentials->new(
        json_key_io => '/path/to/service-account.json',
        scope       => ['https://www.googleapis.com/auth/cloud-platform'],
    );
    my $token = $creds->get_token();

=head1 DESCRIPTION

Authenticates using a Google Cloud service account private key (RS256 JWT assertion signed via OpenSSL XS) and exchanges it for OAuth 2.0 access tokens.

=head1 METHODS AND ATTRIBUTES

=over 4

=item * B<json_key>

=item * B<private_key_id>

=item * B<private_key>

=item * B<client_email>

=item * B<client_id>

=item * B<auth_uri>

=item * B<token_uri>

=item * B<auth_provider_x509_cert_url>

=item * B<client_x509_cert_url>

=item * B<scope>

=item * B<ua>

=item * B<fetch_access_token>

=back

=head1 SEE ALSO

L<Google::Auth>, L<Google::Auth::Credentials>

=head1 AUTHOR

C.J. Collier E<lt>cjac@google.comE<gt>

=head1 LICENSE AND COPYRIGHT

Copyright (c) 2026 Google LLC and contributors.

Licensed under the Apache License, Version 2.0.

=cut



( run in 0.895 second using v1.01-cache-2.11-cpan-8379b9b8ec2 )