Debian Codegraph @

secure/precis/enforce_test.go

raw
1 // Copyright 2015 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package precis
6
7 import (
8 "bytes"
9 "fmt"
10 "reflect"
11 "strings"
12 "testing"
13
14 "golang.org/x/text/internal/testtext"
15 "golang.org/x/text/runes"
16 "golang.org/x/text/secure/bidirule"
17 "golang.org/x/text/transform"
18 )
19
20 type testCase struct {
21 input string
22 output string
23 err error
24 }
25
26 func doTests(t *testing.T, fn func(t *testing.T, p *Profile, tc testCase)) {
27 for _, g := range enforceTestCases {
28 for i, tc := range g.cases {
29 name := fmt.Sprintf("%s:%d:%+q", g.name, i, tc.input)
30 t.Run(name, func(t *testing.T) {
31 fn(t, g.p, tc)
32 })
33 }
34 }
35 }
36
37 func TestString(t *testing.T) {
38 doTests(t, func(t *testing.T, p *Profile, tc testCase) {
39 if e, err := p.String(tc.input); tc.err != err || e != tc.output {
40 t.Errorf("got %+q (err: %v); want %+q (err: %v)", e, err, tc.output, tc.err)
41 }
42 })
43 }
44
45 func TestBytes(t *testing.T) {
46 doTests(t, func(t *testing.T, p *Profile, tc testCase) {
47 if e, err := p.Bytes([]byte(tc.input)); tc.err != err || string(e) != tc.output {
48 t.Errorf("got %+q (err: %v); want %+q (err: %v)", string(e), err, tc.output, tc.err)
49 }
50 })
51
52 t.Run("Copy", func(t *testing.T) {
53 // Test that calling Bytes with something that doesn't transform returns a
54 // copy.
55 orig := []byte("hello")
56 b, _ := NewFreeform().Bytes(orig)
57 if reflect.ValueOf(b).Pointer() == reflect.ValueOf(orig).Pointer() {
58 t.Error("original and result are the same slice; should be a copy")
59 }
60 })
61 }
62
63 func TestAppend(t *testing.T) {
64 doTests(t, func(t *testing.T, p *Profile, tc testCase) {
65 if e, err := p.Append(nil, []byte(tc.input)); tc.err != err || string(e) != tc.output {
66 t.Errorf("got %+q (err: %v); want %+q (err: %v)", string(e), err, tc.output, tc.err)
67 }
68 })
69 }
70
71 func TestStringMallocs(t *testing.T) {
72 if n := testtext.AllocsPerRun(100, func() { UsernameCaseMapped.String("helloworld") }); n > 0 {
73 // TODO: reduce this to 0.
74 t.Skipf("got %f allocs, want 0", n)
75 }
76 }
77
78 func TestAppendMallocs(t *testing.T) {
79 str := []byte("helloworld")
80 out := make([]byte, 0, len(str))
81 if n := testtext.AllocsPerRun(100, func() { UsernameCaseMapped.Append(out, str) }); n > 0 {
82 t.Errorf("got %f allocs, want 0", n)
83 }
84 }
85
86 func TestTransformMallocs(t *testing.T) {
87 str := []byte("helloworld")
88 out := make([]byte, 0, len(str))
89 tr := UsernameCaseMapped.NewTransformer()
90 if n := testtext.AllocsPerRun(100, func() {
91 tr.Reset()
92 tr.Transform(out, str, true)
93 }); n > 0 {
94 t.Errorf("got %f allocs, want 0", n)
95 }
96 }
97
98 // TestTransformerShortBuffers tests that the precis.Transformer implements the
99 // spirit, not just the letter (the method signatures), of the
100 // transform.Transformer interface.
101 //
102 // In particular, it tests that, if one or both of the dst or src buffers are
103 // short, so that multiple Transform calls are required to complete the overall
104 // transformation, the end result is identical to one Transform call with
105 // sufficiently long buffers.
106 func TestTransformerShortBuffers(t *testing.T) {
107 testCases := []struct {
108 name string
109 srcUnit []byte
110 wantUnit []byte
111 srcRepeat int
112 wantRepeat int
113 srcLen int
114 wantLen int
115 wantErr error
116 tr *Transformer
117 }{
118 {
119 name: "Freeform",
120 srcUnit: []byte("a\u0300cce\u0301nts"), // NFD normalization form
121 wantUnit: []byte("àccénts"), // NFC normalization form
122 srcRepeat: 16,
123 wantRepeat: 16,
124 srcLen: 11,
125 wantLen: 9,
126 tr: NewFreeform().NewTransformer(),
127 },
128 {
129 name: "Nickname1",
130 srcUnit: []byte("a\u0300cce\u0301nts"),
131 wantUnit: []byte("àccénts"),
132 srcRepeat: 16,
133 wantRepeat: 16,
134 srcLen: 11,
135 wantLen: 9,
136 tr: Nickname.NewTransformer(),
137 },
138 {
139 name: "Nickname2",
140 srcUnit: []byte("ﷺ"), // U+FDFA
141 wantUnit: []byte("صلى الله عليه وسلم"),
142 srcRepeat: 16,
143 wantRepeat: 16,
144 srcLen: 3,
145 wantLen: 33,
146 tr: Nickname.NewTransformer(),
147 },
148 {
149 name: "incomplete 3-byte rune",
150 srcUnit: []byte("a\xef\xb7"), // input ends in an incomplete 3-byte rune
151 wantUnit: []byte("a"),
152 srcRepeat: 1,
153 wantRepeat: 1,
154 srcLen: 3,
155 wantLen: 1,
156 wantErr: errDisallowedRune,
157 tr: Nickname.NewTransformer(),
158 },
159 {
160 name: "bad utf8",
161 srcUnit: []byte("a\xff"), // \xff is never valid
162 wantUnit: []byte("a"),
163 srcRepeat: 1,
164 wantRepeat: 1,
165 srcLen: 2,
166 wantLen: 1,
167 wantErr: errDisallowedRune,
168 tr: Nickname.NewTransformer(),
169 },
170 {
171 name: "Nickname space",
172 srcUnit: []byte("abcd b"),
173 wantUnit: []byte("abcd b"),
174 srcRepeat: 16,
175 wantRepeat: 16,
176 srcLen: 6,
177 wantLen: 6,
178 tr: Nickname.NewTransformer(),
179 },
180 {
181 name: "Nickname return nil",
182 srcUnit: []byte("a b"),
183 wantUnit: []byte("a b"),
184 srcRepeat: 10,
185 wantRepeat: 10,
186 srcLen: 3,
187 wantLen: 3,
188 tr: Nickname.NewTransformer(),
189 },
190 {
191 name: "Nickname partial",
192 srcUnit: []byte("ﷺ"), // U+FDFA (3 bytes)
193 wantUnit: []byte("ﷺ"),
194 srcRepeat: 16,
195 wantRepeat: 16,
196 srcLen: 3,
197 wantLen: 3,
198 tr: &Transformer{&nickAdditionalMapping{}},
199 },
200 {
201 name: "context boundary",
202 srcUnit: []byte("\u0628\u200c\u0627"), // JoiningD + ZWNJ + JoiningR (2+3+2=7 bytes)
203 wantUnit: []byte("\u0628\u200c\u0627"),
204 srcRepeat: 16,
205 wantRepeat: 16,
206 srcLen: 7,
207 wantLen: 7,
208 tr: NewFreeform().NewTransformer(),
209 },
210 }
211
212 for _, tc := range testCases {
213 t.Run(tc.name, func(t *testing.T) {
214 src := bytes.Repeat(tc.srcUnit, tc.srcRepeat)
215 want := bytes.Repeat(tc.wantUnit, tc.wantRepeat)
216 const long = 4096
217 dst := make([]byte, long)
218
219 // 5, 7, 9, 11, 13, 16 and 17 are all pair-wise co-prime, which means that
220 // slicing the dst and src buffers into 5, 7, 13 and 17 byte chunks will
221 // fall at different places inside the repeated srcUnit's and wantUnit's.
222 if len(tc.srcUnit) != tc.srcLen || len(tc.wantUnit) != tc.wantLen || len(src) > long || len(want) > long {
223 t.Fatal("inconsistent lengths")
224 }
225 for _, deltaD := range []int{5, 7, 13, 17, long} {
226 loop:
227 for _, deltaS := range []int{5, 7, 13, 17, long} {
228 tc.tr.Reset()
229 d0 := 0
230 s0 := 0
231 var nDst, nSrc int
232 var err error
233 for {
234 d1 := min(len(dst), d0+deltaD)
235 s1 := min(len(src), s0+deltaS)
236 nDst, nSrc, err = tc.tr.Transform(dst[d0:d1:d1], src[s0:s1:s1], s1 == len(src))
237 d0 += nDst
238 s0 += nSrc
239 if err == nil && s0 == len(src) {
240 break
241 }
242 if err == nil {
243 continue
244 }
245 if err == transform.ErrShortDst || (err == transform.ErrShortSrc && s1 < len(src)) {
246 continue
247 }
248 if err == tc.wantErr && (s1 == len(src) || tc.wantErr != transform.ErrShortSrc) {
249 break
250 }
251 t.Errorf("deltaD=%d, deltaS=%d: %v", deltaD, deltaS, err)
252 continue loop
253 }
254 if tc.wantErr == nil && s0 != len(src) {
255 t.Errorf("deltaD=%d, deltaS=%d: s0: got %d, want %d", deltaD, deltaS, s0, len(src))
256 continue
257 }
258 if d0 != len(want) {
259 t.Errorf("deltaD=%d, deltaS=%d: d0: got %d, want %d", deltaD, deltaS, d0, len(want))
260 continue
261 }
262 got := dst[:d0]
263 if !bytes.Equal(got, want) {
264 t.Errorf("deltaD=%d, deltaS=%d:\ngot %q\nwant %q", deltaD, deltaS, got, want)
265 continue
266 }
267 if err != tc.wantErr {
268 t.Errorf("incorrect error: got %t, want %t", err, tc.wantErr)
269 }
270 }
271 }
272 })
273 }
274 }
275
276 var enforceTestCases = []struct {
277 name string
278 p *Profile
279 cases []testCase
280 }{
281 {"Basic", NewFreeform(), []testCase{
282 {"e\u0301\u031f", "\u00e9\u031f", nil}, // normalize
283 }},
284
285 {"Context Rule 1", NewFreeform(), []testCase{
286 // Rule 1: zero-width non-joiner (U+200C)
287 // From RFC:
288 // False
289 // If Canonical_Combining_Class(Before(cp)) .eq. Virama Then True;
290 // If RegExpMatch((Joining_Type:{L,D})(Joining_Type:T)*\u200C
291 // (Joining_Type:T)*(Joining_Type:{R,D})) Then True;
292 //
293 // Example runes for different joining types:
294 // Join L: U+A872; PHAGS-PA SUPERFIXED LETTER RA
295 // Join D: U+062C; HAH WITH DOT BELOW
296 // Join T: U+0610; ARABIC SIGN SALLALLAHOU ALAYHE WASSALLAM
297 // Join R: U+0627; ALEF
298 // Virama: U+0A4D; GURMUKHI SIGN VIRAMA
299 // Virama and Join T: U+0ACD; GUJARATI SIGN VIRAMA
300 {"\u200c", "", errContext},
301 {"\u200ca", "", errContext},
302 {"a\u200c", "", errContext},
303 {"\u200c\u0627", "", errContext}, // missing JoinStart
304 {"\u062c\u200c", "", errContext}, // missing JoinEnd
305 {"\u0610\u200c\u0610\u0627", "", errContext}, // missing JoinStart
306 {"\u062c\u0610\u200c\u0610", "", errContext}, // missing JoinEnd
307
308 // Variants of: D T* U+200c T* R
309 {"\u062c\u200c\u0627", "\u062c\u200c\u0627", nil},
310 {"\u062c\u0610\u200c\u0610\u0627", "\u062c\u0610\u200c\u0610\u0627", nil},
311 {"\u062c\u0610\u0610\u200c\u0610\u0610\u0627", "\u062c\u0610\u0610\u200c\u0610\u0610\u0627", nil},
312 {"\u062c\u0610\u200c\u0627", "\u062c\u0610\u200c\u0627", nil},
313 {"\u062c\u200c\u0610\u0627", "\u062c\u200c\u0610\u0627", nil},
314
315 // Variants of: L T* U+200c T* D
316 {"\ua872\u200c\u062c", "\ua872\u200c\u062c", nil},
317 {"\ua872\u0610\u200c\u0610\u062c", "\ua872\u0610\u200c\u0610\u062c", nil},
318 {"\ua872\u0610\u0610\u200c\u0610\u0610\u062c", "\ua872\u0610\u0610\u200c\u0610\u0610\u062c", nil},
319 {"\ua872\u0610\u200c\u062c", "\ua872\u0610\u200c\u062c", nil},
320 {"\ua872\u200c\u0610\u062c", "\ua872\u200c\u0610\u062c", nil},
321
322 // Virama
323 {"\u0a4d\u200c", "\u0a4d\u200c", nil},
324 {"\ua872\u0a4d\u200c", "\ua872\u0a4d\u200c", nil},
325 {"\ua872\u0a4d\u0610\u200c", "", errContext},
326 {"\ua872\u0a4d\u0610\u200c", "", errContext},
327
328 {"\u0acd\u200c", "\u0acd\u200c", nil},
329 {"\ua872\u0acd\u200c", "\ua872\u0acd\u200c", nil},
330 {"\ua872\u0acd\u0610\u200c", "", errContext},
331 {"\ua872\u0acd\u0610\u200c", "", errContext},
332
333 // Using Virama as join T
334 {"\ua872\u0acd\u200c\u062c", "\ua872\u0acd\u200c\u062c", nil},
335 {"\ua872\u200c\u0acd\u062c", "\ua872\u200c\u0acd\u062c", nil},
336 }},
337
338 {"Context Rule 2", NewFreeform(), []testCase{
339 // Rule 2: zero-width joiner (U+200D)
340 {"\u200d", "", errContext},
341 {"\u200da", "", errContext},
342 {"a\u200d", "", errContext},
343
344 {"\u0a4d\u200d", "\u0a4d\u200d", nil},
345 {"\ua872\u0a4d\u200d", "\ua872\u0a4d\u200d", nil},
346 {"\u0a4da\u200d", "", errContext},
347 }},
348
349 {"Context Rule 3", NewFreeform(), []testCase{
350 // Rule 3: middle dot
351 {"·", "", errContext},
352 {"l·", "", errContext},
353 {"·l", "", errContext},
354 {"a·", "", errContext},
355 {"l·a", "", errContext},
356 {"a·a", "", errContext},
357 {"l·l", "l·l", nil},
358 {"al·la", "al·la", nil},
359 }},
360
361 {"Context Rule 4", NewFreeform(), []testCase{
362 // Rule 4: Greek lower numeral U+0375
363 {"͵", "", errContext},
364 {"͵a", "", errContext},
365 {"α͵", "", errContext},
366 {"͵α", "͵α", nil},
367 {"α͵α", "α͵α", nil},
368 {"͵͵α", "͵͵α", nil}, // The numeric sign is itself Greek.
369 {"α͵͵α", "α͵͵α", nil},
370 {"α͵͵", "", errContext},
371 {"α͵͵a", "", errContext},
372 }},
373
374 {"Context Rule 5+6", NewFreeform(), []testCase{
375 // Rule 5+6: Hebrew preceding
376 // U+05f3: Geresh
377 {"׳", "", errContext},
378 {"׳ה", "", errContext},
379 {"a׳b", "", errContext},
380 {"ש׳", "ש׳", nil}, // U+05e9 U+05f3
381 {"ש׳׳׳", "ש׳׳׳", nil}, // U+05e9 U+05f3
382
383 // U+05f4: Gershayim
384 {"״", "", errContext},
385 {"״ה", "", errContext},
386 {"a״b", "", errContext},
387 {"ש״", "ש״", nil}, // U+05e9 U+05f4
388 {"ש״״״", "ש״״״", nil}, // U+05e9 U+05f4
389 {"aש״״״", "aש״״״", nil}, // U+05e9 U+05f4
390 }},
391
392 {"Context Rule 7", NewFreeform(), []testCase{
393 // Rule 7: Katakana middle Dot
394 {"・", "", errContext},
395 {"abc・", "", errContext},
396 {"・def", "", errContext},
397 {"abc・def", "", errContext},
398 {"aヅc・def", "aヅc・def", nil},
399 {"abc・dぶf", "abc・dぶf", nil},
400 {"⺐bc・def", "⺐bc・def", nil},
401 }},
402
403 {"Context Rule 8+9", NewFreeform(), []testCase{
404 // Rule 8+9: Arabic Indic Digit
405 {"١٢٣٤٥۶", "", errContext},
406 {"۱۲۳۴۵٦", "", errContext},
407 {"١٢٣٤٥", "١٢٣٤٥", nil},
408 {"۱۲۳۴۵", "۱۲۳۴۵", nil},
409 }},
410
411 {"Nickname", Nickname, []testCase{
412 {" Swan of Avon ", "Swan of Avon", nil},
413 {"", "", errEmptyString},
414 {" ", "", errEmptyString},
415 {" ", "", errEmptyString},
416 {"a\u00A0a\u1680a\u2000a\u2001a\u2002a\u2003a\u2004a\u2005a\u2006a\u2007a\u2008a\u2009a\u200Aa\u202Fa\u205Fa\u3000a", "a a a a a a a a a a a a a a a a a", nil},
417 {"Foo", "Foo", nil},
418 {"foo", "foo", nil},
419 {"Foo Bar", "Foo Bar", nil},
420 {"foo bar", "foo bar", nil},
421 {"\u03A3", "\u03A3", nil},
422 {"\u03C3", "\u03C3", nil},
423 // Greek final sigma is left as is (do not fold!)
424 {"\u03C2", "\u03C2", nil},
425 {"\u265A", "♚", nil},
426 {"Richard \u2163", "Richard IV", nil},
427 {"\u212B", "Å", nil},
428 {"\uFB00", "ff", nil}, // because of NFKC
429 {"שa", "שa", nil}, // no bidi rule
430 {"동일조건변경허락", "동일조건변경허락", nil},
431 }},
432 {"OpaqueString", OpaqueString, []testCase{
433 {" Swan of Avon ", " Swan of Avon ", nil},
434 {"", "", errEmptyString},
435 {" ", " ", nil},
436 {" ", " ", nil},
437 {"a\u00A0a\u1680a\u2000a\u2001a\u2002a\u2003a\u2004a\u2005a\u2006a\u2007a\u2008a\u2009a\u200Aa\u202Fa\u205Fa\u3000a", "a a a a a a a a a a a a a a a a a", nil},
438 {"Foo", "Foo", nil},
439 {"foo", "foo", nil},
440 {"Foo Bar", "Foo Bar", nil},
441 {"foo bar", "foo bar", nil},
442 {"\u03C3", "\u03C3", nil},
443 {"Richard \u2163", "Richard \u2163", nil},
444 {"\u212B", "Å", nil},
445 {"Jack of \u2666s", "Jack of \u2666s", nil},
446 {"my cat is a \u0009by", "", errDisallowedRune},
447 {"שa", "שa", nil}, // no bidi rule
448 }},
449 {"UsernameCaseMapped", UsernameCaseMapped, []testCase{
450 // TODO: Should this work?
451 // {UsernameCaseMapped, "", "", errDisallowedRune},
452 {"[email protected]", "[email protected]", nil},
453 {"fussball", "fussball", nil},
454 {"fu\u00DFball", "fu\u00DFball", nil},
455 {"\u03C0", "\u03C0", nil},
456 {"\u03A3", "\u03C3", nil},
457 {"\u03C3", "\u03C3", nil},
458 // Greek final sigma is left as is (do not fold!)
459 {"\u03C2", "\u03C2", nil},
460 {"\u0049", "\u0069", nil},
461 {"\u0049", "\u0069", nil},
462 {"\u03D2", "", errDisallowedRune},
463 {"\u03B0", "\u03B0", nil},
464 {"foo bar", "", errDisallowedRune},
465 {"♚", "", bidirule.ErrInvalid},
466 {"\u007E", "~", nil},
467 {"a", "a", nil},
468 {"!", "!", nil},
469 {"²", "", bidirule.ErrInvalid},
470 {"\t", "", errDisallowedRune},
471 {"\n", "", errDisallowedRune},
472 {"\u26D6", "", bidirule.ErrInvalid},
473 {"\u26FF", "", bidirule.ErrInvalid},
474 {"\uFB00", "", errDisallowedRune},
475 {"\u1680", "", bidirule.ErrInvalid},
476 {" ", "", errDisallowedRune},
477 {" ", "", errDisallowedRune},
478 {"\u01C5", "", errDisallowedRune},
479 {"\u16EE", "", errDisallowedRune}, // Nl RUNIC ARLAUG SYMBOL
480 {"\u0488", "", bidirule.ErrInvalid}, // Me COMBINING CYRILLIC HUNDRED THOUSANDS SIGN
481 {"\u212B", "\u00e5", nil}, // Angstrom sign, NFC -> U+00E5
482 {"A\u030A", "å", nil}, // A + ring
483 {"\u00C5", "å", nil}, // A with ring
484 {"\u00E7", "ç", nil}, // c cedille
485 {"\u0063\u0327", "ç", nil}, // c + cedille
486 {"\u0158", "ř", nil},
487 {"\u0052\u030C", "ř", nil},
488
489 {"\u1E61", "\u1E61", nil}, // LATIN SMALL LETTER S WITH DOT ABOVE
490
491 // Confusable characters ARE allowed and should NOT be mapped.
492 {"\u0410", "\u0430", nil}, // CYRILLIC CAPITAL LETTER A
493
494 // Full width should be mapped to the canonical decomposition.
495 {"AB", "ab", nil},
496 {"שc", "", bidirule.ErrInvalid}, // bidi rule
497
498 }},
499 {"UsernameCasePreserved", UsernameCasePreserved, []testCase{
500 {"ABC", "ABC", nil},
501 {"AB", "AB", nil},
502 {"שc", "", bidirule.ErrInvalid}, // bidi rule
503 {"\uFB00", "", errDisallowedRune},
504 {"\u212B", "\u00c5", nil}, // Angstrom sign, NFC -> U+00E5
505 {"ẛ", "", errDisallowedRune}, // LATIN SMALL LETTER LONG S WITH DOT ABOVE
506 }},
507 {"UsernameCaseMappedRestricted", NewRestrictedProfile(UsernameCaseMapped, runes.Predicate(func(r rune) bool {
508 return strings.ContainsRune(`@`, r)
509 })), []testCase{
510 {"[email protected]", "", errDisallowedRune},
511 {"\u0049", "\u0069", nil},
512 }},
513 }