ユーザーとグループのデータアクセスを保護する

コラボレーション アプリの多くは、さまざまなデータへの読み書きを権限のセットに基づいて許可します。たとえば、ドキュメント編集アプリでは、限られたユーザーにドキュメントの読み書きを許可すると同時に、不要なアクセスをブロックすることが必要になる場合があります。

解決策: ロールベースのアクセス制御

Cloud Firestore のデータモデルとカスタム セキュリティ ルールを活用し、アプリにロールベースのアクセス制御を実装することができます。

たとえば、次のセキュリティ要件で「ストーリー」と「コメント」を作成できる文章作成のコラボレーション アプリを構築しているとします。

  • 各ストーリーには所有者が 1 人存在する。また、各ストーリーは「作成者」、「コメント投稿者」、「読者」と共有することができる。
  • 読者はストーリーとコメントのみを表示でき、編集はできない。
  • コメント投稿者は読者のすべてのアクセス権を持ち、さらにストーリーにコメントを追加することもできる。
  • 作成者はコメント投稿者のすべてのアクセス権を持ち、さらにストーリー コンテンツも編集できる。
  • 所有者はストーリーのあらゆる部分を編集でき、他のユーザーのアクセスを制御することもできる。

データ構造

アプリには stories コレクションがあり、そこでは各ドキュメントが 1 つのストーリーを表すとします。各ストーリーには comments サブコレクションもあり、そこでは各ドキュメントがそのストーリーのコメントとなります。

アクセスロールを管理するために、ユーザー ID とロールとのマッピングとなる roles フィールドを追加します。

/stories/{storyid}

{
  title: "A Great Story",
  content: "Once upon a time ...",
  roles: {
    alice: "owner",
    bob: "reader",
    david: "writer",
    jane: "commenter"
    // ...
  }
}

コメントには、投稿者のユーザー ID とコンテンツの 2 つのフィールドのみを含めます。

/stories/{storyid}/comments/{commentid}

{
  user: "alice",
  content: "I think this is a great story!"
}

ルール

以上でユーザーのロールがデータベースに記録されたので、次はセキュリティ ルールを作成してそれらを検証する必要があります。このルールではアプリで Firebase Auth が使用されることを前提としているため、request.auth.uid 変数はユーザー ID となります。

ステップ 1: 最初に基本ルールファイルを作成します。これには、ストーリー用とコメント用の空のルールを含めます。

service cloud.firestore {
   match /databases/{database}/documents {
     match /stories/{story} {
         // TODO: Story rules go here...

         match /comments/{comment} {
            // TODO: Comment rules go here...
         }
     }
   }
}

ステップ 2: 所有者がストーリーを完全に制御できるようにする単純な write ルールを追加します。以下に定義されている各関数は、ユーザーのロールと、新しい文書が有効かどうかを判断するために利用されます。

service cloud.firestore {
   match /databases/{database}/documents {
     match /stories/{story} {
        function isSignedIn() {
          return request.auth != null;
        }

        function getRole(rsc) {
          // Read from the "roles" map in the resource (rsc).
          return rsc.data.roles[request.auth.uid];
        }

        function isOneOfRoles(rsc, array) {
          // Determine if the user is one of an array of roles
          return isSignedIn() && (getRole(rsc) in array);
        }

        function isValidNewStory() {
          // Valid if story does not exist and the new story has the correct owner.
          return resource == null && isOneOfRoles(request.resource, ['owner']);
        }

        // Owners can read, write, and delete stories
        allow write: if isValidNewStory() || isOneOfRoles(resource, ['owner']);

         match /comments/{comment} {
            // ...
         }
     }
   }
}

ステップ 3: すべてのロールのユーザーがストーリーとコメントを読むことができるルールを作成します。前のステップで定義した関数を使用することで、ルールが簡潔でわかりやすくなります。

service cloud.firestore {
   match /databases/{database}/documents {
     match /stories/{story} {
        function isSignedIn() {
          return request.auth != null;
        }

        function getRole(rsc) {
          return rsc.data.roles[request.auth.uid];
        }

        function isOneOfRoles(rsc, array) {
          return isSignedIn() && (getRole(rsc) in array);
        }

        function isValidNewStory() {
          return resource == null
            && request.resource.data.roles[request.auth.uid] == 'owner';
        }

        allow write: if isValidNewStory() || isOneOfRoles(resource, ['owner']);

        // Any role can read stories.
        allow read: if isOneOfRoles(resource, ['owner', 'writer', 'commenter', 'reader']);

        match /comments/{comment} {
          // Any role can read comments.
          allow read: if isOneOfRoles(get(/databases/$(database)/documents/stories/$(story)),
                                      ['owner', 'writer', 'commenter', 'reader']);
        }
     }
   }
}

