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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
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
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
941
942
943
944
945
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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text.Internal;
using System.Text.Unicode;
using Xunit;
namespace System.Text.Encodings.Web.Tests
{
public partial class JavaScriptStringEncoderTests
{
[Fact]
public unsafe void NullPtrThrows()
{
Assert.Throws<ArgumentNullException>(() => JavaScriptEncoder.Default.FindFirstCharacterToEncode(null, 0));
Assert.Throws<ArgumentNullException>(() => JavaScriptEncoder.UnsafeRelaxedJsonEscaping.FindFirstCharacterToEncode(null, 0));
Assert.Throws<ArgumentNullException>(() => JavaScriptEncoder.Create(UnicodeRanges.All).FindFirstCharacterToEncode(null, 0));
Assert.Throws<ArgumentNullException>(() => JavaScriptEncoder.Default.TryEncodeUnicodeScalar('a', null, 0, out _));
Assert.Throws<ArgumentNullException>(() => JavaScriptEncoder.UnsafeRelaxedJsonEscaping.TryEncodeUnicodeScalar('a', null, 0, out _));
Assert.Throws<ArgumentNullException>(() => JavaScriptEncoder.Create(UnicodeRanges.All).TryEncodeUnicodeScalar('a', null, 0, out _));
Assert.Throws<ArgumentNullException>(() => JavaScriptEncoder.Create((TextEncoderSettings)null));
Assert.Throws<ArgumentNullException>(() => JavaScriptEncoder.Create((UnicodeRange)null));
}
[Theory]
[MemberData(nameof(EscapingTestData))]
[MemberData(nameof(EscapingTestData_NonAscii))]
public unsafe void FindFirstCharacterToEncode(char replacementChar, JavaScriptEncoder encoder, bool requiresEscaping)
{
Assert.Equal(-1, encoder.FindFirstCharacterToEncodeUtf8(default));
fixed (char* ptr = string.Empty)
{
Assert.Equal(-1, encoder.FindFirstCharacterToEncode(ptr, 0));
}
var random = new Random(42);
for (int dataLength = 0; dataLength < 50; dataLength++)
{
char[] str = new char[dataLength];
for (int i = 0; i < dataLength; i++)
{
str[i] = (char)random.Next(97, 123);
}
string baseStr = new string(str);
byte[] sourceUtf8 = Encoding.UTF8.GetBytes(baseStr);
Assert.Equal(-1, encoder.FindFirstCharacterToEncodeUtf8(sourceUtf8));
fixed (char* ptr = baseStr)
{
Assert.Equal(-1, encoder.FindFirstCharacterToEncode(ptr, baseStr.Length));
}
for (int i = 0; i < dataLength; i++)
{
char[] changed = baseStr.ToCharArray();
changed[i] = replacementChar;
string source = new string(changed);
sourceUtf8 = Encoding.UTF8.GetBytes(source);
Assert.Equal(requiresEscaping ? i : -1, encoder.FindFirstCharacterToEncodeUtf8(sourceUtf8));
fixed (char* ptr = source)
{
Assert.Equal(requiresEscaping ? i : -1, encoder.FindFirstCharacterToEncode(ptr, source.Length));
}
}
if (dataLength != 0)
{
char[] changed = baseStr.ToCharArray();
changed.AsSpan().Fill(replacementChar);
string source = new string(changed);
sourceUtf8 = Encoding.UTF8.GetBytes(source);
Assert.Equal(requiresEscaping ? 0 : -1, encoder.FindFirstCharacterToEncodeUtf8(sourceUtf8));
fixed (char* ptr = source)
{
Assert.Equal(requiresEscaping ? 0 : -1, encoder.FindFirstCharacterToEncode(ptr, source.Length));
}
}
}
}
public static IEnumerable<object[]> EscapingTestData
{
get
{
return new List<object[]>
{
new object[] { 'a', JavaScriptEncoder.Default, false }, // ASCII not escaped
new object[] { '\u001F', JavaScriptEncoder.Default, true }, // control character within single byte range
new object[] { '\u007F', JavaScriptEncoder.Default, true }, // control character, sbyte.MaxValue
new object[] { '\u2000', JavaScriptEncoder.Default, true }, // space character outside single byte range
new object[] { '\u00A2', JavaScriptEncoder.Default, true }, // non-ASCII but < 255
new object[] { '\uA686', JavaScriptEncoder.Default, true }, // non-ASCII above short.MaxValue
new object[] { '\u6C49', JavaScriptEncoder.Default, true }, // non-ASCII from chinese alphabet - multibyte
new object[] { '"', JavaScriptEncoder.Default, true }, // ASCII but must always be escaped in JSON
new object[] { '\\', JavaScriptEncoder.Default, true }, // ASCII but must always be escaped in JSON
new object[] { '<', JavaScriptEncoder.Default, true }, // ASCII but escaped by default
new object[] { '>', JavaScriptEncoder.Default, true }, // ASCII but escaped by default
new object[] { '&', JavaScriptEncoder.Default, true }, // ASCII but escaped by default
new object[] { '`', JavaScriptEncoder.Default, true }, // ASCII but escaped by default
new object[] { '\'', JavaScriptEncoder.Default, true }, // ASCII but escaped by default
new object[] { '+', JavaScriptEncoder.Default, true }, // ASCII but escaped by default
new object[] { '\uFFFD', JavaScriptEncoder.Default, true }, // Default replacement character
new object[] { 'a', JavaScriptEncoder.Create(UnicodeRanges.BasicLatin), false },
new object[] { '\u001F', JavaScriptEncoder.Create(UnicodeRanges.BasicLatin), true },
new object[] { '\u007F', JavaScriptEncoder.Create(UnicodeRanges.BasicLatin), true },
new object[] { '\u2000', JavaScriptEncoder.Create(UnicodeRanges.BasicLatin), true },
new object[] { '\u00A2', JavaScriptEncoder.Create(UnicodeRanges.BasicLatin), true },
new object[] { '\uA686', JavaScriptEncoder.Create(UnicodeRanges.BasicLatin), true },
new object[] { '\u6C49', JavaScriptEncoder.Create(UnicodeRanges.BasicLatin), true },
new object[] { '"', JavaScriptEncoder.Create(UnicodeRanges.BasicLatin), true },
new object[] { '\\', JavaScriptEncoder.Create(UnicodeRanges.BasicLatin), true },
new object[] { '<', JavaScriptEncoder.Create(UnicodeRanges.BasicLatin), true },
new object[] { '>', JavaScriptEncoder.Create(UnicodeRanges.BasicLatin), true },
new object[] { '&', JavaScriptEncoder.Create(UnicodeRanges.BasicLatin), true },
new object[] { '`', JavaScriptEncoder.Create(UnicodeRanges.BasicLatin), true },
new object[] { '\'', JavaScriptEncoder.Create(UnicodeRanges.BasicLatin), true },
new object[] { '+', JavaScriptEncoder.Create(UnicodeRanges.BasicLatin), true },
new object[] { '\uFFFD', JavaScriptEncoder.Create(UnicodeRanges.BasicLatin), true },
};
}
}
[Theory]
[MemberData(nameof(EscapingTestData_NonAscii))]
public unsafe void FindFirstCharacterToEncode_NonAscii(char replacementChar, JavaScriptEncoder encoder, bool requiresEscaping)
{
var random = new Random(42);
for (int dataLength = 1; dataLength < 50; dataLength++)
{
char[] str = new char[dataLength];
for (int i = 0; i < dataLength; i++)
{
str[i] = (char)random.Next(0x2E9B, 0x2EF4); // CJK Radicals Supplement characters
}
string baseStr = new string(str);
byte[] sourceUtf8 = Encoding.UTF8.GetBytes(baseStr);
Assert.Equal(-1, encoder.FindFirstCharacterToEncodeUtf8(sourceUtf8));
fixed (char* ptr = baseStr)
{
Assert.Equal(-1, encoder.FindFirstCharacterToEncode(ptr, baseStr.Length));
}
for (int i = 0; i < dataLength; i++)
{
string source = baseStr.Insert(i, new string(replacementChar, 1));
sourceUtf8 = Encoding.UTF8.GetBytes(source);
Assert.Equal(requiresEscaping ? i * 3 : -1, encoder.FindFirstCharacterToEncodeUtf8(sourceUtf8)); // Each CJK character expands to 3 utf-8 bytes.
fixed (char* ptr = source)
{
Assert.Equal(requiresEscaping ? i : -1, encoder.FindFirstCharacterToEncode(ptr, source.Length));
}
}
}
}
public static IEnumerable<object[]> EscapingTestData_NonAscii
{
get
{
return new List<object[]>
{
new object[] { 'a', JavaScriptEncoder.Create(UnicodeRanges.All), false },
new object[] { '\u001F', JavaScriptEncoder.Create(UnicodeRanges.All), true },
new object[] { '\u007F', JavaScriptEncoder.Create(UnicodeRanges.All), true },
new object[] { '\u2000', JavaScriptEncoder.Create(UnicodeRanges.All), true },
new object[] { '\u00A2', JavaScriptEncoder.Create(UnicodeRanges.All), false },
new object[] { '\uA686', JavaScriptEncoder.Create(UnicodeRanges.All), false },
new object[] { '\u6C49', JavaScriptEncoder.Create(UnicodeRanges.All), false },
new object[] { '"', JavaScriptEncoder.Create(UnicodeRanges.All), true },
new object[] { '\\', JavaScriptEncoder.Create(UnicodeRanges.All), true },
new object[] { '<', JavaScriptEncoder.Create(UnicodeRanges.All), true },
new object[] { '>', JavaScriptEncoder.Create(UnicodeRanges.All), true },
new object[] { '&', JavaScriptEncoder.Create(UnicodeRanges.All), true },
new object[] { '`', JavaScriptEncoder.Create(UnicodeRanges.All), true },
new object[] { '\'', JavaScriptEncoder.Create(UnicodeRanges.All), true },
new object[] { '+', JavaScriptEncoder.Create(UnicodeRanges.All), true },
new object[] { '\uFFFD', JavaScriptEncoder.Create(UnicodeRanges.All), false },
new object[] { 'a', JavaScriptEncoder.UnsafeRelaxedJsonEscaping, false },
new object[] { '\u001F', JavaScriptEncoder.UnsafeRelaxedJsonEscaping, true },
new object[] { '\u007F', JavaScriptEncoder.UnsafeRelaxedJsonEscaping, true },
new object[] { '\u2000', JavaScriptEncoder.UnsafeRelaxedJsonEscaping, true },
new object[] { '\u00A2', JavaScriptEncoder.UnsafeRelaxedJsonEscaping, false },
new object[] { '\uA686', JavaScriptEncoder.UnsafeRelaxedJsonEscaping, false },
new object[] { '\u6C49', JavaScriptEncoder.UnsafeRelaxedJsonEscaping, false },
new object[] { '"', JavaScriptEncoder.UnsafeRelaxedJsonEscaping, true },
new object[] { '\\', JavaScriptEncoder.UnsafeRelaxedJsonEscaping, true },
new object[] { '<', JavaScriptEncoder.UnsafeRelaxedJsonEscaping, false },
new object[] { '>', JavaScriptEncoder.UnsafeRelaxedJsonEscaping, false },
new object[] { '&', JavaScriptEncoder.UnsafeRelaxedJsonEscaping, false },
new object[] { '`', JavaScriptEncoder.UnsafeRelaxedJsonEscaping, false },
new object[] { '\'', JavaScriptEncoder.UnsafeRelaxedJsonEscaping, false },
new object[] { '+', JavaScriptEncoder.UnsafeRelaxedJsonEscaping, false },
new object[] { '\uFFFD', JavaScriptEncoder.UnsafeRelaxedJsonEscaping, false },
new object[] { 'a', new MyCustomEncoder(UnicodeRanges.All), false },
new object[] { '\u001F', new MyCustomEncoder(UnicodeRanges.All), true },
new object[] { '\u007F', new MyCustomEncoder(UnicodeRanges.All), true },
new object[] { '\u2000', new MyCustomEncoder(UnicodeRanges.All), true },
new object[] { '\u00A2', new MyCustomEncoder(UnicodeRanges.All), false },
new object[] { '\uA686', new MyCustomEncoder(UnicodeRanges.All), false },
new object[] { '\u6C49', new MyCustomEncoder(UnicodeRanges.All), false },
new object[] { '"', new MyCustomEncoder(UnicodeRanges.All), true },
new object[] { '\\', new MyCustomEncoder(UnicodeRanges.All), true },
new object[] { '<', new MyCustomEncoder(UnicodeRanges.All), true },
new object[] { '>', new MyCustomEncoder(UnicodeRanges.All), true },
new object[] { '&', new MyCustomEncoder(UnicodeRanges.All), true },
new object[] { '`', new MyCustomEncoder(UnicodeRanges.All), true },
new object[] { '\'', new MyCustomEncoder(UnicodeRanges.All), true },
new object[] { '+', new MyCustomEncoder(UnicodeRanges.All), true },
new object[] { '\uFFFD', new MyCustomEncoder(UnicodeRanges.All), false },
};
}
}
[Theory]
[MemberData(nameof(JavaScriptEncoders))]
public unsafe void EscapingTestWhileWritingSurrogate(JavaScriptEncoder encoder)
{
char highSurrogate = '\uD801';
char lowSurrogate = '\uDC37';
var random = new Random(42);
for (int dataLength = 2; dataLength < 50; dataLength++)
{
char[] str = new char[dataLength];
for (int i = 0; i < dataLength; i++)
{
str[i] = (char)random.Next(97, 123);
}
string baseStr = new string(str);
byte[] sourceUtf8 = Encoding.UTF8.GetBytes(baseStr);
Assert.Equal(-1, encoder.FindFirstCharacterToEncodeUtf8(sourceUtf8));
fixed (char* ptr = baseStr)
{
Assert.Equal(-1, encoder.FindFirstCharacterToEncode(ptr, baseStr.Length));
}
for (int i = 0; i < dataLength - 1; i++)
{
char[] changed = baseStr.ToCharArray();
changed[i] = highSurrogate;
changed[i + 1] = lowSurrogate;
string newStr = new string(changed);
sourceUtf8 = Encoding.UTF8.GetBytes(newStr);
Assert.Equal(i, encoder.FindFirstCharacterToEncodeUtf8(sourceUtf8));
fixed (char* ptr = newStr)
{
Assert.Equal(i, encoder.FindFirstCharacterToEncode(ptr, newStr.Length));
}
}
{
char[] changed = baseStr.ToCharArray();
for (int i = 0; i < changed.Length - 1; i += 2)
{
changed[i] = highSurrogate;
changed[i + 1] = lowSurrogate;
}
string newStr = new string(changed);
sourceUtf8 = Encoding.UTF8.GetBytes(newStr);
Assert.Equal(0, encoder.FindFirstCharacterToEncodeUtf8(sourceUtf8));
fixed (char* ptr = newStr)
{
Assert.Equal(0, encoder.FindFirstCharacterToEncode(ptr, newStr.Length));
}
}
}
}
public static IEnumerable<object[]> JavaScriptEncoders
{
get
{
return new List<object[]>
{
new object[] { JavaScriptEncoder.Default },
new object[] { JavaScriptEncoder.Create(UnicodeRanges.BasicLatin) },
new object[] { JavaScriptEncoder.Create(UnicodeRanges.All) },
new object[] { JavaScriptEncoder.UnsafeRelaxedJsonEscaping },
new object[] { new MyCustomEncoder(UnicodeRanges.BasicLatin) },
};
}
}
[Theory]
[MemberData(nameof(InvalidEscapingTestData))]
public unsafe void InvalidFindFirstCharacterToEncode(char replacementChar, JavaScriptEncoder encoder)
{
var random = new Random(42);
for (int dataLength = 0; dataLength < 47; dataLength++)
{
char[] str = new char[dataLength];
for (int i = 0; i < dataLength; i++)
{
str[i] = (char)random.Next(97, 123);
}
string baseStr = new string(str);
byte[] baseStrUtf8 = Encoding.UTF8.GetBytes(baseStr);
for (int i = 0; i < dataLength; i++)
{
char[] changed = baseStr.ToCharArray();
changed[i] = replacementChar;
string source = new string(changed);
byte[] sourceUtf8 = new byte[baseStrUtf8.Length];
baseStrUtf8.AsSpan().CopyTo(sourceUtf8);
sourceUtf8[i] = 0xC3; // Invalid, first byte of a 2-byte utf-8 character
Assert.Equal(i, encoder.FindFirstCharacterToEncodeUtf8(sourceUtf8));
fixed (char* ptr = source)
{
Assert.Equal(i, encoder.FindFirstCharacterToEncode(ptr, source.Length));
}
}
}
}
public static IEnumerable<object[]> InvalidEscapingTestData
{
get
{
return new List<object[]>
{
new object[] { '\uD801', JavaScriptEncoder.Default }, // Invalid, high surrogate alone
new object[] { '\uDC01', JavaScriptEncoder.Default }, // Invalid, low surrogate alone
new object[] { '\uD801', JavaScriptEncoder.UnsafeRelaxedJsonEscaping },
new object[] { '\uDC01', JavaScriptEncoder.UnsafeRelaxedJsonEscaping },
new object[] { '\uD801', JavaScriptEncoder.Create(UnicodeRanges.All) },
new object[] { '\uDC01', JavaScriptEncoder.Create(UnicodeRanges.All) },
new object[] { '\uD801', JavaScriptEncoder.Create(UnicodeRanges.BasicLatin) },
new object[] { '\uDC01', JavaScriptEncoder.Create(UnicodeRanges.BasicLatin) },
new object[] { '\uD801', new MyCustomEncoder(UnicodeRanges.BasicLatin) },
new object[] { '\uDC01', new MyCustomEncoder(UnicodeRanges.BasicLatin) },
};
}
}
internal sealed class MyCustomEncoder : JavaScriptEncoder
{
private readonly AllowedCharactersBitmap _allowedCharacters;
public MyCustomEncoder(TextEncoderSettings filter)
{
if (filter == null)
{
throw new ArgumentNullException(nameof(filter));
}
_allowedCharacters = filter.GetAllowedCharacters();
// Forbid codepoints which aren't mapped to characters or which are otherwise always disallowed
// (includes categories Cc, Cs, Co, Cn, Zs [except U+0020 SPACE], Zl, Zp)
_allowedCharacters.ForbidUndefinedCharacters();
// Forbid characters that are special in HTML.
// Even though this is a not HTML encoder,
// it's unfortunately common for developers to
// forget to HTML-encode a string once it has been JS-encoded,
// so this offers extra protection.
ForbidHtmlCharacters(_allowedCharacters);
// '\' (U+005C REVERSE SOLIDUS) must always be escaped in Javascript / ECMAScript / JSON.
// '/' (U+002F SOLIDUS) is not Javascript / ECMAScript / JSON-sensitive so doesn't need to be escaped.
_allowedCharacters.ForbidCharacter('\\');
// '`' (U+0060 GRAVE ACCENT) is ECMAScript-sensitive (see ECMA-262).
_allowedCharacters.ForbidCharacter('`');
}
internal static void ForbidHtmlCharacters(AllowedCharactersBitmap allowedCharacters)
{
allowedCharacters.ForbidCharacter('<');
allowedCharacters.ForbidCharacter('>');
allowedCharacters.ForbidCharacter('&');
allowedCharacters.ForbidCharacter('\''); // can be used to escape attributes
allowedCharacters.ForbidCharacter('\"'); // can be used to escape attributes
allowedCharacters.ForbidCharacter('+'); // technically not HTML-specific, but can be used to perform UTF7-based attacks
}
public MyCustomEncoder(params UnicodeRange[] allowedRanges) : this(new TextEncoderSettings(allowedRanges))
{ }
public override int MaxOutputCharactersPerInputCharacter => 12; // "\uFFFF\uFFFF" is the longest encoded form
public override unsafe bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten)
{
throw new NotImplementedException();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override unsafe int FindFirstCharacterToEncode(char* text, int textLength)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
return _allowedCharacters.FindFirstCharacterToEncode(text, textLength);
}
public override bool WillEncode(int unicodeScalar)
{
if (UnicodeHelpers.IsSupplementaryCodePoint(unicodeScalar))
{
return true;
}
Debug.Assert(unicodeScalar >= char.MinValue && unicodeScalar <= char.MaxValue);
return !_allowedCharacters.IsUnicodeScalarAllowed(unicodeScalar);
}
}
[Fact]
public void TestSurrogate()
{
// Encode(string)
Assert.Equal("\\uD83D\\uDCA9", System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode("\U0001f4a9"));
// Encode(writer, string)
using (var writer = new StringWriter())
{
System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode(writer, "\U0001f4a9");
Assert.Equal("\\uD83D\\uDCA9", writer.GetStringBuilder().ToString());
}
// Encode(Span, ...)
Span<char> destination = new char[12];
OperationStatus status = System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode(
"\U0001f4a9".AsSpan(), destination, out int charsConsumed, out int charsWritten, isFinalBlock: true);
Assert.Equal(OperationStatus.Done, status);
Assert.Equal(2, charsConsumed);
Assert.Equal(12, charsWritten);
Assert.Equal("\\uD83D\\uDCA9", new string(destination.Slice(0, charsWritten).ToArray()));
}
[Fact]
public void TestSurrogateBufferDoesNotUnderOrOverWrite()
{
Span<char> destination = new char[212];
destination[99] = 'x';
destination[112] = 'x';
// Pass in destination + 100 to check for underwrite.
OperationStatus status = System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode(
"\U0001f4a9".AsSpan(), destination.Slice(100, 12), out int charsConsumed, out int charsWritten, isFinalBlock: true);
Assert.Equal(OperationStatus.Done, status);
Assert.Equal(2, charsConsumed);
Assert.Equal(12, charsWritten);
Assert.Equal('x', destination[99]);
Assert.Equal('x', destination[112]);
}
[Fact]
public void TestSurrogateBufferOverlaps()
{
Span<char> destination = new char[100];
"\U0001f4a9".AsSpan().CopyTo(destination);
// Overlap behavior is undefined but documented that it is not valid. Here we don't expect any issues.
OperationStatus status = System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode(
destination.Slice(0, 2), destination, out int charsConsumed, out int charsWritten, isFinalBlock: true);
Assert.Equal(OperationStatus.Done, status);
Assert.Equal(2, charsConsumed);
Assert.Equal(12, charsWritten);
}
[Fact]
public void TestSurrogateBufferTooSmall()
{
Span<char> destination = new char[11];
OperationStatus status = System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode(
"\U0001f4a9".AsSpan(), destination, out int charsConsumed, out int charsWritten, isFinalBlock: true);
Assert.Equal(OperationStatus.DestinationTooSmall, status);
Assert.Equal(0, charsConsumed);
Assert.Equal(0, charsWritten);
}
[Fact]
public void JavaScriptStringEncoder_NonEmptySource_EmptyDest_Throws()
{
OperationStatus status = System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode(
"\U0001f4a9".AsSpan(), destination: null, out int _, out int _, isFinalBlock: true);
Assert.Equal(OperationStatus.DestinationTooSmall, status);
}
[Fact]
public void JavaScriptStringEncoder_EmptySource_EmptyDest()
{
OperationStatus status = System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode(
"".AsSpan(), destination: null, out int _, out int _, isFinalBlock: true);
Assert.Equal(OperationStatus.Done, status);
}
[Fact]
public void TestEmptySourceEncode()
{
// Encode(string)
Assert.Equal("", System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode(""));
// Encode(writer, string)
using (var writer = new StringWriter())
{
System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode(writer, "");
Assert.Equal("", writer.GetStringBuilder().ToString());
}
// Encode(Span, ...)
Span<char> destination = new char[12];
OperationStatus status = System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode(
"".AsSpan(), destination, out int charsConsumed, out int charsWritten, isFinalBlock: true);
Assert.Equal(OperationStatus.Done, status);
Assert.Equal(0, charsConsumed);
Assert.Equal(0, charsWritten);
Assert.Equal("", new string(destination.Slice(0, charsWritten).ToArray()));
destination = null; // null doesn't throw is no characters to encode
status = System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode(
"".AsSpan(), destination, out charsConsumed, out charsWritten, isFinalBlock: true);
Assert.Equal(OperationStatus.Done, status);
Assert.Equal(0, charsConsumed);
Assert.Equal(0, charsWritten);
Assert.Equal("", new string(destination.Slice(0, charsWritten).ToArray()));
}
[Fact]
public void Ctor_WithTextEncoderSettings()
{
// Arrange
var filter = new TextEncoderSettings();
filter.AllowCharacters('a', 'b');
filter.AllowCharacters('\0', '&', '\uFFFF', 'd');
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(filter);
// Act & assert
Assert.Equal("a", encoder.JavaScriptStringEncode("a"));
Assert.Equal("b", encoder.JavaScriptStringEncode("b"));
Assert.Equal(@"\u0063", encoder.JavaScriptStringEncode("c"));
Assert.Equal("d", encoder.JavaScriptStringEncode("d"));
Assert.Equal(@"\u0000", encoder.JavaScriptStringEncode("\0")); // we still always encode control chars
Assert.Equal(@"\u0026", encoder.JavaScriptStringEncode("&")); // we still always encode HTML-special chars
Assert.Equal(@"\uFFFF", encoder.JavaScriptStringEncode("\uFFFF")); // we still always encode non-chars and other forbidden chars
}
[Fact]
public void Ctor_WithUnicodeRanges()
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(UnicodeRanges.Latin1Supplement, UnicodeRanges.MiscellaneousSymbols);
// Act & assert
Assert.Equal(@"\u0061", encoder.JavaScriptStringEncode("a"));
Assert.Equal("\u00E9", encoder.JavaScriptStringEncode("\u00E9" /* LATIN SMALL LETTER E WITH ACUTE */));
Assert.Equal("\u2601", encoder.JavaScriptStringEncode("\u2601" /* CLOUD */));
}
[Fact]
public void Ctor_WithNoParameters_DefaultsToBasicLatin()
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder();
// Act & assert
Assert.Equal("a", encoder.JavaScriptStringEncode("a"));
Assert.Equal(@"\u00E9", encoder.JavaScriptStringEncode("\u00E9" /* LATIN SMALL LETTER E WITH ACUTE */));
Assert.Equal(@"\u2601", encoder.JavaScriptStringEncode("\u2601" /* CLOUD */));
}
[Fact]
public void Default_EquivalentToBasicLatin()
{
// Arrange
JavaScriptStringEncoder controlEncoder = new JavaScriptStringEncoder(UnicodeRanges.BasicLatin);
JavaScriptStringEncoder testEncoder = JavaScriptStringEncoder.Default;
// Act & assert
for (int i = 0; i <= char.MaxValue; i++)
{
if (!IsSurrogateCodePoint(i))
{
string input = new string((char)i, 1);
Assert.Equal(controlEncoder.JavaScriptStringEncode(input), testEncoder.JavaScriptStringEncode(input));
}
}
}
[Fact]
public void JavaScriptStringEncode_AllRangesAllowed_StillEncodesForbiddenChars_Simple_Escaping()
{
// The following two calls could be simply InlineData to the Theory below
// Unfortunately, the xUnit logger fails to escape the inputs when logging the test results,
// and so the suite fails despite all tests passing.
// TODO: I will try to fix it in xUnit, but for now this is a workaround to enable these tests.
JavaScriptStringEncode_AllRangesAllowed_StillEncodesForbiddenChars_Simple("\b", @"\b");
JavaScriptStringEncode_AllRangesAllowed_StillEncodesForbiddenChars_Simple("\f", @"\f");
}
[Theory]
[InlineData("<", @"\u003C")]
[InlineData(">", @"\u003E")]
[InlineData("&", @"\u0026")]
[InlineData("'", @"\u0027")]
[InlineData("\"", @"\u0022")]
[InlineData("+", @"\u002B")]
[InlineData("\\", @"\\")]
[InlineData("\n", @"\n")]
[InlineData("\t", @"\t")]
[InlineData("\r", @"\r")]
public void JavaScriptStringEncode_AllRangesAllowed_StillEncodesForbiddenChars_Simple(string input, string expected)
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(UnicodeRanges.All);
// Act
string retVal = encoder.JavaScriptStringEncode(input);
// Assert
Assert.Equal(expected, retVal);
}
[Fact]
public void JavaScriptStringEncode_AllRangesAllowed_StillEncodesForbiddenChars_Extended()
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(UnicodeRanges.All);
// Act & assert - BMP chars
for (int i = 0; i <= 0xFFFF; i++)
{
string input = new string((char)i, 1);
string expected;
if (IsSurrogateCodePoint(i))
{
expected = "\uFFFD"; // unpaired surrogate -> Unicode replacement char
}
else
{
if (input == "\b") { expected = @"\b"; }
else if (input == "\t") { expected = @"\t"; }
else if (input == "\n") { expected = @"\n"; }
else if (input == "\f") { expected = @"\f"; }
else if (input == "\r") { expected = @"\r"; }
else if (input == "\\") { expected = @"\\"; }
else if (input == "`") { expected = @"\u0060"; }
else
{
bool mustEncode = false;
switch (i)
{
case '<':
case '>':
case '&':
case '\"':
case '\'':
case '+':
mustEncode = true;
break;
}
if (i <= 0x001F || (0x007F <= i && i <= 0x9F))
{
mustEncode = true; // control char
}
else if (!UnicodeHelpers.IsCharacterDefined((char)i))
{
mustEncode = true; // undefined (or otherwise disallowed) char
}
if (mustEncode)
{
expected = string.Format(CultureInfo.InvariantCulture, @"\u{0:X4}", i);
}
else
{
expected = input; // no encoding
}
}
}
string retVal = encoder.JavaScriptStringEncode(input);
Assert.Equal(expected, retVal);
}
// Act & assert - astral chars
for (int i = 0x10000; i <= 0x10FFFF; i++)
{
string input = char.ConvertFromUtf32(i);
string expected = string.Format(CultureInfo.InvariantCulture, @"\u{0:X4}\u{1:X4}", (uint)input[0], (uint)input[1]);
string retVal = encoder.JavaScriptStringEncode(input);
Assert.Equal(expected, retVal);
}
}
[Fact]
public void JavaScriptStringEncode_NoRangesAllowed_EmitsShortFormForCertainCodePoints()
{
// This test ensures that when we're encoding, we always emit the "\uXXXX" form of the
// code point except for very specific code points where we allow a shorter representation.
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(UnicodeRanges.None); // allow no codepoints
// "[U+0000][U+0001]...[U+007F]"
string input = new string(Enumerable.Range(0, 128).Select(i => (char)i).ToArray());
// @"\u0000\u0001..\u007F", then replace certain specific code points
string expected = string.Concat(Enumerable.Range(0, 128).Select(i => FormattableString.Invariant($@"\u{i:X4}")));
expected = expected.Replace(@"\u0008", @"\b"); // U+0008 BACKSPACE -> "\b"
expected = expected.Replace(@"\u0009", @"\t"); // U+0009 CHARACTER TABULATION -> "\t"
expected = expected.Replace(@"\u000A", @"\n"); // U+000A LINE FEED -> "\n"
expected = expected.Replace(@"\u000C", @"\f"); // U+000C FORM FEED -> "\f"
expected = expected.Replace(@"\u000D", @"\r"); // U+000D CARRIAGE RETURN -> "\n"
expected = expected.Replace(@"\u005C", @"\\"); // U+005C REVERSE SOLIDUS -> "\\"
// Act
string retVal = encoder.JavaScriptStringEncode(input);
// Assert
Assert.Equal(expected, retVal);
}
[Fact]
public void JavaScriptStringEncode_BadSurrogates_ReturnsUnicodeReplacementChar()
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(UnicodeRanges.All); // allow all codepoints
// "a<unpaired leading>b<unpaired trailing>c<trailing before leading>d<unpaired trailing><valid>e<high at end of string>"
const string Input = "a\uD800b\uDFFFc\uDFFF\uD800d\uDFFF\uD800\uDFFFe\uD800";
const string Expected = "a\uFFFDb\uFFFDc\uFFFD\uFFFDd\uFFFD\\uD800\\uDFFFe\uFFFD"; // 'D800' 'DFFF' was preserved since it's valid
// Act
string retVal = encoder.JavaScriptStringEncode(Input);
// Assert
Assert.Equal(Expected, retVal);
}
[Fact]
public void JavaScriptEncoder_BadSurrogates_ReturnsUnicodeReplacementChar()
{
// Arrange
JavaScriptEncoder encoder = JavaScriptEncoder.Create(UnicodeRanges.All); // allow all codepoints
// "a<unpaired leading>b<unpaired trailing>c<trailing before leading>d<unpaired trailing><valid>e<high at end of string>"
const string Input = "a\uD800b\uDFFFc\uDFFF\uD800d\uDFFF\uD800\uDFFFe\uD800";
const string Expected = "a\uFFFDb\uFFFDc\uFFFD\uFFFDd\uFFFD\\uD800\\uDFFFe\uFFFD"; // 'D800' 'DFFF' was preserved since it's valid
// String-based Encode()
string retVal = encoder.Encode(Input);
Assert.Equal(Expected, retVal);
// OperationStatus-based Encode()
Span<char> destination = new char[23];
OperationStatus status = encoder.Encode(Input.AsSpan(), destination, out int charsConsumed, out int charsWritten, isFinalBlock: true);
Assert.Equal(OperationStatus.Done, status);
Assert.Equal(13, charsConsumed);
Assert.Equal(13, Input.Length);
Assert.Equal(23, charsWritten);
Assert.Equal(Expected, new string(destination.Slice(0, charsWritten).ToArray()));
}
[Fact]
public void JavaScriptEncoder_UnpairedSurrogatesReplaced()
{
// Arrange
JavaScriptEncoder encoder = JavaScriptEncoder.Create(UnicodeRanges.All); // allow all codepoints
// "a<unpaired leading low><unpaired leading high><unpaired leading high>"
const string Input = "a\uDFFF\uD800\uD800";
const string Expected = "a\uFFFD\uFFFD\uFFFD";
Assert.Equal(4, Input.Length);
// String-based Encode()
string retVal = encoder.Encode(Input);
Assert.Equal(Expected, retVal);
// OperationStatus-based Encode()
OperationStatus status;
Span<char> destination = new char[100];
status = encoder.Encode(Input.AsSpan(), destination, out int charsConsumed, out int charsWritten, isFinalBlock: true);
Assert.Equal(OperationStatus.Done, status);
Assert.Equal(4, charsConsumed);
Assert.Equal(4, charsWritten);
Assert.Equal(Expected, new string(destination.Slice(0, charsWritten).ToArray()));
}
[Fact]
public void JavaScriptEncoder_NeedsMoreData()
{
// "a<paired leading><paired trailing>"
const string Input = "a\uD800\uDFFF";
const string Expected = "a\\uD800\\uDFFF";
Assert.Equal(3, Input.Length);
JavaScriptEncoder encoder = JavaScriptEncoder.Create(UnicodeRanges.All); // allow all codepoints
Span<char> destination = new char[100];
OperationStatus status;
// Just pass in the first two characters, making uD800 an unpaired high surrogate. Set isFinalBlock=false so we get NeedMoreData.
status = encoder.Encode(Input.AsSpan(0, 2), destination, out int charsConsumed1, out int charsWritten1, isFinalBlock: false);
Assert.Equal(OperationStatus.NeedMoreData, status);
Assert.Equal(1, charsConsumed1);
Assert.Equal(1, charsWritten1);
Assert.Equal("a", new string(destination.Slice(0, charsWritten1).ToArray()));
// Append additional data; keep IsFinalBlock=false
status = encoder.Encode(Input.AsSpan(charsConsumed1, 2), destination.Slice(charsWritten1), out int charsConsumed2, out int charsWritten2, isFinalBlock: false);
Assert.Equal(OperationStatus.Done, status);
Assert.Equal(2, charsConsumed2);
Assert.Equal(12, charsWritten2);
Assert.Equal(Expected, new string(destination.Slice(0, charsWritten1 + charsWritten2).ToArray()));
// Ensure isFinalBlock=true has the same result since there is no longer a trailing unpaired high surrogate.
status = encoder.Encode(Input.AsSpan(charsConsumed1, 2), destination.Slice(charsWritten1), out charsConsumed2, out charsWritten2, isFinalBlock: true);
Assert.Equal(OperationStatus.Done, status);
Assert.Equal(2, charsConsumed2);
Assert.Equal(12, charsWritten2);
Assert.Equal(Expected, new string(destination.Slice(0, charsWritten1 + charsWritten2).ToArray()));
}
[Fact]
public void JavaScriptStringEncode_EmptyStringInput_ReturnsEmptyString()
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder();
// Act & assert
Assert.Equal("", encoder.JavaScriptStringEncode(""));
}
[Fact]
public void JavaScriptStringEncode_InputDoesNotRequireEncoding_ReturnsOriginalStringInstance()
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder();
string input = "Hello, there!";
// Act & assert
Assert.Same(input, encoder.JavaScriptStringEncode(input));
}
[Fact]
public void JavaScriptStringEncode_NullInput_Throws()
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder();
Assert.Throws<ArgumentNullException>(() => { encoder.JavaScriptStringEncode(null); });
}
[Fact]
public void JavaScriptStringEncode_WithCharsRequiringEncodingAtBeginning()
{
Assert.Equal(@"\u0026Hello, there!", new JavaScriptStringEncoder().JavaScriptStringEncode("&Hello, there!"));
}
[Fact]
public void JavaScriptStringEncode_WithCharsRequiringEncodingAtEnd()
{
Assert.Equal(@"Hello, there!\u0026", new JavaScriptStringEncoder().JavaScriptStringEncode("Hello, there!&"));
}
[Fact]
public void JavaScriptStringEncode_WithCharsRequiringEncodingInMiddle()
{
Assert.Equal(@"Hello, \u0026there!", new JavaScriptStringEncoder().JavaScriptStringEncode("Hello, &there!"));
}
[Fact]
public void JavaScriptStringEncode_WithCharsRequiringEncodingInterspersed()
{
Assert.Equal(@"Hello, \u003Cthere\u003E!", new JavaScriptStringEncoder().JavaScriptStringEncode("Hello, <there>!"));
}
[Fact]
public void JavaScriptStringEncode_CharArray()
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder();
var output = new StringWriter();
// Act
encoder.JavaScriptStringEncode("Hello+world!".ToCharArray(), 3, 5, output);
// Assert
Assert.Equal(@"lo\u002Bwo", output.ToString());
}
[Fact]
public void JavaScriptStringEncode_StringSubstring()
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder();
var output = new StringWriter();
// Act
encoder.JavaScriptStringEncode("Hello+world!", 3, 5, output);
// Assert
Assert.Equal(@"lo\u002Bwo", output.ToString());
}
[Theory]
[InlineData("\"", @"\u0022")]
[InlineData("'", @"\u0027")]
public void JavaScriptStringEncode_Quotes(string input, string expected)
{
// Per the design document, we provide additional defense-in-depth
// against breaking out of HTML attributes by having the encoders
// never emit the ' or " characters. This means that we want to
// \u-escape these characters instead of using \' and \".
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(UnicodeRanges.All);
// Act
string retVal = encoder.JavaScriptStringEncode(input);
// Assert
Assert.Equal(expected, retVal);
}
[Fact]
public void JavaScriptStringEncode_DoesNotOutputHtmlSensitiveCharacters()
{
// Per the design document, we provide additional defense-in-depth
// by never emitting HTML-sensitive characters unescaped.
// Arrange
JavaScriptStringEncoder javaScriptStringEncoder = new JavaScriptStringEncoder(UnicodeRanges.All);
HtmlEncoder htmlEncoder = new HtmlEncoder(UnicodeRanges.All);
// Act & assert
for (int i = 0; i <= 0x10FFFF; i++)
{
if (IsSurrogateCodePoint(i))
{
continue; // surrogates don't matter here
}
string javaScriptStringEncoded = javaScriptStringEncoder.JavaScriptStringEncode(char.ConvertFromUtf32(i));
string thenHtmlEncoded = htmlEncoder.HtmlEncode(javaScriptStringEncoded);
Assert.Equal(javaScriptStringEncoded, thenHtmlEncoded); // should have contained no HTML-sensitive characters
}
}
private static bool IsSurrogateCodePoint(int codePoint)
{
return (0xD800 <= codePoint && codePoint <= 0xDFFF);
}
}
}
|