diff options
Diffstat (limited to 'testing/web-platform/tests/storage')
40 files changed, 1444 insertions, 0 deletions
diff --git a/testing/web-platform/tests/storage/META.yml b/testing/web-platform/tests/storage/META.yml new file mode 100644 index 0000000000..2aad1fb513 --- /dev/null +++ b/testing/web-platform/tests/storage/META.yml @@ -0,0 +1,4 @@ +spec: https://storage.spec.whatwg.org/ +suggested_reviewers: + - annevk + - inexorabletash diff --git a/testing/web-platform/tests/storage/README.md b/testing/web-platform/tests/storage/README.md new file mode 100644 index 0000000000..8d0dca31b4 --- /dev/null +++ b/testing/web-platform/tests/storage/README.md @@ -0,0 +1,7 @@ +This directory contains the Storage test suite. + +To run the tests in this test suite within a browser, go to: <https://wpt.live/storage/>. + +The living standard is: <https://storage.spec.whatwg.org/> + +The API is at: <https://storage.spec.whatwg.org/#api> diff --git a/testing/web-platform/tests/storage/buckets/META.yml b/testing/web-platform/tests/storage/buckets/META.yml new file mode 100644 index 0000000000..4b63200cdd --- /dev/null +++ b/testing/web-platform/tests/storage/buckets/META.yml @@ -0,0 +1,5 @@ +spec: https://wicg.github.io/storage-buckets/ +suggested_reviewers: + - ayuishii + - evanstade + - inexorabletash diff --git a/testing/web-platform/tests/storage/buckets/bucket-quota-indexeddb.tentative.https.any.js b/testing/web-platform/tests/storage/buckets/bucket-quota-indexeddb.tentative.https.any.js new file mode 100644 index 0000000000..ee9202777e --- /dev/null +++ b/testing/web-platform/tests/storage/buckets/bucket-quota-indexeddb.tentative.https.any.js @@ -0,0 +1,41 @@ +// META: title=Bucket quota enforcement for indexeddb +// META: script=/storage/buckets/resources/util.js + +promise_test(async t => { + prepareForBucketTest(t); + const arraySize = 1e6; + const objectStoreName = "storageManager"; + const dbname = + this.window ? window.location.pathname : 'estimate-worker.https.html'; + + let quota = arraySize * 1.5; + const bucket = await navigator.storageBuckets.open('idb', {quota}); + + await indexedDbDeleteRequest(bucket.indexedDB, dbname); + + const db = + await indexedDbOpenRequest(t, bucket.indexedDB, dbname, (db_to_upgrade) => { + db_to_upgrade.createObjectStore(objectStoreName); + }); + + const txn = db.transaction(objectStoreName, 'readwrite'); + const buffer = new ArrayBuffer(arraySize); + const view = new Uint8Array(buffer); + + for (let i = 0; i < arraySize; i++) { + view[i] = Math.floor(Math.random() * 255); + } + + // Two puts in one transaction to ensure that both are counted towards quota. + txn.objectStore(objectStoreName).add(new Blob([buffer], { + type: 'binary/random' + }), 1); + txn.objectStore(objectStoreName).add(new Blob([buffer], { + type: 'binary/random' + }), 2); + + await promise_rejects_dom( + t, 'QuotaExceededError', transactionPromise(txn)); + + db.close(); +}, 'IDB respects bucket quota'); diff --git a/testing/web-platform/tests/storage/buckets/bucket-storage-policy.tentative.https.any.js b/testing/web-platform/tests/storage/buckets/bucket-storage-policy.tentative.https.any.js new file mode 100644 index 0000000000..d6dce3675d --- /dev/null +++ b/testing/web-platform/tests/storage/buckets/bucket-storage-policy.tentative.https.any.js @@ -0,0 +1,21 @@ +// META: title=Buckets API: Tests for bucket storage policies. +// META: script=/storage/buckets/resources/util.js +// META: global=window,worker + +'use strict'; + +promise_test(async testCase => { + await prepareForBucketTest(testCase); + + await promise_rejects_js( + testCase, TypeError, + navigator.storageBuckets.open('negative', {quota: -1})); + + await promise_rejects_js( + testCase, TypeError, navigator.storageBuckets.open('zero', {quota: 0})); + + await promise_rejects_js( + testCase, TypeError, + navigator.storageBuckets.open( + 'above_max', {quota: Number.MAX_SAFE_INTEGER + 1})); +}, 'The open promise should reject with a TypeError when quota is requested outside the range of 1 to Number.MAX_SAFE_INTEGER.'); diff --git a/testing/web-platform/tests/storage/buckets/bucket_names.tentative.https.any.js b/testing/web-platform/tests/storage/buckets/bucket_names.tentative.https.any.js new file mode 100644 index 0000000000..e0f122dc47 --- /dev/null +++ b/testing/web-platform/tests/storage/buckets/bucket_names.tentative.https.any.js @@ -0,0 +1,93 @@ +// META: title=Buckets API: Basic tests for bucket names. +// META: script=resources/util.js +// META: global=window,worker + +const kGoodBucketNameTests = [ + ['abcdefghijklmnopqrstuvwxyz0123456789-_', 'with allowed characters'], + ['2021-01-01', 'with `-` in the middle'], + ['2021_01_01', 'with `_` in the middle'], + ['2021_01_01_', 'ending with `_`'], + ['2021-01-01-', 'ending with `-`'], +]; + +const kBadBucketNameTests = [ + ['_bucket', 'start with `_`'], + ['-bucket', 'start with `-`'], + ['bucket name', 'have a space'], + ['bUcKet123', 'are not all lower case'], + ['bucket♦♥♠♣', 'are not in ASCII'], + ['2021/01/01', 'include an invalid special character'], + [' ', 'have no characters'], + ['', 'are an empty string'], + ['mjnkhtwsiyjsrxvrzzqafldfvomqopdjfiuxqelfkllcugrhvvblkvmiqlguhhqepoggyu', + 'exceed 64 chars'] +]; + +// Test valid bucket names on open(). +kGoodBucketNameTests.forEach(test_data => { + const bucket_name = test_data[0]; + const test_description = test_data[1]; + + promise_test(async testCase => { + await prepareForBucketTest(testCase); + const bucket = await navigator.storageBuckets.open(bucket_name); + assert_equals(bucket.name, bucket_name); + + const buckets = await navigator.storageBuckets.keys(); + assert_array_equals(buckets, [bucket_name]); + }, `open() allows bucket names ${test_description}`); +}); + +// Test invalid bucket names on open(). +kBadBucketNameTests.forEach(test_data => { + const bucket_name = test_data[0]; + const test_description = test_data[1]; + + promise_test(async testCase => { + await prepareForBucketTest(testCase); + return promise_rejects_js( + testCase, TypeError, + navigator.storageBuckets.open(bucket_name)); + }, `open() throws an error if bucket names ${test_description}`); +}); + +// Test valid bucket names on delete(). +kGoodBucketNameTests.forEach(test_data => { + const bucket_name = test_data[0]; + const test_description = test_data[1]; + + promise_test(async testCase => { + await prepareForBucketTest(testCase); + await navigator.storageBuckets.open(bucket_name); + let buckets = await navigator.storageBuckets.keys(); + assert_equals(buckets.length, 1); + + await navigator.storageBuckets.delete(bucket_name); + + buckets = await navigator.storageBuckets.keys(); + assert_equals(buckets.length, 0); + }, `delete() allows bucket names ${test_description}`); +}); + +// Test invalid bucket names on delete(). +kBadBucketNameTests.forEach(test_data => { + const bucket_name = test_data[0]; + const test_description = test_data[1]; + + promise_test(async testCase => { + await prepareForBucketTest(testCase); + return promise_rejects_js( + testCase, TypeError, + navigator.storageBuckets.delete(bucket_name)); + }, `delete() throws an error if bucket names ${test_description}`); +}); + +promise_test(async testCase => { + await prepareForBucketTest(testCase); + + await navigator.storageBuckets.open('bucket_name'); + await navigator.storageBuckets.open('bucket_name'); + + const buckets = await navigator.storageBuckets.keys(); + assert_array_equals(buckets, ['bucket_name']); +}, 'open() does not store duplicate bucket names'); diff --git a/testing/web-platform/tests/storage/buckets/buckets_basic.tentative.https.any.js b/testing/web-platform/tests/storage/buckets/buckets_basic.tentative.https.any.js new file mode 100644 index 0000000000..20ff227bac --- /dev/null +++ b/testing/web-platform/tests/storage/buckets/buckets_basic.tentative.https.any.js @@ -0,0 +1,50 @@ +// META: title=Buckets API: Basic tests for open(), keys(), delete(). +// META: script=resources/util.js +// META: global=window,worker + +'use strict'; + +// This test is for initial IDL version optimized for debugging. +// Split and add extensive testing once implementation for the endpoints are +// added and method definitions are more defined. +promise_test(async testCase => { + await prepareForBucketTest(testCase); + + await navigator.storageBuckets.open('bucket_name3'); + await navigator.storageBuckets.open('bucket_name1'); + await navigator.storageBuckets.open('bucket_name2'); + + const buckets = await navigator.storageBuckets.keys(); + assert_array_equals( + buckets, ['bucket_name1', 'bucket_name2', 'bucket_name3']); +}, 'keys() lists all stored bucket names alphabetically'); + +promise_test(async testCase => { + await prepareForBucketTest(testCase); + + await navigator.storageBuckets.open('bucket_name1'); + await navigator.storageBuckets.open('bucket_name2'); + + let buckets = await navigator.storageBuckets.keys(); + assert_array_equals(buckets, ['bucket_name1', 'bucket_name2']); + + await navigator.storageBuckets.delete('bucket_name1'); + + buckets = await navigator.storageBuckets.keys(); + assert_array_equals(buckets, ['bucket_name2']); +}, 'delete() removes stored bucket name'); + +promise_test(async testCase => { + await prepareForBucketTest(testCase); + + await navigator.storageBuckets.open('bucket_name'); + + let buckets = await navigator.storageBuckets.keys(); + assert_array_equals(buckets, ['bucket_name']); + + await navigator.storageBuckets.delete('does-not-exist'); + + buckets = await navigator.storageBuckets.keys(); + assert_equals(buckets.length, 1); + assert_equals(buckets[0], 'bucket_name'); +}, 'delete() does nothing if bucket name does not exist'); diff --git a/testing/web-platform/tests/storage/buckets/buckets_storage_policy.tentative.https.any.js b/testing/web-platform/tests/storage/buckets/buckets_storage_policy.tentative.https.any.js new file mode 100644 index 0000000000..918364d731 --- /dev/null +++ b/testing/web-platform/tests/storage/buckets/buckets_storage_policy.tentative.https.any.js @@ -0,0 +1,32 @@ +// META: title=Buckets API: Tests for bucket storage policies. +// META: script=resources/util.js +// META: global=window,worker + +'use strict'; + +function sanitizeQuota(quota) { + return Math.max(1, Math.min(Number.MAX_SAFE_INTEGER, Math.floor(quota))); +} + +async function testQuota(storageKeyQuota, quota, name) { + const safeQuota = sanitizeQuota(quota); + const bucket = await navigator.storageBuckets.open(name, { quota: safeQuota }); + const estimateQuota = (await bucket.estimate()).quota; + assert_equals(estimateQuota, Math.min(safeQuota, storageKeyQuota)); +} + +promise_test(async testCase => { + await prepareForBucketTest(testCase); + + const storageKeyQuota = (await navigator.storage.estimate()).quota; + + testQuota(storageKeyQuota, 1, 'one'); + testQuota(storageKeyQuota, storageKeyQuota / 4, 'quarter'); + testQuota(storageKeyQuota, storageKeyQuota / 2, 'half'); + testQuota(storageKeyQuota, storageKeyQuota - 1, 'one_less'); + testQuota(storageKeyQuota, storageKeyQuota, 'origin_quota'); + testQuota(storageKeyQuota, storageKeyQuota + 1, 'one_more'); + testQuota(storageKeyQuota, storageKeyQuota * 2, 'twice'); + testQuota(storageKeyQuota, storageKeyQuota * 4, 'four_times'); + testQuota(storageKeyQuota, Number.MAX_SAFE_INTEGER, 'max_safe_int'); +}, 'For an individual bucket, the quota is the minimum of the requested quota and the StorageKey quota.'); diff --git a/testing/web-platform/tests/storage/buckets/detached-iframe.https.html b/testing/web-platform/tests/storage/buckets/detached-iframe.https.html new file mode 100644 index 0000000000..a67c89efa3 --- /dev/null +++ b/testing/web-platform/tests/storage/buckets/detached-iframe.https.html @@ -0,0 +1,62 @@ +<!doctype html> +<meta charset=utf-8> +<title>Storage Buckets API on detached iframe</title> +<link rel='help' href=''> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + +<body> +<script> +'use strict'; + +promise_test(async testCase => { + const iframe = document.createElement('iframe'); + document.body.appendChild(iframe); + const bucketManager = iframe.contentWindow.navigator.storageBuckets; + await bucketManager.open('iframe-bucket'); + + let bucketKeys = await bucketManager.keys(); + assert_equals(bucketKeys.length, 1); + + // Note that these tests cannot make use of `prepareForBucketTest` because the + // iframe is detached before the test ends, so the test's cleanup step comes + // too late to delete buckets. + await bucketManager.delete('iframe-bucket'); + + iframe.remove(); + + // Calling open() from a detached iframe should fail but not crash. + assert_equals(bucketManager.open('iframe-bucket'), undefined); +}, 'Verify open() on detached iframe returns an error'); + +promise_test(async testCase => { + const iframe = document.createElement('iframe'); + document.body.appendChild(iframe); + const bucketManager = iframe.contentWindow.navigator.storageBuckets; + await bucketManager.open('iframe-bucket'); + + let bucketKeys = await bucketManager.keys(); + assert_equals(bucketKeys.length, 1); + await bucketManager.delete('iframe-bucket'); + + iframe.remove(); + + // Calling keys() from a detached iframe should fail but not crash. + assert_equals(bucketManager.keys(), undefined); +}, 'Verify keys() on detached iframe returns an error'); + +promise_test(async testCase => { + const iframe = document.createElement('iframe'); + document.body.appendChild(iframe); + const bucketManager = iframe.contentWindow.navigator.storageBuckets; + await bucketManager.open('iframe-bucket'); + await bucketManager.delete('iframe-bucket'); + + iframe.remove(); + + // Calling delete() from a detached iframe should fail but not crash. + assert_equals(bucketManager.delete('foo-bucket'), undefined); +}, 'Verify delete() on detached iframe returns an error'); + +</script> +</body> diff --git a/testing/web-platform/tests/storage/buckets/idlharness-worker.https.any.js b/testing/web-platform/tests/storage/buckets/idlharness-worker.https.any.js new file mode 100644 index 0000000000..9a1a3f80b9 --- /dev/null +++ b/testing/web-platform/tests/storage/buckets/idlharness-worker.https.any.js @@ -0,0 +1,22 @@ +// META: global=window,worker +// META: script=/resources/WebIDLParser.js +// META: script=/resources/idlharness.js + +'use strict'; + +idl_test( + ['storage-buckets'], + ['html'], + async (idl_array, t) => { + idl_array.add_objects({ + StorageBucketManager: ['navigator.storageBuckets'], + StorageBucket: [] + }); + + if (self.Window) { + idl_array.add_objects({ Navigator: ['navigator'] }); + } else { + idl_array.add_objects({ WorkerNavigator: ['navigator'] }); + } + } +); diff --git a/testing/web-platform/tests/storage/buckets/opaque-origin.https.window.js b/testing/web-platform/tests/storage/buckets/opaque-origin.https.window.js new file mode 100644 index 0000000000..c91d3faa67 --- /dev/null +++ b/testing/web-platform/tests/storage/buckets/opaque-origin.https.window.js @@ -0,0 +1,58 @@ +// META: title=Storage Buckets API: Interface is not exposed in opaque origins. +// META: script=resources/util.js +// META: global=window + +const kSandboxWindowUrl = 'resources/opaque-origin-sandbox.html'; + +function add_iframe(test, src, sandbox) { + const iframe = document.createElement('iframe'); + iframe.src = src; + if (sandbox !== undefined) { + iframe.sandbox = sandbox; + } + document.body.appendChild(iframe); + test.add_cleanup(() => { + iframe.remove(); + }); +} + +// |kSandboxWindowUrl| sends the result of methods on StorageBucketManager. +// For windows using sandbox="allow-scripts", it must produce a rejected +// promise. +async function verify_results_from_sandboxed_child_window(test) { + const event_watcher = new EventWatcher(test, self, 'message'); + + const first_message_event = await event_watcher.wait_for('message'); + assert_equals( + first_message_event.data, + 'navigator.storageBuckets.open(): REJECTED: SecurityError'); + + const second_message_event = await event_watcher.wait_for('message'); + assert_equals( + second_message_event.data, + 'navigator.storageBuckets.keys(): REJECTED: SecurityError'); + + const third_message_event = await event_watcher.wait_for('message'); + assert_equals( + third_message_event.data, + 'navigator.storageBuckets.delete(): REJECTED: SecurityError'); +} + +promise_test(async testCase => { + prepareForBucketTest(testCase); + add_iframe(testCase, kSandboxWindowUrl, /*sandbox=*/ 'allow-scripts'); + await verify_results_from_sandboxed_child_window(testCase); +}, 'StorageBucketManager methods must reject in a sandboxed iframe.'); + +promise_test(async testCase => { + prepareForBucketTest(testCase); + const child_window_url = kSandboxWindowUrl + + '?pipe=header(Content-Security-Policy, sandbox allow-scripts)'; + + const child_window = window.open(child_window_url); + testCase.add_cleanup(() => { + child_window.close(); + }); + + await verify_results_from_sandboxed_child_window(testCase); +}, 'StorageBucketManager methods must reject in a sandboxed opened window.'); diff --git a/testing/web-platform/tests/storage/buckets/resources/cached-resource.txt b/testing/web-platform/tests/storage/buckets/resources/cached-resource.txt new file mode 100644 index 0000000000..c57eff55eb --- /dev/null +++ b/testing/web-platform/tests/storage/buckets/resources/cached-resource.txt @@ -0,0 +1 @@ +Hello World!
\ No newline at end of file diff --git a/testing/web-platform/tests/storage/buckets/resources/opaque-origin-sandbox.html b/testing/web-platform/tests/storage/buckets/resources/opaque-origin-sandbox.html new file mode 100644 index 0000000000..4a1ac39fdf --- /dev/null +++ b/testing/web-platform/tests/storage/buckets/resources/opaque-origin-sandbox.html @@ -0,0 +1,52 @@ +<!DOCTYPE html> +<script> + 'use strict' + + // Sends the result of navigator.storageBuckets.open('bucket'). + + function post_message(data) { + if (window.parent !== null) { + window.parent.postMessage(data, { targetOrigin: '*' }); + } + if (window.opener !== null) { + window.opener.postMessage(data, { targetOrigin: '*' }); + } + } + + try { + navigator.storageBuckets.open('opaque-origin-bucket') + .then(() => { + post_message('navigator.storageBuckets.open(): FULFILLED'); + }).catch(error => { + post_message( + `navigator.storageBuckets.open(): REJECTED: ${error.name}`); + }); + } catch (error) { + post_message(`navigator.storageBuckets.open(): EXCEPTION: ${error.name}`); + } + + try { + navigator.storageBuckets.keys() + .then(() => { + post_message('navigator.storageBuckets.keys(): FULFILLED'); + }).catch(error => { + post_message( + `navigator.storageBuckets.keys(): REJECTED: ${error.name}`); + }); + } catch (error) { + post_message(`navigator.storageBuckets.keys(): EXCEPTION: ${error.name}`); + } + + try { + navigator.storageBuckets.delete('opaque-origin-bucket') + .then(() => { + post_message('navigator.storageBuckets.delete(): FULFILLED'); + }).catch(error => { + post_message( + `navigator.storageBuckets.delete(): REJECTED: ${error.name}`); + }); + } catch (error) { + post_message(`navigator.storageBuckets.delete(): EXCEPTION: ${error.name}`); + } +</script> + diff --git a/testing/web-platform/tests/storage/buckets/resources/util.js b/testing/web-platform/tests/storage/buckets/resources/util.js new file mode 100644 index 0000000000..5fff489444 --- /dev/null +++ b/testing/web-platform/tests/storage/buckets/resources/util.js @@ -0,0 +1,57 @@ +'use strict'; + +// Makes sure initial bucket state is as expected and to clean up after the test +// is over (whether it passes or fails). +async function prepareForBucketTest(test) { + // Verify initial state. + assert_equals((await navigator.storageBuckets.keys()).join(), ''); + // Clean up after test. + test.add_cleanup(async function() { + const keys = await navigator.storageBuckets.keys(); + for (const key of keys) { + await navigator.storageBuckets.delete(key); + } + }); +} + +function indexedDbOpenRequest(t, idb, dbname, upgrade_func) { + return new Promise((resolve, reject) => { + const openRequest = idb.open(dbname); + t.add_cleanup(() => { + indexedDbDeleteRequest(idb, dbname); + }); + + openRequest.onerror = () => { + reject(openRequest.error); + }; + openRequest.onsuccess = () => { + resolve(openRequest.result); + }; + openRequest.onupgradeneeded = event => { + upgrade_func(openRequest.result); + }; + }); +} + +function indexedDbDeleteRequest(idb, name) { + return new Promise((resolve, reject) => { + const deleteRequest = idb.deleteDatabase(name); + deleteRequest.onerror = () => { + reject(deleteRequest.error); + }; + deleteRequest.onsuccess = () => { + resolve(); + }; + }); +} + +function transactionPromise(txn) { + return new Promise((resolve, reject) => { + txn.onabort = () => { + reject(txn.error); + }; + txn.oncomplete = () => { + resolve(); + }; + }); +} diff --git a/testing/web-platform/tests/storage/buckets/storage_bucket_object.tentative.https.any.js b/testing/web-platform/tests/storage/buckets/storage_bucket_object.tentative.https.any.js new file mode 100644 index 0000000000..52f1693ccb --- /dev/null +++ b/testing/web-platform/tests/storage/buckets/storage_bucket_object.tentative.https.any.js @@ -0,0 +1,143 @@ +// META: title=Buckets API: Tests for the StorageBucket object. +// META: global=window,worker + +'use strict'; + +promise_test(async testCase => { + const bucket = await navigator.storageBuckets.open('bucket_name'); + testCase.add_cleanup(async () => { + await navigator.storageBuckets.delete('bucket_name'); + }); + const persisted = await bucket.persisted(); + assert_false(persisted); + + // Also verify that the promise is rejected after the bucket is deleted. + await navigator.storageBuckets.delete('bucket_name'); + await promise_rejects_dom(testCase, 'UnknownError', bucket.persisted()); +}, 'persisted() should default to false'); + +promise_test(async testCase => { + const bucket = await navigator.storageBuckets.open('bucket_name'); + testCase.add_cleanup(async () => { + await navigator.storageBuckets.delete('bucket_name'); + }); + const estimate = await bucket.estimate(); + assert_greater_than(estimate.quota, 0); + assert_equals(estimate.usage, 0); + + const cacheName = 'attachments'; + const cacheKey = 'receipt1.txt'; + var inboxCache = await bucket.caches.open(cacheName); + await inboxCache.put(cacheKey, new Response('bread x 2')) + + const estimate2 = await bucket.estimate(); + assert_equals(estimate.quota, estimate2.quota); + assert_less_than(estimate.usage, estimate2.usage); +}, 'estimate() should retrieve quota usage'); + +promise_test(async testCase => { + const bucket = await navigator.storageBuckets.open( + 'bucket_name', { durability: 'strict' }); + testCase.add_cleanup(async () => { + await navigator.storageBuckets.delete('bucket_name'); + }); + + const durability = await bucket.durability(); + assert_equals('strict', durability); + + await navigator.storageBuckets.delete('bucket_name'); + await promise_rejects_dom(testCase, 'UnknownError', bucket.durability()); +}, 'durability() should retrieve bucket durability specified during creation'); + +promise_test(async testCase => { + const bucket = await navigator.storageBuckets.open('bucket_name'); + testCase.add_cleanup(async () => { + await navigator.storageBuckets.delete('bucket_name'); + }); + + const durability = await bucket.durability(); + assert_equals('relaxed', durability); +}, 'Bucket durability defaults to relaxed'); + +promise_test(async testCase => { + const oneYear = 365 * 24 * 60 * 60 * 1000; + const expiresDate = Date.now() + oneYear; + const bucket = await navigator.storageBuckets.open( + 'bucket_name', { expires: expiresDate }); + testCase.add_cleanup(async () => { + await navigator.storageBuckets.delete('bucket_name'); + }); + + const expires = await bucket.expires(); + assert_equals(expires, expiresDate); +}, 'expires() should retrieve expires date'); + +promise_test(async testCase => { + const bucket = await navigator.storageBuckets.open('bucket_name'); + testCase.add_cleanup(async () => { + await navigator.storageBuckets.delete('bucket_name'); + }); + + const expires = await bucket.expires(); + assert_equals(expires, null); + + await navigator.storageBuckets.delete('bucket_name'); + await promise_rejects_dom(testCase, 'UnknownError', bucket.expires()); +}, 'expires() should be defaulted to null'); + +promise_test(async testCase => { + const bucket = await navigator.storageBuckets.open('bucket_name'); + testCase.add_cleanup(async () => { + await navigator.storageBuckets.delete('bucket_name'); + }); + + const oneYear = 365 * 24 * 60 * 60 * 1000; + const expiresDate = Date.now() + oneYear; + await bucket.setExpires(expiresDate); + + const expires = await bucket.expires(); + assert_equals(expires, expiresDate); + + await navigator.storageBuckets.delete('bucket_name'); + await promise_rejects_dom(testCase, 'UnknownError', bucket.setExpires(expiresDate)); +}, 'setExpires() should set bucket expires date'); + +promise_test(async testCase => { + const oneDay = 24 * 60 * 60 * 1000; + const expiresDate = Date.now() + oneDay; + const bucket = await navigator.storageBuckets.open('bucket_name', { + expires: expiresDate + }); + testCase.add_cleanup(async () => { + await navigator.storageBuckets.delete('bucket_name'); + }); + let expires = await bucket.expires(); + assert_equals(expires, expiresDate); + + const oneYear = 365 * oneDay; + const newExpiresDate = Date.now() + oneYear; + await bucket.setExpires(newExpiresDate); + + expires = await bucket.expires(); + assert_equals(expires, newExpiresDate); +}, 'setExpires() should update expires date'); + +promise_test(async testCase => { + const bucket = await navigator.storageBuckets.open( + 'bucket_name', { durability: 'strict' }); + testCase.add_cleanup(async () => { + await navigator.storageBuckets.delete('bucket_name'); + }); + + const same_bucket = await navigator.storageBuckets.open('bucket_name'); + const durability = await bucket.durability(); + const other_durability = await same_bucket.durability(); + assert_equals(durability, other_durability); + + // Delete the bucket and remake it. + await navigator.storageBuckets.delete('bucket_name'); + const remade_bucket = await navigator.storageBuckets.open('bucket_name'); + await promise_rejects_dom(testCase, 'UnknownError', bucket.durability()); + const remade_durability = await remade_bucket.durability(); + assert_not_equals(remade_durability, durability); +}, 'two handles can refer to the same bucket, and a bucket name can be reused after deletion'); diff --git a/testing/web-platform/tests/storage/estimate-indexeddb.https.any.js b/testing/web-platform/tests/storage/estimate-indexeddb.https.any.js new file mode 100644 index 0000000000..6577b021ad --- /dev/null +++ b/testing/web-platform/tests/storage/estimate-indexeddb.https.any.js @@ -0,0 +1,48 @@ +// META: title=StorageManager: estimate() for indexeddb +// META: script=/storage/buckets/resources/util.js + +// Technically, this verifies unspecced behavior. See +// https://github.com/whatwg/storage/issues/110 for defining this behavior. +promise_test(async t => { + const arraySize = 1e6; + const objectStoreName = "storageManager"; + const dbname = + this.window ? window.location.pathname : 'estimate-worker.https.html'; + + await indexedDbDeleteRequest(indexedDB, dbname); + let estimate = await navigator.storage.estimate(); + + const usageBeforeCreate = estimate.usage; + const db = + await indexedDbOpenRequest(t, indexedDB, dbname, (db_to_upgrade) => { + db_to_upgrade.createObjectStore(objectStoreName); + }); + + estimate = await navigator.storage.estimate(); + const usageAfterCreate = estimate.usage; + + assert_greater_than( + usageAfterCreate, usageBeforeCreate, + 'estimated usage should increase after object store is created'); + + const txn = db.transaction(objectStoreName, 'readwrite'); + const buffer = new ArrayBuffer(arraySize); + const view = new Uint8Array(buffer); + + for (let i = 0; i < arraySize; i++) { + view[i] = Math.floor(Math.random() * 255); + } + + const testBlob = new Blob([buffer], {type: 'binary/random'}); + txn.objectStore(objectStoreName).add(testBlob, 1); + + await transactionPromise(txn); + + estimate = await navigator.storage.estimate(); + const usageAfterPut = estimate.usage; + assert_greater_than( + usageAfterPut, usageAfterCreate, + 'estimated usage should increase after large value is stored'); + + db.close(); +}, 'estimate() shows usage increase after large value is stored'); diff --git a/testing/web-platform/tests/storage/estimate-parallel.https.any.js b/testing/web-platform/tests/storage/estimate-parallel.https.any.js new file mode 100644 index 0000000000..090f004b85 --- /dev/null +++ b/testing/web-platform/tests/storage/estimate-parallel.https.any.js @@ -0,0 +1,13 @@ +// META: title=StorageManager: multiple estimate() calls in parallel + +promise_test(async t => { + let r1, r2; + await Promise.all([ + navigator.storage.estimate().then(r => { r1 = r; }), + navigator.storage.estimate().then(r => { r2 = r; }) + ]); + assert_true(('usage' in r1) && ('quota' in r1), + 'first response should have expected fields'); + assert_true(('usage' in r2) && ('quota' in r2), + 'second response should have expected fields'); +}, 'Multiple estimate() calls in parallel should complete'); diff --git a/testing/web-platform/tests/storage/estimate-usage-details-caches.https.tentative.any.js b/testing/web-platform/tests/storage/estimate-usage-details-caches.https.tentative.any.js new file mode 100644 index 0000000000..bf889f8418 --- /dev/null +++ b/testing/web-platform/tests/storage/estimate-usage-details-caches.https.tentative.any.js @@ -0,0 +1,20 @@ +// META: title=StorageManager: estimate() for caches + +promise_test(async t => { + let estimate = await navigator.storage.estimate(); + + const cachesUsageBeforeCreate = estimate.usageDetails.caches || 0; + + const cacheName = 'testCache'; + const cache = await caches.open(cacheName); + t.add_cleanup(() => caches.delete(cacheName)); + + await cache.put('/test.json', new Response('x'.repeat(1024*1024))); + + estimate = await navigator.storage.estimate(); + assert_true('caches' in estimate.usageDetails); + const cachesUsageAfterPut = estimate.usageDetails.caches; + assert_greater_than( + cachesUsageAfterPut, cachesUsageBeforeCreate, + 'estimated usage should increase after value is stored'); +}, 'estimate() shows usage increase after large value is stored'); diff --git a/testing/web-platform/tests/storage/estimate-usage-details-indexeddb.https.tentative.any.js b/testing/web-platform/tests/storage/estimate-usage-details-indexeddb.https.tentative.any.js new file mode 100644 index 0000000000..551cede9c6 --- /dev/null +++ b/testing/web-platform/tests/storage/estimate-usage-details-indexeddb.https.tentative.any.js @@ -0,0 +1,59 @@ +// META: title=StorageManager: estimate() usage details for indexeddb +// META: script=helpers.js +// META: script=../IndexedDB/resources/support-promises.js + +promise_test(async t => { + const estimate = await navigator.storage.estimate() + assert_equals(typeof estimate.usageDetails, 'object'); +}, 'estimate() resolves to dictionary with usageDetails member'); + +promise_test(async t => { + // We use 100KB here because db compaction usually happens every few MB + // 100KB is large enough to avoid a false positive (small amounts of metadata + // getting written for some random reason), and small enough to avoid + // compaction with a reasonably high probability. + const writeSize = 1024 * 100; + const objectStoreName = 'store'; + const dbname = self.location.pathname; + + await indexedDB.deleteDatabase(dbname); + let usageAfterWrite, usageBeforeWrite; + // TODO(crbug.com/906867): Refactor this test to better deal with db/log + // compaction flakiness + // The for loop here is to help make this test less flaky. The reason it is + // flaky is that database and/or log compaction could happen in the middle of + // this loop. The problem is that this test runs in a large batch of tests, + // and previous tests might have created a lot of garbage which could trigger + // compaction. Suppose the initial estimate shows 1MB usage before creating + // the db. Compaction could happen after this step and before we measure + // usage at the end, meaning the 1MB could be wiped to 0, an extra 1024 * 100 + // is put in, and the actual increase in usage does not reach our expected + // increase. Loop 10 times here to be safe (and reduce the number of bot + // builds that fail); all it takes is one iteration without compaction for + // this to pass. + for (let i = 0; i < 10; i++) { + const db = await createDB(dbname, objectStoreName, t); + let estimate = await navigator.storage.estimate(); + + // If usage is 0, usageDetails does not include the usage (undefined) + usageBeforeWrite = estimate.usageDetails.indexedDB || 0; + + const txn = db.transaction(objectStoreName, 'readwrite'); + const valueToStore = largeValue(writeSize, Math.random() * 255); + txn.objectStore(objectStoreName).add(valueToStore, 1); + + await transactionPromise(txn); + + estimate = await navigator.storage.estimate(); + usageAfterWrite = estimate.usageDetails.indexedDB; + db.close(); + + if (usageAfterWrite - usageBeforeWrite >= writeSize) { + break; + } + } + + assert_greater_than_equal(usageAfterWrite - usageBeforeWrite, + writeSize); +}, 'estimate() usage details reflects increase in indexedDB after large ' + + 'value is stored'); diff --git a/testing/web-platform/tests/storage/estimate-usage-details-service-workers.https.tentative.window.js b/testing/web-platform/tests/storage/estimate-usage-details-service-workers.https.tentative.window.js new file mode 100644 index 0000000000..cf3a2aa943 --- /dev/null +++ b/testing/web-platform/tests/storage/estimate-usage-details-service-workers.https.tentative.window.js @@ -0,0 +1,38 @@ +// META: title=StorageManager: estimate() for service worker registrations +const wait_for_active = worker => new Promise(resolve =>{ + if (worker.active) { resolve(worker.active); } + + const listen_for_active = worker => e => { + if (e.target.state === 'activated') { resolve(worker.active); } + } + + if (worker.waiting) { + worker.waiting + .addEventListener('statechange', listen_for_active(worker.waiting)); + } + if (worker.installing) { + worker.installing + .addEventListener('statechange', listen_for_active(worker.installing)); + } +}); + +promise_test(async t => { + let estimate = await navigator.storage.estimate(); + const usageBeforeCreate = estimate.usageDetails.serviceWorkerRegistrations || + 0; + // Note: helpers.js is an arbitrary file; it could be any file that + // exists, but this test does not depend on the contents of said file. + const serviceWorkerRegistration = await + navigator.serviceWorker.register('./helpers.js'); + + t.add_cleanup(() => serviceWorkerRegistration.unregister()); + await wait_for_active(serviceWorkerRegistration); + + estimate = await navigator.storage.estimate(); + assert_true('serviceWorkerRegistrations' in estimate.usageDetails); + + const usageAfterCreate = estimate.usageDetails.serviceWorkerRegistrations; + assert_greater_than( + usageAfterCreate, usageBeforeCreate, + 'estimated usage should increase after service worker is registered'); +}, 'estimate() shows usage increase after large value is stored'); diff --git a/testing/web-platform/tests/storage/estimate-usage-details.https.tentative.any.js b/testing/web-platform/tests/storage/estimate-usage-details.https.tentative.any.js new file mode 100644 index 0000000000..2a1cea5fb8 --- /dev/null +++ b/testing/web-platform/tests/storage/estimate-usage-details.https.tentative.any.js @@ -0,0 +1,12 @@ +// META: title=StorageManager: estimate() should have usage details + +promise_test(async t => { + const estimate = await navigator.storage.estimate(); + assert_equals(typeof estimate, 'object'); + assert_true('usage' in estimate); + assert_equals(typeof estimate.usage, 'number'); + assert_true('quota' in estimate); + assert_equals(typeof estimate.quota, 'number'); + assert_true('usageDetails' in estimate); + assert_equals(typeof estimate.usageDetails, 'object'); +}, 'estimate() resolves to dictionary with members, including usageDetails'); diff --git a/testing/web-platform/tests/storage/helpers.js b/testing/web-platform/tests/storage/helpers.js new file mode 100644 index 0000000000..b524c1b82c --- /dev/null +++ b/testing/web-platform/tests/storage/helpers.js @@ -0,0 +1,46 @@ +/** + * @description - Function will create a database with the supplied name + * and also create an object store with the specified name. + * If a db with the name dbName exists, this will raze the + * existing DB beforehand. + * @param {string} dbName + * @param {string} objectStoreName + * @param {testCase} t + * @returns {Promise} - A promise that resolves to an indexedDB open request + */ +function createDB(dbName, objectStoreName, t) { + return new Promise((resolve, reject) => { + const openRequest = indexedDB.open(dbName); + t.add_cleanup(() => { + indexedDB.deleteDatabase(dbName); + }); + openRequest.onerror = () => { + reject(openRequest.error); + }; + openRequest.onsuccess = () => { + resolve(openRequest.result); + }; + openRequest.onupgradeneeded = (event) => { + openRequest.result.createObjectStore(objectStoreName); + }; + }); +} + +/** + * @description - This function will wrap an IDBTransaction in a promise, + * resolving in the oncomplete() method and rejecting with the + * transaction error in the onabort() case. + * @param {IDBTransaction} transaction - The transaction to wrap in a promise. + * @returns {Promise} - A promise that resolves when the transaction is either + * aborted or completed. + */ +function transactionPromise(transaction) { + return new Promise((resolve, reject) => { + transaction.onabort = () => { + reject(transaction.error); + }; + transaction.oncomplete = () => { + resolve(); + }; + }); +} diff --git a/testing/web-platform/tests/storage/idlharness.https.any.js b/testing/web-platform/tests/storage/idlharness.https.any.js new file mode 100644 index 0000000000..773fac4e4a --- /dev/null +++ b/testing/web-platform/tests/storage/idlharness.https.any.js @@ -0,0 +1,18 @@ +// META: script=/resources/WebIDLParser.js +// META: script=/resources/idlharness.js +// META: timeout=long + +'use strict'; + +idl_test( + ['storage'], + ['html'], + idl_array => { + idl_array.add_objects({ StorageManager: ['navigator.storage'] }); + if (self.Window) { + idl_array.add_objects({ Navigator: ['navigator'] }); + } else { + idl_array.add_objects({ WorkerNavigator: ['navigator'] }); + } + } +); diff --git a/testing/web-platform/tests/storage/opaque-origin.https.window.js b/testing/web-platform/tests/storage/opaque-origin.https.window.js new file mode 100644 index 0000000000..cc1d31fdf2 --- /dev/null +++ b/testing/web-platform/tests/storage/opaque-origin.https.window.js @@ -0,0 +1,80 @@ +// META: title=StorageManager API and opaque origins + +function load_iframe(src, sandbox) { + return new Promise(resolve => { + const iframe = document.createElement('iframe'); + iframe.onload = () => { resolve(iframe); }; + if (sandbox) + iframe.sandbox = sandbox; + iframe.srcdoc = src; + iframe.style.display = 'none'; + document.documentElement.appendChild(iframe); + }); +} + +function wait_for_message(iframe) { + return new Promise(resolve => { + self.addEventListener('message', function listener(e) { + if (e.source === iframe.contentWindow && "result" in e.data) { + resolve(e.data); + self.removeEventListener('message', listener); + } + }); + }); +} + +function make_script(snippet) { + return '<script src="/resources/testharness.js"></script>' + + '<script>' + + ' window.onmessage = () => {' + + ' try {' + + ' (' + snippet + ')' + + ' .then(' + + ' result => {' + + ' window.parent.postMessage({result: "no rejection"}, "*");' + + ' }, ' + + ' error => {' + + ' try {' + + ' assert_throws_js(TypeError, () => { throw error; });' + + ' window.parent.postMessage({result: "correct rejection"}, "*");' + + ' } catch (e) {' + + ' window.parent.postMessage({result: "incorrect rejection"}, "*");' + + ' }' + + ' });' + + ' } catch (ex) {' + + // Report if not implemented/exposed, rather than time out. + ' window.parent.postMessage({result: "API access threw"}, "*");' + + ' }' + + ' };' + + '<\/script>'; +} + +['navigator.storage.persisted()', + 'navigator.storage.estimate()', + // persist() can prompt, so make sure we test that last + 'navigator.storage.persist()', +].forEach(snippet => { + promise_test(t => { + return load_iframe(make_script(snippet)) + .then(iframe => { + iframe.contentWindow.postMessage({}, '*'); + return wait_for_message(iframe); + }) + .then(message => { + assert_equals(message.result, 'no rejection', + `${snippet} should not reject`); + }); + }, `${snippet} in non-sandboxed iframe should not reject`); + + promise_test(t => { + return load_iframe(make_script(snippet), 'allow-scripts') + .then(iframe => { + iframe.contentWindow.postMessage({}, '*'); + return wait_for_message(iframe); + }) + .then(message => { + assert_equals(message.result, 'correct rejection', + `${snippet} should reject with TypeError`); + }); + }, `${snippet} in sandboxed iframe should reject with TypeError`); +}); diff --git a/testing/web-platform/tests/storage/partitioned-estimate-usage-details-caches.tentative.https.sub.html b/testing/web-platform/tests/storage/partitioned-estimate-usage-details-caches.tentative.https.sub.html new file mode 100644 index 0000000000..dc2af7c213 --- /dev/null +++ b/testing/web-platform/tests/storage/partitioned-estimate-usage-details-caches.tentative.https.sub.html @@ -0,0 +1,74 @@ +<!DOCTYPE html> +<meta name=help href="https://privacycg.github.io/storage-partitioning/"> +<title>Partitioned estimate() usage details for caches test</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/utils.js"></script> + +<body> + <script> + const usageDetails = async () => + (await navigator.storage.estimate()).usageDetails.caches || 0; + + const createSomeUsage = async () => { + const cache_name = token(); + const cache_url = `/foo-${cache_name}`; + const cache = await caches.open(cache_name); + await cache.put(cache_url, new Response('x'.repeat(128))); + return [cache, cache_url]; + } + + const testPath = () => location.pathname.split("/").slice(0, -1).join("/"); + + let alt_origin = "https://{{hosts[alt][]}}:{{ports[https][0]}}"; + let details = {}; + + const iframe = document.createElement("iframe"); + iframe.src = `https://{{host}}:{{ports[https][0]}}${testPath()}` + + `/resources/partitioned-estimate-usage-details-caches-helper-frame.html` + document.body.appendChild(iframe); + + + async_test(test => { + if (location.origin === alt_origin) + return; + + + let cache, cache_url; + window.addEventListener("message", test.step_func(async event => { + if (event.data === "iframe-is-ready") { + details.init = await usageDetails(); + [cache, cache_url] = await createSomeUsage(test); + details.after = await usageDetails(); + assert_greater_than(details.after, details.init); + + iframe.contentWindow.postMessage("get-details", iframe.origin); + } + })); + + window.addEventListener("message", test.step_func(event => { + if (event.data.source === "same-site") { + details.same_site = event.data; + + const cross_site_window = window + .open(`${alt_origin}${location.pathname}`, "", "noopener=false"); + + test.add_cleanup(() => cross_site_window.close()); + } + if (event.data.source === "cross-site") { + details.cross_site = event.data; + + // Some cleanup + test.step(async () => await cache.delete(cache_url)); + + test.step(() => { + assert_true(details.cross_site.init == 0, "Usage should be 0."); + assert_equals(details.same_site.init, details.after); + }); + + test.done(); + } + })); + }, "Partitioned estimate() usage details for caches test."); + </script> +</body> diff --git a/testing/web-platform/tests/storage/partitioned-estimate-usage-details-indexeddb.tentative.https.sub.html b/testing/web-platform/tests/storage/partitioned-estimate-usage-details-indexeddb.tentative.https.sub.html new file mode 100644 index 0000000000..98a1ed8da2 --- /dev/null +++ b/testing/web-platform/tests/storage/partitioned-estimate-usage-details-indexeddb.tentative.https.sub.html @@ -0,0 +1,84 @@ +<!DOCTYPE html> +<meta name=help href="https://privacycg.github.io/storage-partitioning/"> +<title>Partitioned estimate() usage details for indexeddb test</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/utils.js"></script> +<script src="./helpers.js"></script> +<script src="../IndexedDB/resources/support-promises.js"></script> + +<body> + <script> + const usageDetails = async () => + (await navigator.storage.estimate()).usageDetails.indexedDB || 0; + + const createSomeUsage = async (test) => { + // We use 100KB here because db compaction usually happens every few MB + // 100KB is large enough to avoid a false positive (small amounts of + // metadata getting written for some random reason), and small enough to + // avoid compaction with a reasonably high probability. + const write_size = 1024 * 100; + const object_store_name = token(); + const db_name = self.location.pathname; + + await indexedDB.deleteDatabase(db_name); + const db = await createDB(db_name, object_store_name, test); + const transaction = db.transaction(object_store_name, 'readwrite'); + const value_to_store = largeValue(write_size, Math.random() * 255); + transaction.objectStore(object_store_name).add(value_to_store, 1); + + await transactionPromise(transaction); + return db; + } + + const testPath = () => location.pathname.split("/").slice(0, -1).join("/"); + + let alt_origin = "https://{{hosts[alt][]}}:{{ports[https][0]}}"; + let details = {}; + + const iframe = document.createElement("iframe"); + iframe.src = `https://{{host}}:{{ports[https][0]}}${testPath()}/resources` + + `/partitioned-estimate-usage-details-indexeddb-helper-frame.html`; + document.body.appendChild(iframe); + + async_test(test => { + if (location.origin === alt_origin) + return; + + let db; + window.addEventListener("message", test.step_func(async event => { + if (event.data === "iframe-is-ready") { + details.init = await usageDetails(); + db = await createSomeUsage(test); + details.after = await usageDetails(); + assert_greater_than(details.after, details.init); + + iframe.contentWindow.postMessage("get-details", iframe.origin); + } + })); + + window.addEventListener("message", test.step_func(event => { + if (event.data.source === "same-site") { + details.same_site = event.data; + + const cross_site_window = window + .open(`${alt_origin}${location.pathname}`, "", "noopener=false"); + test.add_cleanup(() => cross_site_window.close()); + } + if (event.data.source === "cross-site") { + details.cross_site = event.data; + + // Some cleanup + test.step(async () => await db.close()); + + test.step(() => { + assert_true(details.cross_site.init == 0, "Usage should be 0."); + assert_equals(details.same_site.init, details.after); + }); + + test.done(); + } + })); + }, "Partitioned estimate() usage details for indexeddb test."); + </script> +</body> diff --git a/testing/web-platform/tests/storage/partitioned-estimate-usage-details-service-workers.tentative.https.sub.html b/testing/web-platform/tests/storage/partitioned-estimate-usage-details-service-workers.tentative.https.sub.html new file mode 100644 index 0000000000..c52ca34e68 --- /dev/null +++ b/testing/web-platform/tests/storage/partitioned-estimate-usage-details-service-workers.tentative.https.sub.html @@ -0,0 +1,88 @@ +<!DOCTYPE html> +<meta name=help href="https://privacycg.github.io/storage-partitioning/"> +<title>Partitioned estimate() usage details for service workers test</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + +<body> + <script> + const usageDetails = async () => { + return (await navigator.storage.estimate()) + .usageDetails.serviceWorkerRegistrations || 0; + } + + const createSomeUsage = async () => { + const wait_for_active = worker => new Promise(resolve => { + if (worker.active) { resolve(worker.active); } + + const listen_for_active = worker => e => { + if (e.target.state === 'activated') { resolve(worker.active); } + } + + if (worker.waiting) { + worker.waiting + .addEventListener('statechange', listen_for_active(worker.waiting)); + } + if (worker.installing) { + worker.installing.addEventListener('statechange', + listen_for_active(worker.installing)); + } + }); + + const service_worker_registration = + await navigator.serviceWorker.register('resources/worker.js'); + await wait_for_active(service_worker_registration); + return service_worker_registration; + } + + const testPath = () => location.pathname.split("/").slice(0, -1).join("/"); + + let alt_origin = "https://{{hosts[alt][]}}:{{ports[https][0]}}"; + let details = {}; + + const iframe = document.createElement("iframe"); + iframe.src = `https://{{host}}:{{ports[https][0]}}${testPath()}/resources` + + `/partitioned-estimate-usage-details-service-workers-helper-frame.html` + document.body.appendChild(iframe); + + async_test(test => { + if (location.origin === alt_origin) + return; + + let service_worker_registration; + window.addEventListener("message", test.step_func(async event => { + if (event.data === "iframe-is-ready") { + details.init = await usageDetails(); + service_worker_registration = await createSomeUsage(); + details.after = await usageDetails(); + assert_greater_than(details.after, details.init); + + iframe.contentWindow.postMessage("get-details", iframe.origin); + } + })); + + window.addEventListener("message", test.step_func(event => { + if (event.data.source === "same-site") { + details.same_site = event.data; + + const cross_site_window = window + .open(`${alt_origin}${location.pathname}`, "", "noopener=false"); + test.add_cleanup(() => cross_site_window.close()); + } + if (event.data.source === "cross-site") { + details.cross_site = event.data; + + // More cleanup. + test.step(() => service_worker_registration.unregister()); + + test.step(() => { + assert_true(details.cross_site.init == 0, "Usage should be 0."); + assert_equals(details.same_site.init, details.after); + }); + + test.done(); + } + })); + }, "Partitioned estimate() usage details for service workers test."); + </script> +</body> diff --git a/testing/web-platform/tests/storage/permission-query.https.any.js b/testing/web-platform/tests/storage/permission-query.https.any.js new file mode 100644 index 0000000000..9984bdab79 --- /dev/null +++ b/testing/web-platform/tests/storage/permission-query.https.any.js @@ -0,0 +1,10 @@ +// META: title=The Permission API registration for "persistent-storage" + +promise_test(async t => { + const status = + await navigator.permissions.query({name: 'persistent-storage'}); + assert_equals(status.constructor, PermissionStatus, + 'query() result should resolve to a PermissionStatus'); + assert_true(['granted','denied', 'prompt'].includes(status.state), + 'state should be a PermissionState'); +}, 'The "persistent-storage" permission is recognized'); diff --git a/testing/web-platform/tests/storage/persist-permission-manual.https.html b/testing/web-platform/tests/storage/persist-permission-manual.https.html new file mode 100644 index 0000000000..aa49900d69 --- /dev/null +++ b/testing/web-platform/tests/storage/persist-permission-manual.https.html @@ -0,0 +1,27 @@ +<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <title>StorageManager: permission state is granted</title> + <p>Clear all persistent storage permissions before running this test.</p> + <p>Test passes if there is a permission prompt and click allow store persistent data</p> + <meta name="help" href="https://storage.spec.whatwg.org/#dom-storagemanager-persist"> + <meta name="author" title="Mozilla" href="https://www.mozilla.org"> + <script src="/resources/testharness.js"></script> + <script src="/resources/testharnessreport.js"></script> + </head> + <body> + <script> + promise_test(function(t) { + return navigator.storage.persist() + .then(function(result) { + assert_true(result); + return navigator.storage.persisted(); + }) + .then(function(result) { + assert_true(result); + }) + }, 'Expect permission state is granted after calling persist()'); + </script> + </body> +</html> diff --git a/testing/web-platform/tests/storage/persisted.https.any.js b/testing/web-platform/tests/storage/persisted.https.any.js new file mode 100644 index 0000000000..57e15f0e81 --- /dev/null +++ b/testing/web-platform/tests/storage/persisted.https.any.js @@ -0,0 +1,14 @@ +// META: title=StorageManager: persisted() + +test(function(t) { + assert_true('persisted' in navigator.storage); + assert_equals(typeof navigator.storage.persisted, 'function'); + assert_true(navigator.storage.persisted() instanceof Promise); +}, 'persisted() method exists and returns a Promise'); + +promise_test(function(t) { + return navigator.storage.persisted().then(function(result) { + assert_equals(typeof result, 'boolean'); + assert_equals(result, false); + }); +}, 'persisted() returns a promise and resolves as boolean with false'); diff --git a/testing/web-platform/tests/storage/quotachange-in-detached-iframe.tentative.https.html b/testing/web-platform/tests/storage/quotachange-in-detached-iframe.tentative.https.html new file mode 100644 index 0000000000..123af50e3c --- /dev/null +++ b/testing/web-platform/tests/storage/quotachange-in-detached-iframe.tentative.https.html @@ -0,0 +1,21 @@ +<!doctype html> +<meta charset="utf-8"> +<title>quotachange event on DOMWindow of detached iframe</title> +<link rel="author" href="jarrydg@chromium.org" title="Jarryd"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<iframe id="iframe"></iframe> +<script> +'use strict'; + +test(t => { + const iframe = document.getElementById('iframe'); + const frameWindow = iframe.contentWindow; + const storageManager = frameWindow.navigator.storage; + + iframe.parentNode.removeChild(iframe); + const emptyListener = () => {}; + storageManager.addEventListener('quotachange', emptyListener); + storageManager.removeEventListener('quotachange', emptyListener); +}, "Add quotachange listener on detached iframe."); +</script> diff --git a/testing/web-platform/tests/storage/resources/partitioned-estimate-usage-details-caches-helper-frame.html b/testing/web-platform/tests/storage/resources/partitioned-estimate-usage-details-caches-helper-frame.html new file mode 100644 index 0000000000..0679c1decf --- /dev/null +++ b/testing/web-platform/tests/storage/resources/partitioned-estimate-usage-details-caches-helper-frame.html @@ -0,0 +1,30 @@ +<!-- ToDo: Change the virtual suite expected file content once the necessary + partitioning implementation is completed --> +<!DOCTYPE html> +<meta name=help href="https://privacycg.github.io/storage-partitioning/"> +<title>Helper frame</title> + +<script> + const usageDetails = async () => + (await navigator.storage.estimate()).usageDetails.caches || 0; + + let details = {}; + + window.addEventListener("message", async event => { + if (event.data === "get-details") { + details.source = "same-site"; + details.init = await usageDetails(); + event.source.postMessage(details, event.source.origin); + } + }); + + window.addEventListener("load", async () => { + if (parent.opener) { + details.source = "cross-site"; + details.init = await usageDetails(); + parent.opener.postMessage(details, parent.opener.origin); + } + }); + + window.parent.postMessage("iframe-is-ready", window.parent.origin); +</script> diff --git a/testing/web-platform/tests/storage/resources/partitioned-estimate-usage-details-indexeddb-helper-frame.html b/testing/web-platform/tests/storage/resources/partitioned-estimate-usage-details-indexeddb-helper-frame.html new file mode 100644 index 0000000000..fd2cfb669b --- /dev/null +++ b/testing/web-platform/tests/storage/resources/partitioned-estimate-usage-details-indexeddb-helper-frame.html @@ -0,0 +1,28 @@ +<!DOCTYPE html> +<meta name=help href="https://privacycg.github.io/storage-partitioning/"> +<title>Helper frame</title> + +<script> + const usageDetails = async () => + (await navigator.storage.estimate()).usageDetails.indexedDB || 0; + + let details = {}; + + window.addEventListener("message", async event => { + if (event.data === "get-details") { + details.source = "same-site"; + details.init = await usageDetails(); + event.source.postMessage(details, event.source.origin); + } + }); + + window.addEventListener("load", async () => { + if (parent.opener) { + details.source = "cross-site"; + details.init = await usageDetails(); + parent.opener.postMessage(details, parent.opener.origin); + } + }); + + window.parent.postMessage("iframe-is-ready", window.parent.origin); +</script> diff --git a/testing/web-platform/tests/storage/resources/partitioned-estimate-usage-details-service-workers-helper-frame.html b/testing/web-platform/tests/storage/resources/partitioned-estimate-usage-details-service-workers-helper-frame.html new file mode 100644 index 0000000000..25d7554868 --- /dev/null +++ b/testing/web-platform/tests/storage/resources/partitioned-estimate-usage-details-service-workers-helper-frame.html @@ -0,0 +1,30 @@ +<!DOCTYPE html> +<meta name=help href="https://privacycg.github.io/storage-partitioning/"> +<title>Helper frame</title> + +<script> + const usageDetails = async () => { + return (await navigator.storage.estimate()) + .usageDetails.serviceWorkerRegistrations || 0 + } + + let details = {}; + + window.addEventListener("message", async event => { + if (event.data === "get-details") { + details.source = "same-site"; + details.init = await usageDetails(); + event.source.postMessage(details, event.source.origin); + } + }); + + window.addEventListener("load", async () => { + if (parent.opener) { + details.source = "cross-site"; + details.init = await usageDetails(); + parent.opener.postMessage(details, parent.opener.origin); + } + }); + + window.parent.postMessage("iframe-is-ready", window.parent.origin); +</script> diff --git a/testing/web-platform/tests/storage/resources/worker.js b/testing/web-platform/tests/storage/resources/worker.js new file mode 100644 index 0000000000..9271c769b2 --- /dev/null +++ b/testing/web-platform/tests/storage/resources/worker.js @@ -0,0 +1,3 @@ +// Dummy service worker to observe some weight when querying the storage usage +// details from of the service worker from estimate(). +globalThis.oninstall = e => {}; diff --git a/testing/web-platform/tests/storage/storagemanager-estimate.https.any.js b/testing/web-platform/tests/storage/storagemanager-estimate.https.any.js new file mode 100644 index 0000000000..3b6f4d8edc --- /dev/null +++ b/testing/web-platform/tests/storage/storagemanager-estimate.https.any.js @@ -0,0 +1,16 @@ +// META: title=StorageManager: estimate() + +test(t => { + assert_true('estimate' in navigator.storage); + assert_equals(typeof navigator.storage.estimate, 'function'); + assert_true(navigator.storage.estimate() instanceof Promise); +}, 'estimate() method exists and returns a Promise'); + +promise_test(async t => { + const result = await navigator.storage.estimate(); + assert_equals(typeof result, 'object'); + assert_true('usage' in result); + assert_equals(typeof result.usage, 'number'); + assert_true('quota' in result); + assert_equals(typeof result.quota, 'number'); +}, 'estimate() resolves to dictionary with members'); diff --git a/testing/web-platform/tests/storage/storagemanager-persist-persisted-match.https.any.js b/testing/web-platform/tests/storage/storagemanager-persist-persisted-match.https.any.js new file mode 100644 index 0000000000..edbe67fae2 --- /dev/null +++ b/testing/web-platform/tests/storage/storagemanager-persist-persisted-match.https.any.js @@ -0,0 +1,9 @@ +// META: title=StorageManager: result of persist() matches result of persisted() + +promise_test(async t => { + var persistResult = await navigator.storage.persist(); + assert_equals(typeof persistResult, 'boolean', persistResult + ' should be boolean'); + var persistedResult = await navigator.storage.persisted(); + assert_equals(typeof persistedResult, 'boolean', persistedResult + ' should be boolean'); + assert_equals(persistResult, persistedResult); +}, 'navigator.storage.persist() resolves to a value that matches navigator.storage.persisted()'); diff --git a/testing/web-platform/tests/storage/storagemanager-persist.https.window.js b/testing/web-platform/tests/storage/storagemanager-persist.https.window.js new file mode 100644 index 0000000000..13e17a16e1 --- /dev/null +++ b/testing/web-platform/tests/storage/storagemanager-persist.https.window.js @@ -0,0 +1,10 @@ +// META: title=StorageManager: persist() + +promise_test(function() { + var promise = navigator.storage.persist(); + assert_true(promise instanceof Promise, + 'navigator.storage.persist() returned a Promise.'); + return promise.then(function(result) { + assert_equals(typeof result, 'boolean', result + ' should be boolean'); + }); +}, 'navigator.storage.persist() returns a promise that resolves.'); diff --git a/testing/web-platform/tests/storage/storagemanager-persist.https.worker.js b/testing/web-platform/tests/storage/storagemanager-persist.https.worker.js new file mode 100644 index 0000000000..fcf8175f70 --- /dev/null +++ b/testing/web-platform/tests/storage/storagemanager-persist.https.worker.js @@ -0,0 +1,8 @@ +// META: title=StorageManager: persist() (worker) +importScripts("/resources/testharness.js"); + +test(function() { + assert_false('persist' in navigator.storage); +}, 'navigator.storage.persist should not exist in workers'); + +done(); diff --git a/testing/web-platform/tests/storage/storagemanager-persisted.https.any.js b/testing/web-platform/tests/storage/storagemanager-persisted.https.any.js new file mode 100644 index 0000000000..7099940669 --- /dev/null +++ b/testing/web-platform/tests/storage/storagemanager-persisted.https.any.js @@ -0,0 +1,10 @@ +// META: title=StorageManager: persisted() + +promise_test(function() { + var promise = navigator.storage.persisted(); + assert_true(promise instanceof Promise, + 'navigator.storage.persisted() returned a Promise.'); + return promise.then(function (result) { + assert_equals(typeof result, 'boolean', result + ' should be boolean'); + }); +}, 'navigator.storage.persisted() returns a promise that resolves.'); |