Bug 745424 - Add TokenAuthenticatedRESTRequest; r=gps
authorAnant Narayanan <anant@kix.in>
Tue, 17 Apr 2012 15:32:33 -0700
changeset 95721 74bc65aea171a73248ac5529acd606707ad129a0
parent 95720 df780dfa7862b9e6ea16f7303613b09c0bccd2ea
child 95722 8fc61cdd2a71d07ed7f476fc572c36d465724799
push id1439
push userlsblakk@mozilla.com
push dateMon, 04 Jun 2012 20:19:22 +0000
treeherdermozilla-aurora@ea74834dccd3 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersgps
bugs745424
milestone14.0a1
Bug 745424 - Add TokenAuthenticatedRESTRequest; r=gps
services/common/rest.js
services/common/tests/unit/head_global.js
services/common/tests/unit/test_tokenauthenticatedrequest.js
services/common/tests/unit/xpcshell.ini
--- a/services/common/rest.js
+++ b/services/common/rest.js
@@ -1,18 +1,23 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
 
-const EXPORTED_SYMBOLS = ["RESTRequest", "RESTResponse"];
+const EXPORTED_SYMBOLS = [
+  "RESTRequest",
+  "RESTResponse",
+  "TokenAuthenticatedRESTRequest"
+];
 
 Cu.import("resource://gre/modules/Services.jsm");
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://services-crypto/utils.js");
 Cu.import("resource://services-common/log4moz.js");
 Cu.import("resource://services-common/preferences.js");
 Cu.import("resource://services-common/utils.js");
 
 const Prefs = new Preferences("services.common.rest.");
 
 /**
  * Single use HTTP requests to RESTish resources.
@@ -571,8 +576,44 @@ RESTResponse.prototype = {
   },
 
   /**
    * HTTP body (string)
    */
   body: null
 
 };
+
+/**
+ * Single use MAC authenticated HTTP requests to RESTish resources.
+ *
+ * @param uri
+ *        URI going to the RESTRequest constructor.
+ * @param authToken
+ *        (Object) An auth token of the form {id: (string), key: (string)}
+ *        from which the MAC Authentication header for this request will be
+ *        derived. A token as obtained from
+ *        TokenServerClient.getTokenFromBrowserIDAssertion is accepted.
+ * @param extra
+ *        (Object) Optional extra parameters. Valid keys are: nonce_bytes, ts,
+ *        nonce, and ext. See CrytoUtils.computeHTTPMACSHA1 for information on
+ *        the purpose of these values.
+ */
+function TokenAuthenticatedRESTRequest(uri, authToken, extra) {
+  RESTRequest.call(this, uri);
+  this.authToken = authToken;
+  this.extra = extra || {};
+}
+TokenAuthenticatedRESTRequest.prototype = {
+  __proto__: RESTRequest.prototype,
+
+  dispatch: function dispatch(method, data, onComplete, onProgress) {
+    let sig = CryptoUtils.computeHTTPMACSHA1(
+      this.authToken.id, this.authToken.key, method, this.uri, this.extra
+    );
+
+    this.setHeader("Authorization", sig.getHeader());
+
+    return RESTRequest.prototype.dispatch.call(
+      this, method, data, onComplete, onProgress
+    );
+  },
+};
\ No newline at end of file
--- a/services/common/tests/unit/head_global.js
+++ b/services/common/tests/unit/head_global.js
@@ -42,13 +42,16 @@ registrar.registerFactory(Components.ID(
                           "XULAppInfo", "@mozilla.org/xre/app-info;1",
                           XULAppInfoFactory);
 
 function addResourceAlias() {
   Cu.import("resource://gre/modules/Services.jsm");
   const handler = Services.io.getProtocolHandler("resource")
                   .QueryInterface(Ci.nsIResProtocolHandler);
 
-  let uri = Services.io.newURI("resource:///modules/services-common/", null,
-                               null);
-  handler.setSubstitution("services-common", uri);
+  let modules = ["common", "crypto"];
+  for each (let module in modules) {
+    let uri = Services.io.newURI("resource:///modules/services-" + module + "/",
+                                 null, null);
+    handler.setSubstitution("services-" + module, uri);
+  }
 }
-addResourceAlias();
+addResourceAlias();
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/services/common/tests/unit/test_tokenauthenticatedrequest.js
@@ -0,0 +1,51 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+Cu.import("resource://services-crypto/utils.js");
+Cu.import("resource://services-common/async.js");
+Cu.import("resource://services-common/rest.js");
+Cu.import("resource://services-common/utils.js");
+
+function run_test() {
+  initTestLogging("Trace");
+  run_next_test();
+}
+
+add_test(function test_authenticated_request() {
+  _("Ensure that sending a MAC authenticated GET request works as expected.");
+
+  let message = "Great Success!";
+
+  // TODO: We use a preset key here, but use getTokenFromBrowserIDAssertion()
+  // from TokenServerClient to get a real one when possible. (Bug 745800)
+  let id = "eyJleHBpcmVzIjogMTM2NTAxMDg5OC4x";
+  let key = "qTZf4ZFpAMpMoeSsX3zVRjiqmNs=";
+  let method = "GET";
+  let uri = CommonUtils.makeURI(TEST_SERVER_URL + "foo");
+
+  let nonce = btoa(CryptoUtils.generateRandomBytes(16));
+  let ts = Math.floor(Date.now() / 1000);
+  let extra = {ts: ts, nonce: nonce};
+
+  let sig = CryptoUtils.computeHTTPMACSHA1(id, key, method, uri, extra);
+  let auth = sig.getHeader();
+
+  let server = httpd_setup({"/foo": function(request, response) {
+      do_check_true(request.hasHeader("Authorization"));
+      do_check_eq(auth, request.getHeader("Authorization"));
+
+      response.setStatusLine(request.httpVersion, 200, "OK");
+      response.bodyOutputStream.write(message, message.length);
+    }
+  });
+
+  let req = new TokenAuthenticatedRESTRequest(uri, {id: id, key: key}, extra);
+  let cb = Async.makeSpinningCallback();
+  req.get(cb);
+  let result = cb.wait();
+
+  do_check_eq(null, result);
+  do_check_eq(message, req.response.body);
+
+  server.stop(run_next_test);
+});
\ No newline at end of file
--- a/services/common/tests/unit/xpcshell.ini
+++ b/services/common/tests/unit/xpcshell.ini
@@ -13,9 +13,10 @@ tail =
 [test_utils_utf8.js]
 
 [test_async_chain.js]
 [test_async_querySpinningly.js]
 [test_log4moz.js]
 [test_observers.js]
 [test_preferences.js]
 [test_restrequest.js]
+[test_tokenauthenticatedrequest.js]
 [test_tokenserverclient.js]