Passed
Push — master ( 67d090...ef03d0 )
by Thomas
15:00
created

EncryptedDBField::addToQuery()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
namespace LeKoala\Encrypt;
4
5
use Exception;
6
use SilverStripe\ORM\DataList;
7
use SilverStripe\ORM\DataObject;
8
use SilverStripe\Forms\FormField;
9
use SilverStripe\Forms\TextField;
10
use ParagonIE\CipherSweet\BlindIndex;
11
use ParagonIE\CipherSweet\CipherSweet;
12
use SilverStripe\ORM\Queries\SQLSelect;
13
use ParagonIE\CipherSweet\EncryptedField;
14
use SilverStripe\ORM\FieldType\DBComposite;
15
16
/**
17
 * Value will be set on parent record through built in getField
18
 * mechanisms for composite fields
19
 */
20
class EncryptedDBField extends DBComposite
21
{
22
    use HasBaseEncryption;
23
24
    const LARGE_INDEX_SIZE = 32;
25
    const SMALL_INDEX_SIZE = 16;
26
    const VALUE_SUFFIX = "Value";
27
    const INDEX_SUFFIX = "BlindIndex";
28
29
    /**
30
     * @config
31
     * @var int
32
     */
33
    private static $output_size = 15;
0 ignored issues
show
introduced by
The private property $output_size is not used, and could be removed.
Loading history...
34
35
    /**
36
     * @config
37
     * @var int
38
     */
39
    private static $domain_size = 127;
0 ignored issues
show
introduced by
The private property $domain_size is not used, and could be removed.
Loading history...
40
41
    /**
42
     * @var array<string,string>
43
     */
44
    private static $composite_db = array(
0 ignored issues
show
introduced by
The private property $composite_db is not used, and could be removed.
Loading history...
45
        "Value" => "Varchar(191)",
46
        "BlindIndex" => 'Varchar(32)',
47
    );
48
49
    /**
50
     * Output size is the number of bits (not bytes) of a blind index.
51
     * Eg: 4 for a 4 digits year
52
     * Note: the larger the output size, the smaller the index should be
53
     * @return int
54
     */
55
    public function getOutputSize()
56
    {
57
        if (array_key_exists('output_size', $this->options)) {
58
            $outputSize = $this->options['output_size'];
59
        } else {
60
            $outputSize = static::config()->get('output_size');
61
        }
62
        return $outputSize;
63
    }
64
65
    /**
66
     * Input domain is the set of all possible distinct inputs.
67
     * Eg : 4 digits have 10,000 possible values (10^4). The log (base 2) of 10,000 is 13.2877; you would want to always round up (so 14).
68
     * @return int
69
     */
70
    public function getDomainSize()
71
    {
72
        if (array_key_exists('domain_size', $this->options)) {
73
            $domainSize = $this->options['domain_size'];
74
        } else {
75
            $domainSize = static::config()->get('domain_size');
76
        }
77
        return $domainSize;
78
    }
79
80
    /**
81
     * @param int $default
82
     * @return int
83
     */
84
    public function getIndexSize($default = null)
85
    {
86
        if (array_key_exists('index_size', $this->options)) {
87
            return $this->options['index_size'];
88
        }
89
        if ($default !== null) {
90
            return $default;
91
        }
92
        return self::LARGE_INDEX_SIZE;
93
    }
94
95
    /**
96
     * @return string
97
     */
98
    public function getValueField()
99
    {
100
        return $this->getField(self::VALUE_SUFFIX);
101
    }
102
103
    /**
104
     * @param mixed $value
105
     * @param bool $markChanged
106
     * @return $this
107
     */
108
    public function setValueField($value, $markChanged = true)
109
    {
110
        return $this->setField(self::VALUE_SUFFIX, $value, $markChanged);
111
    }
112
113
    /**
114
     * @return string
115
     */
116
    public function getBlindIndexField()
117
    {
118
        return $this->getField(self::INDEX_SUFFIX);
119
    }
120
121
    /**
122
     * @param mixed $value
123
     * @param bool $markChanged
124
     * @return $this
125
     */
126
    public function setBlindIndexField($value, $markChanged = true)
127
    {
128
        return $this->setField(self::INDEX_SUFFIX, $value, $markChanged);
129
    }
130
131
    /**
132
     * @param CipherSweet $engine
133
     * @param bool $fashHash
134
     * @return EncryptedField
135
     */
136
    public function getEncryptedField($engine = null, $fashHash = null)
137
    {
138
        if ($engine === null) {
139
            $engine = EncryptHelper::getCipherSweet();
140
        }
141
        if ($fashHash === null) {
142
            $fashHash = EncryptHelper::getFashHash();
143
        }
144
        $indexSize = $this->getIndexSize(self::LARGE_INDEX_SIZE);
145
146
        //TODO: review how naming is done (see: getEncryptedRow)
147
        // fieldName needs to match exact db name for row rotator to work properly
148
        $fieldName = $this->name . self::VALUE_SUFFIX;
149
        $indexName = $this->name . self::INDEX_SUFFIX;
150
151
        $encryptedField = (new EncryptedField($engine, $this->tableName, $fieldName))
152
            ->addBlindIndex(new BlindIndex($indexName, [], $indexSize, $fashHash));
153
        return $encryptedField;
154
    }
155
156
    /**
157
     * This is not called anymore, we rely on saveInto for now
158
     * @link https://github.com/silverstripe/silverstripe-framework/issues/8800
159
     * @link https://github.com/silverstripe/silverstripe-framework/pull/10913
160
     * @param array<string,mixed> $manipulation
161
     * @return void
162
     */
163
    public function writeToManipulation(&$manipulation)
164
    {
165
        $encryptedField = $this->getEncryptedField();
166
        $aad = $this->encryptionAad;
167
        if ($this->value) {
168
            $dataForStorage = $encryptedField->prepareForStorage($this->value, $aad);
169
            $encryptedValue = $this->prepValueForDB($dataForStorage[0]);
170
            /** @var array<string,string> $blindIndexes */
171
            $blindIndexes = $dataForStorage[1];
172
        } else {
173
            $encryptedValue = null;
174
            $blindIndexes = [];
175
        }
176
177
        $manipulation['fields'][$this->name . self::VALUE_SUFFIX] = $encryptedValue;
178
        foreach ($blindIndexes as $blindIndexName => $blindIndexValue) {
179
            $manipulation['fields'][$blindIndexName] = $blindIndexValue;
180
        }
181
    }
182
183
    /**
184
     * @param SQLSelect $query
185
     * @return void
186
     */
187
    // public function addToQuery(&$query)
188
    // {
189
    //     parent::addToQuery($query);
190
    //     $query->selectField(sprintf('"%s' . self::VALUE_SUFFIX . '"', $this->name));
191
    //     $query->selectField(sprintf('"%s' . self::INDEX_SUFFIX . '"', $this->name));
192
    // }
193
194
    /**
195
     * Return the blind index value to search in the database
196
     *
197
     * @param string $val The unencrypted value
198
     * @param string $indexSuffix The blind index. Defaults to full index
199
     * @return string
200
     */
201
    public function getSearchValue($val, $indexSuffix = null)
202
    {
203
        if (!$this->tableName && $this->record && is_object($this->record)) {
204
            $this->tableName = DataObject::getSchema()->tableName(get_class($this->record));
205
        }
206
        if (!$this->tableName) {
207
            throw new Exception("Table name not set for search value. Please set a dataobject.");
208
        }
209
        if (!$this->name) {
210
            throw new Exception("Name not set for search value");
211
        }
212
        if ($indexSuffix === null) {
213
            $indexSuffix = self::INDEX_SUFFIX;
214
        }
215
        $field = $this->getEncryptedField();
216
        $index = $field->getBlindIndex($val, $this->name . $indexSuffix);
217
        if (is_array($index)) {
218
            return $index['value'];
219
        }
220
        return $index;
221
    }
222
223
    /**
224
     * Return a ready to use array params for a where clause
225
     *
226
     * @param string $val The unencrypted value
227
     * @param string $indexSuffix The blind index. Defaults to full index
228
     * @return array<string,string>
229
     */
230
    public function getSearchParams($val, $indexSuffix = null)
231
    {
232
        if (!$indexSuffix) {
233
            $indexSuffix = self::INDEX_SUFFIX;
234
        }
235
        $searchValue = $this->getSearchValue($val, $indexSuffix);
236
        $blindIndexField = $this->name . $indexSuffix;
237
        return array($blindIndexField . ' = ?' => $searchValue);
238
    }
239
240
    /**
241
     * @param string $val The unencrypted value
242
     * @param string $indexSuffix The blind index. Defaults to full index
243
     * @return DataList
244
     */
245
    public function fetchDataList($val, $indexSuffix = null)
246
    {
247
        if (!$this->record || !is_object($this->record)) {
248
            throw new Exception("No record set for this field");
249
        }
250
        if (!$indexSuffix) {
251
            $indexSuffix = self::INDEX_SUFFIX;
252
        }
253
        $class = get_class($this->record);
254
255
        // A blind index can return false positives
256
        $params = $this->getSearchParams($val, $indexSuffix);
257
        $blindIndexes = $this->getEncryptedField()->getBlindIndexObjects();
0 ignored issues
show
Unused Code introduced by
The assignment to $blindIndexes is dead and can be removed.
Loading history...
258
        $list = $class::get()->where($params);
259
        return $list;
260
    }
261
262
    /**
263
     * @param string $val The unencrypted value
264
     * @param string $indexSuffix The blind index. Defaults to full index
265
     * @return DataObject|false
266
     */
267
    public function fetchRecord($val, $indexSuffix = null)
268
    {
269
        if (!$indexSuffix) {
270
            $indexSuffix = self::INDEX_SUFFIX;
271
        }
272
        $list = $this->fetchDataList($val, $indexSuffix);
273
        $blindIndexes = $this->getEncryptedField()->getBlindIndexObjects();
274
        $blindIndex = $blindIndexes[$this->name . $indexSuffix];
275
        $name = $this->name;
276
        /** @var DataObject $record  */
277
        foreach ($list as $record) {
278
            $obj = $record->dbObject($name);
279
            // Value might be transformed
280
            if ($blindIndex->getTransformed($obj->getValue()) == $val) {
281
                return $record;
282
            }
283
        }
284
        // throw exception if there where matches but none with the right value
285
        if ($list->count()) {
286
            throw new Exception($list->count() . " records were found but none matched the right value");
287
        }
288
        return false;
289
    }
290
291
    public function setValue($value, $record = null, $markChanged = true)
292
    {
293
        $this->setEncryptionAad($record);
294
295
        // Return early if we keep encrypted value in memory
296
        if (!EncryptHelper::getAutomaticDecryption()) {
297
            parent::setValue($value, $record, $markChanged);
298
            return $this;
299
        }
300
301
        if ($markChanged) {
302
            $this->isChanged = true;
303
        }
304
305
        // When given a dataobject, bind this field to that
306
        if ($record instanceof DataObject) {
307
            $this->bindTo($record);
308
        }
309
310
        // Convert an object to an array
311
        if ($record && $record instanceof DataObject) {
312
            $record = $record->getQueriedDatabaseFields();
313
            if (!$record) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $record of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
314
                throw new Exception("Could not convert record to array");
315
            }
316
        }
317
318
        // Set the table name if it was not set earlier
319
        if (!$this->tableName && $record) {
320
            $class = is_array($record) && isset($record['ClassName']) ? $record['ClassName'] : get_class($record);
321
            $this->tableName = DataObject::getSchema()->tableName($class);
322
            if (!$this->tableName) {
323
                throw new Exception("Could not get table name from record from " . gettype($record));
324
            }
325
        }
326
327
        // Value will store the decrypted value
328
        if ($value instanceof EncryptedDBField) {
329
            $this->value = $value->getValue();
330
        } elseif ($record && isset($record[$this->name . self::VALUE_SUFFIX])) {
331
            // In that case, the value come from the database and might be encrypted
332
            $encryptedValue = $record[$this->name . self::VALUE_SUFFIX];
333
            $this->value = $this->decryptValue($encryptedValue);
334
        } elseif (is_array($value)) {
335
            if (array_key_exists(self::VALUE_SUFFIX, $value)) {
336
                $this->value = $value;
337
            }
338
        } elseif (is_string($value) || !$value) {
339
            $this->value = $value;
340
        } else {
341
            throw new Exception("Unexcepted value of type " . gettype($value));
342
        }
343
344
        // Forward changes since writeToManipulation are not called
345
        // $this->setValueField($value, $markChanged);
346
347
        return $this;
348
    }
