שימוש בתנאים בכללי האבטחה של מסדי נתונים בזמן אמת

המדריך הזה מבוסס על המדריך לומדים את השפה הבסיסית של כללי האבטחה של Firebase. במדריך הזה מוסבר איך להוסיף תנאים לכללי האבטחה של Firebase Realtime Database.

אבן הבניין העיקרית של כללי האבטחה של Realtime Database היא התנאי. תנאי הוא ביטוי בוליאני שקובע אם פעולה מסוימת צריכה להיות מותרת או אסורה. בכללים בסיסיים, שימוש במחרוזות true ו-false כבתנאים פועל בצורה מושלמת. אבל שפת כללי האבטחה של Realtime Database מאפשרת לכם לכתוב תנאים מורכבים יותר שיכולים:

  • בדיקת אימות משתמשים
  • הערכת נתונים קיימים מול נתונים חדשים שנשלחו
  • גישה לחלקים שונים של מסד הנתונים והשוואה ביניהם
  • אימות נתונים נכנסים
  • שימוש במבנה של שאילתות נכנסות ללוגיקת אבטחה

שימוש במשתנים מסוג $ כדי לתעד פלחים של נתיבים

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

{
  "rules": {
    "rooms": {
      // this rule applies to any child of /rooms/, the key for each room id
      // is stored inside $room_id variable for reference
      "$room_id": {
        "topic": {
          // the room's topic can be changed if the room id has "public" in it
          ".write": "$room_id.contains('public')"
        }
      }
    }
  }
}

אפשר להשתמש במשתני $ דינמיים גם במקביל לשמות נתיבים קבועים. בדוגמה הזו, אנחנו משתמשים במשתנה $other כדי להצהיר על כלל .validate שמבטיח של-widget אין צאצאים מלבד title ו-color. כל פעולת כתיבה שתגרום ליצירה של צאצאים נוספים תיכשל.

{
  "rules": {
    "widget": {
      // a widget can have a title or color attribute
      "title": { ".validate": true },
      "color": { ".validate": true },

      // but no other child paths are allowed
      // in this case, $other means any key excluding "title" and "color"
      "$other": { ".validate": false }
    }
  }
}

אימות

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

אם האפליקציה משתמשת באימות ב-Firebase, המשתנה request.auth מכיל את פרטי האימות של הלקוח שמבקש נתונים. מידע נוסף על request.auth זמין במסמכי העזרה.

Firebase Authentication משתלב עם Firebase Realtime Database כדי לאפשר לכם לשלוט בגישה לנתונים על בסיס משתמש באמצעות תנאים. אחרי שהמשתמש מאומת, המשתנה auth בכללים שלכם ל-Realtime Database Security Rules יאוכלס בפרטי המשתמש. המידע הזה כולל את המזהה הייחודי של המשתמש (uid), וגם נתונים של חשבונות מקושרים, כמו מזהה בפייסבוק או כתובת אימייל, ומידע נוסף. אם מטמיעים ספק אימות מותאם אישית, אפשר להוסיף שדות משלכם למטען הייעודי (payload) של האימות של המשתמש.

בקטע הזה מוסבר איך לשלב את שפת כללי האבטחה של Firebase Realtime Database עם פרטי אימות לגבי המשתמשים שלכם. שילוב של שני המושגים האלה מאפשר לכם לשלוט בגישה לנתונים על סמך זהות המשתמש.

המשתנה auth

המשתנה auth שמוגדר מראש בכללים הוא null לפני שהאימות מתבצע.

אחרי שמשתמש מאומת באמצעות אימות ב-Firebase, הוא יכיל את המאפיינים הבאים:

provider שיטת האימות שבה נעשה שימוש (password,‏ anonymous,‏ facebook,‏ github,‏ google או twitter).
uid מזהה משתמש ייחודי, שמובטח שהוא ייחודי אצל כל הספקים.
token התוכן של אסימון המזהה של Firebase Auth. מידע נוסף מופיע במאמרי העזרה של auth.token.

הנה דוגמה לכלל שמשתמש במשתנה auth כדי לוודא שכל משתמש יכול לכתוב רק לנתיב ספציפי למשתמש:

{
  "rules": {
    "users": {
      "$user_id": {
        // grants write access to the owner of this user account
        // whose uid must exactly match the key ($user_id)
        ".write": "$user_id === auth.uid"
      }
    }
  }
}

הגדרת מבנה מסד הנתונים לתמיכה בתנאי אימות

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

{
  "rules": {
    "users": {
      "$uid": {
        ".read": "auth !== null && auth.uid === $uid"
      }
    }
  }
}

עבודה עם טענות בהתאמה אישית לאימות

באפליקציות שבהן נדרשת בקרת גישה מותאמת אישית למשתמשים שונים, Firebase Authentication המפתחים יכולים להגדיר טענות לגבי משתמש ב-Firebase. אפשר לגשת לטענות האלה במשתנה auth.token בכללים. הנה דוגמה לכללים שמשתמשים בהצהרה מותאמת אישית: hasEmergencyTowel

