# How Security Rules work

Security can be one of the most complex pieces of the app development puzzle. In most applications, developers must build and run a server that handles authentication (who a user is) and authorization (what a user can do).

Firebase Security Rules remove the middle (server) layer and allow you to specify path-based permissions for clients that connect to your data directly. Use this guide to learn more about how rules are applied to incoming requests.

## Basic structure

Firebase Security Rules in Cloud Firestore and Cloud Storage use the following structure and syntax:

```
service <<name>> {
  // Match the resource path.
  match <<path>> {
    // Allow the request if the following conditions are true.
    allow <<methods>> : if <<condition>>
  }
}
```

The following key concepts are important to understand as you build the rules:

- **Request:** The method or methods invoked in the `allow` statement. These are methods you're allowing to run. The standard methods are: `get`, `list`, `create`, `update`, and `delete`. The `read` and `write` convenience methods enable broad read and write access on the specified database or storage path.
- **Path:** The database or storage location, represented as a URI path.
- **Rule:** The `allow` statement, which includes a condition that permits a request if it evaluates to true.

### Security rules version 2

As of May 2019, version 2 of the Security Rules security rules is now available. Version 2 of the rules changes the behavior of [recursive wildcards](/content/docs/rules/rules-behavior?hl=en#recursive_wildcards/index.html)`{name=**}`. You must use version 2 if you plan to use [collection group queries](/content/docs/firestore/query-data/queries#collection-group-query/index.html). You must opt-in to version 2 by making `rules_version = '2';` the first line in your security rules:

```
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
```

## Matching paths

All match statements should point to documents, not collections. A match statement can point to a specific document, as in `match /cities/SF` or use wildcards to point to any document in the specified path, as in `match /cities/{city}`.

In the example, the match statement uses the `{city}` wildcard syntax. This means the rule applies to any document in the `cities` collection, such as `/cities/SF` or `/cities/NYC`. When the `allow` expressions in the match statement are evaluated, the `city` variable will resolve to the city document name, such as `SF` or `NYC`.

### Matching subcollections

Data in Cloud Firestore is organized into collections of documents, and each document may extend the hierarchy through subcollections. It is important to understand how security rules interact with hierarchical data.

Consider the situation where each document in the `cities` collection contains a `landmarks` subcollection. Security rules apply only at the matched path, so the access controls defined on the `cities` collection don't apply to the `landmarks` subcollection. Instead, write explicit rules to control access to subcollections:

```
service cloud.firestore {
  match /databases/{database}/documents {
    match /cities/{city} {
      allow read, write: if <condition>;

// Explicitly define rules for the 'landmarks' subcollection
      match /landmarks/{landmark} {
        allow read, write: if <condition>;
      }
    }
  }
}
```

When nesting `match` statements, the path of the inner `match` statement is always relative to the path of the outer `match` statement. The following rulesets are therefore equivalent:

```
service cloud.firestore {
  match /databases/{database}/documents {
    match /cities/{city} {
      match /landmarks/{landmark} {
        allow read, write: if <condition>;
      }
    }
  }
}
```

```
service cloud.firestore {
  match /databases/{database}/documents {
    match /cities/{city}/landmarks/{landmark} {
      allow read, write: if <condition>;
    }
  }
}
```

#### Overlapping match statements

It's possible for a document to match more than one `match` statement. In the case where multiple `allow` expressions match a request, the access is allowed if **any** of the conditions is `true`:

```
service cloud.firestore {
  match /databases/{database}/documents {
    // Matches any document in the 'cities' collection.
    match /cities/{city} {
      allow read, write: if false;
    }

// Matches any document in the 'cities' collection.
    match /cities/{document} {
      allow read, write: if true;
    }
  }
}
```

In the example, all reads and writes to the `cities` collection will be allowed because the second rule is always `true`, even though the first rule is always `false`.

#### Recursive wildcards

If you want rules to apply to an arbitrarily deep hierarchy, use the recursive wildcard syntax, `{name=**}`:

```
service cloud.firestore {
  match /databases/{database}/documents {
    // Matches any document in the cities collection as well as any document
    // in a subcollection.
    match /cities/{document=**} {
      allow read, write: if <condition>;
    }
  }
}
```

When using the recursive wildcard syntax, the wildcard variable will contain the entire matching path segment, even if the document is located in a deeply nested subcollection. For example, the rules listed would match a document located at `/cities/SF/landmarks/coit_tower`, and the value of the `document` variable would be `SF/landmarks/coit_tower`.

### Security rule limits

As you work with security rules, note the following limits:

| Limit | Details |
| --- | --- |
| Maximum number of `exists()`, `get()`, and `getAfter()` calls per request | - 10 for single-document requests and query requests.<br>- 20 for multi-document reads, transactions,<br>   and batched writes. The previous limit of 10 also applies to each<br>   operation.<br>   <br>  <br>  For example, imagine you create a batched write request with<br>   3 write operations and that your security rules use 2 document<br>   access calls to validate each write. In this case, each write uses<br>   2 of its 10 access calls and the batched write request uses 6 of<br>   its 20 access calls.<br>   <br>  <br>Exceeding either limit results in a permission denied error.<br>Some document access calls may be cached,<br>and cached calls do not count towards the limits. |
| Maximum nested `match` statement depth | 10 |
| Maximum path length, in path segments, allowed within a set of nested<br> `match` statements | 100 |
| Maximum number of path capture variables allowed within a set of<br> nested `match` statements | 20 |
| Maximum function call depth | 20 |
| Maximum number of function arguments | 7 |
| Maximum number of `let` variable bindings per function | 10 |
| Maximum number of recursive or cyclical function calls | 0 (not permitted) |
| Maximum number of expressions evaluated per request | 1,000 |
| Maximum size of a ruleset | Rulesets must obey two size limits:<br> <br>- a 256 KB limit on the size of the ruleset text source<br>   published from the Firebase console or from the CLI using<br>   `firebase deploy`.<br>   <br>- a 250 KB limit on the size of the compiled ruleset that results<br>   when Firebase processes the source and makes it active on the<br>   back-end. |

## Full Example

Putting it all together, you can create a full example of rules for an image storage solution:

```
service firebase.storage {
 match /b/{bucket}/o {
   match /images {
     // Allow write files to the path "images/*", subject to the constraints:
     // 1) File is less than 5MB
     // 2) Content type is an image
     // 3) Uploaded content type matches existing content type
     // 4) Filename (stored in imageId wildcard variable) is less than 32 characters
     match /{imageId} {
       allow read;
       allow write: if request.resource.size < 5 * 1024 * 1024
                    && request.resource.contentType.matches('image/.*')
                    && request.resource.contentType == resource.contentType
                    && imageId.size() < 32
     }
   }
 }
}
```

## Basic structure

In Realtime Database, Firebase Security Rules consist of JavaScript-like expressions contained in a JSON document.

They use the following syntax:

```
{
  "rules": {
    "<<path>>": {
    // Allow the request if the condition for each method is true.
      ".read": <<condition>>,  
      ".write": <<condition>>,  
      ".validate": <<condition>>
    }
  }
}
```

There are three basic elements in the rule:

- **Path:** The database location. This mirrors your database's JSON structure.
- **Request:** These are the methods the rule uses to grant access. The `read`
and `write` rules grant broad read and write access, while `validate` rules
act as a secondary verification to grant access based on incoming or existing
data.
- **Condition:** The condition that permits a request if it evaluates to true.

## How rules apply to paths

In Realtime Database, Security Rules apply atomically, meaning that rules at
higher-level parent nodes override rules at more granular child nodes and
rules at a deeper node can't grant access to a parent path. You
can't refine or revoke access at a deeper path in your database structure if
you've already granted it for one of the parent paths.

Consider the following rules:

```
{
  "rules": {
     "foo": {
        // allows read to /foo/*
        ".read": "data.child('baz').val() === true",
        "bar": {
          // ignored, since read was allowed already
          ".read": false
        }
     }
  }
}
```

This security structure allows `/bar/` to be read from whenever
`/foo/` contains a child `baz` with value `true`. The `".read": false` rule under `/foo/bar/` has no effect here, since access cannot be revoked by a child path.

While it may not seem immediately intuitive, this is a powerful part of the
rules language and allows for very complex access privileges to be implemented
with minimal effort. This is particularly useful for [user-based security](/content/docs/rules/rules-and-auth/index.html).

However, [".validate" rules](/content/docs/rules/data-validation/index.html) do not cascade. All validate rules
must be satisfied at all levels of the hierarchy for a write to be allowed.

Additionally, because rules do not apply back to a parent path, read or write
operation fail if there isn't a rule at the requested location or at a parent
location that grants access. Even if every affected child path is accessible,
reading at the parent location will fail completely.
