Assigning an external array to a private field

Assigning an external array directly to a private field

Description

If a public method stores a caller's array directly in a private field, the caller can change internal state later by modifying the original array.

Potential impact

  • Changes may bypass validation of role or policy lists.
  • External reference changes may break the object's invariants.

Remediation

  • Copy incoming arrays with spread syntax, Array.from(), or slice() before storing them.
  • Validate element types and allowed values first.
  • Shallow copies retain references to nested objects. Copy mutable elements to the required depth or store immutable values.

Examples

Before

javascript
class AccessPolicy {
  #roles = [];

  setRoles(roles) {
    this.#roles = roles;
  }
}

After

javascript
class AccessPolicy {
  #roles = [];

  setRoles(roles) {
    this.#roles = [...roles];
  }
}

Explanation:

  • Before: The private field and caller share the same array, so later changes to the original affect internal state.
  • After: Store a copy to separate the array itself from the caller's reference.

References