{
  "rules": {
    "frood": {
      // A towel is about the most massively useful thing an interstellar
      // hitchhiker can have
      ".read": "auth.token.hasEmergencyTowel === true"
    }
  }
}

מפתחים שיוצרים אסימוני אימות מותאמים אישית משלהם יכולים להוסיף לאסימונים האלה טענות (claims). הטענות האלה זמינות במשתנה auth.token בכללים.

נתונים קיימים לעומת נתונים חדשים

המשתנה המוגדר מראש data משמש להפניה לנתונים לפני שמתבצעת פעולת כתיבה. לעומת זאת, המשתנה newData מכיל את הנתונים החדשים שיהיו קיימים אם פעולת הכתיבה תצליח. ‫newData מייצג את התוצאה הממוזגת של הנתונים החדשים שנכתבים ושל הנתונים הקיימים.

לדוגמה, הכלל הזה יאפשר לנו ליצור רשומות חדשות או למחוק רשומות קיימות, אבל לא לבצע שינויים בנתונים קיימים שאינם null:

// we can write as long as old data or new data does not exist
// in other words, if this is a delete or a create, but not an update
".write": "!data.exists() || !newData.exists()"

הפניה לנתונים בנתיבים אחרים

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

לדוגמה, הפעולות הבאות מותרות אם הערך של הצומת /allow_writes/ הוא true, בצומת האב לא מוגדר הדגל readOnly, ובנתונים החדשים שייכתבו יש צומת צאצא בשם foo:

".write": "root.child('allow_writes').val() === true &&
          !data.parent().child('readOnly').exists() &&
          newData.child('foo').exists()"

אימות נתונים

כדי לאכוף את מבני הנתונים ולאמת את הפורמט והתוכן של הנתונים, צריך להשתמש ב.validateכללים.write, שמופעלים רק אחרי שכלל .writeמצליח להעניק גישה. בהמשך מופיעה דוגמה להגדרת כלל .validateשמאפשר רק תאריכים בפורמט YYYY-MM-DD בין השנים 1900 ל-2099, שנבדקים באמצעות ביטוי רגולרי.

".validate": "newData.isString() &&
              newData.val().matches(/^(19|20)[0-9][0-9][-\\/. ](0[1-9]|1[012])[-\\/. ](0[1-9]|[12][0-9]|3[01])$/)"

.validate הכללים הם הסוג היחיד של כללי אבטחה שלא מועברים הלאה. אם כלל אימות כלשהו נכשל ברשומה של צאצא כלשהו, פעולת הכתיבה כולה תידחה. בנוסף, המערכת מתעלמת מהגדרות האימות כשמוחקים נתונים (כלומר, כשהערך החדש שנכתב הוא null).

אולי נראה שמדובר בנקודות לא חשובות, אבל למעשה אלה תכונות משמעותיות לכתיבת כללי אבטחה יעילים ל-Firebase Realtime Database. כדאי להביא בחשבון את הכללים הבאים:

