security/core#73 - Fix Contact.getquick API key exposure
[civicrm-core.git] / tests / phpunit / api / v3 / UtilsTest.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
7d61e75f 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
7d61e75f
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035 11
6a488035
TO
12require_once 'CRM/Utils/DeprecatedUtils.php';
13
14/**
15 * Test class for API utils
16 *
17 * @package CiviCRM
acb109b7 18 * @group headless
6a488035
TO
19 */
20class api_v3_UtilsTest extends CiviUnitTestCase {
ca985406 21 protected $_apiversion = 3;
6a488035 22 public $DBResetRequired = FALSE;
b7c9bc4c 23
6a488035
TO
24 public $_contactID = 1;
25
26 /**
27 * Sets up the fixture, for example, opens a network connection.
fe482240 28 *
6a488035 29 * This method is called before a test is executed.
6a488035
TO
30 */
31 protected function setUp() {
32 parent::setUp();
d1e734a5 33 $this->useTransaction(TRUE);
6a488035
TO
34 }
35
00be9182 36 public function testAddFormattedParam() {
9099cab3
CW
37 $values = ['contact_type' => 'Individual'];
38 $params = ['something' => 1];
6a488035
TO
39 $result = _civicrm_api3_deprecated_add_formatted_param($values, $params);
40 $this->assertTrue($result);
41 }
42
00be9182 43 public function testCheckPermissionReturn() {
9099cab3 44 $check = ['check_permissions' => TRUE];
6a488035 45 $config = CRM_Core_Config::singleton();
9099cab3 46 $config->userPermissionClass->permissions = [];
d0c9daa4 47 $this->assertFalse($this->runPermissionCheck('contact', 'create', $check), 'empty permissions should not be enough');
9099cab3 48 $config->userPermissionClass->permissions = ['access CiviCRM'];
d0c9daa4 49 $this->assertFalse($this->runPermissionCheck('contact', 'create', $check), 'lacking permissions should not be enough');
9099cab3 50 $config->userPermissionClass->permissions = ['add contacts'];
d0c9daa4 51 $this->assertFalse($this->runPermissionCheck('contact', 'create', $check), 'lacking permissions should not be enough');
6a488035 52
9099cab3 53 $config->userPermissionClass->permissions = ['access CiviCRM', 'add contacts'];
d0c9daa4 54 $this->assertTrue($this->runPermissionCheck('contact', 'create', $check), 'exact permissions should be enough');
6a488035 55
9099cab3 56 $config->userPermissionClass->permissions = ['access CiviCRM', 'add contacts', 'import contacts'];
d0c9daa4 57 $this->assertTrue($this->runPermissionCheck('contact', 'create', $check), 'overfluous permissions should be enough');
6a488035
TO
58 }
59
00be9182 60 public function testCheckPermissionThrow() {
9099cab3 61 $check = ['check_permissions' => TRUE];
6a488035
TO
62 $config = CRM_Core_Config::singleton();
63 try {
9099cab3 64 $config->userPermissionClass->permissions = ['access CiviCRM'];
d0c9daa4 65 $this->runPermissionCheck('contact', 'create', $check, TRUE);
6a488035 66 }
92915c55 67 catch (Exception $e) {
6a488035
TO
68 $message = $e->getMessage();
69 }
1644b908 70 $this->assertEquals($message, 'API permission check failed for Contact/create call; insufficient permission: require access CiviCRM and add contacts', 'lacking permissions should throw an exception');
6a488035 71
9099cab3 72 $config->userPermissionClass->permissions = ['access CiviCRM', 'add contacts', 'import contacts'];
d0c9daa4 73 $this->assertTrue($this->runPermissionCheck('contact', 'create', $check), 'overfluous permissions should return true');
6a488035
TO
74 }
75
00be9182 76 public function testCheckPermissionSkip() {
6a488035 77 $config = CRM_Core_Config::singleton();
9099cab3
CW
78 $config->userPermissionClass->permissions = ['access CiviCRM'];
79 $params = ['check_permissions' => TRUE];
d0c9daa4 80 $this->assertFalse($this->runPermissionCheck('contact', 'create', $params), 'lacking permissions should not be enough');
9099cab3 81 $params = ['check_permissions' => FALSE];
d0c9daa4
TO
82 $this->assertTrue($this->runPermissionCheck('contact', 'create', $params), 'permission check should be skippable');
83 }
84
85 /**
86 * @param string $entity
87 * @param string $action
88 * @param array $params
e16033b4
TO
89 * @param bool $throws
90 * Whether we should pass any exceptions for authorization failures.
cbdcc634
EM
91 *
92 * @throws API_Exception
93 * @throws Exception
a6c01b45
CW
94 * @return bool
95 * TRUE or FALSE depending on the outcome of the authorization check
d0c9daa4 96 */
00be9182 97 public function runPermissionCheck($entity, $action, $params, $throws = FALSE) {
080b7aca 98 $params['version'] = 3;
d0c9daa4
TO
99 $dispatcher = new \Symfony\Component\EventDispatcher\EventDispatcher();
100 $dispatcher->addSubscriber(new \Civi\API\Subscriber\PermissionCheck());
101 $kernel = new \Civi\API\Kernel($dispatcher);
5a3846f7 102 $apiRequest = \Civi\API\Request::create($entity, $action, $params);
d0c9daa4
TO
103 try {
104 $kernel->authorize(NULL, $apiRequest);
105 return TRUE;
0db6c3e1
TO
106 }
107 catch (\API_Exception $e) {
d0c9daa4
TO
108 $extra = $e->getExtraParams();
109 if (!$throws && $extra['error_code'] == API_Exception::UNAUTHORIZED) {
110 return FALSE;
0db6c3e1
TO
111 }
112 else {
d0c9daa4
TO
113 throw $e;
114 }
115 }
6a488035
TO
116 }
117
c490a46a
CW
118 /**
119 * Test verify mandatory - includes DAO & passed as well as empty & NULL fields
120 */
00be9182 121 public function testVerifyMandatory() {
6a488035 122 _civicrm_api3_initialize(TRUE);
9099cab3 123 $params = [
6a488035
TO
124 'entity_table' => 'civicrm_contact',
125 'note' => '',
126 'contact_id' => $this->_contactID,
127 'modified_date' => '2011-01-31',
128 'subject' => NULL,
21dfd5f5 129 'version' => $this->_apiversion,
9099cab3 130 ];
6a488035 131 try {
9099cab3 132 civicrm_api3_verify_mandatory($params, 'CRM_Core_BAO_Note', ['note', 'subject']);
6a488035 133 }
92915c55 134 catch (Exception $expected) {
446e1c54 135 $this->assertEquals('Mandatory key(s) missing from params array: note, subject', $expected->getMessage());
6a488035
TO
136 return;
137 }
138
139 $this->fail('An expected exception has not been raised.');
140 }
141
c490a46a
CW
142 /**
143 * Test verify one mandatory - includes DAO & passed as well as empty & NULL fields
144 */
00be9182 145 public function testVerifyOneMandatory() {
6a488035 146 _civicrm_api3_initialize(TRUE);
9099cab3 147 $params = [
6a488035
TO
148 'entity_table' => 'civicrm_contact',
149 'note' => '',
150 'contact_id' => $this->_contactID,
151 'modified_date' => '2011-01-31',
152 'subject' => NULL,
153 'version' => $this->_apiversion,
9099cab3 154 ];
6a488035
TO
155
156 try {
9099cab3 157 civicrm_api3_verify_one_mandatory($params, 'CRM_Core_BAO_Note', ['note', 'subject']);
6a488035 158 }
92915c55 159 catch (Exception $expected) {
446e1c54 160 $this->assertEquals('Mandatory key(s) missing from params array: one of (note, subject)', $expected->getMessage());
6a488035
TO
161 return;
162 }
163
164 $this->fail('An expected exception has not been raised.');
165 }
166
c490a46a
CW
167 /**
168 * Test verify one mandatory - includes DAO & passed as well as empty & NULL fields
169 */
00be9182 170 public function testVerifyOneMandatoryOneSet() {
6a488035 171 _civicrm_api3_initialize(TRUE);
9099cab3 172 $params = [
92915c55
TO
173 'version' => 3,
174 'entity_table' => 'civicrm_contact',
175 'note' => 'note',
176 'contact_id' => $this->_contactID,
177 'modified_date' => '2011-01-31',
389bcebf 178 'subject' => NULL,
9099cab3 179 ];
6a488035
TO
180
181 try {
9099cab3 182 civicrm_api3_verify_one_mandatory($params, NULL, ['note', 'subject']);
6a488035 183 }
92915c55 184 catch (Exception$expected) {
6a488035
TO
185 $this->fail('Exception raised when it shouldn\'t have been in line ' . __LINE__);
186 }
187 }
188
c490a46a 189 /**
eceb18cc 190 * Test GET DAO function returns DAO.
b6708aeb 191 */
00be9182 192 public function testGetDAO() {
9099cab3 193 $params = [
49e101d0
CW
194 'civicrm_api3_custom_group_get' => 'CRM_Core_DAO_CustomGroup',
195 'custom_group' => 'CRM_Core_DAO_CustomGroup',
196 'CustomGroup' => 'CRM_Core_DAO_CustomGroup',
197 'civicrm_api3_custom_field_get' => 'CRM_Core_DAO_CustomField',
198 'civicrm_api3_survey_get' => 'CRM_Campaign_DAO_Survey',
199 'civicrm_api3_pledge_payment_get' => 'CRM_Pledge_DAO_PledgePayment',
200 'civicrm_api3_website_get' => 'CRM_Core_DAO_Website',
201 'Membership' => 'CRM_Member_DAO_Membership',
9099cab3 202 ];
49e101d0
CW
203 foreach ($params as $input => $expected) {
204 $result = _civicrm_api3_get_DAO($input);
205 $this->assertEquals($expected, $result);
206 }
6a488035 207 }
c490a46a
CW
208
209 /**
eceb18cc 210 * Test GET BAO function returns BAO when it exists.
b6708aeb 211 */
00be9182 212 public function testGetBAO() {
9099cab3 213 $params = [
49e101d0
CW
214 'civicrm_api3_website_get' => 'CRM_Core_BAO_Website',
215 'civicrm_api3_survey_get' => 'CRM_Campaign_BAO_Survey',
216 'civicrm_api3_pledge_payment_get' => 'CRM_Pledge_BAO_PledgePayment',
217 'Household' => 'CRM_Contact_BAO_Contact',
218 // Note this one DOES NOT have a BAO so we expect to fall back on returning the DAO
219 'mailing_group' => 'CRM_Mailing_DAO_MailingGroup',
5c1174d3
CW
220 // Make sure we get null back with nonexistant entities
221 'civicrm_this_does_not_exist' => NULL,
9099cab3 222 ];
49e101d0
CW
223 foreach ($params as $input => $expected) {
224 $result = _civicrm_api3_get_BAO($input);
225 $this->assertEquals($expected, $result);
226 }
6a488035
TO
227 }
228
cc1b27ee 229 /**
230 * Test the validate function transforms dates.
231 *
232 * @throws \CiviCRM_API3_Exception
233 * @throws \Exception
234 */
00be9182 235 public function test_civicrm_api3_validate_fields() {
cc1b27ee 236 $params = ['relationship_start_date' => '2010-12-20', 'relationship_end_date' => ''];
9099cab3 237 $fields = civicrm_api3('relationship', 'getfields', ['action' => 'get']);
7f8c98cd 238 _civicrm_api3_validate_fields('relationship', 'get', $params, $fields['values']);
cc1b27ee 239 $this->assertEquals('20101220000000', $params['relationship_start_date']);
240 $this->assertEquals('', $params['relationship_end_date']);
6a488035
TO
241 }
242
00be9182 243 public function test_civicrm_api3_validate_fields_membership() {
9099cab3 244 $params = [
92915c55
TO
245 'start_date' => '2010-12-20',
246 'end_date' => '',
247 'membership_end_date' => '0',
09ba1975 248 'membership_join_date' => '2010-12-20',
389bcebf 249 'membership_start_date' => '2010-12-20',
9099cab3
CW
250 ];
251 $fields = civicrm_api3('Membership', 'getfields', ['action' => 'get']);
7f8c98cd 252 _civicrm_api3_validate_fields('Membership', 'get', $params, $fields['values']);
903d0d38 253 $this->assertEquals('2010-12-20', $params['start_date']);
ba4a1892 254 $this->assertEquals('20101220000000', $params['membership_start_date']);
6a488035 255 $this->assertEquals('', $params['end_date']);
09ba1975 256 $this->assertEquals('20101220000000', $params['membership_join_date'], 'join_date not set in line ' . __LINE__);
6a488035
TO
257 }
258
00be9182 259 public function test_civicrm_api3_validate_fields_event() {
6a488035 260
9099cab3 261 $params = [
6a488035 262 'registration_start_date' => 20080601,
6c6e6187 263 'registration_end_date' => '2008-10-15',
92915c55
TO
264 'start_date' => '2010-12-20',
265 'end_date' => '',
9099cab3
CW
266 ];
267 $fields = civicrm_api3('Event', 'getfields', ['action' => 'create']);
7f8c98cd 268 _civicrm_api3_validate_fields('event', 'create', $params, $fields['values']);
ba4a1892
TM
269 $this->assertEquals('20101220000000', $params['start_date']);
270 $this->assertEquals('20081015000000', $params['registration_end_date']);
271 $this->assertEquals('', $params['end_date']);
6a488035
TO
272 $this->assertEquals('20080601000000', $params['registration_start_date']);
273 }
274
00be9182 275 public function test_civicrm_api3_validate_fields_exception() {
9099cab3 276 $params = [
09ba1975 277 'membership_join_date' => 'abc',
9099cab3 278 ];
6a488035 279 try {
9099cab3 280 $fields = civicrm_api3('Membership', 'getfields', ['action' => 'get']);
7f8c98cd 281 _civicrm_api3_validate_fields('Membership', 'get', $params, $fields['values']);
6a488035 282 }
92915c55 283 catch (Exception$expected) {
09ba1975 284 $this->assertEquals('membership_join_date is not a valid date: abc', $expected->getMessage());
6a488035
TO
285 }
286 }
287
00be9182 288 public function testGetFields() {
9099cab3 289 $result = $this->callAPISuccess('membership', 'getfields', []);
6a488035 290 $this->assertArrayHasKey('values', $result);
9099cab3 291 $result = $this->callAPISuccess('relationship', 'getfields', []);
6a488035 292 $this->assertArrayHasKey('values', $result);
9099cab3 293 $result = $this->callAPISuccess('event', 'getfields', []);
6a488035
TO
294 $this->assertArrayHasKey('values', $result);
295 }
41d89fcb 296
00be9182 297 public function testGetFields_AllOptions() {
9099cab3
CW
298 $result = $this->callAPISuccess('contact', 'getfields', [
299 'options' => [
41d89fcb 300 'get_options' => 'all',
9099cab3
CW
301 ],
302 ]);
41d89fcb
TO
303 $this->assertEquals('Household', $result['values']['contact_type']['options']['Household']);
304 $this->assertEquals('HTML', $result['values']['preferred_mail_format']['options']['HTML']);
305 }
96025800 306
5bc7c754 307 public function basicArrayCases() {
9099cab3
CW
308 $records = [
309 ['snack_id' => 'a', 'fruit' => 'apple', 'cheese' => 'swiss'],
310 ['snack_id' => 'b', 'fruit' => 'grape', 'cheese' => 'cheddar'],
311 ['snack_id' => 'c', 'fruit' => 'apple', 'cheese' => 'cheddar'],
312 ['snack_id' => 'd', 'fruit' => 'apple', 'cheese' => 'gouda'],
313 ['snack_id' => 'e', 'fruit' => 'apple', 'cheese' => 'provolone'],
314 ];
315
316 $cases[] = [
5bc7c754 317 $records,
39b959db 318 // params
9099cab3 319 ['version' => 3],
39b959db 320 // expected results
9099cab3
CW
321 ['a', 'b', 'c', 'd', 'e'],
322 ];
5bc7c754 323
9099cab3 324 $cases[] = [
5bc7c754 325 $records,
39b959db 326 // params
9099cab3 327 ['version' => 3, 'fruit' => 'apple'],
39b959db 328 // expected results
9099cab3
CW
329 ['a', 'c', 'd', 'e'],
330 ];
5bc7c754 331
9099cab3 332 $cases[] = [
5bc7c754 333 $records,
9099cab3
CW
334 ['version' => 3, 'cheese' => 'cheddar'],
335 ['b', 'c'],
336 ];
5bc7c754 337
9099cab3 338 $cases[] = [
a066deea 339 $records,
9099cab3
CW
340 ['version' => 3, 'id' => 'd'],
341 ['d'],
342 ];
a066deea 343
5bc7c754
TO
344 return $cases;
345 }
346
347 /**
348 * Make a basic API (Widget.get) which allows getting data out of a simple in-memory
349 * list of records.
350 *
351 * @param $records
352 * The list of all records.
353 * @param $params
354 * The filter criteria
355 * @param array $resultIds
356 * The records which are expected to match.
357 * @dataProvider basicArrayCases
358 */
359 public function testBasicArrayGet($records, $params, $resultIds) {
360 $params['version'] = 3;
361
362 $kernel = new \Civi\API\Kernel(new \Symfony\Component\EventDispatcher\EventDispatcher());
363
364 $provider = new \Civi\API\Provider\AdhocProvider($params['version'], 'Widget');
365 $provider->addAction('get', 'access CiviCRM', function ($apiRequest) use ($records) {
9099cab3 366 return _civicrm_api3_basic_array_get('Widget', $apiRequest['params'], $records, 'snack_id', ['snack_id', 'fruit', 'cheese']);
5bc7c754
TO
367 });
368 $kernel->registerApiProvider($provider);
369
5a3846f7 370 $r1 = $kernel->runSafe('Widget', 'get', $params);
5bc7c754
TO
371 $this->assertEquals(count($resultIds), $r1['count']);
372 $this->assertEquals($resultIds, array_keys($r1['values']));
373 $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('snack_id', $r1['values'])));
374 $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('id', $r1['values'])));
375
5a3846f7 376 $r2 = $kernel->runSafe('Widget', 'get', $params + ['sequential' => 1]);
5bc7c754
TO
377 $this->assertEquals(count($resultIds), $r2['count']);
378 $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('snack_id', $r2['values'])));
379 $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('id', $r2['values'])));
380
5a3846f7 381 $r3 = $kernel->runSafe('Widget', 'get', $params + ['options' => ['offset' => 1, 'limit' => 2]]);
5bc7c754
TO
382 $slice = array_slice($resultIds, 1, 2);
383 $this->assertEquals(count($slice), $r3['count']);
384 $this->assertEquals($slice, array_values(CRM_Utils_Array::collect('snack_id', $r3['values'])));
385 $this->assertEquals($slice, array_values(CRM_Utils_Array::collect('id', $r3['values'])));
386 }
387
388 public function testBasicArrayGetReturn() {
9099cab3
CW
389 $records = [
390 ['snack_id' => 'a', 'fruit' => 'apple', 'cheese' => 'swiss'],
391 ['snack_id' => 'b', 'fruit' => 'grape', 'cheese' => 'cheddar'],
392 ['snack_id' => 'c', 'fruit' => 'apple', 'cheese' => 'cheddar'],
393 ];
5bc7c754
TO
394
395 $kernel = new \Civi\API\Kernel(new \Symfony\Component\EventDispatcher\EventDispatcher());
396 $provider = new \Civi\API\Provider\AdhocProvider(3, 'Widget');
397 $provider->addAction('get', 'access CiviCRM', function ($apiRequest) use ($records) {
9099cab3 398 return _civicrm_api3_basic_array_get('Widget', $apiRequest['params'], $records, 'snack_id', ['snack_id', 'fruit', 'cheese']);
5bc7c754
TO
399 });
400 $kernel->registerApiProvider($provider);
401
5a3846f7 402 $r1 = $kernel->runSafe('Widget', 'get', [
5bc7c754
TO
403 'version' => 3,
404 'snack_id' => 'b',
405 'return' => 'fruit',
9099cab3 406 ]);
5bc7c754 407 $this->assertAPISuccess($r1);
9099cab3 408 $this->assertEquals(['b' => ['id' => 'b', 'fruit' => 'grape']], $r1['values']);
5bc7c754 409
5a3846f7 410 $r2 = $kernel->runSafe('Widget', 'get', [
5bc7c754
TO
411 'version' => 3,
412 'snack_id' => 'b',
9099cab3
CW
413 'return' => ['fruit', 'cheese'],
414 ]);
5bc7c754 415 $this->assertAPISuccess($r2);
9099cab3 416 $this->assertEquals(['b' => ['id' => 'b', 'fruit' => 'grape', 'cheese' => 'cheddar']], $r2['values']);
5bc7c754 417
5a3846f7 418 $r3 = $kernel->runSafe('Widget', 'get', [
5bc7c754
TO
419 'version' => 3,
420 'cheese' => 'cheddar',
9099cab3
CW
421 'return' => ['fruit'],
422 ]);
5bc7c754 423 $this->assertAPISuccess($r3);
9099cab3
CW
424 $this->assertEquals([
425 'b' => ['id' => 'b', 'fruit' => 'grape'],
426 'c' => ['id' => 'c', 'fruit' => 'apple'],
427 ], $r3['values']);
5bc7c754
TO
428 }
429
1f87b2a5
SL
430 /**
431 * CRM-20892 Add Tests of new timestamp checking function
7f1a780c 432 *
433 * @throws \CRM_Core_Exception
1f87b2a5
SL
434 */
435 public function testTimeStampChecking() {
436 CRM_Core_DAO::executeQuery("INSERT INTO civicrm_mailing (id, modified_date) VALUES (25, '2016-06-30 12:52:52')");
437 $this->assertTrue(_civicrm_api3_compare_timestamps('2017-02-15 16:00:00', 25, 'Mailing'));
9099cab3 438 $this->callAPISuccess('Mailing', 'create', ['id' => 25, 'subject' => 'Test Subject']);
1f87b2a5 439 $this->assertFalse(_civicrm_api3_compare_timestamps('2017-02-15 16:00:00', 25, 'Mailing'));
9099cab3 440 $this->callAPISuccess('Mailing', 'delete', ['id' => 25]);
1f87b2a5
SL
441 }
442
7f1a780c 443 /**
444 * Test that the foreign key constraint test correctly interprets pseudoconstants.
445 *
446 * @throws \CRM_Core_Exception
447 * @throws \API_Exception
448 */
449 public function testKeyConstraintCheck() {
450 $fieldInfo = $this->callAPISuccess('Contribution', 'getfields', [])['values']['financial_type_id'];
451 _civicrm_api3_validate_constraint(1, 'financial_type_id', $fieldInfo, 'Contribution');
452 _civicrm_api3_validate_constraint('Donation', 'financial_type_id', $fieldInfo, 'Contribution');
453 try {
454 _civicrm_api3_validate_constraint('Blah', 'financial_type_id', $fieldInfo, 'Contribution');
455 }
456 catch (API_Exception $e) {
457 $this->assertEquals("'Blah' is not a valid option for field financial_type_id", $e->getMessage());
458 return;
459 }
460 $this->fail('Last function call should have thrown an exception');
461 }
462
6a488035 463}