forked from firebase/functions-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwipeout.js
340 lines (309 loc) · 10.4 KB
/
wipeout.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/**
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const deepcopy = require('deepcopy');
const jsep = require('jsep');
const request = require('request-promise');
const sjc = require('strip-json-comments');
const WIPEOUT_UID = '#WIPEOUT_UID';
const WRITE_SIGN = '.write';
const PATH_REGEX = /^\/?$|(^(?=\/))(\/(?=[^/\0])[^/\0]+)*\/?$/;
const BOOK_KEEPING_PATH = '/wipeout';
const exp = require('./expression.js');
const Expression = exp.Expression;
const Access = require('./access.js');
/**
* Initialize the wipeout library.
* @param {object} wipeoutConfig contains the fields:
* 'admin' module returned by require('firebase-admin')
* 'functions' module returned by require('firebase-functions')
* 'DB_URL' the URL of the project's Firebase Realtime Database
* 'WIPEOUT_UID' typically '$WIPEOUT_UID'; change in case of conflict
* 'WRITE_SIGN': should be '.write',
* 'PATH_REGEX': should be /^\/?$|(^(?=\/))(\/(?=[^/\0])[^/\0]+)*\/?$/
*/
exports.initialize = wipeoutConfig => {
global.init = Object.freeze(wipeoutConfig);
return init.db.ref(`${BOOK_KEEPING_PATH}/confirm`).set(false);
};
// Get wipeout configuration from wipeout_config.json,
// or else try to infer from RTDB rules.
const getConfig = () => {
try {
const config = require('./wipeout_config.json').wipeout;
return Promise.resolve(config);
} catch (err) {
console.log(`Failed to read local configuration.
Trying to infer from Realtime Database Security Rules...
(If you intended to use local configuration,
make sure there's a 'wipeout_config.json' file in the
functions directory with a 'wipeout' field.`, err);
return readDBRules().then(DBRules => {
const config = extractFromDBRules(DBRules);
console.log('Using wipeout rules inferred from RTDB rules.');
return Promise.resolve(config);
}).catch(errDB => {
console.error(
'Could not generate wipeout config from RTDB rules.' +
'Failed to read database', errDB);
return Promise.reject(err);
});
}
};
// buid deletion paths from wipeout config
const buildPath = (config, uid) => {
const paths = deepcopy(config);
for (let i = 0, len = config.length; i < len; i++) {
if (!PATH_REGEX.test(config[i].path)) {
return Promise.reject('Invalid wipeout Path: ' + config[i].path);
}
paths[i].path = config[i].path.replace(WIPEOUT_UID, uid.toString());
}
return Promise.resolve(paths);
};
// Read database security rules using REST API.
const readDBRules = () => {
return init.credential.getAccessToken()
.then(snapshot => {
return snapshot.access_token;
})
.then(token => {
const rulesURL = `${init.DB_URL}/.settings/rules.json?` +
`access_token=${token}`;
return request(rulesURL);
})
.catch(err => {
console.error(err, 'Failed to read RTDB rule.');
return Promise.reject(err);
});
};
// extract wipeout rules from RTDB rules.
const extractFromDBRules = DBRules => {
const rules = JSON.parse(sjc(DBRules));
const inferredRules = inferWipeoutRule(rules);
return inferredRules;
};
// BFS traverse of RTDB rules, check all the .write rules
// for potential user data path.
const inferWipeoutRule = tree => {
const queue = [];
const retRules = [];
const initial = {
node: tree,
path: [],
ancestorAccess: new Access(exp.NO_ACCESS, [])
};
queue.push(initial);
while (queue.length > 0) {
const obj = queue.shift();
const node = obj.node;
const path = obj.path;
let ancestor = obj.ancestorAccess;
if (typeof node === 'object') {
const keys = Object.keys(node);
if (keys.includes(WRITE_SIGN)) {
// access status of the write rule
const ruleAccess = checkWriteRules(path, node[WRITE_SIGN]);
// access status of the node, considering ancestor.
const nodeAccess = Access.nodeAccess(ancestor, ruleAccess);
if (nodeAccess.getAccessStatus() === exp.MULT_ACCESS) {
if (ancestor.getAccessStatus() === exp.SINGLE_ACCESS) {
retRules.push(
{'except': nodeAccess.getAccessPattern(path, WIPEOUT_UID)});
}
continue; // won't go into subtree of MULT_ACCESS nodes
} else if (nodeAccess.getAccessStatus() === exp.SINGLE_ACCESS) {
if (ancestor.getAccessStatus() === exp.NO_ACCESS) {
retRules.push(
{'path': nodeAccess.getAccessPattern(path, WIPEOUT_UID)});
}
}
//update ancestor for children
ancestor = nodeAccess;
}
for (let i = 0, len = keys.length; i < len; i++) {
const newPath = path.slice();
newPath.push(keys[i]);
const newObj = {
node: node[keys[i]],
path: newPath,
ancestorAccess: ancestor
};
queue.push(newObj);
}
}
}
return retRules;
};
// check memeber expression of candidate auth.id
const checkMember = obj =>
obj.type === 'MemberExpression' && obj.object.name === 'auth' &&
obj.property.name === 'uid';
// get the DNF expression asscociated with auth.uid
const getExpression = obj => {
if (obj.type === 'Literal') {
return obj.raw === 'true' ?
new Expression(exp.TRUE,[]) : new Expression(exp.FALSE,[]);
}
if (obj.type === 'Identifier') {
return obj.name[0] === '$' ?
new Expression(exp.UNDEFINED, [[obj.name]]) :
new Expression(exp.FALSE,[]);
}
return new Expression(exp.TRUE,[]);// may contain data references.
};
// check binary expressions for candidate auth.uid == ?
function checkBinary(obj) {
if (obj.type === 'BinaryExpression' &&
(obj.operator === '==' || obj.operator === '===')) {
if (checkMember(obj.left)) {
return getExpression(obj.right);
}
if (checkMember(obj.right)) {
return getExpression(obj.left);
}
}
return new Expression(exp.TRUE,[]);
}
// check true or false literals
function checkLiteral(obj) {
if (obj.type === 'Literal') {
if (obj.raw === 'true') {
return new Expression(exp.TRUE,[]);
}
if (obj.raw === 'false') {
return new Expression(exp.FALSE,[]);
}
throw 'Literals else than true or false are not supported';
}
}
// check (nested) logic expressions
function checkLogic(obj) {
if (obj.type === 'BinaryExpression') {
return checkBinary(obj);// also check unary literals
}
if (obj.type === 'Literal') {
return checkLiteral(obj);
}
if (obj.type === 'LogicalExpression') {
const left = checkLogic(obj.left);
const right = checkLogic(obj.right);
if (obj.operator === '||') {
return Expression.or(left, right);
}
if (obj.operator === '&&') {
return Expression.and(left, right);
}
} else {
return new Expression(exp.TRUE, []);
}
}
// check if the write rule indicates only the specific user has write
// access to the path. If so, the path contains user data.
function checkWriteRules(currentPath, rule) {
let ruleTree;
try {
ruleTree = jsep(rule);
} catch (err) {
// ignore write rules which couldn't be parased by jsep/.
return new Access(exp.MULT_ACCESS);
}
return Access.fromExpression(checkLogic(ruleTree), currentPath);
}
/**
* Deletes data in the Realtime Datastore when the accounts are deleted.
*
* @param deletePaths list of path objects.
*/
const deleteUser = deletePaths => {
const deleteTasks = [];
for (let i = 0; i < deletePaths.length; i++) {
deleteTasks.push(init.db.ref(deletePaths[i].path).remove());
}
return Promise.all(deleteTasks);
};
/**
* Write log into RTDB with displayName.
*
* @param data Deleted User.
* TODO(dzdz): check for current wipeout path
*/
const writeLog = data => {
return init.db.ref(`${BOOK_KEEPING_PATH}/history/${data.uid}`)
.set(init.serverValue.TIMESTAMP);
};
/**
* Deletes data in the Realtime Datastore when the accounts are deleted.
* Log into RTDB after successful deletion.
*
*/
exports.cleanupUserData = () => {
return init.users.onDelete(event => {
const configPromise = init.db
.ref(`${BOOK_KEEPING_PATH}/rules`).once('value');
const confirmPromise = init.db
.ref(`${BOOK_KEEPING_PATH}/confirm`).once('value');
return Promise.all([configPromise, confirmPromise])
.then((snapshots) => {
const config = snapshots[0].val();
const confirm = snapshots[1].val();
if (!snapshots[0].exists() || !confirm) {
return Promise.reject('No config or not confirmed by developers. ' +
'No data deleted at user deletion.');
} else {
return Promise.resolve(config);
}
})
.then(config => buildPath(config, event.data.uid))
.then(deletePaths => deleteUser(deletePaths))
.then(() => writeLog(event.data));
});
};
/**
* Give developers the ability to see the wipeout rules through a URL
*
*/
exports.showWipeoutConfig = () => {
return init.https.onRequest((req, res) => {
if (req.method === 'GET') {
return getConfig().then(config => {
return init.db.ref(`${BOOK_KEEPING_PATH}/rules`)
.set(config).then(() => {
const content = `Please verify the wipeout rules. <br>
If correct, click the 'Confirm' button below. <br>
If incorrect, please modify functions/wipeout_config.json
and deploy again. <br> <br> ${JSON.stringify(config)}
<form action='#' method='post'>
<input type='submit' value='Confirm' name ='confirm'></form>`;
res.send(content);
});
});
} else if ((req.method === 'POST') && req.body.confirm === 'Confirm') {
return init.db.ref(`${BOOK_KEEPING_PATH}/confirm`).set(true)
.then(() => res.send('Confirm sent, Wipeout function activated.'));
}
});
};
// only expose internel functions to tests.
if (process.env.NODE_ENV === 'TEST') {
module.exports.buildPath = buildPath;
module.exports.checkWriteRules = checkWriteRules;
module.exports.extractFromDBRules = extractFromDBRules;
module.exports.inferWipeoutRule = inferWipeoutRule;
module.exports.readDBRules = readDBRules;
module.exports.deleteUser = deleteUser;
module.exports.writeLog = writeLog;
}