Skip to content

OpenConceptLab/ocl_online#730 | A REST edit that sends no access keeps its row's current access; search hits load through the database's access check - #1048

Merged
snyaggarwal merged 3 commits into
masterfrom
fix/730-visibility-follow-ups
Nov 24, 2026
Merged

snyaggarwal merged 3 commits into
masterfrom
fix/730-visibility-follow-ups

Conversation

@paynejd

@paynejd paynejd commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

For OpenConceptLab/ocl_online#730 (items 1 and 2; item 3 isn't code). References it without closing it.

1. A REST edit that sends no access keeps its row's current access

A PUT or PATCH of a source or collection, HEAD or version, that sends no public_access saved the access it read at the start of the request. If a concurrent write made the row private in between, the edit made it viewable again, and a source passed that on to its concepts and mappings.

Now such an edit calls persist_changes(..., keep_access=True). It reads the row under the select_for_update(no_key=True) lock that #1009 added for FHIR writes, in the transaction that saves it, and keeps that row's access, whatever it is. So a concurrent publish isn't undone either, and the edit isn't asked make_private for a change it didn't make. An edit that sends public_access works as before. FHIR updates keep keep_private=True, since they may copy a private release's access onto HEAD.

2. Search hits load through the database's access check

Search loaded its hits from the database by id, trusting the index's public_can_view. A document can be stale: a large source made private keeps public concept and mapping documents until its reindex task finishes, and a failed index enqueue inside a transaction leaves the old document. Such a hit was returned to anyone.

Now, wherever a search filters its hits by access, the hits load through the same access check the plain lists use, read from the database:

  • sources, collections and the repo search: get_viewable_versions_criteria();
  • concepts and mappings (by the hits' model, so a concept's collection-versions/ search, whose hits are collections, gets the collection check): get_viewable() (apply_user_criteria), which moves from Concept to SourceChildMixin, and their source must be viewable too. A source made private commits before its save signal makes its concepts and mappings private, so for a while their rows still say public;
  • organizations: Organization.get_viewable(), public (View, or the retired Edit, as the index reads it) or the requester's own, in every scope, since an org search in the requester's own scope reads the index's member list;
  • $match: the same as concepts, when it applies get_visible_repo_criteria().

Like the search's own filter, the check keeps the repositories, concepts and mappings the requester created. Where a search applies no access filter (staff, the requester's own user or org, a collection's members in the requester's scope), nothing changes: the URL's permission check governs, as in the lists.

Cost: one .filter() on the page's existing pk__in query, so no query per hit. The repo search, which already loads its hits one by one, gets one check per model (sources, collections).

Counts: num_found stays the index's count, so until the reindex it can count a hit the page drops; num_returned is what the page holds, which can be fewer than limit. Facet counts come from the index too. A Compress response's num_found is the length of the list it returns, as before.

