Search code examples
firebasegoogle-cloud-functionsfirebase-security

Custom claims set in cloud functions do not show up in cloud rules of firebase storage


I'm trying to set custom claims using the following:

admin.auth().setCustomUserClaims(user.uid, {['hguwukrpyrwxerqr679p']: true});

where hguwukrpyrwxerqr679p is a unique ID of an object in the firestore database. This object, when it was created, has its own bucket. This bucket has the following security rule:

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    allow read: if request.auth.token[bucket];
    allow write: if false;
  }
}

Unfortunately, this does not work and I get a 403 error code. I don't know why and I've tried simulating the request in the rule-playground of firebase storage, using the user from above. The token section does not show any custom claims at all, but it should, shouldn't it?

I've been at it for quite a few hours now, trying out various methods, even setting the claims manually in a cloud function. Can someone point me in the right direction or give hints on how to debug this problem correctly? When debugging a cloud function by executing

console.log(Object.keys(await admin.auth().getUser(uid).customClaims));

it shows the correct contents.


Solution

  • Rules stored in the root of a bucket are somehow ignored.

    rules_version = '2';
    service firebase.storage {
      match /b/{bucket}/o {
        allow read: if request.auth.token[bucket];
        allow write: if false;
      }
    }
    

    Instead, a wildcard should be used

    rules_version = '2';
    service firebase.storage {
      match /b/{bucket}/o {
        match /{somePath=**} {
          allow read: if request.auth.token[bucket];
          allow write: if false;
        }
      }
    }
    

    I'm not sure if this should be accepted as an answer since it's only partially relevant to the problem.