summaryrefslogtreecommitdiffstats
path: root/netwerk/test/unit/test_suspend_channel_on_authRetry.js
blob: e6a173fd7f3297a03d6fd21e891028e075a047e3 (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
// This file tests async handling of a channel suspended in DoAuthRetry
// notifying http-on-modify-request and http-on-before-connect observers.
"use strict";

const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js");

XPCOMUtils.defineLazyGetter(this, "URL", function() {
  return "http://localhost:" + httpserv.identity.primaryPort;
});

var obs = Services.obs;

var requestObserver = null;

function AuthPrompt() {}

AuthPrompt.prototype = {
  user: "guest",
  pass: "guest",

  QueryInterface: ChromeUtils.generateQI(["nsIAuthPrompt"]),

  prompt: function ap1_prompt(title, text, realm, save, defaultText, result) {
    do_throw("unexpected prompt call");
  },

  promptUsernameAndPassword: function promptUP(
    title,
    text,
    realm,
    savePW,
    user,
    pw
  ) {
    user.value = this.user;
    pw.value = this.pass;

    obs.addObserver(requestObserver, "http-on-before-connect");
    obs.addObserver(requestObserver, "http-on-modify-request");
    return true;
  },

  promptPassword: function promptPW(title, text, realm, save, pwd) {
    do_throw("unexpected promptPassword call");
  },
};

function requestListenerObserver(
  suspendOnBeforeConnect,
  suspendOnModifyRequest
) {
  this.suspendOnModifyRequest = suspendOnModifyRequest;
  this.suspendOnBeforeConnect = suspendOnBeforeConnect;
}

requestListenerObserver.prototype = {
  suspendOnModifyRequest: false,
  suspendOnBeforeConnect: false,
  gotOnBeforeConnect: false,
  resumeOnBeforeConnect: false,
  gotOnModifyRequest: false,
  resumeOnModifyRequest: false,
  QueryInterface: ChromeUtils.generateQI(["nsIObserver"]),

  observe(subject, topic, data) {
    if (
      topic === "http-on-before-connect" &&
      subject instanceof Ci.nsIHttpChannel
    ) {
      if (this.suspendOnBeforeConnect) {
        let chan = subject.QueryInterface(Ci.nsIHttpChannel);
        executeSoon(() => {
          this.resumeOnBeforeConnect = true;
          chan.resume();
        });
        this.gotOnBeforeConnect = true;
        chan.suspend();
      }
    } else if (
      topic === "http-on-modify-request" &&
      subject instanceof Ci.nsIHttpChannel
    ) {
      if (this.suspendOnModifyRequest) {
        let chan = subject.QueryInterface(Ci.nsIHttpChannel);
        executeSoon(() => {
          this.resumeOnModifyRequest = true;
          chan.resume();
        });
        this.gotOnModifyRequest = true;
        chan.suspend();
      }
    }
  },
};

function Requestor() {}

Requestor.prototype = {
  QueryInterface: ChromeUtils.generateQI(["nsIInterfaceRequestor"]),

  getInterface: function requestor_gi(iid) {
    if (iid.equals(Ci.nsIAuthPrompt)) {
      // Allow the prompt to store state by caching it here
      if (!this.prompt) {
        this.prompt = new AuthPrompt();
      }
      return this.prompt;
    }

    throw Components.Exception("", Cr.NS_ERROR_NO_INTERFACE);
  },

  prompt: null,
};

var listener = {
  expectedCode: -1, // Uninitialized

  onStartRequest: function test_onStartR(request) {
    try {
      if (!Components.isSuccessCode(request.status)) {
        do_throw("Channel should have a success code!");
      }

      if (!(request instanceof Ci.nsIHttpChannel)) {
        do_throw("Expecting an HTTP channel");
      }

      Assert.equal(request.responseStatus, this.expectedCode);
      // The request should be succeeded iff we expect 200
      Assert.equal(request.requestSucceeded, this.expectedCode == 200);
    } catch (e) {
      do_throw("Unexpected exception: " + e);
    }
    throw Components.Exception("", Cr.NS_ERROR_ABORT);
  },

  onDataAvailable: function test_ODA() {
    do_throw("Should not get any data!");
  },

  onStopRequest: function test_onStopR(request, status) {
    Assert.equal(status, Cr.NS_ERROR_ABORT);
    if (requestObserver.suspendOnBeforeConnect) {
      Assert.ok(
        requestObserver.gotOnBeforeConnect &&
          requestObserver.resumeOnBeforeConnect
      );
    }
    if (requestObserver.suspendOnModifyRequest) {
      Assert.ok(
        requestObserver.gotOnModifyRequest &&
          requestObserver.resumeOnModifyRequest
      );
    }
    obs.removeObserver(requestObserver, "http-on-before-connect");
    obs.removeObserver(requestObserver, "http-on-modify-request");
    moveToNextTest();
  },
};

function makeChan(url, loadingUrl) {
  var principal = Services.scriptSecurityManager.createContentPrincipal(
    Services.io.newURI(loadingUrl),
    {}
  );
  return NetUtil.newChannel({
    uri: url,
    loadingPrincipal: principal,
    securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL,
    contentPolicyType: Ci.nsIContentPolicy.TYPE_OTHER,
  });
}

var tests = [
  test_suspend_on_before_connect,
  test_suspend_on_modify_request,
  test_suspend_all,
];

var current_test = 0;

var httpserv = null;

function moveToNextTest() {
  if (current_test < tests.length - 1) {
    // First, gotta clear the auth cache
    Cc["@mozilla.org/network/http-auth-manager;1"]
      .getService(Ci.nsIHttpAuthManager)
      .clearAll();

    current_test++;
    tests[current_test]();
  } else {
    do_test_pending();
    httpserv.stop(do_test_finished);
  }

  do_test_finished();
}

function run_test() {
  httpserv = new HttpServer();

  httpserv.registerPathHandler("/auth", authHandler);

  httpserv.start(-1);

  tests[0]();
}

function test_suspend_on_auth(suspendOnBeforeConnect, suspendOnModifyRequest) {
  var chan = makeChan(URL + "/auth", URL);
  requestObserver = new requestListenerObserver(
    suspendOnBeforeConnect,
    suspendOnModifyRequest
  );
  chan.notificationCallbacks = new Requestor();
  listener.expectedCode = 200; // OK
  chan.asyncOpen(listener);

  do_test_pending();
}

function test_suspend_on_before_connect() {
  test_suspend_on_auth(true, false);
}

function test_suspend_on_modify_request() {
  test_suspend_on_auth(false, true);
}

function test_suspend_all() {
  test_suspend_on_auth(true, true);
}

// PATH HANDLERS

// /auth
function authHandler(metadata, response) {
  // btoa("guest:guest"), but that function is not available here
  var expectedHeader = "Basic Z3Vlc3Q6Z3Vlc3Q=";

  var body;
  if (
    metadata.hasHeader("Authorization") &&
    metadata.getHeader("Authorization") == expectedHeader
  ) {
    response.setStatusLine(metadata.httpVersion, 200, "OK, authorized");
    response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false);

    body = "success";
  } else {
    // didn't know guest:guest, failure
    response.setStatusLine(metadata.httpVersion, 401, "Unauthorized");
    response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false);

    body = "failed";
  }

  response.bodyOutputStream.write(body, body.length);
}