summaryrefslogtreecommitdiffstats
path: root/services/common/tests/unit/test_tokenauthenticatedrequest.js
blob: a113205ddb38a2b99e2d81ad1c40f7ecd388fead (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

const { CryptoUtils } = ChromeUtils.import(
  "resource://services-crypto/utils.js"
);
const { TokenAuthenticatedRESTRequest } = ChromeUtils.import(
  "resource://services-common/rest.js"
);

function run_test() {
  initTestLogging("Trace");
  run_next_test();
}

add_task(async function test_authenticated_request() {
  _("Ensure that sending a MAC authenticated GET request works as expected.");

  let message = "Great Success!";

  let id = "eyJleHBpcmVzIjogMTM2NTAxMDg5OC4x";
  let key = "qTZf4ZFpAMpMoeSsX3zVRjiqmNs=";
  let method = "GET";

  let nonce = btoa(CryptoUtils.generateRandomBytesLegacy(16));
  let ts = Math.floor(Date.now() / 1000);
  let extra = { ts, nonce };

  let auth;

  let server = httpd_setup({
    "/foo": function(request, response) {
      Assert.ok(request.hasHeader("Authorization"));
      Assert.equal(auth, request.getHeader("Authorization"));

      response.setStatusLine(request.httpVersion, 200, "OK");
      response.bodyOutputStream.write(message, message.length);
    },
  });
  let uri = CommonUtils.makeURI(server.baseURI + "/foo");
  let sig = await CryptoUtils.computeHTTPMACSHA1(id, key, method, uri, extra);
  auth = sig.getHeader();

  let req = new TokenAuthenticatedRESTRequest(uri, { id, key }, extra);
  await req.get();

  Assert.equal(message, req.response.body);

  await promiseStopServer(server);
});