Skip to main content

Python SDK for Iron Book by Identity Machines

Project description

Iron Book Python SDK

A Python SDK for interacting with Iron Book by Identity Machines. This SDK provides seamless integration with Iron Book's agent registration, authentication, and policy decision APIs.

Features

  • Agent Registration: Register new agents and obtain Verifiable Credentials
  • Authentication: Get authentication tokens for agent operations
  • Policy Decisions: Evaluate policy decisions for agent actions
  • Policy Upload: Upload a new access control policy to enforce actions against
  • Async Support: Full async/await support for high-performance applications
  • Type Safety: Comprehensive type hints and dataclass definitions
  • Modern HTTP Client: Built on httpx for reliable HTTP operations

Installation

pip install ironbook-sdk

Quick Start

import asyncio
from ironbook_sdk import IronBookClient, RegisterAgentOptions, GetAuthTokenOptions, PolicyInput

async def main():
    # Initialize the client
    client = IronBookClient(api_key="your-api-key")
    
    # Register a new agent
    register_options = RegisterAgentOptions(
        agent_name="my-agent",
        capabilities=["query", "read"],
        developer_did="did:web:example.com"  # Optional
    )
    
    vc = await client.register_agent(register_options)
    print(f"Agent registered with VC: {vc}")
    
    # Get authentication token
    auth_options = GetAuthTokenOptions(
        agent_did="did:web:agent.example.com",
        vc=vc,
        audience="https://api.identitymachines.com",
        developer_did="did:web:example.com"  # Optional
    )
    
    token_data = await client.get_auth_token(auth_options)
    print(f"Auth token: {token_data}")
    
    # Make a policy decision
    policy_input = PolicyInput(
        did="did:web:agent.example.com",
        token=token_data["access_token"],
        action="query",
        resource="db://finance/tx"
    )
    
    decision = await client.policy_decision(policy_input)
    print(f"Policy decision: {decision.allow}")

# Run the async function
asyncio.run(main())

API Reference

IronBookClient

The main client class for interacting with Iron Book APIs.

Constructor

IronBookClient(api_key: str, base_url: str = "https://dev.identitymachines.com")

Parameters:

  • api_key (str): Your Iron Book API key
  • base_url (str, optional): Base URL for the API. Defaults to development environment.

Methods

register_agent(opts: RegisterAgentOptions) -> str

Registers a new agent and returns a Verifiable Credential.

vc = await client.register_agent(RegisterAgentOptions(
    agent_name="my-agent",
    capabilities=["query", "read"],
    developer_did="did:web:example.com"  # Optional
))
get_auth_token(opts: GetAuthTokenOptions) -> Dict[str, Any]

Gets an authentication token for an agent.

token_data = await client.get_auth_token(GetAuthTokenOptions(
    agent_did="did:web:agent.example.com",
    vc=vc,
    audience="https://api.identitymachines.com",
    developer_did="did:web:example.com"  # Optional
))
policy_decision(opts: PolicyInput) -> PolicyDecision

Gets a policy decision for an agent action.

decision = await client.policy_decision(PolicyInput(
    did="did:web:agent.example.com",
    token="jwt-token",
    action="query",
    resource="db://finance/tx",
    context={"amount": 1000, "ticker": "AAPL"}
))

Data Types

RegisterAgentOptions

Options for registering a new agent.

@dataclass
class RegisterAgentOptions:
    agent_name: str              # Name of the agent
    capabilities: List[str]      # List of agent capabilities
    developer_did: Optional[str] # Developer's DID (optional)

GetAuthTokenOptions

Options for getting an authentication token.

@dataclass
class GetAuthTokenOptions:
    agent_did: str      # Agent's DID
    vc: str            # Verifiable Credential
    audience: str      # Token audience (e.g., API endpoint)
    developer_did: Optional[str] # Developer's DID (optional)

PolicyInput

Input parameters for policy decision.

@dataclass
class PolicyInput:
    did: str                      # Agent DID (subject)
    token: str                    # Short-lived access token (JWT)
    action: str                   # Action (e.g., "query")
    resource: str                 # Resource (e.g., "db://finance/tx")
    context: Optional[Dict[str, Any]] # Optional context (amount, ticker, etc.)

PolicyDecision

Result of a policy decision evaluation.

