Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 treating gradients as unsafe

I'm trying to set a gradient on a component dynamically and am getting the following warning:

WARNING: sanitizing unsafe style value linear-gradient(#000,#00f) (see http://g.co/ng/security#xss).

Here's a minimal reproduction:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: '<h1 [style.background]="(\'linear-gradient(#000,#00f)\')">My First Angular 2 App</h1>'
})
export class AppComponent {}

My googling tells me to use bypassSecurityTrustStyle but I'm not happy doing that until I know

  1. Why is linear gradient considered unsafe?
  2. Is this intended behaviour or just a bug with the current version of Angular 2.
  3. Is there a better way to do this without it being considered unsafe?

This does have to be dynamic as I'm building the gradient string programatically. I can't use css classes for this.

like image 567
david Avatar asked Sep 13 '16 23:09

david


2 Answers

1) Why is linear gradient considered unsafe?

There are restrictions under which misses your style (specifically brackets)

linear-gradient(#000,#00f)

https://github.com/angular/angular/blob/2.0.0-rc.7/modules/%40angular/platform-browser/src/security/style_sanitizer.ts#L30

As of today (RC.7) the RegExp looks like

/^([-,."'%_!# a-zA-Z0-9]+|(?:(?:matrix|translate|scale|rotate|skew|perspective)(?:X|Y|3d)?|(?:rgb|hsl)a?)\([-0-9.%, a-zA-Z]+\))$/g

enter image description here

2) Is this intended behaviour or just a bug with the current version of Angular 2.

I think it is more the expected behavior than the bug

Related issue on github

  • https://github.com/angular/angular/issues/11158

3) Is there a better way to do this without it being considered unsafe?

You can work around this limitation via writing CustomDomSanitizer

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ],
  providers: [ { provide: DomSanitizer, useClass: CustomDomSanitizer } ],
})
export class AppModule { }

See also live Plunker Example

like image 153
yurzui Avatar answered Oct 01 '22 13:10

yurzui


It's fixed in Angular 2.4.4 (https://github.com/angular/angular/blob/master/CHANGELOG.md#244-2017-01-19)

PR: https://github.com/angular/angular/pull/13943/files

like image 42
slaesh Avatar answered Oct 01 '22 13:10

slaesh