widget /tests/WidgetTest/EscapeTest.php

Language PHP Lines 492
MD5 Hash d5bf3dce1a5ba2156d8006ab7a1e531c
Repository https://github.com/putersham/widget.git View Raw File
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 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
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
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
<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace WidgetTest;

use Widget\Escape as Escaper;

/**
 * The test case derived from https://raw.github.com/zendframework/zf2/master/tests/ZendTest/Escaper/EscaperTest.php
 */
class EscapeTest extends TestCase
{
    /**
     * All character encodings supported by htmlspecialchars()
     */
    protected $supportedEncodings = array(
        'iso-8859-1',   'iso8859-1',    'iso-8859-5',   'iso8859-5',
        'iso-8859-15',  'iso8859-15',   'utf-8',        'cp866',
        'ibm866',       '866',          'cp1251',       'windows-1251',
        'win-1251',     '1251',         'cp1252',       'windows-1252',
        '1252',         'koi8-r',       'koi8-ru',      'koi8r',
        'big5',         '950',          'gb2312',       '936',
        'big5-hkscs',   'shift_jis',    'sjis',         'sjis-win',
        'cp932',        '932',          'euc-jp',       'eucjp',
        'eucjp-win',    'macroman'
    );

    protected $htmlSpecialChars = array(
        '\''    => '&#039;',
        '"'     => '&quot;',
        '<'     => '&lt;',
        '>'     => '&gt;',
        '&'     => '&amp;'
    );

    protected $htmlAttrSpecialChars = array(
        '\''    => '&#x27;',
        '"'     => '&quot;',
        '<'     => '&lt;',
        '>'     => '&gt;',
        '&'     => '&amp;',
        /* Characters beyond ASCII value 255 to unicode escape */
        'Ā'     => '&#x0100;',
        /* Immune chars excluded */
        ','     => ',',
        '.'     => '.',
        '-'     => '-',
        '_'     => '_',
        /* Basic alnums exluded */
        'a'     => 'a',
        'A'     => 'A',
        'z'     => 'z',
        'Z'     => 'Z',
        '0'     => '0',
        '9'     => '9',
        /* Basic control characters and null */
        "\r"    => '&#x0D;',
        "\n"    => '&#x0A;',
        "\t"    => '&#x09;',
        "\0"    => '&#xFFFD;', // should use Unicode replacement char
        /* Encode chars as named entities where possible */
        '<'     => '&lt;',
        '>'     => '&gt;',
        '&'     => '&amp;',
        '"'     => '&quot;',
        /* Encode spaces for quoteless attribute protection */
        ' '     => '&#x20;',
    );

    protected $jsSpecialChars = array(
        /* HTML special chars - escape without exception to hex */
        '<'     => '\\x3C',
        '>'     => '\\x3E',
        '\''    => '\\x27',
        '"'     => '\\x22',
        '&'     => '\\x26',
        /* Characters beyond ASCII value 255 to unicode escape */
        'Ā'     => '\\u0100',
        /* Immune chars excluded */
        ','     => ',',
        '.'     => '.',
        '_'     => '_',
        /* Basic alnums exluded */
        'a'     => 'a',
        'A'     => 'A',
        'z'     => 'z',
        'Z'     => 'Z',
        '0'     => '0',
        '9'     => '9',
        /* Basic control characters and null */
        "\r"    => '\\x0D',
        "\n"    => '\\x0A',
        "\t"    => '\\x09',
        "\0"    => '\\x00',
        /* Encode spaces for quoteless attribute protection */
        ' '     => '\\x20',
    );

    protected $urlSpecialChars = array(
        /* HTML special chars - escape without exception to percent encoding */
        '<'     => '%3C',
        '>'     => '%3E',
        '\''    => '%27',
        '"'     => '%22',
        '&'     => '%26',
        /* Characters beyond ASCII value 255 to hex sequence */
        'Ā'     => '%C4%80',
        /* Punctuation and unreserved check */
        ','     => '%2C',
        '.'     => '.',
        '_'     => '_',
        '-'     => '-',
        ':'     => '%3A',
        ';'     => '%3B',
        '!'     => '%21',
        /* Basic alnums excluded */
        'a'     => 'a',
        'A'     => 'A',
        'z'     => 'z',
        'Z'     => 'Z',
        '0'     => '0',
        '9'     => '9',
        /* Basic control characters and null */
        "\r"    => '%0D',
        "\n"    => '%0A',
        "\t"    => '%09',
        "\0"    => '%00',
        /* PHP quirks from the past */
        ' '     => '%20',
        '~'     => '~',
        '+'     => '%2B',
    );

