אימות נתונים

אפשר להשתמש ב-Firebase Security Rules כדי לכתוב נתונים חדשים באופן מותנה על סמך נתונים קיימים במסד הנתונים או בקטגוריית האחסון. אפשר גם לכתוב כללים שמבצעים אימות של נתונים על ידי הגבלת פעולות כתיבה על סמך הנתונים החדשים שנכתבים. בהמשך המאמר מוסבר על כללים שמשתמשים בנתונים קיימים כדי ליצור תנאי אבטחה.

כדי לקבל מידע נוסף על כללי אימות נתונים, בוחרים מוצר בכל קטע.

הגבלות על נתונים חדשים

Cloud Firestore

אם רוצים לוודא שלא נוצר מסמך שמכיל שדה ספציפי, אפשר לכלול את השדה בתנאי allow. לדוגמה, אם רוצים למנוע יצירה של מסמכים שמכילים את השדה ranking, צריך לאסור את זה בתנאי create.

  service cloud.firestore {
    match /databases/{database}/documents {
      // Disallow
      match /cities/{city} {
        allow create: if !("ranking" in request.resource.data)
      }
    }
  }

Realtime Database

אם רוצים לוודא שנתונים שמכילים ערכים מסוימים לא יתווספו למסד הנתונים, צריך לכלול את הערך הזה בכללים ולמנוע כתיבה שלו. לדוגמה, אם רוצים למנוע כתיבה של ערכים מסוג ranking, צריך למנוע כתיבה של מסמכים עם ערכים מסוג ranking.

  {
    "rules": {
      // Write is allowed for all paths
      ".write": true,
      // Allows writes only if new data doesn't include a `ranking` child value
      ".validate": "!newData.hasChild('ranking')
    }
  }

Cloud Storage

אם רוצים לוודא שלא נוצר קובץ שמכיל מטא-נתונים ספציפיים, אפשר לכלול את המטא-נתונים בתנאי allow. לדוגמה, אם רוצים למנוע יצירה של קבצים שמכילים מטא-נתונים של ranking, צריך להגדיר זאת בתנאי create.

  service firebase.storage {
    match /b/{bucket}/o {
      match /files/{fileName} {
      // Disallow
        allow create: if !("ranking" in request.resource.metadata)
      }
    }
  }

שימוש בנתונים קיימים ב-Firebase Security Rules

Cloud Firestore

אפליקציות רבות מאחסנות מידע על בקרת גישה כשדות במסמכים במסד הנתונים. ‫Cloud Firestore Security Rules יכולה לאשר או לדחות גישה באופן דינמי על סמך נתונים במסמך:

  service cloud.firestore {
    match /databases/{database}/documents {
      // Allow the user to read data if the document has the 'visibility'
      // field set to 'public'
      match /cities/{city} {
        allow read: if resource.data.visibility == 'public';
      }
    }
  }

המשתנה resource מתייחס למסמך המבוקש, ו-resource.data הוא מיפוי של כל השדות והערכים שמאוחסנים במסמך. מידע נוסף על המשתנה resource זמין במאמרי העזרה.

כשכותבים נתונים, יכול להיות שתרצו להשוות בין הנתונים הנכנסים לבין הנתונים הקיימים. כך תוכלו לוודא ששדה מסוים לא השתנה, שערך בשדה מסוים גדל רק באחד, או שהערך החדש הוא לפחות שבוע קדימה. במקרה כזה, אם קבוצת הכללים מאפשרת את הכתיבה בהמתנה, המשתנה request.resource מכיל את המצב העתידי של המסמך. בפעולות update שמשנות רק קבוצת משנה של שדות המסמך, המשתנה request.resource יכיל את מצב המסמך בהמתנה אחרי הפעולה. כדי למנוע עדכוני נתונים לא רצויים או לא עקביים, אפשר לבדוק את ערכי השדות ב-request.resource:

   service cloud.firestore {
     match /databases/{database}/documents {
      // Make sure all cities have a positive population and
      // the name is not changed
      match /cities/{city} {
        allow update: if request.resource.data.population > 0
                      && request.resource.data.name == resource.data.name;
      }
    }
  }

Realtime Database

ב-Realtime Database, משתמשים בכללי .validate כדי לאכוף מבני נתונים ולאמת את הפורמט והתוכן של הנתונים. Rules להפעיל כללי .validate אחרי שמוודאים שכלל .write מעניק גישה.

הכללים .validate לא מועברים באופן היררכי. אם כלל אימות כלשהו נכשל בכל נתיב או נתיב משנה בכלל, פעולת הכתיבה כולה תידחה. בנוסף, הפונקציה validate definitions בודקת רק ערכים שאינם null, ואז מתעלמת מכל בקשה למחיקת נתונים.

כדאי לשים לב לכללים הבאים של .validate:

  {
    "rules": {
      // write is allowed for all paths
      ".write": true,
      "widget": {
        // a valid widget must have attributes "color" and "size"
        // allows deleting widgets (since .validate is not applied to delete rules)
        ".validate": "newData.hasChildren(['color', 'size'])",
        "size": {
          // the value of "size" must be a number between 0 and 99
          ".validate": "newData.isNumber() &&
                        newData.val() >= 0 &&
                        newData.val() <= 99"
        },
        "color": {
          // the value of "color" must exist as a key in our mythical
          // /valid_colors/ index
          ".validate": "root.child('valid_colors/' + newData.val()).exists()"
        }
      }
    }
  }

