Graham
08/05/2025, 5:46 AMAsk Inkeep
08/05/2025, 5:46 AMAsk Inkeep
08/05/2025, 5:46 AM.env file (1) :
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 :
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 :
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 :
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) }")
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 :
@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) :
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.Ask Inkeep
08/05/2025, 5:46 AMGraham
08/05/2025, 5:56 AMOr Weis
08/05/2025, 5:56 AMAsk Inkeep
08/05/2025, 5:56 AMAsk Inkeep
08/05/2025, 5:56 AMawait permit.api.roleAssignments.assign({
role: "Marketer",
tenant: "default",
resource_instance: `Dashboard:${dashboard.id}`,
user: "auth0|elon",
}) ;
*Java example:*
RoleAssignmentRead ra = permit.api.users.assignRole("<mailto:elon@tesla.com|elon@tesla.com>", "admin", "tesla") ;
(3)
*.NET example:*
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" byAsk Inkeep
08/05/2025, 5:57 AMGraham
08/05/2025, 5:59 AMAsk Inkeep
08/05/2025, 5:59 AMAsk Inkeep
08/05/2025, 5:59 AMasync 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 :
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.Ask Inkeep
08/05/2025, 5:59 AMGraham
08/05/2025, 6:43 AMAsk Inkeep
08/05/2025, 6:43 AMAsk Inkeep
08/05/2025, 6:43 AMcreate_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)
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)
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.Ask Inkeep
08/05/2025, 6:43 AMGraham
08/05/2025, 6:47 AMAsk Inkeep
08/05/2025, 6:48 AMAsk Inkeep
08/05/2025, 6:48 AMcreate_role function (which should be called sync_user) creates or updates a user in Permit.io's system (1) :
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 :
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 :
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.Ask Inkeep
08/05/2025, 6:48 AMGraham
08/05/2025, 6:51 AMAsk Inkeep
08/05/2025, 6:51 AMAsk Inkeep
08/05/2025, 6:51 AMAsk Inkeep
08/05/2025, 6:51 AMGraham
08/05/2025, 6:59 AMAsk Inkeep
08/05/2025, 6:59 AMAsk Inkeep
08/05/2025, 7:00 AMawait permit.api.resource_instances.create({
key: "react",
resource: "repository",
tenant: "default",
attributes: {
private: "false",
owner: "Company C",
},
}) ;
*Ruby example:*
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:*
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 .Ask Inkeep
08/05/2025, 7:00 AMGraham
08/05/2025, 7:01 AMAsk Inkeep
08/05/2025, 7:01 AMAsk Inkeep
08/05/2025, 7:01 AMconst resourceInstance = await permit.api.resourceInstances.create({
resource: "Transaction",
key: transaction.id,
tenant,
attributes: {
...transaction,
},
}) ;
*Resource Instance with Specific Attributes*
For a repository resource (2) :
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 :
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) :
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 :
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) .Ask Inkeep
08/05/2025, 7:01 AMGraham
08/05/2025, 7:02 AMAsk Inkeep
08/05/2025, 7:02 AMAsk Inkeep
08/05/2025, 7:03 AMawait 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:
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) :
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.Ask Inkeep
08/05/2025, 7:03 AMGraham
08/05/2025, 7:06 AMAsk Inkeep
08/05/2025, 7:06 AMAsk Inkeep
08/05/2025, 7:06 AMresource "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) :
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 :
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 :
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 :
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.Ask Inkeep
08/05/2025, 7:06 AMGraham
08/05/2025, 8:30 AMAsk Inkeep
08/05/2025, 8:30 AMAsk Inkeep
08/05/2025, 8:30 AMfastapi
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 :
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 :
@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) :
@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 tesAsk Inkeep
08/05/2025, 8:31 AMGraham
08/05/2025, 8:47 AMAsk Inkeep
08/05/2025, 8:47 AMAsk Inkeep
08/05/2025, 8:48 AMverified attribute shown in the LangFlow integration example (1) :
{
"membership_tier": "Array",
"region": "String",
"verified": "Boolean"
}
*3. Create Condition Sets That Require Verification*
Set up ABAC rules that check the verified status :
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 allAsk Inkeep
08/05/2025, 8:48 AMGraham
08/05/2025, 3:23 PMAsk Inkeep
08/05/2025, 3:23 PMAsk Inkeep
08/05/2025, 3:23 PMclass 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 :
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 :
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) :
$ 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.Ask Inkeep
08/05/2025, 3:23 PMmypy 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)Omer Zuarets
08/05/2025, 3:29 PMGraham
08/05/2025, 3:46 PMOmer Zuarets
08/05/2025, 3:50 PMOmer Zuarets
08/05/2025, 3:51 PMLastly I am exploring the permission policies. There a still some things that I am unclear on.
Graham
08/05/2025, 3:57 PMGraham
08/05/2025, 4:10 PMGraham
08/05/2025, 4:25 PMAsk Inkeep
08/05/2025, 4:25 PMAsk Inkeep
08/05/2025, 4:25 PMpackage 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.Ask Inkeep
08/05/2025, 4:25 PMOmer Zuarets
08/05/2025, 4:27 PMGraham
08/05/2025, 4:31 PMOmer Zuarets
08/06/2025, 12:58 PMGraham
08/08/2025, 3:30 PMAsk Inkeep
08/08/2025, 3:30 PMAsk Inkeep
08/08/2025, 3:30 PMdef authenticate(request: Request, token: str = Depends(token_auth_scheme) ) :
return verifyToken(token)
Step 2: Initialize Permit.io
Set up your Permit client (3) :
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 :
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 :
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) :
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 :
@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) .Ask Inkeep
08/08/2025, 3:30 PM