Repository navigation
Expand file tree
/
Copy pathfirestore.rules
More file actions
405 lines (357 loc) · 21 KB
/
Copy pathfirestore.rules
File metadata and controls
405 lines (357 loc) · 21 KB
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// Co-authored-by: Claude Code (Claude Opus 5.5, Claude Fable 5.2)
// Co-authored-by: Copilot GPT-5.6 Terra
// Co-authored-by: Copilot (Auto)
// Co-authored-by: Copilot Claude Sonnet 5.5
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function isSignedIn() {
return request.auth != null;
}
// Sign-up only checks the domain in the app, and anyone can create a Firebase Auth account
// through the REST API, so the rules check it again.
function isEpfl() {
return isSignedIn()
&& request.auth.token.email is string
&& request.auth.token.email.lower().matches('.*@epfl[.]ch$');
}
// Everything except creating an account needs a verified EPFL address.
function isVerified() {
return isEpfl() && request.auth.token.email_verified == true;
}
function isOwner(uid) {
return isSignedIn() && request.auth.uid == uid;
}
// Above zero and at most max, in CHF.
function isAmount(value, max) {
return value is number && value > 0 && value <= max;
}
// Same bounds as AuthRules.MIN_USERNAME_LENGTH and MAX_USERNAME_LENGTH in the app.
function validUsernameLength(username) {
return username is string && username.size() >= 3 && username.size() <= 30;
}
// Username -> { uid }. Written once at sign-up, in the same batch as the profile document,
// before the email is verified. The profile must name this username, so an account can only
// ever hold one.
match /usernames/{username} {
// Sign-up checks availability before the account exists, so this has to work signed out.
allow get: if true;
// Sign-in looks up its own username with whereEqualTo("uid", uid).
allow list: if isSignedIn() && resource.data.uid == request.auth.uid;
allow create: if isEpfl()
&& validUsernameLength(username)
&& request.resource.data.keys().hasOnly(['uid'])
&& request.resource.data.uid == request.auth.uid
&& username == username.lower()
&& username == username.trim()
&& getAfter(/databases/$(database)/documents/users/$(request.auth.uid)).data.username == username;
allow update, delete: if false;
}
// Public profile. The email is not stored here.
match /users/{uid} {
// photoPath is a Storage path, not a download URL: a download URL works for anyone who has
// it, so only storage.rules decides who sees the photo. It can only name the user's own.
function validProfile(data) {
return data.keys().hasAll(['username'])
&& validUsernameLength(data.username)
&& data.keys().hasOnly(['username', 'bio', 'photoPath'])
&& (!('bio' in data) || (data.bio is string && data.bio.size() <= 500))
&& (!('photoPath' in data) || data.photoPath == 'users/' + uid + '/profile.jpg');
}
// Other users' profiles are shown next to their listings. Before verifying, a user can
// still see their own.
allow read: if isVerified() || isOwner(uid);
// Part of creating the account, so it does not need a verified email: sign-up writes it
// before the user has verified. getAfter, because sign-up creates the username in the same
// batch.
allow create: if isEpfl() && isOwner(uid)
&& validProfile(request.resource.data)
&& getAfter(/databases/$(database)/documents/usernames/$(request.resource.data.username)).data.uid == uid;
// Every sign-in rewrites the username it already has (ensureProfileDocument). Before
// verifying, that write must change nothing.
allow update: if isOwner(uid)
&& validProfile(request.resource.data)
&& request.resource.data.username == resource.data.username
&& (isVerified() || request.resource.data.diff(resource.data).affectedKeys().size() == 0);
allow delete: if false;
}
match /bookings/{bookingId} {
function validBooking(data) {
let listing = get(/databases/$(database)/documents/listings/$(data.listingId)).data;
return data.keys().hasAll(['listingId', 'renterUid', 'lenderUid', 'days', 'status'])
&& data.keys().hasOnly(['listingId', 'renterUid', 'lenderUid', 'days', 'status'])
&& data.listingId is string && data.listingId.size() > 0
&& data.renterUid == request.auth.uid
&& data.lenderUid is string
&& data.lenderUid == listing.ownerUid
&& listing.paused == false
&& data.renterUid != data.lenderUid
// The days booked, as LocalDate epoch days. They need not follow each other. Every one
// must be on offer, once: hasAll plus no duplicates bounds the size by the listing's
// availableDates, which are at most 366.
&& data.days is list && data.days.size() > 0
&& data.days.toSet().size() == data.days.size()
&& 'availableDates' in listing
&& listing.availableDates.hasAll(data.days)
// Every day counts. A listing without maxRentalDays has no limit.
&& (!('maxRentalDays' in listing) || data.days.size() <= listing.maxRentalDays)
// Rules cannot loop over the days, so only the first is checked against server time
// (not the client clock). The app sends them earliest first; a modified client could
// still add a past day the listing offers (#346).
&& data.days[0] is int
&& data.days[0] >= request.time.toMillis() / 86400000
&& data.status == 'REQUESTED';
}
// Either party cancels a request, or a confirmed booking. Accepting a request also cancels
// the other requests for its days, through this rule.
function isCancel() {
return (resource.data.lenderUid == request.auth.uid || resource.data.renterUid == request.auth.uid)
&& request.resource.data.status == 'CANCELLED'
// Cancelling a cancelled booking changes nothing, so it is allowed: the renter may cancel
// a request while the lender's accept is cancelling it too, and the accept must not fail.
&& (resource.data.status == 'CANCELLED'
|| (resource.data.status in ['REQUESTED', 'CONFIRMED']
// A finished booking is history. The app stores the days earliest first, so the
// last one decides; it must not be before today by server time.
&& resource.data.days[resource.data.days.size() - 1] >= request.time.toMillis() / 86400000));
}
// The lender accepts a request once. Accepting takes the booked days off the listing in the
// same write, so no one can request them again. They must still be offered before it, so two
// requests sharing a day can never both be accepted, even when accepted at the same time: the
// second sees the day gone.
function isAccept() {
let listingPath = /databases/$(database)/documents/listings/$(resource.data.listingId);
return resource.data.lenderUid == request.auth.uid
&& resource.data.status == 'REQUESTED'
&& request.resource.data.status == 'CONFIRMED'
&& get(listingPath).data.get('availableDates', []).hasAll(resource.data.days)
&& !getAfter(listingPath).data.get('availableDates', []).hasAny(resource.data.days);
}
allow read: if isVerified()
&& (resource.data.lenderUid == request.auth.uid || resource.data.renterUid == request.auth.uid);
allow create: if isVerified() && validBooking(request.resource.data);
// Only the status changes.
allow update: if isVerified()
&& request.resource.data.diff(resource.data).affectedKeys().hasOnly(['status'])
&& (isCancel() || isAccept());
allow delete: if false;
}
// One conversation per listing and renter. It is created and bumped only in the same batch as a
// message: lastMessageId names that message, and the message checks it is the one named.
match /conversations/{conversationId} {
function listingPath(listingId) {
return /databases/$(database)/documents/listings/$(listingId);
}
function listingData(listingId) {
return get(listingPath(listingId)).data;
}
function conversationPath() {
return /databases/$(database)/documents/conversations/$(conversationId);
}
// Only a message written by this request has sentAt == request.time: the message rule
// enforces it, and earlier messages cannot be edited.
function isNewMessage(messageId) {
return messageId is string
&& getAfter(/databases/$(database)/documents/conversations/$(conversationId)/messages/$(messageId)).data.sentAt == request.time;
}
// The id is listingId_renterUid. Clients choose listing ids, so ids with more than one '_' are
// refused, which makes the renter readable from the id before the conversation exists.
function isRenterInId() {
let parts = conversationId.split('_');
return parts.size() == 2 && parts[1] == request.auth.uid;
}
// The inbox preview copies the new message, sent by me, and the send marks it read for me only.
// A text is never empty, so a '' preview means a photo-only message (one with no text).
// Call after isNewMessage, which checks lastMessageId is a string; its getAfter is read once.
function validLastMessage(data, readAtBefore) {
return data.lastMessageText == getAfter(/databases/$(database)/documents/conversations/$(conversationId)/messages/$(data.lastMessageId)).data.get('text', '')
&& data.lastMessageSenderUid == request.auth.uid
&& data.lastReadAt is map
&& data.lastReadAt.diff(readAtBefore).affectedKeys().hasOnly([request.auth.uid])
&& data.lastReadAt[request.auth.uid] == request.time;
}
function validNewConversation(data) {
let listing = listingData(data.listingId);
return data.keys().hasAll(['listingId', 'listingTitle', 'renterUid', 'lenderUid', 'participants', 'lastMessageAt', 'lastMessageId', 'lastMessageText', 'lastMessageSenderUid', 'lastReadAt'])
&& data.keys().hasOnly(['listingId', 'listingTitle', 'renterUid', 'lenderUid', 'participants', 'lastMessageAt', 'lastMessageId', 'lastMessageText', 'lastMessageSenderUid', 'lastReadAt'])
&& data.listingId is string
&& conversationId == data.listingId + '_' + request.auth.uid
&& isRenterInId()
&& data.renterUid == request.auth.uid
&& data.lenderUid == listing.ownerUid
&& data.renterUid != data.lenderUid
// Lists the two participants so the inbox can query with array-contains.
&& data.participants == [data.renterUid, data.lenderUid]
&& listing.paused == false
&& data.listingTitle == listing.title
&& data.lastMessageAt == request.time
&& isNewMessage(data.lastMessageId)
&& validLastMessage(data, {});
}
// A send merges the whole conversation again, so only what a send refreshes may change.
// A paused listing still accepts messages; a deleted one does not. Checking the owner, not
// only existence, refuses a listing someone else re-created under the deleted one's id.
function isSend() {
return request.resource.data.diff(resource.data).affectedKeys().hasOnly(['lastMessageAt', 'listingTitle', 'lastMessageId', 'lastMessageText', 'lastMessageSenderUid', 'lastReadAt'])
&& request.resource.data.lastMessageAt == request.time
// Also forces lastMessageId to change: the previous message's sentAt is in the past.
&& isNewMessage(request.resource.data.lastMessageId)
&& validLastMessage(request.resource.data, resource.data.get('lastReadAt', {}))
&& listingData(resource.data.listingId).ownerUid == resource.data.lenderUid
&& (request.resource.data.listingTitle == resource.data.listingTitle
|| request.resource.data.listingTitle == listingData(resource.data.listingId).title);
}
// Mark read: only my own read time moves, to now; no message needed, so any listing state.
function isMarkRead() {
return request.resource.data.diff(resource.data).affectedKeys().hasOnly(['lastReadAt'])
&& request.resource.data.lastReadAt is map
&& request.resource.data.lastReadAt.diff(resource.data.get('lastReadAt', {})).affectedKeys().hasOnly([request.auth.uid])
&& request.resource.data.lastReadAt[request.auth.uid] == request.time;
}
allow get: if isVerified()
&& (isRenterInId() || (resource != null && resource.data.lenderUid == request.auth.uid));
allow list: if isVerified() && request.auth.uid in resource.data.participants;
allow create: if isVerified() && validNewConversation(request.resource.data);
allow update: if isVerified()
&& request.auth.uid in resource.data.participants
&& (isSend() || isMarkRead());
allow delete: if false;
match /messages/{messageId} {
// The app trims before sending; surrounding whitespace does not count, but is capped.
function validText(text) {
return text is string
&& text.trim().size() >= 1
&& text.trim().size() <= 1000
&& text.size() <= 2000;
}
// A photo is stored at the path storage.rules opens for this conversation and message.
function validImagePath(path) {
return path == 'conversations/' + conversationId + '/' + messageId + '.jpg';
}
// getAfter, because the first message creates the conversation in the same batch. Requiring
// the conversation to name this message allows one message per batch. A message has a text,
// a photo, or both (a photo with a caption). exists sees the state before the batch, so a
// photo cannot open a conversation; the app sends a text first. A photo message is written
// before its photo is uploaded, so it starts with photoPending true; a text never has it.
function validMessage(data) {
let conversation = getAfter(conversationPath()).data;
return request.auth.uid in conversation.participants
&& conversation.lastMessageAt == request.time
&& conversation.lastMessageId == messageId
&& data.keys().hasAll(['senderUid', 'sentAt'])
&& data.keys().hasOnly(['senderUid', 'text', 'sentAt', 'imagePath', 'photoPending'])
&& data.keys().hasAny(['text', 'imagePath'])
&& data.senderUid == request.auth.uid
&& data.sentAt == request.time
&& (!('text' in data) || validText(data.text))
&& ('imagePath' in data) == ('photoPending' in data)
&& (!('imagePath' in data)
|| (exists(conversationPath())
&& validImagePath(data.imagePath)
&& data.photoPending == true))
&& listingData(conversation.listingId).ownerUid == conversation.lenderUid;
}
// Once the photo is uploaded, its sender marks it so, once: photoPending goes from true to
// false and nothing else changes. Rules cannot see Storage, so the app marks it only after
// the upload ends.
function isPhotoUploaded() {
return resource.data.senderUid == request.auth.uid
&& resource.data.get('photoPending', false) == true
&& request.resource.data.diff(resource.data).affectedKeys().hasOnly(['photoPending'])
&& request.resource.data.photoPending == false;
}
allow read: if isVerified()
&& (isRenterInId() || get(conversationPath()).data.lenderUid == request.auth.uid);
allow create: if isVerified() && validMessage(request.resource.data);
allow update: if isVerified() && isPhotoUploaded();
// The sender can take back a photo message whose photo never arrived: the app's Remove after
// a failed send. Once photoPending is false the photo is delivered and the message stays. A
// text never has photoPending, so it cannot be deleted.
allow delete: if isVerified()
&& resource.data.senderUid == request.auth.uid
&& resource.data.get('photoPending', false) == true;
}
}
match /listings/{listingId} {
// Storage paths, not download URLs, as for photoPath. Only the listing's own images/0 to
// images/4, the paths storage.rules lets its owner write, each at most once: so at most 5.
function validImagePaths(paths) {
let folder = 'listings/' + request.auth.uid + '/' + listingId + '/images/';
return paths is list
&& paths.hasOnly([folder + '0', folder + '1', folder + '2', folder + '3', folder + '4'])
&& paths.toSet().size() == paths.size();
}
function validCategory(type, category) {
return (type == 'ITEM'
&& category in [
'item_tools',
'item_electronics',
'item_books',
'item_sports',
'item_kitchen',
'item_other'
])
|| (type == 'SERVICE'
&& category in [
'service_tutoring',
'service_repairs',
'service_moving_help',
'service_gardening',
'service_cleaning',
'service_other'
]);
}
function validLocation(location) {
return location is map
&& location.keys().hasAll(['latitude', 'longitude', 'name'])
&& location.keys().hasOnly(['latitude', 'longitude', 'name'])
&& location.latitude is number && location.latitude >= -90 && location.latitude <= 90
&& location.longitude is number && location.longitude >= -180 && location.longitude <= 180
&& location.name is string && location.name.trim().size() > 0
&& location.name.size() <= 80;
}
function validListing(data) {
return data.keys().hasAll(['ownerUid', 'category', 'price', 'type', 'title', 'description', 'imagePaths', 'paused'])
&& data.keys().hasOnly(['ownerUid', 'category', 'price', 'type', 'title', 'description', 'imagePaths', 'paused', 'refundValue', 'maxRentalDays', 'availableDates', 'location'])
&& data.ownerUid == request.auth.uid
// Required, because Browse queries paused == false and a listing without it would never
// show. Only the owner can change it, through the update rule below.
&& data.paused is bool
&& data.category is string && validCategory(data.type, data.category)
// Same as ListingRules.errorFor in the app: no empty or whitespace-only text.
&& data.title is string && data.title.trim().size() > 0 && data.title.size() <= 80
&& data.description is string && data.description.trim().size() > 0
&& data.description.size() <= 1000
// Same limits as ListingRules.MAX_PRICE and MAX_REFUND_VALUE in the app.
&& isAmount(data.price, 10000)
&& validImagePaths(data.imagePaths)
&& ((data.type == 'ITEM' && isAmount(data.refundValue, 100000))
|| (data.type == 'SERVICE' && !('refundValue' in data)))
// Optional rental duration in days, items only. Same bounds as
// ListingRules.MAX_RENTAL_DAYS in the app (a semester, exams included).
&& (!('maxRentalDays' in data)
|| (data.type == 'ITEM' && data.maxRentalDays is int
&& data.maxRentalDays >= 1 && data.maxRentalDays <= 180))
// Optional days the owner offers the listing on, as LocalDate epoch days. At most a
// year of them, each once: same as ListingRules.MAX_AVAILABLE_DAYS in the app. Rules
// cannot loop, so the entries themselves are checked by the app when it reads them.
&& (!('availableDates' in data)
|| (data.availableDates is list
&& data.availableDates.size() <= 366
&& data.availableDates.toSet().size() == data.availableDates.size()))
// Optional place the listing is offered at, as a map rather than a GeoPoint. Same name
// limit as ListingRules.MAX_LOCATION_NAME_LENGTH in the app.
&& (!('location' in data) || validLocation(data.location));
}
allow read: if isVerified();
allow create: if isVerified() && validListing(request.resource.data);
allow update: if isVerified()
&& resource.data.ownerUid == request.auth.uid
&& request.resource.data.ownerUid == resource.data.ownerUid
// The type decides whether refundValue exists, so a listing keeps the type it was created with.
&& request.resource.data.type == resource.data.type
&& validListing(request.resource.data);
allow delete: if isVerified() && resource.data.ownerUid == request.auth.uid;
}
}
}