Sanitize untrusted CSS using Angular $sce.getTrustedCss - css

Trying to use $sce.getTrustedCss but always am getting an error for unsafe input.
Should such an example be safe or am I missing something.
$sce.getTrustedCss('.red {color: red;}');
Alternatively, are there other JS sanitizers that can work on CSS input?
google-caja only works for inline styling, it removes STYLE tags altogether.

Since Angular 2, use DomSanitizer:
import { DomSanitizer } from '#angular/platform-browser';
constructor(
private domSanitizer: DomSanitizer
) {}
// let legal = this.domSanitizer.bypassSecurityTrustStyle( styleAtrStr );

So far as I can tell, there is no actual CSS sanitization built in to Angular.
I think $sce.getTrustedCss(s) will always tell you that the input is unsafe unless you first do: s = $sce.trustAsCss(something). So if you pass your css through a sanitiser, or know it came from a trusted source you can mark it as safe for use.
Note also that the Angular documentation says that Angular doesn't actually use getTrustedCss() but you are free to use it in your own directives. I think that means if you do use it you would be responsible for ensuring the safe inputs were first passed through trustAsCss().
Here's the implementation of getTrusted():
function getTrusted(type, maybeTrusted) {
if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
return maybeTrusted;
}
var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
if (constructor && maybeTrusted instanceof constructor) {
return maybeTrusted.$$unwrapTrustedValue();
}
// If we get here, then we may only take one of two actions.
// 1. sanitize the value for the requested type, or
// 2. throw an exception.
if (type === SCE_CONTEXTS.RESOURCE_URL) {
if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
return maybeTrusted;
} else {
throw $sceMinErr('insecurl',
'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
maybeTrusted.toString());
}
} else if (type === SCE_CONTEXTS.HTML) {
return htmlSanitizer(maybeTrusted);
}
throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
}
return { trustAs: trustAs,
getTrusted: getTrusted,
valueOf: valueOf };
}];
Notice that urls and html have some extra checking, but other types (css, js) are only trusted when have been wrapped by the appropriate trustAs... function. Also trustAsCss() doesn't appear to be documented, but as the shorthand methods are automatically generated it should exist (or you could use trustAs($sce.CSS, ...) directly).

Related

Type of an object that contains CSS properties

