I have a users collection in firestore, which stores some information about the user which I don't want to disclose to the user (e.g. session id). So my question is, is it possible to only allow firebase admin to fetch some fields of a doc and rest of the fields can be fetched if any user is authenticated? Is it possible with firebase security rules?
As you have noted, Firestore security rules "only allow security up to the document level".
Similarly, with the Client SDKs, when you fetch a document, you get the entire set of fields of this document.
(At the time of writing) Only the Firestore REST API allows to apply a DocumentMask
which "restrict a get or update operation on a document to a subset of its fields". Note that this is not a limitation on the read and write access right at the level of the field (i.e. it does not implement/mimic a security rule), it is just a way to reduce the size of the payload passed to/received from the API.
So, having said that, one solution is to duplicate your data and have two different collections:
allow read: if request.auth.uid != null;
).To "link" the two versions of a document, you use the same document id in each collection.
One side effect of this approach is that you need to keep the docs in sync. This synchronization could be done with a Cloud Function triggered if a doc in one of the collections is modified. Since two versions of a document share the same doc id, it is not very complex.