    protected $cssSpecialChars = array(
        /* HTML special chars - escape without exception to hex */
        '<'     => '\\3C ',
        '>'     => '\\3E ',
        '\''    => '\\27 ',
        '"'     => '\\22 ',
        '&'     => '\\26 ',
        /* Characters beyond ASCII value 255 to unicode escape */
        'Ā'     => '\\100 ',
        /* Immune chars excluded */
        ','     => '\\2C ',
        '.'     => '\\2E ',
        '_'     => '\\5F ',
        /* Basic alnums exluded */
        'a'     => 'a',
        'A'     => 'A',
        'z'     => 'z',
        'Z'     => 'Z',
        '0'     => '0',
        '9'     => '9',
        /* Basic control characters and null */
        "\r"    => '\\D ',
        "\n"    => '\\A ',
        "\t"    => '\\9 ',
        "\0"    => '\\0 ',
        /* Encode spaces for quoteless attribute protection */
        ' '     => '\\20 ',
    );


    public function setUp()
    {
        $this->escaper = new Escaper(array(
            'encoding' => 'utf-8'
        ));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testSettingEncodingToEmptyStringShouldThrowException()
    {
        $escaper = new Escaper(array(
            'encoding' => ''
        ));
    }

    public function testSettingValidEncodingShouldNotThrowExceptions()
    {
        foreach ($this->supportedEncodings as $value) {
            $escaper = new Escaper(array(
                'encoding' => $value
            ));
        }
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testSettingEncodingToInvalidValueShouldThrowException()
    {
        $escaper = new Escaper(array(
            'encoding' => 'invalid-encoding'
        ));
    }

    public function testReturnsEncodingFromGetter()
    {
        $this->assertEquals('utf-8', $this->escaper->getEncoding());
    }

    public function testHtmlEscapingConvertsSpecialChars()
    {
        foreach ($this->htmlSpecialChars as $key => $value) {
            $this->assertEquals(
                $value,
                $this->escaper->escapeHtml($key),
                'Failed to escape: ' . $key
            );

            // call by alias
            $this->assertEquals(
                $value,
                $this->escaper->html($key)
            );

            // call by widget
            $this->assertEquals(
                $value,
                $this->escape($key, 'html')
            );
        }
    }

    public function testHtmlAttributeEscapingConvertsSpecialChars()
    {
        foreach ($this->htmlAttrSpecialChars as $key => $value) {
            $this->assertEquals(
                $value,
                $this->escaper->escapeHtmlAttr($key),
                'Failed to escape: ' . $key
            );

            // call by alias
            $this->assertEquals(
                $value,
                $this->escaper->attr($key)
            );

            // call by widget
            $this->assertEquals(
                $value,
                $this->escape($key, 'attr')
            );
        }
    }

    public function testJavascriptEscapingConvertsSpecialChars()
    {
        foreach ($this->jsSpecialChars as $key => $value) {
            $this->assertEquals(
                $value,
                $this->escaper->escapeJs($key),
                'Failed to escape: ' . $key
            );
        }

        // call by alias
            $this->assertEquals(
                $value,
                $this->escaper->js($key)
            );

            // call by widget
            $this->assertEquals(
                $value,
                $this->escape($key, 'js')
            );
    }

    public function testJavascriptEscapingReturnsStringIfZeroLength()
    {
        $this->assertEquals('', $this->escaper->escapeJs(''));
    }

    public function testJavascriptEscapingReturnsStringIfContainsOnlyDigits()
    {
        $this->assertEquals('123', $this->escaper->escapeJs('123'));
    }

    public function testCssEscapingConvertsSpecialChars()
    {
        foreach ($this->cssSpecialChars as $key => $value) {
            $this->assertEquals(
                $value,
                $this->escaper->escapeCss($key),
                'Failed to escape: ' . $key
            );

            // call by alias
            $this->assertEquals(
                $value,
                $this->escaper->css($key)
            );

            // call by widget
            $this->assertEquals(
                $value,
                $this->escape($key, 'css')
            );
        }
    }

    public function testCssEscapingReturnsStringIfZeroLength()
    {
        $this->assertEquals('', $this->escaper->escapeCss(''));
    }

    public function testCssEscapingReturnsStringIfContainsOnlyDigits()
    {
        $this->assertEquals('123', $this->escaper->escapeCss('123'));
    }

    public function testUrlEscapingConvertsSpecialChars()
    {
        foreach ($this->urlSpecialChars as $key => $value) {
            $this->assertEquals(
                $value,
                $this->escaper->escapeUrl($key),
                'Failed to escape: ' . $key
            );

            // call by alias
            $this->assertEquals(
                $value,
                $this->escaper->url($key)
            );

            // call by widget
            $this->assertEquals(
                $value,
                $this->escape($key, 'url')
            );
        }
    }

    /**
     * Range tests to confirm escaped range of characters is within OWASP recommendation
     */

    /**
     * Only testing the first few 2 ranges on this prot. function as that's all these
     * other range tests require
     */
    public function testUnicodeCodepointConversionToUtf8()
    {
        $expected = " ~ޙ";
        $codepoints = array(0x20, 0x7e, 0x799);
        $result = '';
        foreach ($codepoints as $value) {
            $result .= $this->codepointToUtf8($value);
        }
        $this->assertEquals($expected, $result);
    }

    /**
     * Convert a Unicode Codepoint to a literal UTF-8 character.
     *
     * @param int Unicode codepoint in hex notation
     * @return string UTF-8 literal string
     */
    protected function codepointToUtf8($codepoint)
    {
        if ($codepoint < 0x80) {
            return chr($codepoint);
        }
        if ($codepoint < 0x800) {
            return chr($codepoint >> 6 & 0x3f | 0xc0)
                . chr($codepoint & 0x3f | 0x80);
        }
        if ($codepoint < 0x10000) {
            return chr($codepoint >> 12 & 0x0f | 0xe0)
                . chr($codepoint >> 6 & 0x3f | 0x80)
                . chr($codepoint & 0x3f | 0x80);
        }
        if ($codepoint < 0x110000) {
            return chr($codepoint >> 18 & 0x07 | 0xf0)
                . chr($codepoint >> 12 & 0x3f | 0x80)
                . chr($codepoint >> 6 & 0x3f | 0x80)
                . chr($codepoint & 0x3f | 0x80);
        }
        throw new \Exception('Codepoint requested outside of Unicode range');
    }

    public function testJavascriptEscapingEscapesOwaspRecommendedRanges()
    {
        $immune = array(',', '.', '_'); // Exceptions to escaping ranges
        for ($chr=0; $chr < 0xFF; $chr++) {
            if ($chr >= 0x30 && $chr <= 0x39
                || $chr >= 0x41 && $chr <= 0x5A
                || $chr >= 0x61 && $chr <= 0x7A
            ) {
                $literal = $this->codepointToUtf8($chr);
                $this->assertEquals($literal, $this->escaper->escapeJs($literal));
            } else {
                $literal = $this->codepointToUtf8($chr);
                if (in_array($literal, $immune)) {
                    $this->assertEquals($literal, $this->escaper->escapeJs($literal));
                } else {
                    $this->assertNotEquals(
                        $literal,
                        $this->escaper->escapeJs($literal),
                        $literal . ' should be escaped!'
                    );
                }
            }
        }
    }

    public function testHtmlAttributeEscapingEscapesOwaspRecommendedRanges()
    {
        $immune = array(',', '.', '-', '_'); // Exceptions to escaping ranges
        for ($chr=0; $chr < 0xFF; $chr++) {
            if ($chr >= 0x30 && $chr <= 0x39
                || $chr >= 0x41 && $chr <= 0x5A
                || $chr >= 0x61 && $chr <= 0x7A
            ) {
                $literal = $this->codepointToUtf8($chr);
                $this->assertEquals($literal, $this->escaper->escapeHtmlAttr($literal));
            } else {
                $literal = $this->codepointToUtf8($chr);
                if (in_array($literal, $immune)) {
                    $this->assertEquals($literal, $this->escaper->escapeHtmlAttr($literal));
                } else {
                    $this->assertNotEquals(
                        $literal,
                        $this->escaper->escapeHtmlAttr($literal),
                        $literal . ' should be escaped!'
                    );
                }
            }
        }
    }

    public function testCssEscapingEscapesOwaspRecommendedRanges()
    {
        $immune = array(); // CSS has no exceptions to escaping ranges
        for ($chr=0; $chr < 0xFF; $chr++) {
            if ($chr >= 0x30 && $chr <= 0x39
                || $chr >= 0x41 && $chr <= 0x5A
                || $chr >= 0x61 && $chr <= 0x7A
            ) {
                $literal = $this->codepointToUtf8($chr);
                $this->assertEquals($literal, $this->escaper->escapeCss($literal));
            } else {
                $literal = $this->codepointToUtf8($chr);
                $this->assertNotEquals(
                    $literal,
                    $this->escaper->escapeCss($literal),
                    $literal . ' should be escaped!'
                );
            }
        }
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testInvokeUnsupportedTypeShouldThrowException()
    {
        $this->escape('string', 'unsupport-type');
    }

    public function providerForEmptyVar()
    {
        return array(
            array(''),
            array(null),
            array(0),
            array('0'),
        );
    }

    /**
     * @dataProvider providerForEmptyVar
     */
    public function testEmptyVar($value)
    {
        foreach (array('html', 'js', 'css', 'url', 'attr') as $method) {
            $this->assertSame($value, $this->escaper->$method($value));
        }
    }
}
Back to Top