我启动了我的第一个开放式存储库项目EphChat,人们很快就开始充斥它们的请求。
Firebase是否有办法对安全规则中的限制请求进行评级?我假设有一种方法可以使用请求的时间和先前写入数据的时间来完成,但是在文档中找不到关于我将如何执行此操作的任何内容。
目前的安全规则如下。
{
"rules": {
"rooms": {
"$RoomId": {
"connections": {
".read": true,
".write": "auth.username == newData.child('FBUserId').val()"
},
"messages": {
"$any": {
".write": "!newData.exists() || root.child('rooms').child(newData.child('RoomId').val()).child('connections').hasChild(newData.child('FBUserId').val())",
".validate": "newData.hasChildren(['RoomId','FBUserId','userName','userId','message']) && newData.child('message').val().length >= 1",
".read": "root.child('rooms').child(data.child('RoomId').val()).child('connections').hasChild(data.child('FBUserId').val())"
}
},
"poll": {
".write": "auth.username == newData.child('FBUserId').val()",
".read": true
}
}
}
}
}
我想将整个Rooms对象的写入(和读取?)速率限制到db,因此每秒只能生成1个请求(例如)。
谢谢!
答案 0 :(得分:40)
诀窍是对用户上次发布消息的时间进行审核。然后,您可以根据审计值强制发布每条消息的时间:
{
"rules": {
// this stores the last message I sent so I can throttle them by timestamp
"last_message": {
"$user": {
// timestamp can't be deleted or I could just recreate it to bypass our throttle
".write": "newData.exists() && auth.uid === $user",
// the new value must be at least 5000 milliseconds after the last (no more than one message every five seconds)
// the new value must be before now (it will be since `now` is when it reaches the server unless I try to cheat)
".validate": "newData.isNumber() && newData.val() === now && (!data.exists() || newData.val() > data.val()+5000)"
}
},
"messages": {
"$message_id": {
// message must have a timestamp attribute and a sender attribute
".write": "newData.hasChildren(['timestamp', 'sender', 'message'])",
"sender": {
".validate": "newData.val() === auth.uid"
},
"timestamp": {
// in order to write a message, I must first make an entry in timestamp_index
// additionally, that message must be within 500ms of now, which means I can't
// just re-use the same one over and over, thus, we've effectively required messages
// to be 5 seconds apart
".validate": "newData.val() >= now - 500 && newData.val() === data.parent().parent().parent().child('last_message/'+auth.uid).val()"
},
"message": {
".validate": "newData.isString() && newData.val().length < 500"
},
"$other": {
".validate": false
}
}
}
}
}
在行动in this fiddle中查看。这是小提琴中的主要内容:
var fb = new Firebase(URL);
var userId; // log in and store user.uid here
// run our create routine
createRecord(data, function (recordId, timestamp) {
console.log('created record ' + recordId + ' at time ' + new Date(timestamp));
});
// updates the last_message/ path and returns the current timestamp
function getTimestamp(next) {
var ref = fb.child('last_message/' + userId);
ref.set(Firebase.ServerValue.TIMESTAMP, function (err) {
if (err) { console.error(err); }
else {
ref.once('value', function (snap) {
next(snap.val());
});
}
});
}
function createRecord(data, next) {
getTimestamp(function (timestamp) {
// add the new timestamp to the record data
var data = {
sender: userId,
timestamp: timestamp,
message: 'hello world'
};
var ref = fb.child('messages').push(data, function (err) {
if (err) { console.error(err); }
else {
next(ref.name(), timestamp);
}
});
})
}
答案 1 :(得分:2)
我没有足够的声誉写在评论中,但我同意Victor的评论。如果您将fb.child('messages').push(...)
插入循环(即for (let i = 0; i < 100; i++) {...}
),那么它将成功推送60-80个会话(在500毫秒的窗口框架中。
受Kato解决方案的启发,我建议修改规则如下:
rules: {
users: {
"$uid": {
"timestamp": { // similar to Kato's answer
".write": "auth.uid === $uid && newData.exists()"
,".read": "auth.uid === $uid"
,".validate": "newData.hasChildren(['time', 'key'])"
,"time": {
".validate": "newData.isNumber() && newData.val() === now && (!data.exists() || newData.val() > data.val() + 1000)"
}
,"key": {
}
}
,"messages": {
"$key": { /// this key has to be the same is the key in timestamp (checked by .validate)
".write": "auth.uid === $uid && !data.exists()" ///only 'create' allow
,".validate": "newData.hasChildren(['message']) && $key === root.child('/users/' + $uid + '/timestamp/key').val()"
,"message": { ".validate": "newData.isString()" }
/// ...and any other datas such as 'time', 'to'....
}
}
}
}
}
.js代码与Kato的解决方案非常相似,只是getTimestamp会将{time:number,key:string}返回到下一个回调。然后我们只需要ref.update({[key]: data})
这个解决方案避免了500ms的时间窗口,我们不必担心客户端必须足够快以在500ms内推送消息。如果发送多个写入请求(垃圾邮件),则它们只能写入messages
中的1个单个密钥。 (可选)messages
中的仅限创建规则可防止这种情况发生。
答案 2 :(得分:0)
现有答案使用两个数据库更新:(1)标记时间戳,以及(2)将标记的时间戳附加到实际写入。 Kato的答案需要500毫秒的时间窗口,而ChiNhan的答案则需要记住下一个键。
有一个更简单的方法可以在单个数据库更新中完成。这个想法是使用update()方法一次将多个值写入数据库。安全规则将验证写入的值,以使写入不超过配额。配额定义为一对值: quotaTimestamp 和 postCount 。 postCount是在quotaTimestamp的1分钟内写入的帖子数。如果postCount超过某个值,则安全规则仅拒绝下一次写入。当quotaTimestamp超过1分钟时,将重置postCount。
以下是发布新消息的方法:
function postMessage(user, message) {
const now = Date.now() + serverTimeOffset;
if (!user.quotaTimestamp || user.quotaTimestamp + 60 * 1000 < now) {
// Resets the quota when 1 minute has elapsed since the quotaTimestamp.
user.quotaTimestamp = database.ServerValue.TIMESTAMP;
user.postCount = 0;
}
user.postCount++;
const values = {};
const messageId = // generate unique id
values[`users/${user.uid}/quotaTimestamp`] = user.quotaTimestamp;
values[`users/${user.uid}/postCount`] = user.postCount;
values[`messages/${messageId}`] = {
sender: ...,
message: ...,
...
};
return this.db.database.ref().update(values);
}
安全规则将每分钟最多限制5个帖子:
{
"rules": {
"users": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid && newData.child('postCount').val() <= 5",
"quotaTimestamp": {
// Only allow updating quotaTimestamp if it's staler than 1 minute.
".validate": "
newData.isNumber()
&& (newData.val() === now
? (data.val() + 60 * 1000 < now)
: (data.val() == newData.val()))"
},
"postCount": {
// Only allow postCount to be incremented by 1
// or reset to 1 when the quotaTimestamp is being refreshed.
".validate": "
newData.isNumber()
&& (data.exists()
? (data.val() + 1 === newData.val()
|| (newData.val() === 1
&& newData.parent().child('quotaTimestamp').val() === now))
: (newData.val() === 1))"
},
"$other": { ".validate": false }
}
},
"messages": {
...
}
}
}
注意:serverTimeOffset应该保持以避免时钟偏斜。
答案 3 :(得分:0)
我喜欢 Kato's answer,但它没有考虑恶意用户仅使用 for 循环就淹没 500 毫秒窗口之间的聊天。 我提出了这个消除可能性的变体:
{
"rules": {
"users": {
"$uid": {
"rateLimit": {
"lastMessage": {
// newData.exists() ensures newData is not null and prevents deleting node
// and $uid === auth.uid ensures the user writing this child node is the owner
".write": "newData.exists() && $uid === auth.uid",
// newData.val() === now ensures the value written is the current timestamp
// to avoid tricking the rules writting false values
// and (!data.exists() || newData.val() > data.val() + 5000)
// ensures no data exists currently in the node. Otherwise it checks if the
// data that will overwrite the node is a value higher than the current timestamp
// plus the value that will rate limit our messages expressed in milliseconds.
// In this case a value of 5000 means that we can only send a message if
// the last message we sent was more than 5 seconds ago
".validate": "newData.val() === now && (!data.exists() || newData.val() > data.val() + 5000)"
}
}
}
},
"messages": {
"$messageId": {
// This rule ensures that we write lastMessage node avoiding just sending the message without
// registering a new timestamp
".write": "newData.parent().parent().child('users').child(auth.uid).child('rateLimit').child('lastMessage').val() === now",
// This rule ensures that we have all the required message fields
".validate": "newData.hasChildren(['timestamp', 'uid', 'message'])",
"uid": {
// This rule ensures that the value written is the id of the message sender
".validate": "newData.val() === auth.uid"
},
"timestamp": {
// This rule ensures that the message timestamp can't be modified
".write": "!data.exists()",
// This rule ensures that the value written is the current timestamp
".validate": "newData.val() === now"
},
"message": {
// This rule ensures that the value written is a string
".validate": "newData.isString()"
},
"$other": {
// This rule ensures that we cant write other fields in the message other than
// the explicitly declared above
".validate": false
}
}
}
}
}
代码实现使用跨多个位置的原子写入。如果一次验证失败,则操作没有完成,数据库中没有任何操作
function sendMessage(message) {
const database = firebase.database();
const pushId = database.ref().child("messages").push().key;
const userId = firebase.auth().currentUser.uid;
const timestampPlaceholder = firebase.database.ServerValue.TIMESTAMP;
let updates = {};
updates["messages/" + pushId] = {
uid: userId,
timestamp: timestampPlaceholder,
message: message,
};
updates[`users/${userId}/rateLimit/lastMessage`] = timestampPlaceholder;
database.ref().update(updates);
}