PhabricatorPolicyFilter.php 31 KB
Newer Older
1 2
<?php

Joshua Spence's avatar
Joshua Spence committed
3
final class PhabricatorPolicyFilter extends Phobject {
4 5 6

  private $viewer;
  private $objects;
7
  private $capabilities;
8
  private $raisePolicyExceptions;
9
  private $userProjects;
10
  private $customPolicies = array();
11
  private $objectPolicies = array();
12
  private $forcedPolicy;
13

14 15 16 17 18 19 20
  public static function mustRetainCapability(
    PhabricatorUser $user,
    PhabricatorPolicyInterface $object,
    $capability) {

    if (!self::hasCapability($user, $object, $capability)) {
      throw new Exception(
Joshua Spence's avatar
Joshua Spence committed
21 22 23 24
        pht(
          "You can not make that edit, because it would remove your ability ".
          "to '%s' the object.",
          $capability));
25 26 27 28 29 30 31
    }
  }

  public static function requireCapability(
    PhabricatorUser $user,
    PhabricatorPolicyInterface $object,
    $capability) {
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    $filter = id(new PhabricatorPolicyFilter())
      ->setViewer($user)
      ->requireCapabilities(array($capability))
      ->raisePolicyExceptions(true)
      ->apply(array($object));
  }

  /**
   * Perform a capability check, acting as though an object had a specific
   * policy. This is primarily used to check if a policy is valid (for example,
   * to prevent users from editing away their ability to edit an object).
   *
   * Specifically, a check like this:
   *
   *   PhabricatorPolicyFilter::requireCapabilityWithForcedPolicy(
   *     $viewer,
   *     $object,
   *     PhabricatorPolicyCapability::CAN_EDIT,
   *     $potential_new_policy);
   *
   * ...will throw a @{class:PhabricatorPolicyException} if the new policy would
   * remove the user's ability to edit the object.
   *
   * @param PhabricatorUser   The viewer to perform a policy check for.
   * @param PhabricatorPolicyInterface The object to perform a policy check on.
   * @param string            Capability to test.
   * @param string            Perform the test as though the object has this
   *                          policy instead of the policy it actually has.
   * @return void
   */
  public static function requireCapabilityWithForcedPolicy(
    PhabricatorUser $viewer,
    PhabricatorPolicyInterface $object,
    $capability,
    $forced_policy) {

    id(new PhabricatorPolicyFilter())
      ->setViewer($viewer)
      ->requireCapabilities(array($capability))
      ->raisePolicyExceptions(true)
      ->forcePolicy($forced_policy)
      ->apply(array($object));
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
  }

  public static function hasCapability(
    PhabricatorUser $user,
    PhabricatorPolicyInterface $object,
    $capability) {

    $filter = new PhabricatorPolicyFilter();
    $filter->setViewer($user);
    $filter->requireCapabilities(array($capability));
    $result = $filter->apply(array($object));

    return (count($result) == 1);
  }

89 90 91 92
  public static function canInteract(
    PhabricatorUser $user,
    PhabricatorPolicyInterface $object) {

93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
    $capabilities = self::getRequiredInteractCapabilities($object);

    foreach ($capabilities as $capability) {
      if (!self::hasCapability($user, $object, $capability)) {
        return false;
      }
    }

    return true;
  }

  public static function requireCanInteract(
    PhabricatorUser $user,
    PhabricatorPolicyInterface $object) {

    $capabilities = self::getRequiredInteractCapabilities($object);
    foreach ($capabilities as $capability) {
      self::requireCapability($user, $object, $capability);
    }
  }

  private static function getRequiredInteractCapabilities(
    PhabricatorPolicyInterface $object) {
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    $capabilities = $object->getCapabilities();
    $capabilities = array_fuse($capabilities);

    $can_interact = PhabricatorPolicyCapability::CAN_INTERACT;
    $can_view = PhabricatorPolicyCapability::CAN_VIEW;

    $require = array();

    // If the object doesn't support a separate "Interact" capability, we
    // only use the "View" capability: for most objects, you can interact
    // with them if you can see them.
    $require[] = $can_view;

    if (isset($capabilities[$can_interact])) {
      $require[] = $can_interact;
    }

133
    return $require;
134 135
  }

136 137 138 139 140
  public function setViewer(PhabricatorUser $user) {
    $this->viewer = $user;
    return $this;
  }

141 142
  public function requireCapabilities(array $capabilities) {
    $this->capabilities = $capabilities;
143 144 145 146 147 148 149 150
    return $this;
  }