אם תכתבו בקשות למסד נתונים עם הכללים שלמעלה, תקבלו את התוצאות הבאות:

JavaScript
var ref = db.ref("/widget");

// PERMISSION_DENIED: does not have children color and size
ref.set('foo');

// PERMISSION DENIED: does not have child color
ref.set({size: 22});

// PERMISSION_DENIED: size is not a number
ref.set({ size: 'foo', color: 'red' });

// SUCCESS (assuming 'blue' appears in our colors list)
ref.set({ size: 21, color: 'blue'});

// If the record already exists and has a color, this will
// succeed, otherwise it will fail since newData.hasChildren(['color', 'size'])
// will fail to validate
ref.child('size').set(99);
Objective-C
הערה: מוצר Firebase הזה לא זמין ביעד App Clip.
FIRDatabaseReference *ref = [[[FIRDatabase database] reference] child: @"widget"];

// PERMISSION_DENIED: does not have children color and size
[ref setValue: @"foo"];

// PERMISSION DENIED: does not have child color
[ref setValue: @{ @"size": @"foo" }];

// PERMISSION_DENIED: size is not a number
[ref setValue: @{ @"size": @"foo", @"color": @"red" }];

// SUCCESS (assuming 'blue' appears in our colors list)
[ref setValue: @{ @"size": @21, @"color": @"blue" }];

// If the record already exists and has a color, this will
// succeed, otherwise it will fail since newData.hasChildren(['color', 'size'])
// will fail to validate
[[ref child:@"size"] setValue: @99];
Swift
הערה: מוצר Firebase הזה לא זמין ביעד App Clip.
var ref = FIRDatabase.database().reference().child("widget")

// PERMISSION_DENIED: does not have children color and size
ref.setValue("foo")

// PERMISSION DENIED: does not have child color
ref.setValue(["size": "foo"])

// PERMISSION_DENIED: size is not a number
ref.setValue(["size": "foo", "color": "red"])

// SUCCESS (assuming 'blue' appears in our colors list)
ref.setValue(["size": 21, "color": "blue"])

// If the record already exists and has a color, this will
// succeed, otherwise it will fail since newData.hasChildren(['color', 'size'])
// will fail to validate
ref.child("size").setValue(99);
Java
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("widget");

// PERMISSION_DENIED: does not have children color and size
ref.setValue("foo");

// PERMISSION DENIED: does not have child color
ref.child("size").setValue(22);

// PERMISSION_DENIED: size is not a number
Map<String,Object> map = new HashMap<String, Object>();
map.put("size","foo");
map.put("color","red");
ref.setValue(map);

// SUCCESS (assuming 'blue' appears in our colors list)
map = new HashMap<String, Object>();
map.put("size", 21);
map.put("color","blue");
ref.setValue(map);

// If the record already exists and has a color, this will
// succeed, otherwise it will fail since newData.hasChildren(['color', 'size'])
// will fail to validate
ref.child("size").setValue(99);
REST
# PERMISSION_DENIED: does not have children color and size
curl -X PUT -d 'foo' \
https://docs-examples.firebaseio.com/rest/securing-data/example.json

# PERMISSION DENIED: does not have child color
curl -X PUT -d '{"size": 22}' \
https://docs-examples.firebaseio.com/rest/securing-data/example.json

# PERMISSION_DENIED: size is not a number
curl -X PUT -d '{"size": "foo", "color": "red"}' \
https://docs-examples.firebaseio.com/rest/securing-data/example.json

# SUCCESS (assuming 'blue' appears in our colors list)
curl -X PUT -d '{"size": 21, "color": "blue"}' \
https://docs-examples.firebaseio.com/rest/securing-data/example.json

# If the record already exists and has a color, this will
# succeed, otherwise it will fail since newData.hasChildren(['color', 'size'])
# will fail to validate
curl -X PUT -d '99' \
https://docs-examples.firebaseio.com/rest/securing-data/example/size.json

Cloud Storage

כשמעריכים כללים, כדאי גם להעריך את המטא-נתונים של הקובץ שמועלה, מורד, משתנה או נמחק. כך תוכלו ליצור כללים מורכבים ועוצמתיים שיאפשרו לכם, למשל, להעלות רק קבצים עם סוגי תוכן מסוימים, או למחוק רק קבצים שגדולים מגודל מסוים.

אובייקט resource מכיל צמדי מפתח/ערך עם מטא-נתונים של קובץ שמוצגים באובייקט Cloud Storage. אפשר לבדוק את המאפיינים האלה בבקשות אל read או אל write כדי לוודא את שלמות הנתונים. אובייקט resource בודק את המטא-נתונים של קבצים קיימים בקטגוריית Cloud Storage.

  service firebase.storage {
    match /b/{bucket}/o {
      match /images {
        match /{fileName} {
          // Allow reads if a custom 'visibility' field is set to 'public'
          allow read: if resource.metadata.visibility == 'public';
        }
      }
    }
  }

אפשר גם להשתמש באובייקט request.resource בבקשות write (כמו העלאות, עדכוני מטא-נתונים ומחיקות). האובייקט request.resource מקבל מטא-נתונים מהקובץ שייכתב אם הפעולה write מותרת.

אפשר להשתמש בשני הערכים האלה כדי למנוע עדכונים לא רצויים או לא עקביים, או כדי לאכוף מגבלות על האפליקציה, כמו סוג או גודל הקובץ.

  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
        }
      }
    }
  }

רשימה מלאה של המאפיינים באובייקט resource זמינה במסמכי העזר.