@dataclass
class PolicyDecision:
    allow: bool                    # Whether the action is allowed
    evaluation: Optional[List[Any]] # Policy evaluation details
    reason: Optional[str]          # Reason for the decision

PolicyDecisionResult

Enumeration for policy decision results.

class PolicyDecisionResult(str, Enum):
    ALLOW = "allow"
    DENY = "deny"

UploadPolicyOptions

Options for uploading a policy.

@dataclass
class UploadPolicyOptions:
    agent_did: str                 # Agent's DID
    config_type: str               # Configuration type
    policy_content: str            # Policy content
    metadata: Any                  # Policy metadata
    developer_did: Optional[str]   # Developer's DID (optional)

Advanced Usage

Error Handling

import asyncio
from ironbook_sdk import IronBookClient

async def safe_agent_operation():
    client = IronBookClient(api_key="your-api-key")
    
    try:
        # Your operations here
        vc = await client.register_agent(...)
        return vc
    except Exception as e:
        print(f"Error: {e}")
        return None

asyncio.run(safe_agent_operation())

Custom Base URL

# Use production environment
client = IronBookClient(
    api_key="your-api-key",
    base_url="https://api.identitymachines.com"
)

Policy Decision with Context

# Make a policy decision with rich context
decision = await client.policy_decision(PolicyInput(
    did="did:web:agent.example.com",
    token="jwt-token",
    action="transfer",
    resource="bank://account/123",
    context={
        "amount": 5000,
        "currency": "USD",
        "recipient": "alice@example.com",
        "timestamp": "2024-01-15T10:30:00Z"
    }
))

if decision.allow:
    print("Transfer approved")
    if decision.reason:
        print(f"Reason: {decision.reason}")
else:
    print("Transfer denied")
    if decision.reason:
        print(f"Reason: {decision.reason}")

Upload Policy

# Upload a new access control policy
upload_options = UploadPolicyOptions(
    agent_did="did:web:agent.example.com",
    config_type="opa",
    policy_content="package policy\nallow { input.action == \"read\" }",
    metadata={"version": "1.0", "description": "Read-only policy"},
    developer_did="did:web:example.com"  # Optional
)

result = await client.upload_policy(upload_options)
print(f"Policy uploaded: {result}")

Development

Setting up the development environment

# Clone the repository
git clone https://github.com/your-org/ironbook-sdk-python.git
cd ironbook-sdk-python

# Install development dependencies
pip install -e .
pip install pytest pytest-asyncio

# Run tests
pytest

Building and publishing

# Install build tools
pip install build twine

# Build the package
python -m build

# Test upload to TestPyPI
twine upload --repository testpypi dist/*

# Upload to PyPI (when ready)
twine upload dist/*

Support

Changelog

0.1.0

  • Initial release
  • Agent registration functionality
  • Authentication token generation
  • Policy decision evaluation
  • Policy upload functionality
  • Async/await support
  • Comprehensive type hints
  • Context manager support for client lifecycle management
  • Convenience functions for simplified usage

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

ironbook_sdk-0.1.2.tar.gz (13.4 kB view details)

Uploaded Source

Built Distribution

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

ironbook_sdk-0.1.2-py3-none-any.whl (11.3 kB view details)

Uploaded Python 3

File details

Details for the file ironbook_sdk-0.1.2.tar.gz.

File metadata

  • Download URL: ironbook_sdk-0.1.2.tar.gz
  • Upload date:
  • Size: 13.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.7

File hashes

Hashes for ironbook_sdk-0.1.2.tar.gz
Algorithm Hash digest
SHA256 050571bbfac86831f90ae6cbf6e3e137304c9bfe0f3ba2592f9048f82a86c152
MD5 794b524504f0056e2ea38186bdfcba3f
BLAKE2b-256 7983c72dd37b406ea6f36701e7a905ec0ef85e5e3d24b0c07908aa21d520af19

See more details on using hashes here.

File details

Details for the file ironbook_sdk-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: ironbook_sdk-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 11.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.7

File hashes

Hashes for ironbook_sdk-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 df78730f4321b44b63d7b9d30d8af05af6d1b8330ec1e23beee81a3792d8e2bc
MD5 94e017aeb5db1c8ad77d0b5fdb91b02b
BLAKE2b-256 ccbeeff265e544a95b94c73744e6137a46d9171ac778493a0ed5a999723396a6

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