ステップ 4: ストーリー作成者、コメント投稿者、所有者がコメントを投稿できるようにします。このルールでは、コメントの owner がリクエスト元のユーザーと一致しているかどうかも検証し、ユーザーがお互いのコメントを上書きすることがないようにします。

service cloud.firestore {
   match /databases/{database}/documents {
     match /stories/{story} {
        function isSignedIn() {
          return request.auth != null;
        }

        function getRole(rsc) {
          return rsc.data.roles[request.auth.uid];
        }

        function isOneOfRoles(rsc, array) {
          return isSignedIn() && (getRole(rsc) in array);
        }

        function isValidNewStory() {
          return resource == null
            && request.resource.data.roles[request.auth.uid] == 'owner';
        }

        allow write: if isValidNewStory() || isOneOfRoles(resource, ['owner'])
        allow read: if isOneOfRoles(resource, ['owner', 'writer', 'commenter', 'reader']);

        match /comments/{comment} {
          allow read: if isOneOfRoles(get(/databases/$(database)/documents/stories/$(story)),
                                      ['owner', 'writer', 'commenter', 'reader']);

          // Owners, writers, and commenters can create comments. The
          // user id in the comment document must match the requesting
          // user's id.
          //
          // Note: we have to use get() here to retrieve the story
          // document so that we can check the user's role.
          allow create: if isOneOfRoles(get(/databases/$(database)/documents/stories/$(story)),
                                        ['owner', 'writer', 'commenter'])
                        && request.resource.data.user == request.auth.uid;
        }
     }
   }
}

ステップ 5: 作成者に、ストーリーのコンテンツは編集できるが、ストーリーのロールを編集したり、ドキュメントの他のプロパティを変更したりすることはできない権限を付与します。そのためには、次のようにストーリーの write ルールを createupdatedelete の別個のルールに分割し、作成者がストーリーのみを更新できるようにする必要があります。

service cloud.firestore {
   match /databases/{database}/documents {
     match /stories/{story} {
        function isSignedIn() {
          return request.auth != null;
        }

        function getRole(rsc) {
          return rsc.data.roles[request.auth.uid];
        }

        function isOneOfRoles(rsc, array) {
          return isSignedIn() && (getRole(rsc) in array);
        }

        function isValidNewStory() {
          return request.resource.data.roles[request.auth.uid] == 'owner';
        }

        function onlyContentChanged() {
          // Ensure that title and roles are unchanged and that no new
          // fields are added to the document.
          return request.resource.data.title == resource.data.title
            && request.resource.data.roles == resource.data.roles
            && request.resource.data.keys() == resource.data.keys();
        }

        // Split writing into creation, deletion, and updating. Only an
        // owner can create or delete a story but a writer can update
        // story content.
        allow create: if isValidNewStory();
        allow delete: if isOneOfRoles(resource, ['owner']);
        allow update: if isOneOfRoles(resource, ['owner'])
                      || (isOneOfRoles(resource, ['writer']) && onlyContentChanged());
        allow read: if isOneOfRoles(resource, ['owner', 'writer', 'commenter', 'reader']);

        match /comments/{comment} {
          allow read: if isOneOfRoles(get(/databases/$(database)/documents/stories/$(story)),
                                      ['owner', 'writer', 'commenter', 'reader']);
          allow create: if isOneOfRoles(get(/databases/$(database)/documents/stories/$(story)),
                                        ['owner', 'writer', 'commenter'])
                        && request.resource.data.user == request.auth.uid;
        }
     }
   }
}

制限事項

上記の解決策では、セキュリティ ルールを使用してユーザーデータを保護していますが、次の制限事項があることにご注意ください。

  • 粒度: 上記の例では、複数のロール(作成者と所有者)が同じドキュメントへの書き込みアクセス権を持っていますが、制限事項がそれぞれ異なります。このような方法は複雑なドキュメントでは管理が難しくなるため、1 つのドキュメントを複数のドキュメントに分割し、それぞれを単一のロールに所有させる方がよい場合があります。
  • 大規模グループ: 非常に大規模なグループまたは複雑なグループと共有する必要がある場合は、ロールを対象ドキュメントのフィールドとしてではなく、専用のコレクションに格納するシステムを検討してください。