Skip to content

Commit

Permalink
Merge pull request #106 from permitio/omer/per-8404-optimize-getusert…
Browse files Browse the repository at this point in the history
…enants

optimize /user-tenants route
  • Loading branch information
omer9564 authored Nov 16, 2023
2 parents e622e22 + 23a307c commit 6be5c9f
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 21 deletions.
22 changes: 12 additions & 10 deletions horizon/enforcer/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
from opal_client.config import opal_client_config
from opal_client.logger import logger
from opal_client.policy_store.base_policy_store_client import BasePolicyStoreClient
from opal_client.policy_store.opa_client import fail_silently
from opal_client.policy_store.policy_store_client_factory import (
DEFAULT_POLICY_STORE_GETTER,
)
Expand Down Expand Up @@ -49,6 +48,7 @@
BULK_POLICY_PACKAGE = "permit.bulk"
ALL_TENANTS_POLICY_PACKAGE = "permit.any_tenant"
USER_PERMISSIONS_POLICY_PACKAGE = "permit.user_permissions"
USER_TENANTS_POLICY_PACKAGE = USER_PERMISSIONS_POLICY_PACKAGE + ".tenants"
KONG_ROUTES_TABLE_FILE = "/config/kong_routes.json"


Expand Down Expand Up @@ -363,19 +363,21 @@ async def user_tenants(
query: UserTenantsQuery,
x_permit_sdk_language: Optional[str] = Depends(notify_seen_sdk),
):
response = await _is_allowed(query, request, USER_PERMISSIONS_POLICY_PACKAGE)
response = await _is_allowed(query, request, USER_TENANTS_POLICY_PACKAGE)
log_query_result(query, response)
try:
raw_result = json.loads(response.body).get("result", {})
processed_query = (
get_v1_processed_query(raw_result)
or get_v2_processed_query(raw_result)
or {}
)

result = parse_obj_as(UserTenantsResult, raw_result.get("tenants", {}))
if isinstance(raw_result, dict):
tenants = raw_result.get("tenants", {})
elif isinstance(raw_result, list):
tenants = raw_result
else:
raise TypeError(
f"Expected raw result to be dict or list, got {type(raw_result)}"
)
result = parse_obj_as(UserTenantsResult, tenants)
except:
result = parse_obj_as(UserTenantsResult, {})
result = parse_obj_as(UserTenantsResult, [])
logger.warning(
"get user tenants (fallback response)",
reason="cannot decode opa response",
Expand Down
38 changes: 27 additions & 11 deletions horizon/tests/test_enforcer_api.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import pytest
import random
import time
import asyncio
import random

import aiohttp
import pytest
from aioresponses import aioresponses
from fastapi import FastAPI
from fastapi.testclient import TestClient
from aioresponses import aioresponses, CallbackResult
import aiohttp
from opal_client.client import OpalClient
from opal_client.config import opal_client_config

from horizon.pdp import PermitPDP
from horizon.enforcer.schemas import *
from horizon.config import sidecar_config
from opal_client.config import opal_client_config
from opal_client.client import OpalClient
from horizon.enforcer.schemas import *
from horizon.pdp import PermitPDP


class MockPermitPDP(PermitPDP):
Expand Down Expand Up @@ -141,6 +141,15 @@ def __init__(self):
{"result": {"allow": [{"allow": True, "result": True}]}},
{"allow": [{"allow": True, "result": True}]},
),
(
"/user-tenants",
"permit/user_permissions/tenants",
UserTenantsQuery(
user=User(key="user1"),
),
{"result": [{"attributes": {}, "key": "tenant-1"}]},
[{"attributes": {}, "key": "tenant-1"}],
)
# TODO: Add Kong
]

Expand Down Expand Up @@ -182,8 +191,15 @@ def post_endpoint():
response = post_endpoint()
assert response.status_code == 200
print(response.json())
for k, v in expected_response.items():
assert response.json()[k] == v
if isinstance(expected_response, list):
assert response.json() == expected_response
elif isinstance(expected_response, dict):
for k, v in expected_response.items():
assert response.json()[k] == v
else:
raise TypeError(
f"Unexpected expected response type, expected one of list, dict and got {type(expected_response)}"
)

# Test bad status from OPA
bad_status = random.choice([401, 404, 400, 500, 503])
Expand Down
3 changes: 3 additions & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pytest
aioresponses
httpx

0 comments on commit 6be5c9f

Please sign in to comment.