Codepath

Least privilege

Grant access to systems, data, and physical spaces judiciously. Do not automatically grant access to everyone. Do not automatically grant a single user access to everything.

The principle of least privilege is:

"Every program and every privileged user of the system should operate using the least amount of privilege necessary to complete the job." — Jerome Saltzer

The principle of least privilege means giving a user account only those privileges which are essential to that user's work. Nothing more.

The impact of vulnerabilities is limited and the damages are localized.


User privileges are not our only concern. Code has privileges too. Code should be limited in what it exposes and in what it accesses.

In the following example code, $name and display_name() are marked public. That declaration makes them accessible to code outside the Product class. $inventory and is_sold_out() are marked private. That declaration makes the available only inside the Product class, other code and objects do not have access to them and cannot read or modify them.

<?php
  class Product {
    public $name;
    private $inventory;
  
    public function display_name() {
      $output = $this->name;
      if(is_sold_out()) { $output .= " (sold out)"; }
      return $output;
    }
  
    private function is_sold_out() {
      return $this->inventory == 0;
    }
  }
?>
Fork me on GitHub