CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-google-api-core

Google API client core library providing common helpers, utilities, and components for Python client libraries

Pending
Overview
Eval results
Files

iam-policies.mddocs/

IAM Policy Management

Non-API-specific IAM (Identity and Access Management) policy definitions for Google Cloud Platform services. This module provides a high-level abstraction for managing IAM policies, including role bindings, member management, and conditional access controls across Google Cloud resources.

Capabilities

Policy Management

Core IAM policy representation and manipulation with support for role bindings, member management, and policy versioning.

class Policy:
    def __init__(self, etag=None, version=None): ...
    
    @property
    def bindings(self): ...
    
    @bindings.setter  
    def bindings(self, value): ...
    
    # Dictionary interface (version 1 only)
    def __getitem__(self, key): ...
    def __setitem__(self, key, value): ...
    def __delitem__(self, key): ...
    def __iter__(self): ...
    def __len__(self): ...

Policy Serialization

Methods for converting between Policy objects and Google Cloud IAM API representations.

@classmethod
def from_api_repr(cls, resource): ...

def to_api_repr(self): ...

Member Factory Methods

Static methods for creating properly formatted member identifiers for different identity types.

@staticmethod
def user(email): ...

@staticmethod
def service_account(email): ...

@staticmethod
def group(email): ...

@staticmethod
def domain(domain): ...

@staticmethod
def all_users(): ...

@staticmethod
def authenticated_users(): ...

Usage Examples

Basic Policy Creation and Management

from google.api_core import iam

# Create a new policy
policy = iam.Policy()

# Add role bindings using the bindings property
policy.bindings = [
    {
        "role": "roles/viewer",
        "members": {
            iam.Policy.user("user@example.com"),
            iam.Policy.group("admins@example.com"),
            iam.Policy.all_users()
        }
    },
    {
        "role": "roles/editor", 
        "members": {
            iam.Policy.service_account("service@project.iam.gserviceaccount.com")
        }
    }
]

Conditional Access Control

# Create policy with conditional bindings (requires version 3+)
policy = iam.Policy(version=3)
policy.bindings = [
    {
        "role": "roles/viewer",
        "members": {iam.Policy.user("temp-user@example.com")},
        "condition": {
            "title": "time_limited_access",
            "description": "Access expires on 2024-12-31",
            "expression": "request.time < timestamp(\"2024-12-31T23:59:59Z\")"
        }
    }
]

Working with API Resources

# Convert from API response
api_response = {
    "version": 1,
    "etag": "ABC123",
    "bindings": [
        {
            "role": "roles/owner",
            "members": ["user:owner@example.com"]
        }
    ]
}

policy = iam.Policy.from_api_repr(api_response)

# Modify policy
policy.bindings.append({
    "role": "roles/viewer",
    "members": {iam.Policy.user("viewer@example.com")}
})

# Convert back to API format
api_resource = policy.to_api_repr()

Legacy Dictionary Interface (Version 1 Only)

# Version 1 policies support dictionary-like access
policy = iam.Policy(version=1)

# Set members for a role
policy["roles/viewer"] = {
    iam.Policy.user("user@example.com"),
    iam.Policy.group("viewers@example.com")
}

# Get members for a role
viewers = policy["roles/viewer"]

# Remove a role
del policy["roles/editor"]

# Iterate over roles
for role in policy:
    print(f"Role: {role}, Members: {policy[role]}")

Policy Versioning

IAM policy versions control available features and API compatibility.

# Version 1 (default)
# - Supports dictionary-style access
# - No conditional bindings
# - Legacy properties available

# Version 3+  
# - Required for conditional bindings
# - Dictionary access raises InvalidOperationException
# - Must use bindings property

Exception Handling

Comprehensive error handling for policy operations and version compatibility.

class InvalidOperationException(Exception): ...

Version Compatibility Examples

# Version 1 - Basic functionality
policy_v1 = iam.Policy(version=1)
policy_v1["roles/viewer"] = {iam.Policy.user("user@example.com")}  # Works

