title: Restrict querying by a certain child value in security rules
body: <p>I'm struggling to come up with the best way to structure part of my database and its associated security rules.</p>
  
  <p>I have chat groups, and users can be added to those groups at any point. When users are added to a group, they should be able to retrieve only the messages sent <em>after</em> that. It shouldn't be possible for them to retrieve any messages that were sent before they (the users) were added to the group.</p>
  
  <p>My first approach wrongly assumed that security rules would apply only to the data being queried.</p>
  
  <p>Simplifying it for this question, I had the following structure:</p>
  
  <pre class="lang-js prettyprint-override"><code>{
      "groups": {
          "-Kb9fw20GqapLm_b8JNE": {
              "name": "Cool people"
          }
      },
      "groupUsers": {
          "-Kb9fw20GqapLm_b8JNE": {
              "3JzxHLv4b6TcUBvFL64Tyt8dTXJ2": {
                  "timeAdded": 1230779183745
              },
              "S2GMKFPOhVhzZL7q4xAVFIHTmRC3": {
                  "timeAdded": 1480113719485
              }
          }
      },
      "groupMessages": {
          "-Kb9fw20GqapLm_b8JNE": {
              "-KbKWHv4J4XN22aLMzVa": {
                  "from": "3JzxHLv4b6TcUBvFL64Tyt8dTXJ2",
                  "text": "Hello",
                  "timeSent": "1358491277463"
              },
              "-KfHxtwef6_S9C5huGLI": {
                  "from": "S2GMKFPOhVhzZL7q4xAVFIHTmRC3",
                  "text": "Goodbye",
                  "timeSent": "1493948817230"
              }
          }
      }
  }
  </code></pre>
  
  <p>And these security rules:</p>
  
  <pre class="lang-js prettyprint-override"><code>{
      "rules": {
          "groupMessages": {
              ".indexOn": "timeSent",
              "$groupKey": {
                  ".read": "root.child('groupUsers').child(auth.uid).child($groupKey).child('timeAdded').val() &lt;= data.child('timeSent').val()"
                  ".write": "!data.exists() &amp;&amp; root.child('groupUsers').child(auth.uid).child($groupKey).exists() &amp;&amp; newData.child('from').val() === auth.uid",
              }
          }
      }
  }
  </code></pre>
  
  <p>With that, I figured I could retrieve the messages for a particular group like so:</p>
  
  <pre class="lang-js prettyprint-override"><code>var myTimeAdded = /* already retrieved from the database */;
  firebase.database()
    .ref('groupMessages/-Kb9fw20GqapLm_b8JNE')
    .orderByChild('timeSent')
    .startAt(myTimeAdded)
    .on('child_added', /* ... */);
  </code></pre>
  
  <p>But like I said, that was a wrong assumption. Any suggestion on how I could achieve this?</p>