  public function raisePolicyExceptions($raise) {
    $this->raisePolicyExceptions = $raise;
    return $this;
  }

151 152 153 154 155
  public function forcePolicy($forced_policy) {
    $this->forcedPolicy = $forced_policy;
    return $this;
  }

156 157 158
  public function apply(array $objects) {
    assert_instances_of($objects, 'PhabricatorPolicyInterface');

159 160
    $viewer       = $this->viewer;
    $capabilities = $this->capabilities;
161

162
    if (!$viewer || !$capabilities) {
Joshua Spence's avatar
Joshua Spence committed
163
      throw new PhutilInvalidStateException('setViewer', 'requireCapabilities');
164 165
    }

166 167 168 169 170 171 172
    // If the viewer is omnipotent, short circuit all the checks and just
    // return the input unmodified. This is an optimization; we know the
    // result already.
    if ($viewer->isOmnipotent()) {
      return $objects;
    }

173 174 175 176 177 178
    // Before doing any actual object checks, make sure the viewer can see
    // the applications that these objects belong to. This is normally enforced
    // in the Query layer before we reach object filtering, but execution
    // sometimes reaches policy filtering without running application checks.
    $objects = $this->applyApplicationChecks($objects);

179
    $filtered = array();
180 181 182 183 184
    $viewer_phid = $viewer->getPHID();

    if (empty($this->userProjects[$viewer_phid])) {
      $this->userProjects[$viewer_phid] = array();
    }
185

186
    $need_projects = array();
187
    $need_policies = array();
188
    $need_objpolicies = array();
189 190
    foreach ($objects as $key => $object) {
      $object_capabilities = $object->getCapabilities();
191 192 193
      foreach ($capabilities as $capability) {
        if (!in_array($capability, $object_capabilities)) {
          throw new Exception(
Joshua Spence's avatar
Joshua Spence committed
194
            pht(
195 196 197 198
              'Testing for capability "%s" on an object ("%s") which does '.
              'not support that capability.',
              $capability,
              get_class($object)));
199
        }
200

201
        $policy = $this->getObjectPolicy($object, $capability);
202 203 204 205 206 207

        if (PhabricatorPolicyQuery::isObjectPolicy($policy)) {
          $need_objpolicies[$policy][] = $object;
          continue;
        }

208
        $type = phid_get_type($policy);
Joshua Spence's avatar
Joshua Spence committed
209
        if ($type == PhabricatorProjectProjectPHIDType::TYPECONST) {
210
          $need_projects[$policy] = $policy;
211
          continue;
212
        }
213 214

        if ($type == PhabricatorPolicyPHIDTypePolicy::TYPECONST) {
215
          $need_policies[$policy][] = $object;
216
          continue;
217
        }
218 219 220
      }
    }

221 222 223 224
    if ($need_objpolicies) {
      $this->loadObjectPolicies($need_objpolicies);
    }

225
    if ($need_policies) {
226
      $this->loadCustomPolicies($need_policies);
227 228
    }

229 230 231
    // If we need projects, check if any of the projects we need are also the
    // objects we're filtering. Because of how project rules work, this is a
    // common case.
232
    if ($need_projects) {
233 234 235 236 237 238 239 240
      foreach ($objects as $object) {
        if ($object instanceof PhabricatorProject) {
          $project_phid = $object->getPHID();
          if (isset($need_projects[$project_phid])) {
            $is_member = $object->isUserMember($viewer_phid);
            $this->userProjects[$viewer_phid][$project_phid] = $is_member;
            unset($need_projects[$project_phid]);
          }
241 242
        }
      }
243
    }
244

245 246
    if ($need_projects) {
      $need_projects = array_unique($need_projects);
247

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
      // NOTE: We're using the omnipotent user here to avoid a recursive
      // descent into madness. We don't actually need to know if the user can
      // see these projects or not, since: the check is "user is member of
      // project", not "user can see project"; and membership implies
      // visibility anyway. Without this, we may load other projects and
      // re-enter the policy filter and generally create a huge mess.

      $projects = id(new PhabricatorProjectQuery())
        ->setViewer(PhabricatorUser::getOmnipotentUser())
        ->withMemberPHIDs(array($viewer->getPHID()))
        ->withPHIDs($need_projects)
        ->execute();

      foreach ($projects as $project) {
        $this->userProjects[$viewer_phid][$project->getPHID()] = true;
263 264 265 266 267
      }
    }

    foreach ($objects as $key => $object) {
      foreach ($capabilities as $capability) {
268 269 270 271
        if (!$this->checkCapability($object, $capability)) {
          // If we're missing any capability, move on to the next object.
          continue 2;
        }
272
      }
273 274 275

      // If we make it here, we have all of the required capabilities.
      $filtered[$key] = $object;
276 277
    }

Dmitri Iouchtchenko's avatar
Dmitri Iouchtchenko committed
278
    // If we survived the primary checks, apply extended checks to objects
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
    // with extended policies.
    $results = array();
    $extended = array();
    foreach ($filtered as $key => $object) {
      if ($object instanceof PhabricatorExtendedPolicyInterface) {
        $extended[$key] = $object;
      } else {
        $results[$key] = $object;
      }
    }

    if ($extended) {
      $results += $this->applyExtendedPolicyChecks($extended);
      // Put results back in the original order.
      $results = array_select_keys($results, array_keys($filtered));
    }

    return $results;
  }