# Version 3 - Conditional bindings
policy_v3 = iam.Policy(version=3)
try:
    policy_v3["roles/viewer"] = {"user@example.com"}  # Raises InvalidOperationException
except iam.InvalidOperationException:
    # Must use bindings property instead
    policy_v3.bindings = [{
        "role": "roles/viewer",
        "members": {iam.Policy.user("user@example.com")}
    }]

Member Types and Formats

Standard member identifier formats for different identity types:

# Users
iam.Policy.user("user@example.com")
# Returns: "user:user@example.com"

# Service Accounts  
iam.Policy.service_account("service@project.iam.gserviceaccount.com")
# Returns: "serviceAccount:service@project.iam.gserviceaccount.com"

# Groups
iam.Policy.group("admins@example.com") 
# Returns: "group:admins@example.com"

# Domains
iam.Policy.domain("example.com")
# Returns: "domain:example.com"

# Special members
iam.Policy.all_users()
# Returns: "allUsers"

iam.Policy.authenticated_users()
# Returns: "allAuthenticatedUsers"

Predefined Roles

Common IAM role constants for convenience.

OWNER_ROLE = "roles/owner"      # All rights to an object
EDITOR_ROLE = "roles/editor"    # Rights to modify an object  
VIEWER_ROLE = "roles/viewer"    # Rights to access an object

Import Patterns

from google.api_core import iam

# Create policies
policy = iam.Policy()

# Use member factory methods
member = iam.Policy.user("user@example.com")

# Use predefined roles
policy.bindings = [{
    "role": iam.VIEWER_ROLE,
    "members": {member}
}]

# Handle exceptions
try:
    policy["role"] = members  # May raise InvalidOperationException
except iam.InvalidOperationException:
    # Handle version compatibility issue
    pass

Types

from typing import Dict, List, Optional, Set, Union

# Policy binding structure
PolicyBinding = Dict[str, Union[str, Set[str], Dict[str, str]]]

# Condition structure for conditional bindings
Condition = Dict[str, str]  # Contains title, description, expression

# Member identifier types
MemberIdentifier = str  # Formatted as "type:identifier"

# Policy resource structure for API serialization
PolicyResource = Dict[str, Union[int, str, List[PolicyBinding]]]

Policy Binding Structure

Basic Binding Format

{
    "role": "roles/viewer",
    "members": {"user:user@example.com", "group:admins@example.com"}
}

Conditional Binding Format

{
    "role": "roles/viewer",
    "members": {"user:user@example.com"},
    "condition": {
        "title": "time_limited_access",
        "description": "Access valid until year end",
        "expression": "request.time < timestamp(\"2024-12-31T23:59:59Z\")"
    }
}

Architecture and Design Patterns

Policy Versioning Strategy

  • Version 1: Basic role-member bindings with dictionary interface
  • Version 3+: Conditional bindings with restricted access patterns
  • Automatic Migration: Policies automatically upgrade when conditions are added

Member Normalization

  • List to Set Conversion: Automatic conversion for de-duplication
  • Format Validation: Consistent member identifier formatting
  • Type Safety: Static factory methods prevent format errors

API Integration

  • Seamless Serialization: Direct conversion to/from Google Cloud IAM API formats
  • Resource Optimization: Empty bindings are excluded from API calls
  • Sorting and Consistency: Deterministic output for reliable API operations

Error Handling Strategy

  • Version Compatibility: Clear exceptions when using incompatible operations
  • Graceful Degradation: Fallback behaviors for legacy code patterns
  • Validation: Early detection of invalid policy configurations

This module provides the foundation for IAM policy management across all Google Cloud services, supporting both simple role assignments and complex conditional access scenarios.

Install with Tessl CLI

npx tessl i tessl/pypi-google-api-core

docs

bidirectional-streaming.md

client-config.md

datetime.md

exceptions.md

gapic-framework.md

iam-policies.md

index.md

operations.md

page-iteration.md

path-templates.md

protobuf-helpers.md

retry.md

timeout.md

transport.md

universe-domain.md

tile.json