# kiarina-lib-google-auth
A Python client library for Google Cloud authentication with configuration management and support for multiple credential types.
## Features
- **Multiple Authentication Methods**: Support for default credentials, service accounts, and user accounts
- **Service Account Impersonation**: Impersonate service accounts for delegated access
- **Configuration Management**: Use `pydantic-settings-manager` for flexible configuration
- **Credentials Caching**: Cache and refresh user account credentials automatically
- **Self-Signed JWT**: Generate self-signed JWTs for service accounts
- **Type Safety**: Full type hints and Pydantic validation
## Installation
```bash
pip install kiarina-lib-google-auth
```
## Quick Start
### Basic Usage with Default Credentials
```python
from kiarina.lib.google.auth import get_credentials
# Get default credentials (ADC, service account, or compute engine)
credentials = get_credentials()
```
### Service Account Authentication
```python
from kiarina.lib.google.auth import get_credentials, GoogleAuthSettings
# From service account key file
credentials = get_credentials(
settings=GoogleAuthSettings(
type="service_account",
service_account_file="~/path/to/service-account-key.json"
)
)
# From service account key data (JSON string)
import json
credentials = get_credentials(
settings=GoogleAuthSettings(
type="service_account",
service_account_data=json.dumps({
"type": "service_account",
"project_id": "your-project",
"private_key_id": "...",
"private_key": "...",
"client_email": "...",
# ... other fields
})
)
)
```
### User Account Authentication
```python
from kiarina.lib.google.auth import get_credentials, GoogleAuthSettings
# From authorized user file (OAuth2 credentials)
credentials = get_credentials(
settings=GoogleAuthSettings(
type="user_account",
authorized_user_file="~/path/to/authorized-user.json",
scopes=["https://www.googleapis.com/auth/drive"]
)
)
# From authorized user data (JSON string)
credentials = get_credentials(
settings=GoogleAuthSettings(
type="user_account",
authorized_user_data=json.dumps({
"type": "authorized_user",
"client_id": "...",
"client_secret": "...",
"refresh_token": "..."
}),
scopes=["https://www.googleapis.com/auth/drive"]
)
)
```
### Service Account Impersonation
```python
from kiarina.lib.google.auth import get_credentials, GoogleAuthSettings
# Impersonate a service account using source credentials
credentials = get_credentials(
settings=GoogleAuthSettings(
type="service_account",
service_account_file="~/path/to/source-sa-key.json",
impersonate_service_account="target-sa@project.iam.gserviceaccount.com",
scopes=["https://www.googleapis.com/auth/cloud-platform"]
)
)
# Note: Source principal requires roles/iam.serviceAccountTokenCreator role
```
### Credentials Caching
```python
from kiarina.lib.google.auth import get_credentials, GoogleAuthSettings, CredentialsCache
# Implement a cache (e.g., in-memory, Redis, file-based)
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
cache = InMemoryCache()
# Use cache for user account credentials
credentials = get_credentials(
settings=GoogleAuthSettings(
type="user_account",
authorized_user_file="~/path/to/authorized-user.json",
scopes=["https://www.googleapis.com/auth/drive"]
),
cache=cache
)
```
### Self-Signed JWT
```python
from kiarina.lib.google.auth import get_self_signed_jwt, GoogleAuthSettings
# Generate a self-signed JWT for service account
jwt_token = get_self_signed_jwt(
settings=GoogleAuthSettings(
type="service_account",
service_account_file="~/path/to/service-account-key.json"
),
audience="https://your-service.example.com/"
)
```
## Configuration
This library uses [pydantic-settings-manager](https://github.com/kiarina/pydantic-settings-manager) for flexible configuration management.
### Environment Variables
Configure authentication using environment variables:
```bash
# Authentication type
export KIARINA_LIB_GOOGLE_AUTH_TYPE="service_account"
# Service account configuration
export KIARINA_LIB_GOOGLE_AUTH_SERVICE_ACCOUNT_FILE="~/path/to/sa-key.json"
export KIARINA_LIB_GOOGLE_AUTH_SERVICE_ACCOUNT_EMAIL="sa@project.iam.gserviceaccount.com"
# User account configuration
export KIARINA_LIB_GOOGLE_AUTH_AUTHORIZED_USER_FILE="~/path/to/authorized-user.json"
export KIARINA_LIB_GOOGLE_AUTH_USER_ACCOUNT_EMAIL="user@example.com"
# Impersonation
export KIARINA_LIB_GOOGLE_AUTH_IMPERSONATE_SERVICE_ACCOUNT="target-sa@project.iam.gserviceaccount.com"
# Scopes (comma-separated)
export KIARINA_LIB_GOOGLE_AUTH_SCOPES="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/drive"
# Project ID
export KIARINA_LIB_GOOGLE_AUTH_PROJECT_ID="your-project-id"
```
### Programmatic Configuration
```python
from kiarina.lib.google.auth import settings_manager, get_credentials
# Configure multiple environments
settings_manager.user_config = {
"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",
"scopes": ["https://www.googleapis.com/auth/cloud-platform"]
}
}
# Switch to production configuration
settings_manager.active_key = "production"
credentials = get_credentials()
```
## API Reference
### Main Functions
#### `get_credentials(config_key=None, *, settings=None, scopes=None, cache=None)`
Get Google Cloud credentials based on configuration.
**Parameters:**
- `config_key` (str | None): Configuration key for multi-config setup
- `settings` (GoogleAuthSettings | None): Settings object (overrides config_key)
- `scopes` (list[str] | None): OAuth2 scopes (overrides settings.scopes)
- `cache` (CredentialsCache | None): Credentials cache for user accounts
**Returns:**
- `Credentials`: Google Cloud credentials object
**Supported credential types:**
- `google.auth.compute_engine.credentials.Credentials` (Compute Engine)
- `google.oauth2.service_account.Credentials` (Service Account)
- `google.oauth2.credentials.Credentials` (User Account)
- `google.auth.impersonated_credentials.Credentials` (Impersonated)
#### `get_self_signed_jwt(config_key=None, *, settings=None, audience)`
Generate a self-signed JWT for service account authentication.
**Parameters:**
- `config_key` (str | None): Configuration key for multi-config setup
- `settings` (GoogleAuthSettings | None): Settings object (overrides config_key)
- `audience` (str): JWT audience (target service URL)
**Returns:**
- `str`: Self-signed JWT token
### Utility Functions
#### `get_default_credentials()`
Get default Google credentials using Application Default Credentials (ADC).
**Returns:**
- `Credentials`: Default credentials (ADC, service account, or compute engine)
#### `get_service_account_credentials(*, service_account_file=None, service_account_data=None)`
Get service account credentials from file or data.
**Parameters:**
- `service_account_file` (str | PathLike | None): Path to service account key file
- `service_account_data` (dict | None): Service account key data
**Returns:**
- `google.oauth2.service_account.Credentials`: 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.
**Parameters:**
- `authorized_user_file` (str | PathLike | None): Path to authorized user file
- `authorized_user_data` (dict | None): Authorized user data
- `scopes` (list[str]): OAuth2 scopes
- `cache` (CredentialsCache | None): Credentials cache
**Returns:**
- `google.oauth2.credentials.Credentials`: User account credentials
### Configuration Classes
#### `GoogleAuthSettings`
Pydantic settings model for Google Cloud authentication.
**Fields:**
- `type` (Literal["default", "service_account", "user_account"]): Authentication type (default: "default")
- `service_account_email` (str | None): Service account email
- `service_account_file` (str | None): Path to service account key file
- `service_account_data` (str | None): Service account key data (JSON string)
- `user_account_email` (str | None): User account email
- `client_secret_file` (str | None): Path to client secret file
- `client_secret_data` (str | None): Client secret data (JSON string)
- `authorized_user_file` (str | None): Path to authorized user file
- `authorized_user_data` (str | None): Authorized user data (JSON string)
- `impersonate_service_account` (str | None): Target service account email for impersonation
- `scopes` (list[str]): OAuth2 scopes (default: cloud-platform, drive, spreadsheets)
- `project_id` (str | None): GCP project ID
**Methods:**
- `get_service_account_data()`: Parse service_account_data JSON string
- `get_client_secret_data()`: Parse client_secret_data JSON string
- `get_authorized_user_data()`: Parse authorized_user_data JSON string
#### `CredentialsCache` (Protocol)
Protocol for implementing credentials cache.
**Methods:**
- `get() -> str | None`: Retrieve cached credentials (JSON string)
- `set(value: str) -> None`: Store credentials in cache (JSON string)
## Authentication Types
### 1. Default Credentials
Uses Application Default Credentials (ADC) in the following priority:
1. `GOOGLE_APPLICATION_CREDENTIALS` environment variable (service account key file)
2. `gcloud auth application-default login` credentials (user account)
3. Compute Engine metadata server (compute engine credentials)
```python
credentials = get_credentials(
settings=GoogleAuthSettings(type="default")
)
```
### 2. Service Account
Authenticates using a service account key file or data.
```python
# From file
credentials = get_credentials(
settings=GoogleAuthSettings(
type="service_account",
service_account_file="~/sa-key.json"
)
)
# From data
credentials = get_credentials(
settings=GoogleAuthSettings(
type="service_account",
service_account_data='{"type": "service_account", ...}'
)
)
```
### 3. User Account
Authenticates using OAuth2 user credentials (authorized user file).
```python
credentials = get_credentials(
settings=GoogleAuthSettings(
type="user_account",
authorized_user_file="~/.config/gcloud/application_default_credentials.json",
scopes=["https://www.googleapis.com/auth/drive"]
)
)
```
**Note:** User account credentials support automatic refresh and caching.
### 4. Service Account Impersonation
Impersonate a target service account using source credentials.
```python
credentials = get_credentials(
settings=GoogleAuthSettings(
type="service_account",
service_account_file="~/source-sa-key.json",
impersonate_service_account="target-sa@project.iam.gserviceaccount.com",
scopes=["https://www.googleapis.com/auth/cloud-platform"]
)
)
```
**Required IAM Role:** The source principal must have the `roles/iam.serviceAccountTokenCreator` role on the target service account.
## Default Scopes
The library includes the following default scopes:
- `https://www.googleapis.com/auth/cloud-platform` - All GCP resources
- `https://www.googleapis.com/auth/drive` - Google Drive resources
- `https://www.googleapis.com/auth/spreadsheets` - Google Sheets resources
You can override these by specifying custom scopes in the configuration or function call.
## Error Handling
```python
from kiarina.lib.google.auth import get_credentials, GoogleAuthSettings
try:
credentials = get_credentials(
settings=GoogleAuthSettings(
type="service_account",
service_account_file="~/sa-key.json"
)
)
except ValueError as e:
print(f"Configuration error: {e}")
except FileNotFoundError as e:
print(f"Key file not found: {e}")
except Exception as e:
print(f"Authentication failed: {e}")
```
## Development
### Prerequisites
- Python 3.12+
### Setup
```bash
# Clone the repository
git clone https://github.com/kiarina/kiarina-python.git
cd kiarina-python
# Setup development environment
mise run setup
```
### Running Tests
```bash
# Run format, lint, type checks and tests
mise run package kiarina-lib-google-auth
# Coverage report
mise run package:test kiarina-lib-google-auth --coverage
```
### Test Configuration
Some tests require actual GCP credentials. Create a test settings file and set the environment variable to point to it:
```bash
# Create test settings file from sample
cp packages/kiarina-lib-google-auth/test_settings.sample.yaml \
packages/kiarina-lib-google-auth/test_settings.yaml
# Edit the file with your actual credentials
# Then set the environment variable
export KIARINA_LIB_GOOGLE_AUTH_TEST_SETTINGS_FILE="packages/kiarina-lib-google-auth/test_settings.yaml"
```
The test settings file should contain multiple named configurations for different authentication scenarios:
```yaml
kiarina.lib.google.auth:
default:
type: default
service_account_file:
type: service_account
project_id: your-project-id
service_account_email: your-service-account@your-project.iam.gserviceaccount.com
service_account_file: ~/.gcp/service-account/your-project/your-service-account/key.json
service_account_data:
type: service_account
project_id: your-project-id
service_account_email: your-service-account@your-project.iam.gserviceaccount.com
service_account_data: '{"type":"service_account","project_id":"...","private_key":"...","client_email":"..."}'
service_account_impersonate:
type: service_account
project_id: your-project-id
service_account_email: your-service-account@your-project.iam.gserviceaccount.com
service_account_file: ~/.gcp/service-account/your-project/your-service-account/key.json
impersonate_service_account: impersonated-account@your-project.iam.gserviceaccount.com
user_account_file:
type: user_account
project_id: your-project-id
user_account_email: your-email@example.com
authorized_user_file: ~/.gcp/oauth2/your-project/authorized_user.json
user_account_data:
type: user_account
project_id: your-project-id
user_account_email: your-email@example.com
authorized_user_data: '{"type":"authorized_user","client_id":"...","client_secret":"...","refresh_token":"..."}'
```
**Note**: The `test_settings.yaml` file is gitignored to prevent accidental credential exposure.
## Dependencies
- [google-api-python-client](https://github.com/googleapis/google-api-python-client) - Google API client library
- [pydantic-settings](https://docs.pydantic.dev/latest/concepts/pydantic_settings/) - Settings management
- [pydantic-settings-manager](https://github.com/kiarina/pydantic-settings-manager) - Advanced settings management
## License
This project is licensed under the MIT License - see the [LICENSE](../../LICENSE) file for details.
## Contributing
This is a personal project, but contributions are welcome! Please feel free to submit issues or pull requests.
## Related Projects
- [kiarina-python](https://github.com/kiarina/kiarina-python) - The main monorepo containing this package
- [pydantic-settings-manager](https://github.com/kiarina/pydantic-settings-manager) - Configuration management library used by this package
Raw data
{
"_id": null,
"home_page": null,
"name": "kiarina-lib-google-auth",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.12",
"maintainer_email": "kiarina <kiarinadawa@gmail.com>",
"keywords": "client, cloud, gcp, google, google-cloud, pydantic, settings",
"author": null,
"author_email": "kiarina <kiarinadawa@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/83/75/bc5e4231c4895d4872706eb119f7c6720d4242f73b6b302f7bbc2b7a2f9e/kiarina_lib_google_auth-1.6.3.tar.gz",
"platform": null,
"description": "# kiarina-lib-google-auth\n\nA Python client library for Google Cloud authentication with configuration management and support for multiple credential types.\n\n## Features\n\n- **Multiple Authentication Methods**: Support for default credentials, service accounts, and user accounts\n- **Service Account Impersonation**: Impersonate service accounts for delegated access\n- **Configuration Management**: Use `pydantic-settings-manager` for flexible configuration\n- **Credentials Caching**: Cache and refresh user account credentials automatically\n- **Self-Signed JWT**: Generate self-signed JWTs for service accounts\n- **Type Safety**: Full type hints and Pydantic validation\n\n## Installation\n\n```bash\npip install kiarina-lib-google-auth\n```\n\n## Quick Start\n\n### Basic Usage with Default Credentials\n\n```python\nfrom kiarina.lib.google.auth import get_credentials\n\n# Get default credentials (ADC, service account, or compute engine)\ncredentials = get_credentials()\n```\n\n### Service Account Authentication\n\n```python\nfrom kiarina.lib.google.auth import get_credentials, GoogleAuthSettings\n\n# From service account key file\ncredentials = get_credentials(\n settings=GoogleAuthSettings(\n type=\"service_account\",\n service_account_file=\"~/path/to/service-account-key.json\"\n )\n)\n\n# From service account key data (JSON string)\nimport json\ncredentials = get_credentials(\n settings=GoogleAuthSettings(\n type=\"service_account\",\n service_account_data=json.dumps({\n \"type\": \"service_account\",\n \"project_id\": \"your-project\",\n \"private_key_id\": \"...\",\n \"private_key\": \"...\",\n \"client_email\": \"...\",\n # ... other fields\n })\n )\n)\n```\n\n### User Account Authentication\n\n```python\nfrom kiarina.lib.google.auth import get_credentials, GoogleAuthSettings\n\n# From authorized user file (OAuth2 credentials)\ncredentials = get_credentials(\n settings=GoogleAuthSettings(\n type=\"user_account\",\n authorized_user_file=\"~/path/to/authorized-user.json\",\n scopes=[\"https://www.googleapis.com/auth/drive\"]\n )\n)\n\n# From authorized user data (JSON string)\ncredentials = get_credentials(\n settings=GoogleAuthSettings(\n type=\"user_account\",\n authorized_user_data=json.dumps({\n \"type\": \"authorized_user\",\n \"client_id\": \"...\",\n \"client_secret\": \"...\",\n \"refresh_token\": \"...\"\n }),\n scopes=[\"https://www.googleapis.com/auth/drive\"]\n )\n)\n```\n\n### Service Account Impersonation\n\n```python\nfrom kiarina.lib.google.auth import get_credentials, GoogleAuthSettings\n\n# Impersonate a service account using source credentials\ncredentials = get_credentials(\n settings=GoogleAuthSettings(\n type=\"service_account\",\n service_account_file=\"~/path/to/source-sa-key.json\",\n impersonate_service_account=\"target-sa@project.iam.gserviceaccount.com\",\n scopes=[\"https://www.googleapis.com/auth/cloud-platform\"]\n )\n)\n\n# Note: Source principal requires roles/iam.serviceAccountTokenCreator role\n```\n\n### Credentials Caching\n\n```python\nfrom kiarina.lib.google.auth import get_credentials, GoogleAuthSettings, CredentialsCache\n\n# Implement a cache (e.g., in-memory, Redis, file-based)\nclass InMemoryCache(CredentialsCache):\n def __init__(self):\n self._cache: str | None = None\n \n def get(self) -> str | None:\n return self._cache\n \n def set(self, value: str) -> None:\n self._cache = value\n\ncache = InMemoryCache()\n\n# Use cache for user account credentials\ncredentials = get_credentials(\n settings=GoogleAuthSettings(\n type=\"user_account\",\n authorized_user_file=\"~/path/to/authorized-user.json\",\n scopes=[\"https://www.googleapis.com/auth/drive\"]\n ),\n cache=cache\n)\n```\n\n### Self-Signed JWT\n\n```python\nfrom kiarina.lib.google.auth import get_self_signed_jwt, GoogleAuthSettings\n\n# Generate a self-signed JWT for service account\njwt_token = get_self_signed_jwt(\n settings=GoogleAuthSettings(\n type=\"service_account\",\n service_account_file=\"~/path/to/service-account-key.json\"\n ),\n audience=\"https://your-service.example.com/\"\n)\n```\n\n## Configuration\n\nThis library uses [pydantic-settings-manager](https://github.com/kiarina/pydantic-settings-manager) for flexible configuration management.\n\n### Environment Variables\n\nConfigure authentication using environment variables:\n\n```bash\n# Authentication type\nexport KIARINA_LIB_GOOGLE_AUTH_TYPE=\"service_account\"\n\n# Service account configuration\nexport KIARINA_LIB_GOOGLE_AUTH_SERVICE_ACCOUNT_FILE=\"~/path/to/sa-key.json\"\nexport KIARINA_LIB_GOOGLE_AUTH_SERVICE_ACCOUNT_EMAIL=\"sa@project.iam.gserviceaccount.com\"\n\n# User account configuration\nexport KIARINA_LIB_GOOGLE_AUTH_AUTHORIZED_USER_FILE=\"~/path/to/authorized-user.json\"\nexport KIARINA_LIB_GOOGLE_AUTH_USER_ACCOUNT_EMAIL=\"user@example.com\"\n\n# Impersonation\nexport KIARINA_LIB_GOOGLE_AUTH_IMPERSONATE_SERVICE_ACCOUNT=\"target-sa@project.iam.gserviceaccount.com\"\n\n# Scopes (comma-separated)\nexport KIARINA_LIB_GOOGLE_AUTH_SCOPES=\"https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/drive\"\n\n# Project ID\nexport KIARINA_LIB_GOOGLE_AUTH_PROJECT_ID=\"your-project-id\"\n```\n\n### Programmatic Configuration\n\n```python\nfrom kiarina.lib.google.auth import settings_manager, get_credentials\n\n# Configure multiple environments\nsettings_manager.user_config = {\n \"development\": {\n \"type\": \"user_account\",\n \"authorized_user_file\": \"~/.config/gcloud/application_default_credentials.json\",\n \"scopes\": [\"https://www.googleapis.com/auth/cloud-platform\"]\n },\n \"production\": {\n \"type\": \"service_account\",\n \"service_account_file\": \"/secrets/prod-sa-key.json\",\n \"scopes\": [\"https://www.googleapis.com/auth/cloud-platform\"]\n }\n}\n\n# Switch to production configuration\nsettings_manager.active_key = \"production\"\ncredentials = get_credentials()\n```\n\n## API Reference\n\n### Main Functions\n\n#### `get_credentials(config_key=None, *, settings=None, scopes=None, cache=None)`\n\nGet Google Cloud credentials based on configuration.\n\n**Parameters:**\n- `config_key` (str | None): Configuration key for multi-config setup\n- `settings` (GoogleAuthSettings | None): Settings object (overrides config_key)\n- `scopes` (list[str] | None): OAuth2 scopes (overrides settings.scopes)\n- `cache` (CredentialsCache | None): Credentials cache for user accounts\n\n**Returns:**\n- `Credentials`: Google Cloud credentials object\n\n**Supported credential types:**\n- `google.auth.compute_engine.credentials.Credentials` (Compute Engine)\n- `google.oauth2.service_account.Credentials` (Service Account)\n- `google.oauth2.credentials.Credentials` (User Account)\n- `google.auth.impersonated_credentials.Credentials` (Impersonated)\n\n#### `get_self_signed_jwt(config_key=None, *, settings=None, audience)`\n\nGenerate a self-signed JWT for service account authentication.\n\n**Parameters:**\n- `config_key` (str | None): Configuration key for multi-config setup\n- `settings` (GoogleAuthSettings | None): Settings object (overrides config_key)\n- `audience` (str): JWT audience (target service URL)\n\n**Returns:**\n- `str`: Self-signed JWT token\n\n### Utility Functions\n\n#### `get_default_credentials()`\n\nGet default Google credentials using Application Default Credentials (ADC).\n\n**Returns:**\n- `Credentials`: Default credentials (ADC, service account, or compute engine)\n\n#### `get_service_account_credentials(*, service_account_file=None, service_account_data=None)`\n\nGet service account credentials from file or data.\n\n**Parameters:**\n- `service_account_file` (str | PathLike | None): Path to service account key file\n- `service_account_data` (dict | None): Service account key data\n\n**Returns:**\n- `google.oauth2.service_account.Credentials`: Service account credentials\n\n#### `get_user_account_credentials(*, authorized_user_file=None, authorized_user_data=None, scopes, cache=None)`\n\nGet user account credentials from file or data.\n\n**Parameters:**\n- `authorized_user_file` (str | PathLike | None): Path to authorized user file\n- `authorized_user_data` (dict | None): Authorized user data\n- `scopes` (list[str]): OAuth2 scopes\n- `cache` (CredentialsCache | None): Credentials cache\n\n**Returns:**\n- `google.oauth2.credentials.Credentials`: User account credentials\n\n### Configuration Classes\n\n#### `GoogleAuthSettings`\n\nPydantic settings model for Google Cloud authentication.\n\n**Fields:**\n- `type` (Literal[\"default\", \"service_account\", \"user_account\"]): Authentication type (default: \"default\")\n- `service_account_email` (str | None): Service account email\n- `service_account_file` (str | None): Path to service account key file\n- `service_account_data` (str | None): Service account key data (JSON string)\n- `user_account_email` (str | None): User account email\n- `client_secret_file` (str | None): Path to client secret file\n- `client_secret_data` (str | None): Client secret data (JSON string)\n- `authorized_user_file` (str | None): Path to authorized user file\n- `authorized_user_data` (str | None): Authorized user data (JSON string)\n- `impersonate_service_account` (str | None): Target service account email for impersonation\n- `scopes` (list[str]): OAuth2 scopes (default: cloud-platform, drive, spreadsheets)\n- `project_id` (str | None): GCP project ID\n\n**Methods:**\n- `get_service_account_data()`: Parse service_account_data JSON string\n- `get_client_secret_data()`: Parse client_secret_data JSON string\n- `get_authorized_user_data()`: Parse authorized_user_data JSON string\n\n#### `CredentialsCache` (Protocol)\n\nProtocol for implementing credentials cache.\n\n**Methods:**\n- `get() -> str | None`: Retrieve cached credentials (JSON string)\n- `set(value: str) -> None`: Store credentials in cache (JSON string)\n\n## Authentication Types\n\n### 1. Default Credentials\n\nUses Application Default Credentials (ADC) in the following priority:\n\n1. `GOOGLE_APPLICATION_CREDENTIALS` environment variable (service account key file)\n2. `gcloud auth application-default login` credentials (user account)\n3. Compute Engine metadata server (compute engine credentials)\n\n```python\ncredentials = get_credentials(\n settings=GoogleAuthSettings(type=\"default\")\n)\n```\n\n### 2. Service Account\n\nAuthenticates using a service account key file or data.\n\n```python\n# From file\ncredentials = get_credentials(\n settings=GoogleAuthSettings(\n type=\"service_account\",\n service_account_file=\"~/sa-key.json\"\n )\n)\n\n# From data\ncredentials = get_credentials(\n settings=GoogleAuthSettings(\n type=\"service_account\",\n service_account_data='{\"type\": \"service_account\", ...}'\n )\n)\n```\n\n### 3. User Account\n\nAuthenticates using OAuth2 user credentials (authorized user file).\n\n```python\ncredentials = get_credentials(\n settings=GoogleAuthSettings(\n type=\"user_account\",\n authorized_user_file=\"~/.config/gcloud/application_default_credentials.json\",\n scopes=[\"https://www.googleapis.com/auth/drive\"]\n )\n)\n```\n\n**Note:** User account credentials support automatic refresh and caching.\n\n### 4. Service Account Impersonation\n\nImpersonate a target service account using source credentials.\n\n```python\ncredentials = get_credentials(\n settings=GoogleAuthSettings(\n type=\"service_account\",\n service_account_file=\"~/source-sa-key.json\",\n impersonate_service_account=\"target-sa@project.iam.gserviceaccount.com\",\n scopes=[\"https://www.googleapis.com/auth/cloud-platform\"]\n )\n)\n```\n\n**Required IAM Role:** The source principal must have the `roles/iam.serviceAccountTokenCreator` role on the target service account.\n\n## Default Scopes\n\nThe library includes the following default scopes:\n\n- `https://www.googleapis.com/auth/cloud-platform` - All GCP resources\n- `https://www.googleapis.com/auth/drive` - Google Drive resources\n- `https://www.googleapis.com/auth/spreadsheets` - Google Sheets resources\n\nYou can override these by specifying custom scopes in the configuration or function call.\n\n## Error Handling\n\n```python\nfrom kiarina.lib.google.auth import get_credentials, GoogleAuthSettings\n\ntry:\n credentials = get_credentials(\n settings=GoogleAuthSettings(\n type=\"service_account\",\n service_account_file=\"~/sa-key.json\"\n )\n )\nexcept ValueError as e:\n print(f\"Configuration error: {e}\")\nexcept FileNotFoundError as e:\n print(f\"Key file not found: {e}\")\nexcept Exception as e:\n print(f\"Authentication failed: {e}\")\n```\n\n## Development\n\n### Prerequisites\n\n- Python 3.12+\n\n### Setup\n\n```bash\n# Clone the repository\ngit clone https://github.com/kiarina/kiarina-python.git\ncd kiarina-python\n\n# Setup development environment\nmise run setup\n```\n\n### Running Tests\n\n```bash\n# Run format, lint, type checks and tests\nmise run package kiarina-lib-google-auth\n\n# Coverage report\nmise run package:test kiarina-lib-google-auth --coverage\n```\n\n### Test Configuration\n\nSome tests require actual GCP credentials. Create a test settings file and set the environment variable to point to it:\n\n```bash\n# Create test settings file from sample\ncp packages/kiarina-lib-google-auth/test_settings.sample.yaml \\\n packages/kiarina-lib-google-auth/test_settings.yaml\n\n# Edit the file with your actual credentials\n# Then set the environment variable\nexport KIARINA_LIB_GOOGLE_AUTH_TEST_SETTINGS_FILE=\"packages/kiarina-lib-google-auth/test_settings.yaml\"\n```\n\nThe test settings file should contain multiple named configurations for different authentication scenarios:\n\n```yaml\nkiarina.lib.google.auth:\n default:\n type: default\n service_account_file:\n type: service_account\n project_id: your-project-id\n service_account_email: your-service-account@your-project.iam.gserviceaccount.com\n service_account_file: ~/.gcp/service-account/your-project/your-service-account/key.json\n service_account_data:\n type: service_account\n project_id: your-project-id\n service_account_email: your-service-account@your-project.iam.gserviceaccount.com\n service_account_data: '{\"type\":\"service_account\",\"project_id\":\"...\",\"private_key\":\"...\",\"client_email\":\"...\"}'\n service_account_impersonate:\n type: service_account\n project_id: your-project-id\n service_account_email: your-service-account@your-project.iam.gserviceaccount.com\n service_account_file: ~/.gcp/service-account/your-project/your-service-account/key.json\n impersonate_service_account: impersonated-account@your-project.iam.gserviceaccount.com\n user_account_file:\n type: user_account\n project_id: your-project-id\n user_account_email: your-email@example.com\n authorized_user_file: ~/.gcp/oauth2/your-project/authorized_user.json\n user_account_data:\n type: user_account\n project_id: your-project-id\n user_account_email: your-email@example.com\n authorized_user_data: '{\"type\":\"authorized_user\",\"client_id\":\"...\",\"client_secret\":\"...\",\"refresh_token\":\"...\"}'\n```\n\n**Note**: The `test_settings.yaml` file is gitignored to prevent accidental credential exposure.\n\n## Dependencies\n\n- [google-api-python-client](https://github.com/googleapis/google-api-python-client) - Google API client library\n- [pydantic-settings](https://docs.pydantic.dev/latest/concepts/pydantic_settings/) - Settings management\n- [pydantic-settings-manager](https://github.com/kiarina/pydantic-settings-manager) - Advanced settings management\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](../../LICENSE) file for details.\n\n## Contributing\n\nThis is a personal project, but contributions are welcome! Please feel free to submit issues or pull requests.\n\n## Related Projects\n\n- [kiarina-python](https://github.com/kiarina/kiarina-python) - The main monorepo containing this package\n- [pydantic-settings-manager](https://github.com/kiarina/pydantic-settings-manager) - Configuration management library used by this package\n",
"bugtrack_url": null,
"license": null,
"summary": "Google Cloud client library for kiarina namespace",
"version": "1.6.3",
"project_urls": {
"Changelog": "https://github.com/kiarina/kiarina-python/blob/main/packages/kiarina-lib-google-auth/CHANGELOG.md",
"Documentation": "https://github.com/kiarina/kiarina-python/tree/main/packages/kiarina-lib-google-auth#readme",
"Homepage": "https://github.com/kiarina/kiarina-python",
"Issues": "https://github.com/kiarina/kiarina-python/issues",
"Repository": "https://github.com/kiarina/kiarina-python"
},
"split_keywords": [
"client",
" cloud",
" gcp",
" google",
" google-cloud",
" pydantic",
" settings"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "59ad1fea0fe6d3410ec0dce0fbf136a4d6a4bc3211bbcadfef6e8522315d6e88",
"md5": "1b8a7a6f37fb6fff77aaf97492d29dd3",
"sha256": "73cb0c501c4b867570c4689cf81b623f8126281b436255ee05cc131ecd90bc83"
},
"downloads": -1,
"filename": "kiarina_lib_google_auth-1.6.3-py3-none-any.whl",
"has_sig": false,
"md5_digest": "1b8a7a6f37fb6fff77aaf97492d29dd3",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.12",
"size": 12040,
"upload_time": "2025-10-12T17:48:24",
"upload_time_iso_8601": "2025-10-12T17:48:24.678378Z",
"url": "https://files.pythonhosted.org/packages/59/ad/1fea0fe6d3410ec0dce0fbf136a4d6a4bc3211bbcadfef6e8522315d6e88/kiarina_lib_google_auth-1.6.3-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "8375bc5e4231c4895d4872706eb119f7c6720d4242f73b6b302f7bbc2b7a2f9e",
"md5": "ff16519870e7b8bf29385c64f8393cf4",
"sha256": "d891d7be1431db7720d50303e80ac6aea6161720e934e9d4f296992f46d49388"
},
"downloads": -1,
"filename": "kiarina_lib_google_auth-1.6.3.tar.gz",
"has_sig": false,
"md5_digest": "ff16519870e7b8bf29385c64f8393cf4",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.12",
"size": 11046,
"upload_time": "2025-10-12T17:48:34",
"upload_time_iso_8601": "2025-10-12T17:48:34.532803Z",
"url": "https://files.pythonhosted.org/packages/83/75/bc5e4231c4895d4872706eb119f7c6720d4242f73b6b302f7bbc2b7a2f9e/kiarina_lib_google_auth-1.6.3.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-10-12 17:48:34",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "kiarina",
"github_project": "kiarina-python",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "kiarina-lib-google-auth"
}