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

revert: add check for current team in personal api key (#26390) #26438

Merged
merged 1 commit into from
Nov 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
40 changes: 0 additions & 40 deletions ee/api/test/test_feature_flag.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,6 @@
from ee.models.rbac.role import Role, RoleMembership
from posthog.models.feature_flag import FeatureFlag
from posthog.models.organization import OrganizationMembership
from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
from posthog.models import User
from rest_framework import status
from posthog.models.utils import generate_random_token_personal


class TestFeatureFlagEnterpriseAPI(APILicensedTest):
Expand All @@ -27,39 +23,3 @@ def test_adding_role_edit_access_is_not_restrictive(self):
flag_res = self.client.get(f"/api/projects/{self.team.id}/feature_flags/")
self.assertEqual(flag_res.json()["count"], 1)
self.assertEqual(flag_res.json()["results"][0]["can_edit"], True)


class TestFeatureFlagLocalEvaluation(APILicensedTest):
def test_local_evaluation_with_valid_personal_api_key(self):
user = User.objects.create_user(email="[email protected]", first_name="Test", password="password")

OrganizationMembership.objects.create(user=user, organization=self.organization)

user.current_team_id = self.team.id
user.save()

personal_api_key = generate_random_token_personal()
PersonalAPIKey.objects.create(
label="X",
user=user,
last_used_at="2021-08-25T21:09:14",
secure_value=hash_key_value(personal_api_key),
)
FeatureFlag.objects.create(
team=self.team,
name="Beta feature",
key="beta-feature",
created_by=self.user,
filters={"groups": [{"properties": [], "rollout_percentage": 50}]},
)

response = self.client.get(
f"/api/projects/{self.team.id}/feature_flags/local_evaluation",
HTTP_AUTHORIZATION=f"Bearer {personal_api_key}",
)

self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.json()["flags"]), 1)
self.assertEqual(response.json()["flags"][0]["key"], "beta-feature")
self.assertEqual(response.json()["group_type_mapping"], {})
self.assertEqual(response.json()["cohorts"], {})
30 changes: 0 additions & 30 deletions posthog/api/test/test_authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -832,36 +832,6 @@ def test_personal_api_key_does_not_update_last_used_at_when_in_the_past(self):
model_key = PersonalAPIKey.objects.get(secure_value=hash_key_value(personal_api_key))
self.assertEqual(str(model_key.last_used_at), "2021-08-25 21:09:14+00:00")

def test_personal_api_key_not_associated_with_project_or_organization(self):
self.client.logout()

user = User.objects.create_user(email="[email protected]", first_name="Test", password="password")

personal_api_key = generate_random_token_personal()
PersonalAPIKey.objects.create(
label="X",
user=user,
last_used_at="2021-08-25T21:09:14",
secure_value=hash_key_value(personal_api_key),
)

with freeze_time("2021-08-24T21:14:14.252"):
response = self.client.get(
f"/api/projects/{self.team.pk}/feature_flags/",
HTTP_AUTHORIZATION=f"Bearer {personal_api_key}",
)

self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.json(),
{
"type": "authentication_error",
"code": "authentication_failed",
"detail": "Personal API key is not associated with a project or organization.",
"attr": None,
},
)


class TestTimeSensitivePermissions(APIBaseTest):
def test_after_timeout_modifications_require_reauthentication(self):
Expand Down
1 change: 0 additions & 1 deletion posthog/api/test/test_decide.py
Original file line number Diff line number Diff line change
Expand Up @@ -3784,7 +3784,6 @@ def setup_user_and_team_in_db(self, dbname: str = "default"):
email=f"test-{random.randint(1, 100000)}@posthog.com",
password="password",
first_name="first_name",
current_team_id=team.id,
)
OrganizationMembership.objects.db_manager(dbname).create(
user=user,
Expand Down
5 changes: 1 addition & 4 deletions posthog/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,15 +153,12 @@ def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[A
now = timezone.now()
key_last_used_at = personal_api_key_object.last_used_at
# Only updating last_used_at if the hour's changed
# This is to avoid excessive UPDATE queries, while still presenting accurate (down to the hour) info in the UI
# This is to avooid excessive UPDATE queries, while still presenting accurate (down to the hour) info in the UI
if key_last_used_at is None or (now - key_last_used_at > timedelta(hours=1)):
personal_api_key_object.last_used_at = now
personal_api_key_object.save(update_fields=["last_used_at"])
assert personal_api_key_object.user is not None

if not personal_api_key_object.user.current_team_id:
raise AuthenticationFailed(detail="Personal API key is not associated with a project or organization.")

# :KLUDGE: CHMiddleware does not receive the correct user when authenticating by api key.
tag_queries(
user_id=personal_api_key_object.user.pk,
Expand Down
Loading