1Password Python SDK

repository·main·Indexed 41 days ago

https://github.com/1password/onepassword-sdk-python

A Python SDK for programmatically managing 1Password items, vaults, and secrets. It supports both local desktop app authentication for human-in-the-loop workflows and service account authentication for automated environments. Key capabilities include secret retrieval via URIs, TOTP resolution, item and vault management, password generation, and handling specialized item types like SSH keys and documents.

Tokens
9K
Snippets
40
Records
47
Agent score
52%

What's inside 1Password

  1. Overview of supported operations in the 1Password Python SDK

    main

    The SDK allows for comprehensive management of 1Password data. Key capabilities demonstrated in the examples include:

    • Authentication: Using a service account token.
    • Discovery: Listing available vaults and items within those vaults.
    • Secret Retrieval: Retrieving specific secrets and resolving TOTP (one-time password) codes.
    • Item Management:
      • Creating new items with multiple fields and tags.
      • Updating existing items (modifying fields, adding websites).
      • Archiving or deleting items.
    • Password Generation: Generating PINs, memorable passwords, and random passwords.
    • Sharing: Sharing items with recipients and generating shareable links.
    • Specialized Item Types:
      • SSH Keys: Creating and managing SSH key items (including public keys and fingerprints).
      • Documents: Creating, replacing, and reading document items.
      • Files: Creating and managing file field items by attaching and deleting files.
  2. Install the 1Password Python SDK

    main

    Install the SDK using pip:

    pip install onepassword-sdk

    Requirements

    Ensure your environment meets the following criteria:

    • python 3.9 or later
    • libssl 3
    • glibc 2.32 or later

    Note: If you are on a Linux distribution using libssl 1.1.1 (e.g., Debian 11 or Ubuntu 20.04), you must update to a later version or install the required dependencies.

    pip install onepassword-sdk
  3. Set up environment variables for the 1Password Python SDK

    main

    Before running examples or using the SDK with a service account, you must export your service account token and the target vault UUID as environment variables.

    Required variables:

    • OP_SERVICE_ACCOUNT_TOKEN: Your valid 1Password service account token.
    • OP_VAULT_ID: The UUID of the vault you wish to interact with.
    export OP_SERVICE_ACCOUNT_TOKEN="<your token>"
    export OP_VAULT_ID="<your vault uuid>"
  4. Authenticate using the 1Password desktop app

    main

    Use this method for local integrations that require human-in-the-loop approval (e.g., biometrics via Touch ID or Windows Hello).

    1. Install the 1Password desktop app and sign in.
    2. In the app, go to Settings > Developer and select Integrate with other apps under 'Integrate with the 1Password SDKs'.
    3. (Optional) Enable biometrics in Settings > Security.
    4. In your code, use DesktopAuth and provide your account_name (the name appearing at the top left of your 1Password sidebar).
    import asyncio
    from onepassword.client import Client, DesktopAuth
    
    async def main():
        client = await Client.authenticate(
            auth=DesktopAuth(account_name="your-account-name"),
            integration_name="My 1Password Integration",
            integration_version="v1.0.0",
        )
        # ...
    
    asyncio.run(main())
  5. Authenticate using a 1Password Service Account

    main

    Use this method for automated access and least-privilege workflows.

    1. Create a service account and grant it permissions to the necessary vaults.
    2. Provision a service account token. It is recommended to use the OP_SERVICE_ACCOUNT_TOKEN environment variable.

    macOS or Linux:

    export OP_SERVICE_ACCOUNT_TOKEN=<your-service-account-token>

    Windows:

    $Env:OP_SERVICE_ACCOUNT_TOKEN = "<your-service-account-token>"
    1. In your code, pass the token directly to Client.authenticate().
    import asyncio
    import os
    from onepassword.client import Client
    
    async def main():
        token = os.getenv("OP_SERVICE_ACCOUNT_TOKEN")
        client = await Client.authenticate(
            auth=token, 
            integration_name="My 1Password Integration", 
            integration_version="v1.0.0"
        )
        # ...
    
    asyncio.run(main())
  6. Understand 1Password Item structures

    main

    A 1Password Item is a collection of fields, sections, and metadata.

    Key components include:

    • Fields: Individual data points (e.g., username, password, URL) identified by an id and title. Fields have a field_type (e.g., Text, Concealed, Totp, SshKey).
    • Sections: Logical groupings of fields within an item.
    • Websites: A list of Website objects used for autofill behavior (e.g., ExactDomain, AnywhereOnWebsite).
    • Files: Items can contain ItemFile objects stored within specific sections or fields.
    • Metadata: Includes tags, notes, category (e.g., Login, SecureNote, Password), and timestamps (created_at, updated_at).

    Note that some fields provide specialized details via ItemFieldDetails, such as OtpFieldDetails for TOTP codes or SshKeyAttributes for SSH keys.

  7. Understand 1Password Vault structures

    main

    A Vault represents a container for items.

    Key attributes include:

    • ID and Title: Unique identifier and display name.
    • Vault Type: Can be personal, everyone, transfer, or userCreated.
    • Versions: content_version increments when items change; attribute_version increments when vault metadata (like title) changes.
    • Access: Managed via VaultAccess objects, which define how a user or group accesses the vault and what permissions they hold.
  8. Resolve secrets using secret reference URIs

    main

    To securely load secrets into your code, use secret reference URIs with the syntax op://vault/item/field. Use the client.secrets.resolve() method to retrieve the actual value.

    import asyncio
    from onepassword.client import Client, DesktopAuth
    
    async def main():
        client = await Client.authenticate(
            auth=DesktopAuth(account_name="your-account-name"),
            integration_name="My Integration",
            integration_version="v1.0.0",
        )
        
        # Resolves the secret value from the URI
        value = await client.secrets.resolve("op://vault/item/field")
        print(value)
    
    asyncio.run(main())
  9. Update or delete a vault

    main

    To modify an existing vault or remove it entirely:

    1. Update: Use update with VaultUpdateParams to change vault settings. async def update(self, vault_id: str, params: VaultUpdateParams) -> Vault

    2. Delete: Use delete to remove a vault by its ID. async def delete(self, vault_id: str) -> None

    # Update
    await vaults.update(vault_id="vault_id", params=VaultUpdateParams(name="New Name"))
    
    # Delete
    await vaults.delete(vault_id="vault_id")
  10. Create an item sharing link with `create`

    main

    Generate a new item sharing link. This requires an Item object, an ItemShareAccountPolicy, and ItemShareParams. The method returns the sharing link as a string.

    # item: Item
    # policy: ItemShareAccountPolicy
    # params: ItemShareParams
    sharing_link = await items_shares.create(item=item, policy=policy, params=params)
    print(f"Sharing link: {sharing_link}")