  private function applyExtendedPolicyChecks(array $extended_objects) {
    $viewer = $this->viewer;
    $filter_capabilities = $this->capabilities;

    // Iterate over the objects we need to filter and pull all the nonempty
    // policies into a flat, structured list.
    $all_structs = array();
    foreach ($extended_objects as $key => $extended_object) {
      foreach ($filter_capabilities as $extended_capability) {
        $extended_policies = $extended_object->getExtendedPolicy(
          $extended_capability,
          $viewer);
        if (!$extended_policies) {
          continue;
        }

        foreach ($extended_policies as $extended_policy) {
          list($object, $capabilities) = $extended_policy;

          // Build a description of the capabilities we need to check. This
          // will be something like `"view"`, or `"edit view"`, or possibly
          // a longer string with custom capabilities. Later, group the objects
          // up into groups which need the same capabilities tested.
          $capabilities = (array)$capabilities;
          $capabilities = array_fuse($capabilities);
          ksort($capabilities);
          $group = implode(' ', $capabilities);

          $struct = array(
            'key' => $key,
            'for' => $extended_capability,
            'object' => $object,
            'capabilities' => $capabilities,
            'group' => $group,
          );

          $all_structs[] = $struct;
        }
      }
    }

    // Extract any bare PHIDs from the structs; we need to load these objects.
    // These are objects which are required in order to perform an extended
    // policy check but which the original viewer did not have permission to
    // see (they presumably had other permissions which let them load the
    // object in the first place).
    $all_phids = array();
    foreach ($all_structs as $idx => $struct) {
      $object = $struct['object'];
      if (is_string($object)) {
        $all_phids[$object] = $object;
      }
    }

    // If we have some bare PHIDs, we need to load the corresponding objects.
    if ($all_phids) {
      // We can pull these with the omnipotent user because we're immediately
      // filtering them.
      $ref_objects = id(new PhabricatorObjectQuery())
        ->setViewer(PhabricatorUser::getOmnipotentUser())
        ->withPHIDs($all_phids)
        ->execute();
      $ref_objects = mpull($ref_objects, null, 'getPHID');
    } else {
      $ref_objects = array();
    }

    // Group the list of checks by the capabilities we need to check.
    $groups = igroup($all_structs, 'group');
    foreach ($groups as $structs) {
      $head = head($structs);

      // All of the items in each group are checking for the same capabilities.
      $capabilities = $head['capabilities'];

      $key_map = array();
      $objects_in = array();
      foreach ($structs as $struct) {
        $extended_key = $struct['key'];
378
        if (empty($extended_objects[$extended_key])) {
379 380 381 382 383 384 385 386 387 388 389 390 391
          // If this object has already been rejected by an earlier filtering
          // pass, we don't need to do any tests on it.
          continue;
        }

        $object = $struct['object'];
        if (is_string($object)) {
          // This is really a PHID, so look it up.
          $object_phid = $object;
          if (empty($ref_objects[$object_phid])) {
            // We weren't able to load the corresponding object, so just
            // reject this result outright.

392 393
            $reject = $extended_objects[$extended_key];
            unset($extended_objects[$extended_key]);
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408

            // TODO: This could be friendlier.
            $this->rejectObject($reject, false, '<bad-ref>');
            continue;
          }
          $object = $ref_objects[$object_phid];
        }

        $phid = $object->getPHID();

        $key_map[$phid][] = $extended_key;
        $objects_in[$phid] = $object;
      }

      if ($objects_in) {
409 410 411 412 413
        $objects_out = $this->executeExtendedPolicyChecks(
          $viewer,
          $capabilities,
          $objects_in,
          $key_map);
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
        $objects_out = mpull($objects_out, null, 'getPHID');
      } else {
        $objects_out = array();
      }

      // If any objects were removed by filtering, we're going to reject all
      // of the original objects which needed them.
      foreach ($objects_in as $phid => $object_in) {
        if (isset($objects_out[$phid])) {
          // This object survived filtering, so we don't need to throw any
          // results away.
          continue;
        }

        foreach ($key_map[$phid] as $extended_key) {
          if (empty($extended_objects[$extended_key])) {
            // We've already rejected this object, so we don't need to reject
            // it again.
            continue;
          }

          $reject = $extended_objects[$extended_key];
          unset($extended_objects[$extended_key]);

438 439 440 441 442 443 444
          // It's possible that we're rejecting this object for multiple
          // capability/policy failures, but just pick the first one to show
          // to the user.
          $first_capability = head($capabilities);
          $first_policy = $object_in->getPolicy($first_capability);

          $this->rejectObject($reject, $first_policy, $first_capability);
445 446 447 448 449
        }
      }
    }

    return $extended_objects;
450 451
  }

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
  private function executeExtendedPolicyChecks(
    PhabricatorUser $viewer,
    array $capabilities,
    array $objects,
    array $key_map) {

    // Do crude cycle detection by seeing if we have a huge stack depth.
    // Although more sophisticated cycle detection is possible in theory,
    // it is difficult with hierarchical objects like subprojects. Many other
    // checks make it difficult to create cycles normally, so just do a
    // simple check here to limit damage.

    static $depth;

    $depth++;

    if ($depth > 32) {
      foreach ($objects as $key => $object) {
        $this->rejectObject($objects[$key], false, '<cycle>');
        unset($objects[$key]);
        continue;
      }
    }

    if (!$objects) {
      return array();
    }

    $caught = null;
    try {
      $result = id(new PhabricatorPolicyFilter())
        ->setViewer($viewer)
        ->requireCapabilities($capabilities)
        ->apply($objects);
    } catch (Exception $ex) {
      $caught = $ex;
    }

    $depth--;

    if ($caught) {
      throw $caught;
    }

    return $result;
  }

499 500 501 502
  private function checkCapability(
    PhabricatorPolicyInterface $object,
    $capability) {

503
    $policy = $this->getObjectPolicy($object, $capability);
504

505 506 507 508
    if (!$policy) {
      // TODO: Formalize this somehow?
      $policy = PhabricatorPolicies::POLICY_USER;
    }
509

510
    if ($policy == PhabricatorPolicies::POLICY_PUBLIC) {
epriestley's avatar
epriestley committed
511 512
      // If the object is set to "public" but that policy is disabled for this
      // install, restrict the policy to "user".
513 514
      if (!PhabricatorEnv::getEnvConfig('policy.allow-public')) {
        $policy = PhabricatorPolicies::POLICY_USER;
epriestley's avatar
epriestley committed
515 516
      }

517 518 519 520
      // If the object is set to "public" but the capability is not a public
      // capability, restrict the policy to "user".
      $capobj = PhabricatorPolicyCapability::getCapabilityByKey($capability);
      if (!$capobj || !$capobj->shouldAllowPublicPolicySetting()) {
521
        $policy = PhabricatorPolicies::POLICY_USER;
522 523 524
      }
    }

525 526
    $viewer = $this->viewer;

epriestley's avatar
epriestley committed
527 528 529 530
    if ($viewer->isOmnipotent()) {
      return true;
    }

531 532 533 534 535 536 537 538
    if ($object instanceof PhabricatorSpacesInterface) {
      $space_phid = $object->getSpacePHID();
      if (!$this->canViewerSeeObjectsInSpace($viewer, $space_phid)) {
        $this->rejectObjectFromSpace($object, $space_phid);
        return false;
      }
    }

539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
    if ($object->hasAutomaticCapability($capability, $viewer)) {
      return true;
    }

    switch ($policy) {
      case PhabricatorPolicies::POLICY_PUBLIC:
        return true;
      case PhabricatorPolicies::POLICY_USER:
        if ($viewer->getPHID()) {
          return true;
        } else {
          $this->rejectObject($object, $policy, $capability);
        }
        break;
      case PhabricatorPolicies::POLICY_ADMIN:
        if ($viewer->getIsAdmin()) {
          return true;
        } else {
          $this->rejectObject($object, $policy, $capability);
        }
        break;
      case PhabricatorPolicies::POLICY_NOONE:
        $this->rejectObject($object, $policy, $capability);
        break;
      default:
564 565 566 567 568 569 570 571 572
        if (PhabricatorPolicyQuery::isObjectPolicy($policy)) {
          if ($this->checkObjectPolicy($policy, $object)) {
            return true;
          } else {
            $this->rejectObject($object, $policy, $capability);
            break;
          }
        }

573
        $type = phid_get_type($policy);
Joshua Spence's avatar
Joshua Spence committed
574
        if ($type == PhabricatorProjectProjectPHIDType::TYPECONST) {
575
          if (!empty($this->userProjects[$viewer->getPHID()][$policy])) {
576 577 578 579
            return true;
          } else {
            $this->rejectObject($object, $policy, $capability);
          }
Joshua Spence's avatar
Joshua Spence committed
580
        } else if ($type == PhabricatorPeopleUserPHIDType::TYPECONST) {
epriestley's avatar
epriestley committed
581 582 583 584 585
          if ($viewer->getPHID() == $policy) {
            return true;
          } else {
            $this->rejectObject($object, $policy, $capability);
          }
586
        } else if ($type == PhabricatorPolicyPHIDTypePolicy::TYPECONST) {
587
          if ($this->checkCustomPolicy($policy, $object)) {
588 589 590 591
            return true;
          } else {
            $this->rejectObject($object, $policy, $capability);
          }
592
        } else {
593 594
          // Reject objects with unknown policies.
          $this->rejectObject($object, false, $capability);
595
        }
596 597 598
    }

    return false;
599 600
  }

601 602 603 604
  public function rejectObject(
    PhabricatorPolicyInterface $object,
    $policy,
    $capability) {
605
    $viewer = $this->viewer;
606

607 608 609 610
    if (!$this->raisePolicyExceptions) {
      return;
    }

611
    if ($viewer->isOmnipotent()) {
612 613 614 615 616 617 618 619
      // Never raise policy exceptions for the omnipotent viewer. Although we
      // will never normally issue a policy rejection for the omnipotent
      // viewer, we can end up here when queries blanket reject objects that
      // have failed to load, without distinguishing between nonexistent and
      // nonvisible objects.
      return;
    }

620
    $capobj = PhabricatorPolicyCapability::getCapabilityByKey($capability);
621
    $rejection = null;
622 623 624 625
    if ($capobj) {
      $rejection = $capobj->describeCapabilityRejection();
      $capability_name = $capobj->getCapabilityName();
    } else {
626 627 628 629 630 631
      $capability_name = $capability;
    }

    if (!$rejection) {
      // We couldn't find the capability object, or it doesn't provide a
      // tailored rejection string.
632 633 634 635
      $rejection = pht(
        'You do not have the required capability ("%s") to do whatever you '.
        'are trying to do.',
        $capability);
636
    }
637

638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
    // See T13411. If you receive a policy exception because you can't view
    // an object, we also want to avoid disclosing too many details about the
    // actual policy (for example, the names of projects in the policy).

    // If you failed a "CAN_VIEW" check, or failed some other check and don't
    // have "CAN_VIEW" on the object, we give you an "opaque" explanation.
    // Otherwise, we give you a more detailed explanation.

    $view_capability = PhabricatorPolicyCapability::CAN_VIEW;
    if ($capability === $view_capability) {
      $show_details = false;
    } else {
      $show_details = self::hasCapability(
        $viewer,
        $object,
        $view_capability);
    }

656 657 658 659 660 661 662
    // TODO: This is a bit clumsy. We're producing HTML and text versions of
    // this message, but can't render the full policy rules in text today.
    // Users almost never get a text-only version of this exception anyway.

    $head = null;
    $more = null;

663
    if ($show_details) {
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
      $head = PhabricatorPolicy::getPolicyExplanation($viewer, $policy);

      $policy_type = PhabricatorPolicyPHIDTypePolicy::TYPECONST;
      $is_custom = (phid_get_type($policy) === $policy_type);
      if ($is_custom) {
        $policy_map = PhabricatorPolicyQuery::loadPolicies(
          $viewer,
          $object);
        if (isset($policy_map[$capability])) {
          require_celerity_resource('phui-policy-section-view-css');

          $more = id(new PhabricatorPolicyRulesView())
            ->setViewer($viewer)
            ->setPolicy($policy_map[$capability]);

          $more = phutil_tag(
            'div',
            array(
              'class' => 'phui-policy-section-view-rules',
            ),
            $more);
        }
      }
687
    } else {
688
      $head = PhabricatorPolicy::getOpaquePolicyExplanation($viewer, $policy);
689 690
    }

691
    $head = (array)$head;
epriestley's avatar
epriestley committed
692

693 694 695 696 697 698
    $exceptions = PhabricatorPolicy::getSpecialRules(
      $object,
      $this->viewer,
      $capability,
      true);

699 700 701 702
    $text_details = array_filter(array_merge($head, $exceptions));
    $text_details = implode(' ', $text_details);

    $html_details = array($head, $more, $exceptions);
703

704
    $access_denied = $this->renderAccessDenied($object);
705

706 707
    $full_message = pht(
      '[%s] (%s) %s // %s',
708
      $access_denied,
709 710
      $capability_name,
      $rejection,
711
      $text_details);
712 713

    $exception = id(new PhabricatorPolicyException($full_message))
714
      ->setTitle($access_denied)
715
      ->setObjectPHID($object->getPHID())
716
      ->setRejection($rejection)
717
      ->setCapability($capability)
718
      ->setCapabilityName($capability_name)
719
      ->setMoreInfo($html_details);
720 721

    throw $exception;
722
  }
723

724 725 726 727 728 729
  private function loadObjectPolicies(array $map) {
    $viewer = $this->viewer;
    $viewer_phid = $viewer->getPHID();

    $rules = PhabricatorPolicyQuery::getObjectPolicyRules(null);

730 731 732 733 734
    // Make sure we have clean, empty policy rule objects.
    foreach ($rules as $key => $rule) {
      $rules[$key] = clone $rule;
    }

735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
    $results = array();
    foreach ($map as $key => $object_list) {
      $rule = idx($rules, $key);
      if (!$rule) {
        continue;
      }

      foreach ($object_list as $object_key => $object) {
        if (!$rule->canApplyToObject($object)) {
          unset($object_list[$object_key]);
        }
      }

      $rule->willApplyRules($viewer, array(), $object_list);
      $results[$key] = $rule;
    }

    $this->objectPolicies[$viewer_phid] = $results;
  }

755
  private function loadCustomPolicies(array $map) {
756 757 758 759 760
    $viewer = $this->viewer;
    $viewer_phid = $viewer->getPHID();

    $custom_policies = id(new PhabricatorPolicyQuery())
      ->setViewer($viewer)
761
      ->withPHIDs(array_keys($map))
762 763 764 765 766
      ->execute();
    $custom_policies = mpull($custom_policies, null, 'getPHID');

    $classes = array();
    $values = array();
767 768
    $objects = array();
    foreach ($custom_policies as $policy_phid => $policy) {
769 770 771
      foreach ($policy->getCustomRuleClasses() as $class) {
        $classes[$class] = $class;
        $values[$class][] = $policy->getCustomRuleValues($class);
772 773 774 775

        foreach (idx($map, $policy_phid, array()) as $object) {
          $objects[$class][] = $object;
        }
776 777 778 779
      }
    }

    foreach ($classes as $class => $ignored) {
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
      $rule_object = newv($class, array());

      // Filter out any objects which the rule can't apply to.
      $target_objects = idx($objects, $class, array());
      foreach ($target_objects as $key => $target_object) {
        if (!$rule_object->canApplyToObject($target_object)) {
          unset($target_objects[$key]);
        }
      }

      $rule_object->willApplyRules(
        $viewer,
        array_mergev($values[$class]),
        $target_objects);

      $classes[$class] = $rule_object;
796 797 798 799 800 801 802 803 804 805 806 807 808
    }

    foreach ($custom_policies as $policy) {
      $policy->attachRuleObjects($classes);
    }

    if (empty($this->customPolicies[$viewer_phid])) {
      $this->customPolicies[$viewer_phid] = array();
    }

    $this->customPolicies[$viewer->getPHID()] += $custom_policies;
  }

809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
  private function checkObjectPolicy(
    $policy_phid,
    PhabricatorPolicyInterface $object) {
    $viewer = $this->viewer;
    $viewer_phid = $viewer->getPHID();

    $rule = idx($this->objectPolicies[$viewer_phid], $policy_phid);
    if (!$rule) {
      return false;
    }

    if (!$rule->canApplyToObject($object)) {
      return false;
    }

    return $rule->applyRule($viewer, null, $object);
  }

827 828 829 830
  private function checkCustomPolicy(
    $policy_phid,
    PhabricatorPolicyInterface $object) {

831 832 833
    $viewer = $this->viewer;
    $viewer_phid = $viewer->getPHID();

834 835 836 837 838
    $policy = idx($this->customPolicies[$viewer_phid], $policy_phid);
    if (!$policy) {
      // Reject, this policy is bogus.
      return false;
    }
839 840 841 842

    $objects = $policy->getRuleObjects();
    $action = null;
    foreach ($policy->getRules() as $rule) {
843 844 845 846 847
      if (!is_array($rule)) {
        // Reject, this policy rule is invalid.
        return false;
      }

848 849
      $rule_object = idx($objects, idx($rule, 'rule'));
      if (!$rule_object) {
850 851 852 853
        // Reject, this policy has a bogus rule.
        return false;
      }

854 855 856 857 858
      if (!$rule_object->canApplyToObject($object)) {
        // Reject, this policy rule can't be applied to the given object.
        return false;
      }

859
      // If the user matches this rule, use this action.
860
      if ($rule_object->applyRule($viewer, idx($rule, 'value'), $object)) {
861 862 863 864 865 866 867 868 869
        $action = idx($rule, 'action');
        break;
      }
    }

    if ($action === null) {
      $action = $policy->getDefaultAction();
    }

870
    if ($action === PhabricatorPolicy::ACTION_ALLOW) {
871 872 873 874 875 876
      return true;
    }

    return false;
  }

877 878 879 880 881 882 883 884 885 886 887
  private function getObjectPolicy(
    PhabricatorPolicyInterface $object,
    $capability) {

    if ($this->forcedPolicy) {
      return $this->forcedPolicy;
    } else {
      return $object->getPolicy($capability);
    }
  }

888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
  private function renderAccessDenied(PhabricatorPolicyInterface $object) {
    // NOTE: Not every type of policy object has a real PHID; just load an
    // empty handle if a real PHID isn't available.
    $phid = nonempty($object->getPHID(), PhabricatorPHIDConstants::PHID_VOID);

    $handle = id(new PhabricatorHandleQuery())
      ->setViewer($this->viewer)
      ->withPHIDs(array($phid))
      ->executeOne();

    $object_name = $handle->getObjectName();

    $is_serious = PhabricatorEnv::getEnvConfig('phabricator.serious-business');
    if ($is_serious) {
      $access_denied = pht(
        'Access Denied: %s',
        $object_name);
    } else {
      $access_denied = pht(
        'You Shall Not Pass: %s',
        $object_name);
    }

    return $access_denied;
  }

914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940