I have a function that takes an element on the page and adds CSS to its style attribute. I want the argument that is passed to it to be an object with keys such as height, minWidth, flexDirection, etc.
function addStyle (el: HTMLElement, style: Style): void {
for (const property in style) {
el.style[property] = style[property]
}
}
My problem is in typing this object. It's obviously not feasible to define every single CSS property myself. I'm pretty sure that TypeScript should be able to do this itself, I'm just not sure how. This is my best guess:
type Style = Partial<CSSStyleDeclaration>
...but that results in the error "Type 'string | undefined' is not assignable to type 'string'": TypeScript playground
That specific error can be easily overridden, but I'm wary that it indicates I'm doing something wrong or unintuitive.
Is there a standard way to type an object that contains CSS properties?
I don't think there's a good way to do this sort of thing, When typing a property that may or may not exist on an object, TypeScript does not differentiate between the property existing and containing the value undefined, and the property not existing at all.
For example, disregarding styles and everything else, consider typing an object which may have the foo property which is a string. You can't do { foo: string } because the property may not exist. You can do { foo: string | undefined }. You can also do { foo?: string }, but this type is identical to the previous one. I don't think there are any other options: you can't say "This property may or may not exist, but if it does exist, it does not contain undefined."
A CSSStyleDeclaration is the same sort of situation, except with lots more properties. Partial<CSSStyleDeclaration> is the right way to go, but unfortunately, since TypeScript won't distinguish between partial types having properties containing undefined and not having those properties at all, you have to assert that the value does exist, if dealing with an individual value
But, there's another way to bypass having to reference and assert individual values, which is to use Object.assign:
type Style = Partial<CSSStyleDeclaration>;
function addStyle(el: HTMLElement, style: Style) {
Object.assign(el.style, style);
}
(also remember that there's no need to specify the return type of a function if TS can determine it automatically - less code to read and write is usually a good thing)
Use the non-null assertion operator that is here exactly for your use case.
adding exclamation mark
type Style = Partial<CSSStyleDeclaration>
function addStyle (el: HTMLElement, style: Style): void {
for (const property in style) {
el.style[property] = style[property]!;
}
}
Or add || ''
type Style = Partial<CSSStyleDeclaration>
function addStyle (el: HTMLElement, style: Style): void {
for (const property in style) {
el.style[property] = style[property] || '';
}
}

Access Kotlin Delegate Type without an Instance

I have read Access property delegate in Kotlin which is about accessing a delegate from an instance. One can use KProperty::getDelegate since Kotlin 1.1, however this will return the instance of the delegate and therefore needs an instance of the class first.
Now I want to get the type of the delegate without having an instance of the class. Consider a library with a custom delegate type CustomDelegate that want's to get all properties of a class that are delegated to an instance of CustomDelegate:
class Example
{
var nonDelegatedProperty = "I don't care about this property"
var delegatedProperty1 by lazy { "I don't care about this too" }
var delegatedProperty2 by CustomDelegate("I care about this one")
}
How can I, given I have KClass<Example>, but not an instance of Example, get all properties delegated to CustomDelegate?
How can I, given I have KClass<Example>, but not an instance of
Example, get all properties delegated to CustomDelegate?
You can do it in two ways depending on your needs.
First of all, you have to include the kotlin-reflect dependency in your build.gradle file:
compile "org.jetbrains.kotlin:kotlin-reflect:1.1.51"
In my opinion, you should use the first solution if you can, because it's the most clear and optimized one. The second solution instead, can handle one case that the first solution can't.
First
You can loop an the declared properties and check if the type of the property or the type of the delegate is CustomDelegate.
// Loop on the properties of this class.
Example::class.declaredMemberProperties.filter { property ->
// If the type of field is CustomDelegate or the delegate is an instance of CustomDelegate,
// it will return true.
CustomDelegate::class.java == property.javaField?.type
}
There's only one problem with this solution, you will get also the fields with type CustomDelegate, so, given this example:
class Example {
var nonDelegatedProperty = "I don't care about this property"
val delegatedProperty1 by lazy { "I don't care about this too" }
val delegatedProperty2 by CustomDelegate("I care about this one")
val customDelegate = CustomDelegate("jdo")
}
You will get delegatedProperty2 and customDelegate. If you want to get only delegatedProperty2, I found an horrible solution that you can use if you need to manage this case.
Second
If you check the source code of KPropertyImpl, you can see how a delegation is implemented. So, you can do something like this:
// Loop on the properties of this class.
Example::class.declaredMemberProperties.filter { property ->
// You must check in all superclasses till you find the right method.
property::class.allSuperclasses.find {
val computeField = try {
// Find the protected method "computeDelegateField".
it.declaredFunctions.find { it.name == "computeDelegateField" } ?: return#find false
} catch (t: Throwable) {
// Catch KotlinReflectionInternalError.
return#find false
}
// Get the delegate or null if the delegate is not present.
val delegateField = computeField.call(property) as? Field
// If the delegate was null or the type is different from CustomDelegate, it will return false.
CustomDelegate::class.java == delegateField?.type
} != null
}
In this case, you will get only delegatedProperty2 as result.

How to check if a variable exists in flex

In flex, how to check if a variable exists? I have tried using
if (this['some_variable'] != undefined) {
//do something
}
There is a run time error saying the property some_variable does not exists. I have checked with null instead of undefined, still the same error.
please help.
[EDIT]
Based on the replies I have used this.hasOwnProperty('variable_name'). I found that its returning true if variable_name is a public but false if its private/protected. How to check for a private variable?
There are two ways for that:
if ("some_variable" in this) {
//do something
}
It uses in operator.
And:
if (this.hasOwnProperty("some_variable")) {
//do something
}
See documentation about hasOwnProperty().
What about getting information about private/protected properties the situation is that you can't get this info with the current state of Flash Player. The only possible way, I suppose, is some kind of runtime bytecode manipulation. But as far as I know nobody implemented it yet.
But I have a question about getting info about private/protected properties: for what purpose you need it? The nature of these properties/methods is you can't call them. Even if you know about their existence.
You can use
if (this. hasOwnProperty("some_variable")) {
//access the variable inside
}
if (this.hasOwnProperty('some_variable')) DO_IT_!()
Explanation:
this['some_variable'] tries to evaluate the value of the instance property some_variable. If there is no such a property, you will get this error.
To test if a property exists for a particular object use hasOwnProperty or wrap your condition in a try/catch block or use if ('some_variable' in this).
Usually you create an object property in a class file:
public class MyClass {
public var myProperty : String = "ich bin hier";
}
Then you refer to that property within the class:
trace (myProperty);
trace (this.myProperty);
Using the array syntax [] is also possible but will throw the error if the property is not defined.
trace (this['myProperty']);
And finally! If you declare your class to be dynamic you might use the array syntax even if the property does not exist.
public dynamic class MyClass {
public function MyClass() {
trace (this["never_declared_property"]);
}
}

Flex-IFrame Comm Test Not Working

I'm trying to get the IFrameCommTest example (from the Flex-IFrame site) to work in Flex 4, and, while the IFrame itself works, the communication does not. In particular, I need to get the included HTML page to call functions from the flex app (I already have a way to get the Flex app to talk to the HTML).
I've exported the project to facilitate your help.
The problem, I suspect, is that the "parent.FABridge" doesn't exist. My guess is that something in flex4 changed with regard to how things are located in the DOM.
(This post is related to the earlier post about FABridge.
I thought this would be a clearer example of the problem. )
Thanks,
Brian
I've solved this my own self :D
The difference over the mechanism above is in the getFlexApp() function, and it provides a way to, well, get the flex object. Once the objecty it gotten, I just call the EIButtonClicked() function, and pass a value to it.
function getFlexApp(appName) {
if (navigator.appName.indexOf ("Microsoft") !=-1) {
return window.top[appName];
} else {
return window.top.document[appName];
}
}
function callFlexFunction() {
var sTxt ;
sTxt = document.getElementById('txt1').value;
alert('HTML/Javascript wants to tell you about ' + sTxt);
getFlexApp('iframeCommTest').EIButtonClicked(sTxt) ;
}
Meanwhile, the flex side has an external interface callback established. You can see that the "EIButtonClicked" referenced in the JS above is matched by the label for the callback in the AS below.
/**
* When the button is clicked.
*/
public function onEIButtonClicked(data:String):void {
Alert.show("Flash wants to tell you about " + data);
}
protected function application1_creationCompleteHandler():void {
// TODO Auto-generated method stub
if (ExternalInterface.available) {
ExternalInterface.addCallback("EIButtonClicked", onEIButtonClicked);
}
}

How to know if an object is dynamic in AS3

In Action Script 3, you can write a class that defines a dynamic object (MovieClip and Object are two examples), this objects can be modified in run-time. What I want to know if is there some way (in run-time, of course) to know if certain object is dynamic or not.
PS: Without making something like this:
function isDynamic(object) {
try {
object.newProperty = 'someValue'
} catch (e) {
return false
}
return true
}
CookieOfFortune has the right idea, but unfortunately the code itself has problems, isDynamic is an attribute, and the returned value will be a XMLList with a value of a String that reflects a true or false value, not a child node that directly returns a Boolean. It should look more like this:
function isDynamic(object) : Boolean
{
var type:XML = describeType(object);
return type.#isDynamic.toString() == "true";
}
Be careful!
Anytime you want to use the describeType() function, please please please use the variation:
import mx.utils.DescribeTypeCache;
var typeDesc:XML = DescribeTypeCache.describeType(object).typeDescription;
Performance of making repeated calls to the runtime reflective machinery will absolutely suck. That's why Adobe invented the DescribeTypeCache class.
You can use describeType from flash.utils to describe the object in XML form. Here's the reference to the API: flash.utils.describeType
function isDynamic(object) {
var type:XML = describeType(object);
if (type.#isDynamic == "true") return true;
return false;
}
This is a very old post, but I'll add an option for those future searchers.
AS3 has a built in way of doing this:
mx.utils.ObjectUtil.isDynamicObject(yourObject);
Read more about it here.

Resources