-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
add initial data filtering support to python sdk #101
Open
asafc
wants to merge
1
commit into
main
Choose a base branch
from
asaf/cto-314-data-filtering-poc
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,6 +5,7 @@ | |
import aiohttp | ||
from aiohttp import ClientTimeout | ||
from loguru import logger | ||
from permit_datafilter.boolean_expression.schemas import ResidualPolicyResponse | ||
from pydantic import parse_obj_as | ||
|
||
from ..config import PermitConfig | ||
|
@@ -397,6 +398,143 @@ async def check( | |
Read more about setting up the PDP at https://docs.permit.io/sdk/python/quickstart-python/#2-setup-your-pdp-policy-decision-point-container" | ||
) | ||
|
||
async def filter_resources( | ||
self, | ||
user: User, | ||
action: Action, | ||
resource_type: str, | ||
context: Context = {}, | ||
) -> ResidualPolicyResponse: | ||
""" | ||
Returns a filter that can be applied to the user database that filters all the resources a user can access given a user, action and resource type. | ||
|
||
The filter is a residual policy compiled from OPA Rego AST and transformed to be expressed as a boolean expression | ||
(combination of logical and comparison operators, where the operands can be variable references or literal values). | ||
|
||
An example for a residual policy: | ||
{ | ||
"type": "conditional", | ||
"condition": { | ||
"expression": { | ||
"operator": "eq", | ||
"operands": [ | ||
{ | ||
"variable": "input.resource.tenant" | ||
}, | ||
{ | ||
"value": "082f6978-6424-4e05-a706-1ab6f26c3768" | ||
} | ||
] | ||
} | ||
} | ||
} | ||
|
||
The user can then map this residual policy into an SQL expression using various plugins. | ||
|
||
Args: | ||
user: The user object representing the user. | ||
action: The action to be performed on the resource. | ||
resource_type: The resource type. | ||
context: The context object representing the context in which the action is performed. Defaults to None. | ||
|
||
Returns: | ||
ResidualPolicyResponse: a residual policy that can be transformed into an SQL expression. | ||
|
||
Raises: | ||
PermitConnectionError: If an error occurs while sending the authorization request to the PDP. | ||
|
||
Examples: | ||
|
||
from sqlalchemy.orm import declarative_base, relationship | ||
|
||
from permit import Permit | ||
from permit_datafilter.plugins.sqlalchemy import QueryBuilder | ||
|
||
# assuming we have the following SQL tables: | ||
Base = declarative_base() | ||
|
||
class Tenant(Base): | ||
__tablename__ = "tenant" | ||
|
||
id = Column(String, primary_key=True) | ||
key = Column(String(255)) | ||
|
||
class Task(Base): | ||
__tablename__ = "task" | ||
|
||
id = Column(String, primary_key=True) | ||
created_at = Column(DateTime, default=datetime.utcnow()) | ||
updated_at = Column(DateTime) | ||
description = Column(String(255)) | ||
tenant_id = Column(String, ForeignKey("tenant.id")) | ||
tenant = relationship("Tenant", backref="tasks") | ||
|
||
# this is how we can filter all the task records in the database | ||
# that are readable by the user according to the authz policy | ||
# (i.e: that user have the `task:read` permission on them) | ||
permit = Permit(...) | ||
authz_filter = await permit.filter_resources("[email protected]", "read", "task") | ||
query = ( | ||
QueryBuilder() | ||
.select(Task) | ||
.filter_by(authz_filter) | ||
.map_references({ | ||
# if mapping a reference to a field on a related table | ||
"input.resource.tenant": Tenant.key, | ||
}) | ||
# you must specify how to perform a join against that table | ||
.join(Tenant, Task.tenant_id == Tenant.id) | ||
.build() | ||
) | ||
""" | ||
normalized_user: UserInput = ( | ||
UserInput(key=user) if isinstance(user, str) else UserInput(**user) | ||
) | ||
normalized_resource: ResourceInput = self._normalize_resource( | ||
self._resource_from_string(resource_type) | ||
) | ||
query_context = self._context_store.get_derived_context(context) | ||
input = dict( | ||
user=normalized_user.dict(exclude_unset=True), | ||
action=action, | ||
resource=normalized_resource.dict(exclude_unset=True), | ||
context=query_context, | ||
) | ||
async with aiohttp.ClientSession( | ||
headers=self._headers, **self._timeout_config | ||
) as session: | ||
api_url = f"{self._base_url}/filter_resources" | ||
try: | ||
async with session.post( | ||
api_url, | ||
data=json.dumps(input), | ||
) as response: | ||
if response.status != 200: | ||
raise PermitConnectionError( | ||
f"Permit SDK got unexpected status code: {response.status}, please check your Permit SDK class init and PDP container are configured correctly. \n\ | ||
Read more about setting up the PDP at https://docs.permit.io/sdk/python/quickstart-python/#2-setup-your-pdp-policy-decision-point-container" | ||
) | ||
|
||
response_data: dict = await response.json() | ||
logger.debug( | ||
f"permit.filter_resources() response:\ninput: {pformat(input, indent=2)}\nresponse status: {response.status}\nresponse data: {pformat(response_data, indent=2)}" | ||
) | ||
return ResidualPolicyResponse(**response_data) | ||
except aiohttp.ClientError as err: | ||
logger.error( | ||
"error in permit.filter_resources({}, {}, {}):\n{}".format( | ||
normalized_user, | ||
action, | ||
self._resource_repr(normalized_resource), | ||
err, | ||
) | ||
) | ||
raise PermitConnectionError( | ||
f"Permit SDK got error: {err}, \n \ | ||
and cannot connect to the PDP container, please check your configuration and make sure it's running at {self._base_url} and accepting requests. \n \ | ||
Read more about setting up the PDP at https://docs.permit.io/sdk/python/quickstart-python/#2-setup-your-pdp-policy-decision-point-container" | ||
) | ||
|
||
def _normalize_resource(self, resource: ResourceInput) -> ResourceInput: | ||
normalized_resource: ResourceInput = resource.copy() | ||
if normalized_resource.context is None: | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,6 +3,7 @@ | |
from typing import Generator, Optional | ||
|
||
from loguru import logger | ||
from permit_datafilter.boolean_expression.schemas import ResidualPolicyResponse | ||
from pydantic import NonNegativeFloat | ||
from typing_extensions import Self | ||
|
||
|
@@ -224,3 +225,96 @@ async def check( | |
await permit.check(user, 'close', {'type': 'issue', 'tenant': 't1'}) | ||
""" | ||
return await self._enforcer.check(user, action, resource, context) | ||
|
||
async def filter_resources( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same here |
||
self, | ||
user: User, | ||
action: Action, | ||
resource_type: str, | ||
context: Context = {}, | ||
) -> ResidualPolicyResponse: | ||
""" | ||
Returns a filter that can be applied to the user database that filters all the resources a user can access given a user, action and resource type. | ||
|
||
The filter is a residual policy compiled from OPA Rego AST and transformed to be expressed as a boolean expression | ||
(combination of logical and comparison operators, where the operands can be variable references or literal values). | ||
|
||
An example for a residual policy: | ||
{ | ||
"type": "conditional", | ||
"condition": { | ||
"expression": { | ||
"operator": "eq", | ||
"operands": [ | ||
{ | ||
"variable": "input.resource.tenant" | ||
}, | ||
{ | ||
"value": "082f6978-6424-4e05-a706-1ab6f26c3768" | ||
} | ||
] | ||
} | ||
} | ||
} | ||
|
||
The user can then map this residual policy into an SQL expression using various plugins. | ||
|
||
Args: | ||
user: The user object representing the user. | ||
action: The action to be performed on the resource. | ||
resource_type: The resource type. | ||
context: The context object representing the context in which the action is performed. Defaults to None. | ||
|
||
Returns: | ||
ResidualPolicyResponse: a residual policy that can be transformed into an SQL expression. | ||
|
||
Raises: | ||
PermitConnectionError: If an error occurs while sending the authorization request to the PDP. | ||
|
||
Examples: | ||
|
||
from sqlalchemy.orm import declarative_base, relationship | ||
|
||
from permit import Permit | ||
from permit_datafilter.plugins.sqlalchemy import QueryBuilder | ||
|
||
# assuming we have the following SQL tables: | ||
Base = declarative_base() | ||
|
||
class Tenant(Base): | ||
__tablename__ = "tenant" | ||
|
||
id = Column(String, primary_key=True) | ||
key = Column(String(255)) | ||
|
||
class Task(Base): | ||
__tablename__ = "task" | ||
|
||
id = Column(String, primary_key=True) | ||
created_at = Column(DateTime, default=datetime.utcnow()) | ||
updated_at = Column(DateTime) | ||
description = Column(String(255)) | ||
tenant_id = Column(String, ForeignKey("tenant.id")) | ||
tenant = relationship("Tenant", backref="tasks") | ||
|
||
# this is how we can filter all the task records in the database | ||
# that are readable by the user according to the authz policy | ||
# (i.e: that user have the `task:read` permission on them) | ||
permit = Permit(...) | ||
authz_filter = await permit.filter_resources("[email protected]", "read", "task") | ||
query = ( | ||
QueryBuilder() | ||
.select(Task) | ||
.filter_by(authz_filter) | ||
.map_references({ | ||
# if mapping a reference to a field on a related table | ||
"input.resource.tenant": Tenant.key, | ||
}) | ||
# you must specify how to perform a join against that table | ||
.join(Tenant, Task.tenant_id == Tenant.id) | ||
.build() | ||
) | ||
""" | ||
return await self._enforcer.filter_resources( | ||
user, action, resource_type, context | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,3 +3,4 @@ httpx>=0.24.1,<1 | |
loguru>=0.7.0,<1 | ||
pydantic[email]>=1.10.7 | ||
typing-extensions>=4.5.0,<5 | ||
permit-datafilter>=0.0.3,<1 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This should be optional dependency |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -18,7 +18,7 @@ def get_readme() -> str: | |
|
||
setup( | ||
name="permit", | ||
version="2.6.0", | ||
version="2.7.0", | ||
packages=find_packages(), | ||
author="Asaf Cohen", | ||
author_email="[email protected]", | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This should be in a separate file and should only be imported if the relevant optional dependency was chosen, otherwise you will force installing irrelevant packages