Skip to content
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

Cache public tenant #1368

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add method to retrieve the public tenant
This adds a method on the `Tenant` model manager, `get_public_tenant()` which can
be called with `Tenant.objects.get_public_tenant()`.

The public tenant record will be added to/retrieved from the cache. A new cache
inheriting from `TenantCache` was added to allow for a custom TTL and key to be
used for the public tenant (open to feedback here, I just didn't want to refactor
too much initially).
  • Loading branch information
coderbydesign committed Dec 4, 2024
commit 051edc9285703fb452fed07c262b1054abede88e
12 changes: 12 additions & 0 deletions rbac/api/models.py
Original file line number Diff line number Diff line change
@@ -22,6 +22,7 @@

from api.cross_access.model import CrossAccountRequest # noqa: F401
from api.status.model import Status # noqa: F401
from management.cache import PublicTenantCache


class TenantModifiedQuerySet(models.QuerySet):
@@ -35,6 +36,15 @@ def modified_only(self):
.distinct()
)

def get_public_tenant(self):
"""Return the public tenant."""
cache = PublicTenantCache()
tenant = cache.get_tenant(Tenant.PUBLIC_TENANT_NAME)
if tenant is None:
tenant = self.get(tenant_name=Tenant.PUBLIC_TENANT_NAME)
cache.save_tenant(tenant)
return tenant


class Tenant(models.Model):
"""The model used to create a tenant schema."""
@@ -45,6 +55,8 @@ class Tenant(models.Model):
org_id = models.CharField(max_length=36, unique=True, default=None, db_index=True, null=True)
objects = TenantModifiedQuerySet.as_manager()

PUBLIC_TENANT_NAME = "public"

def __str__(self):
"""Get string representation of Tenant."""
return f"Tenant ({self.org_id})"
40 changes: 40 additions & 0 deletions tests/api/test_models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#
# Copyright 2024 Red Hat, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""Test cases for api models."""

from django.test import TestCase

from api.models import Tenant


class TenantModelTests(TestCase):
"""Test the Tenant model."""

def setUp(self):
"""Set up the tenant model tests."""
super().setUp()
self.tenant = Tenant.objects.create(tenant_name="acct1234", org_id="1234")
self.public_tenant = Tenant.objects.get(tenant_name="public")

def tearDown(self):
"""Tear down tenant model tests."""
Tenant.objects.all().delete()

def test_get_public_tenant(self):
"""Test the tenant model manager method to get the public tenant."""
self.assertCountEqual(Tenant.objects.all(), [self.public_tenant, self.tenant])
self.assertEqual(Tenant.objects.get_public_tenant(), self.public_tenant)
56 changes: 55 additions & 1 deletion tests/rbac/test_cache.py
Original file line number Diff line number Diff line change
@@ -21,7 +21,7 @@

from django.conf import settings
from django.test import TestCase
from management.cache import TenantCache
from management.cache import TenantCache, PublicTenantCache
from management.models import Access, Group, Permission, Policy, Principal, ResourceDefinition, Role

from api.models import Tenant
@@ -302,3 +302,57 @@ def test_tenant_cache_functions_failure(self, redis_health_check, redis_connecti
tenant = tenant_cache.get_tenant(tenant_org_id)
redis_health_check.assert_called_once()
self.assertNotEqual(tenant, self.tenant)


class PublicTenantCacheTest(TestCase):
@classmethod
def setUpClass(self):
"""Set up the tenant."""
super().setUpClass()
self.tenant = Tenant.objects.create(tenant_name="public")
self.tenant_name = self.tenant.tenant_name
self.key = f"rbac::tenant::tenant={self.tenant_name}"

@classmethod
def tearDownClass(self):
self.tenant.delete()
super().tearDownClass()

@patch("management.cache.PublicTenantCache.connection")
@patch("management.cache.BasicCache.redis_health_check")
def test_public_tenant_cache_functions_success(self, redis_health_check, redis_connection):
dump_content = pickle.dumps(self.tenant)

# Save tenant to cache
cache = PublicTenantCache()
cache.save_tenant(self.tenant)
self.assertTrue(call().__enter__().set(self.key, dump_content) in redis_connection.pipeline.mock_calls)

redis_connection.get.return_value = dump_content
redis_health_check.return_value = True
# Get tenant from cache
tenant = cache.get_tenant(self.tenant_name)
redis_health_check.assert_called_once()
redis_connection.get.assert_called_once_with(self.key)
self.assertEqual(tenant, self.tenant)

# Delete tenant from cache
cache.delete_tenant(self.tenant_name)
redis_connection.delete.assert_called_once_with(self.key)

@patch("management.cache.PublicTenantCache.connection")
@patch("management.cache.BasicCache.redis_health_check")
def test_public_tenant_cache_functions_failure(self, redis_health_check, redis_connection):
dump_content = pickle.dumps(self.tenant)

# Save tenant to cache
cache = PublicTenantCache()
cache.save_tenant(self.tenant)
self.assertTrue(call().__enter__().set(self.key, dump_content) in redis_connection.pipeline.mock_calls)

redis_connection.get.return_value = dump_content
redis_health_check.return_value = False
# Get tenant from cache (should fail because redis_health_check failed)
tenant = cache.get_tenant(self.tenant_name)
redis_health_check.assert_called_once()
self.assertNotEqual(tenant, self.tenant)