Skip to main content

Google Cloud client library for kiarina namespace

Project description

kiarina-lib-google

A Python library for Google Cloud authentication with configuration management using pydantic-settings-manager.

Features

  • Multiple Authentication Methods: Default credentials (ADC), service accounts, and user accounts
  • Service Account Impersonation: Delegated access with configurable scopes
  • Configuration Management: Flexible configuration with pydantic-settings-manager
  • Credentials Caching: Automatic caching and refresh for user accounts
  • Self-Signed JWT: Generate JWTs for service account authentication
  • Type Safety: Full type hints and Pydantic validation

Installation

pip install kiarina-lib-google

Quick Start

Default Credentials (ADC)

from kiarina.lib.google import get_credentials

# Uses Application Default Credentials
credentials = get_credentials()

Service Account

from kiarina.lib.google import get_credentials, GoogleSettings

# From key file
credentials = get_credentials(
    settings=GoogleSettings(
        type="service_account",
        service_account_file="~/path/to/key.json"
    )
)

# From JSON data
credentials = get_credentials(
    settings=GoogleSettings(
        type="service_account",
        service_account_data='{"type":"service_account",...}'
    )
)

User Account (OAuth2)

# From authorized user file
credentials = get_credentials(
    settings=GoogleSettings(
        type="user_account",
        authorized_user_file="~/.config/gcloud/application_default_credentials.json",
        scopes=["https://www.googleapis.com/auth/drive"]
    )
)

Service Account Impersonation

# Impersonate a service account
credentials = get_credentials(
    settings=GoogleSettings(
        type="service_account",
        service_account_file="~/source-key.json",
        impersonate_service_account="target@project.iam.gserviceaccount.com",
        scopes=["https://www.googleapis.com/auth/cloud-platform"]
    )
)

Note: Source principal requires roles/iam.serviceAccountTokenCreator role.

Credentials Caching

from kiarina.lib.google import CredentialsCache

class InMemoryCache(CredentialsCache):
    def __init__(self):
        self._cache: str | None = None

    def get(self) -> str | None:
        return self._cache

    def set(self, value: str) -> None:
        self._cache = value

# Use cache for user account credentials
credentials = get_credentials(
    settings=GoogleSettings(
        type="user_account",
        authorized_user_file="~/authorized-user.json",
        scopes=["https://www.googleapis.com/auth/drive"]
    ),
    cache=InMemoryCache()
)

Self-Signed JWT

from kiarina.lib.google import get_self_signed_jwt

jwt_token = get_self_signed_jwt(
    settings=GoogleSettings(
        type="service_account",
        service_account_file="~/key.json"
    ),
    audience="https://your-service.example.com/"
)

Configuration

YAML Configuration (Recommended)

kiarina.lib.google:
  development:
    type: user_account
    authorized_user_file: ~/.config/gcloud/application_default_credentials.json
    scopes:
      - https://www.googleapis.com/auth/cloud-platform

  production:
    type: service_account
    service_account_file: /secrets/prod-sa-key.json
    project_id: your-project-id
    scopes:
      - https://www.googleapis.com/auth/cloud-platform

  impersonation:
    type: service_account
    service_account_file: ~/source-key.json
    impersonate_service_account: target@project.iam.gserviceaccount.com
    scopes:
      - https://www.googleapis.com/auth/cloud-platform

Load configuration:

from pydantic_settings_manager import load_user_configs
import yaml

with open("config.yaml") as f:
    config = yaml.safe_load(f)
    load_user_configs(config)

# Use configured credentials
from kiarina.lib.google import get_credentials
credentials = get_credentials("production")

Environment Variables

export KIARINA_LIB_GOOGLE_TYPE="service_account"
export KIARINA_LIB_GOOGLE_SERVICE_ACCOUNT_FILE="~/key.json"
export KIARINA_LIB_GOOGLE_PROJECT_ID="your-project-id"
export KIARINA_LIB_GOOGLE_SCOPES="https://www.googleapis.com/auth/cloud-platform"

Programmatic Configuration

from kiarina.lib.google import settings_manager

settings_manager.user_config = {
    "dev": {
        "type": "user_account",
        "authorized_user_file": "~/.config/gcloud/application_default_credentials.json"
    },
    "prod": {
        "type": "service_account",
        "service_account_file": "/secrets/key.json"
    }
}

settings_manager.active_key = "prod"
credentials = get_credentials()

API Reference

Main Functions

get_credentials(settings_key=None, *, settings=None, scopes=None, cache=None)

Get Google Cloud credentials based on configuration.

