Reputation: 31495
If the client code is supposed to do a batched write to Firestore like the following:
DOC: Transactions and Batched writes
const db = firebase.firestore();
const batch = db.batch();
// UPDATE CITY POPULATION IN CITIES COLLECTION
const docRef = db.collection('CITIES').doc('NYC');
batch.update(nycRef, {population: 10000000});
// UPDATE CITY POPULATION IN ALL_CITIES_POPULATIONS COLLECTION
const docRef = db.collection('ALL_CITIES_POPULATION').doc('ALL_CITIES_POPULATION');
batch.update(docRef, {
NYC: 1000000
});
On the 1st update, I'm updating a property on the NYC
doc on the CITIES
collection.
On the 2nd update, I'm updating a property named NYC
on the ALL_CITIES_POPULATION
doc, that is on the ALL_CITIES_POPULATION
collection. I.e: it's a single doc to keep populations for every city.
This code should work fine.
But is there a security rule to make sure that those writes are always going to be fired together? What if some malicious code fires a single write with only the 1st or the 2nd update?
What is the proper way of handling security for the scenario of a batched write?
Upvotes: 3
Views: 779
Reputation: 600126
To check for batched writes in security rules, you can use the getAfter()
and existsAfter()
functions. These return/check for the data as it exists after the write operation, if that write operation will be allowed.
So in your case you can check whether the ALL_CITIES_POPULATION
document's NYC
field after the write is the same as the NYC
document's population
field.
Upvotes: 5