Skip to content

[fix] Make VpnClient objects immutable after creation - #1431

Open
sameerrandive-dev wants to merge 3 commits into
openwisp:masterfrom
sameerrandive-dev:sameerrandive-dev/issue-1428-vpnclient-block-modifications
Open

[fix] Make VpnClient objects immutable after creation#1431
sameerrandive-dev wants to merge 3 commits into
openwisp:masterfrom
sameerrandive-dev:sameerrandive-dev/issue-1428-vpnclient-block-modifications

Conversation

@sameerrandive-dev

Copy link
Copy Markdown

Summary

Fixes #1428 by making VpnClient objects immutable after creation while allowing the internally managed ip field to be updated.

Changes

  • Prevent updates to persisted VpnClient identity fields by enforcing immutability in both clean() and save().
  • Restrict auto-provisioning to object creation, preventing reprovisioning on subsequent saves.
  • Explicitly allow ip updates required by the asynchronous subnet provisioning workflow.
  • Add regression tests covering:
    • Immutability of persisted VpnClient objects.
    • Allowed ip updates.
    • Create, delete, and recreate workflows.

Validation

  • Added regression tests for all newly introduced behaviors.
  • Verified that all new and existing VPN-related test suites pass, including the subnet_division and swapped-model test suites.
  • Confirmed existing create/delete workflows remain unchanged.
  • No database migrations are required.
image

@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This change enforces post-creation immutability for VpnClient records. AbstractVpnClient allows only ip updates, validates persisted-field changes, and checks direct save() calls. Automatic provisioning runs only during creation. The subnet division handler saves only ip. Tests cover rejected modifications, allowed IP reassignment, deletion, and template-driven recreation. Documentation and translation text describe the new lifecycle.

Sequence Diagram(s)

sequenceDiagram
  participant TemplateOrCaller
  participant AbstractVpnClient
  participant Database
  participant VpnSubnetDivisionRuleType

  TemplateOrCaller->>AbstractVpnClient: full_clean()
  AbstractVpnClient->>Database: load persisted row
  Database-->>AbstractVpnClient: stored field values
  alt immutable field changed
    AbstractVpnClient-->>TemplateOrCaller: ValidationError
  else update is allowed
    TemplateOrCaller->>AbstractVpnClient: save()
    AbstractVpnClient->>Database: persist changes
  end

  VpnSubnetDivisionRuleType->>AbstractVpnClient: set instance.ip
  VpnSubnetDivisionRuleType->>AbstractVpnClient: save(update_fields=["ip"])
  AbstractVpnClient->>Database: write ip only
Loading

Estimated code review effort: 3 (Moderate) | ~25 minutes

Suggested labels: enhancement


Caution

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

  • Ignore

❌ Failed checks (1 error, 1 inconclusive)

