Skip to content

Cloud Storage Security

This section covers security best practices for Firebase Cloud Storage, including access control and file validation.

Overview

Firebase Cloud Storage allows users to upload and download files, but without proper security rules, it can become a significant security and billing risk. This section covers comprehensive security practices.

Common Security Issues

Access Control

Rule Configuration

Validation and Constraints

User Ownership and Metadata

App Check Integration

Best Practices

Access Control

  1. Start with deny-all rules and explicitly grant permissions
  2. Validate user ownership before allowing access
  3. Use path-based access control for organization
  4. Implement proper authentication checks

File Validation

  1. Restrict file types to only what's needed
  2. Set maximum file sizes to prevent abuse
  3. Validate file content beyond just extensions
  4. Sanitize file names and metadata

Security Rules Structure

  1. Use consistent path patterns for user data
  2. Implement reusable functions for common checks
  3. Test rules thoroughly before deployment
  4. Monitor storage usage and access patterns

Performance Considerations

  1. Avoid expensive operations in security rules
  2. Use efficient path matching patterns
  3. Cache frequently accessed data
  4. Monitor rule evaluation costs

Example Secure Rules

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    // Users can only access their own files
    match /users/{userId}/{allPaths=**} {
      allow read, write: if request.auth != null 
        && request.auth.uid == userId
        && isValidFile();
    }

    // Shared public read-only content
    match /public/{allPaths=**} {
      allow read;
      allow write: if request.auth != null 
        && hasAdminRole()
        && isValidFile();
    }

    function isValidFile() {
      return request.resource.size < 10 * 1024 * 1024 // 10MB
        && request.resource.contentType.matches('image/.*|application/pdf');
    }

    function hasAdminRole() {
      return request.auth.token.admin == true;
    }
  }
}