[FIX] Mark server-managed organization field non-editable (DRF 3.15 compat)#2092
[FIX] Mark server-managed organization field non-editable (DRF 3.15 compat)#2092
Conversation
…ompat) `organization` is set server-side and never accepted as client input, but `fields="__all__"` exposed it as a writable serializer field. DRF 3.15 derives multi-field UniqueTogetherValidators from model UniqueConstraints and requires every field of the constraint in the request body, so every org-scoped create started failing with `organization: This field is required`. Mark `organization` editable=False on DefaultOrganizationMixin and on the five models that attach it directly (Configuration, OrganizationGroup, ResourceGroupShare, PlatformKey, NotificationBuffer). DRF then builds it read-only, which drops it from the auto-generated uniqueness validators for every org-scoped constraint. Migrations are state-only (editable is not a database attribute, so no DDL is emitted). Keeps DRF on 3.15.2, retaining the CVE-2024-21520 XSS patch. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DoRxNHky8RoutBCFrSzZQ7
Summary by CodeRabbit
Walkthrough
ChangesServer-managed organization FK enforcement
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
| Filename | Overview |
|---|---|
| backend/utils/models/organization_mixin.py | Core of the fix: adds editable=False to the shared organization FK and removes the now-redundant default=None (covered by null=True). Clean change. |
| backend/api_v2/admin.py | Adds organization to readonly_fields to prevent FieldError when the admin form build encounters an editable=False field in an explicit fieldset. Correct handling. |
| backend/adapter_processor_v2/tests/test_org_editable.py | New regression test verifying the DRF 3.15 fix; ORG_SCOPED_MODELS is incomplete — 8 models that received migrations are missing from the parametrized guard. |
| backend/configuration/models.py | Adds editable=False to the directly-declared organization FK on Configuration (one of the five non-mixin models). Correct. |
| backend/tenant_account_v2/models.py | Adds editable=False to OrganizationGroup and ResourceGroupShare FK declarations (non-mixin models). OrganizationMember is covered via the mixin. |
| backend/notification_v2/models.py | Adds editable=False to NotificationBuffer.organization — the fifth non-mixin model. Correct. |
| backend/account_v2/migrations/0005_alter_platformkey_organization.py | State-only AlterField migration (editable is not a DB attribute, no DDL emitted). Migration chain correctly depends on account_v2.0004. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Client sends create request\nno organization in payload] --> B[DRF ModelSerializer.is_valid]
B --> C{organization\neditable?}
C -- "Before fix\n(editable=True)" --> D[DRF builds UniqueTogetherValidator\nrequiring organization field]
D --> E["400: organization\nThis field is required"]
C -- "After fix\n(editable=False)" --> F[DRF marks organization read_only\nDrops UniqueTogetherValidator]
F --> G[Validation passes]
G --> H[serializer.save calls model.save]
H --> I[DefaultOrganizationMixin.save\nsets organization from UserContext]
I --> J[Record persisted with\ncorrect tenant scoping]
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
flowchart TD
A[Client sends create request\nno organization in payload] --> B[DRF ModelSerializer.is_valid]
B --> C{organization\neditable?}
C -- "Before fix\n(editable=True)" --> D[DRF builds UniqueTogetherValidator\nrequiring organization field]
D --> E["400: organization\nThis field is required"]
C -- "After fix\n(editable=False)" --> F[DRF marks organization read_only\nDrops UniqueTogetherValidator]
F --> G[Validation passes]
G --> H[serializer.save calls model.save]
H --> I[DefaultOrganizationMixin.save\nsets organization from UserContext]
I --> J[Record persisted with\ncorrect tenant scoping]
Prompt To Fix All With AI
Fix the following 1 code review issue. Work through them one at a time, proposing concise fixes.
---
### Issue 1 of 1
backend/adapter_processor_v2/tests/test_org_editable.py:33-46
**Regression test doesn't cover all migrated models**
Eight models received `AlterField` migrations in this PR but are absent from `ORG_SCOPED_MODELS`: `dashboard_metrics.EventMetricsDaily/Hourly/Monthly`, `platform_api.PlatformApiKey`, `prompt_studio_core_v2.CustomTool`, `prompt_studio_registry_v2.PromptStudioRegistry`, `tenant_account_v2.OrganizationMember`, and `usage_v2.Usage`. Since they all inherit from `DefaultOrganizationMixin` the invariant holds today, but if a future developer overrides `organization` on one of these models without `editable=False`, the regression guard won't catch it. Adding the missing entries to the parametrize list would close that gap.
Reviews (2): Last reviewed commit: "Merge branch 'main' into fix/org-editabl..." | Re-trigger Greptile
jaseemjaskp
left a comment
There was a problem hiding this comment.
Automated PR review (PR Review Toolkit). Posting the one critical/high-confidence regression below; lower-severity notes are shared with the author separately for confirmation before posting.
jaseemjaskp
left a comment
There was a problem hiding this comment.
Follow-up: posting the medium/low findings from the PR Review Toolkit pass (the test silent-pass on line 51 is omitted — already covered by greptile's existing comment).
…uard - OrganizationRateLimitAdmin: add organization to readonly_fields. It is now editable=False, and listing a non-editable field in fieldsets raises FieldError at admin form build (runtime 500, not caught by manage.py check). - Expand regression test to assert the organization field stays editable=False across every org-scoped model (the root-cause invariant), plus the existing adapter serializer checks for the concrete DRF 3.15 symptom. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DoRxNHky8RoutBCFrSzZQ7
There was a problem hiding this comment.
🧹 Nitpick comments (1)
backend/api_v2/admin.py (1)
18-18: ⚡ Quick winUse tuple instead of list for
readonly_fieldsto follow Django convention.Django admin conventionally uses immutable tuples for
readonly_fields,list_display, and other field sequences. The current list triggers RUF012 (mutable default value for class attribute).♻️ Proposed fix
- readonly_fields = ["organization", "created_at", "modified_at"] + readonly_fields = ("organization", "created_at", "modified_at")🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@backend/api_v2/admin.py` at line 18, The readonly_fields attribute is defined as a list but Django convention requires using an immutable tuple for field sequences like readonly_fields, list_display, and similar admin attributes. Convert the list syntax (using square brackets) to tuple syntax (using parentheses) for the readonly_fields assignment that contains "organization", "created_at", and "modified_at" to follow Django conventions and resolve the RUF012 lint warning about mutable default values.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@backend/api_v2/admin.py`:
- Line 18: The readonly_fields attribute is defined as a list but Django
convention requires using an immutable tuple for field sequences like
readonly_fields, list_display, and similar admin attributes. Convert the list
syntax (using square brackets) to tuple syntax (using parentheses) for the
readonly_fields assignment that contains "organization", "created_at", and
"modified_at" to follow Django conventions and resolve the RUF012 lint warning
about mutable default values.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: ac3d33fe-2262-47f2-be47-81e279d567c8
📒 Files selected for processing (2)
backend/adapter_processor_v2/tests/test_org_editable.pybackend/api_v2/admin.py
🚧 Files skipped from review as they are similar to previous changes (1)
- backend/adapter_processor_v2/tests/test_org_editable.py
Unstract test resultsPer-group results
Critical paths
|
|
…herValidator errors (#2098) [FIX] Revert djangorestframework 3.15.2 -> 3.14.0 to unblock staging The DRF 3.15.2 bump (#2087) regressed rc.343. DRF 3.15 auto-derives multi-field UniqueTogetherValidators from model UniqueConstraints, which 3.14 only did for legacy unique_together. Two breakages followed for every ModelSerializer(fields="__all__") over a model using Meta.constraints: 1. Server-set constraint fields (e.g. organization) -> "<field>: required" on create. Partially patched by #2092 for the 5 org-attached models. 2. Client-supplied constraint fields (TableSettings, ProfileManager, agentic table settings, lookups) -> "...must make a unique set" raised at is_valid(), short-circuiting the views' intended `except IntegrityError: raise DuplicateData(<friendly>)` path. This both replaced the friendly message and moved the error from a top-level `detail` string into nested `non_field_errors`, which the frontend does not surface -> silent failures (e.g. duplicate LLM profile name, table settings no longer editable after first save). Pin back to 3.14.0 to restore the known-good behaviour across the whole unique-constraint class at once. The CVE-2024-21520 XSS patch carried by 3.15.2 is intentionally deprioritized; the 3.15 upgrade will be reattempted later with a serializer-level fix (drop auto-derived uniqueness validators). Reverts only the DRF entry from #2087; other batched bumps untouched. The org `editable=False` changes (#2092) remain correct no-ops under 3.14 (org is set server-side in save() from UserContext), so no rollback is needed there. Claude-Session: https://claude.ai/code/session_01G8hAHc4HUo42zY1g9LAjKu Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Problem
On DRF 3.15.2, every org-scoped create started failing with
organization: This field is required(e.g. Add LLM adapter). Root cause: DRF 3.15 auto-derives a multi-fieldUniqueTogetherValidatorfrom a model'sUniqueConstraints, and that validator requires every field of the constraint in the request body.organizationis set server-side (never sent by clients) butfields="__all__"exposed it as a writable field, so it landed in the validator's required set → 400.This is a latent modeling issue DRF 3.15 surfaced: a server-managed column was client-writable (also a cross-tenant injection risk). Downgrading DRF was rejected — 3.14.0 carries CVE-2024-21520 (XSS).
Fix
Mark
organizationeditable=False:DefaultOrganizationMixin(covers adapter, connector, workflow, pipeline, api, prompt-studio, tags, platform-api, usage, dashboard-metrics, tenantOrganizationMember, and cloudlookups/manual_review_v2).organizationdirectly rather than via the mixin:Configuration,OrganizationGroup,ResourceGroupShare,account_v2.PlatformKey,notification_v2.NotificationBuffer.DRF then builds
organizationread-only, which removes it fromfield_sourcesand drops the auto-generated validator for every org-scoped constraint (every such constraint includesorganization, so one field change covers all). It also closes the latent injection —organizationis no longer client-writable.Verified on DRF 3.15.2 against the real serializers: before →
organizationwritable, validator present,is_valid()fails with "required"; after → read-only, zero org validators, create payload withoutorganizationvalidates. A sweep of all 87ModelSerializers confirms no org-scoped validator remains.Migrations
15
AlterField(editable=False)migrations, generated viamakemigrations(not hand-written). All state-only —editableis not a database attribute, so no DDL is emitted.Notes
created_by/modified_byneed no change: the only constraint that includescreated_by(cloudAgenticProject) also includesorganization, so it's already covered; andcreated_at/modified_atareauto_now*(already non-editable).lookups/manual_review_v2, which inherit the mixin): Zipstack/unstract-cloud#1574. Merge/deploy this OSS PR first.adapter_processor_v2/tests/test_org_editable.py).🤖 Generated with Claude Code