Skip to content
Open
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
17 changes: 0 additions & 17 deletions src/lando/api/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
from lando.api.legacy.workers.uplift_worker import (
UpliftWorker,
)
from lando.api.tests.mocks import PhabricatorDouble
from lando.main.models import JobStatus, Repo, Revision
from lando.main.models.uplift import (
RevisionUpliftJob,
Expand Down Expand Up @@ -135,22 +134,6 @@ def request_mocker():
yield m


@pytest.fixture
def phabdouble(monkeypatch):
"""Mock the Phabricator service and build fake response objects."""
phabdouble = PhabricatorDouble(monkeypatch)

# Create required projects.
phabdouble.project(SEC_PROJ_SLUG)
phabdouble.project(CHECKIN_PROJ_SLUG)
phabdouble.project(SEC_APPROVAL_PROJECT_SLUG)
phabdouble.project(
RELMAN_PROJECT_SLUG,
attachments={"members": {"members": [{"phid": "PHID-USER-1"}]}},
)
yield phabdouble


@pytest.fixture
def mock_uplift_email_tasks(monkeypatch):
success_task = mock.MagicMock()
Expand Down
24 changes: 23 additions & 1 deletion src/lando/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,19 @@
from django.contrib.contenttypes.models import ContentType
from requests.models import HTTPError

from lando.api.legacy.projects import (
CHECKIN_PROJ_SLUG,
RELMAN_PROJECT_SLUG,
SEC_APPROVAL_PROJECT_SLUG,
SEC_PROJ_SLUG,
)
from lando.api.legacy.stacks import (
RevisionStack,
build_stack_graph,
request_extended_revision_data,
)
from lando.api.legacy.transplants import build_stack_assessment_state
from lando.api.tests.mocks import TreeStatusDouble
from lando.api.tests.mocks import PhabricatorDouble, TreeStatusDouble
from lando.headless_api.models.automation_job import AutomationJob
from lando.headless_api.models.tokens import ApiToken
from lando.main.models import (
Expand Down Expand Up @@ -1186,6 +1192,22 @@ def treestatusdouble(monkeypatch, treestatus_url):
yield TreeStatusDouble(monkeypatch, treestatus_url)


@pytest.fixture
def phabdouble(monkeypatch):
"""Mock the Phabricator service and build fake response objects."""
phabdouble = PhabricatorDouble(monkeypatch)

# Create required projects.
phabdouble.project(SEC_PROJ_SLUG)
phabdouble.project(CHECKIN_PROJ_SLUG)
phabdouble.project(SEC_APPROVAL_PROJECT_SLUG)
phabdouble.project(
RELMAN_PROJECT_SLUG,
attachments={"members": {"members": [{"phid": "PHID-USER-1"}]}},
)
yield phabdouble


#
# PushLog fixtures
#
Expand Down
32 changes: 31 additions & 1 deletion src/lando/ui/legacy/user_settings.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,35 @@
import logging

from django.core.handlers.wsgi import WSGIRequest
from django.db import IntegrityError
from django.http import HttpResponseNotAllowed, JsonResponse

from lando.main.auth import require_authenticated_user
from lando.main.models.profile import Profile
from lando.ui.legacy.forms import UserSettingsForm
from lando.utils.phabricator import get_phabricator_client

logger = logging.getLogger(__name__)


def phid_conflict_response(phid: str) -> JsonResponse:
"""Return a 400 response indicating the PHID is owned by another account."""
logger.info(
"Phabricator PHID `%s` is already linked to another Lando account.",
phid,
)
return JsonResponse(
{
"errors": {
"phabricator_api_key": [
"This Phabricator account is already linked to another Lando user."
]
}
},
status=400,
)


@require_authenticated_user
def manage_api_key(request: WSGIRequest) -> JsonResponse:
"""Sets `phabricator-api-token` cookie from the UserSettingsForm.
Expand Down Expand Up @@ -43,6 +63,16 @@ def manage_api_key(request: WSGIRequest) -> JsonResponse:
phid = whoami["phid"]
logger.debug("Phabricator API key verified for PHID `%s`.", phid)

profile.save_phabricator_api_key(api_key, phid=phid)
if (
Profile.objects.filter(phabricator_phid=phid)
.exclude(pk=profile.pk)
.exists()
):
return phid_conflict_response(phid)

try:
profile.save_phabricator_api_key(api_key, phid=phid)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we not check for existing PHIDs here, avoiding the integrity error altogether?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could, but it would add another DB query on every API key update, and we'd still want to keep the IntegrityError handler to cover the potential race condition (unlikely but technically possible). Happy to change it, this just follows EAFP and is more efficient for the happy path. WDYT?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This endpoint is not used frequently, the extra DB query would be negligible.

The code flow would be more logical if we're explicit about detecting the error state, rather than working around the issue. The integrity error could also (in theory, though very unlikely) occur in a different situation, so here we'd be handling the expected error case that we already discovered.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added a check for a duplicate PHID. Personally I don't think it's a meaningful improvement - we're still catching the IntegrityError to catch the race condition, so it's more code for the same functionality - but happy to move forward with it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm what's the point of catching the IntegrityError? We don't need to do that as long as we know there is no duplicate value. Otherwise it would be a misleading error since if triggered, it is some other issue that is causing that and not the PHID.

I would suggest removing the try/except altogether.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm what's the point of catching the IntegrityError? We don't need to do that as long as we know there is no duplicate value. Otherwise it would be a misleading error since if triggered, it is some other issue that is causing that and not the PHID.

The IntegrityError handler covers the race between our .exists() and .save() — without it, two concurrent requests linking the same PHID would 500 instead of returning a clean 400. And since phabricator_phid is the only unique field we touch here, an IntegrityError can't really come from anywhere else.

Yes, the race is unlikely — but the bug is specifically about an unhandled server error, and switching to just an exists() check doesn't actually resolve that; it just makes the window smaller.

This is why I preferred just the try/except version — it was less code, handled both cases, and required fewer DB lookups on the happy path.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To handle the (very unlikely) race condition we could do the check and the save with a lock, but I think that's overkill. This endpoint is infrequently used, I think the basic issue is to present a meaningful error to the user and avoid having a server issue.

I won't split more hairs here but I think preventing an integrity error is better than handling it when it happens.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TL;DR this should be handled as a validation problem, and not a database integrity problem.

except IntegrityError:
return phid_conflict_response(phid)

return JsonResponse({"success": True}, status=200)
71 changes: 71 additions & 0 deletions src/lando/ui/tests/test_user_settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import pytest
from django.contrib.auth.models import User
from django.test import Client

from lando.main.models.profile import Profile

VALID_API_KEY = "api-aaaaaaaaaaaaaaaaaaaaaaaaaaaa"


def post_api_key(client: Client, api_key: str = VALID_API_KEY):
"""Submit an API key to the `manage_api_key` view."""
return client.post(
"/manage_api_key/",
data={"phabricator_api_key": api_key, "reset_key": False},
)


@pytest.mark.django_db(transaction=True)
def test_manage_api_key_happy_path(
client: Client,
user,
phabdouble,
):
"""A successful API key update stores the new key and PHID on the profile."""
phab_user = phabdouble.user(username="phab_user", api_key=VALID_API_KEY)

client.force_login(user)
response = post_api_key(client)

assert response.status_code == 200, (
"A valid API key with a unique PHID should be accepted."
)
assert response.json() == {"success": True}, "Response body should report success."

user.profile.refresh_from_db()
assert user.profile.phabricator_phid == phab_user["phid"], (
"Profile should store the PHID reported by `user.whoami`."
)
assert user.profile.phabricator_api_key == VALID_API_KEY, (
"Profile should store the submitted API key."
)


@pytest.mark.django_db(transaction=True)
def test_manage_api_key_phid_conflict_returns_error(
client: Client,
user,
phabdouble,
):
"""Linking an API key whose PHID already belongs to another user returns a 400."""
phab_user = phabdouble.user(username="phab_user", api_key=VALID_API_KEY)

# Another Lando user already owns this Phabricator PHID.
other_user = User.objects.create_user(
username="other_user", email="other@example.org"
)
Profile.objects.create(user=other_user, phabricator_phid=phab_user["phid"])

client.force_login(user)
response = post_api_key(client)

assert response.status_code == 400, (
"Linking an API key whose PHID is owned by another user should return 400."
)
assert response.json() == {
"errors": {
"phabricator_api_key": [
"This Phabricator account is already linked to another Lando user."
]
}
}, "Response body should describe the PHID conflict."
Loading