Skip to main content

A high performance and flexible authorization/permission engine built for developers and inspired by Google Zanzibar.

Project description

Python SDK for OpenFGA

pypi Release License FOSSA Status Discord Server Twitter

This is an autogenerated python SDK for OpenFGA. It provides a wrapper around the OpenFGA API definition.

Table of Contents

About

OpenFGA is an open source Fine-Grained Authorization solution inspired by Google's Zanzibar paper. It was created by the FGA team at Auth0 based on Auth0 Fine-Grained Authorization (FGA), available under a permissive license (Apache-2) and welcomes community contributions.

OpenFGA is designed to make it easy for application builders to model their permission layer, and to add and integrate fine-grained authorization into their applications. OpenFGA’s design is optimized for reliability and low latency at a high scale.

Resources

Installation

pip install

PyPI

The openfga_sdk is available to be downloaded via PyPI, you can install directly using:

pip3 install openfga_sdk

(you may need to run pip with root permission: sudo pip3 install openfga_sdk)

Then import the package:

import openfga_sdk

GitHub

The openfga_sdk is also hosted in GitHub, you can install directly using:

pip3 install https://github.com/openfga/python-sdk.git

(you may need to run pip with root permission: sudo pip3 install https://github.com/openfga/python-sdk.git)

Then import the package:

import openfga_sdk

Setuptools

Install via Setuptools.

python setup.py install --user

(or sudo python setup.py install to install the package for all users)

Then import the package:

import openfga_sdk

Getting Started

Initializing the API Client

Learn how to initialize your SDK

The documentation below refers to the OpenFgaClient, to read the documentation for OpenFgaApi, check out the v0.1.1 documentation.

The OpenFgaClient will by default retry API requests up to 15 times on 429 and 5xx errors.

No Credentials

import openfga_sdk
from openfga_sdk.client import OpenFgaClient


async def main():
    configuration = openfga_sdk.ClientConfiguration(
        api_scheme = OPENFGA_API_SCHEME, # optional, defaults to "https"
        api_host = OPENFGA_API_HOST, # required, define without the scheme (e.g. api.fga.example instead of https://api.fga.example)
        store_id = OPENFGA_STORE_ID, # optional, not needed when calling `CreateStore` or `ListStores`
        authorization_model_id = OPENFGA_AUTHORIZATION_MODEL_ID, # Optional, can be overridden per request
    )
    # Enter a context with an instance of the OpenFgaClient
    async with OpenFgaClient(configuration) as fga_client:
        api_response = await fga_client.read_authorization_models()
        await fga_client.close()

API Token

import openfga_sdk
from openfga_sdk.client import OpenFgaClient
from openfga_sdk.credentials import Credentials, CredentialConfiguration


async def main():
    configuration = openfga_sdk.ClientConfiguration(
        api_scheme = OPENFGA_API_SCHEME, # optional, defaults to "https"
        api_host = OPENFGA_API_HOST, # required, define without the scheme (e.g. api.fga.example instead of https://api.fga.example)
        store_id = OPENFGA_STORE_ID, # optional, not needed when calling `CreateStore` or `ListStores`
        authorization_model_id = OPENFGA_AUTHORIZATION_MODEL_ID, # Optional, can be overridden per request
        credentials = Credentials(
            method='api_token',
            configuration=CredentialConfiguration(
                api_token= OPENFGA_API_TOKEN,
            )
        )
    )
    # Enter a context with an instance of the OpenFgaClient
    async with OpenFgaClient(configuration) as fga_client:
        api_response = await fga_client.read_authorization_models()
        await fga_client.close()

Client Credentials

import openfga_sdk
from openfga_sdk.client import OpenFgaClient
from openfga_sdk.credentials import Credentials, CredentialConfiguration


async def main():
    configuration = openfga_sdk.ClientConfiguration(
        api_scheme = OPENFGA_API_SCHEME, # optional, defaults to "https"
        api_host = OPENFGA_API_HOST, # required, define without the scheme (e.g. api.fga.example instead of https://api.fga.example)
        store_id = OPENFGA_STORE_ID, # optional, not needed when calling `CreateStore` or `ListStores`
        authorization_model_id = OPENFGA_AUTHORIZATION_MODEL_ID, # Optional, can be overridden per request
        credentials = Credentials(
            method='client_credentials',
            configuration=CredentialConfiguration(
                api_issuer= OPENFGA_API_TOKEN_ISSUER,
                api_audience= OPENFGA_API_AUDIENCE,
                client_id= OPENFGA_CLIENT_ID,
                client_secret= OPENFGA_CLIENT_SECRET,
            )
        )
    )
    # Enter a context with an instance of the OpenFgaClient
    async with OpenFgaClient(configuration) as fga_client:
        api_response = await fga_client.read_authorization_models()
        await fga_client.close()

Get your Store ID

You need your store id to call the OpenFGA API (unless it is to call the CreateStore or ListStores methods).

If your server is configured with authentication enabled, you also need to have your credentials ready.

Calling the API

Stores

List Stores

Get a paginated list of stores.

API Documentation

options = {"page_size": 25, "continuation_token": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ=="}
response = await fga_client.list_stores(options)
# response = ListStoresResponse(...)
# response.stores = [Store({"id": "01FQH7V8BEG3GPQW93KTRFR8JB", "name": "FGA Demo Store", "created_at": "2022-01-01T00:00:00.000Z", "updated_at": "2022-01-01T00:00:00.000Z"})]
Create Store

Create and initialize a store.

API Documentation

body = CreateStoreRequest(
    name = "FGA Demo Store",
)
response = await fga_client.create_store(body)
# response.id = "01FQH7V8BEG3GPQW93KTRFR8JB"
Get Store

Get information about the current store.

API Documentation

Requires a client initialized with a storeId

response = await fga_client.get_store()
# response = Store({"id": "01FQH7V8BEG3GPQW93KTRFR8JB", "name": "FGA Demo Store", "created_at": "2022-01-01T00:00:00.000Z", "updated_at": "2022-01-01T00:00:00.000Z"})
Delete Store

Delete a store.

API Documentation

Requires a client initialized with a storeId

response = await fga_client.delete_store()

Authorization Models

Read Authorization Models

Read all authorization models in the store.

API Documentation

options = {"page_size": 25, "continuation_token": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ=="}
response = await fga_client.read_authorization_models(options)
# response.authorization_models = [AuthorizationModel(id='01GXSA8YR785C4FYS3C0RTG7B1', schema_version = '1.1', type_definitions=type_definitions[...], AuthorizationModel(id='01GXSBM5PVYHCJNRNKXMB4QZTW', schema_version = '1.1', type_definitions=type_definitions[...])]
Write Authorization Model

Create a new authorization model.

API Documentation

Note: To learn how to build your authorization model, check the Docs at https://openfga.dev/docs.

Learn more about the OpenFGA configuration language.

You can use the OpenFGA Syntax Transformer to convert between the friendly DSL and the JSON authorization model.

body = WriteAuthorizationModelRequest(
    schema_version = "1.1",
    type_definitions=[
        TypeDefinition(
            type="user",
        ),
        TypeDefinition(
            type="document",
            relations=dict(
                writer=Userset(
                    this=dict(),
                ),
                viewer=Userset(
                    union=Usersets(
                        child=[
                            Userset(this=dict()),
                            Userset(computed_userset=ObjectRelation(
                                object="",
                                relation="writer",
                            )),
                        ],
                    ),
                ),
            )
        ),
    ],
)

response = await fga_client.write_authorization_model(body)
# response.authorization_model_id = "01GXSA8YR785C4FYS3C0RTG7B1"
Read a Single Authorization Model

Read a particular authorization model.

API Documentation

options = {
    # You can rely on the model id set in the configuration or override it for this specific request
    "authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1"
}

response = await fga_client.read_authorization_model(id)
# response.authorization_model =  AuthorizationModel(id='01GXSA8YR785C4FYS3C0RTG7B1', schema_version = '1.1', type_definitions=type_definitions[...])
Read the Latest Authorization Model

Reads the latest authorization model (note: this ignores the model id in configuration).

API Documentation

response = await fga_client.read_latest_authorization_model()
# response.authorization_model =  AuthorizationModel(id='01GXSA8YR785C4FYS3C0RTG7B1', schema_version = '1.1', type_definitions=type_definitions[...])

Relationship Tuples

Read Relationship Tuple Changes (Watch)

Reads the list of historical relationship tuple writes and deletes.

API Documentation

options = {
    # You can rely on the model id set in the configuration or override it for this specific request
    "page_size": "25",
    "continuation_token": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ=="
}
body = ClientReadChangesRequest("document")

response = await fga_client.read_changes(body, options)
# response.continuation_token = ...
# response.changes = [TupleChange(tuple_key=TupleKey(object="...",relation="...",user="..."),operation=TupleOperation("TUPLE_OPERATION_WRITE"),timestamp=datetime.fromisoformat("..."))]
Read Relationship Tuples

Reads the relationship tuples stored in the database. It does not evaluate nor exclude invalid tuples according to the authorization model.

API Documentation

# Find if a relationship tuple stating that a certain user is a viewer of certain document
body = TupleKey(
    user="user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    relation="viewer",
    object="document:roadmap",
)

response = await fga_client.read(body)
# response = ReadResponse({"tuples": [Tuple({"key": TupleKey({"user":"...","relation":"...","object":"..."}), "timestamp": datetime.fromisoformat("...") })]})
# Find all relationship tuples where a certain user has a relationship as any relation to a certain document
body = TupleKey(
    user="user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    object="document:roadmap",
)

response = await fga_client.read(body)
# response = ReadResponse({"tuples": [Tuple({"key": TupleKey({"user":"...","relation":"...","object":"..."}), "timestamp": datetime.fromisoformat("...") })]})
# Find all relationship tuples where a certain user is a viewer of any document
body = TupleKey(
    user="user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    relation="viewer",
    object="document:",
)

response = await fga_client.read(body)
# response = ReadResponse({"tuples": [Tuple({"key": TupleKey({"user":"...","relation":"...","object":"..."}), "timestamp": datetime.fromisoformat("...") })]})
# Find all relationship tuples where any user has a relationship as any relation with a particular document
body = TupleKey(
    object="document:roadmap",
)

response = await fga_client.read(body)
# response = ReadResponse({"tuples": [Tuple({"key": TupleKey({"user":"...","relation":"...","object":"..."}), "timestamp": datetime.fromisoformat("...") })]})
# Read all stored relationship tuples
body = TupleKey()

response = await api_instance.read(body)
# response = ReadResponse({"tuples": [Tuple({"key": TupleKey({"user":"...","relation":"...","object":"..."}), "timestamp": datetime.fromisoformat("...") })]})
Write (Create and Delete) Relationship Tuples

Create and/or delete relationship tuples to update the system state.

API Documentation

Transaction mode (default)

By default, write runs in a transaction mode where any invalid operation (deleting a non-existing tuple, creating an existing tuple, one of the tuples was invalid) or a server error will fail the entire operation.

options = {
    # You can rely on the model id set in the configuration or override it for this specific request
    "authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1"
}
body = ClientWriteRequest(
    writes=[
        ClientTuple(
            user="user:81684243-9356-4421-8fbf-a4f8d36aa31b",
            relation="viewer",
            object="document:roadmap",
        ),
        ClientTuple(
            user="user:81684243-9356-4421-8fbf-a4f8d36aa31b",
            relation="viewer",
            object="document:budget",
        ),
    ],
    deletes=[
        ClientTuple(
            user="user:81684243-9356-4421-8fbf-a4f8d36aa31b",
            relation="writer",
            object="document:roadmap",
        ),
    ],
)

response = await fga_client.write(body, options)

Convenience write_tuples and delete_tuples methods are also available.

Non-transaction mode

The SDK will split the writes into separate requests and send them sequentially to avoid violating rate limits.

options = {
    # You can rely on the model id set in the configuration or override it for this specific request
    "authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1",
    "transaction": WriteTransactionOpts(
        disabled=True,
        max_parallel_requests=10, # Maximum number of requests to issue in parallel
        max_per_chunk=1, # Maximum number of requests to be sent in a transaction in a particular chunk
    )
}
body = ClientWriteRequest(
    writes=[
        ClientTuple(
            user="user:81684243-9356-4421-8fbf-a4f8d36aa31b",
            relation="viewer",
            object="document:roadmap",
        ),
        ClientTuple(
            user="user:81684243-9356-4421-8fbf-a4f8d36aa31b",
            relation="viewer",
            object="document:budget",
        ),
    ],
    deletes=[
        ClientTuple(
            user="user:81684243-9356-4421-8fbf-a4f8d36aa31b",
            relation="writer",
            object="document:roadmap",
        ),
    ],
)

response = await fga_client.write(body, options)

Relationship Queries

Check

Check if a user has a particular relation with an object.

API Documentation

options = {
    # You can rely on the model id set in the configuration or override it for this specific request
    "authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1"
}
body = ClientCheckRequest(
    user="user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    relation="writer",
    object="document:roadmap",
)

response = await fga_client.check(body, options)
# response.allowed = True
Batch Check

Run a set of checks. Batch Check will return allowed: false if it encounters an error, and will return the error in the body. If 429s or 5xxs are encountered, the underlying check will retry up to 15 times before giving up.

options = {
    # You can rely on the model id set in the configuration or override it for this specific request
    "authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1"
}
body = [ClientCheckRequest(
    user="user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    relation="viewer",
    object="document:roadmap",
    contextual_tuples=[ # optional
        ClientTuple(
            user="user:81684243-9356-4421-8fbf-a4f8d36aa31b",
            relation="editor",
            object="document:roadmap",
        ),
    ]
), ClientCheckRequest(
    user="user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    relation="admin",
    object="document:roadmap",
    contextual_tuples=[ # optional
        ClientTuple(
            user="user:81684243-9356-4421-8fbf-a4f8d36aa31b",
            relation="editor",
            object="document:roadmap",
        ),
    ]
), ClientCheckRequest(
    user="user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    relation="creator",
    object="document:roadmap",
), ClientCheckRequest(
    user="user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    relation="deleter",
    object="document:roadmap",
)]

response = await fga_client.batch_check(body, options)
# response.responses = [{
#   allowed: false,
#   request: {
#     user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
#     relation: "viewer",
#     object: "document:roadmap",
#     contextual_tuples: [{
#       user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
#       relation: "editor",
#       object: "document:roadmap"
#     }]
#   }
# }, {
#   allowed: false,
#   request: {
#     user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
#     relation: "admin",
#     object: "document:roadmap",
#     contextual_tuples: [{
#       user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
#       relation: "editor",
#       object: "document:roadmap"
#     }]
#   }
# }, {
#   allowed: false,
#   request: {
#     user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
#     relation: "creator",
#     object: "document:roadmap",
#   },
#   error: <FgaError ...>
# }, {
#   allowed: true,
#   request: {
#     user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
#     relation: "deleter",
#     object: "document:roadmap",
#   }},
# ]

Expand

Expands the relationships in userset tree format.

API Documentation

options = {
    # You can rely on the model id set in the configuration or override it for this specific request
    "authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1"
}
body = ClientExpandRequest(
    relation="viewer",
    object="document:roadmap",
)

response = await fga_client.expand(body. options)
# response = ExpandResponse({"tree": UsersetTree({"root": Node({"name": "document:roadmap#viewer", "leaf": Leaf({"users": Users({"users": ["user:81684243-9356-4421-8fbf-a4f8d36aa31b", "user:f52a4f7a-054d-47ff-bb6e-3ac81269988f"]})})})})})
List Objects

List the objects of a particular type a user has access to.

API Documentation

options = {
    # You can rely on the model id set in the configuration or override it for this specific request
    "authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1"
}
body = ClientListObjectsRequest(
    user="user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    relation="viewer",
    type="document",
    contextual_tuples=[ # optional
        ClientTuple(
            user="user:81684243-9356-4421-8fbf-a4f8d36aa31b",
            relation="writer",
            object="document:budget",
        ),
    ]
)

response = await fga_client.list_objects(body)
# response.objects = ["document:roadmap"]
List Relations

List the relations a user has on an object.

options = {
    # You can rely on the model id set in the configuration or override it for this specific request
    "authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1"
}
body = ClientListRelationsRequest(
    user = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    object = "document:roadmap",
    relations = ["can_view", "can_edit", "can_delete", "can_rename"],
    contextual_tuples=[ # optional
        ClientTuple(
            user="user:81684243-9356-4421-8fbf-a4f8d36aa31b",
            relation="writer",
            object="document:budget",
        ),
    ]
)
var response = await fga_client.list_relations(body, options);

// response.relations = ["can_view", "can_edit"]

Assertions

Read Assertions

Read assertions for a particular authorization model.

API Documentation

options = {
    # You can rely on the model id set in the configuration or override it for this specific request
    "authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1"
}
response = await fga_client.read_assertions(options);
Write Assertions

Update the assertions for a particular authorization model.

API Documentation

options = {
    # You can rely on the model id set in the configuration or override it for this specific request
    "authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1"
}
body = [ClientAssertion(
    user = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    relation = "viewer",
    object = "document:roadmap",
    expectation = true,
)];
response = await fga_client.write_assertions(body, options);

API Endpoints

Class Method HTTP request Description
OpenFgaApi check POST /stores/{store_id}/check Check whether a user is authorized to access an object
OpenFgaApi create_store POST /stores Create a store
OpenFgaApi delete_store DELETE /stores/{store_id} Delete a store
OpenFgaApi expand POST /stores/{store_id}/expand Expand all relationships in userset tree format, and following userset rewrite rules. Useful to reason about and debug a certain relationship
OpenFgaApi get_store GET /stores/{store_id} Get a store
OpenFgaApi list_objects POST /stores/{store_id}/list-objects List all objects of the given type that the user has a relation with
OpenFgaApi list_stores GET /stores List all stores
OpenFgaApi read POST /stores/{store_id}/read Get tuples from the store that matches a query, without following userset rewrite rules
OpenFgaApi read_assertions GET /stores/{store_id}/assertions/{authorization_model_id} Read assertions for an authorization model ID
OpenFgaApi read_authorization_model GET /stores/{store_id}/authorization-models/{id} Return a particular version of an authorization model
OpenFgaApi read_authorization_models GET /stores/{store_id}/authorization-models Return all the authorization models for a particular store
OpenFgaApi read_changes GET /stores/{store_id}/changes Return a list of all the tuple changes
OpenFgaApi write POST /stores/{store_id}/write Add or delete tuples from the store
OpenFgaApi write_assertions PUT /stores/{store_id}/assertions/{authorization_model_id} Upsert assertions for an authorization model ID
OpenFgaApi write_authorization_model POST /stores/{store_id}/authorization-models Create a new authorization model

Models

Documentation For Models

Contributing

Issues

If you have found a bug or if you have a feature request, please report them on the sdk-generator repo issues section. Please do not report security vulnerabilities on the public GitHub issue tracker.

Pull Requests

All changes made to this repo will be overwritten on the next generation, so we kindly ask that you send all pull requests related to the SDKs to the sdk-generator repo instead.

Author

OpenFGA

License

This project is licensed under the Apache-2.0 license. See the LICENSE file for more info.

The code in this repo was auto generated by OpenAPI Generator from a template based on the python legacy template, licensed under the Apache License 2.0.

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

openfga-sdk-0.2.1.tar.gz (120.5 kB view hashes)

Uploaded Source

Built Distribution

openfga_sdk-0.2.1-py3-none-any.whl (176.0 kB view hashes)

Uploaded Python 3

Supported by

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