firebase-tools icon indicating copy to clipboard operation
firebase-tools copied to clipboard

Firestore Emulator see's rule changes but doesn't actually apply the change until emulator is restarted

Open ScottPierce opened this issue 6 years ago • 9 comments

[REQUIRED] Environment info

firebase-tools: firebase --version: 8.9.0

Platform: macOS

[REQUIRED] Test case

firebase-bug-repro.zip

[REQUIRED] Steps to reproduce

  1. yarn install in the root directory.
  2. npm install in the ./firebase/functions directory.
  3. From root directory run yarn start-emulators to start emulators
  4. From lib-service directory run yarn jest
  5. 2 tests should fail.
  6. Open ./firebase/firestore.rules. Change
    • From allow create: if request.auth.uid == null && request.auth.uid in request.resource.data.admins;
    • To allow create: if request.auth.uid != null && request.auth.uid in request.resource.data.admins;
  7. Notice that the emulator log says that it noticed the change and it's applied.:
i  firestore: Change detected, updating rules...
✔  firestore: Rules updated.
  1. From lib-service directory run yarn jest
  2. All tests should pass, but 2 tests fail still, because the rule change has not actually been applied.
  3. Restart the emulator by killing the process and running yarn start-emulators again.
  4. From lib-service directory run yarn jest
  5. Tests now all pass, because restarting the emulator has now applied the rule changes.

[REQUIRED] Expected behavior

After I change firestore.rules the rule change is applied live without requiring an emulator restart.

[REQUIRED] Actual behavior

After I change firestore.rules an emulator restart is required before the rule change actually takes place.

ScottPierce avatar Sep 12 '20 15:09 ScottPierce

@ScottPierce thanks for the detailed repro. I was able to reproduce this bug, don't know the cause yet but the workaround is to call loadFirestoreRules() within your test suite so that you can load the rules before each test run. I can confirm that works.

In store-service.test.js

beforeAll(async () => {
    const fs = require("fs");
    const rules = fs.readFileSync('../firebase/firestore.rules').toString();

    console.log("Updating firestore rules...");
    await loadFirestoreRules({
        projectId: projectId,
        rules: rules,
    });
});

samtstern avatar Sep 15 '20 14:09 samtstern

Ok so when I run the emulators with --debug and then look at the outgoing request for a rules update with a hot reload it looks like this:

[2020-09-15T14:26:18.166Z] >>> HTTP REQUEST PUT http://localhost:8080/emulator/v1/projects/iq-tv-int:securityRules  
 {"ignore_errors":true,"rules":{"files":[{"name":"security.rules","content":"rules_version = '2';\nservice cloud.firestore {\n  match /databases/{database}/documents {\n    // Reject all requests by default. Only allow what we explicitly allow.\n    match /{document=**} {\n      allow read, write: if false;\n    }\n\n    // Stores\n    match /stores/{storeId} {\n      allow read, update: if request.auth.uid != null && request.auth.uid in resource.data.admins;\n      allow create: if request.auth.uid == null && request.auth.uid in request.resource.data.admins;\n    }\n  }\n}\n"}]}}

Within the source of @firebase/testing here's how the equivalent thing is done:

request.put({
    uri: "http://" + FIRESTORE_ADDRESS + "/emulator/v1/projects/" + options.projectId + ":securityRules",
    body: JSON.stringify({
        rules: {
            files: [{ content: options.rules }]
        }
    })
}, function (err, resp, body) {

The only difference I can see is that inside the first request we include "name":"security.rules" but from @firebase/testing we do not. I'll see if that makes a difference.

samtstern avatar Sep 15 '20 14:09 samtstern

@ScottPierce I found the issue.

In your test you use this projectId:

const projectId = `test-db`

But in your .firebaserc file:

{
  "projects": {
    "default": "iq-tv-int"
  }
}

When you use emulators:start it only hot reloads rules on your default project ID, so in this case iq-tv-int.

So if you want hot reloading of rules to work during tests, try using the same project ID in tests and with emulators:start. Or use loadFirestoreRules in tests.

samtstern avatar Sep 15 '20 14:09 samtstern

I spent a few hours of total frustration with this. I changed the rules but my test output did not change. I really think your testing docs and/or the "rules updated" message from the emulator are NOT leading developers down the pit of success. I saw the "load rules" code in some of the samples but as soon as I saw the emulator give a message "rules updated" I figured I could take out the dynamically "load rules" code and it still worked - UNTIL I later changed the project ID. I'm not sure what should be improved here but here are a couple suggestions...

  1. The sample testing code, where you have the dynamic loading of the rules file, could have a comment like "Do not take this out. The emulator only automatically updates rules for the default project."
  2. The emulator message could say rules updated (only for project x)

Maybe there is some way the emulator can update the rules for all situations so there isn't this 'gotcha' case.

jmagaram avatar Mar 12 '21 05:03 jmagaram

@jmagaram thank you for your feedback. We're actually looking at completely changing how the emulators handle project IDs to help people avoid a whole bunch of confusing experiences, so I will add your comment to our (long) list of reasons to do this!

samtstern avatar Mar 12 '21 10:03 samtstern

I take it this is still ongoing? I'm seeing this issue even when projectId in the test script and .firebaserc default key are identical. I don't think the emulator is reading .firebaserc but using whatever that shell has set via firebase use. When I changed it to match the test script, it worked, regardless of the default key in .firebaserc (and, by contrast, setting the default project id to match the test script did not work if I'd run firebase use otherProject at any stage).

Using loadFirestoreRules() does work of course, so perhaps that's the safest method.

dsl101 avatar Jul 07 '21 13:07 dsl101

This problem also occurs during development, not during testing

sinano1107 avatar Mar 26 '22 08:03 sinano1107

I can confirm this is still happening for me using firebase-tools version 11.16.0 when using one project ID across everything. I'll try to make a MRE when I can showing this.

cjwhitsitt avatar Nov 25 '22 03:11 cjwhitsitt

Is it possible to use similar workaround during development of functions? Inside the i.e. .onCreate trigger?

beforeAll(async () => { const fs = require("fs"); const rules = fs.readFileSync('../firebase/firestore.rules').toString();

console.log("Updating firestore rules...");
await loadFirestoreRules({
    projectId: projectId,
    rules: rules,
});

});

tymek2 avatar Dec 04 '22 19:12 tymek2