  private function canViewerSeeObjectsInSpace(
    PhabricatorUser $viewer,
    $space_phid) {

    $spaces = PhabricatorSpacesNamespaceQuery::getAllSpaces();

    // If there are no spaces, everything exists in an implicit default space
    // with no policy controls. This is the default state.
    if (!$spaces) {
      if ($space_phid !== null) {
        return false;
      } else {
        return true;
      }
    }

    if ($space_phid === null) {
      $space = PhabricatorSpacesNamespaceQuery::getDefaultSpace();
    } else {
      $space = idx($spaces, $space_phid);
    }

    if (!$space) {
      return false;
    }

941 942 943 944 945
    // See long comment in PhabricatorCursorPagedPolicyAwareQuery
    if ($space->getPHID() == PhabricatorSpacesNamespaceQuery::getMagicAllUsersSpace()->getPHID()) {
      return true;
    }

946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
    // This may be more involved later, but for now being able to see the
    // space is equivalent to being able to see everything in it.
    return self::hasCapability(
      $viewer,
      $space,
      PhabricatorPolicyCapability::CAN_VIEW);
  }

  private function rejectObjectFromSpace(
    PhabricatorPolicyInterface $object,
    $space_phid) {

    if (!$this->raisePolicyExceptions) {
      return;
    }

    if ($this->viewer->isOmnipotent()) {
      return;
    }

    $access_denied = $this->renderAccessDenied($object);

    $rejection = pht(
      'This object is in a space you do not have permission to access.');
    $full_message = pht('[%s] %s', $access_denied, $rejection);

    $exception = id(new PhabricatorPolicyException($full_message))
      ->setTitle($access_denied)
974 975 976
      ->setObjectPHID($object->getPHID())
      ->setRejection($rejection)
      ->setCapability(PhabricatorPolicyCapability::CAN_VIEW);
977 978 979 980

    throw $exception;
  }

981 982 983 984
  private function applyApplicationChecks(array $objects) {
    $viewer = $this->viewer;

    foreach ($objects as $key => $object) {
985 986 987 988 989 990 991 992 993 994 995 996 997
      // Don't filter handles: users are allowed to see handles from an
      // application they can't see even if they can not see objects from
      // that application. Note that the application policies still apply to
      // the underlying object, so these will be "Restricted Object" handles.

      // If we don't let these through, PhabricatorHandleQuery will completely
      // fail to load results for PHIDs that are part of applications which
      // the viewer can not see, but a fundamental property of handles is that
      // we always load something and they can safely be assumed to load.
      if ($object instanceof PhabricatorObjectHandle) {
        continue;
      }

998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
      $phid = $object->getPHID();
      if (!$phid) {
        continue;
      }

      $application_class = $this->getApplicationForPHID($phid);
      if ($application_class === null) {
        continue;
      }

      $can_see = PhabricatorApplication::isClassInstalledForViewer(
        $application_class,
        $viewer);
      if ($can_see) {
        continue;
      }

      unset($objects[$key]);

      $application = newv($application_class, array());
      $this->rejectObject(
        $application,
        $application->getPolicy(PhabricatorPolicyCapability::CAN_VIEW),
        PhabricatorPolicyCapability::CAN_VIEW);
    }

    return $objects;
  }

  private function getApplicationForPHID($phid) {
1028 1029
    static $class_map = array();

1030
    $phid_type = phid_get_type($phid);
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
    if (!isset($class_map[$phid_type])) {
      $type_objects = PhabricatorPHIDType::getTypes(array($phid_type));
      $type_object = idx($type_objects, $phid_type);
      if (!$type_object) {
        $class = false;
      } else {
        $class = $type_object->getPHIDTypeApplicationClass();
      }

      $class_map[$phid_type] = $class;
    }
1042

1043 1044
    $class = $class_map[$phid_type];
    if ($class === false) {
1045 1046 1047
      return null;
    }

1048
    return $class;
1049 1050
  }

1051
}