/
security_spec.ts
597 lines (516 loc) Β· 19.2 KB
/
security_spec.ts
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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CommonModule, NgIf} from '@angular/common';
import {Component, Directive, inject, TemplateRef, Type, ViewChild, ViewContainerRef} from '@angular/core';
import {RuntimeErrorCode} from '@angular/core/src/errors';
import {global} from '@angular/core/src/util/global';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {DomSanitizer} from '@angular/platform-browser';
describe('comment node text escaping', () => {
// see: https://html.spec.whatwg.org/multipage/syntax.html#comments
['>', // self closing
'-->', // standard closing
'--!>', // alternate closing
'<!-- -->', // embedded comment.
].forEach((xssValue) => {
it('should not be possible to do XSS through comment reflect data when writing: ' + xssValue,
() => {
@Component({template: `<div><span *ngIf="xssValue"></span><div>`})
class XSSComp {
// ngIf serializes the `xssValue` into a comment for debugging purposes.
xssValue: string = xssValue + '<script>"evil"</script>';
}
TestBed.configureTestingModule({declarations: [XSSComp]});
const fixture = TestBed.createComponent(XSSComp);
fixture.detectChanges();
const div = fixture.nativeElement.querySelector('div') as HTMLElement;
// Serialize into a string to mimic SSR serialization.
const html = div.innerHTML;
// This must be escaped or we have XSS.
expect(html).not.toContain('--><script');
// Now parse it back into DOM (from string)
div.innerHTML = html;
// Verify that we did not accidentally deserialize the `<script>`
const script = div.querySelector('script');
expect(script).toBeFalsy();
});
});
});
describe('iframe processing', () => {
function getErrorMessageRegexp() {
const errorMessagePart = 'NG0' + Math.abs(RuntimeErrorCode.UNSAFE_IFRAME_ATTRS).toString();
return new RegExp(errorMessagePart);
}
function ensureNoIframePresent(fixture?: ComponentFixture<unknown>) {
// Note: a `fixture` may not exist in case an error was thrown at creation time.
const iframe = fixture?.nativeElement.querySelector('iframe');
expect(!!iframe).toBeFalse();
}
function expectIframeCreationToFail<T>(
component: Type<T>, declarations?: Array<Type<unknown>>): ComponentFixture<T> {
TestBed.configureTestingModule({
imports: [CommonModule],
declarations: [component, ...(declarations ?? [])],
});
let fixture: ComponentFixture<T>|undefined;
expect(() => {
fixture = TestBed.createComponent(component);
fixture.detectChanges();
}).toThrowError(getErrorMessageRegexp());
ensureNoIframePresent(fixture);
return fixture!;
}
function expectIframeToBeCreated<T>(
component: Type<T>, attrsToCheck: {[key: string]: string},
declarations?: Array<Type<unknown>>): ComponentFixture<T> {
TestBed.configureTestingModule({
imports: [CommonModule],
declarations: [component, ...(declarations ?? [])],
});
let fixture: ComponentFixture<T>;
expect(() => {
fixture = TestBed.createComponent(component);
fixture.detectChanges();
}).not.toThrow();
const iframe = fixture!.nativeElement.querySelector('iframe');
for (const [attrName, attrValue] of Object.entries(attrsToCheck)) {
expect(iframe[attrName]).toEqual(attrValue);
}
return fixture!;
}
// *Must* be in sync with the `SECURITY_SENSITIVE_ATTRS` list
// from the `packages/compiler/src/schema/dom_security_schema.ts`.
const SECURITY_SENSITIVE_ATTRS = ['sandbox', 'allow', 'allowFullscreen', 'referrerPolicy'];
if (!isBrowser) {
// Browsers used during the CI may not have support for the 'csp'
// and 'fetchPriority' properties, so the Angular logs an "unknown
// property" error and exits. As a result, we can only check this
// behavior while running tests in Node.
SECURITY_SENSITIVE_ATTRS.push('csp', 'fetchPriority');
}
const TEST_IFRAME_URL = 'https://angular.io/assets/images/logos/angular/angular.png';
let oldNgDevMode!: typeof ngDevMode;
beforeAll(() => {
oldNgDevMode = ngDevMode;
});
afterAll(() => {
global['ngDevMode'] = oldNgDevMode;
});
[true, false].forEach(devModeFlag => {
beforeAll(() => {
global['ngDevMode'] = devModeFlag;
// TestBed and JIT compilation have some dependencies on the ngDevMode state, so we need to
// reset TestBed to ensure we get a 'clean' JIT compilation under the new rules.
TestBed.resetTestingModule();
});
describe(`with ngDevMode = ${devModeFlag}`, () => {
SECURITY_SENSITIVE_ATTRS.forEach((securityAttr: string) => {
['src', 'srcdoc'].forEach((srcAttr: string) => {
it(`should work when a security-sensitive attribute is set ` +
`as a static attribute (checking \`${securityAttr}\`)`,
() => {
@Component({
selector: 'my-comp',
template: `
<iframe
${srcAttr}="${TEST_IFRAME_URL}"
${securityAttr}="">
</iframe>`,
})
class IframeComp {
}
expectIframeToBeCreated(IframeComp, {[srcAttr]: TEST_IFRAME_URL});
});
it(`should error when a security-sensitive attribute is applied ` +
`using a property binding (checking \`${securityAttr}\`)`,
() => {
@Component({
selector: 'my-comp',
template:
`<iframe ${srcAttr}="${TEST_IFRAME_URL}" [${securityAttr}]="''"></iframe>`,
})
class IframeComp {
}
expectIframeCreationToFail(IframeComp);
});
it(`should error when a security-sensitive attribute is applied ` +
`using a property interpolation (checking \`${securityAttr}\`)`,
() => {
@Component({
selector: 'my-comp',
template:
`<iframe ${srcAttr}="${TEST_IFRAME_URL}" ${securityAttr}="{{''}}"></iframe>`,
})
class IframeComp {
}
expectIframeCreationToFail(IframeComp);
});
it(`should error when a security-sensitive attribute is applied ` +
`using a property binding (checking \`${securityAttr}\`)`,
() => {
@Component({
selector: 'my-comp',
template: `
<iframe
${srcAttr}="${TEST_IFRAME_URL}"
[attr.${securityAttr}]="''"
></iframe>
`,
})
class IframeComp {
}
expectIframeCreationToFail(IframeComp);
});
it(`should allow changing \`${srcAttr}\` after initial render`, () => {
@Component({
selector: 'my-comp',
template: `
<iframe
${securityAttr}="allow-forms"
[${srcAttr}]="src">
</iframe>
`,
})
class IframeComp {
src = this.sanitizeFn(TEST_IFRAME_URL);
constructor(private sanitizer: DomSanitizer) {}
get sanitizeFn() {
return srcAttr === 'src' ? this.sanitizer.bypassSecurityTrustResourceUrl :
this.sanitizer.bypassSecurityTrustHtml;
}
}
const fixture = expectIframeToBeCreated(IframeComp, {[srcAttr]: TEST_IFRAME_URL});
const component = fixture.componentInstance;
// Changing `src` or `srcdoc` is allowed.
const newUrl = 'https://angular.io/about?group=Angular';
component.src = component.sanitizeFn(newUrl);
fixture.detectChanges();
// expect(() => fixture.detectChanges()).not.toThrow();
expect(fixture.nativeElement.querySelector('iframe')[srcAttr]).toEqual(newUrl);
});
});
});
it('should work when a directive sets a security-sensitive attribute as a static attribute',
() => {
@Directive({
selector: '[dir]',
host: {
'src': TEST_IFRAME_URL,
'sandbox': '',
},
})
class IframeDir {
}
@Component({
selector: 'my-comp',
template: '<iframe dir></iframe>',
})
class IframeComp {
}
expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL}, [IframeDir]);
});
it('should work when a directive sets a security-sensitive host attribute on a non-iframe element',
() => {
@Directive({
selector: '[dir]',
host: {
'src': TEST_IFRAME_URL,
'sandbox': '',
},
})
class Dir {
}
@Component({
selector: 'my-comp',
template: '<img dir>',
})
class NonIframeComp {
}
TestBed.configureTestingModule({
declarations: [NonIframeComp, Dir],
});
const fixture = TestBed.createComponent(NonIframeComp);
fixture.detectChanges();
expect(fixture.nativeElement.firstChild.src).toEqual(TEST_IFRAME_URL);
});
it('should work when a security-sensitive attribute on an <iframe> ' +
'which also has a structural directive (*ngIf)',
() => {
@Component({
selector: 'my-comp',
template: `<iframe *ngIf="visible" src="${TEST_IFRAME_URL}" sandbox=""></iframe>`,
})
class IframeComp {
visible = true;
}
expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL}, [NgIf]);
});
it('should work when a security-sensitive attribute is set between `src` and `srcdoc`',
() => {
@Component({
selector: 'my-comp',
template: `<iframe src="${TEST_IFRAME_URL}" sandbox srcdoc="Hi!"></iframe>`,
})
class IframeComp {
}
expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL});
});
it('should work when a directive sets a security-sensitive attribute before setting `src`',
() => {
@Directive({
selector: '[dir]',
host: {
'sandbox': '',
'src': TEST_IFRAME_URL,
},
})
class IframeDir {
}
@Component({
selector: 'my-comp',
template: '<iframe dir></iframe>',
})
class IframeComp {
}
expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL}, [IframeDir]);
});
it('should work when a directive sets an `src` and ' +
'there was a security-sensitive attribute set in a template' +
'(directive attribute after `sandbox`)',
() => {
@Directive({
selector: '[dir]',
host: {
'src': TEST_IFRAME_URL,
},
})
class IframeDir {
}
@Component({
selector: 'my-comp',
template: '<iframe sandbox dir></iframe>',
})
class IframeComp {
}
expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL}, [IframeDir]);
});
it('should error when a directive sets a security-sensitive attribute ' +
'as an attribute binding (checking that it\'s case-insensitive)',
() => {
@Directive({
selector: '[dir]',
host: {
'[attr.SANDBOX]': '\'\'',
},
})
class IframeDir {
}
@Component({
selector: 'my-comp',
template: `<IFRAME dir src="${TEST_IFRAME_URL}"></IFRAME>`,
})
class IframeComp {
}
expectIframeCreationToFail(IframeComp, [IframeDir]);
});
it('should work when a directive sets an `src` and ' +
'there was a security-sensitive attribute set in a template' +
'(directive attribute before `sandbox`)',
() => {
@Directive({
selector: '[dir]',
host: {
'src': TEST_IFRAME_URL,
},
})
class IframeDir {
}
@Component({
selector: 'my-comp',
template: '<iframe dir sandbox></iframe>',
})
class IframeComp {
}
expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL}, [IframeDir]);
});
it('should work when a directive sets a security-sensitive attribute and ' +
'there was an `src` attribute set in a template' +
'(directive attribute after `src`)',
() => {
@Directive({
selector: '[dir]',
host: {
'sandbox': '',
},
})
class IframeDir {
}
@Component({
selector: 'my-comp',
template: `<iframe src="${TEST_IFRAME_URL}" dir></iframe>`,
})
class IframeComp {
}
expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL}, [IframeDir]);
});
it('should work when a security-sensitive attribute is set as a static attribute', () => {
@Component({
selector: 'my-comp',
template: `
<iframe referrerPolicy="no-referrer" src="${TEST_IFRAME_URL}"></iframe>
`,
})
class IframeComp {
}
expectIframeToBeCreated(IframeComp, {
src: TEST_IFRAME_URL,
referrerPolicy: 'no-referrer',
});
});
it('should error when a security-sensitive attribute is set ' +
'as a property binding and an <iframe> is wrapped into another element',
() => {
@Component({
selector: 'my-comp',
template: `
<section>
<iframe
src="${TEST_IFRAME_URL}"
[referrerPolicy]="'no-referrer'"
></iframe>
</section>`,
})
class IframeComp {
}
expectIframeCreationToFail(IframeComp);
});
it('should work when a directive sets a security-sensitive attribute and ' +
'there was an `src` attribute set in a template' +
'(directive attribute before `src`)',
() => {
@Directive({
selector: '[dir]',
host: {
'sandbox': '',
},
})
class IframeDir {
}
@Component({
selector: 'my-comp',
template: `<iframe dir src="${TEST_IFRAME_URL}"></iframe>`,
})
class IframeComp {
}
expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL}, [IframeDir]);
});
it('should work when a directive that sets a security-sensitive attribute goes ' +
'before the directive that sets an `src` attribute value',
() => {
@Directive({
selector: '[set-src]',
host: {
'src': TEST_IFRAME_URL,
},
})
class DirThatSetsSrc {
}
@Directive({
selector: '[set-sandbox]',
host: {
'sandbox': '',
},
})
class DirThatSetsSandbox {
}
@Component({
selector: 'my-comp',
// Important note: even though the `set-sandbox` goes after the `set-src`,
// the directive matching order (thus the order of host attributes) is
// based on the imports order, so the `sandbox` gets set first and the `src` second.
template: '<iframe set-src set-sandbox></iframe>',
})
class IframeComp {
}
expectIframeToBeCreated(
IframeComp, {src: TEST_IFRAME_URL}, [DirThatSetsSandbox, DirThatSetsSrc]);
});
it('should error when creating a view that contains an <iframe> ' +
'with security-sensitive attributes set via property bindings',
() => {
@Component({
selector: 'my-comp',
template: `
<ng-container #container></ng-container>
<ng-template #template>
<iframe src="${TEST_IFRAME_URL}" [sandbox]="''"></iframe>
</ng-template>
`,
})
class IframeComp {
@ViewChild('container', {read: ViewContainerRef}) container!: ViewContainerRef;
@ViewChild('template') template!: TemplateRef<unknown>;
createEmbeddedView() {
this.container.createEmbeddedView(this.template);
}
}
const fixture = TestBed.createComponent(IframeComp);
fixture.detectChanges();
expect(() => {
fixture.componentInstance.createEmbeddedView();
fixture.detectChanges();
}).toThrowError(getErrorMessageRegexp());
ensureNoIframePresent(fixture);
});
describe('i18n', () => {
it('should error when a security-sensitive attribute is set as ' +
'a property binding on an <iframe> inside i18n block',
() => {
@Component({
selector: 'my-comp',
template: `
<section i18n>
<iframe src="${TEST_IFRAME_URL}" [sandbox]="''">
</iframe>
</section>
`,
})
class IframeComp {
}
expectIframeCreationToFail(IframeComp);
});
it('should error when a security-sensitive attribute is set as ' +
'a property binding on an <iframe> annotated with i18n attribute',
() => {
@Component({
selector: 'my-comp',
template: `
<iframe i18n src="${TEST_IFRAME_URL}" [sandbox]="''">
</iframe>
`,
})
class IframeComp {
}
expectIframeCreationToFail(IframeComp);
});
it('should work when a security-sensitive attributes are marked for translation', () => {
@Component({
selector: 'my-comp',
template: `
<iframe src="${TEST_IFRAME_URL}" i18n-sandbox sandbox="">
</iframe>
`,
})
class IframeComp {
}
expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL});
});
});
});
});
});