Sunday, September 15, 2013

Changing the Dart URI Policy for HTML Sanitizing


I was not prepared to like the HTML sanitization in Dart, but there it is.

I believe that it is fantastic that a web language—not a web framework, but a web language—is putting so much thought into security. It bodes well for the future of the web. No doubt other languages will follow suit and if they don't, well developers will not have any business using those languages.

The “why” of language security is a no-brainer. The “how” is what concerns me here. The default HTML sanitization is pretty reasonable. It will strip out anything that is known to be risky. The developer (that's me!) has to decide whether to work within the confines of the sanitized code or to change the sanitization strategy.

Last night, I tried the latter, which led to:
    list_el.setInnerHtml(
      graphic_novels_template(list),
      validator: new NodeValidatorBuilder()
        ..allowHtml5()
        ..allowElement('a', attributes: ['href'])
    );
Given an HTML template that is comprised of comic books:
graphic_novel_template(graphic_novel) {
  return '''
    <li id="${graphic_novel['id']}">
      ${graphic_novel['title']}
      <a href="#" class="delete">[delete]</a>
    </li>''';
}
The list_el.setInnerHtml() operation does pretty much what you might expect: it sets the HTML contents inside the list_el element.

This is not the usual Dart setter for inner HTML because of the need for the optional validator. If I did not need a specialized validator, I could have done something more like:
list_el.innerHtml = graphic_novels_template(list);
The default sanitization scheme lets through just about everything I need in my template. In fact, under normal conditions, it lets through everything that I need. But as I found last night, under file:// context test, the href attributes are stripped off with console warnings:
Removing disallowed attribute <A href="#">
I can probably live with that under test, but it got me wondering how to handle this situation. In the end, I found that I could take the base HtmlValidator and allow typical HTML5 elements along with any href attributes:
    list_el.setInnerHtml(
      graphic_novels_template(list),
      validator: new NodeValidatorBuilder()
        ..allowHtml5()
        ..allowElement('a', attributes: ['href'])
    );
(the double dot operator is a method cascade which calls the method on the object, but returns the object instead of the method's return value)

That worked, but is not quite what I wanted. I do not want to allow all href attributes—just “#” in addition to the usual values that are allowed. The reason that “#” is not allowed from file:// is that it is running afoul of the default URI policy. Actually, I am not sure why “#” runs afoul of the default URL policy when run from a file:// URL. That seems like it ought to work regardless of the context. But it is what it is and I would like to allow it.

To do so, I create my own URI policy class that allows the URI if it equals “#”:
class MyUriPolicy implements UriPolicy {
  bool allowsUri(uri) => uri == '#';
}
I can then replace the blanket allow href for <A> tags with my URI policy for navigation:
    list_el.setInnerHtml(
      graphic_novels_template(list),
      validator: new NodeValidatorBuilder()
        ..allowHtml5()
        ..allowNavigation(new MyUriPolicy())
    );
And that does the trick. I have my tests passing without any sanitization warnings. In the end I will probably switch back to the regular innerHtml setter—at least in this case. Still, I am glad that I figured that out.


Day #875

Saturday, September 14, 2013

Somebody is Wrong on the Internet


I will not go to bed until this particular fool is disabused:So yeah, I was wrong about that one. But that is one of the many benefits of blogging daily—I make a fool of myself so often that I am long past the days of caring that people realize that I am capable of making foolish mistakes.

I was convinced of this particular mistake for several days. So convinced was I, that I devised a plan to work around this: use <button> tags instead of <a> tags. But as I was prepping for today's post, a funny thing happened. I could not reproduced the error.

This particular error would have occurred when I was introducing the clear superiority of Dart strings in Dart for Hipsters. They can be multi-line and have nice value interpolation:
graphic_novel_template(graphic_novel) {
  return '''
    <li id="${graphic_novel['id']}">
      ${graphic_novel['title']}
      <a href="#" class="delete">[delete]</a>
    </li>''';
}
As my tweet indicates, I thought the href attribute was running afoul of Dart's HTML sanitization censors, but, now that I try to load the page up to address it, I find:



So what prompted my hissy fit? Well, it turns out that I was running my test suite from file://. That, it turns out, does set off sanitization alarms:
Removing disallowed attribute <A href="#"> 
If I want to allow that href attribute, I need to specify a custom HTML validator when assigning raw HTML:
    list_el.setInnerHtml(
      graphic_novels_template(list),
      validator: new NodeValidatorBuilder()
        ..allowTextElements()
        ..allowHtml5()
        ..allowElement('a', attributes: ['href'])
    );
I doubt that I will include that in my code just to appease my tests—especially since this is chapter one. Still, it is good to know how to accomplish it should I need it elsewhere. I am also beginning to understand the benefit of building HTML validation policies in this manner—it is fairly easy to build a policy that is nicely tailored to my needs in this particular instance. Plus, I am 100% assured that I cannot make a later coding mistake that sees an invalid element or attribute slip into my page.

I still rather wish for a way to de-taint strings in order to avoid validation in certain circumstances. But perhaps a few more foolish statements on my part will make me come around.


Day #874

Friday, September 13, 2013

I Don't Understand Drop Events (in any language)


Regardless of whether or not I can test it in Dart, I still need to be able to drop project files into ICE Code Editor. So as much as it pains me to do this… tonight I will add that feature to ICE without a test to guide me.

After last night's vain attempt to TDD the behavior into existence, I have the outline of how this will look:
    Element.
      dropEvent.
      forTarget(document).
      listen((event) {
        event
          ..preventDefault()
          ..stopPropagation();

        var file = event.dataTransfer.files.first;
      });
Nothing too fancy there—in Dart or JavaScript. It establishes an event stream for drop events. When such an event occurs, the listener callback is invoked with the drop event. I prevent the default action (which would be to open the file in the browser) and then get started with reading the contents of the dropped file.

As of last night, I had only gotten as far as getting a reference to the uploaded file. I was unable to populate the dataTransfer property in a test, but it ought to work just fine in real life. The API for file readers in Dart seems to follow the JavaScript exactly. So my next step is to create a FileReader object that reads the dropped file as text:

      // ...
      listen((event) {
        event
          ..preventDefault()
          ..stopPropagation();

        var file = event.dataTransfer.files.first;
        new FileReader()
          ..onLoad((read_event) {
              print(read_event.target.result);
            })
          ..readAsText(file);
      });
If everything is working correctly, when I drop a file into ICE:



I should now see the contents of the file printed to the console.

Instead, I see the contents of the file that I just uploaded:



Arrgh! Is drop just completely broken in Dart?!

Er, no. It's just me.

In the end, I have to boil this down into the simplest JavaScript version that is possible before I realize that it still does not work. It seems that it is not sufficient to prevent the drop event—I also have to prevent the “dragover” event:
<body>
<h1>Hello</h1>
</body>
<script>
document.addEventListener('dragover', function (e) {
  e.preventDefault();
});

document.addEventListener('drop', function(e) {
  e.preventDefault();
  var file = e.dataTransfer.files[0];

  console.log('file.name: ' + file.name);
  console.log('file.type: ' + file.type);

  var reader = new FileReader();
  reader.onload = function (e) {
    console.log(e.target.result);
  };
  reader.readAsText(file);
});
</script>
And, in fact, I need to prevent both the dragover and drop default event behavior so that the dropped file does not open in the browser:



DOM coding: catch the fever!

Comforted in the knowledge that my trouble is with DOM coding, not Dart, I switch back to Dart. There, I also prevent the default dragover event behavior:
    document
      ..onDragOver.
          listen((event) {
            event.preventDefault();
          })
      ..onDrop.
          listen((event) {
            event.preventDefault();

            var file = event.dataTransfer.files.first;
            print('file.name: ${file.name}');
            print('file.type: ${file.type}');

            new FileReader()
              ..onLoad.
                  listen((read_event) {
                    print(read_event.target.result);
                  })
              ..readAsText(file);
          });
With that, I can successfully read the pertinent information from the dropped file:



No doubt there is a very good reason for needing to prevent two different events. I do not really want to know what it is. Really. Mostly I would like Dart or one of its libraries to make this go away. Regardless, I believe that I have a sufficient understanding of how this works to enable me to hook it into ICE—even if I cannot test it. That seems a fine stopping point for tonight.


Day #873

Thursday, September 12, 2013

Trying to Test Drive Drop Events in Dart


OK, I really am going to give up now. I have been banging my head against the custom keyboard event wall in Dart of late. I feel that I have made some real progress on that front, but think it probably best to wait for the new KeyEvent changes to land in Dart proper.

Instead, I switch gears tonight to something different: events in Dart. Well, maybe not that different, but Definitely not keyboard events. Tonight, I will try to add the ability to drop a code file onto the ICE Code Editor, triggering a file reader.

I am going to drive this with tests. So I start with a fixture file in my tests directory:
➜  ice-code-editor git:(master) ✗ cat test/fixtures/file_upload.html 
<body></body>
<script>
console.log("yo");
</script>
Actually…

That probably will not work. The browser and dart:html tends not to have access to the file system. I am starting to get a scary feeling about this. But I plug ahead anyway. I start with the usual setUp() that creates an instance of the full screen editor with single projects whose contents are Test. Then, in my test, I create a drop event, dispatch it to the document, and set my expectation:
    test("can create projects", (){
      var file_upload_event = new MouseEvent('drop');
      document.dispatchEvent(file_upload_event);

      expect(
        editor.content,
        'File Upload Content'
      );
    });
I have no reason whatsoever to expect that dispatching the drop event will change the editor content. I am not setting the “File Upload Content” content anywhere in the event. Even if that content were in the event, there is no code in the editor to process the event. Since I am not sure where to put the content in the event, I start with the code to start a file reader.

I already have a private method to attach mouse handlers in ICE, so this seems a reasonable place to put the drop handler:
  _attachMouseHandlers() {
    // ...
    Element.
      dropEvent.
      forTarget(document).
      listen((event) {
        print('event: ${event}');
        event
          ..preventDefault()
          ..stopPropagation();
        // File reader will go here...
      });
  }
My test still fails, but I see the mouse event in the handler's print statement:
unittest-suite-wait-for-done
event: Instance of 'MouseEvent'
FAIL: File Upload can create projects
  Expected: 'File Upload Content'
    Actual: 'Test'
     Which: is different.
  Expected: File Uploa ...
    Actual: Test
            ^
   Differ at offset 0
  
  package:unittest/src/expect.dart 78:29                                                                                                 expect
  ../full/file_upload_test.dart 27:13 
Dart seems to support the same dataTransfer property from JavaScript, so I add that into my handler:
    Element.
      dropEvent.
      forTarget(document).
      listen((event) {
        print('event: ${event}');
        event
          ..preventDefault()
          ..stopPropagation();

        var file = event.dataTransfer.files.first;
        print('file: $file');
      });
That results in an error because the dataTransfer property on my event is null:
Exception: The null object does not have a getter 'files'.

NoSuchMethodError : method not found: 'files'
Receiver: null
Arguments: [] dart:core-patch/object_patch.dart:20
Object.noSuchMethod dart:core-patch/object_patch.dart:20
Full._attachMouseHandlers.<anonymous closure> package:ice_code_editor/full.dart:229
Node.dispatchEvent /mnt/data/b/build/slave/dartium-lucid64-full-trunk/build/src/out/Release/gen/blink/bindings/dart/dart/html/Node.dart:215
file_upload_tests.<anonymous closure>.<anonymous closure> file_upload_test.dart:25
_run.<anonymous closure>
Unfortunately, I find myself in familiar territory here. The dataTransfer property on Dart's MouseEvent is final—there is no way to update it. Even if there was, I have no means of creating an instance of DataTransfer—it has no constructor (it is only instantiated internally).

Perhaps this is a job for mocks?

I import the mock library:
import 'package:unittest/unittest.dart';
import 'package:unittest/mock.dart';
Then create a mock version of the MouseEvent class:
class MockMouseEvent extends Mock implements MouseEvent {
  MockMouseEvent(String type);
}
If this works, I will add a mock DataTransfer. First, I update my test to dispatch my mock mouse event:
    test("can create projects", (){
      var file_upload_event = new MockMouseEvent('drop');
      document.dispatchEvent(file_upload_event);

      expect(
        editor.content,
        'File Upload Content'
      );
    });
And, when I run my test now, I get:
unittest-suite-wait-for-done undefined:1
ERROR: File Upload can create projects
  Test failed: Caught InvalidStateError: Internal Dartium Exception
  ../../../../../../mnt/data/b/build/slave/dartium-lucid64-full-trunk/build/src/out/Release/gen/blink/bindings/dart/dart/html/Node.dart 215:120  Node.dispatchEvent
  ../full/file_upload_test.dart 29:29                                                                                                            file_upload_tests.<fn>.<fn>
That is disappointing.

I am starting to get the feeling that testing anything involving events in Dart will not work. It is certainly frustrating because I would like to do the right thing for my codebase. One of the reasons that I switched from JavaScript to Dart for ICE was to gain the assurance that comes with testing. And yet I have hit my second testing dead-end.

Bother.


Day #872

Wednesday, September 11, 2013

Pre-Supporting an API


I got the tests passing last night in ctrl-alt-foo, keyboard shortcut library. That does not necessarily mean that the entire library works however. Much of the code and original functionality in that library was originally extracted from the ICE Code Editor. So I try the code out in there.

For the most part, I seem to have this working. When I smoke test ICE, I am able to create new projects and open existing projects using keyboard shortcuts. Oddly, focusing of the INPUT fields seems to have broken. I can get it working again with a Timer.run() around the focus() calls:
    // ...
    parent.append(dialog);
    // Allow event to finish propagating so that another element can be active
    Timer.run(()=> dialog.query('input').focus());
    // ...
A Timer.run() waits one event loop before performing the action. My initial thought is that last night's crazy JavaScript eval'd event listener combined with a Dart event stream has a minor impedance mismatch. Perhaps the event has not quite finished bubbling which triggers the dialog to be added to the parent element before the browser is ready to perform other actions.

My supposition turns out to be incorrect. I can add data and manipulate the DOM elements. I just cannot focus them. I suspect that this is because I am not preventing the default event actions from taking place when shortcuts are handled. I could invest time in doing this, but it seems like a lot of work especially since it seems likely that Dart will soon support creating keyboard events.

I hate to leave a problem half solved, but I am reasonably sure that I will just end up exploring new ways to abuse js-interop. So instead I shift focus to getting ready for the new keyboard event API. If I can get that close, then it should make it easier to switch once the changes land in Dart.

The proposed API will be:
var stream = KeyEvent.keyDownEvent.forTarget(document.body);
var subscription = stream.listen((keyEvent) {
  print(keyEvent.charCode);
  print(keyEvent.keyCode);
});

var k = new KeyEvent('keydown', keyCode: 65, charCode: 97);
stream.add(k);
I already have an “X” version of KeyEvent (KeyEventX). To conform to the new API, I need to convert my existing constructor into a wrapper constructor:
class KeyEventX implements KeyEvent {
  int keyCode;
  bool ctrlKey, metaKey, shiftKey;
  var _parent;

  KeyEventX.wrap(KeyboardEvent parent) {
    keyCode = parent.keyCode;
    ctrlKey = parent.ctrlKey;
    metaKey = parent.metaKey;
    shiftKey = parent.shiftKey;
  }
  // ...
}
The wrap() named constructor mimics the change in the proposed update to Dart's KeyEvent, though the implementation is slightly different owing to my use of JavaScript. Still, the exposed API should be the same:
    // ...
    var dartCallback = new js.Callback.many((event) {
      _controller.add(new KeyEventX.wrap(event));
    });
    // ...
That particular bit of code can probably go away once KeyEvent has its own nice streams, but if it needs to remain for any reason, I can make the quick change of removing the “X” from the class name.

As for dispatching the event, my use of JavaScript complicates supporting the same API. For now, I add the same constructor:
KeyEventX(String typem
      {Window view, bool canBubble: true, bool cancelable: true, int keyCode: 0,
      int charCode: 0, int keyLocation: 1, bool ctrlKey: false,
      bool altKey: false, bool shiftKey: false, bool metaKey: false,
      bool altGraphKey: false}) {
    // js-interop here
  }

But build my JavaScript event in there. I cut my effort there, however. Adding an event directly to a stream is non-standard Dart (though it certainly makes sense in this context). To get that working, I think I would have to duplicate a good part of the forthcoming patch. Rather than duplicating effort, I stop here with a reasonable chunk of the proposed API supported. Hopefully this will translate into a quicker adoption when the change lands.

/me waits patiently...


Day #871

Tuesday, September 10, 2013

The Power of JavaScript (in Dart)


I was able to generate JavaScript code from Dart last night, but was not quite able to use it to register event handlers. Tonight, I hope to do just that, so that I can finally generate and test keyboard events with data in Dart.

This is all because, at present, there is no way to add character data to custom built keyboard events in Dart. Actually, it turns out that there is no way to do so in JavaScript (Chrome/WebKit) either, but there are ways around this thanks to JavaScript's weak typing. Dart may not be statically typed, but it is strongly typed. The end result being that there is no way to trick it into seeing a vanilla event as a keyboard event as is possible in JavaScript.

The code that I am dynamically creating to listen for events in JavaScript is as follows:
  static void createJsListener() {
    js.context.eval('''
function _dart_key_event_x(target_classname, cb) {
  //var target = document.getElementsByClassName(target_classname)[0];
  target = document;

  target.addEventListener("keydown", function(event) {
    console.log("js event " + event);
    cb(event);
  });
}''');
  }
I am using the js-interop top-level context property to access JavaScript's eval(). This is admittedly pretty awful, but I cannot dynamically create functions with JavaScript's function keyword. So I place my dynamic JavaScript code inside a string, which js-interop is quite good at proxying into JavaScript. Actually, I will likely have to make that more dynamic in the future so that I can operate on HTML elements besides document, but I keep it simple here.

Once the _dart_key_event_x() JavaScript function is eval'd into existence, I can access it like any other top-level JavaScript function or property via Dart js-interop's context property:
js.context._dart_key_event_x(temp_classname, js.context.dartCallback);
Here, I am calling it with a temporary CSS class name that I will use to uniquely identify the HTML element to the JavaScript code. Currently that does nothing in the _dart_key_event_x() JavaScript function since I am only listening for events on document. I will need to supply a unique identifier because js-interop cannot pass object data back and forth—just primitives (that's not 100% true, but close enough for my purposes here). Anyhow, that first parameter is not even used yet as I am just listening on document.

The second parameter that is suppltied to _dart_key_event_x() is a callback. What is interesting here is that I am supplying a Dart callback for JavaScript to call. To make that work, I need to use the Callback class in js-interop:
    var dartCallback = new js.Callback.many((event) {
     //
    });
At the risk of doing the usual computer programming book thing, I make a big leap and put that together such that the callback puts a decorated version of the event onto a stream:
  static Stream<KeyEventX> onKeyDown(EventTarget target) {
    var _controller = new StreamController.broadcast();

    var temp_classname = "dart_id-${new Random().nextInt(1000)}";

    createJsListener();
    var dartCallback = new js.Callback.many((event) {
      _controller.add(new KeyEventX(event));
    });

    js.context._dart_key_event_x(temp_classname, dartCallback);

    return _controller.stream;
  }
And that almost works, but I keep getting js-interop proxy errors when I try to retain a reference to that JavaScript event inside KeyEventX (the class decorating the JavaScript event):
Caught Proxy js-ref-10 has been invalidated.
  package:js/js.dart 1037:22
  package:js/js.dart 1027:20
Proxy.noSuchMethod
  package:ctrl_alt_foo/key_event_x.dart 98:38
KeyEventX.keyCode
  ../test.dart 27:34
main.<fn>.<fn>
  dart:async 
I do manage to get this working by extracting the values that I need from the event directly in the KeyEventX constructor:
class KeyEventX implements KeyEvent {
  int keyCode;

  KeyEventX(KeyboardEvent parent) {
    keyCode = parent.keyCode;
  }

  bool isKey(String char) {
    return KeyIdentifier.keyCodeFor(char) == keyCode;
  }
  // ...
}
With that, I actually have one of my keyboard tests passing:
  test("can listen for key events", (){
    KeyboardEventStreamX.onKeyDown(document).listen(expectAsync1((e) {
      expect(e.isKey('A'), true);
    }));

    type('A');
  });
I can create and dispatch a keyboard event with character data attached and subscribe to an event that sees that same data come back through. All thanks to the power of JavaScript. In Dart.


Day #870

Monday, September 9, 2013

Dynamically Generated JavaScript from Dart


I'll admit that I am completely obsessed at this point.

I must figure out a way to test keyboard events in Dart. I must.

I was thwarted in my attempts to use JavaScript, via js-interop, to generate keyboard events with character data. It turns out that this really does not work in JavaScript—at least not with Chrome/WebKit. Most JavaScript libraries that do this wind up populating additional Event properties like which or use other event types to fake keyboard events. Since Dart is typed, these kinds of tricks won't work for me.

So it is time to try even dumber tricks.

Tonight's try will be to add listeners in JavaScript, where keyboard event malarky is acceptable. If successful, I will convert those listeners to streams in Dart.

The first question is, how do I create a function in JavaScript that can be used in Dart? I could add it via a <script> tag, but then anyone using my library would have to do the same. I would also have to deal with <script> load order issues. No thanks.

What about JavaScript's eval()? I would normally avoid that, but it might just do the trick. By way of proof of concept, I eval() a JavaScript function into life from Dart, and then call it from Dart as well:
    js.context.eval("function hi(name) {alert('hi ' + name)}");
    js.context.hi('bob');
And that just works!



From there, I can create a JavaScript function that will invoke a callback in Dart:
  static void createJsListener() {
    js.context.eval('''
function _dart_key_event_x(target_classname, cb) {
  //var target = document.getElementsByClassName(target_classname)[0];
  target = document;

  target.addEventListener("keydown", function(event) {
    console.log("js event " + event);
    cb(event);
  });
}''');
  }
And I can can get that JavaScript listener to invoke my Dart callback function:
    createJsListener();
    js.context.dartCallback = new js.Callback.many((event) {
      print('event! ${event}');
      _controller.add(new KeyEventX(event));
    });

    js.context._dart_key_event_x(temp_classname, js.context.dartCallback);
I am still not quite done. The event that is returned is a proxy to the JavaScript event object. I will need a little more malarky to convert that into a KeyEvent sub-class in Dart. But it does look like it will be possible. If I print the keyCode from that proxied object:
class KeyEventX implements KeyEvent {
  KeyboardEvent _parent;

  KeyEventX(KeyboardEvent parent) {
    _parent = parent;
    print('[KeyEventX] ${parent.keyCode}');
  }
  // ...
}
Then I see an actual keycode:
[KeyEventX] 65
I will pick back up tomorrow to see if I can finish this off. But, so far, the ability to generate JavaScript from Dart seems like it may be just what I need.


Day #869