-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathfirestore.rules
356 lines (304 loc) · 11.6 KB
/
firestore.rules
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
// This file is auto-formatted by the VS Code ChFlick.firecode extension
// Name: Firestore Rules
// Id: ChFlick.firecode
// Description: Firestore Security Rules Syntax Highlighting and Suggestions
// VS Marketplace Link: https://marketplace.visualstudio.com/items?itemName=ChFlick.firecode
// Helpful docs on data type validation with `is`
// - https://stackoverflow.com/a/58034743/4973029
// - https://youtu.be/qbd_4LT0Y4s?t=652
// Can't find this in the official docs so far!
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Generic functions
function isOwner(userId) {
return request.auth.uid == userId
}
function isVerified() {
return request.auth.token.email_verified;
}
function isSignedIn() {
return request.auth != null;
}
function isAdmin() {
return request.auth.token.admin;
}
function isMember() {
return get(/databases/$(database)/documents/users/$(requesterId())).data.superfan == true;
}
function requesterId() {
return request.auth.uid;
}
function existingData() {
return resource.data
}
function incomingData() {
return request.resource.data
}
function userExists(uid) {
return exists(/databases/$(database)/documents/users/$(uid))
}
function requestHas(field) {
return field in request.resource.data;
}
// General validation functions
function isNonEmptyString(str) {
return str is string &&
str.size() > 0
}
// Public user collection
function validateUserState(user) {
// See src/lib/models/Users.ts -> UserPublic
// and api/src/auth.js -> createUser
return isNonEmptyString(user.firstName) &&
isNonEmptyString(user.countryCode)
}
match /users/{userId} {
allow read;
allow update:
if isSignedIn() &&
isOwner(userId) &&
validateUserState(request.resource.data) &&
// Don't allow superfan status to be changed by clients
// Note: this also doesn't allow *creation* by clients, but that's OK, because the backend creates the doc.
!request.resource.data.diff(resource.data).affectedKeys().hasAny(['superfan'])
}
// Private user collection
function validateUserPrivateState(user) {
return isNonEmptyString(user.lastName)
&& user.consentedAt is timestamp
&& user.emailPreferences is map
&& user.emailPreferences.newChat is bool
&& user.emailPreferences.news is bool
// Don't allow sensitive indentifiers to be changed by clients
// Note: this also doesn't allow *creation* by clients, but that's OK, because the backend creates the doc.
&& !request.resource.data.diff(resource.data).affectedKeys().hasAny(['stripeCustomerId', 'stripeSubscription', 'sendgridId', 'oldEmail', 'newEmail'])
}
function validateTrailState(trail) {
return isNonEmptyString(trail.originalFileName)
&& isNonEmptyString(trail.md5Hash)
&& trail.visible is bool
}
function isValidTrailAccess(userId) {
// Only superfans (members) can access trails
return isSignedIn() && isOwner(userId) && isMember()
}
match /users-private/{userId} {
// users-private documents are always created by firebase-admin.
allow read: if isOwner(userId);
allow update:
if isSignedIn() &&
isOwner(userId) &&
validateUserPrivateState(request.resource.data)
match /trails/{trailId} {
allow read: if isValidTrailAccess(userId);
allow create: if isValidTrailAccess(userId)
&& validateTrailState(incomingData())
allow update: if isValidTrailAccess(userId)
// Only the visibility should be updateable by the user, once the trail is created.
&& incomingData().diff(existingData()).affectedKeys().hasOnly(['visible'])
&& incomingData().visible is bool;
allow delete: if isValidTrailAccess(userId);
}
match /push-registrations/{registrationId} {
allow read: if isSignedIn() && isOwner(userId);
allow write: if isSignedIn() && isOwner(userId);
}
}
// Garden functions
function validateDescription(description) {
return description is string &&
// Note: min. 20 characters is enforced by the frontend.
// However, we have 6 gardens form before the time that this was enforced,
// which have a description of min. 11 characters.
// They should still be able to change their description.
// description.size() >= 20 &&
description.size() >= 11 &&
description.size() <= 300
}
// TODO unused
function validateContactLanguages(languages) {
// TODO: verify firestore enum security rule?
// return languages in ['Dutch', 'French', 'German', 'English']
return true;
}
function validateLocation(location) {
// Note: these could be a float, but there might be some ints too
// did not check this. Hence, number is the safest.
return location.latitude is number
&& location.latitude >= -90
&& location.latitude <= 90
&& location.longitude is number
&& location.longitude >= -180
&& location.longitude <= 180
// NOTE: using `return location is latlng` would be nice, but for that
// we need to migrate all location values in to real Firebase GeoPoints
// - https://firebase.google.com/docs/reference/rules/rules.LatLng
// - https://firebase.google.com/docs/reference/js/firestore_.geopoint
}
function validateFacilities(facilities) {
return facilities.keys().hasAll([
'capacity',
'toilet',
'shower',
'electricity',
'water',
'drinkableWater',
'bonfire',
'tent'
]) &&
facilities.capacity is number &&
facilities.capacity >= 1 &&
facilities.toilet is bool &&
facilities.shower is bool &&
facilities.electricity is bool &&
facilities.water is bool &&
facilities.drinkableWater is bool &&
facilities.bonfire is bool &&
facilities.tent is bool
}
function validatePhoto(photo) {
// photo can not be undefined
return photo == null || photo is string
}
function validatePreviousPhotoId(garden) {
// Allowed values are: undefined | null | string
// previousPhotoId is undefined for 1480 gardens
// Map.get is needed to check undefined safely: https://stackoverflow.com/a/67138054/4973029
return garden.get('previousPhotoId', null) == null || garden.previousPhotoId is string
}
function validateGardenState(garden) {
return garden.keys().hasAll([
'description',
'location',
'facilities',
'photo',
'listed'
]) &&
validateFacilities(garden.facilities) &&
validateDescription(garden.description) &&
validatePhoto(garden.photo) &&
validateLocation(garden.location) &&
validatePreviousPhotoId(garden) &&
garden.listed is bool
}
// Garden collection
match /campsites/{userId} {
allow read;
allow create:
if isSignedIn() &&
validateGardenState(request.resource.data) &&
isVerified() &&
isOwner(userId)
allow update:
if isSignedIn() &&
validateGardenState(request.resource.data) &&
isVerified() &&
isOwner(userId) &&
// Don't allow garden change timestamps to be modified by clients
!incomingData().diff(existingData()).affectedKeys().hasAny(['latestRemovedAt', 'latestWarningForInactivityAt', 'latestListedChangeAt'])
allow delete:
if isSignedIn() &&
isVerified() &&
isOwner(userId)
}
// Chats
function getChatUsers(chatId) {
return get(/databases/$(database)/documents/chats/$(chatId)).data.users;
}
// Conditions for chat reads
// Note: this function will not work on *creation* operations (existingData reference)
function canReadChat() {
return isSignedIn() && isVerified() && requesterId() in existingData().users;
}
// Function that acts a global variable
function maxMessageLength() {
return 800;
}
// Conditions common to chat creations and updates
function isValidChatWrite() {
return isSignedIn() && isVerified()
&& incomingData().keys().hasAll(['users', 'lastActivity', 'createdAt', 'lastMessage'])
// A chat can only exist between exactly two users
&& incomingData().users.size() == 2
// A user can not send a message to themself
&& incomingData().users[0] != incomingData().users[1]
&& incomingData().lastActivity is timestamp
&& incomingData().lastMessage is string
&& incomingData().lastMessage.size() >= 1
&& incomingData().lastMessage.size() <= maxMessageLength()
// The following keys are optional.
// The client creates a chat before it has sent the first message in it, so these message-related properties may be empty.
// Some old chats with existing messages before these features were lauched, may also not have these keys, until someone sends a new message in the chat.
&&
(
!incomingData().keys().hasAny(['lastMessageSeen', 'lastMessageSender'])
||
(
incomingData().keys().hasAll(['lastMessageSeen', 'lastMessageSender'])
&& incomingData().lastMessageSeen is bool
&& incomingData().lastMessageSender is string
&& incomingData().lastMessageSender in incomingData().users
)
)
}
// Conditions for chat creations
function canCreateChat() {
return isValidChatWrite()
// The first user in the participating `users` array must be the chat creator (first message sender)
&& incomingData().users[0] == requesterId()
// Only superfans (members) can create chats
&& isMember()
// Both participants exist
&& userExists(incomingData().users[0])
&& userExists(incomingData().users[1])
}
// Conditions for chat updates
function canUpdateChat() {
return isValidChatWrite()
// Only chat participants can update the chat
&& requesterId() in incomingData().users
// Participants can not change the creation timestamp
&& incomingData().createdAt == existingData().createdAt
// Participants can not change the chat participants
&& incomingData().users == existingData().users
}
function canReadMessage(chatId) {
return isSignedIn() && isVerified()
// this condition doubles as a "does the chat exist" check
&& requesterId() in getChatUsers(chatId);
}
function canSendMessage(chatId) {
return canReadMessage(chatId)
&& incomingData().keys().hasOnly(['content', 'createdAt', 'from'])
&& incomingData().content is string
&& incomingData().content.size() >= 1
&& incomingData().content.size() <= maxMessageLength()
&& incomingData().createdAt is timestamp
&& incomingData().from == requesterId()
}
match /chats/{chatId} {
allow create: if canCreateChat();
allow read: if canReadChat();
allow update: if canUpdateChat();
allow delete: if false;
match /messages/{messageId} {
allow read: if canReadMessage(chatId);
allow create: if canSendMessage(chatId);
allow update, delete: if false;
}
}
// Stats
match /stats/{type} {
allow read: if isSignedIn() && isAdmin();
allow write: if false;
}
// Allow reading superfan & campsite stats on our public pages
match /stats/superfans {
allow read: if true;
}
match /stats/campsites {
allow read: if true;
}
}
}