You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opendal.apache.org by xu...@apache.org on 2026/09/07 05:42:36 UTC
(opendal-reqsign) branch xuanwo/gcp-live-credential-tests created (now b7b6157)
This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a change to branch xuanwo/gcp-live-credential-tests
in repository https://gitbox.apache.org/repos/asf/opendal-reqsign.git
at b7b6157 test(google): validate credentials with live services
This branch includes the following new commits:
new b7b6157 test(google): validate credentials with live services
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(opendal-reqsign) 01/01: test(google): validate credentials with live services
Posted by xu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch xuanwo/gcp-live-credential-tests
in repository https://gitbox.apache.org/repos/asf/opendal-reqsign.git
commit b7b61579fb4bddf1f7d91bed09c6e869adb8855d
Author: Xuanwo <gi...@xuanwo.io>
AuthorDate: Mon Sep 7 13:42:23 2026 +0800
test(google): validate credentials with live services
---
.github/workflows/google.yml | 560 +++++++++++----------
.../src/credential_access_boundary/server_side.rs | 28 +-
.../src/provide_credential/authorized_user.rs | 27 +-
services/google/src/provide_credential/default.rs | 2 +-
.../impersonated_service_account.rs | 28 +-
.../google/src/provide_credential/vm_metadata.rs | 10 +-
.../google/src/service_account_impersonation.rs | 56 ++-
services/google/tests/README.md | 244 +++++----
.../google/tests/credential_access_boundary.rs | 21 +-
.../tests/credential_providers/authorized_user.rs | 35 +-
.../google/tests/credential_providers/default.rs | 20 +-
services/google/tests/credential_providers/env.rs | 58 +++
.../tests/credential_providers/external_account.rs | 104 ++--
services/google/tests/credential_providers/file.rs | 15 +-
.../impersonated_service_account.rs | 73 +--
services/google/tests/credential_providers/mod.rs | 51 +-
.../service_account_impersonation.rs | 101 ++++
.../tests/credential_providers/static_provider.rs | 29 +-
.../google/tests/credential_providers/token.rs | 17 +-
.../tests/credential_providers/vm_metadata.rs | 51 +-
services/google/tests/fixtures.rs | 83 +++
.../fixtures/authorized_user_token_response.json | 7 +
.../iam_generate_access_token_response.json | 4 +
.../fixtures/server_side_cab_sts_response.json | 5 +
.../tests/fixtures/vm_metadata_token_response.json | 5 +
services/google/tests/mocks/sts_mock_server.py | 140 ------
.../google/tests/mocks/vm_metadata_mock_server.py | 114 -----
services/google/tests/service_account_token.rs | 21 +-
services/google/tests/signing/signed_url.rs | 24 +-
services/google/tests/signing/standard.rs | 15 +-
30 files changed, 970 insertions(+), 978 deletions(-)
diff --git a/.github/workflows/google.yml b/.github/workflows/google.yml
index a075b13..c4df5e9 100644
--- a/.github/workflows/google.yml
+++ b/.github/workflows/google.yml
@@ -30,184 +30,249 @@ concurrency:
cancel-in-progress: true
env:
- RUST_LOG: DEBUG
- RUST_BACKTRACE: full
+ RUST_BACKTRACE: "1"
+ REQSIGN_GOOGLE_CLOUD_STORAGE_SCOPE: https://www.googleapis.com/auth/devstorage.read_only
+ REQSIGN_GOOGLE_CLOUD_STORAGE_URL: https://storage.googleapis.com/storage/v1/b/reqsign
+ REQSIGN_GOOGLE_CLOUD_STORAGE_PROBE_URL: https://storage.googleapis.com/storage/v1/b/reqsign/o/live%2Fcredential-ok?alt=media
+ REQSIGN_GOOGLE_CLOUD_STORAGE_SIGNED_PROBE_URL: https://storage.googleapis.com/reqsign/live/credential-ok
+ REQSIGN_GOOGLE_CAB_BUCKET: reqsign
+ REQSIGN_GOOGLE_CAB_OBJECT_PREFIX: live/cab/allowed/
+ REQSIGN_GOOGLE_IMPERSONATED_SERVICE_ACCOUNT: reqsign-impersonated@reqsign.iam.gserviceaccount.com
permissions: {}
jobs:
- # Unit tests - always run, no secrets needed
unit_test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- - name: Run unit tests
- working-directory: ./services/google
+ - name: Run deterministic tests and redacted real-response replays
run: |
- echo "::group::Running unit tests"
- cargo test --lib --all-features --no-fail-fast
- cargo test --doc --all-features --no-fail-fast
- echo "::endgroup::"
+ cargo test -p reqsign-google --lib --tests --all-features --no-fail-fast
+ cargo test -p reqsign-google --doc --all-features --no-fail-fast
- # Check if we can run integration tests
check_secrets:
runs-on: ubuntu-latest
outputs:
- has_secrets: ${{ steps.check.outputs.has_secrets }}
+ trusted: ${{ steps.check.outputs.trusted }}
steps:
- - name: Check if secrets are available
+ - name: Check whether live credentials are available
id: check
+ env:
+ EVENT_NAME: ${{ github.event_name }}
+ HAS_CONNECT_HOST: ${{ secrets.OP_CONNECT_HOST != '' }}
+ HAS_CONNECT_TOKEN: ${{ secrets.OP_CONNECT_TOKEN != '' }}
run: |
- if [[ "${{ github.event_name }}" == "push" || ( "${{ github.event_name }}" == "pull_request" && "${{ github.event.pull_request.head.repo.fork }}" == "false" && "${{ github.actor }}" != "dependabot[bot]" ) ]]; then
- echo "has_secrets=true" >> $GITHUB_OUTPUT
- echo "::notice::Integration tests will be executed (base repository and non-dependabot PR)"
+ if [[ "$EVENT_NAME" == "push" || ( "$HAS_CONNECT_HOST" == "true" && "$HAS_CONNECT_TOKEN" == "true" ) ]]; then
+ echo "trusted=true" >> "$GITHUB_OUTPUT"
else
- echo "has_secrets=false" >> $GITHUB_OUTPUT
- echo "::warning::Integration tests will be skipped (forked repository, dependabot PR, or no secrets available)"
+ echo "trusted=false" >> "$GITHUB_OUTPUT"
fi
- # Signing tests - test signature algorithm with static credentials
- signing_test:
+ test_service_account_providers:
+ name: Service account providers live test
needs: check_secrets
- if: needs.check_secrets.outputs.has_secrets == 'true'
+ if: needs.check_secrets.outputs.trusted == 'true'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- - name: Setup 1Password Connect
+ - name: Configure 1Password Connect
uses: 1Password/load-secrets-action/configure@eb2efd0703da22a93c467f2d1ffbb6826c11e19c # v4.1.1
with:
connect-host: ${{ secrets.OP_CONNECT_HOST }}
connect-token: ${{ secrets.OP_CONNECT_TOKEN }}
- - name: Load secrets
+ - name: Load Google service-account credential
+ id: load_secrets
uses: 1Password/load-secrets-action@eb2efd0703da22a93c467f2d1ffbb6826c11e19c # v4.1.1
- with:
- export-env: true
env:
- REQSIGN_GOOGLE_CREDENTIAL: op://reqsign/google/credential_base64
- REQSIGN_GOOGLE_CLOUD_STORAGE_SCOPE: op://reqsign/google/storage_scope
- REQSIGN_GOOGLE_CLOUD_STORAGE_URL: op://reqsign/google/storage_url
- - name: Test signing
- working-directory: ./services/google
+ GOOGLE_CREDENTIAL_BASE64: op://reqsign/google/credential_base64
+ - name: Set up service-account credential sources
env:
- # Gate flags must live on the test step. 1Password export-env only
- # forwards op:// secrets, so literals set on Load secrets are dropped.
- REQSIGN_GOOGLE_TEST: on
+ GOOGLE_CREDENTIAL_BASE64: ${{ steps.load_secrets.outputs.GOOGLE_CREDENTIAL_BASE64 }}
run: |
- test "${REQSIGN_GOOGLE_TEST}" = "on"
- echo "::group::Running signing tests"
- cargo test signing:: --no-fail-fast -- --no-capture
- echo "::endgroup::"
+ credential_path="$RUNNER_TEMP/google-service-account.json"
+ printf '%s' "$GOOGLE_CREDENTIAL_BASE64" | base64 --decode > "$credential_path"
+ test -s "$credential_path"
+ chmod 600 "$credential_path"
+ mkdir -p "$HOME/.config/gcloud"
+ cp "$credential_path" "$HOME/.config/gcloud/application_default_credentials.json"
+ echo "GOOGLE_APPLICATION_CREDENTIALS=$credential_path" >> "$GITHUB_ENV"
+ echo "REQSIGN_GOOGLE_CREDENTIAL=$GOOGLE_CREDENTIAL_BASE64" >> "$GITHUB_ENV"
+ - name: Test static, file, environment, well-known, and default providers
+ env:
+ REQSIGN_GOOGLE_TEST_STATIC: "on"
+ REQSIGN_GOOGLE_TEST_FILE: "on"
+ REQSIGN_GOOGLE_TEST_ENV: "on"
+ REQSIGN_GOOGLE_TEST_WELL_KNOWN: "on"
+ REQSIGN_GOOGLE_TEST_DEFAULT: "on"
+ run: |
+ cargo test -p reqsign-google --test main credential_providers::static_provider:: -- --no-capture
+ cargo test -p reqsign-google --test main credential_providers::file::test_file_credential_provider_live -- --exact --no-capture
+ cargo test -p reqsign-google --test main credential_providers::env:: -- --no-capture
+ cargo test -p reqsign-google --test main credential_providers::default::test_default_credential_provider -- --exact --no-capture
+ - name: Test ServiceAccountTokenCredentialProvider and server-side CAB
+ env:
+ REQSIGN_GOOGLE_TEST_SERVICE_ACCOUNT_TOKEN: "on"
+ run: |
+ cargo test -p reqsign-google --test service_account_token -- --no-capture
+ - name: Test standard and service-account signed URL signing
+ env:
+ REQSIGN_GOOGLE_TEST: "on"
+ run: |
+ cargo test -p reqsign-google --test main signing:: -- --no-capture
- # DefaultCredentialProvider test
- test_default_provider:
+ test_authorized_user_provider:
+ name: Authorized user provider live test
needs: check_secrets
- if: needs.check_secrets.outputs.has_secrets == 'true'
+ if: needs.check_secrets.outputs.trusted == 'true'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- - name: Setup 1Password Connect
+ - name: Configure 1Password Connect
uses: 1Password/load-secrets-action/configure@eb2efd0703da22a93c467f2d1ffbb6826c11e19c # v4.1.1
with:
connect-host: ${{ secrets.OP_CONNECT_HOST }}
connect-token: ${{ secrets.OP_CONNECT_TOKEN }}
- - name: Load secrets
+ - name: Load authorized-user credential
id: load_secrets
uses: 1Password/load-secrets-action@eb2efd0703da22a93c467f2d1ffbb6826c11e19c # v4.1.1
env:
- GOOGLE_APPLICATION_CREDENTIALS_BASE64: op://reqsign/google/credential_base64
- - name: Setup test credentials file
- run: |
- echo "${STEPS_LOAD_SECRETS_OUTPUTS_GOOGLE_APPLICATION_CREDENTIALS_BASE64}" | base64 -d > /tmp/gcp_credentials.json
- echo "GOOGLE_APPLICATION_CREDENTIALS=/tmp/gcp_credentials.json" >> $GITHUB_ENV
+ GOOGLE_AUTHORIZED_USER_BASE64: op://reqsign/google/authorized_user_base64
+ - name: Set up authorized-user credential
env:
- STEPS_LOAD_SECRETS_OUTPUTS_GOOGLE_APPLICATION_CREDENTIALS_BASE64: ${{ steps.load_secrets.outputs.GOOGLE_APPLICATION_CREDENTIALS_BASE64 }}
- - name: Test DefaultCredentialProvider
- working-directory: ./services/google
+ GOOGLE_AUTHORIZED_USER_BASE64: ${{ steps.load_secrets.outputs.GOOGLE_AUTHORIZED_USER_BASE64 }}
+ run: |
+ credential_path="$RUNNER_TEMP/google-authorized-user.json"
+ printf '%s' "$GOOGLE_AUTHORIZED_USER_BASE64" | base64 --decode > "$credential_path"
+ test -s "$credential_path"
+ chmod 600 "$credential_path"
+ echo "REQSIGN_GOOGLE_AUTHORIZED_USER_CREDENTIALS=$credential_path" >> "$GITHUB_ENV"
+ - name: Test AuthorizedUserCredentialProvider against Cloud Storage
env:
- REQSIGN_GOOGLE_TEST_DEFAULT: on
+ REQSIGN_GOOGLE_TEST_AUTHORIZED_USER: "on"
run: |
- test "${REQSIGN_GOOGLE_TEST_DEFAULT}" = "on"
- echo "::group::Testing DefaultCredentialProvider"
- cargo test test_default_credential_provider --no-fail-fast -- --no-capture
- echo "::endgroup::"
+ cargo test -p reqsign-google --test main credential_providers::authorized_user::test_authorized_user_credential_provider -- --exact --no-capture
- # StaticCredentialProvider test
- test_static_provider:
+ test_workload_identity_and_token_providers:
+ name: Workload identity, token, CAB, and IAM Credentials live test
needs: check_secrets
- if: needs.check_secrets.outputs.has_secrets == 'true'
+ if: needs.check_secrets.outputs.trusted == 'true'
runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ id-token: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- - name: Setup 1Password Connect
+ - name: Configure 1Password Connect
uses: 1Password/load-secrets-action/configure@eb2efd0703da22a93c467f2d1ffbb6826c11e19c # v4.1.1
with:
connect-host: ${{ secrets.OP_CONNECT_HOST }}
connect-token: ${{ secrets.OP_CONNECT_TOKEN }}
- - name: Load secrets
+ - name: Load workload identity configuration
uses: 1Password/load-secrets-action@eb2efd0703da22a93c467f2d1ffbb6826c11e19c # v4.1.1
with:
export-env: true
env:
- REQSIGN_GOOGLE_CREDENTIAL: op://reqsign/google/credential_base64
- REQSIGN_GOOGLE_CLOUD_STORAGE_SCOPE: op://reqsign/google/storage_scope
- - name: Test StaticCredentialProvider
- working-directory: ./services/google
+ GOOGLE_WORKLOAD_IDENTITY_PROVIDER: op://reqsign/google/workload_identity_provider
+ GOOGLE_SERVICE_ACCOUNT: op://reqsign/google/service_account_email
+ - name: Load caller-bound GitHub OIDC subject token
+ run: |
+ audience="//iam.googleapis.com/${GOOGLE_WORKLOAD_IDENTITY_PROVIDER}"
+ encoded_audience=$(jq --null-input --raw-output --arg value "$audience" '$value | @uri')
+ subject_token=$(curl --fail-with-body --silent --show-error --header "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" "${ACTIONS_ID_TOKEN_REQUEST_URL}&audience=${encoded_audience}" |
+ jq --exit-status --raw-output '.value')
+ test -n "$subject_token"
+ echo "::add-mask::$subject_token"
+ echo "REQSIGN_GOOGLE_SUBJECT_TOKEN=$subject_token" >> "$GITHUB_ENV"
+ echo "REQSIGN_GOOGLE_WORKLOAD_IDENTITY_AUDIENCE=$audience" >> "$GITHUB_ENV"
+ - name: Authenticate to Google Cloud through workload identity
+ id: auth
+ uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3.0.0
+ with:
+ create_credentials_file: true
+ token_format: access_token
+ access_token_lifetime: 1800s
+ access_token_scopes: https://www.googleapis.com/auth/cloud-platform
+ workload_identity_provider: ${{ env.GOOGLE_WORKLOAD_IDENTITY_PROVIDER }}
+ service_account: ${{ env.GOOGLE_SERVICE_ACCOUNT }}
+ - name: Test Workload Identity and caller-provided subject tokens
+ env:
+ REQSIGN_GOOGLE_TEST_WORKLOAD_IDENTITY: "on"
+ REQSIGN_GOOGLE_ACCESS_TOKEN: ${{ steps.auth.outputs.access_token }}
+ run: |
+ cargo test -p reqsign-google --test main credential_providers::external_account:: -- --no-capture
+ - name: Test TokenCredentialProvider
+ env:
+ REQSIGN_GOOGLE_TEST_TOKEN: "on"
+ REQSIGN_GOOGLE_ACCESS_TOKEN: ${{ steps.auth.outputs.access_token }}
+ run: |
+ cargo test -p reqsign-google --test main credential_providers::token::test_token_credential_provider_live -- --exact --no-capture
+ - name: Test typed service-account impersonation and IAM signBlob
env:
- REQSIGN_GOOGLE_TEST_STATIC: on
+ REQSIGN_GOOGLE_TEST_SERVICE_ACCOUNT_IMPERSONATION: "on"
+ REQSIGN_GOOGLE_ACCESS_TOKEN: ${{ steps.auth.outputs.access_token }}
run: |
- test "${REQSIGN_GOOGLE_TEST_STATIC}" = "on"
- echo "::group::Testing StaticCredentialProvider"
- cargo test test_static_credential_provider --no-fail-fast -- --no-capture
- echo "::endgroup::"
+ cargo test -p reqsign-google --test main credential_providers::service_account_impersonation:: -- --no-capture
+ - name: Test client-side Credential Access Boundary
+ env:
+ REQSIGN_GOOGLE_TEST_CAB: "on"
+ REQSIGN_GOOGLE_CAB_SOURCE_TOKEN: ${{ steps.auth.outputs.access_token }}
+ run: |
+ export REQSIGN_GOOGLE_CAB_SOURCE_EXPIRES_AT
+ REQSIGN_GOOGLE_CAB_SOURCE_EXPIRES_AT=$(date --utc --date='+25 minutes' '+%Y-%m-%dT%H:%M:%SZ')
+ cargo test -p reqsign-google --features credential-access-boundary-client-side --test credential_access_boundary -- --no-capture
- # AuthorizedUserCredentialProvider test
- test_authorized_user_provider:
+ test_impersonated_adc_provider:
+ name: Impersonated ADC provider live test
needs: check_secrets
- if: needs.check_secrets.outputs.has_secrets == 'true'
+ if: needs.check_secrets.outputs.trusted == 'true'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- - name: Setup 1Password Connect
+ - name: Configure 1Password Connect
uses: 1Password/load-secrets-action/configure@eb2efd0703da22a93c467f2d1ffbb6826c11e19c # v4.1.1
with:
connect-host: ${{ secrets.OP_CONNECT_HOST }}
connect-token: ${{ secrets.OP_CONNECT_TOKEN }}
- - name: Load secrets
+ - name: Load impersonated ADC credential
id: load_secrets
uses: 1Password/load-secrets-action@eb2efd0703da22a93c467f2d1ffbb6826c11e19c # v4.1.1
env:
- AUTHORIZED_USER_CREDENTIALS_BASE64: op://reqsign/google/authorized_user_base64
- - name: Setup test credentials file
- run: |
- echo "${STEPS_LOAD_SECRETS_OUTPUTS_AUTHORIZED_USER_CREDENTIALS_BASE64}" | base64 -d > /tmp/authorized_user.json
- echo "REQSIGN_GOOGLE_AUTHORIZED_USER_CREDENTIALS=/tmp/authorized_user.json" >> $GITHUB_ENV
+ GOOGLE_IMPERSONATED_ADC_BASE64: op://reqsign/google/impersonated_sa_base64
+ - name: Set up impersonated ADC credential
env:
- STEPS_LOAD_SECRETS_OUTPUTS_AUTHORIZED_USER_CREDENTIALS_BASE64: ${{ steps.load_secrets.outputs.AUTHORIZED_USER_CREDENTIALS_BASE64 }}
- - name: Test AuthorizedUserCredentialProvider
- working-directory: ./services/google
+ GOOGLE_IMPERSONATED_ADC_BASE64: ${{ steps.load_secrets.outputs.GOOGLE_IMPERSONATED_ADC_BASE64 }}
+ run: |
+ credential_path="$RUNNER_TEMP/google-impersonated-adc.json"
+ printf '%s' "$GOOGLE_IMPERSONATED_ADC_BASE64" | base64 --decode > "$credential_path"
+ test -s "$credential_path"
+ chmod 600 "$credential_path"
+ echo "REQSIGN_GOOGLE_IMPERSONATED_SERVICE_ACCOUNT_CREDENTIALS=$credential_path" >> "$GITHUB_ENV"
+ - name: Test ImpersonatedServiceAccountCredentialProvider against Cloud Storage
env:
- REQSIGN_GOOGLE_TEST_AUTHORIZED_USER: on
+ REQSIGN_GOOGLE_TEST_IMPERSONATED_SERVICE_ACCOUNT: "on"
run: |
- test "${REQSIGN_GOOGLE_TEST_AUTHORIZED_USER}" = "on"
- echo "::group::Testing AuthorizedUserCredentialProvider"
- cargo test test_authorized_user_credential_provider --no-fail-fast -- --no-capture
- echo "::endgroup::"
+ cargo test -p reqsign-google --test main credential_providers::impersonated_service_account::test_impersonated_service_account_credential_provider -- --exact --no-capture
- # ExternalAccountCredentialProvider test (Workload Identity)
- test_external_account_provider:
+ test_vm_metadata_provider:
+ name: VM metadata provider live test
needs: check_secrets
- if: needs.check_secrets.outputs.has_secrets == 'true'
+ if: needs.check_secrets.outputs.trusted == 'true'
runs-on: ubuntu-latest
+ timeout-minutes: 30
+ env:
+ GOOGLE_PROJECT_ID: reqsign
+ GOOGLE_METADATA_SERVICE_ACCOUNT: reqsign-metadata@reqsign.iam.gserviceaccount.com
permissions:
contents: read
id-token: write
@@ -215,221 +280,162 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- - name: Setup 1Password Connect
+ - name: Configure 1Password Connect
uses: 1Password/load-secrets-action/configure@eb2efd0703da22a93c467f2d1ffbb6826c11e19c # v4.1.1
with:
connect-host: ${{ secrets.OP_CONNECT_HOST }}
connect-token: ${{ secrets.OP_CONNECT_TOKEN }}
- - name: Load secrets
+ - name: Load Google control-plane configuration
uses: 1Password/load-secrets-action@eb2efd0703da22a93c467f2d1ffbb6826c11e19c # v4.1.1
with:
export-env: true
env:
GOOGLE_WORKLOAD_IDENTITY_PROVIDER: op://reqsign/google/workload_identity_provider
GOOGLE_SERVICE_ACCOUNT: op://reqsign/google/service_account_email
- - name: Setup Workload Identity with Google Auth
+ - name: Authenticate Google control plane through workload identity
uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3.0.0
with:
create_credentials_file: true
workload_identity_provider: ${{ env.GOOGLE_WORKLOAD_IDENTITY_PROVIDER }}
service_account: ${{ env.GOOGLE_SERVICE_ACCOUNT }}
- - name: Test ExternalAccountCredentialProvider
- working-directory: ./services/google
- env:
- REQSIGN_GOOGLE_TEST_WORKLOAD_IDENTITY: on
- run: |
- test "${REQSIGN_GOOGLE_TEST_WORKLOAD_IDENTITY}" = "on"
- echo "::group::Testing ExternalAccountCredentialProvider"
- # The google-github-actions/auth action sets GOOGLE_APPLICATION_CREDENTIALS
- # reqsign should be able to use this external_account configuration
- cargo test test_external_account_with_workload_identity --no-fail-fast -- --no-capture
- echo "::endgroup::"
-
- # ImpersonatedServiceAccountCredentialProvider test
- test_impersonated_service_account_provider:
- needs: check_secrets
- if: needs.check_secrets.outputs.has_secrets == 'true'
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- with:
- persist-credentials: false
- - name: Setup 1Password Connect
- uses: 1Password/load-secrets-action/configure@eb2efd0703da22a93c467f2d1ffbb6826c11e19c # v4.1.1
+ - name: Set up Google Cloud CLI
+ uses: google-github-actions/setup-gcloud@aa5489c8933f4cc7a4f7d45035b3b1440c9c10db # v3.0.1
with:
- connect-host: ${{ secrets.OP_CONNECT_HOST }}
- connect-token: ${{ secrets.OP_CONNECT_TOKEN }}
- - name: Load secrets
- id: load_secrets
- uses: 1Password/load-secrets-action@eb2efd0703da22a93c467f2d1ffbb6826c11e19c # v4.1.1
- env:
- IMPERSONATED_SA_CREDENTIALS_BASE64: op://reqsign/google/impersonated_sa_base64
- - name: Setup test credentials file
+ project_id: ${{ env.GOOGLE_PROJECT_ID }}
+ - name: Build VM metadata live test binary
+ id: build
run: |
- echo "${STEPS_LOAD_SECRETS_OUTPUTS_IMPERSONATED_SA_CREDENTIALS_BASE64}" | base64 -d > /tmp/impersonated_sa.json
- echo "REQSIGN_GOOGLE_IMPERSONATED_SERVICE_ACCOUNT_CREDENTIALS=/tmp/impersonated_sa.json" >> $GITHUB_ENV
- env:
- STEPS_LOAD_SECRETS_OUTPUTS_IMPERSONATED_SA_CREDENTIALS_BASE64: ${{ steps.load_secrets.outputs.IMPERSONATED_SA_CREDENTIALS_BASE64 }}
- - name: Test ImpersonatedServiceAccountCredentialProvider
- working-directory: ./services/google
+ messages="$RUNNER_TEMP/google-metadata-cargo-messages.json"
+ cargo test -p reqsign-google --test main --no-run --message-format=json > "$messages"
+ executable=$(jq --raw-output 'select(.profile.test == true and .target.name == "main") | .executable' "$messages" | tail -n 1)
+ test -n "$executable"
+ test -x "$executable"
+ echo "executable=$executable" >> "$GITHUB_OUTPUT"
+ - name: Upload VM metadata live test binary
+ id: artifact
env:
- REQSIGN_GOOGLE_TEST_IMPERSONATED_SERVICE_ACCOUNT: on
+ TEST_EXECUTABLE: ${{ steps.build.outputs.executable }}
run: |
- test "${REQSIGN_GOOGLE_TEST_IMPERSONATED_SERVICE_ACCOUNT}" = "on"
- echo "::group::Testing ImpersonatedServiceAccountCredentialProvider"
- cargo test test_impersonated_service_account_credential_provider --no-fail-fast -- --no-capture
- echo "::endgroup::"
-
- # VmMetadataCredentialProvider test
- test_vm_metadata_provider:
- needs: check_secrets
- if: needs.check_secrets.outputs.has_secrets == 'true'
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- with:
- persist-credentials: false
- - name: Start mock metadata server
+ artifact_name="ci-artifact-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
+ gcloud storage cp "$TEST_EXECUTABLE" "gs://reqsign/$artifact_name" --quiet
+ echo "name=$artifact_name" >> "$GITHUB_OUTPUT"
+ - name: Create private Compute Engine VM
+ id: vm
+ env:
+ ARTIFACT_NAME: ${{ steps.artifact.outputs.name }}
run: |
- python3 services/google/tests/mocks/vm_metadata_mock_server.py 8080 &
- echo "MOCK_PID=$!" >> $GITHUB_ENV
- sleep 2
- # Verify the mock server is running
- curl -f -H "Metadata-Flavor: Google" http://127.0.0.1:8080/computeMetadata/v1/instance/service-accounts/ || exit 1
- - name: Test VmMetadataCredentialProvider with mock
- working-directory: ./services/google
+ vm_name="reqsign-metadata-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
+ startup_script="$RUNNER_TEMP/google-metadata-startup.sh"
+ cat > "$startup_script" <<SCRIPT
+ #!/usr/bin/env bash
+ set -euo pipefail
+ exec > >(tee /dev/ttyS0) 2>&1
+ token_response=\$(curl --connect-timeout 15 --fail --silent --show-error \
+ --header 'Metadata-Flavor: Google' \
+ 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token?scopes=https://www.googleapis.com/auth/cloud-platform')
+ storage_token=\$(python3 -c 'import json,sys; print(json.loads(sys.argv[1])["access_token"])' "\$token_response")
+ curl --connect-timeout 15 --fail --silent --show-error \
+ --header "Authorization: Bearer \$storage_token" \
+ "https://storage.googleapis.com/storage/v1/b/reqsign/o/${ARTIFACT_NAME}?alt=media" \
+ --output /tmp/reqsign-google-metadata-live-test
+ chmod 700 /tmp/reqsign-google-metadata-live-test
+ REQSIGN_GOOGLE_TEST_VM_METADATA=on \
+ REQSIGN_GOOGLE_CLOUD_STORAGE_SCOPE='https://www.googleapis.com/auth/devstorage.read_only' \
+ REQSIGN_GOOGLE_CLOUD_STORAGE_PROBE_URL='https://storage.googleapis.com/storage/v1/b/reqsign/o/live%2Fcredential-ok?alt=media' \
+ /tmp/reqsign-google-metadata-live-test credential_providers::vm_metadata:: --nocapture
+ echo REQSIGN_GOOGLE_METADATA_TEST_SUCCEEDED
+ SCRIPT
+
+ for zone in us-east1-b us-east1-c us-east1-d; do
+ if gcloud compute instances create "$vm_name" --project="$GOOGLE_PROJECT_ID" --zone="$zone" --machine-type=e2-micro --subnet=default --no-address --image-family=ubuntu-2404-lts-amd64 --image-project=ubuntu-os-cloud --service-account="$GOOGLE_METADATA_SERVICE_ACCOUNT" --scopes=https://www.googleapis.com/auth/cloud-platform --metadata-from-file=startup-script="$startup_script" --max-run-duration=15m --instance-termination-action=DELETE --boot-disk-auto-delete --labels=project=r [...]
+ echo "name=$vm_name" >> "$GITHUB_OUTPUT"
+ echo "zone=$zone" >> "$GITHUB_OUTPUT"
+ exit
+ fi
+ done
+ echo "No configured Compute Engine zone had capacity" >&2
+ exit 1
+ - name: Wait for VM metadata live test
+ env:
+ VM_NAME: ${{ steps.vm.outputs.name }}
+ VM_ZONE: ${{ steps.vm.outputs.zone }}
run: |
- echo "::group::Testing VmMetadataCredentialProvider with mock"
- export REQSIGN_GOOGLE_TEST_VM_METADATA_MOCK=on
- export GCE_METADATA_HOST=127.0.0.1:8080
- cargo test test_vm_metadata_credential_provider_with_mock --no-fail-fast -- --no-capture
- echo "::endgroup::"
- - name: Stop mock server
+ deadline=$((SECONDS + 900))
+ while (( SECONDS < deadline )); do
+ output=$(gcloud compute instances get-serial-port-output "$VM_NAME" --zone="$VM_ZONE" --port=1 --start=0 2>/dev/null || true)
+ if grep --quiet REQSIGN_GOOGLE_METADATA_TEST_SUCCEEDED <<< "$output"; then
+ exit
+ fi
+ if grep --quiet 'FAILED' <<< "$output"; then
+ printf '%s\n' "$output"
+ exit 1
+ fi
+ sleep 10
+ done
+ gcloud compute instances get-serial-port-output "$VM_NAME" --zone="$VM_ZONE" --port=1 --start=0 || true
+ echo "VM metadata live test did not finish before the timeout" >&2
+ exit 1
+ - name: Delete ephemeral Google resources
if: always()
+ env:
+ ARTIFACT_NAME: ${{ steps.artifact.outputs.name }}
+ VM_NAME: ${{ steps.vm.outputs.name }}
+ VM_ZONE: ${{ steps.vm.outputs.zone }}
run: |
- if [ ! -z "$MOCK_PID" ]; then
- kill $MOCK_PID || true
+ if [[ -n "$VM_NAME" ]] && [[ -n "$VM_ZONE" ]] && gcloud compute instances describe "$VM_NAME" --zone="$VM_ZONE" >/dev/null 2>&1; then
+ gcloud compute instances delete "$VM_NAME" --zone="$VM_ZONE" --quiet
+ fi
+ if [[ -n "$ARTIFACT_NAME" ]]; then
+ gcloud storage rm "gs://reqsign/$ARTIFACT_NAME" --quiet
fi
- # Summary
- test_summary:
+ summary:
+ name: Test Summary
needs:
- [
- unit_test,
- signing_test,
- test_default_provider,
- test_static_provider,
- test_authorized_user_provider,
- test_external_account_provider,
- test_impersonated_service_account_provider,
- test_vm_metadata_provider,
- ]
- if: always()
+ - unit_test
+ - check_secrets
+ - test_service_account_providers
+ - test_authorized_user_provider
+ - test_workload_identity_and_token_providers
+ - test_impersonated_adc_provider
+ - test_vm_metadata_provider
+ if: always() && !cancelled()
runs-on: ubuntu-latest
steps:
- - name: Test Summary
+ - name: Summarize Google credential coverage
+ env:
+ UNIT_RESULT: ${{ needs.unit_test.result }}
+ TRUSTED: ${{ needs.check_secrets.outputs.trusted }}
+ SERVICE_ACCOUNT_RESULT: ${{ needs.test_service_account_providers.result }}
+ AUTHORIZED_USER_RESULT: ${{ needs.test_authorized_user_provider.result }}
+ WORKLOAD_IDENTITY_RESULT: ${{ needs.test_workload_identity_and_token_providers.result }}
+ IMPERSONATED_ADC_RESULT: ${{ needs.test_impersonated_adc_provider.result }}
+ VM_METADATA_RESULT: ${{ needs.test_vm_metadata_provider.result }}
run: |
- echo "## Google Cloud Test Summary" >> $GITHUB_STEP_SUMMARY
- echo "" >> $GITHUB_STEP_SUMMARY
-
- # Unit tests status
- if [[ "${NEEDS_UNIT_TEST_RESULT}" == "success" ]]; then
- echo "✅ Unit tests passed" >> $GITHUB_STEP_SUMMARY
- elif [[ "${NEEDS_UNIT_TEST_RESULT}" == "skipped" ]]; then
- echo "⏭️ Unit tests skipped" >> $GITHUB_STEP_SUMMARY
- else
- echo "❌ Unit tests failed" >> $GITHUB_STEP_SUMMARY
- fi
-
- # Integration tests status
- echo "" >> $GITHUB_STEP_SUMMARY
- echo "### Integration Tests" >> $GITHUB_STEP_SUMMARY
-
- if [[ "${NEEDS_SIGNING_TEST_RESULT}" == "success" ]]; then
- echo "✅ Signing tests passed" >> $GITHUB_STEP_SUMMARY
- elif [[ "${NEEDS_SIGNING_TEST_RESULT}" == "skipped" ]]; then
- echo "⏭️ Signing tests skipped (no secrets)" >> $GITHUB_STEP_SUMMARY
- else
- echo "❌ Signing tests failed" >> $GITHUB_STEP_SUMMARY
- fi
-
- if [[ "${NEEDS_TEST_DEFAULT_PROVIDER_RESULT}" == "success" ]]; then
- echo "✅ DefaultCredentialProvider tests passed" >> $GITHUB_STEP_SUMMARY
- elif [[ "${NEEDS_TEST_DEFAULT_PROVIDER_RESULT}" == "skipped" ]]; then
- echo "⏭️ DefaultCredentialProvider tests skipped (no secrets)" >> $GITHUB_STEP_SUMMARY
- else
- echo "❌ DefaultCredentialProvider tests failed" >> $GITHUB_STEP_SUMMARY
- fi
-
- if [[ "${NEEDS_TEST_STATIC_PROVIDER_RESULT}" == "success" ]]; then
- echo "✅ StaticCredentialProvider tests passed" >> $GITHUB_STEP_SUMMARY
- elif [[ "${NEEDS_TEST_STATIC_PROVIDER_RESULT}" == "skipped" ]]; then
- echo "⏭️ StaticCredentialProvider tests skipped (no secrets)" >> $GITHUB_STEP_SUMMARY
- else
- echo "❌ StaticCredentialProvider tests failed" >> $GITHUB_STEP_SUMMARY
+ {
+ echo "## Google Cloud Test Summary"
+ echo
+ echo "| Coverage | Real service acceptance | Result |"
+ echo "|----------|-------------------------|--------|"
+ echo "| Unit tests and redacted real-response replays | Local | $UNIT_RESULT |"
+ if [[ "$TRUSTED" == "true" ]]; then
+ echo "| Static, file, environment, well-known, and default providers | OAuth and Cloud Storage | $SERVICE_ACCOUNT_RESULT |"
+ echo "| ServiceAccountTokenCredentialProvider and server-side CAB | OAuth, STS, and Cloud Storage | $SERVICE_ACCOUNT_RESULT |"
+ echo "| Authorized user provider | OAuth and Cloud Storage | $AUTHORIZED_USER_RESULT |"
+ echo "| External account and TokenCredentialProvider | GitHub OIDC, STS, IAM Credentials, and Cloud Storage | $WORKLOAD_IDENTITY_RESULT |"
+ echo "| Typed impersonation, IAM signBlob, and client-side CAB | IAM Credentials, STS, and Cloud Storage | $WORKLOAD_IDENTITY_RESULT |"
+ echo "| Impersonated ADC provider | OAuth, IAM Credentials, and Cloud Storage | $IMPERSONATED_ADC_RESULT |"
+ echo "| VmMetadataCredentialProvider | Compute Engine metadata and Cloud Storage | $VM_METADATA_RESULT |"
+ else
+ echo "| Live service integration tests | Skipped because Connect secrets are unavailable | skipped |"
+ fi
+ } >> "$GITHUB_STEP_SUMMARY"
+
+ test "$UNIT_RESULT" = "success"
+ if [[ "$TRUSTED" == "true" ]]; then
+ test "$SERVICE_ACCOUNT_RESULT" = "success"
+ test "$AUTHORIZED_USER_RESULT" = "success"
+ test "$WORKLOAD_IDENTITY_RESULT" = "success"
+ test "$IMPERSONATED_ADC_RESULT" = "success"
+ test "$VM_METADATA_RESULT" = "success"
fi
-
- if [[ "${NEEDS_TEST_AUTHORIZED_USER_PROVIDER_RESULT}" == "success" ]]; then
- echo "✅ AuthorizedUserCredentialProvider tests passed" >> $GITHUB_STEP_SUMMARY
- elif [[ "${NEEDS_TEST_AUTHORIZED_USER_PROVIDER_RESULT}" == "skipped" ]]; then
- echo "⏭️ AuthorizedUserCredentialProvider tests skipped (no secrets)" >> $GITHUB_STEP_SUMMARY
- else
- echo "❌ AuthorizedUserCredentialProvider tests failed" >> $GITHUB_STEP_SUMMARY
- fi
-
- if [[ "${NEEDS_TEST_EXTERNAL_ACCOUNT_PROVIDER_RESULT}" == "success" ]]; then
- echo "✅ ExternalAccountCredentialProvider tests passed" >> $GITHUB_STEP_SUMMARY
- elif [[ "${NEEDS_TEST_EXTERNAL_ACCOUNT_PROVIDER_RESULT}" == "skipped" ]]; then
- echo "⏭️ ExternalAccountCredentialProvider tests skipped (no secrets)" >> $GITHUB_STEP_SUMMARY
- else
- echo "❌ ExternalAccountCredentialProvider tests failed" >> $GITHUB_STEP_SUMMARY
- fi
-
- if [[ "${NEEDS_TEST_IMPERSONATED_SERVICE_ACCOUNT_PROVIDER_RESULT}" == "success" ]]; then
- echo "✅ ImpersonatedServiceAccountCredentialProvider tests passed" >> $GITHUB_STEP_SUMMARY
- elif [[ "${NEEDS_TEST_IMPERSONATED_SERVICE_ACCOUNT_PROVIDER_RESULT}" == "skipped" ]]; then
- echo "⏭️ ImpersonatedServiceAccountCredentialProvider tests skipped (no secrets)" >> $GITHUB_STEP_SUMMARY
- else
- echo "❌ ImpersonatedServiceAccountCredentialProvider tests failed" >> $GITHUB_STEP_SUMMARY
- fi
-
- if [[ "${NEEDS_TEST_VM_METADATA_PROVIDER_RESULT}" == "success" ]]; then
- echo "✅ VmMetadataCredentialProvider tests passed" >> $GITHUB_STEP_SUMMARY
- elif [[ "${NEEDS_TEST_VM_METADATA_PROVIDER_RESULT}" == "skipped" ]]; then
- echo "⏭️ VmMetadataCredentialProvider tests skipped (no secrets)" >> $GITHUB_STEP_SUMMARY
- else
- echo "❌ VmMetadataCredentialProvider tests failed" >> $GITHUB_STEP_SUMMARY
- fi
-
- # Overall status
- echo "" >> $GITHUB_STEP_SUMMARY
- if [[ "${NEEDS_UNIT_TEST_RESULT}" == "success" ]] && \
- ( [[ "${NEEDS_SIGNING_TEST_RESULT}" == "success" ]] || [[ "${NEEDS_SIGNING_TEST_RESULT}" == "skipped" ]] ) && \
- ( [[ "${NEEDS_TEST_DEFAULT_PROVIDER_RESULT}" == "success" ]] || [[ "${NEEDS_TEST_DEFAULT_PROVIDER_RESULT}" == "skipped" ]] ) && \
- ( [[ "${NEEDS_TEST_STATIC_PROVIDER_RESULT}" == "success" ]] || [[ "${NEEDS_TEST_STATIC_PROVIDER_RESULT}" == "skipped" ]] ) && \
- ( [[ "${NEEDS_TEST_AUTHORIZED_USER_PROVIDER_RESULT}" == "success" ]] || [[ "${NEEDS_TEST_AUTHORIZED_USER_PROVIDER_RESULT}" == "skipped" ]] ) && \
- ( [[ "${NEEDS_TEST_EXTERNAL_ACCOUNT_PROVIDER_RESULT}" == "success" ]] || [[ "${NEEDS_TEST_EXTERNAL_ACCOUNT_PROVIDER_RESULT}" == "skipped" ]] ) && \
- ( [[ "${NEEDS_TEST_IMPERSONATED_SERVICE_ACCOUNT_PROVIDER_RESULT}" == "success" ]] || [[ "${NEEDS_TEST_IMPERSONATED_SERVICE_ACCOUNT_PROVIDER_RESULT}" == "skipped" ]] ) && \
- ( [[ "${NEEDS_TEST_VM_METADATA_PROVIDER_RESULT}" == "success" ]] || [[ "${NEEDS_TEST_VM_METADATA_PROVIDER_RESULT}" == "skipped" ]] ); then
- echo "### ✅ All tests completed successfully" >> $GITHUB_STEP_SUMMARY
- else
- echo "### ❌ Some tests failed" >> $GITHUB_STEP_SUMMARY
- exit 1
- fi
-
- env:
- NEEDS_UNIT_TEST_RESULT: ${{ needs.unit_test.result }}
-
- NEEDS_SIGNING_TEST_RESULT: ${{ needs.signing_test.result }}
-
- NEEDS_TEST_DEFAULT_PROVIDER_RESULT: ${{ needs.test_default_provider.result }}
-
- NEEDS_TEST_STATIC_PROVIDER_RESULT: ${{ needs.test_static_provider.result }}
-
- NEEDS_TEST_AUTHORIZED_USER_PROVIDER_RESULT: ${{ needs.test_authorized_user_provider.result }}
-
- NEEDS_TEST_EXTERNAL_ACCOUNT_PROVIDER_RESULT: ${{ needs.test_external_account_provider.result }}
-
- NEEDS_TEST_IMPERSONATED_SERVICE_ACCOUNT_PROVIDER_RESULT: ${{ needs.test_impersonated_service_account_provider.result }}
-
- NEEDS_TEST_VM_METADATA_PROVIDER_RESULT: ${{ needs.test_vm_metadata_provider.result }}
diff --git a/services/google/src/credential_access_boundary/server_side.rs b/services/google/src/credential_access_boundary/server_side.rs
index aed87d5..f04af31 100644
--- a/services/google/src/credential_access_boundary/server_side.rs
+++ b/services/google/src/credential_access_boundary/server_side.rs
@@ -469,13 +469,18 @@ mod tests {
}
fn success_response(access_token: &str, expires_in: Option<u64>) -> http::Response<Bytes> {
- let mut value = serde_json::json!({
- "access_token": access_token,
- "issued_token_type": ACCESS_TOKEN_TYPE,
- "token_type": "Bearer"
- });
+ let mut value: serde_json::Value = serde_json::from_slice(include_bytes!(
+ "../../tests/fixtures/server_side_cab_sts_response.json"
+ ))
+ .expect("real server-side CAB STS response fixture must parse");
+ value["access_token"] = access_token.into();
if let Some(expires_in) = expires_in {
value["expires_in"] = expires_in.into();
+ } else {
+ value
+ .as_object_mut()
+ .expect("STS response fixture must be an object")
+ .remove("expires_in");
}
response(
http::StatusCode::OK,
@@ -483,6 +488,19 @@ mod tests {
)
}
+ #[test]
+ fn parses_redacted_real_server_side_sts_response() {
+ let response: StsTokenResponse = serde_json::from_slice(include_bytes!(
+ "../../tests/fixtures/server_side_cab_sts_response.json"
+ ))
+ .expect("real server-side CAB STS response fixture must parse");
+
+ assert_eq!(response.access_token, "REDACTED");
+ assert_eq!(response.issued_token_type, ACCESS_TOKEN_TYPE);
+ assert_eq!(response.token_type, "Bearer");
+ assert_eq!(response.expires_in, None);
+ }
+
fn viewer_bucket_grant() -> CredentialAccessBoundaryGrant {
CredentialAccessBoundaryGrant::for_bucket(
"example-bucket",
diff --git a/services/google/src/provide_credential/authorized_user.rs b/services/google/src/provide_credential/authorized_user.rs
index ac74e25..e095f92 100644
--- a/services/google/src/provide_credential/authorized_user.rs
+++ b/services/google/src/provide_credential/authorized_user.rs
@@ -41,6 +41,12 @@ struct RefreshTokenResponse {
expires_in: Option<u64>,
}
+fn parse_refresh_token_response(body: &[u8]) -> Result<RefreshTokenResponse> {
+ serde_json::from_slice(body).map_err(|e| {
+ reqsign_core::Error::unexpected("failed to parse token response").with_source(e)
+ })
+}
+
/// AuthorizedUserCredentialProvider exchanges OAuth2 user credentials for access tokens.
#[derive(Debug, Clone)]
pub struct AuthorizedUserCredentialProvider {
@@ -88,10 +94,7 @@ impl ProvideCredential for AuthorizedUserCredentialProvider {
)));
}
- let token_resp: RefreshTokenResponse =
- serde_json::from_slice(resp.body()).map_err(|e| {
- reqsign_core::Error::unexpected("failed to parse token response").with_source(e)
- })?;
+ let token_resp = parse_refresh_token_response(resp.body())?;
let expires_at = token_resp
.expires_in
@@ -103,3 +106,19 @@ impl ProvideCredential for AuthorizedUserCredentialProvider {
})))
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parses_redacted_real_authorized_user_response() {
+ let response = parse_refresh_token_response(include_bytes!(
+ "../../tests/fixtures/authorized_user_token_response.json"
+ ))
+ .expect("real authorized-user token response fixture must parse");
+
+ assert_eq!(response.access_token, "REDACTED");
+ assert_eq!(response.expires_in, Some(3599));
+ }
+}
diff --git a/services/google/src/provide_credential/default.rs b/services/google/src/provide_credential/default.rs
index 85d40e6..3a9e05a 100644
--- a/services/google/src/provide_credential/default.rs
+++ b/services/google/src/provide_credential/default.rs
@@ -254,7 +254,7 @@ mod tests {
Ok(http::Response::builder()
.status(http::StatusCode::OK)
.body(
- br#"{"access_token":"test-access-token","expires_in":3600}"#
+ include_bytes!("../../tests/fixtures/vm_metadata_token_response.json")
.as_slice()
.into(),
)
diff --git a/services/google/src/provide_credential/impersonated_service_account.rs b/services/google/src/provide_credential/impersonated_service_account.rs
index 17370fc..1a05556 100644
--- a/services/google/src/provide_credential/impersonated_service_account.rs
+++ b/services/google/src/provide_credential/impersonated_service_account.rs
@@ -189,20 +189,34 @@ mod tests {
impl HttpSend for MockHttpSend {
async fn http_send(&self, req: http::Request<Bytes>) -> Result<http::Response<Bytes>> {
- let body = match req.uri().to_string().as_str() {
- "https://oauth2.googleapis.com/token" => {
- br#"{"access_token":"source-token","expires_in":3600}"#.as_slice()
- }
+ let mut body: serde_json::Value = match req.uri().to_string().as_str() {
+ "https://oauth2.googleapis.com/token" => serde_json::from_slice(include_bytes!(
+ "../../tests/fixtures/authorized_user_token_response.json"
+ ))
+ .expect("real authorized-user response fixture must parse"),
"https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/target%40example.com:generateAccessToken" => {
- br#"{"accessToken":"impersonated-token","expireTime":"2100-01-01T00:00:00Z"}"#
- .as_slice()
+ serde_json::from_slice(include_bytes!(
+ "../../tests/fixtures/iam_generate_access_token_response.json"
+ ))
+ .expect("real IAM Credentials response fixture must parse")
}
uri => panic!("unexpected request: {uri}"),
};
+ if req.uri() == "https://oauth2.googleapis.com/token" {
+ body["access_token"] = "source-token".into();
+ body["expires_in"] = 3600.into();
+ } else {
+ body["accessToken"] = "impersonated-token".into();
+ body["expireTime"] = "2100-01-01T00:00:00Z".into();
+ }
Ok(http::Response::builder()
.status(http::StatusCode::OK)
- .body(body.into())
+ .body(
+ serde_json::to_vec(&body)
+ .expect("response fixture must serialize")
+ .into(),
+ )
.expect("response must build"))
}
}
diff --git a/services/google/src/provide_credential/vm_metadata.rs b/services/google/src/provide_credential/vm_metadata.rs
index c8f73b3..53f8ac5 100644
--- a/services/google/src/provide_credential/vm_metadata.rs
+++ b/services/google/src/provide_credential/vm_metadata.rs
@@ -147,7 +147,7 @@ mod tests {
Ok(http::Response::builder()
.status(http::StatusCode::OK)
.body(
- br#"{"access_token":"test-access-token","expires_in":3600}"#
+ include_bytes!("../../tests/fixtures/vm_metadata_token_response.json")
.as_slice()
.into(),
)
@@ -167,6 +167,10 @@ mod tests {
.expect("credential must exist");
assert!(cred.has_token());
+ assert_eq!(
+ cred.token.as_ref().map(|token| token.access_token.as_str()),
+ Some("REDACTED")
+ );
assert!(cred.signer_email.is_none());
assert_eq!(
http.uris.lock().unwrap().as_slice(),
@@ -190,6 +194,10 @@ mod tests {
.expect("credential must exist");
assert!(cred.has_token());
+ assert_eq!(
+ cred.token.as_ref().map(|token| token.access_token.as_str()),
+ Some("REDACTED")
+ );
assert_eq!(
cred.signer_email.as_deref(),
Some("custom@test-project.iam.gserviceaccount.com")
diff --git a/services/google/src/service_account_impersonation.rs b/services/google/src/service_account_impersonation.rs
index 58930ba..7036651 100644
--- a/services/google/src/service_account_impersonation.rs
+++ b/services/google/src/service_account_impersonation.rs
@@ -609,6 +609,17 @@ mod tests {
value.parse().expect("timestamp must parse")
}
+ #[test]
+ fn parses_redacted_real_generate_access_token_response() {
+ let response: GenerateAccessTokenResponse = serde_json::from_slice(include_bytes!(
+ "../tests/fixtures/iam_generate_access_token_response.json"
+ ))
+ .expect("real IAM Credentials response fixture must parse");
+
+ assert_eq!(response.access_token, "REDACTED");
+ assert_eq!(response.expire_time, "2026-09-03T13:30:38Z");
+ }
+
fn response(status: http::StatusCode, body: &str) -> http::Response<Bytes> {
http::Response::builder()
.status(status)
@@ -616,6 +627,19 @@ mod tests {
.expect("response must build")
}
+ fn iam_success_response(access_token: &str, expire_time: &str) -> http::Response<Bytes> {
+ let mut value: serde_json::Value = serde_json::from_slice(include_bytes!(
+ "../tests/fixtures/iam_generate_access_token_response.json"
+ ))
+ .expect("real IAM Credentials response fixture must parse");
+ value["accessToken"] = access_token.into();
+ value["expireTime"] = expire_time.into();
+ response(
+ http::StatusCode::OK,
+ &serde_json::to_string(&value).expect("IAM response fixture must serialize"),
+ )
+ }
+
fn source(expires_at: &str) -> Credential {
Credential::with_token(Token {
access_token: "source-secret-token".to_string(),
@@ -641,9 +665,9 @@ mod tests {
async fn constructs_canonical_request_and_preserves_authoritative_expiration() -> Result<()> {
let now = timestamp("2026-09-02T00:00:00Z");
let expires_at = timestamp("2026-09-02T01:00:00Z");
- let http = MockHttpSend::new([response(
- http::StatusCode::OK,
- r#"{"accessToken":"impersonated-secret-token","expireTime":"2026-09-02T01:00:00Z"}"#,
+ let http = MockHttpSend::new([iam_success_response(
+ "impersonated-secret-token",
+ "2026-09-02T01:00:00Z",
)]);
let granter = ServiceAccountImpersonationGranter::new(grant()).with_time(now);
@@ -808,14 +832,8 @@ mod tests {
let now = timestamp("2026-09-02T00:00:00Z");
let response_time = timestamp("2026-09-02T00:00:20Z");
let http = MockHttpSend::new([
- response(
- http::StatusCode::OK,
- r#"{"accessToken":"impersonated-token","expireTime":"2026-09-02T01:00:00Z"}"#,
- ),
- response(
- http::StatusCode::OK,
- r#"{"accessToken":"impersonated-token","expireTime":"2026-09-02T00:00:25Z"}"#,
- ),
+ iam_success_response("impersonated-token", "2026-09-02T01:00:00Z"),
+ iam_success_response("impersonated-token", "2026-09-02T00:00:25Z"),
]);
let context = Context::new().with_http_send(http);
@@ -880,14 +898,8 @@ mod tests {
credential: Some(source("2100-01-01T00:00:00Z")),
};
let http = MockHttpSend::new([
- response(
- http::StatusCode::OK,
- r#"{"accessToken":"first-token","expireTime":"2100-01-01T00:00:00Z"}"#,
- ),
- response(
- http::StatusCode::OK,
- r#"{"accessToken":"second-token","expireTime":"2100-01-01T00:00:00Z"}"#,
- ),
+ iam_success_response("first-token", "2100-01-01T00:00:00Z"),
+ iam_success_response("second-token", "2100-01-01T00:00:00Z"),
]);
let context = Context::new().with_http_send(http.clone());
let granter = Granter::new(
@@ -909,9 +921,9 @@ mod tests {
assert_eq!(calls.load(Ordering::SeqCst), 1);
assert_eq!(http.request_count(), 2);
- let wrapper_http = MockHttpSend::new([response(
- http::StatusCode::OK,
- r#"{"accessToken":"provider-token","expireTime":"2100-01-01T00:00:00Z"}"#,
+ let wrapper_http = MockHttpSend::new([iam_success_response(
+ "provider-token",
+ "2100-01-01T00:00:00Z",
)]);
let wrapper = ServiceAccountImpersonationCredentialProvider::new(
CountingProvider {
diff --git a/services/google/tests/README.md b/services/google/tests/README.md
index 9572be6..c7d907a 100644
--- a/services/google/tests/README.md
+++ b/services/google/tests/README.md
@@ -1,144 +1,126 @@
-# Google Cloud Service Tests
-
-This directory contains integration tests for the Google Cloud service implementation in reqsign.
-
-## Test Structure
-
-The tests are organized into two main categories:
-
-### 1. Credential Providers (`credential_providers/`)
-Tests for various Google Cloud credential providers:
-- **DefaultCredentialProvider**: Tests the default credential chain (GOOGLE_APPLICATION_CREDENTIALS environment variable)
-- **StaticCredentialProvider**: Tests loading credentials from base64-encoded JSON
-- **AuthorizedUserCredentialProvider**: Tests OAuth2 user credentials (refresh token exchange)
-- **ExternalAccountCredentialProvider**: Tests external account credentials (Workload Identity Federation)
-- **ImpersonatedServiceAccountCredentialProvider**: Tests service account impersonation
-- **VmMetadataCredentialProvider**: Tests fetching credentials from GCP VM metadata service (only available on GCP VMs)
-
-### 2. Signing Tests (`signing/`)
-Tests for request signing functionality:
-- **Standard signing**: Tests OAuth2 bearer token signing for GCS API requests
-- **Signed URLs**: Tests generating pre-signed URLs for GCS objects
-
-## Environment Variables
-
-### Core Test Control
-- `REQSIGN_GOOGLE_TEST`: Set to `on` to enable signing tests
-- `REQSIGN_GOOGLE_TEST_DEFAULT`: Set to `on` to enable DefaultCredentialProvider tests
-- `REQSIGN_GOOGLE_TEST_STATIC`: Set to `on` to enable StaticCredentialProvider tests
-- `REQSIGN_GOOGLE_TEST_AUTHORIZED_USER`: Set to `on` to enable AuthorizedUserCredentialProvider tests
-- `REQSIGN_GOOGLE_TEST_AUTHORIZED_USER_GCLOUD`: Set to `on` to test gcloud authorized user credentials
-- `REQSIGN_GOOGLE_TEST_EXTERNAL_ACCOUNT`: Set to `on` to enable ExternalAccountCredentialProvider tests with test data
-- `REQSIGN_GOOGLE_TEST_WORKLOAD_IDENTITY`: Set to `on` to enable real Workload Identity tests
-- `REQSIGN_GOOGLE_TEST_IMPERSONATED_SERVICE_ACCOUNT`: Set to `on` to enable ImpersonatedServiceAccountCredentialProvider tests
-- `REQSIGN_GOOGLE_TEST_IMPERSONATION_REAL`: Set to `on` to test with real impersonation credentials
-- `REQSIGN_GOOGLE_TEST_IMPERSONATION_DELEGATES`: Set to `on` to test impersonation with delegation chain
-- `REQSIGN_GOOGLE_TEST_VM_METADATA`: Set to `on` to enable VmMetadataCredentialProvider tests (GCP VMs only)
-- `REQSIGN_GOOGLE_TEST_VM_METADATA_MOCK`: Set to `on` to enable VmMetadataCredentialProvider tests with the local mock server
-- `REQSIGN_GOOGLE_TEST_CAB`: Set to `on` to enable the live CAB interoperability test
-- `REQSIGN_GOOGLE_TEST_SERVICE_ACCOUNT_TOKEN`: Set to `on` to enable the live service-account token provider test
-
-### Google Cloud Configuration
-- `GOOGLE_APPLICATION_CREDENTIALS`: Path to credential JSON file (supports all credential types)
-- `REQSIGN_GOOGLE_CREDENTIAL`: Base64-encoded service account JSON (for StaticCredentialProvider)
-- `REQSIGN_GOOGLE_CLOUD_STORAGE_SCOPE`: OAuth2 scope for GCS (e.g., `https://www.googleapis.com/auth/devstorage.read_write`)
-- `REQSIGN_GOOGLE_CLOUD_STORAGE_URL`: GCS bucket URL (e.g., `https://storage.googleapis.com/storage/v1/b/your-bucket`)
-- `REQSIGN_GOOGLE_CAB_SOURCE_TOKEN`: Service-account OAuth access token with the Cloud Platform scope
-- `REQSIGN_GOOGLE_CAB_SOURCE_EXPIRES_AT`: Absolute RFC 3339 expiration of the source token
-- `REQSIGN_GOOGLE_CAB_BUCKET`: Bucket used by the client-issued CAB live test
-- `REQSIGN_GOOGLE_CAB_OBJECT_PREFIX`: Non-empty object prefix used by the CAB list test
-- `GOOGLE_IMPERSONATED_CREDENTIALS`: Path to impersonated service account credential file
-- `GOOGLE_WORKLOAD_IDENTITY_PROVIDER`: Workload Identity Provider ID (for GitHub Actions)
-- `GOOGLE_SERVICE_ACCOUNT`: Service account email for Workload Identity
-
-## Running Tests
-
-### Local Development
-
-1. Copy `.env.example` to `.env` in the repository root
-2. Configure your Google Cloud credentials in the `.env` file
-3. Run tests using the provided script:
- ```bash
- cd services/google
- ./scripts/test.sh
- ```
-
-Or run specific test suites:
-```bash
-# Run only signing tests
-REQSIGN_GOOGLE_TEST=on cargo test signing::
-
-# Run only DefaultCredentialProvider tests
-REQSIGN_GOOGLE_TEST_DEFAULT=on cargo test test_default_credential_provider
-
-# Run all credential provider tests
-cargo test credential_providers::
-
-# Run the live CAB STS and Cloud Storage interoperability test
-REQSIGN_GOOGLE_TEST_CAB=on cargo test --features credential-access-boundary-client-side test_client_side_credential_access_boundary_live_interoperability
-
-# Run the live service-account token provider and server-side CAB interoperability test
-REQSIGN_GOOGLE_TEST_SERVICE_ACCOUNT_TOKEN=on cargo test test_service_account_token_provider_with_server_side_cab_live_interoperability
-```
-
-### GitHub Actions
-
-The tests are automatically run in GitHub Actions with the following setup:
-- Unit tests run on all PRs (no secrets required)
-- Integration tests only run on the main repository (not on forks)
-- Credentials are managed through 1Password Connect
+# Google Cloud Tests
+
+The Google test suite separates deterministic protocol coverage from live
+credential-provider acceptance. Deterministic tests replay sanitized responses
+captured from Google services. Live tests obtain a real credential and use it
+to read a fixed private Cloud Storage object containing
+`reqsign-live-google-ok\n`.
+
+## CI Contract
+
+The workflow runs on pull requests and pushes to `main`; it has no scheduled
+trigger.
+
+- Pull requests without 1Password Connect secrets, including fork and
+ Dependabot pull requests, run unit tests and sanitized response replays.
+- Pull requests that receive the Connect secrets run the deterministic suite
+ and every live test.
+- Every push to `main` runs the deterministic suite and every live test again.
+
+Live tests cover:
+
+- `StaticCredentialProvider`, `FileCredentialProvider`,
+ `EnvCredentialProvider`, `WellKnownCredentialProvider`, and
+ `DefaultCredentialProvider` with a service-account credential.
+- Authorized-user ADC refresh through Google OAuth.
+- GitHub OIDC workload identity through Security Token Service and IAM
+ Credentials, including caller-provided subject tokens.
+- `TokenCredentialProvider` with a live workload-identity access token.
+- Both the ADC-shaped and typed service-account impersonation providers.
+- IAM Credentials `generateAccessToken` and `signBlob`.
+- Server-side and client-side Credential Access Boundary flows.
+- `VmMetadataCredentialProvider` on an ephemeral private Compute Engine VM.
+- OAuth bearer signing and service-account signed URLs against Cloud Storage.
+
+Each provider must read the fixed probe successfully. Merely obtaining or
+parsing a token is not live acceptance.
+
+## Personal Google Cloud Resources
+
+All live resources belong to the personal `reqsign` project:
+
+- Bucket: `gs://reqsign`
+- Probe: `gs://reqsign/live/credential-ok`
+- CAB probe: `gs://reqsign/live/cab/allowed/credential-ok`
+- Metadata identity: `reqsign-metadata@reqsign.iam.gserviceaccount.com`
+- Impersonation target:
+ `reqsign-impersonated@reqsign.iam.gserviceaccount.com`
+- Runtime region: `us-east1`
+
+The metadata job builds the integration-test binary on GitHub, uploads it as a
+short-lived private object, and starts an `e2-micro` VM without a public IP.
+The VM has a 15-minute maximum runtime and automatic deletion. The workflow
+also removes the VM and binary in an unconditional cleanup step.
+
+## Live Test Variables
+
+| Variable | Purpose |
+| --- | --- |
+| `REQSIGN_GOOGLE_CLOUD_STORAGE_SCOPE` | OAuth scope used by Storage requests |
+| `REQSIGN_GOOGLE_CLOUD_STORAGE_PROBE_URL` | JSON API media URL for the fixed probe |
+| `REQSIGN_GOOGLE_CLOUD_STORAGE_SIGNED_PROBE_URL` | XML API URL for signed URL validation |
+| `REQSIGN_GOOGLE_CREDENTIAL` | Base64 service-account JSON |
+| `GOOGLE_APPLICATION_CREDENTIALS` | ADC credential file path |
+| `REQSIGN_GOOGLE_AUTHORIZED_USER_CREDENTIALS` | Authorized-user ADC file path |
+| `REQSIGN_GOOGLE_ACCESS_TOKEN` | Live token for token and typed impersonation providers |
+| `REQSIGN_GOOGLE_SUBJECT_TOKEN` | Caller-provided GitHub OIDC token |
+| `REQSIGN_GOOGLE_WORKLOAD_IDENTITY_AUDIENCE` | Google STS audience |
+| `GOOGLE_SERVICE_ACCOUNT` | WIF service account |
+| `REQSIGN_GOOGLE_IMPERSONATED_SERVICE_ACCOUNT` | Typed impersonation target |
+| `REQSIGN_GOOGLE_CAB_BUCKET` | CAB test bucket |
+| `REQSIGN_GOOGLE_CAB_OBJECT_PREFIX` | Allowed CAB object prefix |
+
+Provider-specific `REQSIGN_GOOGLE_TEST_*` variables gate live tests. CI sets
+them only on the exact live test step so deterministic runs never reach Google.
## 1Password Configuration
-The following secrets need to be configured in 1Password under the `reqsign/google` item:
-
-| Field | Description | Example |
-|-------|-------------|---------|
-| `credential_json` | Service account JSON content | `{"type": "service_account", ...}` |
-| `credential_base64` | Base64-encoded service account JSON | `eyJ0eXBlIjogInNlcnZpY2VfYWNjb3VudCIsIC4uLn0=` |
-| `storage_scope` | OAuth2 scope for GCS | `https://www.googleapis.com/auth/devstorage.read_write` |
-| `storage_url` | GCS bucket URL for testing | `https://storage.googleapis.com/storage/v1/b/test-bucket` |
-
-## Creating Test Credentials
-
-1. Create a service account in Google Cloud Console
-2. Grant the service account appropriate permissions (e.g., Storage Object Admin)
-3. Create and download a JSON key for the service account
-4. For base64 encoding: `base64 -i service-account.json | tr -d '\n'`
+GitHub Actions reads the existing `reqsign/google` item through 1Password
+Connect. The workflow uses these fields:
-## Credential Types Support
+- `credential_base64`
+- `authorized_user_base64`
+- `impersonated_sa_base64`
+- `workload_identity_provider`
+- `service_account_email`
-Google Cloud supports multiple credential types:
+No Google credential is available to fork or Dependabot pull-request jobs.
-1. **Service Account**: Standard service account with private key
-2. **Authorized User**: OAuth2 user credentials from `gcloud auth application-default login`
-3. **External Account**: Workload Identity Federation (GitHub Actions, AWS, Azure, etc.)
-4. **Impersonated Service Account**: Service account impersonation with delegation chain
-5. **VM Metadata**: Credentials from GCP VM metadata service
-
-The DefaultCredentialProvider automatically detects and handles all these types.
-
-## Notes
+## Running Tests
-- The VmMetadataCredentialProvider tests are disabled by default in CI as they require running on actual GCP VMs
-- CI runs a separate VmMetadataCredentialProvider test via the mock metadata server
-- External Account tests can run in GitHub Actions with proper Workload Identity setup
-- Impersonation tests require proper IAM permissions for the source credentials
-- Tests use real GCS API endpoints to verify signature validity
-- All tests are designed to be idempotent and safe to run repeatedly
-- Some credential provider tests use test data that will fail token exchange - this is expected
-- CAB unit tests use Google's non-secret Java auth-library keyset fixture. The live
- CAB test is opt-in because it requires a current OAuth access token with the Cloud Platform scope
- and a matching Cloud Storage bucket and prefix; it is not enabled by the repository CI secrets.
-- The live service-account token provider test is separately opt-in because it requires
- service-account JSON and a matching Cloud Storage bucket and prefix.
+Run deterministic tests and response replays:
-## Local STS Mock
+```bash
+cargo test -p reqsign-google --lib --tests --all-features --no-fail-fast
+```
-For local development without real Google Cloud credentials, you can run a simple STS mock:
+Live tests are disabled unless their exact gate variable is `on`. For example:
```bash
-python3 services/google/tests/mocks/sts_mock_server.py 5000
+REQSIGN_GOOGLE_TEST_STATIC=on \
+REQSIGN_GOOGLE_CREDENTIAL="$SERVICE_ACCOUNT_JSON_BASE64" \
+REQSIGN_GOOGLE_CLOUD_STORAGE_SCOPE=https://www.googleapis.com/auth/devstorage.read_only \
+REQSIGN_GOOGLE_CLOUD_STORAGE_PROBE_URL='https://storage.googleapis.com/storage/v1/b/reqsign/o/live%2Fcredential-ok?alt=media' \
+cargo test -p reqsign-google --test main \
+ credential_providers::static_provider:: -- --no-capture
```
-The example credential file `services/google/testdata/test_external_account.json` is configured to use this mock.
+## Updating Response Replays
+
+Files under `tests/fixtures/` must come from the corresponding real Google
+endpoint. Replace access tokens, refresh tokens, JWTs, private keys, session
+keys, account emails, and project identifiers before committing. Preserve
+field names, JSON types, optional-field presence, and time formats.
+
+A fixture update is accepted only after the same live path succeeds against
+Google Cloud Storage. Synthetic malformed, timeout, and transport cases may be
+derived from a captured response, but must not become the source for a success
+fixture.
+
+The repository currently contains captured success responses for authorized
+user OAuth, Compute Engine metadata, IAM Credentials `generateAccessToken`, and
+server-side CAB STS. Service-account OAuth, direct GitHub workload-identity
+STS, client-side CAB STS, and IAM Credentials `signBlob` still require captured
+success fixtures. Keep their live tests authoritative until those responses
+have been captured and sanitized; do not replace them with fabricated success
+fixtures.
diff --git a/services/google/tests/credential_access_boundary.rs b/services/google/tests/credential_access_boundary.rs
index e09735a..25d17d2 100644
--- a/services/google/tests/credential_access_boundary.rs
+++ b/services/google/tests/credential_access_boundary.rs
@@ -100,10 +100,27 @@ async fn test_client_side_credential_access_boundary_live_interoperability() ->
.map_err(|err| {
reqsign_core::Error::unexpected("client-side CAB live request failed").with_source(err)
})?;
+ let status = response.status();
+ let body = response.text().await.map_err(|err| {
+ reqsign_core::Error::unexpected("failed to read client-side CAB live response")
+ .with_source(err)
+ })?;
assert!(
- response.status().is_success(),
+ status.is_success(),
"client-issued CAB token was rejected with status {}",
- response.status()
+ status
+ );
+ let listing: serde_json::Value = serde_json::from_str(&body).map_err(|err| {
+ reqsign_core::Error::unexpected("client-side CAB live response was not valid JSON")
+ .with_source(err)
+ })?;
+ assert!(
+ listing["items"]
+ .as_array()
+ .is_some_and(|items| items.iter().any(|item| item["name"]
+ .as_str()
+ .is_some_and(|name| name.starts_with(&object_prefix)))),
+ "client-issued CAB token did not list the fixed probe object"
);
let disallowed_prefix = if object_prefix.starts_with('a') {
diff --git a/services/google/tests/credential_providers/authorized_user.rs b/services/google/tests/credential_providers/authorized_user.rs
index 539be2d..2a1ed7c 100644
--- a/services/google/tests/credential_providers/authorized_user.rs
+++ b/services/google/tests/credential_providers/authorized_user.rs
@@ -15,9 +15,9 @@
// specific language governing permissions and limitations
// under the License.
-use super::create_test_context_with_env;
+use super::{assert_provider_reads_probe, create_test_context_with_env};
use log::warn;
-use reqsign_core::{ProvideCredential, Result};
+use reqsign_core::Result;
use reqsign_google::DefaultCredentialProvider;
use std::collections::HashMap;
use std::env;
@@ -47,21 +47,7 @@ async fn test_authorized_user_credential_provider() -> Result<()> {
cred_path,
)]));
- let provider = DefaultCredentialProvider::new();
- let credential = provider
- .provide_credential(&ctx)
- .await?
- .expect("credential must be provided for authorized user");
-
- // Authorized user credentials should have a token
- assert!(credential.has_token(), "Must have access token");
- assert!(credential.has_valid_token(), "Token must be valid");
- assert!(
- !credential.has_service_account(),
- "Should not have service account"
- );
-
- Ok(())
+ assert_provider_reads_probe(DefaultCredentialProvider::new(), ctx).await
}
#[tokio::test]
@@ -86,18 +72,5 @@ async fn test_authorized_user_from_well_known_location() -> Result<()> {
// Don't set GOOGLE_APPLICATION_CREDENTIALS so it falls back to well-known location
let ctx = create_test_context_with_env(HashMap::new());
- let provider = DefaultCredentialProvider::new();
- let credential = provider
- .provide_credential(&ctx)
- .await?
- .expect("credential must be provided from well-known location");
-
- assert!(credential.has_token(), "Must have access token");
- assert!(credential.has_valid_token(), "Token must be valid");
- assert!(
- !credential.has_service_account(),
- "Should not have service account"
- );
-
- Ok(())
+ assert_provider_reads_probe(DefaultCredentialProvider::new(), ctx).await
}
diff --git a/services/google/tests/credential_providers/default.rs b/services/google/tests/credential_providers/default.rs
index 5076b51..5bb2cae 100644
--- a/services/google/tests/credential_providers/default.rs
+++ b/services/google/tests/credential_providers/default.rs
@@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-use super::create_test_context_with_env;
+use super::{assert_provider_reads_probe, create_test_context_with_env};
use log::warn;
use reqsign_core::{ProvideCredential, Result};
use reqsign_google::DefaultCredentialProvider;
@@ -37,27 +37,11 @@ async fn test_default_credential_provider() -> Result<()> {
cred_path,
)]));
- let provider = DefaultCredentialProvider::new();
- let credential = provider
- .provide_credential(&ctx)
- .await?
- .expect("credential must be provided");
-
- assert!(credential.has_service_account());
- let sa = credential.service_account.as_ref().unwrap();
- assert!(!sa.client_email.is_empty());
- assert!(!sa.private_key.is_empty());
-
- Ok(())
+ assert_provider_reads_probe(DefaultCredentialProvider::new(), ctx).await
}
#[tokio::test]
async fn test_default_credential_provider_with_json_file() -> Result<()> {
- if env::var("REQSIGN_GOOGLE_TEST_DEFAULT").unwrap_or_default() != "on" {
- warn!("REQSIGN_GOOGLE_TEST_DEFAULT is not set, skipped");
- return Ok(());
- }
-
// CI runs cargo test with working-directory = services/google.
let test_file_path = format!(
"{}/testdata/test_credential.json",
diff --git a/services/google/tests/credential_providers/env.rs b/services/google/tests/credential_providers/env.rs
new file mode 100644
index 0000000..133e6f3
--- /dev/null
+++ b/services/google/tests/credential_providers/env.rs
@@ -0,0 +1,58 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.
+
+use std::collections::HashMap;
+
+use log::warn;
+use reqsign_core::Result;
+use reqsign_google::{EnvCredentialProvider, WellKnownCredentialProvider};
+
+use super::{assert_provider_reads_probe, create_test_context_with_env};
+
+#[tokio::test]
+async fn test_env_credential_provider_live() -> Result<()> {
+ if std::env::var("REQSIGN_GOOGLE_TEST_ENV").unwrap_or_default() != "on" {
+ warn!("REQSIGN_GOOGLE_TEST_ENV is not set, skipped");
+ return Ok(());
+ }
+
+ let path = std::env::var("GOOGLE_APPLICATION_CREDENTIALS")
+ .expect("GOOGLE_APPLICATION_CREDENTIALS must be set");
+ let ctx = create_test_context_with_env(HashMap::from([(
+ "GOOGLE_APPLICATION_CREDENTIALS".to_string(),
+ path,
+ )]));
+
+ assert_provider_reads_probe(EnvCredentialProvider::new(), ctx).await
+}
+
+#[tokio::test]
+async fn test_well_known_credential_provider_live() -> Result<()> {
+ if std::env::var("REQSIGN_GOOGLE_TEST_WELL_KNOWN").unwrap_or_default() != "on" {
+ warn!("REQSIGN_GOOGLE_TEST_WELL_KNOWN is not set, skipped");
+ return Ok(());
+ }
+
+ let home = std::env::var("REQSIGN_GOOGLE_WELL_KNOWN_HOME")
+ .or_else(|_| std::env::var("HOME"))
+ .expect("HOME must be set");
+ assert_provider_reads_probe(
+ WellKnownCredentialProvider::new(),
+ create_test_context_with_env(HashMap::from([("HOME".to_string(), home)])),
+ )
+ .await
+}
diff --git a/services/google/tests/credential_providers/external_account.rs b/services/google/tests/credential_providers/external_account.rs
index 533c403..8c7acbb 100644
--- a/services/google/tests/credential_providers/external_account.rs
+++ b/services/google/tests/credential_providers/external_account.rs
@@ -15,61 +15,15 @@
// specific language governing permissions and limitations
// under the License.
-use super::create_test_context_with_env;
+use super::{assert_provider_reads_probe, create_test_context_with_env};
use log::warn;
-use reqsign_core::{ProvideCredential, Result};
-use reqsign_google::DefaultCredentialProvider;
+use reqsign_core::Result;
+use reqsign_google::{
+ DefaultCredentialProvider, ExternalAccountConfig, ExternalAccountCredentialProvider,
+};
use std::collections::HashMap;
use std::env;
-#[tokio::test]
-async fn test_external_account_credential_provider() -> Result<()> {
- if env::var("REQSIGN_GOOGLE_TEST_EXTERNAL_ACCOUNT").unwrap_or_default() != "on" {
- warn!("REQSIGN_GOOGLE_TEST_EXTERNAL_ACCOUNT is not set, skipped");
- return Ok(());
- }
-
- // This test requires a valid external account credential file
- let cred_path = env::var("REQSIGN_GOOGLE_EXTERNAL_ACCOUNT_CREDENTIALS")
- .expect("REQSIGN_GOOGLE_EXTERNAL_ACCOUNT_CREDENTIALS must be set for this test");
-
- // Verify the file exists and is an external_account type.
- // google-github-actions/auth writes compact JSON (`"type":"external_account"`).
- let content = std::fs::read_to_string(&cred_path)
- .expect("Failed to read external account credential file");
- let parsed: serde_json::Value =
- serde_json::from_str(&content).expect("credential file must be valid JSON");
- assert_eq!(
- parsed.get("type").and_then(|v| v.as_str()),
- Some("external_account"),
- "Credential file must be external_account type, got: {content}"
- );
-
- let ctx = create_test_context_with_env(HashMap::from_iter([
- ("GOOGLE_APPLICATION_CREDENTIALS".to_string(), cred_path),
- (
- "GOOGLE_SCOPE".to_string(),
- "https://www.googleapis.com/auth/devstorage.read_write".to_string(),
- ),
- ]));
-
- let provider = DefaultCredentialProvider::new();
-
- let credential = provider
- .provide_credential(&ctx)
- .await?
- .expect("credential must be provided for external account");
-
- assert!(credential.has_token(), "Must have access token");
- assert!(credential.has_valid_token(), "Token must be valid");
- assert!(
- !credential.has_service_account(),
- "Should not have service account"
- );
-
- Ok(())
-}
-
#[tokio::test]
async fn test_external_account_with_workload_identity() -> Result<()> {
if env::var("REQSIGN_GOOGLE_TEST_WORKLOAD_IDENTITY").unwrap_or_default() != "on" {
@@ -93,27 +47,41 @@ async fn test_external_account_with_workload_identity() -> Result<()> {
"Credential file must be external_account type for workload identity, got: {content}"
);
+ let scope = env::var("REQSIGN_GOOGLE_CLOUD_STORAGE_SCOPE")
+ .unwrap_or_else(|_| "https://www.googleapis.com/auth/devstorage.read_only".to_string());
let ctx = create_test_context_with_env(HashMap::from_iter([
("GOOGLE_APPLICATION_CREDENTIALS".to_string(), cred_path),
- (
- "GOOGLE_SCOPE".to_string(),
- "https://www.googleapis.com/auth/devstorage.read_write".to_string(),
- ),
+ ("GOOGLE_SCOPE".to_string(), scope),
]));
- let provider = DefaultCredentialProvider::new();
-
- let credential = provider
- .provide_credential(&ctx)
- .await?
- .expect("credential must be provided for workload identity");
+ assert_provider_reads_probe(DefaultCredentialProvider::new(), ctx).await
+}
- assert!(credential.has_token(), "Must have access token");
- assert!(credential.has_valid_token(), "Token must be valid");
- assert!(
- !credential.has_service_account(),
- "Should not have service account"
- );
+#[tokio::test]
+async fn test_external_account_with_caller_subject_token_live() -> Result<()> {
+ if env::var("REQSIGN_GOOGLE_TEST_WORKLOAD_IDENTITY").unwrap_or_default() != "on" {
+ warn!("REQSIGN_GOOGLE_TEST_WORKLOAD_IDENTITY is not set, skipped");
+ return Ok(());
+ }
- Ok(())
+ let subject_token =
+ env::var("REQSIGN_GOOGLE_SUBJECT_TOKEN").expect("REQSIGN_GOOGLE_SUBJECT_TOKEN must be set");
+ let audience = env::var("REQSIGN_GOOGLE_WORKLOAD_IDENTITY_AUDIENCE")
+ .expect("REQSIGN_GOOGLE_WORKLOAD_IDENTITY_AUDIENCE must be set");
+ let service_account =
+ env::var("GOOGLE_SERVICE_ACCOUNT").expect("GOOGLE_SERVICE_ACCOUNT must be set");
+ let scope = env::var("REQSIGN_GOOGLE_CLOUD_STORAGE_SCOPE")
+ .unwrap_or_else(|_| "https://www.googleapis.com/auth/devstorage.read_only".to_string());
+ let config = ExternalAccountConfig::new(
+ audience,
+ "urn:ietf:params:oauth:token-type:jwt",
+ "https://sts.googleapis.com/v1/token",
+ )
+ .with_service_account_impersonation_url(format!(
+ "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/{service_account}:generateAccessToken"
+ ));
+ let provider = ExternalAccountCredentialProvider::from_subject_token(config, subject_token)
+ .with_scope(scope);
+
+ assert_provider_reads_probe(provider, super::create_test_context()).await
}
diff --git a/services/google/tests/credential_providers/file.rs b/services/google/tests/credential_providers/file.rs
index 205b52e..3b49c44 100644
--- a/services/google/tests/credential_providers/file.rs
+++ b/services/google/tests/credential_providers/file.rs
@@ -15,7 +15,8 @@
// specific language governing permissions and limitations
// under the License.
-use super::create_test_context;
+use super::{assert_provider_reads_probe, create_test_context};
+use log::warn;
use reqsign_core::{ProvideCredential, Result};
use reqsign_google::FileCredentialProvider;
use std::env;
@@ -62,3 +63,15 @@ async fn test_file_credential_provider_missing_file() {
.expect_err("missing file must fail");
assert_eq!(reqsign_core::ErrorKind::Unexpected, err.kind());
}
+
+#[tokio::test]
+async fn test_file_credential_provider_live() -> Result<()> {
+ if env::var("REQSIGN_GOOGLE_TEST_FILE").unwrap_or_default() != "on" {
+ warn!("REQSIGN_GOOGLE_TEST_FILE is not set, skipped");
+ return Ok(());
+ }
+
+ let path = env::var("GOOGLE_APPLICATION_CREDENTIALS")
+ .expect("GOOGLE_APPLICATION_CREDENTIALS must be set");
+ assert_provider_reads_probe(FileCredentialProvider::new(path), create_test_context()).await
+}
diff --git a/services/google/tests/credential_providers/impersonated_service_account.rs b/services/google/tests/credential_providers/impersonated_service_account.rs
index dab620e..3b96942 100644
--- a/services/google/tests/credential_providers/impersonated_service_account.rs
+++ b/services/google/tests/credential_providers/impersonated_service_account.rs
@@ -15,9 +15,9 @@
// specific language governing permissions and limitations
// under the License.
-use super::create_test_context_with_env;
+use super::{assert_provider_reads_probe, create_test_context_with_env};
use log::warn;
-use reqsign_core::{ProvideCredential, Result};
+use reqsign_core::Result;
use reqsign_google::DefaultCredentialProvider;
use std::collections::HashMap;
use std::env;
@@ -42,29 +42,14 @@ async fn test_impersonated_service_account_credential_provider() -> Result<()> {
"Credential file must be impersonated_service_account type"
);
+ let scope = env::var("REQSIGN_GOOGLE_CLOUD_STORAGE_SCOPE")
+ .unwrap_or_else(|_| "https://www.googleapis.com/auth/devstorage.read_only".to_string());
let ctx = create_test_context_with_env(HashMap::from_iter([
("GOOGLE_APPLICATION_CREDENTIALS".to_string(), cred_path),
- (
- "GOOGLE_SCOPE".to_string(),
- "https://www.googleapis.com/auth/devstorage.read_write".to_string(),
- ),
+ ("GOOGLE_SCOPE".to_string(), scope),
]));
- let provider = DefaultCredentialProvider::new();
-
- let credential = provider
- .provide_credential(&ctx)
- .await?
- .expect("credential must be provided for impersonated service account");
-
- assert!(credential.has_token(), "Must have access token");
- assert!(credential.has_valid_token(), "Token must be valid");
- assert!(
- !credential.has_service_account(),
- "Should not have service account"
- );
-
- Ok(())
+ assert_provider_reads_probe(DefaultCredentialProvider::new(), ctx).await
}
#[tokio::test]
@@ -90,29 +75,14 @@ async fn test_impersonated_service_account_with_real_credentials() -> Result<()>
"Credential file must be impersonated_service_account type"
);
+ let scope = env::var("REQSIGN_GOOGLE_CLOUD_STORAGE_SCOPE")
+ .unwrap_or_else(|_| "https://www.googleapis.com/auth/devstorage.read_only".to_string());
let ctx = create_test_context_with_env(HashMap::from_iter([
("GOOGLE_APPLICATION_CREDENTIALS".to_string(), cred_path),
- (
- "GOOGLE_SCOPE".to_string(),
- "https://www.googleapis.com/auth/devstorage.read_write".to_string(),
- ),
+ ("GOOGLE_SCOPE".to_string(), scope),
]));
- let provider = DefaultCredentialProvider::new();
-
- let credential = provider
- .provide_credential(&ctx)
- .await?
- .expect("credential must be provided for real impersonation");
-
- assert!(credential.has_token(), "Must have access token");
- assert!(credential.has_valid_token(), "Token must be valid");
- assert!(
- !credential.has_service_account(),
- "Should not have service account"
- );
-
- Ok(())
+ assert_provider_reads_probe(DefaultCredentialProvider::new(), ctx).await
}
#[tokio::test]
@@ -138,27 +108,12 @@ async fn test_impersonated_service_account_with_delegates() -> Result<()> {
"Credential file must contain delegation chain"
);
+ let scope = env::var("REQSIGN_GOOGLE_CLOUD_STORAGE_SCOPE")
+ .unwrap_or_else(|_| "https://www.googleapis.com/auth/devstorage.read_only".to_string());
let ctx = create_test_context_with_env(HashMap::from_iter([
("GOOGLE_APPLICATION_CREDENTIALS".to_string(), cred_path),
- (
- "GOOGLE_SCOPE".to_string(),
- "https://www.googleapis.com/auth/devstorage.read_write".to_string(),
- ),
+ ("GOOGLE_SCOPE".to_string(), scope),
]));
- let provider = DefaultCredentialProvider::new();
-
- let credential = provider
- .provide_credential(&ctx)
- .await?
- .expect("credential must be provided for delegation chain");
-
- assert!(credential.has_token(), "Must have access token");
- assert!(credential.has_valid_token(), "Token must be valid");
- assert!(
- !credential.has_service_account(),
- "Should not have service account"
- );
-
- Ok(())
+ assert_provider_reads_probe(DefaultCredentialProvider::new(), ctx).await
}
diff --git a/services/google/tests/credential_providers/mod.rs b/services/google/tests/credential_providers/mod.rs
index f2409a8..ca448c2 100644
--- a/services/google/tests/credential_providers/mod.rs
+++ b/services/google/tests/credential_providers/mod.rs
@@ -17,18 +17,24 @@
mod authorized_user;
mod default;
+mod env;
mod external_account;
mod file;
mod impersonated_service_account;
+mod service_account_impersonation;
mod static_provider;
mod token;
mod vm_metadata;
-use reqsign_core::{Context, OsEnv, StaticEnv};
+use bytes::Bytes;
+use reqsign_core::{Context, Error, OsEnv, ProvideCredential, Signer, StaticEnv};
use reqsign_file_read_tokio::TokioFileRead;
+use reqsign_google::{Credential, RequestSigner};
use reqsign_http_send_reqwest::ReqwestHttpSend;
use std::collections::HashMap;
+const EXPECTED_PROBE_BODY: &[u8] = b"reqsign-live-google-ok\n";
+
pub fn create_test_context() -> Context {
let _ = env_logger::builder().is_test(true).try_init();
let _ = dotenvy::dotenv();
@@ -39,11 +45,15 @@ pub fn create_test_context() -> Context {
.with_env(OsEnv)
}
-pub fn create_test_context_with_env(envs: HashMap<String, String>) -> Context {
+pub fn create_test_context_with_env(mut envs: HashMap<String, String>) -> Context {
let _ = env_logger::builder().is_test(true).try_init();
let _ = dotenvy::dotenv();
let home_dir = std::env::var("HOME").ok().map(std::path::PathBuf::from);
+ if let Some(home) = &home_dir {
+ envs.entry("HOME".to_string())
+ .or_insert_with(|| home.to_string_lossy().into_owned());
+ }
let ctx = Context::new()
.with_file_read(TokioFileRead)
@@ -52,3 +62,40 @@ pub fn create_test_context_with_env(envs: HashMap<String, String>) -> Context {
ctx.with_env(StaticEnv { home_dir, envs })
}
+
+pub async fn assert_provider_reads_probe(
+ provider: impl ProvideCredential<Credential = Credential> + 'static,
+ ctx: Context,
+) -> reqsign_core::Result<()> {
+ let url = std::env::var("REQSIGN_GOOGLE_CLOUD_STORAGE_PROBE_URL")
+ .map_err(|_| Error::unexpected("REQSIGN_GOOGLE_CLOUD_STORAGE_PROBE_URL must be set"))?;
+ let scope = std::env::var("REQSIGN_GOOGLE_CLOUD_STORAGE_SCOPE")
+ .unwrap_or_else(|_| "https://www.googleapis.com/auth/devstorage.read_only".to_string());
+ let signer = Signer::new(
+ ctx.clone(),
+ provider,
+ RequestSigner::new("storage").with_scope(scope),
+ );
+ let request = http::Request::get(url).body(Bytes::new()).map_err(|err| {
+ Error::unexpected("failed to build Google Cloud Storage probe request").with_source(err)
+ })?;
+ let (mut parts, body) = request.into_parts();
+
+ signer.sign(&mut parts, None).await?;
+ let response = ctx
+ .http_send(http::Request::from_parts(parts, body))
+ .await?;
+
+ if response.status() != http::StatusCode::OK {
+ return Err(Error::unexpected(format!(
+ "Google Cloud Storage probe returned HTTP {}",
+ response.status()
+ )));
+ }
+ if response.body().as_ref() != EXPECTED_PROBE_BODY {
+ return Err(Error::unexpected(
+ "Google Cloud Storage probe returned an unexpected body",
+ ));
+ }
+ Ok(())
+}
diff --git a/services/google/tests/credential_providers/service_account_impersonation.rs b/services/google/tests/credential_providers/service_account_impersonation.rs
new file mode 100644
index 0000000..6a97c97
--- /dev/null
+++ b/services/google/tests/credential_providers/service_account_impersonation.rs
@@ -0,0 +1,101 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.
+
+use std::time::Duration;
+
+use log::warn;
+use reqsign_core::{Result, Signer};
+use reqsign_google::{
+ RequestSigner, ServiceAccountImpersonationCredentialProvider, ServiceAccountImpersonationGrant,
+ TokenCredentialProvider,
+};
+
+use super::{assert_provider_reads_probe, create_test_context};
+
+fn live_provider() -> ServiceAccountImpersonationCredentialProvider {
+ let source_token = std::env::var("REQSIGN_GOOGLE_ACCESS_TOKEN")
+ .expect("REQSIGN_GOOGLE_ACCESS_TOKEN must be set");
+ let target = std::env::var("REQSIGN_GOOGLE_IMPERSONATED_SERVICE_ACCOUNT")
+ .expect("REQSIGN_GOOGLE_IMPERSONATED_SERVICE_ACCOUNT must be set");
+ let source =
+ TokenCredentialProvider::new(source_token).with_expires_in(Duration::from_secs(1800));
+ // The resulting token reads the probe and calls IAM Credentials signBlob.
+ let grant = ServiceAccountImpersonationGrant::new(
+ target,
+ ["https://www.googleapis.com/auth/cloud-platform"],
+ );
+ ServiceAccountImpersonationCredentialProvider::new(source, grant)
+ .with_lifetime(Duration::from_secs(1800))
+}
+
+#[tokio::test]
+async fn test_service_account_impersonation_provider_live() -> Result<()> {
+ if std::env::var("REQSIGN_GOOGLE_TEST_SERVICE_ACCOUNT_IMPERSONATION").unwrap_or_default()
+ != "on"
+ {
+ warn!("REQSIGN_GOOGLE_TEST_SERVICE_ACCOUNT_IMPERSONATION is not set, skipped");
+ return Ok(());
+ }
+
+ assert_provider_reads_probe(live_provider(), create_test_context()).await
+}
+
+#[tokio::test]
+async fn test_service_account_impersonation_sign_blob_live() -> Result<()> {
+ if std::env::var("REQSIGN_GOOGLE_TEST_SERVICE_ACCOUNT_IMPERSONATION").unwrap_or_default()
+ != "on"
+ {
+ warn!("REQSIGN_GOOGLE_TEST_SERVICE_ACCOUNT_IMPERSONATION is not set, skipped");
+ return Ok(());
+ }
+
+ let url = std::env::var("REQSIGN_GOOGLE_CLOUD_STORAGE_SIGNED_PROBE_URL")
+ .expect("REQSIGN_GOOGLE_CLOUD_STORAGE_SIGNED_PROBE_URL must be set");
+ let ctx = create_test_context();
+ let signer = Signer::new(ctx, live_provider(), RequestSigner::new("storage"));
+ let request = http::Request::get(url)
+ .body("")
+ .expect("Google Cloud Storage signed probe request must build");
+ let (mut parts, body) = request.into_parts();
+ signer
+ .sign(&mut parts, Some(Duration::from_secs(300)))
+ .await?;
+
+ let response = reqwest::Client::new()
+ .execute(
+ http::Request::from_parts(parts, body)
+ .try_into()
+ .map_err(|err| {
+ reqsign_core::Error::unexpected(
+ "failed to convert signBlob signed probe request",
+ )
+ .with_source(err)
+ })?,
+ )
+ .await
+ .map_err(|err| {
+ reqsign_core::Error::unexpected("signBlob signed probe request failed").with_source(err)
+ })?;
+ let status = response.status();
+ let body = response.text().await.map_err(|err| {
+ reqsign_core::Error::unexpected("failed to read signBlob signed probe response")
+ .with_source(err)
+ })?;
+ assert_eq!(status, reqwest::StatusCode::OK);
+ assert_eq!(body, "reqsign-live-google-ok\n");
+ Ok(())
+}
diff --git a/services/google/tests/credential_providers/static_provider.rs b/services/google/tests/credential_providers/static_provider.rs
index 75727ce..e836cb0 100644
--- a/services/google/tests/credential_providers/static_provider.rs
+++ b/services/google/tests/credential_providers/static_provider.rs
@@ -15,9 +15,9 @@
// specific language governing permissions and limitations
// under the License.
-use super::create_test_context;
+use super::{assert_provider_reads_probe, create_test_context};
use log::warn;
-use reqsign_core::{ProvideCredential, Result};
+use reqsign_core::Result;
use reqsign_google::StaticCredentialProvider;
use std::env;
@@ -35,17 +35,7 @@ async fn test_static_credential_provider() -> Result<()> {
let provider = StaticCredentialProvider::from_base64(credential_content)
.expect("credential must be valid base64");
- let credential = provider
- .provide_credential(&ctx)
- .await?
- .expect("credential must be provided");
-
- assert!(credential.has_service_account());
- let sa = credential.service_account.as_ref().unwrap();
- assert!(!sa.client_email.is_empty());
- assert!(!sa.private_key.is_empty());
-
- Ok(())
+ assert_provider_reads_probe(provider, ctx).await
}
#[tokio::test]
@@ -65,16 +55,5 @@ async fn test_static_credential_provider_with_scope() -> Result<()> {
let provider = StaticCredentialProvider::from_base64(credential_content)
.expect("credential must be valid base64")
.with_scope(&scope);
- let credential = provider
- .provide_credential(&ctx)
- .await?
- .expect("credential must be provided");
-
- assert!(credential.has_service_account());
- // When a scope is provided, the provider may also fetch a token
- if credential.has_token() {
- assert!(credential.has_valid_token());
- }
-
- Ok(())
+ assert_provider_reads_probe(provider, ctx).await
}
diff --git a/services/google/tests/credential_providers/token.rs b/services/google/tests/credential_providers/token.rs
index 70790dd..3d432d1 100644
--- a/services/google/tests/credential_providers/token.rs
+++ b/services/google/tests/credential_providers/token.rs
@@ -15,7 +15,8 @@
// specific language governing permissions and limitations
// under the License.
-use super::create_test_context;
+use super::{assert_provider_reads_probe, create_test_context};
+use log::warn;
use reqsign_core::time::Timestamp;
use reqsign_core::{ErrorKind, ProvideCredential, Result};
use reqsign_google::TokenCredentialProvider;
@@ -90,3 +91,17 @@ async fn test_token_credential_provider_empty_token() {
.expect_err("empty token must fail");
assert_eq!(ErrorKind::CredentialInvalid, err.kind());
}
+
+#[tokio::test]
+async fn test_token_credential_provider_live() -> Result<()> {
+ if std::env::var("REQSIGN_GOOGLE_TEST_TOKEN").unwrap_or_default() != "on" {
+ warn!("REQSIGN_GOOGLE_TEST_TOKEN is not set, skipped");
+ return Ok(());
+ }
+
+ let access_token = std::env::var("REQSIGN_GOOGLE_ACCESS_TOKEN")
+ .expect("REQSIGN_GOOGLE_ACCESS_TOKEN must be set");
+ let provider =
+ TokenCredentialProvider::new(access_token).with_expires_in(Duration::from_secs(1800));
+ assert_provider_reads_probe(provider, create_test_context()).await
+}
diff --git a/services/google/tests/credential_providers/vm_metadata.rs b/services/google/tests/credential_providers/vm_metadata.rs
index 3f13b7d..6777b9f 100644
--- a/services/google/tests/credential_providers/vm_metadata.rs
+++ b/services/google/tests/credential_providers/vm_metadata.rs
@@ -15,9 +15,9 @@
// specific language governing permissions and limitations
// under the License.
-use super::create_test_context;
+use super::{assert_provider_reads_probe, create_test_context};
use log::warn;
-use reqsign_core::{ProvideCredential, Result};
+use reqsign_core::Result;
use reqsign_google::VmMetadataCredentialProvider;
use std::env;
@@ -31,41 +31,7 @@ async fn test_vm_metadata_credential_provider() -> Result<()> {
// This test should only run on actual GCP VMs
let ctx = create_test_context();
- let provider = VmMetadataCredentialProvider::new();
- let credential = provider
- .provide_credential(&ctx)
- .await?
- .expect("credential must be provided on GCP VM");
-
- assert!(credential.has_token(), "Must have access token");
- assert!(credential.has_valid_token(), "Token must be valid");
- let token = credential.token.as_ref().unwrap();
- assert!(!token.access_token.is_empty(), "Token must not be empty");
-
- Ok(())
-}
-
-#[tokio::test]
-async fn test_vm_metadata_credential_provider_with_mock() -> Result<()> {
- if env::var("REQSIGN_GOOGLE_TEST_VM_METADATA_MOCK").unwrap_or_default() != "on" {
- warn!("REQSIGN_GOOGLE_TEST_VM_METADATA_MOCK is not set, skipped");
- return Ok(());
- }
-
- let ctx = create_test_context();
-
- let provider = VmMetadataCredentialProvider::new();
- let credential = provider
- .provide_credential(&ctx)
- .await?
- .expect("credential must be provided with mock metadata server");
-
- assert!(credential.has_token(), "Must have access token");
- assert!(credential.has_valid_token(), "Token must be valid");
- let token = credential.token.as_ref().unwrap();
- assert!(!token.access_token.is_empty(), "Token must not be empty");
-
- Ok(())
+ assert_provider_reads_probe(VmMetadataCredentialProvider::new(), ctx).await
}
#[tokio::test]
@@ -81,14 +47,5 @@ async fn test_vm_metadata_credential_provider_with_scope() -> Result<()> {
let ctx = create_test_context();
- let provider = VmMetadataCredentialProvider::new().with_scope(&scope);
- let credential = provider
- .provide_credential(&ctx)
- .await?
- .expect("credential must be provided on GCP VM");
-
- assert!(credential.has_token(), "Must have access token");
- assert!(credential.has_valid_token(), "Token must be valid");
-
- Ok(())
+ assert_provider_reads_probe(VmMetadataCredentialProvider::new().with_scope(&scope), ctx).await
}
diff --git a/services/google/tests/fixtures.rs b/services/google/tests/fixtures.rs
new file mode 100644
index 0000000..73fe8b0
--- /dev/null
+++ b/services/google/tests/fixtures.rs
@@ -0,0 +1,83 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.
+
+use std::fs;
+use std::path::Path;
+
+fn assert_secret_fields_are_redacted(value: &serde_json::Value, path: &Path) {
+ match value {
+ serde_json::Value::Object(fields) => {
+ for (key, value) in fields {
+ if matches!(
+ key.as_str(),
+ "access_token"
+ | "accessToken"
+ | "id_token"
+ | "refresh_token"
+ | "client_secret"
+ | "private_key"
+ | "access_boundary_session_key"
+ ) {
+ let redacted = value.as_str().is_some_and(|value| {
+ value == "REDACTED" || value.starts_with("DERIVED_TEST_")
+ });
+ assert!(redacted, "secret field {key} is not redacted in {path:?}");
+ }
+ assert_secret_fields_are_redacted(value, path);
+ }
+ }
+ serde_json::Value::Array(values) => {
+ for value in values {
+ assert_secret_fields_are_redacted(value, path);
+ }
+ }
+ _ => {}
+ }
+}
+
+#[test]
+fn google_response_fixtures_are_valid_json_and_redacted() {
+ let fixture_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
+ let mut fixture_count = 0;
+
+ for entry in fs::read_dir(&fixture_dir).expect("Google fixture directory must exist") {
+ let path = entry.expect("fixture entry must be readable").path();
+ if path.extension().and_then(|value| value.to_str()) != Some("json") {
+ continue;
+ }
+ fixture_count += 1;
+ let content = fs::read(&path).expect("Google fixture must be readable");
+ let value: serde_json::Value =
+ serde_json::from_slice(&content).expect("Google fixture must contain valid JSON");
+ assert_secret_fields_are_redacted(&value, &path);
+
+ let text = String::from_utf8(content).expect("Google fixture must be UTF-8");
+ for forbidden in [
+ "-----BEGIN PRIVATE KEY-----",
+ "-----BEGIN RSA PRIVATE KEY-----",
+ "ya29.",
+ "@gmail.com",
+ ] {
+ assert!(
+ !text.contains(forbidden),
+ "fixture contains forbidden credential material in {path:?}"
+ );
+ }
+ }
+
+ assert!(fixture_count > 0, "Google response fixtures must exist");
+}
diff --git a/services/google/tests/fixtures/authorized_user_token_response.json b/services/google/tests/fixtures/authorized_user_token_response.json
new file mode 100644
index 0000000..c5fb2f3
--- /dev/null
+++ b/services/google/tests/fixtures/authorized_user_token_response.json
@@ -0,0 +1,7 @@
+{
+ "access_token": "REDACTED",
+ "expires_in": 3599,
+ "scope": "https://www.googleapis.com/auth/sqlservice.login https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/userinfo.email openid https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/accounts.reauth",
+ "token_type": "Bearer",
+ "id_token": "REDACTED"
+}
diff --git a/services/google/tests/fixtures/iam_generate_access_token_response.json b/services/google/tests/fixtures/iam_generate_access_token_response.json
new file mode 100644
index 0000000..8c64396
--- /dev/null
+++ b/services/google/tests/fixtures/iam_generate_access_token_response.json
@@ -0,0 +1,4 @@
+{
+ "accessToken": "REDACTED",
+ "expireTime": "2026-09-03T13:30:38Z"
+}
diff --git a/services/google/tests/fixtures/server_side_cab_sts_response.json b/services/google/tests/fixtures/server_side_cab_sts_response.json
new file mode 100644
index 0000000..ff7e2b2
--- /dev/null
+++ b/services/google/tests/fixtures/server_side_cab_sts_response.json
@@ -0,0 +1,5 @@
+{
+ "access_token": "REDACTED",
+ "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
+ "token_type": "Bearer"
+}
diff --git a/services/google/tests/fixtures/vm_metadata_token_response.json b/services/google/tests/fixtures/vm_metadata_token_response.json
new file mode 100644
index 0000000..aaf1048
--- /dev/null
+++ b/services/google/tests/fixtures/vm_metadata_token_response.json
@@ -0,0 +1,5 @@
+{
+ "access_token": "REDACTED",
+ "expires_in": 3557,
+ "token_type": "Bearer"
+}
diff --git a/services/google/tests/mocks/sts_mock_server.py b/services/google/tests/mocks/sts_mock_server.py
deleted file mode 100644
index a54e7b3..0000000
--- a/services/google/tests/mocks/sts_mock_server.py
+++ /dev/null
@@ -1,140 +0,0 @@
-#!/usr/bin/env python3
-"""
-Mock server for Google STS and external account credential sources.
-
-This server provides:
-- GET /token : returns an OIDC subject token in JSON format
-- POST /v1/token : accepts RFC 8693 token exchange via application/x-www-form-urlencoded
-- POST */:generateAccessToken : simulates IAMCredentials generateAccessToken (optional)
-
-It is intended for local testing with services/google/testdata/test_external_account.json.
-"""
-
-import json
-import sys
-import time
-from datetime import datetime, timedelta, timezone
-from http.server import BaseHTTPRequestHandler, HTTPServer
-from urllib.parse import parse_qs
-
-
-def _read_body(handler: BaseHTTPRequestHandler) -> bytes:
- length = int(handler.headers.get("Content-Length", "0"))
- if length <= 0:
- return b""
- return handler.rfile.read(length)
-
-
-class StsHandler(BaseHTTPRequestHandler):
- def do_GET(self):
- if self.path == "/token":
- self._handle_subject_token()
- return
-
- self.send_error(404, "Not Found")
-
- def do_POST(self):
- if self.path == "/v1/token":
- self._handle_sts_token_exchange()
- return
-
- if self.path.endswith(":generateAccessToken"):
- self._handle_generate_access_token()
- return
-
- self.send_error(404, "Not Found")
-
- def _handle_subject_token(self):
- token_response = {
- "id_token": "mock-oidc-subject-token",
- }
- self.send_response(200)
- self.send_header("Content-Type", "application/json")
- self.end_headers()
- self.wfile.write(json.dumps(token_response).encode())
-
- def _handle_sts_token_exchange(self):
- content_type = self.headers.get("Content-Type", "")
- if not content_type.startswith("application/x-www-form-urlencoded"):
- self.send_error(
- 415,
- "Content-Type must be application/x-www-form-urlencoded for STS token exchange",
- )
- return
-
- body = _read_body(self).decode("utf-8", errors="replace")
- values = {k: v[0] for k, v in parse_qs(body, keep_blank_values=True).items()}
-
- required = [
- "grant_type",
- "requested_token_type",
- "audience",
- "scope",
- "subject_token",
- "subject_token_type",
- ]
- missing = [k for k in required if not values.get(k)]
- if missing:
- self.send_error(400, f"Missing required form fields: {', '.join(missing)}")
- return
-
- if values["grant_type"] != "urn:ietf:params:oauth:grant-type:token-exchange":
- self.send_error(400, "Invalid grant_type")
- return
- if values["requested_token_type"] != "urn:ietf:params:oauth:token-type:access_token":
- self.send_error(400, "Invalid requested_token_type")
- return
-
- token_response = {
- "access_token": f"mock-sts-access-token-{int(time.time())}",
- "expires_in": 3600,
- "token_type": "Bearer",
- }
- self.send_response(200)
- self.send_header("Content-Type", "application/json")
- self.end_headers()
- self.wfile.write(json.dumps(token_response).encode())
-
- def _handle_generate_access_token(self):
- auth = self.headers.get("Authorization", "")
- if not auth.startswith("Bearer "):
- self.send_error(401, "Authorization: Bearer <token> required")
- return
-
- expires_in = 3600
- expire_time = datetime.now(timezone.utc) + timedelta(seconds=expires_in)
- token_response = {
- "accessToken": f"mock-impersonated-access-token-{int(time.time())}",
- "expireTime": expire_time.isoformat().replace("+00:00", "Z"),
- }
- self.send_response(200)
- self.send_header("Content-Type", "application/json")
- self.end_headers()
- self.wfile.write(json.dumps(token_response).encode())
-
- def log_message(self, format, *args):
- sys.stderr.write(
- f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {format % args}\n"
- )
-
-
-def run_server(port: int = 5000):
- server_address = ("127.0.0.1", port)
- httpd = HTTPServer(server_address, StsHandler)
- print(f"Mock Google STS Server running on http://127.0.0.1:{port}")
- print("Press Ctrl+C to stop")
- print("")
- print("Endpoints:")
- print(f" GET http://127.0.0.1:{port}/token")
- print(f" POST http://127.0.0.1:{port}/v1/token")
- print(
- f" POST http://127.0.0.1:{port}/v1/projects/-/serviceAccounts/test@example.com:generateAccessToken"
- )
- httpd.serve_forever()
-
-
-if __name__ == "__main__":
- port = 5000
- if len(sys.argv) > 1:
- port = int(sys.argv[1])
- run_server(port)
diff --git a/services/google/tests/mocks/vm_metadata_mock_server.py b/services/google/tests/mocks/vm_metadata_mock_server.py
deleted file mode 100644
index da64ce9..0000000
--- a/services/google/tests/mocks/vm_metadata_mock_server.py
+++ /dev/null
@@ -1,114 +0,0 @@
-#!/usr/bin/env python3
-"""
-Mock server for Google Cloud VM Metadata Service.
-
-This server simulates the GCP metadata service that runs on 169.254.169.254
-and provides instance metadata and service account tokens.
-"""
-
-import json
-import sys
-import time
-from datetime import datetime, timedelta, timezone
-from http.server import BaseHTTPRequestHandler, HTTPServer
-
-
-class MetadataHandler(BaseHTTPRequestHandler):
- """Handler for GCP metadata service requests."""
-
- def do_GET(self):
- """Handle GET requests to metadata endpoints."""
- # Check for required Metadata-Flavor header
- if self.headers.get("Metadata-Flavor") != "Google":
- self.send_error(
- 403, "Metadata-Flavor: Google header required"
- )
- return
-
- # Route to appropriate handler based on path
- if self.path == "/computeMetadata/v1/instance/service-accounts/":
- self.handle_list_service_accounts()
- elif self.path == "/computeMetadata/v1/instance/service-accounts/default/":
- self.handle_default_service_account()
- elif self.path.startswith(
- "/computeMetadata/v1/instance/service-accounts/default/token"
- ):
- self.handle_token_request()
- elif self.path == "/computeMetadata/v1/instance/service-accounts/default/email":
- self.handle_email_request()
- else:
- self.send_error(404, "Not Found")
-
- def handle_list_service_accounts(self):
- """List available service accounts."""
- self.send_response(200)
- self.send_header("Content-Type", "text/plain")
- self.end_headers()
- self.wfile.write(b"default/\n")
-
- def handle_default_service_account(self):
- """Get default service account info."""
- self.send_response(200)
- self.send_header("Content-Type", "text/plain")
- self.end_headers()
- response = "aliases\nemail\nidentity\nscopes\ntoken\n"
- self.wfile.write(response.encode())
-
- def handle_email_request(self):
- """Return the service account email."""
- self.send_response(200)
- self.send_header("Content-Type", "text/plain")
- self.end_headers()
- email = "test-vm-sa@test-project.iam.gserviceaccount.com"
- self.wfile.write(email.encode())
-
- def handle_token_request(self):
- """Generate and return an access token."""
- # Parse query parameters for scopes
- scopes = None
- if "?" in self.path:
- query_string = self.path.split("?")[1]
- for param in query_string.split("&"):
- if param.startswith("scopes="):
- scopes = param.split("=")[1]
-
- # Generate token response
- expires_in = 3600
- expires_at = datetime.now(timezone.utc) + timedelta(seconds=expires_in)
-
- token_response = {
- "access_token": f"mock-vm-metadata-token-{int(time.time())}",
- "expires_in": expires_in,
- "token_type": "Bearer",
- }
-
- self.send_response(200)
- self.send_header("Content-Type", "application/json")
- self.end_headers()
- self.wfile.write(json.dumps(token_response).encode())
-
- def log_message(self, format, *args):
- """Override to provide custom logging format."""
- sys.stderr.write(
- f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {format % args}\n"
- )
-
-
-def run_server(port=8080):
- """Run the mock metadata server."""
- server_address = ("127.0.0.1", port)
- httpd = HTTPServer(server_address, MetadataHandler)
- print(f"Mock GCP Metadata Server running on http://127.0.0.1:{port}")
- print("Press Ctrl+C to stop")
- print("")
- print("Test with:")
- print(f" curl -H 'Metadata-Flavor: Google' http://127.0.0.1:{port}/computeMetadata/v1/instance/service-accounts/default/token")
- print("")
- httpd.serve_forever()
-
-
-if __name__ == "__main__":
- port = 8080
- if len(sys.argv) > 1:
- port = int(sys.argv[1])
- run_server(port)
\ No newline at end of file
diff --git a/services/google/tests/service_account_token.rs b/services/google/tests/service_account_token.rs
index c4ddafd..d6d02b6 100644
--- a/services/google/tests/service_account_token.rs
+++ b/services/google/tests/service_account_token.rs
@@ -98,10 +98,27 @@ async fn test_service_account_token_provider_with_server_side_cab_live_interoper
reqsign_core::Error::unexpected("service-account token live request failed")
.with_source(err)
})?;
+ let status = response.status();
+ let body = response.text().await.map_err(|err| {
+ reqsign_core::Error::unexpected("failed to read server-side CAB live response")
+ .with_source(err)
+ })?;
assert!(
- response.status().is_success(),
+ status.is_success(),
"server-issued CAB token was rejected with status {}",
- response.status()
+ status
+ );
+ let listing: serde_json::Value = serde_json::from_str(&body).map_err(|err| {
+ reqsign_core::Error::unexpected("server-side CAB live response was not valid JSON")
+ .with_source(err)
+ })?;
+ assert!(
+ listing["items"]
+ .as_array()
+ .is_some_and(|items| items.iter().any(|item| item["name"]
+ .as_str()
+ .is_some_and(|name| name.starts_with(&object_prefix)))),
+ "server-issued CAB token did not list the fixed probe object"
);
let disallowed_prefix = if object_prefix.starts_with('a') {
diff --git a/services/google/tests/signing/signed_url.rs b/services/google/tests/signing/signed_url.rs
index d2b5fb9..1a531ca 100644
--- a/services/google/tests/signing/signed_url.rs
+++ b/services/google/tests/signing/signed_url.rs
@@ -56,16 +56,12 @@ async fn test_get_object_with_signed_url() -> Result<()> {
return Ok(());
};
- let url = &env::var("REQSIGN_GOOGLE_CLOUD_STORAGE_URL")
- .expect("env REQSIGN_GOOGLE_CLOUD_STORAGE_URL must set");
+ let url = &env::var("REQSIGN_GOOGLE_CLOUD_STORAGE_SIGNED_PROBE_URL")
+ .expect("env REQSIGN_GOOGLE_CLOUD_STORAGE_SIGNED_PROBE_URL must be set");
let mut builder = http::Request::builder();
builder = builder.method(http::Method::GET);
- builder = builder.uri(format!(
- "{}/{}",
- url.replace("storage/v1/b/", ""),
- "not_exist_file"
- ));
+ builder = builder.uri(url);
let req = builder.body("").map_err(|e| {
reqsign_core::Error::unexpected("failed to build HTTP request").with_source(e)
})?;
@@ -88,14 +84,12 @@ async fn test_get_object_with_signed_url() -> Result<()> {
.expect("request must succeed");
let code = resp.status();
- debug!("got response: {resp:?}");
- debug!(
- "got body: {}",
- resp.text().await.map_err(|e| {
- reqsign_core::Error::unexpected("failed to read response body").with_source(e)
- })?
- );
- assert_eq!(StatusCode::NOT_FOUND, code);
+ let body = resp.text().await.map_err(|e| {
+ reqsign_core::Error::unexpected("failed to read response body").with_source(e)
+ })?;
+ debug!("got response status: {code}");
+ assert_eq!(StatusCode::OK, code);
+ assert_eq!("reqsign-live-google-ok\n", body);
Ok(())
}
diff --git a/services/google/tests/signing/standard.rs b/services/google/tests/signing/standard.rs
index fc7d553..e9ced1e 100644
--- a/services/google/tests/signing/standard.rs
+++ b/services/google/tests/signing/standard.rs
@@ -57,12 +57,12 @@ async fn test_get_object() -> Result<()> {
return Ok(());
};
- let url = &env::var("REQSIGN_GOOGLE_CLOUD_STORAGE_URL")
- .expect("env REQSIGN_GOOGLE_CLOUD_STORAGE_URL must set");
+ let url = &env::var("REQSIGN_GOOGLE_CLOUD_STORAGE_PROBE_URL")
+ .expect("env REQSIGN_GOOGLE_CLOUD_STORAGE_PROBE_URL must be set");
let mut builder = http::Request::builder();
builder = builder.method(http::Method::GET);
- builder = builder.uri(format!("{}/o/{}", url, "not_exist_file"));
+ builder = builder.uri(url);
let req = builder.body("").map_err(|e| {
reqsign_core::Error::unexpected("failed to build HTTP request").with_source(e)
})?;
@@ -84,8 +84,13 @@ async fn test_get_object() -> Result<()> {
.await
.expect("request must succeed");
- debug!("got response: {resp:?}");
- assert_eq!(StatusCode::NOT_FOUND, resp.status());
+ let status = resp.status();
+ let body = resp.text().await.map_err(|e| {
+ reqsign_core::Error::unexpected("failed to read response body").with_source(e)
+ })?;
+ debug!("got response status: {status}");
+ assert_eq!(StatusCode::OK, status);
+ assert_eq!("reqsign-live-google-ok\n", body);
Ok(())
}