3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
12 namespace Civi\API\Subscriber
;
15 use Symfony\Component\EventDispatcher\EventSubscriberInterface
;
18 * Given an entity which dynamically attaches itself to another entity,
19 * determine if one has permission to the other entity.
21 * Example: Suppose one tries to manipulate a File which is attached to a
22 * Mailing. DynamicFKAuthorization will enforce permissions on the File by
23 * imitating the permissions of the Mailing.
25 * Note: This enforces a constraint: all matching API calls must define
26 * "id" (e.g. for the file) or "entity_table+entity_id" or
27 * "field_name+entity_id".
29 * Note: The permission guard does not exactly authorize the request, but it
30 * may veto authorization.
32 class DynamicFKAuthorization
implements EventSubscriberInterface
{
37 public static function getSubscribedEvents() {
39 Events
::AUTHORIZE
=> [
40 ['onApiAuthorize', Events
::W_EARLY
],
46 * @var \Civi\API\Kernel
48 * Treat as private. Marked public due to PHP 5.3-compatibility issues.
53 * @var string, the entity for which we want to manage permissions
55 protected $entityName;
58 * @var array <string> the actions for which we want to manage permissions
63 * @var string, SQL. Given a file ID, determine the entity+table it's attached to.
65 * ex: "SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
66 * FROM civicrm_file cf
67 * INNER JOIN civicrm_entity_file cef ON cf.id = cef.file_id
70 * Note: %1 is a parameter
71 * Note: There are three parameters
72 * - is_valid: "1" if %1 identifies an actual record; otherwise "0"
73 * - entity_table: NULL or the name of a related table
74 * - entity_id: NULL or the ID of a row in the related table
76 protected $lookupDelegateSql;
79 * @var string, SQL. Get a list of (field_name, table_name, extends) tuples.
81 * For example, one tuple might be ("custom_123", "civicrm_value_mygroup_4",
84 protected $lookupCustomFieldSql;
89 * Each item is an array(field_name => $, table_name => $, extends => $)
91 protected $lookupCustomFieldCache;
94 * @var array list of related tables for which FKs are allowed
96 protected $allowedDelegates;
99 * @param \Civi\API\Kernel $kernel
101 * @param string $entityName
102 * The entity for which we want to manage permissions (e.g. "File" or
104 * @param array $actions
105 * The actions for which we want to manage permissions (e.g. "create",
107 * @param string $lookupDelegateSql
108 * See docblock in DynamicFKAuthorization::$lookupDelegateSql.
109 * @param string $lookupCustomFieldSql
110 * See docblock in DynamicFKAuthorization::$lookupCustomFieldSql.
111 * @param array|NULL $allowedDelegates
112 * e.g. "civicrm_mailing","civicrm_activity"; NULL to allow any.
114 public function __construct($kernel, $entityName, $actions, $lookupDelegateSql, $lookupCustomFieldSql, $allowedDelegates = NULL) {
115 $this->kernel
= $kernel;
116 $this->entityName
= \CRM_Utils_String
::convertStringToCamel($entityName);
117 $this->actions
= $actions;
118 $this->lookupDelegateSql
= $lookupDelegateSql;
119 $this->lookupCustomFieldSql
= $lookupCustomFieldSql;
120 $this->allowedDelegates
= $allowedDelegates;
124 * @param \Civi\API\Event\AuthorizeEvent $event
125 * API authorization event.
126 * @throws \API_Exception
127 * @throws \Civi\API\Exception\UnauthorizedException
129 public function onApiAuthorize(\Civi\API\Event\AuthorizeEvent
$event) {
130 $apiRequest = $event->getApiRequest();
131 if ($apiRequest['version'] == 3 && \CRM_Utils_String
::convertStringToCamel($apiRequest['entity']) == $this->entityName
&& in_array(strtolower($apiRequest['action']), $this->actions
)) {
132 if (isset($apiRequest['params']['field_name'])) {
133 $fldIdx = \CRM_Utils_Array
::index(['field_name'], $this->getCustomFields());
134 if (empty($fldIdx[$apiRequest['params']['field_name']])) {
135 throw new \
Exception("Failed to map custom field to entity table");
137 $apiRequest['params']['entity_table'] = $fldIdx[$apiRequest['params']['field_name']]['entity_table'];
138 unset($apiRequest['params']['field_name']);
142 empty($apiRequest['params']['id']) && empty($apiRequest['params']['entity_table'])
144 throw new \
API_Exception("Mandatory key(s) missing from params array: 'id' or 'entity_table'");
147 if (isset($apiRequest['params']['id'])) {
148 list($isValidId, $entityTable, $entityId) = $this->getDelegate($apiRequest['params']['id']);
149 if ($isValidId && $entityTable && $entityId) {
150 $this->authorizeDelegate($apiRequest['action'], $entityTable, $entityId, $apiRequest);
151 $this->preventReassignment($apiRequest['params']['id'], $entityTable, $entityId, $apiRequest);
154 elseif ($isValidId) {
155 throw new \
API_Exception("Failed to match record to related entity");
157 elseif (!$isValidId && strtolower($apiRequest['action']) == 'get') {
158 // The matches will be an empty set; doesn't make a difference if we
160 // To pass SyntaxConformanceTest, we won't veto "get" on empty-set.
165 if (isset($apiRequest['params']['entity_table'])) {
166 if (!\CRM_Core_DAO_AllCoreTables
::isCoreTable($apiRequest['params']['entity_table'])) {
167 throw new \
API_Exception("Unrecognized target entity table {$apiRequest['params']['entity_table']}");
169 $this->authorizeDelegate(
170 $apiRequest['action'],
171 $apiRequest['params']['entity_table'],
172 \CRM_Utils_Array
::value('entity_id', $apiRequest['params'], NULL),
178 throw new \
API_Exception("Failed to run permission check");
183 * @param string $action
184 * The API action (e.g. "create").
185 * @param string $entityTable
186 * The target entity table (e.g. "civicrm_mailing").
187 * @param int|null $entityId
188 * The target entity ID.
189 * @param array $apiRequest
190 * The full API request.
192 * @throws \API_Exception
193 * @throws \Civi\API\Exception\UnauthorizedException
195 public function authorizeDelegate($action, $entityTable, $entityId, $apiRequest) {
196 if ($this->isTrusted($apiRequest)) {
200 $entity = $this->getDelegatedEntityName($entityTable);
202 throw new \
API_Exception("Failed to run permission check: Unrecognized target entity table ($entityTable)");
205 throw new \Civi\API\Exception\
UnauthorizedException("Authorization failed on ($entity): Missing entity_id");
209 * @var \Exception $exception
213 \CRM_Core_Transaction
::create(TRUE)->run(function($tx) use ($entity, $action, $entityId, &$exception, $self) {
219 'check_permissions' => 1,
223 $result = $self->kernel
->run($entity, $self->getDelegatedAction($action), $params);
224 if ($result['is_error'] ||
empty($result['values'])) {
225 $exception = new \Civi\API\Exception\
UnauthorizedException("Authorization failed on ($entity,$entityId)", [
237 * If the request attempts to change the entity_table/entity_id of an
238 * existing record, then generate an error.
241 * The main record being changed.
242 * @param string $entityTable
244 * @param int $entityId
246 * @param array $apiRequest
247 * The full API request.
248 * @throws \API_Exception
250 public function preventReassignment($fileId, $entityTable, $entityId, $apiRequest) {
251 if (strtolower($apiRequest['action']) == 'create' && $fileId && !$this->isTrusted($apiRequest)) {
252 // TODO: no change in field_name?
253 if (isset($apiRequest['params']['entity_table']) && $entityTable != $apiRequest['params']['entity_table']) {
254 throw new \
API_Exception("Cannot modify entity_table");
256 if (isset($apiRequest['params']['entity_id']) && $entityId != $apiRequest['params']['entity_id']) {
257 throw new \
API_Exception("Cannot modify entity_id");
263 * @param string $entityTable
264 * The target entity table (e.g. "civicrm_mailing" or "civicrm_activity").
265 * @return string|NULL
266 * The target entity name (e.g. "Mailing" or "Activity").
268 public function getDelegatedEntityName($entityTable) {
269 if ($this->allowedDelegates
=== NULL ||
in_array($entityTable, $this->allowedDelegates
)) {
270 $className = \CRM_Core_DAO_AllCoreTables
::getClassForTable($entityTable);
272 $entityName = \CRM_Core_DAO_AllCoreTables
::getBriefName($className);
282 * @param string $action
283 * API action name -- e.g. "create" ("When running *create* on a file...").
285 * e.g. "create" ("Check for *create* permission on the mailing to which
288 public function getDelegatedAction($action) {
291 // reading attachments requires reading the other entity
296 // creating/updating/deleting an attachment requires editing
309 * (0 => bool $isValid, 1 => string $entityTable, 2 => int $entityId)
312 public function getDelegate($id) {
313 $query = \CRM_Core_DAO
::executeQuery($this->lookupDelegateSql
, [
314 1 => [$id, 'Positive'],
316 if ($query->fetch()) {
317 if (!preg_match('/^civicrm_value_/', $query->entity_table
)) {
318 // A normal attachment directly on its entity.
319 return [$query->is_valid
, $query->entity_table
, $query->entity_id
];
322 // Ex: Translate custom-field table ("civicrm_value_foo_4") to
323 // entity table ("civicrm_activity").
324 $tblIdx = \CRM_Utils_Array
::index(['table_name'], $this->getCustomFields());
325 if (isset($tblIdx[$query->entity_table
])) {
326 return [$query->is_valid
, $tblIdx[$query->entity_table
]['entity_table'], $query->entity_id
];
328 throw new \
Exception('Failed to lookup entity table for custom field.');
331 return [FALSE, NULL, NULL];
336 * @param array $apiRequest
337 * The full API request.
340 public function isTrusted($apiRequest) {
341 // isn't this redundant?
342 return empty($apiRequest['params']['check_permissions']) or $apiRequest['params']['check_permissions'] == FALSE;
347 * Each item has keys 'field_name', 'table_name', 'extends', 'entity_table'
349 public function getCustomFields() {
350 $query = \CRM_Core_DAO
::executeQuery($this->lookupCustomFieldSql
);
352 while ($query->fetch()) {
354 'field_name' => $query->field_name
,
355 'table_name' => $query->table_name
,
356 'extends' => $query->extends,
357 'entity_table' => \CRM_Core_BAO_CustomGroup
::getTableNameByEntityName($query->extends),