Tests

  • UpdateToPrivateTest: a PUT or PATCH of a HEAD or version keeps the access a concurrent write gave its row, in both directions, with a source's concepts, and isn't asked make_private; and it reads the row FOR NO KEY UPDATE inside the transaction that saves it, only when it sends no access.
  • tests_stale_search_access.py (es): rows made private in the database without a reindex are no hit for the public or an outsider in the org, source, collection, repo, concept and mapping searches, another user's org list, or $match; members, staff and creators still find them.
  • The same file: a concept or mapping of a source made private, before its own row follows, is no hit for the public or an outsider (members and creators still find it); a public org stored as Edit is still a hit; a former member's own org search drops a private org; a concept's searched collection-versions/ list answers.
  • Every new test fails on the code before it (33 failures on master's code; 5 for the second commit's tests on the first; 3 for the third's on the second) and passes here. Full suite at the first commit, as CI runs it: 3,666 tests (TEST_ES=off, parallel) and 706 (es), OK. pylint -j0 core/ (4.0.9): clean.

Reviewer: @snyaggarwal.

🤖 Generated with Claude Code

https://claude.ai/code/session_01AaZ4qTLYUUSTSy1TKzRmkd

paynejd and others added 2 commits November 24, 2026 01:24
…s its row's current access; search hits load through the database's access check

- A PUT or PATCH of a source or collection (HEAD or version) that sends no public_access reads its row under a lock,
  in the transaction that saves it, and keeps that row's access. A concurrent write that made the row private, or
  public, isn't overwritten, and the concepts and mappings of a source keep its access too.
- Where a search filters its hits by access (lists, the repo search and $match), the hits load through the access
  check the lists use, read from the database: an index document that's stale, such as a row made private before
  it was reindexed, is no hit. It keeps search's rule for the items a requester created. A page can then hold fewer
  hits than its limit, while num_found stays the index's count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qTLYUUSTSy1TKzRmkd
… its source to be viewable too; a public org stored as Edit stays a hit

- A source made private commits before its save signal makes its concepts and mappings private, so their rows can
  still be public for a while: a hit for one also needs its source to be viewable, in the same query. Creators keep
  theirs, as before. $match loads its hits the same way.
- Organization.get_viewable reads public_can_view's values (View and the retired Edit), as the index does, so a
  public org stored as Edit is still a hit.
- The REST edit test checks the source's mappings too, and compares the row itself, not ids from two tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qTLYUUSTSy1TKzRmkd
@paynejd
paynejd requested a review from snyaggarwal November 24, 2026 06:35
@paynejd

paynejd commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Codex review, pass 1 (codex-cli 0.169.0, commit 18f9972)

Verdict: 3 findings: 1 P1, 2 P2.

  • F1.1 P1 core/common/mixins.py:910: a source made private commits before its save signal makes its concepts and mappings private, so a search can still return one whose row and index document both say public.
  • F1.2 P2 core/capabilities/tests/test_make_private.py:390: the REST edit test compares a collection's id with the source's (two tables, so they can match), and creates no mapping.
  • F1.3 P2 core/common/mixins.py:310: a Compress search response sets num_found to the length of its filtered list, not the index's count.

Replies (858313d; the stale-search and make-private tests pass, 30; pylint -j0 core/ clean):

  • F1.1, fixed: a concept or mapping hit also needs its source to be viewable (Source.get_viewable() on the page's parents), in the same query, and creators keep theirs. $match loads its hits the same way. New test: test_a_concept_or_mapping_of_a_source_made_private_is_no_hit_before_its_own_row_follows, which fails on 18f9972.
  • F1.2, fixed: the test compares the row itself and checks a mapping too.
  • F1.3, accepted: an unpaginated Compress response has always set num_found to the length of the list it returns, so it counts what's there. The PR body says so, and the paginated case is pinned by a num_found assertion.
  • Also in 858313d: Organization.get_viewable() reads the index's public values (View and the retired Edit), where get_visible_to() reads only View. A public org stored as Edit stays a hit (new test).
findings.json
{
  "reviewer": "codex-cli 0.169.0",
  "perspective": "defects",
  "mode": "full",
  "commit": "18f99729",
  "verdict": "findings",
  "prior": [],
  "findings": [
    {
      "id": "F1.1",
      "severity": "P1",
      "tag": null,
      "file": "core/common/mixins.py",
      "line": 910,
      "claim": "Search can still return concepts and mappings from a source that the database already marks private.",
      "scenario": "An explicit REST privacy edit commits the source row before its post-save signal finishes updating the child rows. During that interval, an anonymous search can return a concept or mapping because both its database row and its stale index document still say View. The source's own URL already denies access.",
      "action": "Check current parent-source visibility in the same batched query as child visibility, preserving the existing creator exception where it applies. Add a regression test that makes the source private while leaving the child rows and index documents unchanged.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F1.2",
      "severity": "P2",
      "tag": null,
      "file": "core/capabilities/tests/test_make_private.py",
      "line": 390,
      "claim": "The concurrency test can fail on unrelated collection edits and does not verify the mapping behavior it claims to cover.",
      "scenario": "Source and Collection use separate primary-key sequences. If their fixtures have the same numeric ID, the collection subtest that makes the collection private also asserts that the source's concept became private. The preceding source subtest left that concept public, so the test fails despite a correct collection edit. The fixture also creates no mapping, so a mapping-only regression passes.",
      "action": "Compare the model instance with self.source and create and refresh a mapping alongside the concept when asserting child access.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F1.3",
      "severity": "P2",
      "tag": null,
      "file": "core/common/mixins.py",
      "line": 310,
      "claim": "Compressed searches report the filtered result count in num_found even though the stated behavior is to retain the index count.",
      "scenario": "A source search has one indexed hit that the database check drops. The paginated response reports num_found of 1 and num_returned of 0. The same search with Compress set to true reports num_found of 0 because that branch takes the length of the filtered hits.",
      "action": "Use the index count for compressed searches too, or explicitly document the compressed response as an exception. Add a stale-hit assertion for num_found.",
      "lines_delta": null,
      "confidence": "high"
    }
  ]
}

…nd mapping hits by their model; org hits are checked in the requester's own scope too

- A concept's collection-versions search has collection hits, though it searches as a concept view does: the source
  check now applies by the hits' model, not the view's, so that search answers again instead of failing.
- An org search in the requester's own scope reads the index's member list, so a former member could still find a
  private org there: org hits load through Organization.get_viewable() in every scope.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qTLYUUSTSy1TKzRmkd

@snyaggarwal snyaggarwal left a comment

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.

Approving. The REST-edit lock and the database check on search hits both look right to me. The check only narrows what the index's filter already let through, so where it's more permissive than the index (creators, members), results can't widen. Every document model that reaches the check has a get_viewable. $match is the same.

Codex pass 1 (F1.1 to F1.3) already covered the window after a source is made private, the test's id comparison and Compress's num_found, so I have nothing to add there.

Inline, all optional: four nits, two docstring wording suggestions, one pre-existing.

Comment thread core/common/models.py
queue_schema_update_task = obj.is_validation_necessary()
try:
with transaction.atomic() if keep_private else nullcontext():
with transaction.atomic() if lock else nullcontext():

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.

Nit (optional): every REST edit that sends no access now runs inside transaction.atomic(), so CelerySignalProcessor.handle_save defers the index enqueue with robust=True. If that enqueue fails (broker down), the error is now logged and swallowed and the edit returns 200 with the old search document. Under autocommit, the error used to reach the caller. That's the stale-document source the PR body names, now on the most common edit path. The new hit check covers access, but a renamed repo just won't be findable by its new name until something reindexes it. Either note in the docstring that this is accepted, or surface a failed enqueue after the block.

Comment thread core/common/models.py
# no key update, so a concurrent child write's foreign-key check on the row isn't blocked
original_repo = (stored_rows.select_for_update(no_key=True) if keep_private else stored_rows).first()
if keep_private and not original_repo.public_can_view:
original_repo = (stored_rows.select_for_update(no_key=True) if lock else stored_rows).first()

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.

Pre-existing (not from this change, not blocking): .first() returns None if the row was hard-deleted between the view's lookup and this read, and original_repo.public_access / .released below then raises AttributeError, which is a 500. The lock doesn't change that. A None check returning an error (or raising 404) would.

Comment thread core/common/views.py
viewable = viewable.filter(parent_id__in=parents.values('id'))
if user.is_authenticated and not user.is_staff and (
self.is_concept_container_document_model() or self.is_source_child_document_model()):
viewable = hits.filter(models.Q(id__in=viewable.values('id')) | models.Q(created_by_id=user.id))

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.

Nit (optional): the creator branch keeps any hit the requester created, so it also skips the is_active=True part of get_viewable_versions_criteria and the parent-source check. A deleted source whose document hasn't been reindexed yet (or one of its concepts, whose is_active the save signal turns off) is still a hit for its creator, while everyone else loses it. Requiring the row to be active on that branch closes it. It's worth checking that no search here opts into inactive hits first:

Suggested change
viewable = hits.filter(models.Q(id__in=viewable.values('id')) | models.Q(created_by_id=user.id))
viewable = hits.filter(
models.Q(id__in=viewable.values('id')) | models.Q(created_by_id=user.id, is_active=True))

Comment thread core/orgs/models.py
return cls.objects.filter(public_access=ACCESS_TYPE_VIEW)

@classmethod
def get_viewable(cls, queryset, user):

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.

Nit (optional): get_viewable and get_visible_to (just below) are now two org visibility checks that disagree. This one counts the retired Edit as public, while get_visible_to (through get_public) counts only View. So an org stored as Edit is a search hit but missing from the database-backed org lists. Having get_visible_to delegate to get_viewable, or having get_public use PUBLIC_ACCESS_VALUES, would leave one rule. Fine as a follow-up.

self.assertNotIn(self.source.mnemonic, self.search_ids(url, self.outsider))

def test_match_drops_a_concept_made_private_without_a_reindex(self):
self.outsider.groups.add(Group.objects.get(name=PREVIEW_GROUP_NAME))

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.

Nit (optional): this grants $match access by adding the outsider to a named access group. That copies existing debt tracked in OpenConceptLab/ocl_online#532 into a new file. If there's no neutral way yet to give a test user Mapper access, a shared helper in core/common/tests.py would at least keep the name in one place. Otherwise, note this use on that ticket.

def made_private_first(model, method, access=ACCESS_TYPE_NONE):
"""
`model`'s `method`, run after a concurrent write that makes its row (the first argument) private commits, or
gives it `access`, with its concepts' and mappings' (as the save signal does).

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.

Nit (optional): this reads oddly ("with its concepts' and mappings'").

Suggested change
gives it `access`, with its concepts' and mappings' (as the save signal does).
gives it `access` and, for a source, its concepts and mappings too (as the save signal does).

Comment on lines +369 to +370
meanwhile stays private, with its concepts and mappings, and a row made public stays public without the edit
being asked make_private.

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.

Nit (optional): "being asked make_private" is hard to parse.

Suggested change
meanwhile stays private, with its concepts and mappings, and a row made public stays public without the edit
being asked make_private.
meanwhile stays private, with its concepts and mappings, and a row made public stays public, without the edit
going through the make_private check.

@paynejd

paynejd commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Codex review, pass 2 (codex-cli 0.169.0, commit 858313d)

Verdict: 4 findings: 3 P1, 1 P2. Earlier: F1.2 resolved; F1.1 marked regressed (F2.1 below); F1.3 unresolved (accepted in pass 1).

  • F2.1 P1 core/common/views.py:1352: a concept's collection-versions/?q= search has collection hits but a concept view's facet class, so the new source check asks a Collection queryset for parent_id and fails.
  • F2.2 P1 core/common/views.py:1061: an org search in the requester's own scope (/user/orgs/?q=) reads the index's member list and skipped the check, so a former member could still find a private org.
  • F2.3 P1 core/graphql/queries.py:522: GraphQL's global concept search checks each concept's own row, which lags its source while a source made private passes its access on.
  • F2.4 P2 core/concepts/views.py:1152: $match could return hits from a target release made private between resolving the target and loading the hits.

Replies (45fba55; stale-search and make-private tests pass, 32; pylint -j0 core/ clean):

  • F2.1, fixed: the source check applies by the hits' model (SourceChildMixin), not the view's. New test: test_a_concept_s_collection_versions_search_loads_collections, which errors on 858313d.
  • F2.2, fixed: org hits load through Organization.get_viewable() in every scope. New test: test_a_former_member_s_own_org_search_drops_a_private_org, which fails on 858313d.
  • F2.3, accepted: GraphQL's search doesn't read the index: it filters concepts in the database, as the plain concept lists do, and both see a concept's row lag its source while the save signal updates them, when the edit sends public_access and so runs under autocommit. That predates this PR. Closing it at the root means running that update in the source's transaction, which for REST edits changes how a failed index enqueue is reported (kept as is in OpenConceptLab/ocl_online#365 | The write checkpoint asks make_private when a repository row is saved as private #1009's review); I've passed it on as a possible follow-up.
  • F2.4, accepted: a race inside one request, between its own access check and its read, as with any checked read.
findings.json
{
  "reviewer": "codex-cli 0.169.0",
  "perspective": "defects",
  "mode": "verify",
  "commit": "858313d1",
  "verdict": "findings",
  "prior": [
    {"id": "F1.1", "status": "regressed"},
    {"id": "F1.2", "status": "resolved"},
    {"id": "F1.3", "status": "unresolved"}
  ],
  "findings": [
    {
      "id": "F2.1",
      "severity": "P1",
      "tag": null,
      "file": "core/common/views.py",
      "line": 1352,
      "claim": "Searching a concept’s collection versions raises a FieldError.",
      "scenario": "An anonymous reader adds `?q=...` to a public concept’s `collection-versions/` URL. The view searches CollectionDocument but inherits ConceptFacetedSearch, so the new source check tries to select `parent_id` from the Collection queryset. Collection exposes `parent_id` as a Python property and Django cannot use it in `values()`.",
      "action": "Choose the source-parent check from the hit queryset’s model. Apply repository visibility to Collection hits and add a test for a searched collection-version listing.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F2.2",
      "severity": "P1",
      "tag": null,
      "file": "core/common/views.py",
      "line": 1061,
      "claim": "A former member can still find a private organization through their own organization search.",
      "scenario": "A user is removed from a private organization while its search document still lists them as a member. `/user/orgs/?q=...` uses that indexed membership and skips the database check in the requester’s own scope. The search returns the private organization even though the plain list excludes it.",
      "action": "Intersect organization search hits with current database membership and visibility for the user named by the URL. Add a test that removes membership without refreshing the index.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F2.3",
      "severity": "P1",
      "tag": null,
      "file": "core/graphql/queries.py",
      "line": 522,
      "claim": "Global GraphQL concept search still returns hits from sources already marked private.",
      "scenario": "A source’s HEAD is made private while its concept rows and search documents still say public. An authenticated outsider runs a global GraphQL text search. The database queryset checks the concept’s copied access and returns the hit while the source itself denies access.",
      "action": "Apply the live source visibility check to the global GraphQL queryset in bulk and add a test that changes only the source’s access.",
      "lines_delta": null,
      "confidence": "high"
    },
    {
      "id": "F2.4",
      "severity": "P2",
      "tag": null,
      "file": "core/concepts/views.py",
      "line": 1152,
      "claim": "$match can return hits from a target release that becomes private during the search.",
      "scenario": "An outsider starts a match against a public release. After target resolution and before hit loading, the release is made private while its HEAD stays public. The matching concept rows still point to HEAD, so the database check passes and the response returns hits from the now-private release.",
      "action": "Carry the resolved target release IDs into hit loading and recheck their visibility in bulk. Test a release access change between target resolution and hit loading.",
      "lines_delta": null,
      "confidence": "high"
    }
  ]
}

@paynejd

paynejd commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

@snyaggarwal thanks for the approval. Please hold the merge for now: the third Codex pass on 45fba55 found two more cases in the search check (a source or collection CSV export whose only hit is dropped falls back to the plain list, and facets still name a source whose hits were dropped). I'm fixing both and will post exactly what changed since your approval so you can re-check.

@snyaggarwal
snyaggarwal merged commit cd63886 into master Nov 24, 2026
2 checks passed
@snyaggarwal
snyaggarwal deleted the fix/730-visibility-follow-ups branch November 24, 2026 06:51
@paynejd

paynejd commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Codex review, pass 3 (codex-cli 0.169.0, commit 45fba55)

Verdict: 3 findings: 2 P1, 1 P2. Earlier: F1.1, F1.2, F2.1, F2.2 resolved; F1.3, F2.3, F2.4 unresolved (accepted in passes 1 and 2).

  • F3.1 P1 core/common/views.py:1317: a source or collection CSV search whose only hit the check drops gives an empty queryset, and the CSV row builder treats empty as missing and falls back to the plain list.
  • F3.2 P1 core/common/views.py:1062: facets come from the index, so a stale concept search's source and owner facets still name a source whose hits were dropped.
  • F3.3 P2 core/common/models.py:1423: a REST edit that sends no access now runs in a transaction, where a failed index enqueue is only logged; under autocommit it reached the request.

This PR merged before this pass came back, so the fixes are in the follow-up, #1050 (@snyaggarwal: that replaces my hold note's ask; please review #1050 instead).

Replies:

findings.json
{
    "reviewer": "codex-cli 0.169.0",
    "perspective": "defects",
    "mode": "verify",
    "commit": "45fba556",
    "verdict": "findings",
    "prior": [
        {
            "id": "F1.1",
            "status": "resolved"
        },
        {
            "id": "F1.2",
            "status": "resolved"
        },
        {
            "id": "F1.3",
            "status": "unresolved"
        },
        {
            "id": "F2.1",
            "status": "resolved"
        },
        {
            "id": "F2.2",
            "status": "resolved"
        },
        {
            "id": "F2.3",
            "status": "unresolved"
        },
        {
            "id": "F2.4",
            "status": "unresolved"
        }
    ],
    "findings": [
        {
            "id": "F3.1",
            "severity": "P1",
            "tag": null,
            "file": "core/common/views.py",
            "line": 1317,
            "claim": "A source or collection CSV search can export a release the database visibility check dropped.",
            "scenario": "An anonymous CSV search with allVersions=true and version=v1 finds a single stale hit for a release whose row still says View after its HEAD was made private. The database check drops the hit. The CSV row builder treats the empty queryset as missing and falls back to the plain list, which checks the release's own access and exports it.",
            "action": "In the source and collection CSV row builders, fall back only when the queryset is None. Add a regression test that checks the contents of an export after its only hit is dropped.",
            "lines_delta": null,
            "confidence": "high"
        },
        {
            "id": "F3.2",
            "severity": "P1",
            "tag": null,
            "file": "core/common/views.py",
            "line": 1062,
            "claim": "Search facets still disclose the names of private sources whose hits were dropped.",
            "scenario": "When a source is made private before its concept documents are reindexed, an anonymous global concept search with facets drops those concepts from the results. The facets still use the stale Elasticsearch documents and return the source's mnemonic and owner.",
            "action": "Apply the live access check to named source and owner facets, and add a stale-index test for the facet response. Keep num_found based on the index as documented.",
            "lines_delta": null,
            "confidence": "high"
        },
        {
            "id": "F3.3",
            "severity": "P2",
            "tag": null,
            "file": "core/common/models.py",
            "line": 1423,
            "claim": "A REST edit that omits public_access now suppresses a search-index enqueue failure that previously reached the caller.",
            "scenario": "A name-only PATCH commits while the indexing broker is unavailable. The new transaction makes CelerySignalProcessor register the enqueue with robust=True, so the request can return 200 while the search document keeps the old name. The same save previously surfaced the enqueue error under autocommit.",
            "action": "Keep the row lock and preserve enqueue-error reporting for REST edits that previously ran under autocommit. Cover the name-only PATCH with a transaction test that makes the enqueue fail.",
            "lines_delta": null,
            "confidence": "high"
        }
    ]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants