Hi. My name is Graham. I am the sole technical per...
# permit-saas
g
Hi. My name is Graham. I am the sole technical person in a partnership. We train business women. Our customer base is small. We want to provide management procedures online and a client training platform. Expecting under 100 users. My expertise is python and have built a simple FastApi application (to be built out later). I use Auth0 and Permit.io. I would like help with the authorisation flow once Auth0 has returned a token. Thank you
a
Hi @Graham, I'm an AI assistant for Permit.io. I'll analyze available sources and get back to you shortly.
Hi Graham! I can help you implement the authorization flow with FastAPI and Permit.io after Auth0 authentication. Here's how to set it up: Initial Setup First, add your Permit credentials to your
.env
file (1) :
Copy code
PERMIT_API_KEY="your_permit_api_key"
PERMIT_PDP_URL="your_permit_pdp_url"
Initialize Permit SDK Create a
permit.py
file to initialize the SDK :
Copy code
from permit import Permit
from constants import PERMIT_API_KEY, PERMIT_PDP_URL
permit = Permit(
   pdp=PERMIT_PDP_URL,
   token=PERMIT_API_KEY,
)
Create Authorization Check Function Create an
authorization.py
file with this permission checking utility :
Copy code
from fastapi import HTTPException, Depends, Request, Response
from lib.permit import permit
from utils.dependencies import get_user
from models.db import User
async def check_permission(action: str, resource: str, user: User) :
    """
 Checks if a user is authorized to perform a specific action on a resource.
 """
    print("checking permission")
    try:
        allowed = await permit.check(
            str(user.id) ,
            action,
            {
                "type": resource,
            },
        )
        if not allowed:
            raise HTTPException(status_code=403, detail="Forbidden: Not allowed")
        return True
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Authorization error: {str(e) }")
Sync Users from Auth0 to Permit When a user signs up or logs in via Auth0, sync them to Permit :
Copy code
async def create_role(user) :
    try:
        await permit.api.users.sync(
            {
                "key": user["id"],
                "email": user["email"],
                "first_name": user["surname"],
                "last_name": user["surname"],
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Authorization error: {str(e) }")
Copy code
async def assign_role(user_id: str, role: str) :
    try:
        await permit.api.users.assign_role(
            {
                # the user key
                "user": user_id,
                # the role key
                "role": role,
                # the tenant key
                "tenant": "default",
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Authorization error: {str(e) }")
Protect Your Routes Use the
check_permission
function in your FastAPI routes :
Copy code
@router.get("/dashboard")
async def dashboard(
 request: Request,
 user: db.User = Depends(get_user) ,
 ) :
    """
 Render the dashboard page showing all contacts.
 """
    if user is None:
        return RedirectResponse(url="/login")

    await check_permission(action="readany", resource="contact", user=user)
    try:
        contacts = contact_service.get_all_contacts()
        return templates.TemplateResponse(
            "dashboard.jinja",
            {
                "request": request,
                "contacts": contacts,
                "user": user,
            },
        )
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e) )
Basic Permission Check For simpler checks, you can use (2) :
Copy code
await permit.check(user, "read", { type: "Account", tenant }) ;
This flow ensures that after Auth0 authenticates a user, Permit.io handles the authorization based on roles and permissions you define in your Permit dashboard.
To learn more, see the sources I considered: [[1] FastAPI RBAC - Full Implementation Tutorial](https://www.permit.io/blog/fastapi-rbac-full-implementation-tutorial) [[2] Fintech / Banking Demo Application](https://docs.permit.io/modeling/mesa-verde)
g
What role do I give a new user?
o
@tag @Ask Inkeep to get it to follow up
a
Thanks for tagging me @Or Weis. I'll look through relevant sources and get back to you shortly.
When deciding what role to assign a new user, you should consider your application's access control requirements. By default, Permit.io provides some standard roles (1) : • ​*Admin*​ - Full access with actions: Read, Create, Update, Delete • ​*Editor*​ - Moderate access with actions: Read, Create, Update • ​*Viewer*​ - Limited access with action: Read For your training platform with management procedures, you might want to start new users with minimal permissions and upgrade them as needed (2) . Here's how to assign roles programmatically: ​*Node.js example:*​
Copy code
await permit.api.roleAssignments.assign({
  role: "Marketer",
  tenant: "default",
  resource_instance: `Dashboard:${dashboard.id}`,
  user: "auth0|elon",
}) ;
​*Java example:*​
Copy code
RoleAssignmentRead ra = permit.api.users.assignRole("<mailto:elon@tesla.com|elon@tesla.com>", "admin", "tesla") ;
(3) ​*.NET example:*​
Copy code
var response = await permitClient.Api.AssignRole(userId, roleId, tenantId) ;
(4) Since you're building a training platform for business women, you might want to create custom roles that match your business needs (5) - perhaps roles like "Trainer", "Student", or "Administrator" - and assign new users to "Student" by
To learn more, see the sources I considered: [[1] Policy Basics](https://docs.permit.io/how-to/build-policies/policy-basics) [[2] Sync Data into your App](https://docs.permit.io/overview/sync-applications-data) [[3] permit.api.users.assignRole()](https://docs.permit.io/sdk/java/role/assign-role) [[4] AssignRole](https://docs.permit.io/sdk/dotnet/role/AssignRole) [[5] Configure your first RBAC Policy](https://docs.permit.io/overview/configure-your-first-rbac-policy)
g
@tag @Ask Inkeep I use python and fastapi
a
Thanks for tagging me @Graham. I'll look through relevant sources and get back to you shortly.
For Python/FastAPI applications, here's how to assign roles to new users: In the FastAPI RBAC tutorial example, new users are assigned the "viewer" role by default (1) :
Copy code
async def assign_role(user_id: str, role: str) :
    try:
        await permit.api.users.assign_role(
            {
                # the user key
                "user": user_id,
                # the role key
                "role": role,
                # the tenant key
                "tenant": "default",
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Authorization error: {str(e) }")
When a new user registers, you would sync them to Permit and assign their initial role :
Copy code
await create_role(created_user_dict)
await assign_role(created_user_dict["id"], "viewer")
For your training platform, you can create custom roles that match your business needs. The example shows a contact management system with two roles : • ​*Admin*​: Can manage all contacts in the application • ​*Viewer*​: Can only manage their own contacts You'd typically start new users with the most restrictive role (like "viewer" or "student") and upgrade their permissions as needed based on your business requirements.
To learn more, see the sources I considered: [[1] FastAPI RBAC - Full Implementation Tutorial](https://www.permit.io/blog/fastapi-rbac-full-implementation-tutorial)
g
@tag @Ask Inkeep explain, from previous code, create role and assign role
a
Thanks for tagging me @Graham. I'll look through relevant sources and get back to you shortly.
Looking at the previous code, let me clarify the difference between
create_role
and
assign_role
functions: ​*The
create_role
function*​ (which is actually syncing a user, not creating a role) : This function syncs a user from your authentication system (Auth0) to Permit.io. Despite its misleading name, it's actually creating/updating a user in Permit: (1) , (2)
Copy code
async def create_role(user) :
    try:
        await permit.api.users.sync(
            {
                "key": user["id"],
                "email": user["email"],
                "first_name": user["surname"],
                "last_name": user["surname"],
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Authorization error: {str(e) }")
(1) This uses the
permit.api.users.sync()
method which creates a new user in Permit if they don't exist, or updates them if they do. (3) , (4) ​*The
assign_role
function*​: This function assigns a specific role to a user within a tenant: (1)
Copy code
async def assign_role(user_id: str, role: str) :
    try:
        await permit.api.users.assign_role(
            {
                # the user key
                "user": user_id,
                # the role key
                "role": role,
                # the tenant key
                "tenant": "default",
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Authorization error: {str(e) }")
The workflow is: 1. First, sync the user to Permit (despite the function name
create_role
) 2. Then, assign them a role like "viewer" or "admin" in your default tenant Note: The function naming in the example is confusing -
create_role
should really be called something like
sync_user
since it's not creating roles but syncing user data to Permit.
g
@tag @Ask Inkeep I understand Auth0. I did not think the previous example used it. Please explain the reason for the create role and assign role
a
Thanks for tagging me @Graham. I'll look through relevant sources and get back to you shortly.
Let me explain why you need both functions when working with Permit.io, regardless of which authentication provider you use: ​*Why sync users to Permit.io*​ Even though Auth0 (or any auth provider) handles authentication, Permit.io needs to know about your users to make authorization decisions. The
create_role
function (which should be called
sync_user
) creates or updates a user in Permit.io's system (1) :
Copy code
async def create_role(user) :
    try:
        await permit.api.users.sync(
            {
                "key": user["id"],
                "email": user["email"],
                "first_name": user["surname"],
                "last_name": user["surname"],
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Authorization error: {str(e) }")
​*Why assign roles*​ After Permit.io knows about the user, you need to give them permissions. The
assign_role
function grants a specific role (like "viewer" or "admin") to that user :
Copy code
async def assign_role(user_id: str, role: str) :
    try:
        await permit.api.users.assign_role(
            {
                # the user key
                "user": user_id,
                # the role key
                "role": role,
                # the tenant key
                "tenant": "default",
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Authorization error: {str(e) }")
​*The complete flow*​ When a new user registers in your FastAPI app :
Copy code
await create_role(created_user_dict)
await assign_role(created_user_dict["id"], "viewer")
This two-step process is necessary because: 1. Permit.io needs to track users separately from your auth provider to manage permissions 2. Each user needs explicit role assignments to determine what they can access in your application Without syncing users to Permit.io, the authorization checks (
permit.check()
) would fail because Permit.io wouldn't recognize the user ID from your auth provider.
To learn more, see the sources I considered: [[1] FastAPI RBAC - Full Implementation Tutorial](https://www.permit.io/blog/fastapi-rbac-full-implementation-tutorial)
g
@Ask Inkeep in the permit UI what are user instances
a
Thanks for tagging me @Graham. I'll look through relevant sources and get back to you shortly.
In the Permit UI, "user instances" refer to individual users that have been synced to Permit.io (1) . These are the actual user records in your application that Permit uses to make authorization decisions. According to the documentation, users are entities (humans or automated entities) whose access you want to control . Each user has an identity that can be authenticated and authorized to access certain resources . When you sync users to Permit (like in your FastAPI app) , they appear as user instances in the UI. You can manage them through the User Management screen : 1. Navigate to the User Management screen via the navigation bar 2. View all synced users in the currently selected tenant 3. Create new users or edit existing ones Users can be assigned to tenants (each user can belong to more than one tenant) and can then be assigned roles and permissions . The distinction is important: "Users" refers to your application's end users, while "Members" refers to your team members who work within the Permit app itself .
To learn more, see the sources I considered: [[1] Sync Users](https://docs.permit.io/how-to/sync-users)
g
@Ask Inkeep no instance resourse
a
Thanks for tagging me @Graham. I'll look through relevant sources and get back to you shortly.
In the Permit UI, "resource instances" are specific occurrences of resources that you've defined in your authorization model (1) . They represent actual objects in your application that users can interact with. For example, if you have a "Document" resource type, each individual document (like "budget_report" or "salary_report") would be a resource instance . Here's how to create resource instances using the SDK: ​*Python example:*​
Copy code
await permit.api.resource_instances.create({
    key: "react",
    resource: "repository",
    tenant: "default",
    attributes: {
        private: "false",
        owner: "Company C",
    },
}) ;
​*Ruby example:*​
Copy code
def create_resource_instance(proj_id, env_id, resource_instance_create, opts = {})
  data, _status_code, _headers = create_resource_instance_with_http_info(proj_id, env_id, resource_instance_create, opts)
  data
end
(2) ​*Go example:*​
Copy code
func (a *ResourceInstancesApiService) CreateResourceInstance(ctx context.Context, projId string, envId string) ApiCreateResourceInstanceRequest {
	return ApiCreateResourceInstanceRequest{
		ApiService: a,
		ctx:        ctx,
		projId:     projId,
		envId:      envId,
	}
}
(3) Resource instances can have attributes that are used for ABAC (Attribute-Based Access Control) policies (1) . In the UI, you can navigate to Directory > Instances to view and manage your resource instances .
To learn more, see the sources I considered: [[1] Sync Data into your App](https://docs.permit.io/overview/sync-applications-data) [[2] permitio/permit-ruby/lib/openapi_client/api/resource_instances_api.rb](https://github.com/permitio/permit-ruby/blob/main/lib/openapi_client/api/resource_instances_api.rb) [[3] permitio/permit-golang/pkg/openapi/api_resource_instances.go](https://github.com/permitio/permit-golang/blob/master/pkg/openapi/api_resource_instances.go)
g
@Ask Inkeep more examples
a
Thanks for tagging me @Graham. I'll look through relevant sources and get back to you shortly.
Here are more examples of working with resource instances in Permit.io: ​*Creating Resource Instances with Attributes*​ From the Mesa Verde banking demo (1) :
Copy code
const resourceInstance = await permit.api.resourceInstances.create({  
 resource: "Transaction",  
 key: transaction.id,  
 tenant,  
 attributes: {  
 ...transaction,  
 },  
}) ;
​*Resource Instance with Specific Attributes*​ For a repository resource (2) :
Copy code
await permit.api.resource_instances.create({
 key: "react",
 resource: "repository",
 tenant: "default",
 attributes: {
 private: "false",
 owner: "Company C",
 },
}) ;
​*Assigning Roles to Resource Instances*​ You can assign users to specific resource instances :
Copy code
await permit.api.roleAssignments.assign({
 role: "Marketer",
 tenant: "default",
 resource_instance: `Dashboard:${dashboard.id}`,
 user: "auth0|elon",
}) ;
​*Resource Instance Roles in Banking Context*​ The Mesa Verde demo shows resource-level role assignments (1) :
Copy code
await permit.api.roleAssignments.assign({  
 role: "Sender",  
 tenant,  
 resource_instance: `Transaction:${transaction.id}`,  
 user,  
}) ;
​*Checking Permissions with Resource Attributes*​ When checking permissions, you can include resource attributes :
Copy code
const transactionAllowed = await permit.check(  
 {  
 key: user,  
 attributes: { strongAuth: !!OTP, location },  
 },  
 "create",  
 {  
 type: "Transaction",  
 attributes: { ...transaction },  
 tenant,  
 }  
) ;
Resource instances allow you to implement fine-grained permissions on specific objects in your application, not just resource types (2) (1) .
To learn more, see the sources I considered: [[1] Fintech / Banking Demo Application](https://docs.permit.io/modeling/mesa-verde) [[2] Sync Data into your App](https://docs.permit.io/overview/sync-applications-data)
g
@Ask Inkeep are these advanced use cases?
a
Thanks for tagging me @Graham. I'll look through relevant sources and get back to you shortly.
Resource instances and resource-level role assignments are indeed more advanced use cases in Permit.io. Here's the distinction: ​*Basic Use Cases:*​ • Simple RBAC where users have roles like "admin" or "viewer" at the tenant level • Checking if a user can perform an action on a resource type (e.g., "can user read documents?") ​*Advanced Use Cases (like resource instances) :*​ The Mesa Verde banking demo showcases these advanced patterns (1) (2) : 1. ​*Resource-specific roles*​ - Users can have different roles on individual resources:
Copy code
await permit.api.roleAssignments.assign({  
 role: "Sender",  
 tenant,  
 resource_instance: `Transaction:${transaction.id}`,  
 user,  
}) ;
(1) 2. ​*Attribute-based checks*​ - Permissions based on resource and user attributes:
Copy code
const transactionAllowed = await permit.check(  
 {  
 key: user,  
 attributes: { strongAuth: !!OTP, location },  
 },  
 "create",  
 {  
 type: "Transaction",  
 attributes: { ...transaction },  
 tenant,  
 }  
) ;
3. *Relationship-Based Access Control (ReBAC) * - The Google Drive example shows even more advanced patterns with relationships between resources (3) :
Copy code
await permit.api.relationshipTuples.create({
 subject: "folder:finance",
 relation: "parent",
 object: "file:2023_report",
}) ;
For your training platform with under 100 users, you might start with basic RBAC (users have roles like "trainer" or "student") and only implement resource instances if you need permissions on specific training modules or documents.
To learn more, see the sources I considered: [[1] Fintech / Banking Demo Application](https://docs.permit.io/modeling/mesa-verde) [[2] Fintech / Banking Demo Application](https://docs.permit.io/modeling/mesa-verde) [[3] Modeling Google Drive Permissions with ReBAC](https://docs.permit.io/modeling/google-drive)
g
@Ask Inkeep within my platform customers will purchase one off course, subscription based course.
a
Thanks for tagging me @Graham. I'll look through relevant sources and get back to you shortly.
Thanks for tagging me @Graham. I'll look through relevant sources and get back to you shortly. For your training platform with one-off and subscription-based courses, you'll want to model courses as resources and control access based on purchase status. Here's how to structure this with Permit.io: ​*Define Course Resources*​ Based on the policy modeling approach (1) (2) , you'd create resources for your courses:
Copy code
resource "permitio_resource" "Course" {
  key = "Course"
  name = "Course"
  actions = {
    "read" = {
      name = "Read"
    }
    "download" = {
      name = "Download"
    }
    "complete" = {
      name = "Complete"
    }
  }
  attributes = {
    "course_type" = {
      name = "Course Type"
      type = "string"
    }
    "price" = {
      name = "Price"
      type = "number"
    }
  }
}
(3) ​*Create Course-Specific Roles*​ Define roles that map to your business model (1) (4) :
Copy code
resource "permitio_role" "CourseOwner" {
  key = "CourseOwner"
  name = "Course Owner"
  permissions = [
    "Course:read",
    "Course:download",
    "Course:complete",
  ]
  depends_on = [permitio_resource.Course]
}

resource "permitio_role" "SubscriptionMember" {
  key = "SubscriptionMember"
  name = "Subscription Member"
  permissions = [
    "Course:read",
    "Course:complete",
  ]
  depends_on = [permitio_resource.Course]
}
(3) ​*Sync Course Instances When Purchased*​ When a customer purchases a course, create a resource instance :
Copy code
const resourceInstance = await permit.api.resourceInstances.create({
  resource: "Course",
  key: course.id,
  tenant,
  attributes: {
    ...course,
  },
}) ;
​*Assign Access Based on Purchase Type*​ For one-off purchases, assign course-specific access :
Copy code
await permit.api.roleAssignments.assign({
  role: "CourseOwner",
  tenant,
  resource_instance: `Course:${course.id}`,
  user,
}) ;
For subscription members, you could assign a tenant-level role that grants access to all subscription courses. ​*Check Course Access*​ When a user tries to access course content :
Copy code
const allowed = await permit.check(
  user.id,
  "read",
  {
    type: "Course",
    key: course.id,
    tenant: user.tenant
  }
) ;
This approach lets you manage both one-off purchases (resource-specific permissions) and subscription access (broader role-based permissions) within the same authorization framework.
To learn more, see the sources I considered: [[1] Policy Basics](https://docs.permit.io/how-to/build-policies/policy-basics) [[2] How to Model (and Implement) Cloud-Native Authorization](https://www.permit.io/blog/how-to-model-and-implement-cloud-native-authorization) [[3] Fintech / Banking Demo Application](https://docs.permit.io/modeling/mesa-verde) [[4] Components](https://docs.permit.io/how-to/build-policies/rbac/components)
g
@Ask Inkeep How to test my implementation with pytest
a
Thanks for tagging me @Graham. I'll look through relevant sources and get back to you shortly.
To test your FastAPI implementation with Permit.io using pytest, here's how to set it up: ​*Install Testing Dependencies*​ First, ensure you have the necessary testing packages (1) :
Copy code
fastapi 
uvicorn[standard]
pydantic
httpx
pytest
permit
​*Basic Test Setup*​ For testing FastAPI applications with Permit.io, you'll need to mock the Permit SDK calls. Here's a basic test structure based on the FastAPI authorization example :
Copy code
import pytest
from fastapi.testclient import TestClient
from unittest.mock import patch, AsyncMock

# Import your FastAPI app
from main import app

client = TestClient(app)

@pytest.fixture
def mock_permit() :
    with patch('main.permit') as mock:
        # Mock the check method to return True for authorized requests
        mock.check = AsyncMock(return_value=True)
        yield mock

def test_authorized_request(mock_permit) :
    # Test authorized access
    response = client.get("/tasks")
    assert response.status_code == 200
    
def test_create_task_authorized(mock_permit) :
    # Test creating a task with authorization
    headers = {"Authorization": "Bearer <mailto:test-user@example.com|test-user@example.com>"}
    task_data = {"title": "Test Task", "checked": False}
    
    response = <http://client.post|client.post>("/tasks", json=task_data, headers=headers)
    assert response.status_code == 200
​*Testing Permission Checks*​ To test different permission scenarios, you can configure the mock to return different values :
Copy code
@pytest.mark.asyncio
async def test_permission_denied() :
    with patch('main.permit.check', new_callable=AsyncMock) as mock_check:
        mock_check.return_value = False
        
        headers = {"Authorization": "Bearer <mailto:unauthorized-user@example.com|unauthorized-user@example.com>"}
        response = <http://client.post|client.post>("/tasks", json={"title": "Test"}, headers=headers)
        
        assert response.status_code == 403
        assert response.json() ["detail"] == "Not authorized"
​*E2E Testing Framework*​ For more comprehensive end-to-end testing, you can set up a framework that runs OPAL Server and Client in Docker (2) . The framework should: 1. Run OPAL Server and Client inside Docker 2. Test for health check responsivity 3. Check logs for errors and critical alerts 4. Verify client-server connection using the Statistics API ​*Testing Your Specific Implementation*​ For your FastAPI RBAC implementation with courses, you'd test the authorization flow (3) :
Copy code
@pytest.fixture
def mock_permit_with_roles() :
    with patch('utils.authorization.permit') as mock:
        # Mock user sync and role assignment
        mock.api.users.sync = AsyncMock()
        mock.api.users.assign_role = AsyncMock()
        mock.check = AsyncMock(return_value=True)
        yield mock

def test_user_registration_with_permit(mock_permit_with_roles) :
    # Test that new users are synced to Permit
    response = <http://client.post|client.post>("/auth/register", data={
        "email": "<mailto:test@example.com|test@example.com>",
        "password": "testpass",
        "name": "Test",
        "surname": "User"
    })
    
    # Verify user was synced to Permit
    mock_permit_with_roles.api.users.sync.assert_called_once()
    mock_permit_with_roles.api.users.assign_role.assert_called_once()
This testing approach allows you to verify your Permit.io integration without requiring actual API calls during tes
g
@Ask Inkeep What steps would you take when a new user does not verify their email?
a
Thanks for tagging me @Graham. I'll look through relevant sources and get back to you shortly.
For handling unverified email users in your FastAPI/Permit.io implementation, here's what I'd recommend: ​*1. Don't Sync to Permit Until Verified*​ Only sync users to Permit.io after they verify their email. This prevents unverified users from having any permissions in your system. ​*2. Use User Attributes for Verification Status*​ If you need to sync users before verification, you can use the
verified
attribute shown in the LangFlow integration example (1) :
Copy code
{
  "membership_tier": "Array",
  "region": "String",
  "verified": "Boolean"
}
​*3. Create Condition Sets That Require Verification*​ Set up ABAC rules that check the verified status :
Copy code
user.membership_tier includes resource.class AND user.verified == true
This ensures that even if an unverified user exists in Permit, they can't access resources until
verified == true
. ​*4. Handle Authorization Errors*​ If an unverified user tries to access resources, they'll likely encounter errors like "User not synced error" (2) or "No matching user sets found" (3) since they won't match your condition sets. ​*5. Update User After Verification*​ Once the user verifies their email, update their Permit profile to set
verified: true
and assign appropriate roles. This approach ensures unverified users have no access to your platform's resources while still all
To learn more, see the sources I considered: [[1] LangFlow Integration](https://docs.permit.io/ai-security/integrations/langflow) [[2] User not synced error](https://docs.permit.io/how-to/use-audit-logs/errors/user_not_synced) [[3] No matching user sets found for the given user and attributes](https://docs.permit.io/how-to/use-audit-logs/errors/no_matching_usersets)
g
@Ask Inkeep Pytest Mocks. Please provide more information about these
a
Thanks for tagging me @Graham. I'll look through relevant sources and get back to you shortly.
Looking at the Python SDK code, here's more detail about mocking Permit.io for pytest: ​*Understanding the Permit Client Structure*​ The Permit Python SDK uses aiohttp for HTTP requests (1) . The main client components you'll need to mock are:
Copy code
class SimpleHttpClient:
    """
    wraps aiohttp client to reduce boilerplace
    """

    def __init__(self, client_config: dict, base_url: str = "", timeout: Optional[int] = None) :
        self._client_config = client_config
        self._base_url = base_url
        if timeout is not None:
            self._client_config["timeout"] = ClientTimeout(total=timeout)
​*Key Methods to Mock*​ The SDK provides several async methods you'll need to mock :
Copy code
async def get(self, url, model: Type[TModel], **kwargs) -> TModel:
    url = f"{self._base_url}{url}"
    async with aiohttp.ClientSession(**self._client_config) as client:
        self._log_request(url, "GET")
        async with client.get(url, **kwargs) as response:
            await handle_api_error(response)
            self._log_response(url, "GET", response.status)
            data = await response.json()
            return parse_obj_as(model, data)

async def post(
    self,
    url,
    model: Type[TModel],
    json: Optional[Union[TData, dict, list]] = None,
    **kwargs,
) -> TModel:
    url = f"{self._base_url}{url}"
    async with aiohttp.ClientSession(**self._client_config) as client:
        self._log_request(url, "POST")
        async with <http://client.post|client.post>(url, json=self._prepare_json(json) , **kwargs) as response:
            await handle_api_error(response)
            self._log_response(url, "POST", response.status)
            data = await response.json()
            return parse_obj_as(model, data)
​*BasePermitApi Structure*​ The BasePermitApi class initializes HTTP clients :
Copy code
class BasePermitApi:
    """
    The base class for Permit APIs.
    """

    def __init__(self, config: PermitConfig) :
        """
        Initialize a BasePermitApi.

        Args:
            config: The Permit SDK configuration.
        """

        self.config = config
        self.__api_keys = self._build_http_client("/v2/api-key")
​*Mocking Strategy for Tests*​ When testing, you'll typically mock: 1. The
permit.check()
method for authorization checks 2. The
permit.api.users.sync()
method for user synchronization 3. The
permit.api.users.assign_role()
method for role assignments 4. The
permit.api.resource_instances.create()
method for resource instance creation Since these are async methods, use
AsyncMock
from
unittest.mock
to properly handle the async behavior. ​*Note on Type Checking*​ Be aware that the Permit library currently lacks type stubs, which may cause mypy warnings (2) :
Copy code
$ mypy .
mymodule.py:9: error: Skipping analyzing "permit": module is installed, but missing library stubs or py.typed marker  [import-untyped]
This won't affect your pytest mocks but may require suppressing type checking warnings for permit imports in your test files.
To learn more, see the sources I considered: [[1] https://github.com/permitio/permit-python/blob/main/permit](https://github.com/permitio/permit-python/blob/main/permit) [[2]
mypy
error: Skipping analyzing "permit": module is installed, but missing library stubs or py.typed marker [import-untyped]](https://github.com/permitio/permit-python/issues/116)
o
@Graham let me know if you need more help then the AI is providing. it’s a pretty big thread so if you do need further help I’d appreciate if you can focus me and summarize on what you need
g
@Omer Zuarets Thank you for reaching out. Yes it is quite a bit thread but the AI has been very useful. I am currently focusing on the authentication/authorisation flow for my FASTApi application. I now want to build a robust test framework. Lastly I am exploring the permission policies. There a still some things that I am unclear on.
o
About your latest question regarding mocking, I guess the permit client is granted via fastapi dependency, I would use fastapi dependency overrides to return a mock client that returns a mock result
Wdym by
Lastly I am exploring the permission policies. There a still some things that I am unclear on.
g
@Omer Zuarets Dependency overrides seem to be the way to go. Great recommendation. Thank you.
🤙 1
🥂 1
@Omer Zuarets I have watched various videos about the permit permission UI. I see things like an Instance tab alongside the user tab. I have not seen the instance tab used. I currently have two requirements. Management documentation and Client business training platform There will only be 3-5 users for the management side and less than 100 for the business training platform. The business training will be video and textual content split into saleable on off products and memberships.
@Ask Inkeep Is permission as code something that I can use?
a
Thanks for tagging me @Graham. I'll look through relevant sources and get back to you shortly.
Yes, Policy as Code is definitely something you can use with Permit.io! It's actually one of the recommended best practices for managing authorization in your application. Policy as Code is the practice of defining, managing, and enforcing policies using code rather than relying on static configurations or manual enforcement (1) . Here's how it applies to your use case: ​*What Policy as Code Means for Your Platform*​ With Permit.io, you can express your authorization rules as code using policy languages like Rego (with OPA) or Cedar . For example, a simple access control policy in Rego looks like this:
Copy code
package example
import input
default allow = false
allow {
  input.user.role == "admin"
  input.resource.category == "sensitive"
}
​*Benefits for Your Training Platform*​ Policy as Code offers several advantages for your management documentation and training platform : 1. ​*Version Control*​ - Store policies in Git repositories for full traceability 2. ​*Automation*​ - Automatically test and deploy policy changes through CI/CD 3. ​*Consistency*​ - Ensure uniform policy enforcement across all environments 4. ​*Collaboration*​ - Teams can review and contribute to policy changes ​*How Permit.io Simplifies Policy as Code*​ Permit.io provides a unique approach - you can use their ​*low-code/no-code interface*​ to create policies, which then generates policy code that goes right into your Git repository . This means you get the benefits of Policy as Code without needing to write complex policy languages directly. ​*Practical Implementation for Your Use Case*​ For your training platform with courses and memberships, Policy as Code enables you to (2) : • Define policies for course access based on purchase type • Manage subscription-based permissions • Control access to management documentation • Update permissions without changing application code The best part is that Permit.io supports multiple policy engines (OPA, Cedar, OpenFGA) , giving you flexibility to choose the right approach for your needs (1) . Since you're already using FastAPI with Permit.io, you're well-positioned to leverage Policy as Code for managing your complex permission requirements while keeping your application code clean and focused on business logic.
To learn more, see the sources I considered: [[1] What is Policy as Code?](https://www.permit.io/blog/what-is-policy-as-code) [[2] Best Practices for Microservice Authorization](https://www.permit.io/blog/best-practices-for-authorization-in-microservices)
o
Instances are used to declare a more fine grained access, e.g if you want to give a user permissions to a specific video. Not sure I understood your policy is it based on roles or attributes + conditions ?
g
@Omer Zuarets I can see a product [defines a series of pages/videos] requiring permission. [roles, attributes + conditions]. I am not sure about that yet. I have only been conscious of the concepts for 5 days.
o
Not sure I completely understood your last message here, can you clarify exactly what you meant here?
g
@Ask Inkeep I am getting confused with setting up a fastapi application with Auth0 to provide the token for authorization by permit. For something that is supposed to save hours of development time and be less risky, it is frustrating. Can you help?
a
Thanks for tagging me @Graham. I'll look through relevant sources and get back to you shortly.
I understand the frustration! Let me break down the Auth0 + Permit.io integration for FastAPI into clear steps: The Flow Overview Auth0 handles ​*authentication*​ (who the user is) while Permit.io handles ​*authorization*​ (what they can do) (1) . The JWT from Auth0 contains the user identity that you'll use with Permit.io. Step 1: Extract User from Auth0 Token After Auth0 authentication, decode the JWT to get the user information (2) :
Copy code
def authenticate(request: Request, token: str = Depends(token_auth_scheme) ) :
    return verifyToken(token)
Step 2: Initialize Permit.io Set up your Permit client (3) :
Copy code
from permit import Permit
from constants import PERMIT_API_KEY, PERMIT_PDP_URL

permit = Permit(
   pdp=PERMIT_PDP_URL,
   token=PERMIT_API_KEY,
)
Step 3: Sync Auth0 User to Permit.io When a user logs in via Auth0, sync them to Permit :
Copy code
async def create_role(user) :
    try:
        await permit.api.users.sync(
            {
                "key": user["id"],
                "email": user["email"],
                "first_name": user["surname"],
                "last_name": user["surname"],
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Authorization error: {str(e) }")
Step 4: Assign Initial Role Give the user a default role :
Copy code
async def assign_role(user_id: str, role: str) :
    try:
        await permit.api.users.assign_role(
            {
                # the user key
                "user": user_id,
                # the role key
                "role": role,
                # the tenant key
                "tenant": "default",
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Authorization error: {str(e) }")
Step 5: Create Authorization Middleware Create a dependency that checks permissions (2) :
Copy code
async def authorize(request: Request, token: str = Depends(token_auth_scheme) , body={}) :
    resource_name = request.url.path.strip('/') .split('/') [0]
    method = request.method.lower()
    resource = await request.json() if method in ["post", "put"] else body
    user = token.credentials
    allowed = await permit.check(user, method, {
        "type": resource_name,
        "attributes": resource
    })
    if not allowed:
        raise HTTPException(status_code=403, detail="Not authorized")
Step 6: Protect Your Routes Apply the authorization to your endpoints :
Copy code
@app.post("/tasks", dependencies=[Depends(authenticate) ])
async def create_task(task: Task) :
    tasks.append(task)
    return task
Key Points to Remember: 1. Auth0 JWT provides the user identity (user ID or email) (4) 2. Use that identity as the "key" when syncing to Permit.io (3) 3. Permit.io needs to know about users before it can authorize them (5) 4. The PDP (Policy Decision Point) makes the actual authorization decisions The confusion often comes from mixing authentication and authorization concepts. Auth0 gives you the "who", Permit.io determines the "what they can do" (1) .
To learn more, see the sources I considered: [[1] FAQ | Permit.io Documentation](https://docs.permit.io/faq) [[2] How to Add RBAC into a FastAPI Application](https://www.permit.io/blog/implement-authorization-in-fastapi) [[3] FastAPI RBAC - Full Implementation Tutorial](https://www.permit.io/blog/fastapi-rbac-full-implementation-tutorial) [[4] What is Token-Based Authentication?](https://www.permit.io/blog/what-is-token-based-authentication) [[5] Concepts / Glossary](https://docs.permit.io/overview/glossary)