-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfirestore.rules
More file actions
510 lines (457 loc) · 18.7 KB
/
Copy pathfirestore.rules
File metadata and controls
510 lines (457 loc) · 18.7 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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function hasVerifiedEmail() {
// Firebase Auth owns this token claim. A profile field or request value
// is not authorization, and missing/malformed values fail this exact
// boolean comparison closed.
return request.auth != null
&& request.auth.token.email_verified == true;
}
function hasVerifiedRole(role) {
return hasVerifiedEmail() && request.auth.token.role == role;
}
function isAdmin() {
return hasVerifiedRole('admin');
}
function isMember() {
return hasVerifiedRole('member') || isAdmin();
}
function isNonEmptyString(value, maxLength) {
return value is string && value.size() > 0 && value.size() <= maxLength;
}
function isBoundedString(value, maxLength) {
return value is string && value.size() <= maxLength;
}
function isNullableBoundedString(value, maxLength) {
return value == null || isBoundedString(value, maxLength);
}
function isNullableHttpsUrl(value) {
return value == null
|| (isBoundedString(value, 2048)
&& value.matches('https://[^ ]+'));
}
function isValidSlug(value) {
return isNonEmptyString(value, 200)
&& value.matches('[a-z0-9-]+');
}
function isNullableTimestamp(value) {
return value == null || value is timestamp;
}
function isNonNegativeInteger(value) {
return value is int && value >= 0;
}
function isPublishedEventStatus(data) {
return 'status' in data
&& data.status in ['open', 'closed', 'cancelled'];
}
function hasLegacyPublishedStatus(data) {
return !('status' in data) || isPublishedEventStatus(data);
}
function hasValidEventCreateFields(data) {
return data.keys().hasAll([
'slug',
'title',
'description',
'startAt',
'endAt',
'location',
'locationDetails',
'capacity',
'registeredCount',
'status',
'visibility',
'pricing',
'stripePriceIds',
'waiverText',
'waiverVersion',
'customFields',
'resultsUrl',
'resultsText',
'resultsPublishedAt',
'registrationOpensAt',
'registrationClosesAt',
'heroImageUrl',
'createdBy',
'createdAt',
'updatedAt'
]) && data.keys().hasOnly([
'slug',
'title',
'description',
'startAt',
'endAt',
'location',
'locationDetails',
'capacity',
'registeredCount',
'status',
'visibility',
'pricing',
'stripePriceIds',
'waiverText',
'waiverVersion',
'customFields',
'volunteerEnabled',
'volunteerFields',
'resultsUrl',
'resultsText',
'resultsPublishedAt',
'registrationOpensAt',
'registrationClosesAt',
'heroImageUrl',
'createdBy',
'createdAt',
'updatedAt'
]);
}
function hasOnlyEventUpdateFields() {
return request.resource.data.diff(resource.data).affectedKeys().hasOnly([
'title',
'description',
'startAt',
'endAt',
'location',
'locationDetails',
'resultsUrl',
'resultsText',
'resultsPublishedAt',
'heroImageUrl',
'updatedAt'
]);
}
function hasValidEventPricing(pricing) {
return pricing is map
&& pricing.keys().hasAll(['memberCents', 'nonMemberCents'])
&& pricing.keys().hasOnly([
'memberCents',
'nonMemberCents',
'earlyBirdCents',
'earlyBirdUntil'
])
&& isNonNegativeInteger(pricing.memberCents)
&& isNonNegativeInteger(pricing.nonMemberCents)
&& (!('earlyBirdCents' in pricing)
|| isNonNegativeInteger(pricing.earlyBirdCents))
&& (!('earlyBirdUntil' in pricing)
|| isNullableTimestamp(pricing.earlyBirdUntil));
}
function hasInertEventOperationalConfig(data) {
return data.capacity == null
&& data.status == 'draft'
// The current client submits visibility=public on a new form. Draft
// status keeps it unreadable and unregistrable; visibility is then
// immutable in browser updates until a server approves publication.
&& data.visibility == 'public'
&& data.pricing is map
&& data.pricing.keys().hasAll(['memberCents', 'nonMemberCents'])
&& data.pricing.keys().hasOnly(['memberCents', 'nonMemberCents'])
&& data.pricing.memberCents == 0
&& data.pricing.nonMemberCents == 0
// Volunteer signup currently takes a zero-charge comp path. Browser
// creation therefore starts with volunteering disabled, and the update
// allowlist keeps these values server-owned.
&& data.volunteerEnabled == false
&& data.volunteerFields is list
&& data.volunteerFields.size() == 0
&& data.customFields is list
&& data.customFields.size() == 0
&& data.waiverText == ''
&& data.waiverVersion == '1'
&& data.registrationOpensAt == null
&& data.registrationClosesAt == null;
}
function hasValidEventEditorValues(data) {
return isNonEmptyString(data.title, 200)
&& isBoundedString(data.description, 20000)
&& data.startAt is timestamp
&& isNullableTimestamp(data.endAt)
&& isBoundedString(data.location, 500)
&& isBoundedString(data.locationDetails, 2000)
// `null` is the only unlimited-capacity sentinel. Zero would be
// falsey in the current checkout code and could silently disable the
// capacity check, so every configured capacity must be positive.
&& (data.capacity == null
|| (isNonNegativeInteger(data.capacity) && data.capacity > 0))
&& data.status in ['draft', 'open', 'closed', 'cancelled']
&& data.visibility in ['public', 'members_only', 'draft']
&& hasValidEventPricing(data.pricing)
&& isBoundedString(data.waiverText, 50000)
&& isNonEmptyString(data.waiverVersion, 200)
&& data.customFields is list
&& data.customFields.size() <= 50
&& data.volunteerEnabled is bool
&& data.volunteerFields is list
&& data.volunteerFields.size() <= 50
&& isNullableHttpsUrl(data.resultsUrl)
&& isNullableBoundedString(data.resultsText, 10000)
&& (!('resultsPublishedAt' in data)
|| isNullableTimestamp(data.resultsPublishedAt))
&& isNullableTimestamp(data.registrationOpensAt)
&& isNullableTimestamp(data.registrationClosesAt)
&& isNullableHttpsUrl(data.heroImageUrl)
&& data.updatedAt is timestamp;
}
function hasValidProductCreateFields(data) {
return data.keys().hasAll([
'slug',
'title',
'description',
'priceCents',
'imageUrl',
'sizes',
'colors',
'status',
'createdBy',
'createdAt',
'updatedAt'
]) && data.keys().hasOnly([
'slug',
'title',
'description',
'priceCents',
'imageUrl',
'sizes',
'colors',
'status',
'createdBy',
'createdAt',
'updatedAt'
]);
}
function hasOnlyProductUpdateFields() {
return request.resource.data.diff(resource.data).affectedKeys().hasOnly([
'title',
'description',
'imageUrl',
'updatedAt'
]);
}
function hasValidProductEditorValues(data) {
return isNonEmptyString(data.title, 200)
&& isBoundedString(data.description, 20000)
&& isNonNegativeInteger(data.priceCents)
&& isNullableHttpsUrl(data.imageUrl)
&& data.sizes is list
&& data.sizes.size() <= 100
&& data.colors is list
&& data.colors.size() <= 100
&& data.status in ['draft', 'active', 'sold_out', 'archived']
// Active products reach Stripe Checkout and therefore cannot use the
// zero-price draft sentinel.
&& (data.status != 'active' || data.priceCents > 0)
&& data.updatedAt is timestamp;
}
// Members-only legacy collection
match /members_only/{document} {
allow read: if isMember();
}
// A signed-in user can read and update their own member doc.
// Member docs are created only by the create-once signup or recovery
// Cloud Functions (Admin SDK); there is intentionally no client `create` rule.
match /members/{uid} {
// Admin screens may enumerate profiles, but role and profile creation
// remain server-managed. In particular, an admin claim in a browser is
// not authority to change another user's role mirror.
allow read: if request.auth != null
&& (request.auth.uid == uid || isAdmin());
// Self-service edits are restricted to a name-only field allowlist while
// optional phone collection is paused for privacy review. Existing phone
// values remain untouched; browser clients cannot add, replace, or clear
// them through this rule.
// An allowlist (rather than pinning each protected field individually)
// blocks BOTH tampering with managed fields — role, email, createdAt,
// emailVerified, provider — AND injection of arbitrary new fields (e.g.
// a planted `isAdmin` flag or a multi-MB blob). Managed fields are set
// only by Cloud Functions (Admin SDK).
allow update: if request.auth != null
&& request.auth.uid == uid
&& request.resource.data.diff(resource.data).affectedKeys()
.hasOnly(['fullName', 'updatedAt'])
&& request.resource.data.diff(resource.data).affectedKeys()
.hasAll(['updatedAt'])
&& (request.resource.data.fullName == null
|| (request.resource.data.fullName is string
&& request.resource.data.fullName.size() <= 200))
&& request.resource.data.updatedAt is timestamp;
// Third-party connections (Strava, etc). Users can read *whether*
// a connection exists and basic metadata, but CANNOT read tokens —
// enforced server-side: the token fields live in a sibling `secrets`
// subcollection with allow read: false. Writes always via Cloud
// Functions, which use the Admin SDK.
match /connections/{connectionId} {
allow read: if request.auth != null && request.auth.uid == uid;
allow write: if false;
}
// OAuth tokens & other secrets — server-only. Clients MUST NOT read.
match /secrets/{secretId} {
allow read, write: if false;
}
}
// ---------------------------------------------------------------
// Events
//
// Schema fields used here:
// - visibility: 'public' | 'members_only' | 'draft'
// - status: 'draft' | 'open' | 'closed' | 'cancelled'
// - member_only: legacy boolean (pre-stripe schema)
//
// The current admin editor reads and writes non-financial event catalog
// fields directly. Price and capacity are fixed to inert values on browser
// creation and immutable from browser updates. Registration, payment, and
// capacity configuration remains server-owned.
// ---------------------------------------------------------------
match /events/{eventId} {
allow read: if isAdmin();
// The editor initializes server-owned fields only to inert values. Any
// Stripe reference, payment/audit field, non-zero counter, or unknown
// field must be created by trusted server code instead.
allow create: if isAdmin()
&& hasValidEventCreateFields(request.resource.data)
&& isValidSlug(request.resource.data.slug)
&& request.resource.data.slug == eventId
&& request.resource.data.createdBy == request.auth.uid
&& request.resource.data.createdAt is timestamp
&& request.resource.data.registeredCount is int
&& request.resource.data.registeredCount == 0
&& request.resource.data.stripePriceIds is map
&& request.resource.data.stripePriceIds.keys().hasOnly([])
&& hasInertEventOperationalConfig(request.resource.data)
&& hasValidEventEditorValues(request.resource.data);
// Updates are limited to display-only editor fields. In particular,
// slug/ownership, status/visibility, pricing/capacity, registration and
// waiver configuration, Stripe references, payment/inventory state, and
// audit data are immutable from a browser. Delete is intentionally absent.
allow update: if isAdmin()
&& hasOnlyEventUpdateFields()
&& hasValidEventEditorValues(request.resource.data);
// Public read: new-schema event with public visibility and not draft
allow read: if resource.data.visibility == 'public'
&& isPublishedEventStatus(resource.data);
// Public read: legacy event (no visibility field) not flagged member_only
allow read: if !('visibility' in resource.data)
&& resource.data.member_only != true
&& hasLegacyPublishedStatus(resource.data);
// Authenticated member/admin read: members-only events
allow read: if isMember()
&& ((resource.data.visibility == 'members_only'
&& isPublishedEventStatus(resource.data))
|| (!('visibility' in resource.data)
&& resource.data.member_only == true
&& hasLegacyPublishedStatus(resource.data)));
// Registrations subcollection — browser admins may read rosters for the
// current admin UI, but no client may write lifecycle or financial
// fields directly. Creation, updates, refunds, and substitutions all go
// through Cloud Functions which use the Admin SDK.
match /registrations/{regId} {
allow read: if isAdmin();
allow write: if false;
}
}
// ---------------------------------------------------------------
// Promo codes — server-only. Clients may not read or mutate discount
// authority; validation happens in the Cloud Function that creates the
// Stripe Checkout Session.
// ---------------------------------------------------------------
match /promoCodes/{codeId} {
allow read, write: if false;
}
// ---------------------------------------------------------------
// Rate-limit buckets — server-only. Configure a Firestore TTL
// policy on this collection (field: expiresAt) to prune old docs.
// ---------------------------------------------------------------
match /ratelimits/{bucketId} {
allow read, write: if false;
}
// ---------------------------------------------------------------
// Shop products — publicly readable when active or sold_out. The current
// admin editor may manage non-financial product catalog fields directly.
// Browser creation is an inert zero-price draft and browser updates cannot
// change price. Drafts and archived products remain hidden from others.
// ---------------------------------------------------------------
match /products/{productId} {
allow read: if isAdmin();
allow create: if isAdmin()
&& hasValidProductCreateFields(request.resource.data)
&& isValidSlug(request.resource.data.slug)
&& request.resource.data.slug == productId
&& request.resource.data.createdBy == request.auth.uid
&& request.resource.data.createdAt is timestamp
&& request.resource.data.status == 'draft'
&& request.resource.data.priceCents == 0
&& request.resource.data.sizes is list
&& request.resource.data.sizes.size() == 0
&& request.resource.data.colors is list
&& request.resource.data.colors.size() == 0
&& hasValidProductEditorValues(request.resource.data);
// Price, availability status, variants, Stripe references, inventory,
// payment fields, and audit data are not browser editor fields. Delete
// is intentionally absent.
allow update: if isAdmin()
&& hasOnlyProductUpdateFields()
&& hasValidProductEditorValues(request.resource.data);
allow read: if (resource.data.status == 'active'
|| resource.data.status == 'sold_out');
}
// Orders contain financial state and PII. Browser admins may read them for
// the current admin UI; every mutation goes through Cloud Functions.
match /orders/{orderId} {
allow read: if isAdmin();
allow write: if false;
}
// ---------------------------------------------------------------
// Server-owned operational boundaries. Explicit deny rules document the
// known sensitive collections; unmatched/future collections are denied by
// default because there is intentionally no recursive admin catch-all.
// ---------------------------------------------------------------
match /mail/{messageId} {
allow read, write: if false;
}
match /stripeEvents/{stripeEventId} {
allow read, write: if false;
}
match /checkoutRequests/{requestId} {
allow read, write: if false;
// Firestore subcollections do not inherit their parent document's rule.
// Keep every command lifecycle and any future nested command record at
// this server-only boundary, including from browser-admin clients.
match /{nestedDocument=**} {
allow read, write: if false;
}
}
// Profile-directory preferences and processed thumbnails contain private
// member data. Owners and browser admins use authenticated callable
// Functions for every read and mutation so that validation, revision
// checks, and audit writes remain one server-authoritative operation.
match /memberDirectoryPreferences/{uid} {
allow read, write: if false;
// Subcollections do not inherit the parent document rule. Keep any
// future nested preference records behind the same server-only boundary.
match /{nestedDocument=**} {
allow read, write: if false;
}
}
match /memberDirectoryPhotos/{uid} {
allow read, write: if false;
// Processed photo bytes and any future nested media records must never
// become browser-readable merely because a subcollection is introduced.
match /{nestedDocument=**} {
allow read, write: if false;
}
}
// Optional people-finder entries are a server-owned candidate index, not
// a browser-readable roster. The search Function revalidates every result.
match /memberDirectoryEntries/{uid} {
allow read, write: if false;
match /{nestedDocument=**} {
allow read, write: if false;
}
}
match /auditEvents/{auditEventId} {
allow read, write: if false;
}
match /retentionJobs/{jobId} {
allow read, write: if false;
}
}
}