openwisp-controller icon indicating copy to clipboard operation
openwisp-controller copied to clipboard

[fix] Device name corrupted by in-place mutation in _get_common_name() during VPN cert provisioning

Open mn-ram opened this issue 8 months ago • 3 comments

Bug Report: In-place Mutation of Device Name in _get_common_name()

Description

The _get_common_name() function currently truncates long device names by mutating device.name directly.

Due to Django’s ForeignKey caching behavior, this modification affects the original in-memory Device instance, leading to silent data corruption during VPN certificate provisioning.


Steps to Reproduce

  1. Create a Device with a name exceeding the certificate Common Name (CN) length limit.
  2. Trigger VPN certificate provisioning for that device.
  3. Inspect the device.name attribute after provisioning.

Actual Behavior

  • device.name is unexpectedly modified (truncated) in memory.
  • This happens because _get_common_name() alters the original object instead of working on a copy.

Expected Behavior

  • device.name should remain unchanged.
  • Only the certificate’s Common Name (CN) should be truncated for compliance.

Related PR

  • #1294

Impact

  • Silent mutation of model instances
  • Potential inconsistencies across the application
  • Hard-to-debug side effects due to Django ORM caching

Suggested Fix

Avoid mutating the original device.name. Instead, operate on a derived value:

cn = device.name[:MAX_CN_LENGTH]

without modifying the device instance itself.


Benefit

Ensures data integrity, avoids unintended side effects, and aligns with Django best practices for immutable model handling in utility functions.

mn-ram avatar Mar 17 '26 23:03 mn-ram

Hi, I would like to work on this issue. Can you please assign it to me?

k-sumayya avatar Mar 19 '26 07:03 k-sumayya

Nice work on the fix @k-sumayya 👍

I had previously explored this issue as well and went with a more extensive approach including additional test coverage. It's good to see a minimal and clean fix here.

Thanks for addressing this!

mn-ram avatar Mar 19 '26 11:03 mn-ram

Thank you for the feedback! I’m glad the fix looks good. I’d love to continue contributing—please let me know if there are other issues I can help with.

k-sumayya avatar Mar 19 '26 15:03 k-sumayya