המדריך הזה מבוסס על המדריך למידת שפת הליבה של כללי האבטחה של Firebase, ומסביר איך להוסיף תנאים לכללי האבטחה של מסד נתונים בזמן אמת ב-Firebase.
אבן הבניין העיקרית של כללי האבטחה של מסד נתונים בזמן אמת היא התנאי. תנאי הוא ביטוי בוליאני שקובע אם לאשר או לדחות פעולה מסוימת. בכללים בסיסיים, אפשר להשתמש בערכים המילוליים true ו-false כתנאים. אבל שפת כללי האבטחה של מסד נתונים בזמן אמת מאפשרת לכם לכתוב תנאים מורכבים יותר, שיכולים:
- בדיקת אימות המשתמשים
- הערכת נתונים קיימים בהשוואה לנתונים חדשים שנשלחו
- גישה לחלקים שונים של מסד הנתונים והשוואה ביניהם
- אימות נתונים נכנסים
- שימוש במבנה של שאילתות נכנסות ללוגיקת אבטחה
שימוש במשתני $ כדי לתעד פלחים של נתיבים
כדי לתעד חלקים מהנתיב לקריאה או לכתיבה, אפשר להצהיר על משתני תיעוד עם הקידומת $.
הוא משמש כתו כללי לחיפוש ושומר את הערך של המפתח הזה לשימוש בתנאים של כללים:
{ "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 בכללי האבטחה של מסד הנתונים בזמן אמת יאוכלס בפרטי המשתמש. המידע הזה כולל את המזהה הייחודי שלהם (uid), נתונים של חשבונות מקושרים כמו מזהה פייסבוק או כתובת אימייל, ומידע נוסף. אם אתם מטמיעים ספק אימות בהתאמה אישית, אתם יכולים להוסיף שדות משלכם למטען הייעודי (payload) של אימות המשתמש.
בקטע הזה מוסבר איך לשלב את שפת כללי האבטחה של מסד נתונים בזמן אמת ב-Firebase עם פרטי האימות של המשתמשים. שילוב שני המושגים האלה מאפשר לכם לשלוט בגישה לנתונים על סמך זהות המשתמש.
המשתנה auth
המשתנה המוגדר מראש auth בכללים הוא null לפני שמתבצע אימות.
אחרי שמשתמש מאומת באמצעות אימות ב-Firebase, הוא יכיל את המאפיינים הבאים:
| ספק | שיטת האימות שבה נעשה שימוש ("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"
}
}
}
}הגדרת המבנה של מסד הנתונים לתמיכה בתנאי אימות
בדרך כלל כדאי לבנות את מסד הנתונים באופן שיקל על כתיבת Security Rules. דפוס נפוץ לאחסון נתוני משתמשים ב-Realtime Database הוא לאחסן את כל המשתמשים בצומת users יחיד, שהצאצאים שלו הם ערכי ה-uid של כל משתמש. אם אתם רוצים להגביל את הגישה לנתונים האלה כך שרק המשתמש שמחובר לחשבון יוכל לראות את הנתונים שלו, הכללים שלכם ייראו בערך כך:
{
"rules": {
"users": {
"$uid": {
".read": "auth !== null && auth.uid === $uid"
}
}
}
}עבודה עם טענות נכונות (claims) מותאמות אישית לאימות
באפליקציות שדורשות בקרת גישה בהתאמה אישית למשתמשים שונים, Firebase Authentication מאפשר למפתחים להגדיר טענות נכונות (claims) למשתמש Firebase.
הטענות האלה נגישות במשתנה auth.token בכללים שלכם.
הנה דוגמה לכללים שמשתמשים בטענה הנכונה (claim) המותאמת אישית hasEmergencyTowel:
{
"rules": {
"frood": {
// A towel is about the most massively useful thing an interstellar
// hitchhiker can have
".read": "auth.token.hasEmergencyTowel === true"
}
}
}מפתחים שיוצרים אסימוני אימות בהתאמה אישית יכולים להוסיף להם הצהרות. ההצהרות האלה זמינות במשתנה 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 מצליח להעניק גישה. למטה מוצגת הגדרת כלל לדוגמה של .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. כדאי להביא בחשבון את הכללים הבאים:
{
"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
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
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 *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
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. זמינים בכללי האבטחה של מסד נתונים בזמן אמת.
| ביטויים של כללים שמבוססים על שאילתות | ||
|---|---|---|
| Expression | סוג | תיאור |
| 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 אם לא הוגדרה מגבלה. |
השלבים הבאים
אחרי הדיון הזה בתנאים, יש לכם הבנה מעמיקה יותר של Security Rules ואתם מוכנים:
איך מטפלים בתרחישי שימוש עיקריים, ואיך פועל תהליך העבודה לפיתוח, לבדיקה ולפריסה של Security Rules:
- מידע על כל Security Rules המשתנים המוגדרים מראש שאפשר להשתמש בהם כדי ליצור תנאים.
- כתבו כללים שמתייחסים לתרחישים נפוצים.
- כדי להרחיב את הידע שלכם, כדאי לעיין במצבים שבהם צריך לזהות כללים לא מאובטחים ולהימנע מהם.
- מידע ולמידה על הכלים לאמולטור מקומי ב-Firebase ואיך אפשר להשתמש בהם כדי לבחון Security Rules.
- בודקים את השיטות הזמינות לפריסת Security Rules.
מידע על תכונות של Security Rules שספציפיות ל-Realtime Database: