summaryrefslogtreecommitdiffstats
path: root/services/common/tests/unit/head_http.js
blob: 6c2a0a3f0fc97013d8c14a8d317dbc7a265d64a8 (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
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

/* import-globals-from head_global.js */

var { CommonUtils } = ChromeUtils.importESModule(
  "resource://services-common/utils.sys.mjs"
);

function basic_auth_header(user, password) {
  return "Basic " + btoa(user + ":" + CommonUtils.encodeUTF8(password));
}

function basic_auth_matches(req, user, password) {
  if (!req.hasHeader("Authorization")) {
    return false;
  }

  let expected = basic_auth_header(user, CommonUtils.encodeUTF8(password));
  return req.getHeader("Authorization") == expected;
}

function httpd_basic_auth_handler(body, metadata, response) {
  if (basic_auth_matches(metadata, "guest", "guest")) {
    response.setStatusLine(metadata.httpVersion, 200, "OK, authorized");
    response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false);
  } else {
    body = "This path exists and is protected - failed";
    response.setStatusLine(metadata.httpVersion, 401, "Unauthorized");
    response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false);
  }
  response.bodyOutputStream.write(body, body.length);
}