Подтвердить что ты не робот

Ограничение скорости в Firebase в правилах безопасности?

Я запустил свой первый открытый проект репозитория 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
          }
        }
      }
    }
}

Я хотел бы записывать (и читать?) в db для всего объекта "Комнаты", поэтому только один запрос может быть сделан в секунду (например).

Спасибо!

4b9b3361

Ответ 1

Хитрость заключается в том, чтобы провести аудит в последний раз, когда пользователь отправил сообщение. Затем вы можете обеспечить соблюдение времени, в течение которого каждое сообщение отправляется на основе значения аудита:

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

Посмотрите на него в действии в этой скрипте. Здесь суть того, что в скрипке:

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

Ответ 2

У меня нет достаточной репутации для записи в комментарии, но я согласен с комментарием Виктора. Если вы вставляете fb.child('messages').push(...) в цикл (т.е. for (let i = 0; i < 100; i++) {...}), то он успешно нажимает 60-80 сообщений (в этом оконном фрейме 500 м.

Вдохновленный решением Kato, я предлагаю изменить правила следующим образом:

rules: {
  users: {
    "$uid": {
      "timestamp": { // similar to Kato 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})

Это решение позволяет избежать временного окна 500 мс, нам не нужно беспокоиться о том, что клиент должен быть достаточно быстрым, чтобы нажимать сообщение в течение 500 мс. Если отправлено несколько запросов на запись (спам), они могут записывать только одну единственную клавишу в messages. При желании правило только для создания в messages предотвращает это.