Check name Status Explanation Resolution
General Rules ❌ Error The new immutability test changes only five fields; it omits cert, private_key, config, template, and swapped-model inherited fields despite generic enforcement. Add regression cases for every immutable concrete field, including direct save and update_fields paths, plus representative boundary values.
Features ❓ Inconclusive placeholder2 placeholder2
✅ Passed checks (6 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes enforce post-creation immutability through clean() and save(), while preserving the required internal ip update path and recreate workflow.
Out of Scope Changes check ✅ Passed All code, tests, documentation, and localization changes support VPN-client immutability, controlled IP updates, or the recreate workflow.
Bug Fixes ✅ Passed The fix compares persisted concrete fields, blocks changed fields in clean() and save(), and permits only ip updates; regression tests cover the old mutable paths and are deterministic, local DB te...
Changes ✅ Passed The PR updates all four VPN guides, adds regression tests for immutability, saves, IP updates, and recreation, and documents the remove/re-add path; no UI files changed.
Title check ✅ Passed The title uses the required [fix] prefix and clearly describes the VpnClient immutability change.
Description check ✅ Passed The description identifies issue #1428, explains the changes, documents validation, and includes a relevant screenshot.
✨ Finishing Touches 💡 1
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch sameerrandive-dev/issue-1428-vpnclient-block-modifications
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@sameerrandive-dev
sameerrandive-dev force-pushed the sameerrandive-dev/issue-1428-vpnclient-block-modifications branch from 2e72025 to 749d9e6 Compare July 9, 2026 07:37

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 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.

Inline comments:
In `@openwisp_controller/config/base/vpn.py`:
- Around line 911-923: The save() method in VpnClient currently uses only
_state.adding to decide whether this is a create, which can miss cases where a
new instance is constructed with an existing pk. Update the branching in save()
to treat objects with an existing self.pk as updates, and ensure
_check_immutable_fields() is called for those cases even when _state.adding is
still true. Keep the auto-provisioning path in save() for true creates, but gate
it on both _state.adding and absence of an existing primary key.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 1c0ce29a-b984-4dc9-aad2-6e6feb291f2d

📥 Commits

Reviewing files that changed from the base of the PR and between 2e72025 and 749d9e6.

📒 Files selected for processing (3)
  • openwisp_controller/config/base/vpn.py
  • openwisp_controller/config/tests/test_vpn.py
  • openwisp_controller/subnet_division/rule_types/vpn.py
📜 Review details
⏰ Context from checks skipped due to timeout. (11)
  • GitHub Check: Python==3.11 | django~=5.1.0
  • GitHub Check: Python==3.11 | django~=5.2.0
  • GitHub Check: Python==3.12 | django~=5.1.0
  • GitHub Check: Python==3.12 | django~=5.2.0
  • GitHub Check: Python==3.10 | django~=4.2.0
  • GitHub Check: Python==3.12 | django~=4.2.0
  • GitHub Check: Python==3.10 | django~=5.1.0
  • GitHub Check: Python==3.13 | django~=5.1.0
  • GitHub Check: Python==3.13 | django~=5.2.0
  • GitHub Check: Python==3.11 | django~=4.2.0
  • GitHub Check: Python==3.10 | django~=5.2.0
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

**/*.py: Mark user-facing strings for translation with Django i18n helpers in Django code
Avoid unnecessary blank lines inside function and method bodies
Be careful with authentication, authorization, queryset filtering, serializers, admin behavior, cache invalidation, signals, Celery tasks, and websocket updates in Django code
Preserve validation around templates, VPN/PKI material, SSH credentials, device commands, uploaded files, URLs, and subnet/IP data
Write comments and docstrings only when they explain why code is shaped a certain way, placing them before the relevant code block instead of scattering them inside it

Files:

  • openwisp_controller/subnet_division/rule_types/vpn.py
  • openwisp_controller/config/tests/test_vpn.py
  • openwisp_controller/config/base/vpn.py
**/*.{py,html}

📄 CodeRabbit inference engine (Custom checks)

For Django pull requests, ensure all user-facing strings are marked as translatable using the Django i18n framework.

Files:

  • openwisp_controller/subnet_division/rule_types/vpn.py
  • openwisp_controller/config/tests/test_vpn.py
  • openwisp_controller/config/base/vpn.py
🧠 Learnings (8)
📚 Learning: 2026-01-15T15:05:49.557Z
Learnt from: DragnEmperor
Repo: openwisp/openwisp-controller PR: 1175
File: openwisp_controller/config/management/commands/clear_last_ip.py:38-42
Timestamp: 2026-01-15T15:05:49.557Z
Learning: In Django projects, when using select_related() to traverse relations (for example, select_related("organization__config_settings")), the traversed relation must not be deferred. If you also use .only() in the same query, include the relation name or FK field (e.g., "organization" or "organization_id") in the .only() list to avoid the error "Field X cannot be both deferred and traversed using select_related at the same time." Apply this guideline to Django code in openwisp_controller/config/management/commands/clear_last_ip.py and similar modules by ensuring any select_related with an accompanying only() includes the related field names to prevent deferred/traversed conflicts.

Applied to files:

  • openwisp_controller/subnet_division/rule_types/vpn.py
  • openwisp_controller/config/tests/test_vpn.py
  • openwisp_controller/config/base/vpn.py
📚 Learning: 2026-02-17T19:13:10.088Z
Learnt from: nemesifier
Repo: openwisp/openwisp-controller PR: 1175
File: openwisp_controller/config/whois/commands.py:0-0
Timestamp: 2026-02-17T19:13:10.088Z
Learning: In reviews for the openwisp/openwisp-controller repository, do not propose changes based on Ruff warnings. The project does not use Ruff as its linter; ignore Ruff-related suggestions and follow the repository’s established linting and configuration rules. This guidance applies to all Python files under the openwisp_controller directory.

Applied to files:

  • openwisp_controller/subnet_division/rule_types/vpn.py
  • openwisp_controller/config/tests/test_vpn.py
  • openwisp_controller/config/base/vpn.py
📚 Learning: 2026-01-15T15:07:17.354Z
Learnt from: DragnEmperor
Repo: openwisp/openwisp-controller PR: 1175
File: openwisp_controller/geo/estimated_location/tests/tests.py:172-175
Timestamp: 2026-01-15T15:07:17.354Z
Learning: In this repository, flake8 enforces E501 (line too long) via setup.cfg (max-line-length = 88) while ruff ignores E501 via ruff.toml. Therefore, use '# noqa: E501' on lines that intentionally exceed 88 characters to satisfy flake8 without affecting ruff checks. This applies to Python files across the project (any .py) and is relevant for tests as well. Use sparingly and only where breaking lines is not feasible without hurting readability or functionality.

Applied to files:

  • openwisp_controller/subnet_division/rule_types/vpn.py
  • openwisp_controller/config/tests/test_vpn.py
  • openwisp_controller/config/base/vpn.py
📚 Learning: 2026-06-07T12:07:08.468Z
Learnt from: stktyagi
Repo: openwisp/openwisp-controller PR: 1378
File: openwisp_controller/config/tests/test_admin.py:2335-2335
Timestamp: 2026-06-07T12:07:08.468Z
Learning: In this project’s Python test suite (files under openwisp_controller/**/tests/), don’t require or request prose/inline comments that document the breakdown of query-count changes (e.g., assertions around template/DB query counts in helpers like _verify_template_queries). Treat query-count assertions as volatile implementation details that change frequently; review should focus on whether the test asserts the expected behavior, not on explaining the specific query-count deltas in comments.

Applied to files:

  • openwisp_controller/config/tests/test_vpn.py
📚 Learning: 2026-06-07T12:07:24.608Z
Learnt from: stktyagi
Repo: openwisp/openwisp-controller PR: 1378
File: openwisp_controller/pki/tests/test_api.py:155-155
Timestamp: 2026-06-07T12:07:24.608Z
Learning: When reviewing Python test files in this repository, avoid recommending inline comments that explain or justify `assertNumQueries` (Django query count) expectations. Query counts can change frequently as implementations evolve, and inline explanations add maintenance burden; the expected count should be understandable without added comment blocks.

Applied to files:

  • openwisp_controller/config/tests/test_vpn.py
📚 Learning: 2026-06-25T12:20:18.414Z
Learnt from: dee077
Repo: openwisp/openwisp-controller PR: 1395
File: openwisp_controller/connection/base/models.py:571-572
Timestamp: 2026-06-25T12:20:18.414Z
Learning: When writing or reviewing tests that override pagination behavior via OpenWispPagination.paginate_queryset(), patch `view.pagination_page_size` (not `page_size`). The method uses `getattr(view, "pagination_page_size", self.page_size)`, so tests must set the attribute on the view to affect pagination. If the view class does not define `pagination_page_size`, using `unittest.mock.patch(..., create=True)` is intentional and correct because the attribute may not exist until patched.

Applied to files:

  • openwisp_controller/config/tests/test_vpn.py
📚 Learning: 2026-06-07T12:07:25.164Z
Learnt from: stktyagi
Repo: openwisp/openwisp-controller PR: 1378
File: openwisp_controller/config/tests/test_config.py:864-865
Timestamp: 2026-06-07T12:07:25.164Z
Learning: When reviewing this repo’s Python test suite, treat changes to the *expected* query count in `assertNumQueries(...)` calls as routine test maintenance. If a PR updates the numeric argument (e.g., in `test_config.py`, `test_api.py`, `test_admin.py`, `test_pki.py`) and the test remains consistent with the feature changes, reviewers should not flag the increased number as a performance regression that requires investigation solely because the count went up; instead, focus on whether the update is intentional and the surrounding test/code changes justify the revised expectation.

Applied to files:

  • openwisp_controller/config/tests/test_vpn.py
📚 Learning: 2026-06-25T12:20:45.387Z
Learnt from: dee077
Repo: openwisp/openwisp-controller PR: 1395
File: openwisp_controller/connection/tests/test_api.py:916-932
Timestamp: 2026-06-25T12:20:45.387Z
Learning: When reviewing API pagination behavior in openwisp-controller, assume `OpenWispPagination.paginate_queryset()` allows a per-view page-size override via `getattr(view, "pagination_page_size", self.page_size)` (so `view.pagination_page_size`, if present, should affect pagination). In Python tests, it is valid to patch `pagination_page_size` on a view class even if the attribute isn’t declared on the class by default, by using `unittest.mock.patch.object(..., "pagination_page_size", ..., create=True)` so the override is available for the pagination logic during the test.

Applied to files:

  • openwisp_controller/config/tests/test_vpn.py
🔇 Additional comments (2)
openwisp_controller/subnet_division/rule_types/vpn.py (1)

55-56: LGTM!

openwisp_controller/config/tests/test_vpn.py (1)

275-302: LGTM!

Also applies to: 512-584

Comment thread openwisp_controller/config/base/vpn.py Outdated
@sameerrandive-dev
sameerrandive-dev force-pushed the sameerrandive-dev/issue-1428-vpnclient-block-modifications branch from 749d9e6 to d07983c Compare July 10, 2026 08:40
@kilo-code-bot

kilo-code-bot Bot commented Jul 10, 2026

Copy link
Copy Markdown

Code Review Summary

Status: No Issues Found | Recommendation: Merge

The coderabbitai comment about _state.adding being unreliable for instances constructed with an existing pk is resolved by patch 3/3, which now uses self.pk is None to distinguish creates from updates. No new critical issues found in the incremental diff.

Files Reviewed (2 files)
  • openwisp_controller/config/base/vpn.py
  • openwisp_controller/config/tests/test_vpn.py
Previous Review Summaries (3 snapshots, latest commit fd4f09e)

Current summary above is authoritative. Previous snapshots are kept for context only.

Previous review (commit fd4f09e)

Status: No Issues Found | Recommendation: Merge

No new issues found in the incremental diff. Documentation and translation changes added since the previous review are clean.

Files Reviewed (6 files)
  • docs/partials/vpn-client-immutability.rst
  • docs/user/openvpn.rst
  • docs/user/vxlan-wireguard.rst
  • docs/user/wireguard.rst
  • docs/user/zerotier.rst
  • openwisp_controller/locale/en/LC_MESSAGES/django.po

Previous review (commit 8983946)

Status: No Issues Found | Recommendation: Merge

No new code changes since the previous review — current HEAD (89839460) is tree-identical to the previously reviewed commit (d07983c), so there is nothing new to re-review.

The immutability enforcement remains clean and well-targeted: clean() and save() both guard against post-creation changes, _updatable_fields = ("ip",) preserves the asynchronous subnet_division IP-update path, and the user-facing error string is wrapped with _() for translation.

Policy checks from the custom instructions are satisfied:

  • Bug fix (Fixes [enancement] VpnClient objects should block modifications  #1428): regression tests are included (test_vpn_client_immutable_after_creation, test_vpn_client_direct_save_rejected, test_vpn_client_ip_update_allowed, test_vpn_client_delete_recreate_flow).
  • Existing behavior change: the affected auto_cert test case in test_vpn.py was updated accordingly.
  • Title lacks the repository's bracketed type prefix (e.g. [fix]), but the PR is not from dependabot and is not a [release]/[backport], so it is in scope; this is a minor convention note, not blocking under lenient review.

No critical bugs or security vulnerabilities were found in the changed lines. An existing reviewer comment already tracks the _state.adding edge case on vpn.py:923; it is not re-flagged here to avoid duplication.

Files Reviewed (3 files)
  • openwisp_controller/config/base/vpn.py
  • openwisp_controller/config/tests/test_vpn.py
  • openwisp_controller/subnet_division/rule_types/vpn.py

Previous review (commit d07983c)

Status: No Issues Found | Recommendation: Merge

Nice work — the immutability enforcement is clean and well-targeted. clean() and save() both guard against post-creation changes, _updatable_fields = ("ip",) correctly preserves the asynchronous subnet_division IP-update path, and the user-facing error string is wrapped with _() for translation.

The policy checks from the custom instructions are satisfied:

  • Bug fix (Fixes [enancement] VpnClient objects should block modifications  #1428): regression tests are included (test_vpn_client_immutable_after_creation, test_vpn_client_direct_save_rejected, test_vpn_client_ip_update_allowed, test_vpn_client_delete_recreate_flow).
  • Existing behavior change: the affected auto_cert test case in test_vpn.py was updated accordingly.
  • Title lacks the repository's bracketed type prefix (e.g. [fix]), but the PR is not from dependabot and is not a [release]/[backport], so it is in scope; this is a minor convention note, not a blocking issue under lenient review.

No critical bugs or security vulnerabilities were found in the changed lines. An existing reviewer comment already tracks the _state.adding edge case on vpn.py:923; it is not re-flagged here to avoid duplication.

Files Reviewed (3 files)
  • openwisp_controller/config/base/vpn.py
  • openwisp_controller/config/tests/test_vpn.py
  • openwisp_controller/subnet_division/rule_types/vpn.py

Reviewed by ling-3.0-flash:free · Input: 180.5K · Output: 22.5K · Cached: 301.7K



Make VpnClient objects immutable after creation while allowing managed IP updates.

Fixes openwisp#1428
@sameerrandive-dev
sameerrandive-dev force-pushed the sameerrandive-dev/issue-1428-vpnclient-block-modifications branch from d07983c to 8983946 Compare July 10, 2026 16:24
@coveralls

Copy link
Copy Markdown

Coverage Status

coverage: 98.537% (-0.01%) from 98.547% — sameerrandive-dev:sameerrandive-dev/issue-1428-vpnclient-block-modifications into openwisp:master

@CodingWithSaksham CodingWithSaksham left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks for the contribution! Overall, you did a good job with this PR. Before it can be merged, I'd like to request a couple of changes:

  • Please add documentation mentioning that VPNClient instances are now immutable after creation.
  • Since you've introduced a new translatable string, please update the corresponding .po file as well.
  • Please update the PR description and PR title to follow the provided pull request template. PRs that don't use the template may be flagged by the maintainers as AI-generated or low-quality ("AI Slop"). You can find the relevant guidance here: https://openwisp.io/docs/dev/general/code-of-conduct.html.
  • Please address the comments given by coderabbit.

Once those changes are in place, I'll be happy to take another look.

@openwisp-companion

Copy link
Copy Markdown

Hi @sameerrandive-dev 👋,

This is a friendly reminder that this pull request has had no activity for 7 days since changes were requested.

We'd love to see this contribution merged! Please take a moment to:

  • Address the review feedback
  • Push your changes
  • Let us know if you have any questions or need clarification

If you're busy or need more time, no worries! Just leave a comment to let us know you're still working on it.

Note: within 7 more days, the linked issue will be unassigned to allow other contributors to work on it.

Thank you for your contribution! 🙏

@openwisp-companion

Copy link
Copy Markdown

Hi @sameerrandive-dev 👋,

This pull request has been marked as stale due to 14 days of inactivity after changes were requested.

As a result, any linked issues are being unassigned from you so other contributors can pick them up.

However, you can still continue working on this PR! If you push new commits or respond to the review feedback:

  • The issue will be reassigned to you
  • Your contribution is still very welcome

If you need more time or have questions about the requested changes, please let us know. We're happy to help! 🤝

- added docs/partials/vpn-client-immutability.rst and included it in the
  OpenVPN, WireGuard, VXLAN over WireGuard and ZeroTier tutorials
- bootstrapped locale catalog (locale/en/LC_MESSAGES/django.po) with the
  new translatable string introduced by the immutability validation
…h an existing pk openwisp#1428

_state.adding is True on any freshly constructed instance, so VpnClient(pk=<existing pk>, ...).save() bypassed the immutability check and updated the persisted row. The persisted row's existence is now the authoritative signal for create vs update.
@sameerrandive-dev sameerrandive-dev changed the title Fix #1428: Make VpnClient objects immutable after creation [fix] Make VpnClient objects immutable after creation Aug 3, 2026
@openwisp-companion openwisp-companion Bot removed the stale label Aug 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[enancement] VpnClient objects should block modifications

4 participants