{
  "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

עכשיו נסתכל על אותו מבנה, אבל נשתמש בכללי .write במקום .validate:

{
  "rules": {
    // this variant will NOT allow deleting records (since .write would be disallowed)
    "widget": {
      // a widget must have 'color' and 'size' in order to be written to this path
      ".write": "newData.hasChildren(['color', 'size'])",
      "size": {
        // the value of "size" must be a number between 0 and 99, ONLY IF WE WRITE DIRECTLY TO SIZE
        ".write": "newData.isNumber() && newData.val() >= 0 && newData.val() <= 99"
      },
      "color": {
        // the value of "color" must exist as a key in our mythical valid_colors/ index
        // BUT ONLY IF WE WRITE DIRECTLY TO COLOR
        ".write": "root.child('valid_colors/'+newData.val()).exists()"
      }
    }
  }
}

בגרסה הזו, כל אחת מהפעולות הבאות תצליח:

JavaScript
var ref = new Firebase(URL + "/widget");

// ALLOWED? Even though size is invalid, widget has children color and size,
// so write is allowed and the .write rule under color is ignored
ref.set({size: 99999, color: 'red'});

// ALLOWED? Works even if widget does not exist, allowing us to create a widget
// which is invalid and does not have a valid color.
// (allowed by the write rule under "color")
ref.child('size').set(99);
Objective-C
הערה: מוצר Firebase הזה לא זמין ביעד App Clip.
Firebase *ref = [[Firebase alloc] initWithUrl:URL];

// ALLOWED? Even though size is invalid, widget has children color and size,
// so write is allowed and the .write rule under color is ignored
[ref setValue: @{ @"size": @9999, @"color": @"red" }];

// ALLOWED? Works even if widget does not exist, allowing us to create a widget
// which is invalid and does not have a valid color.
// (allowed by the write rule under "color")
[[ref childByAppendingPath:@"size"] setValue: @99];
Swift
הערה: מוצר Firebase הזה לא זמין ביעד App Clip.
var ref = Firebase(url:URL)

// ALLOWED? Even though size is invalid, widget has children color and size,
// so write is allowed and the .write rule under color is ignored
ref.setValue(["size": 9999, "color": "red"])

// ALLOWED? Works even if widget does not exist, allowing us to create a widget
// which is invalid and does not have a valid color.
// (allowed by the write rule under "color")
ref.childByAppendingPath("size").setValue(99)
Java
Firebase ref = new Firebase(URL + "/widget");

// ALLOWED? Even though size is invalid, widget has children color and size,
// so write is allowed and the .write rule under color is ignored
Map<String,Object> map = new HashMap<String, Object>();
map.put("size", 99999);
map.put("color", "red");
ref.setValue(map);

// ALLOWED? Works even if widget does not exist, allowing us to create a widget
// which is invalid and does not have a valid color.
// (allowed by the write rule under "color")
ref.child("size").setValue(99);
REST
# ALLOWED? Even though size is invalid, widget has children color and size,
# so write is allowed and the .write rule under color is ignored
curl -X PUT -d '{size: 99999, color: "red"}' \
https://docs-examples.firebaseio.com/rest/securing-data/example.json

# ALLOWED? Works even if widget does not exist, allowing us to create a widget
# which is invalid and does not have a valid color.
# (allowed by the write rule under "color")
curl -X PUT -d '99' \
https://docs-examples.firebaseio.com/rest/securing-data/example/size.json

כך אפשר לראות את ההבדלים בין כללי .write לבין כללי .validate. כפי שמוצג, צריך לכתוב את כל הכללים האלה באמצעות .validate, אולי למעט הכלל newData.hasChildren(), שיהיה תלוי בשאלה אם צריך לאפשר מחיקות.

כללים מבוססי-שאילתות

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

לדוגמה, הכלל הבא שמבוסס על שאילתה משתמש בכללי אבטחה שמבוססים על משתמשים ובכללים שמבוססים על שאילתות כדי להגביל את הגישה לנתונים באוסף baskets רק לעגלות הקניות שהמשתמש הפעיל הוא הבעלים שלהן:

"baskets": {
  ".read": "auth.uid !== null &&
            query.orderByChild === 'owner' &&
            query.equalTo === auth.uid" // restrict basket access to owner of basket
}

השאילתה הבאה, שכוללת את הפרמטרים של השאילתה בכלל, תצליח:

db.ref("baskets").orderByChild("owner")
                 .equalTo(auth.currentUser.uid)
                 .on("value", cb)                 // Would succeed

עם זאת, שאילתות שלא כוללות את הפרמטרים בכלל ייכשלו עם השגיאה PermissionDenied:

db.ref("baskets").on("value", cb)                 // Would fail with PermissionDenied

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

לדוגמה, הכלל הבא מגביל את גישת הקריאה ל-1,000 התוצאות הראשונות של שאילתה, לפי סדר העדיפות:

messages: {
  ".read": "query.orderByKey &&
            query.limitToFirst <= 1000"
}

// Example queries:

db.ref("messages").on("value", cb)                // Would fail with PermissionDenied

db.ref("messages").limitToFirst(1000)
                  .on("value", cb)                // Would succeed (default order by key)

הביטויים הבאים של query. זמינים בכללי האבטחה של Realtime Database.

ביטויים של כללים מבוססי-שאילתות
ביטוי סוג תיאור
query.orderByKey
query.orderByPriority
query.orderByValue
בוליאני הערך True עבור שאילתות שממוינות לפי מפתח, עדיפות או ערך. אחרת, הפלט הוא False.
query.orderByChild מחרוזת
null
משתמשים במחרוזת כדי לייצג את הנתיב היחסי לצומת צאצא. לדוגמה, query.orderByChild === "address/zip". אם השאילתה לא ממוינת לפי צומת צאצא, הערך הזה הוא null.
query.startAt
query.endAt
query.equalTo
string
number
boolean
null
הפונקציה מאחזרת את הגבולות של השאילתה שמופעלת, או מחזירה null אם לא מוגדר גבול.
query.limitToFirst
query.limitToLast
מספר
null
הפונקציה מאחזרת את המגבלה על השאילתה שמופעלת, או מחזירה ערך null אם לא הוגדרה מגבלה.

השלבים הבאים

אחרי הדיון הזה על תנאים, יש לך הבנה מורכבת יותר של Rules ואתה מוכן:

כאן מוסבר איך לטפל בתרחישי שימוש מרכזיים, ואיך לפתח, לבדוק ולפרוס את Rules:

מידע נוסף על התכונות של Rules שספציפיות ל-Realtime Database: