File: jar_serialization_test.js

package info (click to toggle)
node-tough-cookie 2.3.4+dfsg-1~bpo9+1
  • links: PTS, VCS
  • area: main
  • in suites: stretch-backports
  • size: 608 kB
  • sloc: makefile: 8; sh: 2
file content (356 lines) | stat: -rw-r--r-- 11,817 bytes parent folder | download | duplicates (2)
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
/*!
 * Copyright (c) 2015, Salesforce.com, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. Neither the name of Salesforce.com nor the names of its contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

'use strict';
var vows = require('vows');
var assert = require('assert');
var tough = require('../lib/cookie');
var Cookie = tough.Cookie;
var CookieJar = tough.CookieJar;
var Store = tough.Store;
var MemoryCookieStore = tough.MemoryCookieStore;
var VERSION = require('../package.json').version;

var domains = ['example.com','www.example.com','example.net'];
var paths = ['/','/foo','/foo/bar'];

var isInteger = Number.isInteger || function(value) {
  // Node 0.10 (still supported) doesn't have Number.isInteger
  // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  return typeof value === "number" &&
    isFinite(value) &&
    Math.floor(value) === value;
};

function setUp(context) {
  context.now = new Date();
  context.nowISO = context.now.toISOString();
  context.expires = new Date(context.now.getTime() + 86400000);

  var c, domain;
  context.jar = new CookieJar();

  context.totalCookies = 0;

  // Do paths first since the MemoryCookieStore index is domain at the top
  // level. This should cause the preservation of creation order in
  // getAllCookies to be exercised.
  for (var i = 0; i<paths.length; i++) {
    var path = paths[i];
    for (var j = 0; j<domains.length; j++) {
      domain = domains[j];
      c = new Cookie({
        expires: context.expires,
        domain: domain,
        path: path,
        key: 'key',
        value: 'value'+j+i
      });
      context.jar.setCookieSync(c, 'http://'+domain+'/', {now: context.now});
      context.totalCookies++;
    }
  }

  // corner cases
  domain = 'example.com';
  var cornerCases = [
    { expires: 'Infinity', key: 'infExp', value: 'infExp' },
    { maxAge: 3600, key: 'max', value: 'max' },
    { expires: context.expires, key: 'flags', value: 'flags',
      secure: true, httpOnly: true },
    { expires: context.expires, key: 'honly', value: 'honly',
      hostOnly: true, domain: 'www.example.org' },
  ];

  for (var i = 0; i<cornerCases.length; i++) {
    cornerCases[i].domain = cornerCases[i].domain || 'example.org';
    cornerCases[i].path = '/';
    c = new Cookie(cornerCases[i]);
    context.jar.setCookieSync(c, 'https://www.example.org/', {now: context.now});
    context.totalCookies++;
  }
}

function checkMetadata(serialized) {
  assert.notEqual(serialized, null);
  assert.isObject(serialized);
  assert.equal(serialized.version, 'tough-cookie@'+VERSION);
  assert.equal(serialized.storeType, 'MemoryCookieStore');
  assert.typeOf(serialized.rejectPublicSuffixes, 'boolean');
  assert.isArray(serialized.cookies);
}

var serializedCookiePropTypes = {
  'key': 'string',
  'value': 'string',
  'expires': 'isoDate', // if "Infinity" it's supposed to be missing
  'maxAge': 'intOrInf',
  'domain': 'string',
  'path': 'string',
  'secure': 'boolean',
  'httpOnly': 'boolean',
  'extensions': 'array', // of strings, technically
  'hostOnly': 'boolean',
  'pathIsDefault': 'boolean',
  'creation': 'isoDate',
  'lastAccessed': 'isoDate'
};

function validateSerializedCookie(cookie) {
  assert.isObject(cookie);
  assert.isFalse(cookie instanceof Cookie);

  Object.keys(cookie).forEach(function(prop) {
    var type = serializedCookiePropTypes[prop];
    switch(type) {
    case 'string':
    case 'boolean':
    case 'array':
    case 'number':
      assert.typeOf(cookie[prop], type);
      break;

    case 'intOrInf':
      if (cookie[prop] === 'Infinity' || cookie[prop] === '-Infinity') {
        assert(true);
      } else {
        assert(isInteger(cookie[prop]),
               "serialized property isn't integer: "+prop);
      }
      break;

    case 'isoDate':
      // rather than a regexp, assert it's parsable and equal
      var parsed = Date.parse(cookie[prop]);
      assert(parsed, 'could not parse serialized date property');
      // assert.equals(cookie[prop], parsed.toISOString());
      break;

    default:
      assert.fail("unexpected serialized property: "+prop);
    }
  });

}

vows
  .describe('CookieJar serialization')
  .addBatch({
    "Assumptions:": {
      "serializableProperties all accounted for": function() {
        var actualKeys = Cookie.serializableProperties.concat([]); // copy
        actualKeys.sort();
        var expectedKeys = Object.keys(serializedCookiePropTypes);
        expectedKeys.sort();
        assert.deepEqual(actualKeys, expectedKeys);
      }
    }
  })
  .addBatch({
    "For Stores without getAllCookies": {
      topic: function() {
        var store = new Store();
        store.synchronous = true;
        var jar = new CookieJar(store);
        return jar;
      },
      "Cannot call toJSON": function(jar) {
        assert.throws(function() {
          jar.toJSON();
        }, 'getAllCookies is not implemented (therefore jar cannot be serialized)');
      }
    }
  })
  .addBatch({
    "For async stores": {
      topic: function() {
        var store = new MemoryCookieStore();
        store.synchronous = false; // pretend it's async
        var jar = new CookieJar(store);
        return jar;
      },
      "Cannot call toJSON": function(jar) {
        assert.throws(function() {
          jar.toJSON();
        }, 'CookieJar store is not synchronous; use async API instead.');
      }
    }
  })
  .addBatch({
    "With a small store": {
      topic: function() {
        var now = this.now = new Date();
        this.jar = new CookieJar();
        // domain cookie with custom extension
        var cookie = Cookie.parse('sid=one; domain=example.com; path=/; fubar');
        this.jar.setCookieSync(cookie, 'http://example.com/', {now: this.now});

        cookie = Cookie.parse('sid=two; domain=example.net; path=/; fubar');
        this.jar.setCookieSync(cookie, 'http://example.net/', {now: this.now});

        return this.jar;
      },

      "serialize synchronously": {
        topic: function(jar) {
          return jar.serializeSync();
        },
        "it gives a serialization with the two cookies": function(data) {
          checkMetadata(data);
          assert.equal(data.cookies.length, 2);
          data.cookies.forEach(function(cookie) {
            validateSerializedCookie(cookie);
          });
        },
        "then deserialize": {
          topic: function(data) {
            return CookieJar.deserializeSync(data);
          },
          "memstores are identical": function(newJar) {
            assert.deepEqual(newJar.store, this.jar.store);
          }
        },
        "then deserialize again": {
          topic: function(data) {
            return CookieJar.deserializeSync(data);
          },
          "memstores are still identical": function(newJar) {
            assert.deepEqual(newJar.store, this.jar.store);
          }
        }
      },

      "serialize asynchronously": {
        topic: function(jar) {
          jar.serialize(this.callback);
        },
        "it gives a serialization with the two cookies": function(data) {
          checkMetadata(data);
          assert.equal(data.cookies.length, 2);
          data.cookies.forEach(function(cookie) {
            validateSerializedCookie(cookie);
          });
        },
        "then deserialize": {
          topic: function(data) {
            CookieJar.deserialize(data, this.callback);
          },
          "memstores are identical": function(newJar) {
            assert.deepEqual(this.jar.store, newJar.store);
          }
        }
      }
    }
  })
  .addBatch({
    "With a moderately-sized store": {
      topic: function() {
        setUp(this);
        this.jar.serialize(this.callback);
      },
      "has expected metadata": function(err,jsonObj) {
        assert.isNull(err);
        assert.equal(jsonObj.version, 'tough-cookie@'+VERSION);
        assert.isTrue(jsonObj.rejectPublicSuffixes);
        assert.equal(jsonObj.storeType, 'MemoryCookieStore');
      },
      "has a bunch of objects as 'raw' cookies": function(jsonObj) {
        assert.isArray(jsonObj.cookies);
        assert.equal(jsonObj.cookies.length, this.totalCookies);

        jsonObj.cookies.forEach(function(cookie) {
          validateSerializedCookie(cookie);

          if (cookie.key === 'key') {
            assert.match(cookie.value, /^value\d\d/);
          }

          if (cookie.key === 'infExp' || cookie.key === 'max') {
            assert.isUndefined(cookie.expires);
          } else {
            assert.strictEqual(cookie.expires, this.expires.toISOString())
          }

          if (cookie.key === 'max') {
            assert.strictEqual(cookie.maxAge, 3600);
          } else {
            assert.isUndefined(cookie.maxAge);
          }

          assert.equal(cookie.hostOnly, cookie.key === 'honly');

          if (cookie.key === 'flags') {
            assert.isTrue(cookie.secure);
            assert.isTrue(cookie.httpOnly);
          } else {
            assert.isUndefined(cookie.secure);
            assert.isUndefined(cookie.httpOnly);
          }

          assert.strictEqual(cookie.creation, this.nowISO);
          assert.strictEqual(cookie.lastAccessed, this.nowISO);

        }, this);
      },

      "then taking it for a round-trip": {
        topic: function(jsonObj) {
          CookieJar.deserialize(jsonObj, this.callback);
        },
        "memstore index is identical": function(err,newJar) {
          assert.deepEqual(newJar.store.idx, this.jar.store.idx);
        },
        "then spot-check retrieval": {
          topic: function(newJar) {
            newJar.getCookies('http://example.org/', this.callback);
          },
          "gets expected cookies": function(results) {
            assert.isArray(results);
            assert.equal(results.length, 2);

            results.forEach(function(cookie) {
              assert.instanceOf(cookie, Cookie);

              if (cookie.key === 'infExp') {
                assert.strictEqual(cookie.expires, "Infinity");
                assert.strictEqual(cookie.TTL(this.now), Infinity);
              } else if (cookie.key === 'max') {
                assert.strictEqual(cookie.TTL(this.now), 3600*1000);
              } else {
                assert.fail('Unexpected cookie key: '+cookie.key);
              }
            }.bind(this));
          }
        }
      }
    }
  })
  .export(module);