349
350
    /**
351
     * @param array<string,mixed> $options
352
     * @return string
353
     */
354
    public function Nice($options = array())
0 ignored issues
show
Unused Code introduced by
The parameter $options is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

354
    public function Nice(/** @scrutinizer ignore-unused */ $options = array())

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
355
    {
356
        return $this->getValue();
357
    }
358
359
    /**
360
     * @return boolean
361
     */
362
    public function exists()
363
    {
364
        return strlen($this->value ?? '') > 0;
365
    }
366
367
    /**
368
     * This is called by getChangedFields() to check if a field is changed
369
     *
370
     * @return boolean
371
     */
372
    public function isChanged()
373
    {
374
        return $this->isChanged;
375
    }
376
377
    /**
378
     * If we pass a DBField to the setField method, it will
379
     * trigger this method
380
     *
381
     * We save encrypted value on sub fields. They will be collected
382
     * by write() operation by prepareManipulationTable
383
     *
384
     * Currently prepareManipulationTable ignores composite fields
385
     * so we rely on the sub field mechanisms
386
     *
387
     * @param DataObject $dataObject
388
     * @return void
389
     */
390
    public function saveInto($dataObject)
391
    {
392
        $encryptedField = $this->getEncryptedField();
393
        $aad = $this->encryptionAad;
394
        if ($this->value) {
395
            $dataForStorage = $encryptedField->prepareForStorage($this->value, $aad);
396
            $encryptedValue = $this->prepValueForDB($dataForStorage[0]);
397
            /** @var array<string,string> $blindIndexes */
398
            $blindIndexes = $dataForStorage[1];
399
        } else {
400
            $encryptedValue = null;
401
            $blindIndexes = [];
402
        }
403
404
        // This cause infinite loops
405
        // $dataObject->setField($this->getName(), $this->value);
406
407
        // Encrypt value
408
        $key = $this->getName() . self::VALUE_SUFFIX;
409
        $dataObject->setField($key, $encryptedValue);
410
411
        // Build blind indexes
412
        foreach ($blindIndexes as $blindIndexName => $blindIndexValue) {
413
            $dataObject->setField($blindIndexName, $blindIndexValue);
414
        }
415
    }
416
417
    /**
418
     * @param string $title Optional. Localized title of the generated instance
419
     * @param array<mixed> $params
420
     * @return FormField
421
     */
422
    public function scaffoldFormField($title = null, $params = null)
423
    {
424
        $field = TextField::create($this->getName());
425
        return $field;
426
    }
427
428
    /**
429
     * Returns the string value
430
     */
431
    public function __toString()
432
    {
433
        return (string) $this->getValue();
434
    }
435
436
    public function scalarValueOnly()
437
    {
438
        return false;
439
    }
440
}
441