In Firebase Security Rules for Cloud Storage, how do you limit a student's assignment upload to their own folder, PDF files and a maximum size?
answer
- a different service block
- the incoming file's metadata
- size and contentType
- uid in the path
- delete gets its own rule
basics
~10 sIn a service firebase.storage ruleset, match /submissions/{studentId}/{fileName} and allow create only when request.auth.uid equals studentId, request.resource.size is under the cap and request.resource.contentType is application/pdf.
solid answer
~40 sCloud Storage rules use the same language as Firestore's but a different frame: `service firebase.storage` with `match /b/{bucket}/o`, and paths are object names. For `match /submissions/{studentId}/{fileName}`, the upload rule checks `request.auth.uid == studentId`, `request.resource.size < 10 * 1024 * 1024` and `request.resource.contentType == 'application/pdf'`. `request.resource` describes the incoming object's metadata, while `resource` describes the object already stored, which is what read and delete rules inspect. Put the size and type checks on `create` and `update` and give `delete` its own ownership condition, so upload checks never decide whether a file may be removed. Rules see metadata, not bytes: `contentType` is what the client declared, so it limits honest mistakes and casual abuse, not a crafted file. A denied upload reaches the Android app as a `StorageException` whose `errorCode` is `ERROR_NOT_AUTHORIZED`.
go deeper
Recall the frame, service firebase.storage with match /b/{bucket}/o, and that request.resource.size and contentType describe the incoming upload.
Explain resource versus request.resource for files, why delete gets its own rule, and why contentType is only the client's declaration, including how the Android SDK picks it.
Design group access with claims, object metadata or capped Firestore lookups, and handle ERROR_NOT_AUTHORIZED as a final failure in the app.
Decide which upload guarantees the rules carry and which need server-side processing, since rules see metadata only and cannot inspect content.
## Same language, different service Cloud Storage for Firebase is guarded by the same Security Rules language as Firestore, but the ruleset is its own file with its own frame: - the service is **`service firebase.storage`**, and the Firebase CLI keeps Storage and Firestore rules in **separate files**; - the outer match is **`match /b/{bucket}/o`**, the bucket and the object namespace; - below it, paths are **object names** split on `/`, so `submissions/alice/essay.pdf` matches `match /submissions/{studentId}/{fileName}`; - methods are the same: `read` splits into `get` and `list`, `write` into `create`, `update` and `delete`, where `update` on a file means changing its metadata. `request.auth` behaves as in Firestore: `null` when signed out, otherwise `uid` plus the ID token's claims in `request.auth.token`. ## What a rule can see about a file Storage rules work on **metadata**. Two objects carry it: | Object | Meaning | Present on | |---|---|---| | `resource` | the object already stored at the path | rules on an existing object | | `request.resource` | the object as it would be stored if the write were allowed | write rules | Useful properties include `size` (bytes), `contentType`, `name`, `metadata` (your custom key-value pairs), `timeCreated` and `md5Hash`. `request.resource` has all of them except the ones the server assigns: `generation`, `metageneration`, `etag`, `timeCreated` and `updated`. The limitation follows directly: a rule cannot open the file. `contentType` is the type the client declared when uploading, so a rule enforcing `application/pdf` stops the wrong picker result or a casual abuser, not a deliberately mislabelled file. Content inspection belongs in server code that processes uploads after they land. ## The assignment ruleset ```plaintext rules_version = '2'; service firebase.storage { match /b/{bucket}/o { match /submissions/{studentId}/{fileName} { allow read: if request.auth != null && (request.auth.uid == studentId || request.auth.token.get('teacher', false) == true); allow create, update: if request.auth != null && request.auth.uid == studentId && request.resource.size < 10 * 1024 * 1024 && request.resource.contentType == 'application/pdf'; allow delete: if request.auth != null && request.auth.uid == studentId; } } } ``` What each line does: 1. The student's UID in the path makes ownership checkable with no lookup. 2. Teachers read through a custom claim; `get('teacher', false)` avoids an error for students whose token has no such claim. 3. Size and type checks apply to uploads and metadata changes. 4. `delete` is separate, with an ownership check only. Keeping the upload checks off it means a rule written for new files never decides whether an old one may be removed. For images, `request.resource.contentType.matches('image/.*')` accepts any image subtype. ## Traps specific to Storage rules - **Broad recursive matches stay broad.** As in Firestore, any matching `allow` grants the request. A `match /submissions/{allPaths=**}` with a loose condition overrides the careful per-student block. - **Group access needs data from somewhere.** Either a custom claim such as a class ID in `request.auth.token`, custom metadata on the object read through `resource.metadata`, or a Firestore lookup. - **Firestore lookups are tightly capped.** `firestore.get()` and `firestore.exists()` let Storage rules read Firestore documents, but no more than **two** per evaluation, only from the **default** database, and only after you grant the permission the console or CLI asks for on first deploy. Each counts as a Firestore read. - **Client-side checks are not enough.** The app can refuse to pick a 50 MB file, but any client with the project's configuration can call Storage directly; the rule is the real limit. ## What the Android app sees A denied upload fails its `UploadTask` with a `StorageException`. The SDK maps an HTTP 403, Storage's permission failure, to `ERROR_NOT_AUTHORIZED`, and an HTTP 401 to `ERROR_NOT_AUTHENTICATED`. The app should treat a denial as final, not retry it, and show the reason it can infer, such as file too large or wrong type. The content type deserves care on the client too. For `putFile`, the Android SDK sends the content type from the upload's `StorageMetadata`; if none is set it asks the `ContentResolver` for the `Uri`'s type, and if that is empty it sends `application/octet-stream`, which a strict PDF rule rejects. Setting it explicitly with `StorageMetadata.Builder().setContentType("application/pdf")` keeps legitimate uploads from failing the check. ## Testing it The Storage emulator evaluates the same rules locally. With the rules-unit-testing library, an `authenticatedContext` for the owner should upload a small PDF, while uploads that are too large, of the wrong type, or into another student's folder should fail, and an unauthenticated context should be denied everything except what the rules deliberately leave public.
- A legitimate PDF upload from the Android app is denied by the contentType check; what is the likely cause?For `putFile`, the SDK uses the content type in the upload's `StorageMetadata`, otherwise the `ContentResolver`'s type for the `Uri`, otherwise `application/octet-stream`. A `Uri` the resolver cannot type therefore arrives as octet-stream and fails `contentType == 'application/pdf'`. Set the type explicitly with `StorageMetadata.Builder().setContentType("application/pdf")`.
- How can a Storage rule let only teachers of a class read its submissions?Three sources work. A custom claim, such as a class ID in `request.auth.token`, costs nothing but changes only with a new ID token. Custom metadata on the object, read as `resource.metadata`, must be set by whoever uploads the object or later updates its metadata. A `firestore.exists()` on a teachers document is current but limited to two Firestore reads per evaluation and the default database.
- Storage rules can inspect the uploaded file's bytes to confirm it is a PDF.
- A size check on resource.size limits how large an upload can be.
- Storage rules can call firestore.get() as many times as needed.
- Limiting file size in the Android picker makes a size rule unnecessary.
- Storage rules go in the same service block as the Firestore rules.