7

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.

david
  • 17,925
  • 4
  • 43
  • 57
  • Are you using the DomSanitationService? See https://github.com/angular/angular/issues/8491#issuecomment-217467582 and this answer http://stackoverflow.com/questions/37076867/in-rc-1-some-styles-cant-be-added-using-binding-syntax/37076868#37076868 – TylerH Sep 14 '16 at 02:52
  • Yeah the `DomSanitationService` is where all the `bypassSecurityTrust*` stuff lives. I'm not convinced that it should be needed for gradients. – david Sep 14 '16 at 03:27

2 Answers2

2

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

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

yurzui
  • 205,937
  • 32
  • 433
  • 399
  • That "workaround" just disables sanitisation globally... That seems like a terrible idea. I still don't understand why linear-gradient isn't in that regex whitelist. Is it actually unsafe or is it an oversight? – david Sep 14 '16 at 19:54
  • FWIW, I've sent https://github.com/angular/angular/pull/13943 to support this use case. Consider filing an issue in the future, this is really just an oversight in the CSS validator! – Martin Probst Jan 16 '17 at 10:23