Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

fix(organizations): a 401 from the members service is not a sign-in

Petr Bauch998cf32d0534
diff --git a/core/switch_core/members_service.py b/core/switch_core/members_service.py
index 5dae0650c..4e52fdec3 100644
--- a/core/switch_core/members_service.py
+++ b/core/switch_core/members_service.py
@@ -20,7 +20,11 @@ A refusal comes back as `{"error": <reason>}`.
from __future__ import annotations
+import logging
+import time
+
import httpx
+import jwt
from switch_core.organization_directory import (
DirectoryRefusal,
@@ -28,6 +32,8 @@ from switch_core.organization_directory import (
DirectoryUnavailable,
)
+logger = logging.getLogger(__name__)
+
# Bounds every call: a route holds locks while it waits.
MEMBERS_SERVICE_TIMEOUT_SECONDS = 10.0
@@ -36,6 +42,14 @@ SIGN_IN_AGAIN = (
"to change the organization's members."
)
+# The service checks a token without asking WorkOS, so a 401 for one that has
+# not run out is the service not accepting Switch's AuthKit application at
+# all: signing in again would get the same answer.
+NOT_ACCEPTED = (
+ "Your organization's account service doesn't accept member changes from "
+ "Switch yet. Make the change in the organization's account settings."
+)
+
class MembersService:
def __init__(self, http: httpx.AsyncClient, url: str) -> None:
@@ -76,7 +90,15 @@ class MembersService:
f"The members service could not be reached ({type(error).__name__})."
) from error
if response.status_code == 401:
- raise DirectorySignInRequired(SIGN_IN_AGAIN)
+ if _ran_out(access_token):
+ raise DirectorySignInRequired(SIGN_IN_AGAIN)
+ logger.error(
+ "The members service refused Switch's WorkOS token (401) on %s %s; "
+ "it is not set up to accept WORKOS_CLIENT_ID's tokens",
+ method,
+ path,
+ )
+ raise DirectoryUnavailable(NOT_ACCEPTED)
if response.status_code in (400, 403, 404, 409, 422):
raise DirectoryRefusal(_reason(response))
if response.status_code >= 300:
@@ -85,6 +107,19 @@ class MembersService:
)
+def _ran_out(access_token: str) -> bool:
+ """Whether the token's own expiry has passed. Read unverified, for which
+ answer to give only: the token is the one WorkOS gave the admin
+ (`workos_sign_in.py`), and the service is what verifies it."""
+ try:
+ expires_at = jwt.decode(access_token, options={"verify_signature": False})[
+ "exp"
+ ]
+ except (jwt.PyJWTError, KeyError):
+ return False
+ return isinstance(expires_at, int) and expires_at <= time.time()
+
+
def _reason(response: httpx.Response) -> str:
"""The service's own words for a refusal, or its status when it gave none."""
try:
diff --git a/core/tests/switch_core/gateway/test_workos_sign_in_routes.py b/core/tests/switch_core/gateway/test_workos_sign_in_routes.py
index 52e5069c4..875e46dcc 100644
--- a/core/tests/switch_core/gateway/test_workos_sign_in_routes.py
+++ b/core/tests/switch_core/gateway/test_workos_sign_in_routes.py
@@ -329,7 +329,7 @@ class TestChangingMembers:
assert refused.status_code == 409
assert "workspaces first" in refused.json()["detail"]
- async def test_a_token_refused_after_access_was_ended_says_so(
+ async def test_a_token_not_accepted_after_access_was_ended_says_so(
self, session_factory
) -> None:
ada, cy = _name("ada"), _name("cy")
@@ -346,11 +346,11 @@ class TestChangingMembers:
f"/organizations/current/members/{cy}", json={"role": "member"}
)
- assert refused.status_code == 403
+ # The token has not run out, so signing in again would not help.
+ assert refused.status_code == 503
detail = refused.json()["detail"]
- assert detail["error"] == "directory_sign_in_required"
- assert detail["access_ended"] is True
- assert "already been taken away" in detail["message"]
+ assert "doesn't accept member changes from Switch" in detail
+ assert "already been taken away" in detail
assert await _role(session_factory, organization_id, cy) == "org_admin"
diff --git a/core/tests/switch_core/test_members_service.py b/core/tests/switch_core/test_members_service.py
index 1b20af049..6ebd65eeb 100644
--- a/core/tests/switch_core/test_members_service.py
+++ b/core/tests/switch_core/test_members_service.py
@@ -3,8 +3,10 @@
from __future__ import annotations
import json
+import time
import httpx
+import jwt
import pytest
from switch_core.members_service import MembersService
@@ -18,6 +20,10 @@ URL = "https://members.example.test"
TOKEN = "token-of-the-admin"
+def _token(expires_in: int) -> str:
+ return jwt.encode({"exp": int(time.time()) + expires_in}, "test-key-not-a-secret")
+
+
def _service(handler) -> MembersService:
return MembersService(
httpx.AsyncClient(transport=httpx.MockTransport(handler)), URL
@@ -57,12 +63,29 @@ class TestChanging:
class TestRefusals:
- async def test_a_token_it_no_longer_takes_asks_for_a_sign_in(self) -> None:
+ async def test_a_token_it_does_not_accept_is_unavailable_not_a_sign_in(
+ self, caplog: pytest.LogCaptureFixture
+ ) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(401, json={"error": "unauthorized"})
+
+ token = _token(300)
+ with pytest.raises(
+ DirectoryUnavailable, match="doesn't accept member changes from Switch"
+ ):
+ await _service(handler).remove(token, "om_1")
+ assert any(
+ r.levelname == "ERROR" and "refused Switch's WorkOS token" in r.getMessage()
+ for r in caplog.records
+ )
+ assert token not in caplog.text
+
+ async def test_a_token_that_ran_out_asks_for_a_sign_in(self) -> None:
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(401, json={"error": "unauthorized"})
with pytest.raises(DirectorySignInRequired):
- await _service(handler).remove(TOKEN, "om_1")
+ await _service(handler).remove(_token(-1), "om_1")
async def test_its_own_rules_refuse_in_its_words(self) -> None:
def handler(request: httpx.Request) -> httpx.Response:
diff --git a/docs/old/workos-directory.md b/docs/old/workos-directory.md
index fe5daab69..5038cd9aa 100644
--- a/docs/old/workos-directory.md
+++ b/docs/old/workos-directory.md
@@ -149,7 +149,10 @@ in as, or to another organization, is refused. Switch's own checks still run
first; the service may refuse by its own rules, and its reason is shown. If
the token runs out after a demotion or removal has already taken away the
person's workspace access, the dashboard says so before sending the admin to
-sign in again to finish. A platform operator restoring an Org Admin can't
+sign in again to finish. If the service refuses a token that has not run
+out, it is not set up to accept this AuthKit application's tokens: Switch
+answers 503, says to make the change in the account settings, and logs an
+error, rather than sending the admin to sign in again. A platform operator restoring an Org Admin can't
sign in there: unless WorkOS already has that person as `org_admin`, they are
told to have someone made one in the organization's account settings.