summaryrefslogtreecommitdiffstats
path: root/extensions/cookie/test/unit/head_cookies.js
blob: fe4c0a53dc53f9991df28cc2e59ec71ff8f073d7 (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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/NetUtil.jsm");
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");

var Cc = Components.classes;
var Ci = Components.interfaces;
var Cr = Components.results;

XPCOMUtils.defineLazyServiceGetter(Services, "cookies",
                                   "@mozilla.org/cookieService;1",
                                   "nsICookieService");
XPCOMUtils.defineLazyServiceGetter(Services, "cookiemgr",
                                   "@mozilla.org/cookiemanager;1",
                                   "nsICookieManager2");

XPCOMUtils.defineLazyServiceGetter(Services, "etld",
                                   "@mozilla.org/network/effective-tld-service;1",
                                   "nsIEffectiveTLDService");

function do_check_throws(f, result, stack)
{
  if (!stack)
    stack = Components.stack.caller;

  try {
    f();
  } catch (exc) {
    if (exc.result == result)
      return;
    do_throw("expected result " + result + ", caught " + exc, stack);
  }
  do_throw("expected result " + result + ", none thrown", stack);
}

// Helper to step a generator function and catch a StopIteration exception.
function do_run_generator(generator)
{
  try {
    generator.next();
  } catch (e) {
    if (e != StopIteration)
      do_throw("caught exception " + e, Components.stack.caller);
  }
}

// Helper to finish a generator function test.
function do_finish_generator_test(generator)
{
  do_execute_soon(function() {
    generator.close();
    do_test_finished();
  });
}

function _observer(generator, topic) {
  Services.obs.addObserver(this, topic, false);

  this.generator = generator;
  this.topic = topic;
}

_observer.prototype = {
  observe: function (subject, topic, data) {
    do_check_eq(this.topic, topic);

    Services.obs.removeObserver(this, this.topic);

    // Continue executing the generator function.
    if (this.generator)
      do_run_generator(this.generator);

    this.generator = null;
    this.topic = null;
  }
}

// Close the cookie database. If a generator is supplied, it will be invoked
// once the close is complete.
function do_close_profile(generator) {
  // Register an observer for db close.
  let obs = new _observer(generator, "cookie-db-closed");

  // Close the db.
  let service = Services.cookies.QueryInterface(Ci.nsIObserver);
  service.observe(null, "profile-before-change", "shutdown-persist");
}

// Load the cookie database. If a generator is supplied, it will be invoked
// once the load is complete.
function do_load_profile(generator) {
  // Register an observer for read completion.
  let obs = new _observer(generator, "cookie-db-read");

  // Load the profile.
  let service = Services.cookies.QueryInterface(Ci.nsIObserver);
  service.observe(null, "profile-do-change", "");
}

// Set a single session cookie using http and test the cookie count
// against 'expected'
function do_set_single_http_cookie(uri, channel, expected) {
  Services.cookies.setCookieStringFromHttp(uri, null, null, "foo=bar", null, channel);
  do_check_eq(Services.cookiemgr.countCookiesFromHost(uri.host), expected);
}

// Set four cookies; with & without channel, http and non-http; and test
// the cookie count against 'expected' after each set.
function do_set_cookies(uri, channel, session, expected) {
  let suffix = session ? "" : "; max-age=1000";

  // without channel
  Services.cookies.setCookieString(uri, null, "oh=hai" + suffix, null);
  do_check_eq(Services.cookiemgr.countCookiesFromHost(uri.host), expected[0]);
  // with channel
  Services.cookies.setCookieString(uri, null, "can=has" + suffix, channel);
  do_check_eq(Services.cookiemgr.countCookiesFromHost(uri.host), expected[1]);
  // without channel, from http
  Services.cookies.setCookieStringFromHttp(uri, null, null, "cheez=burger" + suffix, null, null);
  do_check_eq(Services.cookiemgr.countCookiesFromHost(uri.host), expected[2]);
  // with channel, from http
  Services.cookies.setCookieStringFromHttp(uri, null, null, "hot=dog" + suffix, null, channel);
  do_check_eq(Services.cookiemgr.countCookiesFromHost(uri.host), expected[3]);
}

function do_count_enumerator(enumerator) {
  let i = 0;
  while (enumerator.hasMoreElements()) {
    enumerator.getNext();
    ++i;
  }
  return i;
}

function do_count_cookies() {
  return do_count_enumerator(Services.cookiemgr.enumerator);
}

// Helper object to store cookie data.
function Cookie(name,
                value,
                host,
                path,
                expiry,
                lastAccessed,
                creationTime,
                isSession,
                isSecure,
                isHttpOnly)
{
  this.name = name;
  this.value = value;
  this.host = host;
  this.path = path;
  this.expiry = expiry;
  this.lastAccessed = lastAccessed;
  this.creationTime = creationTime;
  this.isSession = isSession;
  this.isSecure = isSecure;
  this.isHttpOnly = isHttpOnly;

  let strippedHost = host.charAt(0) == '.' ? host.slice(1) : host;

  try {
    this.baseDomain = Services.etld.getBaseDomainFromHost(strippedHost);
  } catch (e) {
    if (e.result == Cr.NS_ERROR_HOST_IS_IP_ADDRESS ||
        e.result == Cr.NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS)
      this.baseDomain = strippedHost;
  }
}

// Object representing a database connection and associated statements. The
// implementation varies depending on schema version.
function CookieDatabaseConnection(file, schema)
{
  // Manually generate a cookies.sqlite file with appropriate rows, columns,
  // and schema version. If it already exists, just set up our statements.
  let exists = file.exists();

  this.db = Services.storage.openDatabase(file);
  this.schema = schema;
  if (!exists)
    this.db.schemaVersion = schema;

  switch (schema) {
  case 1:
    {
      if (!exists) {
        this.db.executeSimpleSQL(
          "CREATE TABLE moz_cookies (       \
             id INTEGER PRIMARY KEY,        \
             name TEXT,                     \
             value TEXT,                    \
             host TEXT,                     \
             path TEXT,                     \
             expiry INTEGER,                \
             isSecure INTEGER,              \
             isHttpOnly INTEGER)");
      }

      this.stmtInsert = this.db.createStatement(
        "INSERT INTO moz_cookies (        \
           id,                            \
           name,                          \
           value,                         \
           host,                          \
           path,                          \
           expiry,                        \
           isSecure,                      \
           isHttpOnly)                    \
           VALUES (                       \
           :id,                           \
           :name,                         \
           :value,                        \
           :host,                         \
           :path,                         \
           :expiry,                       \
           :isSecure,                     \
           :isHttpOnly)");

      this.stmtDelete = this.db.createStatement(
        "DELETE FROM moz_cookies WHERE id = :id");

      break;
    }

  case 2:
    {
      if (!exists) {
        this.db.executeSimpleSQL(
          "CREATE TABLE moz_cookies (       \
             id INTEGER PRIMARY KEY,        \
             name TEXT,                     \
             value TEXT,                    \
             host TEXT,                     \
             path TEXT,                     \
             expiry INTEGER,                \
             lastAccessed INTEGER,          \
             isSecure INTEGER,              \
             isHttpOnly INTEGER)");
      }

      this.stmtInsert = this.db.createStatement(
        "INSERT OR REPLACE INTO moz_cookies ( \
           id,                            \
           name,                          \
           value,                         \
           host,                          \
           path,                          \
           expiry,                        \
           lastAccessed,                  \
           isSecure,                      \
           isHttpOnly)                    \
           VALUES (                       \
           :id,                           \
           :name,                         \
           :value,                        \
           :host,                         \
           :path,                         \
           :expiry,                       \
           :lastAccessed,                 \
           :isSecure,                     \
           :isHttpOnly)");

      this.stmtDelete = this.db.createStatement(
        "DELETE FROM moz_cookies WHERE id = :id");

      this.stmtUpdate = this.db.createStatement(
        "UPDATE moz_cookies SET lastAccessed = :lastAccessed WHERE id = :id");

      break;
    }

  case 3:
    {
      if (!exists) {
        this.db.executeSimpleSQL(
          "CREATE TABLE moz_cookies (       \
            id INTEGER PRIMARY KEY,         \
            baseDomain TEXT,                \
            name TEXT,                      \
            value TEXT,                     \
            host TEXT,                      \
            path TEXT,                      \
            expiry INTEGER,                 \
            lastAccessed INTEGER,           \
            isSecure INTEGER,               \
            isHttpOnly INTEGER)");

        this.db.executeSimpleSQL(
          "CREATE INDEX moz_basedomain ON moz_cookies (baseDomain)");
      }

      this.stmtInsert = this.db.createStatement(
        "INSERT INTO moz_cookies (        \
           id,                            \
           baseDomain,                    \
           name,                          \
           value,                         \
           host,                          \
           path,                          \
           expiry,                        \
           lastAccessed,                  \
           isSecure,                      \
           isHttpOnly)                    \
           VALUES (                       \
           :id,                           \
           :baseDomain,                   \
           :name,                         \
           :value,                        \
           :host,                         \
           :path,                         \
           :expiry,                       \
           :lastAccessed,                 \
           :isSecure,                     \
           :isHttpOnly)");

      this.stmtDelete = this.db.createStatement(
        "DELETE FROM moz_cookies WHERE id = :id");

      this.stmtUpdate = this.db.createStatement(
        "UPDATE moz_cookies SET lastAccessed = :lastAccessed WHERE id = :id");

      break;
    }

  case 4:
    {
      if (!exists) {
        this.db.executeSimpleSQL(
          "CREATE TABLE moz_cookies (       \
            id INTEGER PRIMARY KEY,         \
            baseDomain TEXT,                \
            name TEXT,                      \
            value TEXT,                     \
            host TEXT,                      \
            path TEXT,                      \
            expiry INTEGER,                 \
            lastAccessed INTEGER,           \
            creationTime INTEGER,           \
            isSecure INTEGER,               \
            isHttpOnly INTEGER              \
            CONSTRAINT moz_uniqueid UNIQUE (name, host, path))");

        this.db.executeSimpleSQL(
          "CREATE INDEX moz_basedomain ON moz_cookies (baseDomain)");

        this.db.executeSimpleSQL(
          "PRAGMA journal_mode = WAL");
      }

      this.stmtInsert = this.db.createStatement(
        "INSERT INTO moz_cookies (        \
           baseDomain,                    \
           name,                          \
           value,                         \
           host,                          \
           path,                          \
           expiry,                        \
           lastAccessed,                  \
           creationTime,                  \
           isSecure,                      \
           isHttpOnly)                    \
           VALUES (                       \
           :baseDomain,                   \
           :name,                         \
           :value,                        \
           :host,                         \
           :path,                         \
           :expiry,                       \
           :lastAccessed,                 \
           :creationTime,                 \
           :isSecure,                     \
           :isHttpOnly)");

      this.stmtDelete = this.db.createStatement(
        "DELETE FROM moz_cookies          \
           WHERE name = :name AND host = :host AND path = :path");

      this.stmtUpdate = this.db.createStatement(
        "UPDATE moz_cookies SET lastAccessed = :lastAccessed \
           WHERE name = :name AND host = :host AND path = :path");

      break;
    }

  default:
    do_throw("unrecognized schemaVersion!");
  }
}

CookieDatabaseConnection.prototype =
{
  insertCookie: function(cookie)
  {
    if (!(cookie instanceof Cookie))
      do_throw("not a cookie");

    switch (this.schema)
    {
    case 1:
      this.stmtInsert.bindByName("id", cookie.creationTime);
      this.stmtInsert.bindByName("name", cookie.name);
      this.stmtInsert.bindByName("value", cookie.value);
      this.stmtInsert.bindByName("host", cookie.host);
      this.stmtInsert.bindByName("path", cookie.path);
      this.stmtInsert.bindByName("expiry", cookie.expiry);
      this.stmtInsert.bindByName("isSecure", cookie.isSecure);
      this.stmtInsert.bindByName("isHttpOnly", cookie.isHttpOnly);
      break;

    case 2:
      this.stmtInsert.bindByName("id", cookie.creationTime);
      this.stmtInsert.bindByName("name", cookie.name);
      this.stmtInsert.bindByName("value", cookie.value);
      this.stmtInsert.bindByName("host", cookie.host);
      this.stmtInsert.bindByName("path", cookie.path);
      this.stmtInsert.bindByName("expiry", cookie.expiry);
      this.stmtInsert.bindByName("lastAccessed", cookie.lastAccessed);
      this.stmtInsert.bindByName("isSecure", cookie.isSecure);
      this.stmtInsert.bindByName("isHttpOnly", cookie.isHttpOnly);
      break;

    case 3:
      this.stmtInsert.bindByName("id", cookie.creationTime);
      this.stmtInsert.bindByName("baseDomain", cookie.baseDomain);
      this.stmtInsert.bindByName("name", cookie.name);
      this.stmtInsert.bindByName("value", cookie.value);
      this.stmtInsert.bindByName("host", cookie.host);
      this.stmtInsert.bindByName("path", cookie.path);
      this.stmtInsert.bindByName("expiry", cookie.expiry);
      this.stmtInsert.bindByName("lastAccessed", cookie.lastAccessed);
      this.stmtInsert.bindByName("isSecure", cookie.isSecure);
      this.stmtInsert.bindByName("isHttpOnly", cookie.isHttpOnly);
      break;

    case 4:
      this.stmtInsert.bindByName("baseDomain", cookie.baseDomain);
      this.stmtInsert.bindByName("name", cookie.name);
      this.stmtInsert.bindByName("value", cookie.value);
      this.stmtInsert.bindByName("host", cookie.host);
      this.stmtInsert.bindByName("path", cookie.path);
      this.stmtInsert.bindByName("expiry", cookie.expiry);
      this.stmtInsert.bindByName("lastAccessed", cookie.lastAccessed);
      this.stmtInsert.bindByName("creationTime", cookie.creationTime);
      this.stmtInsert.bindByName("isSecure", cookie.isSecure);
      this.stmtInsert.bindByName("isHttpOnly", cookie.isHttpOnly);
      break;

    default:
      do_throw("unrecognized schemaVersion!");
    }

    do_execute_stmt(this.stmtInsert);
  },

  deleteCookie: function(cookie)
  {
    if (!(cookie instanceof Cookie))
      do_throw("not a cookie");

    switch (this.db.schemaVersion)
    {
    case 1:
    case 2:
    case 3:
      this.stmtDelete.bindByName("id", cookie.creationTime);
      break;

    case 4:
      this.stmtDelete.bindByName("name", cookie.name);
      this.stmtDelete.bindByName("host", cookie.host);
      this.stmtDelete.bindByName("path", cookie.path);
      break;

    default:
      do_throw("unrecognized schemaVersion!");
    }

    do_execute_stmt(this.stmtDelete);
  },

  updateCookie: function(cookie)
  {
    if (!(cookie instanceof Cookie))
      do_throw("not a cookie");

    switch (this.db.schemaVersion)
    {
    case 1:
      do_throw("can't update a schema 1 cookie!");

    case 2:
    case 3:
      this.stmtUpdate.bindByName("id", cookie.creationTime);
      this.stmtUpdate.bindByName("lastAccessed", cookie.lastAccessed);
      break;

    case 4:
      this.stmtDelete.bindByName("name", cookie.name);
      this.stmtDelete.bindByName("host", cookie.host);
      this.stmtDelete.bindByName("path", cookie.path);
      this.stmtUpdate.bindByName("lastAccessed", cookie.lastAccessed);
      break;

    default:
      do_throw("unrecognized schemaVersion!");
    }

    do_execute_stmt(this.stmtUpdate);
  },

  close: function()
  {
    this.stmtInsert.finalize();
    this.stmtDelete.finalize();
    if (this.stmtUpdate)
      this.stmtUpdate.finalize();
    this.db.close();

    this.stmtInsert = null;
    this.stmtDelete = null;
    this.stmtUpdate = null;
    this.db = null;
  }
}

function do_get_cookie_file(profile)
{
  let file = profile.clone();
  file.append("cookies.sqlite");
  return file;
}

// Count the cookies from 'host' in a database. If 'host' is null, count all
// cookies.
function do_count_cookies_in_db(connection, host)
{
  let select = null;
  if (host) {
    select = connection.createStatement(
      "SELECT COUNT(1) FROM moz_cookies WHERE host = :host");
    select.bindByName("host", host);
  } else {
    select = connection.createStatement(
      "SELECT COUNT(1) FROM moz_cookies");
  }

  select.executeStep();
  let result = select.getInt32(0);
  select.reset();
  select.finalize();
  return result;
}

// Execute 'stmt', ensuring that we reset it if it throws.
function do_execute_stmt(stmt)
{
  try {
    stmt.executeStep();
    stmt.reset();
  } catch (e) {
    stmt.reset();
    throw e;
  }
}