Parameters:

  • settings_key (str | None): Configuration key for multi-config setup
  • settings (GoogleSettings | None): Settings object (overrides settings_key)
  • scopes (list[str] | None): OAuth2 scopes (overrides settings.scopes)
  • cache (CredentialsCache | None): Credentials cache for user accounts

Returns: Credentials - Google Cloud credentials

get_self_signed_jwt(settings_key=None, *, settings=None, audience)

Generate a self-signed JWT for service account authentication.

Parameters:

  • settings_key (str | None): Configuration key
  • settings (GoogleSettings | None): Settings object
  • audience (str): JWT audience (target service URL)

Returns: str - Self-signed JWT token

Utility Functions

get_default_credentials()

Get default credentials using Application Default Credentials (ADC).

Returns: Credentials

get_service_account_credentials(*, service_account_file=None, service_account_data=None)

Get service account credentials from file or data.

Returns: google.oauth2.service_account.Credentials

get_user_account_credentials(*, authorized_user_file=None, authorized_user_data=None, scopes, cache=None)

Get user account credentials from file or data with optional caching.

Returns: google.oauth2.credentials.Credentials

Configuration

GoogleSettings

Pydantic settings model for authentication configuration.

Key Fields:

  • type: Authentication type ("default", "service_account", "user_account")
  • service_account_file: Path to service account key file
  • service_account_data: Service account key data (JSON string, SecretStr)
  • authorized_user_file: Path to authorized user file
  • authorized_user_data: Authorized user data (JSON string, SecretStr)
  • impersonate_service_account: Target service account email for impersonation
  • scopes: OAuth2 scopes (default: cloud-platform, drive, spreadsheets)
  • project_id: GCP project ID

Helper Methods:

  • get_service_account_data(): Parse service_account_data JSON
  • get_client_secret_data(): Parse client_secret_data JSON
  • get_authorized_user_data(): Parse authorized_user_data JSON

CredentialsCache (Protocol)

Protocol for implementing credentials cache.

Methods:

  • get() -> str | None: Retrieve cached credentials (JSON string)
  • set(value: str) -> None: Store credentials (JSON string)

Authentication Priority

Default Credentials

Uses Application Default Credentials (ADC) in this order:

  1. GOOGLE_APPLICATION_CREDENTIALS environment variable (service account)
  2. gcloud auth application-default login credentials (user account)
  3. Compute Engine metadata server (compute engine)

Default Scopes

  • https://www.googleapis.com/auth/cloud-platform - All GCP resources
  • https://www.googleapis.com/auth/drive - Google Drive
  • https://www.googleapis.com/auth/spreadsheets - Google Sheets

Override by specifying custom scopes in configuration or function call.

Testing

Setup Test Configuration

[!Note] ADC tests Tests that depend on default credentials (ADC) require you to be authenticated with Google Cloud. Run gcloud auth application-default login before running the tests.

# Copy sample configuration
cp packages/kiarina-lib-google/test_settings.sample.yaml \
   packages/kiarina-lib-google/test_settings.yaml

# Edit with your credentials
# Set environment variable
export KIARINA_LIB_GOOGLE_TEST_SETTINGS_FILE="packages/kiarina-lib-google/test_settings.yaml"

Run Tests

# Run all checks
mise run package kiarina-lib-google

# Run tests with coverage
mise run package:test kiarina-lib-google --coverage

Dependencies

License

MIT License - see the LICENSE file for details.

Related Projects

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

kiarina_lib_google-2.0.0.tar.gz (10.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

kiarina_lib_google-2.0.0-py3-none-any.whl (10.3 kB view details)

Uploaded Python 3

File details

Details for the file kiarina_lib_google-2.0.0.tar.gz.

File metadata

  • Download URL: kiarina_lib_google-2.0.0.tar.gz
  • Upload date:
  • Size: 10.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for kiarina_lib_google-2.0.0.tar.gz
Algorithm Hash digest
SHA256 ece9f2713fe1af862e96d6186a3f7b71cbb79c9773ff6c2d85b085c71e422633
MD5 6c1c08751935f5010652d42a52f398db
BLAKE2b-256 9a94fd38a8a964195a8684354eaddaa303e05e0ba1e1eba46d1fca54dd14efab

See more details on using hashes here.

File details

Details for the file kiarina_lib_google-2.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for kiarina_lib_google-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6c36bb823d581c6796bfdb77cf4ec3c97df880c4c08d9f31d9f15329b11911d9
MD5 d0aa8c1baea5871f361fb1e441bd855c
BLAKE2b-256 7ad3053ba810e664ae972424e7d60ef73c1a5411d7341be082cf856caf8b2ca9

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page