Repository navigation
OpenConceptLab/ocl_online#730 | Search facets name only the sources and owners the requester can view; a REST edit that sends no access saves every column but the access - #1050
Conversation
…nd owners the requester can view Where a search filters by access, each source or owner facet name stays only if a repository the requester can view has it, so a stale index document doesn't name a source made private, or its owner. Counts stay the index's. The search's access filter moves into get_search_visibility_criteria(), which the facets read too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qW1SrjGg8mwU3zehyF
…s every column but the access, with no lock So a concurrent write's access stays whenever it commits, and the edit runs under autocommit, where a failed search-index enqueue reaches the request. A blank access is still stored as None, while it's still blank. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qW1SrjGg8mwU3zehyF
Simplification review (Claude subagent, commit d009179)Verdict: 2 items, both low confidence; neither applied, so no new commits.
|
snyaggarwal
left a comment
There was a problem hiding this comment.
Review: two issues with the no-lock path for blank-access rows, plus four nits, inline.
| field.name for field in cls._meta.concrete_fields | ||
| if not field.primary_key and field.name != 'public_access'] | ||
| obj.save(**kwargs) | ||
| if keep_access and original_repo.public_access == '': # stored as None, unless a write changed it |
There was a problem hiding this comment.
Race on a blank-access row can leave a public source with private concepts and mappings. Without the lock, a blank row reads '', obj.public_access becomes None, and _should_update_public_access is True, so the post_save signal sets every concept and mapping to None. If a concurrent write sets the row to View between the read and the save, this conditional update correctly skips, but the children were already set to None from the stale value.
Scenario: source stored with ''; a name-only PATCH reads it; a make-public commits View; the PATCH saves without the column and its signal makes all children private; this update matches nothing.
Suggestion: for keep_access, do the blank-to-None update first as the conditional update and propagate to children only if it changed a row (or keep the lock just for the blank case).
There was a problem hiding this comment.
Agreed, thanks. Fixed in 01259ee the second way you suggest: a row stored with a blank access is saved as #1048 saved it, under the row lock in one transaction, so its None and the cascade to concepts and mappings either both happen or wait for the concurrent write. Every other edit that sends no access stays lock-free. The blank-access test now asserts the FOR NO KEY UPDATE read (fails on d009179).
| kwargs['update_fields'] = [ | ||
| field.name for field in cls._meta.concrete_fields | ||
| if not field.primary_key and field.name != 'public_access'] | ||
| obj.save(**kwargs) |
There was a problem hiding this comment.
This fix-up is skipped when obj.save() raises after writing. Under autocommit the index enqueue runs inside save() through on_commit, and RestEditIndexEnqueueTest shows its error propagates out of save(). By then the UPDATE and the signal (children set to None) have run, but the next line never does, so the row keeps '' while its children are None. In #1048 this was one atomic save.
Suggestion: run the conditional filter(public_access='').update(...) before obj.save(), or in a finally.
There was a problem hiding this comment.
Right. The separate fix-up is gone in 01259ee: the blank case is one locked transaction again, so the row, its None and the children's update commit together or not at all. (Only that rare case runs in a transaction, where a failed index enqueue is logged; all other edits that send no access run under autocommit and report it.)
| # 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 lock else stored_rows).first() | ||
| original_repo = (stored_rows.select_for_update(no_key=True) if keep_private else stored_rows).first() | ||
| if keep_access or (keep_private and not original_repo.public_can_view): |
There was a problem hiding this comment.
Nit: with keep_access this value now comes from an unlocked read and the column isn't saved, so if a concurrent write changes the access in between, the PATCH response (and anything later in the request that reads obj.public_can_view) reports the old access. Maybe obj.refresh_from_db(fields=['public_access']) after the save when keep_access is set.
There was a problem hiding this comment.
Done in 01259ee: after the lock-free save, obj.refresh_from_db(fields=['public_access']), so the response has the access the row has after the save. New test test_a_rest_edit_that_sends_no_access_keeps_an_access_changed_between_its_read_and_its_save changes the access between the edit's read and its save and checks both the row and the response (fails on d009179).
| repo_models = [Collection] if self.document_model == CollectionDocument else ( | ||
| [Source, Collection] if self.is_repo_document_model() else [Source]) | ||
| for facet in named: | ||
| names = {str(name).lower() for name, _, _ in facets[facet]} |
There was a problem hiding this comment.
Nit: owner names are matched ignoring case, but get_scope_owner_criteria treats owners that differ only in case as other owners. So a private org ACME with stale docs keeps its owner facet bucket (with its private hit counts) when a user acme has a viewable repo. The source facet is matched across all owners in the same way. Match exactly where the facet isn't lowercased, or note in the docstring that this is accepted.
There was a problem hiding this comment.
Fixed in 01259ee where the index keeps the names' case: a concept search's source and owner facets (and the mapping from/to facets and targetRepo, now checked too) are matched exactly, so a twin that differs only in case doesn't keep a private name (new test). The mapping, source, collection and repo source/owner facets are lowercased in the index, so names that differ only in case are one bucket there; it stays if any of them is viewable. The docstring says so.
| for facet in named: | ||
| names = {str(name).lower() for name, _, _ in facets[facet]} | ||
| name_field = Lower('mnemonic') if facet == 'source' else Lower( | ||
| Coalesce('organization__mnemonic', 'user__username')) |
There was a problem hiding this comment.
Nit (performance): this adds one or two DB queries per facet to every non-staff search facet request, cached facets included. Each applies get_viewable_versions_criteria (with its Exists) to all HEAD repos and filters on Lower(...)/Lower(Coalesce(...)) across joins, which a plain index can't serve. get_search_visibility_criteria() is also computed a second time. Worth checking the plan on production-size data, or prefiltering to the bucket names.
There was a problem hiding this comment.
Reduced in 01259ee: the facets reuse the search's own search_checks_access when the facets search was built (only a cached facets answer works out the filter again), and the exact-case facets (a concept search's, the most common) use mnemonic IN (...) / organization__mnemonic IN / username IN / uri IN, which an index can serve; the bucket names (at most FACET_SIZE) prefilter every query. The lowercased facets of mapping and repo searches still use lower(), which a plain index can't serve. I can't read production data from here, so an EXPLAIN of one source-facet query there would settle it; if it's slow, an expression index on lower(mnemonic) is the fix.
| from core.collections.models import Collection | ||
| from core.sources.models import Source | ||
| repo_models = [Collection] if self.document_model == CollectionDocument else ( | ||
| [Source, Collection] if self.is_repo_document_model() else [Source]) |
There was a problem hiding this comment.
Nit: Python's str.lower() and Postgres lower() can differ for some non-ASCII characters (depending on the DB ctype), so a viewable name could fail to match and its bucket would drop for non-staff users.
There was a problem hiding this comment.
Mnemonics and usernames are ASCII only (NAMESPACE_REGEX, [a-zA-Z0-9\-\.\_\@]), where Python's and Postgres's lower() agree; and since 01259ee the concept facets don't lowercase at all. A legacy non-ASCII name could only go missing from a facet, never be wrongly kept.
… requester can view none of; a blank-access edit saves under the lock - The mapping facets that name the sources and owners of the concepts mapped from and to, and a concept's targetRepo, are checked too. A name is left out if the repositories it names exist and the requester can view none of them, so a target outside OCL keeps its name. Any version counts, not only HEAD. - A concept search's source and owner facets keep the names' case, so they're matched as they are, by index; the lowercased facets match any case. - The facets reuse the search's own access-filter answer when it ran. - A REST edit that sends no access to a row stored with a blank access saves under the row lock again, in one transaction, so it stores None and passes it on to a source's concepts and mappings without undoing a concurrent change. Other such edits answer with the access the row has after the save. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qW1SrjGg8mwU3zehyF
Codex check of commits 93d5690..d009179 (codex-cli 0.169.0)Verdict: 3 findings, all P2. Prior: F3.2 unresolved (FC.1), F3.3 regressed (FC.2).
Replies (01259ee):
check-1050.json{
"reviewer": "codex-cli 0.169.0",
"perspective": "defects",
"mode": "verify",
"commit": "d009179b",
"verdict": "findings",
"prior": [
{
"id": "F3.2",
"status": "unresolved"
},
{
"id": "F3.3",
"status": "regressed"
}
],
"findings": [
{
"id": "FC.1",
"severity": "P2",
"tag": null,
"file": "core/common/views.py",
"line": 853,
"claim": "The concept owner facet can still expose the exact name of a private owner.",
"scenario": "Two distinct organizations are named `ExampleOrg` and `exampleorg`. A concept under `ExampleOrg` still has a public index document after its source becomes private. An anonymous search drops the hit, but the public source under `exampleorg` keeps the exact `ExampleOrg` bucket because the database check lowercases both names.",
"action": "Match exact-case concept facet labels as stored. Use lowercase comparisons for facets backed by lowercase-normalized index fields, and test the original bucket labels.",
"lines_delta": null,
"confidence": "high"
},
{
"id": "FC.2",
"severity": "P2",
"tag": null,
"file": "core/common/models.py",
"line": 1460,
"claim": "An edit that omits access can overwrite the access a concurrent publish gave the source's concepts and mappings.",
"scenario": "A metadata PATCH reads a source with legacy blank access and prepares to normalize it to `None`. Another request publishes the source and finishes updating its children before the PATCH saves. The PATCH's save signal sets the children back to `None`. Its conditional update then skips the source because it is already `View`, leaving the published source's children hidden by the database access check.",
"action": "Run the legacy-blank child cascade only if the conditional normalization updates the source. Keep the normalization and cascade in the same transaction, and surface any index enqueue error after commit.",
"lines_delta": null,
"confidence": "high"
},
{
"id": "FC.3",
"severity": "P2",
"tag": null,
"file": "core/common/views.py",
"line": 858,
"claim": "An all-versions search can lose the owner facet for a public repository version it still returns.",
"scenario": "An owner changes their only public source's writable `version` from `HEAD` to `v1`. After reindexing, an anonymous source search with `allVersions=true` still returns the public `v1` row. The same search now drops its owner bucket because the facet check requires a viewable HEAD.",
"action": "For all-versions searches, allow viewable non-HEAD rows to supply owner facet names and apply the same version access check used for hits.",
"lines_delta": null,
"confidence": "high"
}
]
} |
Adversarial pass (Claude subagent, read-only, #1048 + #1050 at d009179)It tried to make search return a hit or a facet name the requester can't view, and to make a REST edit undo a concurrent access change, as anonymous, an outsider, a former member, a creator and staff, across scopes, versions, the facet and list caches,
It found no way for a REST edit that sends no access to make a private row viewable, and nothing else beyond the accepted items. |
…ly if it names a repository the requester can view As it did before the target facets were checked: a stale document's source or owner that no row has any more (deleted or renamed) is no facet name. A target facet still keeps a name no repository has, such as a mapping's target outside OCL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qW1SrjGg8mwU3zehyF
Codex check of commits d009179..01259ee (codex-cli 0.169.0)Verdict: 4 findings: 2 P1, 2 P2. Prior: FC.1, FC.2, FC.3 resolved.
Replies (c6a3d34):
check2-1050.json{
"reviewer": "codex-cli 0.169.0",
"perspective": "defects",
"mode": "verify",
"commit": "01259ee2468f7dea7186aaa86ee594fb10762cf1",
"verdict": "findings",
"prior": [
{
"id": "FC.1",
"status": "resolved"
},
{
"id": "FC.2",
"status": "resolved"
},
{
"id": "FC.3",
"status": "resolved"
}
],
"findings": [
{
"id": "FC.1",
"severity": "P1",
"tag": null,
"file": "core/common/views.py",
"line": 879,
"claim": "`targetRepo` only checks stored repository paths, so canonical URLs for private sources remain visible.",
"scenario": "A public concept has a mapping whose stored `to_source_url` is the canonical URL of a linked OCL source. When the target becomes private, the concept index still emits that canonical URL. The `uri__in` lookup finds no row for it, so an outsider still sees the `targetRepo` bucket. The new test calls the helper with `Source.uri`, which misses this path.",
"action": "Apply the access check to canonical URLs that resolve to local sources. Add an endpoint test covering a private canonical target and an unresolved external URL.",
"lines_delta": null,
"confidence": "high"
},
{
"id": "FC.2",
"severity": "P1",
"tag": null,
"file": "core/common/views.py",
"line": 852,
"claim": "Owner-scoped mapping searches skip access checks on the repositories their mappings point to.",
"scenario": "A member searches mappings in their own organization's source. A mapping points to another organization's source that has become private. When the requesting organization has no case twin, the mapping search builds no access filter and this guard skips facet filtering. The member still sees the private target's `toConceptSource` and `toConceptOwner` buckets.",
"action": "Check facets that name mapping endpoints independently of whether the parent search applies an access filter. Cover an owner-scoped search with a target outside the requester's organization.",
"lines_delta": null,
"confidence": "high"
},
{
"id": "FC.3",
"severity": "P2",
"tag": null,
"file": "core/common/views.py",
"line": 867,
"claim": "Stale `source` and `owner` buckets reappear after their repository rows are removed.",
"scenario": "A public concept document remains in Elasticsearch after its source is deleted. If no other repository matches the source or owner name, the database lookup returns neither name as hidden. The public facets still list those names even though the search returns no hit. The preceding commit dropped both buckets.",
"action": "Keep `source` and `owner` buckets only when a viewable repository matches. Preserve unknown names on facets that can represent external targets.",
"lines_delta": null,
"confidence": "high"
},
{
"id": "FC.4",
"severity": "P2",
"tag": null,
"file": "core/common/views.py",
"line": 864,
"claim": "An unrelated private source can hide a valid external `toConceptSource` bucket.",
"scenario": "A public mapping points to an unresolved external URL ending in `ICPC-2`. The mapping document uses that last segment as its target source name. If the only local source named `ICPC-2` is private and unrelated to the URL, the mnemonic lookup suppresses the external bucket that the preceding commit returned.",
"action": "Use the contributing mappings' target identities to check access, preserving a bucket when an external target contributes to it.",
"lines_delta": null,
"confidence": "high"
}
]
} |
snyaggarwal
left a comment
There was a problem hiding this comment.
Approving at c6a3d34. Thanks for working through my earlier comments: the blank-access case is one locked transaction again, the response reads the access back after the save, the concept and target facets match names exactly, and the facet queries are limited to the bucket names. An EXPLAIN of a lowercased source-facet query on production data is still worth doing; if it's slow, an expression index on lower(mnemonic) would fix it, as you said.
Your Codex and adversarial passes (FC2.1 to FC2.4, A1 to A5) are covered, so I have nothing to add there. Inline: three optional nits.
| # a concept search's source and owner facets keep the names' case, as the others' facets do but those | ||
| exact = facet not in ('source', 'owner') or self.is_concept_document() | ||
| key = str if exact else lambda name: str(name).lower() | ||
| shown, hidden = self.get_repo_names_by_access( |
There was a problem hiding this comment.
Nit (optional): source names are matched by mnemonic across every owner, so a private source with stale documents keeps its bucket, with its counts, whenever any other owner has a viewable source of the same name. Copies of CIEL or ICD-10 nearly always have a public twin, so for those the check rarely hides anything. Buckets aren't owner-qualified, so it can't do much better here. A line in the docstring saying so would be enough.
| obj.custom_validation_schema = original_schema | ||
|
|
||
| if keep_access and not lock: | ||
| kwargs['update_fields'] = [ |
There was a problem hiding this comment.
Nit (optional): with public_access left out of update_fields, a row stored with the retired Edit now stays Edit after such an edit. BaseModel.save normalizes it to View only in memory, and refresh_from_db reads Edit back. On master every such edit wrote View. It's harmless, since both count as public, but the legacy value now lingers. Either include the column when the stored value is the retired Edit, or accept it.
| user = self.request.user | ||
| named = [facet for facet in self.repo_name_facets if facets.get(facet)] | ||
| if not named or get(user, 'is_staff') or not ( | ||
| self.search_checks_access if search is not None else self.get_search_visibility_criteria() is not None): |
There was a problem hiding this comment.
Nit (optional): the fresh path uses search_checks_access, which is also True for an org search in the requester's own scope (is_org_document()). The cached path recomputes get_search_visibility_criteria() is not None, which is None there. Org searches have none of these facets, so nothing shows today, but the rule lives in two places. One helper for both would keep them from drifting.
For OpenConceptLab/ocl_online#730 (items 1 and 2, follow-up to #1048). References it without closing it. These are the fixes for the third Codex pass on #1048's last commit (45fba55), which came in after #1048 was approved and merged; that pass and its replies are on #1048.
Search facets name only repositories the requester can view (F3.2)
#1048 loads search hits through the database's access check, so a stale index document (a source made private before it, or its concepts and mappings, were reindexed) is no hit. Facets still came from the index, so they could still name that source and its owner.
Now, where the search filters by access (
get_search_visibility_criteria(), the condition the search itself uses, now factored out),keep_repo_facets_viewable()(core/common/views.py, next to #1044's collection check, on cached facets too) checks every facet that names repositories:sourceandowner(concept, mapping, source, collection and repo searches): a name stays only if it names a repository the requester can view, any version.fromConceptSource,toConceptSource,fromConceptOwner,toConceptOwnerand a concept'stargetRepo: a name is left out if the repositories it names exist and the requester can view none of them, so a target outside OCL keeps its name.One query per facet and model, prefiltered to the bucket names. Where the index keeps the names' case (a concept search's facets, the target facets) they're matched as they are, which an index can serve; the lowercased facets match any case, so names that differ only in case are one bucket there. Counts stay the index's, as
num_founddoes. A hit kept as its creator's can have its names missing, never a wrong one. Staff see the facets as they are.A REST edit that sends no access doesn't write the access column (F3.3)
#1048 kept such an edit from undoing a concurrent access change by reading the row under a lock, in a transaction. Inside a transaction a failed search-index enqueue is only logged, where REST writes under autocommit report it to the request (kept that way in #1009's review).
Now
persist_changes(..., keep_access=True)takes no lock: it saves every column butpublic_access(update_fields), so a concurrent write's access stays whenever it commits, and the edit runs under autocommit as before #1048; it then reads the row's access back for the response. A row stored with a blank access is the exception: it's saved as #1048 saved it, under the lock in one transaction, storingNoneand passing it on to a source's concepts and mappings. FHIR updates keepkeep_private=Trueand its lock.Not changed: source and collection CSV exports (F3.1)
The pass found that a source or collection CSV search whose only hit is dropped falls back to the plain list. That path can't be reached on master: a source or collection CSV export fails before it writes anything, with or without hits. That's tracked separately in OpenConceptLab/ocl_online#759.
Tests
tests_stale_search_access.py(es): rows made private without a reindex are nosource,owneror mapping target facet name for the public or an outsider in the concept, mapping, source, collection and repo searches (members and staff still see them); a public case twin doesn't keep a concept facet's private name; a stale name no row has is nosourceorownername; a target URL facet hides a private repository's URL and keeps one outside OCL.test_make_private.py: a name-only PATCH's save leavespublic_accessout and locks nothing, a PATCH that sends access writes it; an access changed between the edit's read and its save stays, and the response has it; a blank-access row is read for update and stored asNone;RestEditIndexEnqueueTest: a failed index enqueue reaches a name-only PATCH of a source and a collection.TEST_ES=off, parallel) and 719 (es), OK.pylint -j0 core/(4.0.9): clean.Reviewer: @snyaggarwal.
🤖 Generated with Claude Code
https://claude.ai/code/session_01AaZ4qW1SrjGg8mwU3zehyF