Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
remote_billing: Implement session expiry mechanism.
Mateusz Mandera7fad8f1f54be
diff --git a/corporate/lib/remote_billing_util.py b/corporate/lib/remote_billing_util.pyindex 38054e18cbb..bd4d44e8543 100644--- a/corporate/lib/remote_billing_util.py+++ b/corporate/lib/remote_billing_util.py@@ -2,13 +2,20 @@ import loggingfrom typing import Optional, TypedDict, Union, castfrom django.http import HttpRequest+from django.utils.timezone import now as timezone_nowfrom django.utils.translation import gettext as _from zerver.lib.exceptions import JsonableError+from zerver.lib.timestamp import datetime_to_timestampfrom zilencer.models import RemoteRealm, RemoteZulipServerbilling_logger = logging.getLogger("corporate.stripe")+# The sessions are relatively short-lived, so that we can avoid issues+# with users who have their privileges revoked on the remote server+# maintaining access to the billing page for too long.+REMOTE_BILLING_SESSION_VALIDITY_SECONDS = 2 * 60 * 60+class RemoteBillingUserDict(TypedDict):user_uuid: str@@ -21,6 +28,8 @@ class RemoteBillingIdentityDict(TypedDict):remote_server_uuid: strremote_realm_uuid: str+ authenticated_at: int+next_page: Optional[str]@@ -29,6 +38,8 @@ class LegacyServerIdentityDict(TypedDict):# to add more information as appropriate.remote_server_uuid: str+ authenticated_at: int+def get_identity_dict_from_session(request: HttpRequest,@@ -44,10 +55,20 @@ def get_identity_dict_from_session(return Noneif realm_uuid is not None:- return identity_dicts.get(f"remote_realm:{realm_uuid}")+ result = identity_dicts.get(f"remote_realm:{realm_uuid}")else:assert server_uuid is not None- return identity_dicts.get(f"remote_server:{server_uuid}")+ result = identity_dicts.get(f"remote_server:{server_uuid}")++ if result is None:+ return None+ if (+ datetime_to_timestamp(timezone_now()) - result["authenticated_at"]+ > REMOTE_BILLING_SESSION_VALIDITY_SECONDS+ ):+ return None++ return resultdef get_remote_realm_from_session(diff --git a/corporate/tests/test_remote_billing.py b/corporate/tests/test_remote_billing.pyindex 80e95b5a98d..ec7e7c18c92 100644--- a/corporate/tests/test_remote_billing.py+++ b/corporate/tests/test_remote_billing.py@@ -1,12 +1,20 @@+import datetimefrom typing import TYPE_CHECKING, Optionalfrom unittest import mockimport responses+import time_machinefrom django.test import override_settings+from django.utils.timezone import now as timezone_now-from corporate.lib.remote_billing_util import RemoteBillingIdentityDict, RemoteBillingUserDict+from corporate.lib.remote_billing_util import (+ REMOTE_BILLING_SESSION_VALIDITY_SECONDS,+ RemoteBillingIdentityDict,+ RemoteBillingUserDict,+)from zerver.lib.remote_server import send_realms_only_to_push_bouncerfrom zerver.lib.test_classes import BouncerTestCase+from zerver.lib.timestamp import datetime_to_timestampfrom zerver.models import UserProfilefrom zilencer.models import RemoteRealm@@ -19,16 +27,21 @@ class RemoteBillingAuthenticationTest(BouncerTestCase):def execute_remote_billing_authentication_flow(self, user: UserProfile, next_page: Optional[str] = None) -> "TestHttpResponse":+ now = timezone_now()+self_hosted_billing_url = "/self-hosted-billing/"if next_page is not None:self_hosted_billing_url += f"?next_page={next_page}"- result = self.client_get(self_hosted_billing_url)+ with time_machine.travel(now, tick=False):+ result = self.client_get(self_hosted_billing_url)+self.assertEqual(result.status_code, 302)self.assertIn("http://selfhosting.testserver/remote-billing-login/", result["Location"])# We've received a redirect to an URL that will grant us an authenticated# session for remote billing.- result = self.client_get(result["Location"], subdomain="selfhosting")+ with time_machine.travel(now, tick=False):+ result = self.client_get(result["Location"], subdomain="selfhosting")# When successful, we receive a final redirect.self.assertEqual(result.status_code, 302)@@ -41,6 +54,7 @@ class RemoteBillingAuthenticationTest(BouncerTestCase):),remote_server_uuid=str(self.server.uuid),remote_realm_uuid=str(user.realm.uuid),+ authenticated_at=datetime_to_timestamp(now),next_page=next_page,)self.assertEqual(@@ -109,6 +123,43 @@ class RemoteBillingAuthenticationTest(BouncerTestCase):self.assert_in_success_response(["Your remote user info:"], result)self.assert_in_success_response([desdemona.delivery_email], result)+ @responses.activate+ def test_remote_billing_authentication_flow_expired_session(self) -> None:+ now = timezone_now()++ self.login("desdemona")+ desdemona = self.example_user("desdemona")+ realm = desdemona.realm++ self.add_mock_response()+ send_realms_only_to_push_bouncer()++ with time_machine.travel(now, tick=False):+ result = self.execute_remote_billing_authentication_flow(desdemona)++ self.assertEqual(result["Location"], f"/realm/{realm.uuid!s}/plans")++ final_url = result["Location"]++ # Go to the URL we're redirected to after authentication and make sure+ # we're granted access.+ with time_machine.travel(+ now + datetime.timedelta(seconds=1),+ tick=False,+ ):+ result = self.client_get(final_url, subdomain="selfhosting")+ self.assert_in_success_response(["Your remote user info:"], result)+ self.assert_in_success_response([desdemona.delivery_email], result)++ # Now go there again, simulating doing this after the session has expired.+ # We should be denied access.+ with time_machine.travel(+ now + datetime.timedelta(seconds=REMOTE_BILLING_SESSION_VALIDITY_SECONDS + 1),+ tick=False,+ ):+ result = self.client_get(final_url, subdomain="selfhosting")+ self.assert_json_error(result, "User not authenticated")+@responses.activatedef test_remote_billing_authentication_flow_to_sponsorship_page(self) -> None:self.login("desdemona")diff --git a/corporate/views/remote_billing_page.py b/corporate/views/remote_billing_page.pyindex fdbdd437a5e..3c5063a6568 100644--- a/corporate/views/remote_billing_page.py+++ b/corporate/views/remote_billing_page.py@@ -7,12 +7,14 @@ from django.http import HttpRequest, HttpResponse, HttpResponseRedirectfrom django.shortcuts import renderfrom django.urls import reversefrom django.utils.crypto import constant_time_compare+from django.utils.timezone import now as timezone_nowfrom django.utils.translation import gettext as _from django.views.decorators.csrf import csrf_exemptfrom pydantic import Jsonfrom corporate.lib.decorator import self_hosting_management_endpointfrom corporate.lib.remote_billing_util import (+ REMOTE_BILLING_SESSION_VALIDITY_SECONDS,LegacyServerIdentityDict,RemoteBillingIdentityDict,RemoteBillingUserDict,@@ -21,6 +23,7 @@ from corporate.lib.remote_billing_util import (from zerver.lib.exceptions import JsonableError, MissingRemoteRealmErrorfrom zerver.lib.remote_server import RealmDataForAnalytics, UserDataForRemoteBillingfrom zerver.lib.response import json_success+from zerver.lib.timestamp import datetime_to_timestampfrom zerver.lib.typed_endpoint import PathOnly, typed_endpointfrom zilencer.models import RemoteRealm, RemoteZulipServer, get_remote_server_by_uuid@@ -57,6 +60,7 @@ def remote_server_billing_entry(),remote_server_uuid=str(remote_server.uuid),remote_realm_uuid=str(remote_realm.uuid),+ authenticated_at=datetime_to_timestamp(timezone_now()),next_page=next_page,)@@ -74,6 +78,11 @@ def remote_server_billing_finalize_login(request: HttpRequest,signed_billing_access_token: str,) -> HttpResponse:+ # Sanity assert, because otherwise these make no sense.+ assert (+ settings.SIGNED_ACCESS_TOKEN_VALIDITY_IN_SECONDS < REMOTE_BILLING_SESSION_VALIDITY_SECONDS+ )+try:identity_dict: RemoteBillingIdentityDict = signing.loads(signed_billing_access_token, max_age=settings.SIGNED_ACCESS_TOKEN_VALIDITY_IN_SECONDS@@ -271,6 +280,9 @@ def remote_billing_legacy_server_login(request.session["remote_billing_identities"] = {}request.session["remote_billing_identities"][f"remote_server:{remote_server_uuid}"- ] = LegacyServerIdentityDict(remote_server_uuid=remote_server_uuid)+ ] = LegacyServerIdentityDict(+ remote_server_uuid=remote_server_uuid,+ authenticated_at=datetime_to_timestamp(timezone_now()),+ )return HttpResponseRedirect(reverse("remote_billing_page_server", args=(remote_server_uuid,)))