Skip to content

Conversation

@AmitChotaliya
Copy link

Fixes #1165

This features allows using access token in the sdk without having any of the GCP related credentials.

Example Usage:

  • Generate the token using CLI gcloud auth print-access-token [email protected]
  • Generate the token using python.
from google.auth import compute_engine
from google.auth import default, credentials
from google.auth.transport.requests import Request
import google.auth
from google.cloud import compute_v1

def generate_access_token():    
    creds, project = google.auth.default()    
    
    creds.refresh(Request())
    return creds.token, creds.expiry
  • Copy this access token to a different/local machine or container having no other google credentials.
  • Set the required environment variable.
export GOOGLE_TEMPORARY_ACCESS_TOKEN=token copied from above
  • Try running the following python code to verify if the credentials are working.
def list_virtual_machines(project_id, creds):
    # Create a client for Compute Engine with the provided access token
    compute_client = compute_v1.NetworksClient(credentials=creds)

    # List VMs
    vm_list = compute_client.list(project=project_id)

    # Print VM names
    print("Virtual Machines:")
    for vm in vm_list:
        print(vm.name)
os.environ["GOOGLE_TEMPORARY_ACCESS_TOKEN"] = "access token copied from above"
    creds, project_id = google.auth.default()    
    list_virtual_machines("bamboo-weft-375813", creds=creds)

It should work fine till the token is valid.

@AmitChotaliya AmitChotaliya requested review from a team as code owners February 6, 2024 10:19
@google-cla
Copy link

google-cla bot commented Feb 6, 2024

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@conventional-commit-lint-gcf
Copy link

🤖 I detect that the PR title and the commit message differ and there's only one commit. To use the PR title for the commit history, you can use Github's automerge feature with squashing, or use automerge label. Good luck human!

-- conventional-commit-lint bot
https://conventionalcommits.org/

@AmitChotaliya AmitChotaliya changed the title Added Temporary token based authentication similar to cli --access-token-file feat: Added Temporary token based authentication similar to cli --access-token-file Feb 6, 2024
@chalmerlowe chalmerlowe requested a review from a team as a code owner January 7, 2026 14:04
@chalmerlowe
Copy link
Contributor

chalmerlowe commented Jan 8, 2026

I appreciate the time and effort invested into this PR. In looking it over, there are some issues that concern me. In light of the push to migrate this library to the google-cloud-python mono-repo we need to resolve all the PRs.

I recommend that we close this PR (once the migration is complete, it might make sense to revisit this. For that reason, I will leave my thoughts below on what it would take to enable us to merge this PR).

Logical Conflicts: The PR introduces a top-level import requests in google/oauth2/credentials.py. In setup.py, requests is listed under extras_require (specifically requests_extra_require), not install_requires. This means requests is an optional dependency. Making it a hard import in a core file like credentials.py will break the library for users who have not installed the requests extra. It will also modify the lightweight nature of the library. An option is to import the module lazily within the function or wrap it in a try/except block.

Error Handling: The implementation in google/auth/_default.py inside _get_temporary_access_token_environ catches ValueError but fails to catch network-related exceptions (e.g., requests.exceptions.RequestException, ConnectionError). If the environment variable is set but the network is flaky or the endpoint is unreachable, google.auth.default() will crash the application. This function should be robust and fail gracefully (returning None, None) if the token cannot be validated, rather than propagating a crash.

Transport Agnosticism: The from_temporary_access_token method hardcodes the use of requests.get. This bypasses any custom transport or proxy settings the user might expect the library to use.

Missing Tests: There are no unit tests added for the new checker in google/auth/_default.py. We need to add unittests to ensure that the chain of responsibility works correctly when the environment variable is set (with both valid/invalid inputs) and when it is unset.

Incomplete Logic: The PR assumes datetime.now() (local time) for expiry but compares it or uses it in contexts where UTC is expected (the library uses _helpers.utcnow() and/or _helpers.utcfromtimestamp() extensively). Mixing naive local time and naive UTC time can lead to incorrect expiration logic.

Type Hinting: The new method from_temporary_access_token has type hints, but they are incomplete and should be updated.

Docstrings: The docstring for from_temporary_access_token should explicitly mention that it performs a blocking network call.

Architecture: Validating credentials during the default() detection phase by making a synchronous network call is risky. While it ensures the token is valid, it adds latency to startup. If this validation is a strict requirement, it must be handled safely.

Critical Issues:

  • The test test_with_temporary_access_token in tests/oauth2/test_credentials.py is invalid. It relies on a real environment variable GOOGLE_TEMPORARY_ACCESS_TOKEN being present, which will likely not be true in CI.
  • It makes a real network call to googleapis.com. Unit tests must never depend on external network availability.
  • It does not use mock to simulate the response.

@chalmerlowe chalmerlowe closed this Jan 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support for CLOUDSDK_AUTH_ACCESS_TOKEN environment variable

2 participants