How to upload files when unit testing firebase storage security rules?

Viewed 56

I have a bucket into which users can upload audio files, and my goal is to test that it is working as expected. But when I try to use the "@firebase/rules-unit-testing" library to upload a test file into the emulator the upload gets stuck and makes no progress.

Rules

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if false;
    }
    match /audio/{audioFileID} {
      allow create: if request.auth != null && request.resource.contentType.matches('audio/(flac|wav)');
    }
  }
}

Test code

import {
  assertFails,
  assertSucceeds,
  initializeTestEnvironment,
  RulesTestEnvironment,
} from "@firebase/rules-unit-testing";
import { test, beforeAll, beforeEach, afterAll } from "vitest";
import fs from "fs";

const createTestFile = (size: number) => Buffer.alloc(size);
let testEnv: RulesTestEnvironment;

beforeAll(async () => {
  testEnv = await initializeTestEnvironment({
    projectId: "stst-et-interviewer-dev",
    hub: {
      host: "localhost",
      port: 4400,
    },
  });
});

beforeEach(async () => {
  await testEnv.clearStorage();
  await testEnv.clearFirestore();
});

afterAll(async () => await testEnv.cleanup());

const loadStepStoneImage = () =>
  fs.readFileSync("./public/images/stepstoneLogo.svg");

test("Storage does not allow you to read files", async () => {
  const rouge = testEnv.unauthenticatedContext();
  const alice = testEnv.authenticatedContext("alice");
  await assertFails(
    rouge.storage().ref("audio/test-interview.flac").getDownloadURL()
  );
  await assertFails(
    alice.storage().ref("audio/test-interview.flac").getDownloadURL()
  );
  await assertFails(alice.storage().ref("audio/").listAll());
});

test("Storage does not allow you to upload a file if you are not logged in", async () => {
  const rouge = testEnv.unauthenticatedContext();
  const upload = rouge
    .storage("stst-et-interviewer-dev.appspot.com")
    .ref("audio/logo.svg")
    .put(createTestFile(200), { contentType: "audio/flac" });
  
  await assertFails(upload.then()); // <- GETS STUCK HERE
  console.log("this does not happen");
});

What are the possible reasons for this happening? Are there any simple ways of debugging?

0 Answers
Related