@firebase/rules-unit-testing 4.0.0 → 4.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.d.ts +19 -19
- package/dist/esm/index.esm.js +587 -587
- package/dist/esm/index.esm.js.map +1 -1
- package/dist/esm/src/impl/discovery.d.ts +46 -46
- package/dist/esm/src/impl/rules.d.ts +29 -29
- package/dist/esm/src/impl/test_environment.d.ts +43 -43
- package/dist/esm/src/impl/url.d.ts +32 -32
- package/dist/esm/src/initialize.d.ts +39 -39
- package/dist/esm/src/public_types/index.d.ts +228 -228
- package/dist/esm/src/util.d.ts +75 -75
- package/dist/esm/test/dummy.test.d.ts +17 -17
- package/dist/esm/test/impl/discovery.test.d.ts +17 -17
- package/dist/esm/test/impl/rules.test.d.ts +17 -17
- package/dist/esm/test/setup.d.ts +19 -19
- package/dist/esm/test/test_utils.d.ts +18 -18
- package/dist/esm/test/util.test.d.ts +17 -17
- package/dist/index.cjs.js +587 -587
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +19 -19
- package/dist/src/impl/discovery.d.ts +46 -46
- package/dist/src/impl/rules.d.ts +29 -29
- package/dist/src/impl/test_environment.d.ts +43 -43
- package/dist/src/impl/url.d.ts +32 -32
- package/dist/src/initialize.d.ts +39 -39
- package/dist/src/public_types/index.d.ts +228 -228
- package/dist/src/util.d.ts +75 -75
- package/dist/test/dummy.test.d.ts +17 -17
- package/dist/test/impl/discovery.test.d.ts +17 -17
- package/dist/test/impl/rules.test.d.ts +17 -17
- package/dist/test/setup.d.ts +19 -19
- package/dist/test/test_utils.d.ts +18 -18
- package/dist/test/util.test.d.ts +17 -17
- package/package.json +1 -1
package/dist/esm/index.esm.js
CHANGED
|
@@ -3,603 +3,603 @@ import 'firebase/compat/firestore';
|
|
|
3
3
|
import 'firebase/compat/storage';
|
|
4
4
|
import firebase from 'firebase/compat/app';
|
|
5
5
|
|
|
6
|
-
/**
|
|
7
|
-
* @license
|
|
8
|
-
* Copyright 2021 Google LLC
|
|
9
|
-
*
|
|
10
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
11
|
-
* you may not use this file except in compliance with the License.
|
|
12
|
-
* You may obtain a copy of the License at
|
|
13
|
-
*
|
|
14
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
15
|
-
*
|
|
16
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
17
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
18
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
19
|
-
* See the License for the specific language governing permissions and
|
|
20
|
-
* limitations under the License.
|
|
21
|
-
*/
|
|
22
|
-
/**
|
|
23
|
-
* Return a connectable hostname, replacing wildcard 0.0.0.0 or :: with loopback
|
|
24
|
-
* addresses 127.0.0.1 / ::1 correspondingly. See below for why this is needed:
|
|
25
|
-
* https://github.com/firebase/firebase-tools-ui/issues/286
|
|
26
|
-
*
|
|
27
|
-
* This assumes emulators are running on the same device as fallbackHost (e.g.
|
|
28
|
-
* hub), which should hold if both are started from the same CLI command.
|
|
29
|
-
* @private
|
|
30
|
-
*/
|
|
31
|
-
function fixHostname(host, fallbackHost) {
|
|
32
|
-
host = host.replace('[', '').replace(']', ''); // Remove IPv6 brackets
|
|
33
|
-
if (host === '0.0.0.0') {
|
|
34
|
-
host = fallbackHost || '127.0.0.1';
|
|
35
|
-
}
|
|
36
|
-
else if (host === '::') {
|
|
37
|
-
host = fallbackHost || '::1';
|
|
38
|
-
}
|
|
39
|
-
return host;
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* Create a URL with host, port, and path. Handles IPv6 bracketing correctly.
|
|
43
|
-
* @private
|
|
44
|
-
*/
|
|
45
|
-
function makeUrl(hostAndPort, path) {
|
|
46
|
-
if (typeof hostAndPort === 'object') {
|
|
47
|
-
const { host, port } = hostAndPort;
|
|
48
|
-
if (host.includes(':')) {
|
|
49
|
-
hostAndPort = `[${host}]:${port}`;
|
|
50
|
-
}
|
|
51
|
-
else {
|
|
52
|
-
hostAndPort = `${host}:${port}`;
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
const url = new URL(`http://${hostAndPort}/`);
|
|
56
|
-
url.pathname = path;
|
|
57
|
-
return url;
|
|
6
|
+
/**
|
|
7
|
+
* @license
|
|
8
|
+
* Copyright 2021 Google LLC
|
|
9
|
+
*
|
|
10
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
11
|
+
* you may not use this file except in compliance with the License.
|
|
12
|
+
* You may obtain a copy of the License at
|
|
13
|
+
*
|
|
14
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
15
|
+
*
|
|
16
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
17
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
18
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
19
|
+
* See the License for the specific language governing permissions and
|
|
20
|
+
* limitations under the License.
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* Return a connectable hostname, replacing wildcard 0.0.0.0 or :: with loopback
|
|
24
|
+
* addresses 127.0.0.1 / ::1 correspondingly. See below for why this is needed:
|
|
25
|
+
* https://github.com/firebase/firebase-tools-ui/issues/286
|
|
26
|
+
*
|
|
27
|
+
* This assumes emulators are running on the same device as fallbackHost (e.g.
|
|
28
|
+
* hub), which should hold if both are started from the same CLI command.
|
|
29
|
+
* @private
|
|
30
|
+
*/
|
|
31
|
+
function fixHostname(host, fallbackHost) {
|
|
32
|
+
host = host.replace('[', '').replace(']', ''); // Remove IPv6 brackets
|
|
33
|
+
if (host === '0.0.0.0') {
|
|
34
|
+
host = fallbackHost || '127.0.0.1';
|
|
35
|
+
}
|
|
36
|
+
else if (host === '::') {
|
|
37
|
+
host = fallbackHost || '::1';
|
|
38
|
+
}
|
|
39
|
+
return host;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Create a URL with host, port, and path. Handles IPv6 bracketing correctly.
|
|
43
|
+
* @private
|
|
44
|
+
*/
|
|
45
|
+
function makeUrl(hostAndPort, path) {
|
|
46
|
+
if (typeof hostAndPort === 'object') {
|
|
47
|
+
const { host, port } = hostAndPort;
|
|
48
|
+
if (host.includes(':')) {
|
|
49
|
+
hostAndPort = `[${host}]:${port}`;
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
hostAndPort = `${host}:${port}`;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const url = new URL(`http://${hostAndPort}/`);
|
|
56
|
+
url.pathname = path;
|
|
57
|
+
return url;
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
-
/**
|
|
61
|
-
* @license
|
|
62
|
-
* Copyright 2021 Google LLC
|
|
63
|
-
*
|
|
64
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
65
|
-
* you may not use this file except in compliance with the License.
|
|
66
|
-
* You may obtain a copy of the License at
|
|
67
|
-
*
|
|
68
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
69
|
-
*
|
|
70
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
71
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
72
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
73
|
-
* See the License for the specific language governing permissions and
|
|
74
|
-
* limitations under the License.
|
|
75
|
-
*/
|
|
76
|
-
/**
|
|
77
|
-
* Use the Firebase Emulator hub to discover other running emulators.
|
|
78
|
-
*
|
|
79
|
-
* @param hub the host and port where the Emulator Hub is running
|
|
80
|
-
* @private
|
|
81
|
-
*/
|
|
82
|
-
async function discoverEmulators(hub, fetchImpl = fetch) {
|
|
83
|
-
const res = await fetchImpl(makeUrl(hub, '/emulators'));
|
|
84
|
-
if (!res.ok) {
|
|
85
|
-
throw new Error(`HTTP Error ${res.status} when attempting to reach Emulator Hub at ${res.url}, are you sure it is running?`);
|
|
86
|
-
}
|
|
87
|
-
const emulators = {};
|
|
88
|
-
const data = await res.json();
|
|
89
|
-
if (data.database) {
|
|
90
|
-
emulators.database = {
|
|
91
|
-
host: data.database.host,
|
|
92
|
-
port: data.database.port
|
|
93
|
-
};
|
|
94
|
-
}
|
|
95
|
-
if (data.firestore) {
|
|
96
|
-
emulators.firestore = {
|
|
97
|
-
host: data.firestore.host,
|
|
98
|
-
port: data.firestore.port
|
|
99
|
-
};
|
|
100
|
-
}
|
|
101
|
-
if (data.storage) {
|
|
102
|
-
emulators.storage = {
|
|
103
|
-
host: data.storage.host,
|
|
104
|
-
port: data.storage.port
|
|
105
|
-
};
|
|
106
|
-
}
|
|
107
|
-
if (data.hub) {
|
|
108
|
-
emulators.hub = {
|
|
109
|
-
host: data.hub.host,
|
|
110
|
-
port: data.hub.port
|
|
111
|
-
};
|
|
112
|
-
}
|
|
113
|
-
return emulators;
|
|
114
|
-
}
|
|
115
|
-
/**
|
|
116
|
-
* @private
|
|
117
|
-
*/
|
|
118
|
-
function getEmulatorHostAndPort(emulator, conf, discovered) {
|
|
119
|
-
var _a, _b;
|
|
120
|
-
if (conf && ('host' in conf || 'port' in conf)) {
|
|
121
|
-
const { host, port } = conf;
|
|
122
|
-
if (host || port) {
|
|
123
|
-
if (!host || !port) {
|
|
124
|
-
throw new Error(`Invalid configuration ${emulator}.host=${host} and ${emulator}.port=${port}. ` +
|
|
125
|
-
'If either parameter is supplied, both must be defined.');
|
|
126
|
-
}
|
|
127
|
-
if (discovered && !discovered[emulator]) {
|
|
128
|
-
console.warn(`Warning: config for the ${emulator} emulator is specified, but the Emulator hub ` +
|
|
129
|
-
'reports it as not running. This may lead to errors such as connection refused.');
|
|
130
|
-
}
|
|
131
|
-
return {
|
|
132
|
-
host: fixHostname(
|
|
133
|
-
port:
|
|
134
|
-
};
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
const envVar = EMULATOR_HOST_ENV_VARS[emulator];
|
|
138
|
-
const fallback = (discovered === null || discovered === void 0 ? void 0 : discovered[emulator]) || emulatorFromEnvVar(envVar);
|
|
139
|
-
if (fallback) {
|
|
140
|
-
if (discovered && !discovered[emulator]) {
|
|
141
|
-
console.warn(`Warning: the environment variable ${envVar} is set, but the Emulator hub reports the ` +
|
|
142
|
-
`${emulator} emulator as not running. This may lead to errors such as connection refused.`);
|
|
143
|
-
}
|
|
144
|
-
return {
|
|
145
|
-
host: fixHostname(fallback.host, (_b = discovered === null || discovered === void 0 ? void 0 : discovered.hub) === null || _b === void 0 ? void 0 : _b.host),
|
|
146
|
-
port: fallback.port
|
|
147
|
-
};
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
// Visible for testing.
|
|
151
|
-
const EMULATOR_HOST_ENV_VARS = {
|
|
152
|
-
'database': 'FIREBASE_DATABASE_EMULATOR_HOST',
|
|
153
|
-
'firestore': 'FIRESTORE_EMULATOR_HOST',
|
|
154
|
-
'hub': 'FIREBASE_EMULATOR_HUB',
|
|
155
|
-
'storage': 'FIREBASE_STORAGE_EMULATOR_HOST'
|
|
156
|
-
};
|
|
157
|
-
function emulatorFromEnvVar(envVar) {
|
|
158
|
-
const hostAndPort = process.env[envVar];
|
|
159
|
-
if (!hostAndPort) {
|
|
160
|
-
return undefined;
|
|
161
|
-
}
|
|
162
|
-
let parsed;
|
|
163
|
-
try {
|
|
164
|
-
parsed = new URL(`http://${hostAndPort}`);
|
|
165
|
-
}
|
|
166
|
-
catch (_a) {
|
|
167
|
-
throw new Error(`Invalid format in environment variable ${envVar}=${hostAndPort} (expected host:port)`);
|
|
168
|
-
}
|
|
169
|
-
let host = parsed.hostname;
|
|
170
|
-
const port = Number(parsed.port || '80');
|
|
171
|
-
if (!Number.isInteger(port)) {
|
|
172
|
-
throw new Error(`Invalid port in environment variable ${envVar}=${hostAndPort}`);
|
|
173
|
-
}
|
|
174
|
-
return { host, port };
|
|
60
|
+
/**
|
|
61
|
+
* @license
|
|
62
|
+
* Copyright 2021 Google LLC
|
|
63
|
+
*
|
|
64
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
65
|
+
* you may not use this file except in compliance with the License.
|
|
66
|
+
* You may obtain a copy of the License at
|
|
67
|
+
*
|
|
68
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
69
|
+
*
|
|
70
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
71
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
72
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
73
|
+
* See the License for the specific language governing permissions and
|
|
74
|
+
* limitations under the License.
|
|
75
|
+
*/
|
|
76
|
+
/**
|
|
77
|
+
* Use the Firebase Emulator hub to discover other running emulators.
|
|
78
|
+
*
|
|
79
|
+
* @param hub the host and port where the Emulator Hub is running
|
|
80
|
+
* @private
|
|
81
|
+
*/
|
|
82
|
+
async function discoverEmulators(hub, fetchImpl = fetch) {
|
|
83
|
+
const res = await fetchImpl(makeUrl(hub, '/emulators'));
|
|
84
|
+
if (!res.ok) {
|
|
85
|
+
throw new Error(`HTTP Error ${res.status} when attempting to reach Emulator Hub at ${res.url}, are you sure it is running?`);
|
|
86
|
+
}
|
|
87
|
+
const emulators = {};
|
|
88
|
+
const data = await res.json();
|
|
89
|
+
if (data.database) {
|
|
90
|
+
emulators.database = {
|
|
91
|
+
host: data.database.host,
|
|
92
|
+
port: data.database.port
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
if (data.firestore) {
|
|
96
|
+
emulators.firestore = {
|
|
97
|
+
host: data.firestore.host,
|
|
98
|
+
port: data.firestore.port
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
if (data.storage) {
|
|
102
|
+
emulators.storage = {
|
|
103
|
+
host: data.storage.host,
|
|
104
|
+
port: data.storage.port
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
if (data.hub) {
|
|
108
|
+
emulators.hub = {
|
|
109
|
+
host: data.hub.host,
|
|
110
|
+
port: data.hub.port
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
return emulators;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* @private
|
|
117
|
+
*/
|
|
118
|
+
function getEmulatorHostAndPort(emulator, conf, discovered) {
|
|
119
|
+
var _a, _b;
|
|
120
|
+
if (conf && ('host' in conf || 'port' in conf)) {
|
|
121
|
+
const { host, port } = conf;
|
|
122
|
+
if (host || port) {
|
|
123
|
+
if (!host || !port) {
|
|
124
|
+
throw new Error(`Invalid configuration ${emulator}.host=${host} and ${emulator}.port=${port}. ` +
|
|
125
|
+
'If either parameter is supplied, both must be defined.');
|
|
126
|
+
}
|
|
127
|
+
if (discovered && !discovered[emulator]) {
|
|
128
|
+
console.warn(`Warning: config for the ${emulator} emulator is specified, but the Emulator hub ` +
|
|
129
|
+
'reports it as not running. This may lead to errors such as connection refused.');
|
|
130
|
+
}
|
|
131
|
+
return {
|
|
132
|
+
host: fixHostname(host, (_a = discovered === null || discovered === void 0 ? void 0 : discovered.hub) === null || _a === void 0 ? void 0 : _a.host),
|
|
133
|
+
port: port
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
const envVar = EMULATOR_HOST_ENV_VARS[emulator];
|
|
138
|
+
const fallback = (discovered === null || discovered === void 0 ? void 0 : discovered[emulator]) || emulatorFromEnvVar(envVar);
|
|
139
|
+
if (fallback) {
|
|
140
|
+
if (discovered && !discovered[emulator]) {
|
|
141
|
+
console.warn(`Warning: the environment variable ${envVar} is set, but the Emulator hub reports the ` +
|
|
142
|
+
`${emulator} emulator as not running. This may lead to errors such as connection refused.`);
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
host: fixHostname(fallback.host, (_b = discovered === null || discovered === void 0 ? void 0 : discovered.hub) === null || _b === void 0 ? void 0 : _b.host),
|
|
146
|
+
port: fallback.port
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
// Visible for testing.
|
|
151
|
+
const EMULATOR_HOST_ENV_VARS = {
|
|
152
|
+
'database': 'FIREBASE_DATABASE_EMULATOR_HOST',
|
|
153
|
+
'firestore': 'FIRESTORE_EMULATOR_HOST',
|
|
154
|
+
'hub': 'FIREBASE_EMULATOR_HUB',
|
|
155
|
+
'storage': 'FIREBASE_STORAGE_EMULATOR_HOST'
|
|
156
|
+
};
|
|
157
|
+
function emulatorFromEnvVar(envVar) {
|
|
158
|
+
const hostAndPort = process.env[envVar];
|
|
159
|
+
if (!hostAndPort) {
|
|
160
|
+
return undefined;
|
|
161
|
+
}
|
|
162
|
+
let parsed;
|
|
163
|
+
try {
|
|
164
|
+
parsed = new URL(`http://${hostAndPort}`);
|
|
165
|
+
}
|
|
166
|
+
catch (_a) {
|
|
167
|
+
throw new Error(`Invalid format in environment variable ${envVar}=${hostAndPort} (expected host:port)`);
|
|
168
|
+
}
|
|
169
|
+
let host = parsed.hostname;
|
|
170
|
+
const port = Number(parsed.port || '80');
|
|
171
|
+
if (!Number.isInteger(port)) {
|
|
172
|
+
throw new Error(`Invalid port in environment variable ${envVar}=${hostAndPort}`);
|
|
173
|
+
}
|
|
174
|
+
return { host, port };
|
|
175
175
|
}
|
|
176
176
|
|
|
177
|
-
/**
|
|
178
|
-
* @license
|
|
179
|
-
* Copyright 2021 Google LLC
|
|
180
|
-
*
|
|
181
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
182
|
-
* you may not use this file except in compliance with the License.
|
|
183
|
-
* You may obtain a copy of the License at
|
|
184
|
-
*
|
|
185
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
186
|
-
*
|
|
187
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
188
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
189
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
190
|
-
* See the License for the specific language governing permissions and
|
|
191
|
-
* limitations under the License.
|
|
192
|
-
*/
|
|
193
|
-
/**
|
|
194
|
-
* An implementation of {@code RulesTestEnvironment}. This is private to hide the constructor,
|
|
195
|
-
* which should never be directly called by the developer.
|
|
196
|
-
* @private
|
|
197
|
-
*/
|
|
198
|
-
class RulesTestEnvironmentImpl {
|
|
199
|
-
constructor(projectId, emulators) {
|
|
200
|
-
this.projectId = projectId;
|
|
201
|
-
this.emulators = emulators;
|
|
202
|
-
this.contexts = new Set();
|
|
203
|
-
this.destroyed = false;
|
|
204
|
-
}
|
|
205
|
-
authenticatedContext(user_id, tokenOptions) {
|
|
206
|
-
this.checkNotDestroyed();
|
|
207
|
-
return this.createContext(Object.assign(Object.assign({}, tokenOptions), { sub: user_id, user_id: user_id }));
|
|
208
|
-
}
|
|
209
|
-
unauthenticatedContext() {
|
|
210
|
-
this.checkNotDestroyed();
|
|
211
|
-
return this.createContext(/* authToken = */ undefined);
|
|
212
|
-
}
|
|
213
|
-
async withSecurityRulesDisabled(callback) {
|
|
214
|
-
this.checkNotDestroyed();
|
|
215
|
-
// The "owner" token is recognized by the emulators as a special value that bypasses Security
|
|
216
|
-
// Rules. This should only ever be used in withSecurityRulesDisabled.
|
|
217
|
-
// If you're reading this and thinking about doing this in your own app / tests / scripts, think
|
|
218
|
-
// twice. Instead, just use withSecurityRulesDisabled for unit testing OR connect your Firebase
|
|
219
|
-
// Admin SDKs to the emulators for integration testing via environment variables.
|
|
220
|
-
// See: https://firebase.google.com/docs/emulator-suite/connect_firestore#admin_sdks
|
|
221
|
-
const context = this.createContext('owner');
|
|
222
|
-
try {
|
|
223
|
-
await callback(context);
|
|
224
|
-
}
|
|
225
|
-
finally {
|
|
226
|
-
// We eagerly clean up this context to actively prevent misuse outside of the callback, e.g.
|
|
227
|
-
// storing the context in a variable.
|
|
228
|
-
context.cleanup();
|
|
229
|
-
this.contexts.delete(context);
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
createContext(authToken) {
|
|
233
|
-
const context = new RulesTestContextImpl(this.projectId, this.emulators, authToken);
|
|
234
|
-
this.contexts.add(context);
|
|
235
|
-
return context;
|
|
236
|
-
}
|
|
237
|
-
clearDatabase() {
|
|
238
|
-
this.checkNotDestroyed();
|
|
239
|
-
return this.withSecurityRulesDisabled(context => {
|
|
240
|
-
return context.database().ref('/').set(null);
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
|
-
async clearFirestore() {
|
|
244
|
-
this.checkNotDestroyed();
|
|
245
|
-
assertEmulatorRunning(this.emulators, 'firestore');
|
|
246
|
-
const resp = await fetch(makeUrl(this.emulators.firestore, `/emulator/v1/projects/${this.projectId}/databases/(default)/documents`), {
|
|
247
|
-
method: 'DELETE'
|
|
248
|
-
});
|
|
249
|
-
if (!resp.ok) {
|
|
250
|
-
throw new Error(await resp.text());
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
clearStorage() {
|
|
254
|
-
this.checkNotDestroyed();
|
|
255
|
-
return this.withSecurityRulesDisabled(async (context) => {
|
|
256
|
-
const { items } = await context.storage().ref().listAll();
|
|
257
|
-
await Promise.all(items.map((item) => {
|
|
258
|
-
return item.delete();
|
|
259
|
-
}));
|
|
260
|
-
});
|
|
261
|
-
}
|
|
262
|
-
async cleanup() {
|
|
263
|
-
this.destroyed = true;
|
|
264
|
-
this.contexts.forEach(context => {
|
|
265
|
-
context.envDestroyed = true;
|
|
266
|
-
context.cleanup();
|
|
267
|
-
});
|
|
268
|
-
this.contexts.clear();
|
|
269
|
-
}
|
|
270
|
-
checkNotDestroyed() {
|
|
271
|
-
if (this.destroyed) {
|
|
272
|
-
throw new Error('This RulesTestEnvironment has already been cleaned up. ' +
|
|
273
|
-
'(This may indicate a leak or missing `await` in your test cases. If you do intend to ' +
|
|
274
|
-
'perform more tests, please call cleanup() later or create another RulesTestEnvironment.)');
|
|
275
|
-
}
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
/**
|
|
279
|
-
* An implementation of {@code RulesTestContext}. This is private to hide the constructor,
|
|
280
|
-
* which should never be directly called by the developer.
|
|
281
|
-
* @private
|
|
282
|
-
*/
|
|
283
|
-
class RulesTestContextImpl {
|
|
284
|
-
constructor(projectId, emulators, authToken) {
|
|
285
|
-
this.projectId = projectId;
|
|
286
|
-
this.emulators = emulators;
|
|
287
|
-
this.authToken = authToken;
|
|
288
|
-
this.destroyed = false;
|
|
289
|
-
this.envDestroyed = false;
|
|
290
|
-
}
|
|
291
|
-
cleanup() {
|
|
292
|
-
var _a;
|
|
293
|
-
this.destroyed = true;
|
|
294
|
-
(_a = this.app) === null || _a === void 0 ? void 0 : _a.delete();
|
|
295
|
-
this.app = undefined;
|
|
296
|
-
}
|
|
297
|
-
firestore(settings) {
|
|
298
|
-
assertEmulatorRunning(this.emulators, 'firestore');
|
|
299
|
-
const firestore = this.getApp().firestore();
|
|
300
|
-
if (settings) {
|
|
301
|
-
firestore.settings(settings);
|
|
302
|
-
}
|
|
303
|
-
firestore.useEmulator(this.emulators.firestore.host, this.emulators.firestore.port, { mockUserToken: this.authToken });
|
|
304
|
-
return firestore;
|
|
305
|
-
}
|
|
306
|
-
database(databaseURL) {
|
|
307
|
-
assertEmulatorRunning(this.emulators, 'database');
|
|
308
|
-
if (!databaseURL) {
|
|
309
|
-
const url = makeUrl(this.emulators.database, '');
|
|
310
|
-
// Make sure to set the namespace equal to projectId -- otherwise the RTDB SDK will by default
|
|
311
|
-
// use `${projectId}-default-rtdb`, which is treated as a different DB by the RTDB emulator
|
|
312
|
-
// (and thus WON'T apply any rules set for the `projectId` DB during initialization).
|
|
313
|
-
url.searchParams.append('ns', this.projectId);
|
|
314
|
-
databaseURL = url.toString();
|
|
315
|
-
}
|
|
316
|
-
const database = this.getApp().database(databaseURL);
|
|
317
|
-
database.useEmulator(this.emulators.database.host, this.emulators.database.port, { mockUserToken: this.authToken });
|
|
318
|
-
return database;
|
|
319
|
-
}
|
|
320
|
-
storage(bucketUrl = `gs://${this.projectId}`) {
|
|
321
|
-
assertEmulatorRunning(this.emulators, 'storage');
|
|
322
|
-
const storage = this.getApp().storage(bucketUrl);
|
|
323
|
-
storage.useEmulator(this.emulators.storage.host, this.emulators.storage.port, { mockUserToken: this.authToken });
|
|
324
|
-
return storage;
|
|
325
|
-
}
|
|
326
|
-
getApp() {
|
|
327
|
-
if (this.envDestroyed) {
|
|
328
|
-
throw new Error('This RulesTestContext is no longer valid because its RulesTestEnvironment has been ' +
|
|
329
|
-
'cleaned up. (This may indicate a leak or missing `await` in your test cases.)');
|
|
330
|
-
}
|
|
331
|
-
if (this.destroyed) {
|
|
332
|
-
throw new Error('This RulesTestContext is no longer valid. When using withSecurityRulesDisabled, ' +
|
|
333
|
-
'make sure to perform all operations on the context within the callback function and ' +
|
|
334
|
-
'return a Promise that resolves when the operations are done.');
|
|
335
|
-
}
|
|
336
|
-
if (!this.app) {
|
|
337
|
-
this.app = firebase.initializeApp({ projectId: this.projectId }, `_Firebase_RulesUnitTesting_${Date.now()}_${Math.random()}`);
|
|
338
|
-
}
|
|
339
|
-
return this.app;
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
function assertEmulatorRunning(emulators, emulator) {
|
|
343
|
-
if (!emulators[emulator]) {
|
|
344
|
-
if (emulators.hub) {
|
|
345
|
-
throw new Error(`The ${emulator} emulator is not running (according to Emulator hub). To force ` +
|
|
346
|
-
'connecting anyway, please specify its host and port in initializeTestEnvironment({...}).');
|
|
347
|
-
}
|
|
348
|
-
else {
|
|
349
|
-
throw new Error(`The host and port of the ${emulator} emulator must be specified. (You may wrap the test ` +
|
|
350
|
-
"script with `firebase emulators:exec './your-test-script'` to enable automatic " +
|
|
351
|
-
`discovery, or specify manually via initializeTestEnvironment({${emulator}: {host, port}}).`);
|
|
352
|
-
}
|
|
353
|
-
}
|
|
177
|
+
/**
|
|
178
|
+
* @license
|
|
179
|
+
* Copyright 2021 Google LLC
|
|
180
|
+
*
|
|
181
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
182
|
+
* you may not use this file except in compliance with the License.
|
|
183
|
+
* You may obtain a copy of the License at
|
|
184
|
+
*
|
|
185
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
186
|
+
*
|
|
187
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
188
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
189
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
190
|
+
* See the License for the specific language governing permissions and
|
|
191
|
+
* limitations under the License.
|
|
192
|
+
*/
|
|
193
|
+
/**
|
|
194
|
+
* An implementation of {@code RulesTestEnvironment}. This is private to hide the constructor,
|
|
195
|
+
* which should never be directly called by the developer.
|
|
196
|
+
* @private
|
|
197
|
+
*/
|
|
198
|
+
class RulesTestEnvironmentImpl {
|
|
199
|
+
constructor(projectId, emulators) {
|
|
200
|
+
this.projectId = projectId;
|
|
201
|
+
this.emulators = emulators;
|
|
202
|
+
this.contexts = new Set();
|
|
203
|
+
this.destroyed = false;
|
|
204
|
+
}
|
|
205
|
+
authenticatedContext(user_id, tokenOptions) {
|
|
206
|
+
this.checkNotDestroyed();
|
|
207
|
+
return this.createContext(Object.assign(Object.assign({}, tokenOptions), { sub: user_id, user_id: user_id }));
|
|
208
|
+
}
|
|
209
|
+
unauthenticatedContext() {
|
|
210
|
+
this.checkNotDestroyed();
|
|
211
|
+
return this.createContext(/* authToken = */ undefined);
|
|
212
|
+
}
|
|
213
|
+
async withSecurityRulesDisabled(callback) {
|
|
214
|
+
this.checkNotDestroyed();
|
|
215
|
+
// The "owner" token is recognized by the emulators as a special value that bypasses Security
|
|
216
|
+
// Rules. This should only ever be used in withSecurityRulesDisabled.
|
|
217
|
+
// If you're reading this and thinking about doing this in your own app / tests / scripts, think
|
|
218
|
+
// twice. Instead, just use withSecurityRulesDisabled for unit testing OR connect your Firebase
|
|
219
|
+
// Admin SDKs to the emulators for integration testing via environment variables.
|
|
220
|
+
// See: https://firebase.google.com/docs/emulator-suite/connect_firestore#admin_sdks
|
|
221
|
+
const context = this.createContext('owner');
|
|
222
|
+
try {
|
|
223
|
+
await callback(context);
|
|
224
|
+
}
|
|
225
|
+
finally {
|
|
226
|
+
// We eagerly clean up this context to actively prevent misuse outside of the callback, e.g.
|
|
227
|
+
// storing the context in a variable.
|
|
228
|
+
context.cleanup();
|
|
229
|
+
this.contexts.delete(context);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
createContext(authToken) {
|
|
233
|
+
const context = new RulesTestContextImpl(this.projectId, this.emulators, authToken);
|
|
234
|
+
this.contexts.add(context);
|
|
235
|
+
return context;
|
|
236
|
+
}
|
|
237
|
+
clearDatabase() {
|
|
238
|
+
this.checkNotDestroyed();
|
|
239
|
+
return this.withSecurityRulesDisabled(context => {
|
|
240
|
+
return context.database().ref('/').set(null);
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
async clearFirestore() {
|
|
244
|
+
this.checkNotDestroyed();
|
|
245
|
+
assertEmulatorRunning(this.emulators, 'firestore');
|
|
246
|
+
const resp = await fetch(makeUrl(this.emulators.firestore, `/emulator/v1/projects/${this.projectId}/databases/(default)/documents`), {
|
|
247
|
+
method: 'DELETE'
|
|
248
|
+
});
|
|
249
|
+
if (!resp.ok) {
|
|
250
|
+
throw new Error(await resp.text());
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
clearStorage() {
|
|
254
|
+
this.checkNotDestroyed();
|
|
255
|
+
return this.withSecurityRulesDisabled(async (context) => {
|
|
256
|
+
const { items } = await context.storage().ref().listAll();
|
|
257
|
+
await Promise.all(items.map((item) => {
|
|
258
|
+
return item.delete();
|
|
259
|
+
}));
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
async cleanup() {
|
|
263
|
+
this.destroyed = true;
|
|
264
|
+
this.contexts.forEach(context => {
|
|
265
|
+
context.envDestroyed = true;
|
|
266
|
+
context.cleanup();
|
|
267
|
+
});
|
|
268
|
+
this.contexts.clear();
|
|
269
|
+
}
|
|
270
|
+
checkNotDestroyed() {
|
|
271
|
+
if (this.destroyed) {
|
|
272
|
+
throw new Error('This RulesTestEnvironment has already been cleaned up. ' +
|
|
273
|
+
'(This may indicate a leak or missing `await` in your test cases. If you do intend to ' +
|
|
274
|
+
'perform more tests, please call cleanup() later or create another RulesTestEnvironment.)');
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* An implementation of {@code RulesTestContext}. This is private to hide the constructor,
|
|
280
|
+
* which should never be directly called by the developer.
|
|
281
|
+
* @private
|
|
282
|
+
*/
|
|
283
|
+
class RulesTestContextImpl {
|
|
284
|
+
constructor(projectId, emulators, authToken) {
|
|
285
|
+
this.projectId = projectId;
|
|
286
|
+
this.emulators = emulators;
|
|
287
|
+
this.authToken = authToken;
|
|
288
|
+
this.destroyed = false;
|
|
289
|
+
this.envDestroyed = false;
|
|
290
|
+
}
|
|
291
|
+
cleanup() {
|
|
292
|
+
var _a;
|
|
293
|
+
this.destroyed = true;
|
|
294
|
+
(_a = this.app) === null || _a === void 0 ? void 0 : _a.delete();
|
|
295
|
+
this.app = undefined;
|
|
296
|
+
}
|
|
297
|
+
firestore(settings) {
|
|
298
|
+
assertEmulatorRunning(this.emulators, 'firestore');
|
|
299
|
+
const firestore = this.getApp().firestore();
|
|
300
|
+
if (settings) {
|
|
301
|
+
firestore.settings(settings);
|
|
302
|
+
}
|
|
303
|
+
firestore.useEmulator(this.emulators.firestore.host, this.emulators.firestore.port, { mockUserToken: this.authToken });
|
|
304
|
+
return firestore;
|
|
305
|
+
}
|
|
306
|
+
database(databaseURL) {
|
|
307
|
+
assertEmulatorRunning(this.emulators, 'database');
|
|
308
|
+
if (!databaseURL) {
|
|
309
|
+
const url = makeUrl(this.emulators.database, '');
|
|
310
|
+
// Make sure to set the namespace equal to projectId -- otherwise the RTDB SDK will by default
|
|
311
|
+
// use `${projectId}-default-rtdb`, which is treated as a different DB by the RTDB emulator
|
|
312
|
+
// (and thus WON'T apply any rules set for the `projectId` DB during initialization).
|
|
313
|
+
url.searchParams.append('ns', this.projectId);
|
|
314
|
+
databaseURL = url.toString();
|
|
315
|
+
}
|
|
316
|
+
const database = this.getApp().database(databaseURL);
|
|
317
|
+
database.useEmulator(this.emulators.database.host, this.emulators.database.port, { mockUserToken: this.authToken });
|
|
318
|
+
return database;
|
|
319
|
+
}
|
|
320
|
+
storage(bucketUrl = `gs://${this.projectId}`) {
|
|
321
|
+
assertEmulatorRunning(this.emulators, 'storage');
|
|
322
|
+
const storage = this.getApp().storage(bucketUrl);
|
|
323
|
+
storage.useEmulator(this.emulators.storage.host, this.emulators.storage.port, { mockUserToken: this.authToken });
|
|
324
|
+
return storage;
|
|
325
|
+
}
|
|
326
|
+
getApp() {
|
|
327
|
+
if (this.envDestroyed) {
|
|
328
|
+
throw new Error('This RulesTestContext is no longer valid because its RulesTestEnvironment has been ' +
|
|
329
|
+
'cleaned up. (This may indicate a leak or missing `await` in your test cases.)');
|
|
330
|
+
}
|
|
331
|
+
if (this.destroyed) {
|
|
332
|
+
throw new Error('This RulesTestContext is no longer valid. When using withSecurityRulesDisabled, ' +
|
|
333
|
+
'make sure to perform all operations on the context within the callback function and ' +
|
|
334
|
+
'return a Promise that resolves when the operations are done.');
|
|
335
|
+
}
|
|
336
|
+
if (!this.app) {
|
|
337
|
+
this.app = firebase.initializeApp({ projectId: this.projectId }, `_Firebase_RulesUnitTesting_${Date.now()}_${Math.random()}`);
|
|
338
|
+
}
|
|
339
|
+
return this.app;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
function assertEmulatorRunning(emulators, emulator) {
|
|
343
|
+
if (!emulators[emulator]) {
|
|
344
|
+
if (emulators.hub) {
|
|
345
|
+
throw new Error(`The ${emulator} emulator is not running (according to Emulator hub). To force ` +
|
|
346
|
+
'connecting anyway, please specify its host and port in initializeTestEnvironment({...}).');
|
|
347
|
+
}
|
|
348
|
+
else {
|
|
349
|
+
throw new Error(`The host and port of the ${emulator} emulator must be specified. (You may wrap the test ` +
|
|
350
|
+
"script with `firebase emulators:exec './your-test-script'` to enable automatic " +
|
|
351
|
+
`discovery, or specify manually via initializeTestEnvironment({${emulator}: {host, port}}).`);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
354
|
}
|
|
355
355
|
|
|
356
|
-
/**
|
|
357
|
-
* @license
|
|
358
|
-
* Copyright 2021 Google LLC
|
|
359
|
-
*
|
|
360
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
361
|
-
* you may not use this file except in compliance with the License.
|
|
362
|
-
* You may obtain a copy of the License at
|
|
363
|
-
*
|
|
364
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
365
|
-
*
|
|
366
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
367
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
368
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
369
|
-
* See the License for the specific language governing permissions and
|
|
370
|
-
* limitations under the License.
|
|
371
|
-
*/
|
|
372
|
-
/**
|
|
373
|
-
* @private
|
|
374
|
-
*/
|
|
375
|
-
async function loadDatabaseRules(hostAndPort, databaseName, rules) {
|
|
376
|
-
const url = makeUrl(hostAndPort, '/.settings/rules.json');
|
|
377
|
-
url.searchParams.append('ns', databaseName);
|
|
378
|
-
const resp = await fetch(url, {
|
|
379
|
-
method: 'PUT',
|
|
380
|
-
headers: { Authorization: 'Bearer owner' },
|
|
381
|
-
body: rules
|
|
382
|
-
});
|
|
383
|
-
if (!resp.ok) {
|
|
384
|
-
throw new Error(await resp.text());
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
/**
|
|
388
|
-
* @private
|
|
389
|
-
*/
|
|
390
|
-
async function loadFirestoreRules(hostAndPort, projectId, rules) {
|
|
391
|
-
const resp = await fetch(makeUrl(hostAndPort, `/emulator/v1/projects/${projectId}:securityRules`), {
|
|
392
|
-
method: 'PUT',
|
|
393
|
-
body: JSON.stringify({
|
|
394
|
-
rules: {
|
|
395
|
-
files: [{ content: rules }]
|
|
396
|
-
}
|
|
397
|
-
})
|
|
398
|
-
});
|
|
399
|
-
if (!resp.ok) {
|
|
400
|
-
throw new Error(await resp.text());
|
|
401
|
-
}
|
|
402
|
-
}
|
|
403
|
-
/**
|
|
404
|
-
* @private
|
|
405
|
-
*/
|
|
406
|
-
async function loadStorageRules(hostAndPort, rules) {
|
|
407
|
-
const resp = await fetch(makeUrl(hostAndPort, '/internal/setRules'), {
|
|
408
|
-
method: 'PUT',
|
|
409
|
-
headers: {
|
|
410
|
-
'Content-Type': 'application/json'
|
|
411
|
-
},
|
|
412
|
-
body: JSON.stringify({
|
|
413
|
-
rules: {
|
|
414
|
-
files: [{ name: 'storage.rules', content: rules }]
|
|
415
|
-
}
|
|
416
|
-
})
|
|
417
|
-
});
|
|
418
|
-
if (!resp.ok) {
|
|
419
|
-
throw new Error(await resp.text());
|
|
420
|
-
}
|
|
356
|
+
/**
|
|
357
|
+
* @license
|
|
358
|
+
* Copyright 2021 Google LLC
|
|
359
|
+
*
|
|
360
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
361
|
+
* you may not use this file except in compliance with the License.
|
|
362
|
+
* You may obtain a copy of the License at
|
|
363
|
+
*
|
|
364
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
365
|
+
*
|
|
366
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
367
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
368
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
369
|
+
* See the License for the specific language governing permissions and
|
|
370
|
+
* limitations under the License.
|
|
371
|
+
*/
|
|
372
|
+
/**
|
|
373
|
+
* @private
|
|
374
|
+
*/
|
|
375
|
+
async function loadDatabaseRules(hostAndPort, databaseName, rules) {
|
|
376
|
+
const url = makeUrl(hostAndPort, '/.settings/rules.json');
|
|
377
|
+
url.searchParams.append('ns', databaseName);
|
|
378
|
+
const resp = await fetch(url, {
|
|
379
|
+
method: 'PUT',
|
|
380
|
+
headers: { Authorization: 'Bearer owner' },
|
|
381
|
+
body: rules
|
|
382
|
+
});
|
|
383
|
+
if (!resp.ok) {
|
|
384
|
+
throw new Error(await resp.text());
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* @private
|
|
389
|
+
*/
|
|
390
|
+
async function loadFirestoreRules(hostAndPort, projectId, rules) {
|
|
391
|
+
const resp = await fetch(makeUrl(hostAndPort, `/emulator/v1/projects/${projectId}:securityRules`), {
|
|
392
|
+
method: 'PUT',
|
|
393
|
+
body: JSON.stringify({
|
|
394
|
+
rules: {
|
|
395
|
+
files: [{ content: rules }]
|
|
396
|
+
}
|
|
397
|
+
})
|
|
398
|
+
});
|
|
399
|
+
if (!resp.ok) {
|
|
400
|
+
throw new Error(await resp.text());
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* @private
|
|
405
|
+
*/
|
|
406
|
+
async function loadStorageRules(hostAndPort, rules) {
|
|
407
|
+
const resp = await fetch(makeUrl(hostAndPort, '/internal/setRules'), {
|
|
408
|
+
method: 'PUT',
|
|
409
|
+
headers: {
|
|
410
|
+
'Content-Type': 'application/json'
|
|
411
|
+
},
|
|
412
|
+
body: JSON.stringify({
|
|
413
|
+
rules: {
|
|
414
|
+
files: [{ name: 'storage.rules', content: rules }]
|
|
415
|
+
}
|
|
416
|
+
})
|
|
417
|
+
});
|
|
418
|
+
if (!resp.ok) {
|
|
419
|
+
throw new Error(await resp.text());
|
|
420
|
+
}
|
|
421
421
|
}
|
|
422
422
|
|
|
423
|
-
/**
|
|
424
|
-
* @license
|
|
425
|
-
* Copyright 2021 Google LLC
|
|
426
|
-
*
|
|
427
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
428
|
-
* you may not use this file except in compliance with the License.
|
|
429
|
-
* You may obtain a copy of the License at
|
|
430
|
-
*
|
|
431
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
432
|
-
*
|
|
433
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
434
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
435
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
436
|
-
* See the License for the specific language governing permissions and
|
|
437
|
-
* limitations under the License.
|
|
438
|
-
*/
|
|
439
|
-
/**
|
|
440
|
-
* Initializes a test environment for rules unit testing. Call this function first for test setup.
|
|
441
|
-
*
|
|
442
|
-
* Requires emulators to be running. This function tries to discover those emulators via environment
|
|
443
|
-
* variables or through the Firebase Emulator hub if hosts and ports are unspecified. It is strongly
|
|
444
|
-
* recommended to specify security rules for emulators used for testing. See minimal example below.
|
|
445
|
-
*
|
|
446
|
-
* @param config - the configuration for emulators. Most fields are optional if they can be discovered
|
|
447
|
-
* @returns a promise that resolves with an environment ready for testing, or rejects on error.
|
|
448
|
-
* @public
|
|
449
|
-
* @example
|
|
450
|
-
* ```javascript
|
|
451
|
-
* const testEnv = await initializeTestEnvironment({
|
|
452
|
-
* firestore: {
|
|
453
|
-
* rules: fs.readFileSync("/path/to/firestore.rules", "utf8"), // Load rules from file
|
|
454
|
-
* // host and port can be omitted if they can be discovered from the hub.
|
|
455
|
-
* },
|
|
456
|
-
* // ...
|
|
457
|
-
* });
|
|
458
|
-
* ```
|
|
459
|
-
*/
|
|
460
|
-
async function initializeTestEnvironment(config) {
|
|
461
|
-
var _a, _b, _c;
|
|
462
|
-
const projectId = config.projectId || process.env.GCLOUD_PROJECT;
|
|
463
|
-
if (!projectId) {
|
|
464
|
-
throw new Error('Missing projectId option or env var GCLOUD_PROJECT! Please specify the projectId either ' +
|
|
465
|
-
'way.\n(A demo-* projectId is strongly recommended for unit tests, such as "demo-test".)');
|
|
466
|
-
}
|
|
467
|
-
const hub = getEmulatorHostAndPort('hub', config.hub);
|
|
468
|
-
let discovered = hub ? Object.assign(Object.assign({}, (await discoverEmulators(hub))), { hub }) : undefined;
|
|
469
|
-
const emulators = {};
|
|
470
|
-
if (hub) {
|
|
471
|
-
emulators.hub = hub;
|
|
472
|
-
}
|
|
473
|
-
for (const emulator of SUPPORTED_EMULATORS) {
|
|
474
|
-
const hostAndPort = getEmulatorHostAndPort(emulator, config[emulator], discovered);
|
|
475
|
-
if (hostAndPort) {
|
|
476
|
-
emulators[emulator] = hostAndPort;
|
|
477
|
-
}
|
|
478
|
-
}
|
|
479
|
-
if ((_a = config.database) === null || _a === void 0 ? void 0 : _a.rules) {
|
|
480
|
-
assertEmulatorRunning(emulators, 'database');
|
|
481
|
-
await loadDatabaseRules(emulators.database, projectId, config.database.rules);
|
|
482
|
-
}
|
|
483
|
-
if ((_b = config.firestore) === null || _b === void 0 ? void 0 : _b.rules) {
|
|
484
|
-
assertEmulatorRunning(emulators, 'firestore');
|
|
485
|
-
await loadFirestoreRules(emulators.firestore, projectId, config.firestore.rules);
|
|
486
|
-
}
|
|
487
|
-
if ((_c = config.storage) === null || _c === void 0 ? void 0 : _c.rules) {
|
|
488
|
-
assertEmulatorRunning(emulators, 'storage');
|
|
489
|
-
await loadStorageRules(emulators.storage, config.storage.rules);
|
|
490
|
-
}
|
|
491
|
-
return new RulesTestEnvironmentImpl(projectId, emulators);
|
|
492
|
-
}
|
|
423
|
+
/**
|
|
424
|
+
* @license
|
|
425
|
+
* Copyright 2021 Google LLC
|
|
426
|
+
*
|
|
427
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
428
|
+
* you may not use this file except in compliance with the License.
|
|
429
|
+
* You may obtain a copy of the License at
|
|
430
|
+
*
|
|
431
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
432
|
+
*
|
|
433
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
434
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
435
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
436
|
+
* See the License for the specific language governing permissions and
|
|
437
|
+
* limitations under the License.
|
|
438
|
+
*/
|
|
439
|
+
/**
|
|
440
|
+
* Initializes a test environment for rules unit testing. Call this function first for test setup.
|
|
441
|
+
*
|
|
442
|
+
* Requires emulators to be running. This function tries to discover those emulators via environment
|
|
443
|
+
* variables or through the Firebase Emulator hub if hosts and ports are unspecified. It is strongly
|
|
444
|
+
* recommended to specify security rules for emulators used for testing. See minimal example below.
|
|
445
|
+
*
|
|
446
|
+
* @param config - the configuration for emulators. Most fields are optional if they can be discovered
|
|
447
|
+
* @returns a promise that resolves with an environment ready for testing, or rejects on error.
|
|
448
|
+
* @public
|
|
449
|
+
* @example
|
|
450
|
+
* ```javascript
|
|
451
|
+
* const testEnv = await initializeTestEnvironment({
|
|
452
|
+
* firestore: {
|
|
453
|
+
* rules: fs.readFileSync("/path/to/firestore.rules", "utf8"), // Load rules from file
|
|
454
|
+
* // host and port can be omitted if they can be discovered from the hub.
|
|
455
|
+
* },
|
|
456
|
+
* // ...
|
|
457
|
+
* });
|
|
458
|
+
* ```
|
|
459
|
+
*/
|
|
460
|
+
async function initializeTestEnvironment(config) {
|
|
461
|
+
var _a, _b, _c;
|
|
462
|
+
const projectId = config.projectId || process.env.GCLOUD_PROJECT;
|
|
463
|
+
if (!projectId) {
|
|
464
|
+
throw new Error('Missing projectId option or env var GCLOUD_PROJECT! Please specify the projectId either ' +
|
|
465
|
+
'way.\n(A demo-* projectId is strongly recommended for unit tests, such as "demo-test".)');
|
|
466
|
+
}
|
|
467
|
+
const hub = getEmulatorHostAndPort('hub', config.hub);
|
|
468
|
+
let discovered = hub ? Object.assign(Object.assign({}, (await discoverEmulators(hub))), { hub }) : undefined;
|
|
469
|
+
const emulators = {};
|
|
470
|
+
if (hub) {
|
|
471
|
+
emulators.hub = hub;
|
|
472
|
+
}
|
|
473
|
+
for (const emulator of SUPPORTED_EMULATORS) {
|
|
474
|
+
const hostAndPort = getEmulatorHostAndPort(emulator, config[emulator], discovered);
|
|
475
|
+
if (hostAndPort) {
|
|
476
|
+
emulators[emulator] = hostAndPort;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
if ((_a = config.database) === null || _a === void 0 ? void 0 : _a.rules) {
|
|
480
|
+
assertEmulatorRunning(emulators, 'database');
|
|
481
|
+
await loadDatabaseRules(emulators.database, projectId, config.database.rules);
|
|
482
|
+
}
|
|
483
|
+
if ((_b = config.firestore) === null || _b === void 0 ? void 0 : _b.rules) {
|
|
484
|
+
assertEmulatorRunning(emulators, 'firestore');
|
|
485
|
+
await loadFirestoreRules(emulators.firestore, projectId, config.firestore.rules);
|
|
486
|
+
}
|
|
487
|
+
if ((_c = config.storage) === null || _c === void 0 ? void 0 : _c.rules) {
|
|
488
|
+
assertEmulatorRunning(emulators, 'storage');
|
|
489
|
+
await loadStorageRules(emulators.storage, config.storage.rules);
|
|
490
|
+
}
|
|
491
|
+
return new RulesTestEnvironmentImpl(projectId, emulators);
|
|
492
|
+
}
|
|
493
493
|
const SUPPORTED_EMULATORS = ['database', 'firestore', 'storage'];
|
|
494
494
|
|
|
495
|
-
/**
|
|
496
|
-
* @license
|
|
497
|
-
* Copyright 2021 Google LLC
|
|
498
|
-
*
|
|
499
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
500
|
-
* you may not use this file except in compliance with the License.
|
|
501
|
-
* You may obtain a copy of the License at
|
|
502
|
-
*
|
|
503
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
504
|
-
*
|
|
505
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
506
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
507
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
508
|
-
* See the License for the specific language governing permissions and
|
|
509
|
-
* limitations under the License.
|
|
510
|
-
*/
|
|
511
|
-
async function withFunctionTriggersDisabled(fnOrHub, maybeFn) {
|
|
512
|
-
let hub;
|
|
513
|
-
if (typeof fnOrHub === 'function') {
|
|
514
|
-
maybeFn = fnOrHub;
|
|
515
|
-
hub = getEmulatorHostAndPort('hub');
|
|
516
|
-
}
|
|
517
|
-
else {
|
|
518
|
-
hub = getEmulatorHostAndPort('hub', fnOrHub);
|
|
519
|
-
if (!maybeFn) {
|
|
520
|
-
throw new Error('The callback function must be specified!');
|
|
521
|
-
}
|
|
522
|
-
}
|
|
523
|
-
if (!hub) {
|
|
524
|
-
throw new Error('Please specify the Emulator Hub host and port via arguments or set the environment ' +
|
|
525
|
-
`variable ${EMULATOR_HOST_ENV_VARS.hub}!`);
|
|
526
|
-
}
|
|
527
|
-
hub.host = fixHostname(hub.host);
|
|
528
|
-
makeUrl(hub, '/functions/disableBackgroundTriggers');
|
|
529
|
-
// Disable background triggers
|
|
530
|
-
const disableRes = await fetch(makeUrl(hub, '/functions/disableBackgroundTriggers'), {
|
|
531
|
-
method: 'PUT'
|
|
532
|
-
});
|
|
533
|
-
if (!disableRes.ok) {
|
|
534
|
-
throw new Error(`HTTP Error ${disableRes.status} when disabling functions triggers, are you using firebase-tools 8.13.0 or higher?`);
|
|
535
|
-
}
|
|
536
|
-
// Run the user's function
|
|
537
|
-
let result = undefined;
|
|
538
|
-
try {
|
|
539
|
-
result = await maybeFn();
|
|
540
|
-
}
|
|
541
|
-
finally {
|
|
542
|
-
// Re-enable background triggers
|
|
543
|
-
const enableRes = await fetch(makeUrl(hub, '/functions/enableBackgroundTriggers'), {
|
|
544
|
-
method: 'PUT'
|
|
545
|
-
});
|
|
546
|
-
if (!enableRes.ok) {
|
|
547
|
-
throw new Error(`HTTP Error ${enableRes.status} when enabling functions triggers, are you using firebase-tools 8.13.0 or higher?`);
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
// Return the user's function result
|
|
551
|
-
return result;
|
|
552
|
-
}
|
|
553
|
-
/**
|
|
554
|
-
* Assert the promise to be rejected with a "permission denied" error.
|
|
555
|
-
*
|
|
556
|
-
* Useful to assert a certain request to be denied by Security Rules. See example below.
|
|
557
|
-
* This function recognizes permission-denied errors from Database, Firestore, and Storage JS SDKs.
|
|
558
|
-
*
|
|
559
|
-
* @param pr - the promise to be asserted
|
|
560
|
-
* @returns a Promise that is fulfilled if pr is rejected with "permission denied". If pr is
|
|
561
|
-
* rejected with any other error or resolved, the returned promise rejects.
|
|
562
|
-
* @public
|
|
563
|
-
* @example
|
|
564
|
-
* ```javascript
|
|
565
|
-
* const unauthed = testEnv.unauthenticatedContext();
|
|
566
|
-
* await assertFails(get(doc(unauthed.firestore(), '/private/doc'), { ... });
|
|
567
|
-
* ```
|
|
568
|
-
*/
|
|
569
|
-
function assertFails(pr) {
|
|
570
|
-
return pr.then(() => {
|
|
571
|
-
return Promise.reject(new Error('Expected request to fail, but it succeeded.'));
|
|
572
|
-
}, (err) => {
|
|
573
|
-
var _a, _b;
|
|
574
|
-
const errCode = ((_a = err === null || err === void 0 ? void 0 : err.code) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || '';
|
|
575
|
-
const errMessage = ((_b = err === null || err === void 0 ? void 0 : err.message) === null || _b === void 0 ? void 0 : _b.toLowerCase()) || '';
|
|
576
|
-
const isPermissionDenied = errCode === 'permission-denied' ||
|
|
577
|
-
errCode === 'permission_denied' ||
|
|
578
|
-
errMessage.indexOf('permission_denied') >= 0 ||
|
|
579
|
-
errMessage.indexOf('permission denied') >= 0 ||
|
|
580
|
-
// Storage permission errors contain message: (storage/unauthorized)
|
|
581
|
-
errMessage.indexOf('unauthorized') >= 0;
|
|
582
|
-
if (!isPermissionDenied) {
|
|
583
|
-
return Promise.reject(new Error(`Expected PERMISSION_DENIED but got unexpected error: ${err}`));
|
|
584
|
-
}
|
|
585
|
-
return err;
|
|
586
|
-
});
|
|
587
|
-
}
|
|
588
|
-
/**
|
|
589
|
-
* Assert the promise to be successful.
|
|
590
|
-
*
|
|
591
|
-
* This is a no-op function returning the passed promise as-is, but can be used for documentational
|
|
592
|
-
* purposes in test code to emphasize that a certain request should succeed (e.g. allowed by rules).
|
|
593
|
-
*
|
|
594
|
-
* @public
|
|
595
|
-
* @example
|
|
596
|
-
* ```javascript
|
|
597
|
-
* const alice = testEnv.authenticatedContext('alice');
|
|
598
|
-
* await assertSucceeds(get(doc(alice.firestore(), '/doc/readable/by/alice'), { ... });
|
|
599
|
-
* ```
|
|
600
|
-
*/
|
|
601
|
-
function assertSucceeds(pr) {
|
|
602
|
-
return pr;
|
|
495
|
+
/**
|
|
496
|
+
* @license
|
|
497
|
+
* Copyright 2021 Google LLC
|
|
498
|
+
*
|
|
499
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
500
|
+
* you may not use this file except in compliance with the License.
|
|
501
|
+
* You may obtain a copy of the License at
|
|
502
|
+
*
|
|
503
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
504
|
+
*
|
|
505
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
506
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
507
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
508
|
+
* See the License for the specific language governing permissions and
|
|
509
|
+
* limitations under the License.
|
|
510
|
+
*/
|
|
511
|
+
async function withFunctionTriggersDisabled(fnOrHub, maybeFn) {
|
|
512
|
+
let hub;
|
|
513
|
+
if (typeof fnOrHub === 'function') {
|
|
514
|
+
maybeFn = fnOrHub;
|
|
515
|
+
hub = getEmulatorHostAndPort('hub');
|
|
516
|
+
}
|
|
517
|
+
else {
|
|
518
|
+
hub = getEmulatorHostAndPort('hub', fnOrHub);
|
|
519
|
+
if (!maybeFn) {
|
|
520
|
+
throw new Error('The callback function must be specified!');
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
if (!hub) {
|
|
524
|
+
throw new Error('Please specify the Emulator Hub host and port via arguments or set the environment ' +
|
|
525
|
+
`variable ${EMULATOR_HOST_ENV_VARS.hub}!`);
|
|
526
|
+
}
|
|
527
|
+
hub.host = fixHostname(hub.host);
|
|
528
|
+
makeUrl(hub, '/functions/disableBackgroundTriggers');
|
|
529
|
+
// Disable background triggers
|
|
530
|
+
const disableRes = await fetch(makeUrl(hub, '/functions/disableBackgroundTriggers'), {
|
|
531
|
+
method: 'PUT'
|
|
532
|
+
});
|
|
533
|
+
if (!disableRes.ok) {
|
|
534
|
+
throw new Error(`HTTP Error ${disableRes.status} when disabling functions triggers, are you using firebase-tools 8.13.0 or higher?`);
|
|
535
|
+
}
|
|
536
|
+
// Run the user's function
|
|
537
|
+
let result = undefined;
|
|
538
|
+
try {
|
|
539
|
+
result = await maybeFn();
|
|
540
|
+
}
|
|
541
|
+
finally {
|
|
542
|
+
// Re-enable background triggers
|
|
543
|
+
const enableRes = await fetch(makeUrl(hub, '/functions/enableBackgroundTriggers'), {
|
|
544
|
+
method: 'PUT'
|
|
545
|
+
});
|
|
546
|
+
if (!enableRes.ok) {
|
|
547
|
+
throw new Error(`HTTP Error ${enableRes.status} when enabling functions triggers, are you using firebase-tools 8.13.0 or higher?`);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
// Return the user's function result
|
|
551
|
+
return result;
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* Assert the promise to be rejected with a "permission denied" error.
|
|
555
|
+
*
|
|
556
|
+
* Useful to assert a certain request to be denied by Security Rules. See example below.
|
|
557
|
+
* This function recognizes permission-denied errors from Database, Firestore, and Storage JS SDKs.
|
|
558
|
+
*
|
|
559
|
+
* @param pr - the promise to be asserted
|
|
560
|
+
* @returns a Promise that is fulfilled if pr is rejected with "permission denied". If pr is
|
|
561
|
+
* rejected with any other error or resolved, the returned promise rejects.
|
|
562
|
+
* @public
|
|
563
|
+
* @example
|
|
564
|
+
* ```javascript
|
|
565
|
+
* const unauthed = testEnv.unauthenticatedContext();
|
|
566
|
+
* await assertFails(get(doc(unauthed.firestore(), '/private/doc'), { ... });
|
|
567
|
+
* ```
|
|
568
|
+
*/
|
|
569
|
+
function assertFails(pr) {
|
|
570
|
+
return pr.then(() => {
|
|
571
|
+
return Promise.reject(new Error('Expected request to fail, but it succeeded.'));
|
|
572
|
+
}, (err) => {
|
|
573
|
+
var _a, _b;
|
|
574
|
+
const errCode = ((_a = err === null || err === void 0 ? void 0 : err.code) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || '';
|
|
575
|
+
const errMessage = ((_b = err === null || err === void 0 ? void 0 : err.message) === null || _b === void 0 ? void 0 : _b.toLowerCase()) || '';
|
|
576
|
+
const isPermissionDenied = errCode === 'permission-denied' ||
|
|
577
|
+
errCode === 'permission_denied' ||
|
|
578
|
+
errMessage.indexOf('permission_denied') >= 0 ||
|
|
579
|
+
errMessage.indexOf('permission denied') >= 0 ||
|
|
580
|
+
// Storage permission errors contain message: (storage/unauthorized)
|
|
581
|
+
errMessage.indexOf('unauthorized') >= 0;
|
|
582
|
+
if (!isPermissionDenied) {
|
|
583
|
+
return Promise.reject(new Error(`Expected PERMISSION_DENIED but got unexpected error: ${err}`));
|
|
584
|
+
}
|
|
585
|
+
return err;
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
/**
|
|
589
|
+
* Assert the promise to be successful.
|
|
590
|
+
*
|
|
591
|
+
* This is a no-op function returning the passed promise as-is, but can be used for documentational
|
|
592
|
+
* purposes in test code to emphasize that a certain request should succeed (e.g. allowed by rules).
|
|
593
|
+
*
|
|
594
|
+
* @public
|
|
595
|
+
* @example
|
|
596
|
+
* ```javascript
|
|
597
|
+
* const alice = testEnv.authenticatedContext('alice');
|
|
598
|
+
* await assertSucceeds(get(doc(alice.firestore(), '/doc/readable/by/alice'), { ... });
|
|
599
|
+
* ```
|
|
600
|
+
*/
|
|
601
|
+
function assertSucceeds(pr) {
|
|
602
|
+
return pr;
|
|
603
603
|
}
|
|
604
604
|
|
|
605
605
|
export { assertFails, assertSucceeds, initializeTestEnvironment, withFunctionTriggersDisabled };
|