BE: Fix race condition while creating protected branch rules

Problem

While creating a security policy project via the GraphQL mutation, we also create protected branch rules for the default branch with no one having push access and only maintainers having merge access. Since the project is created with a default branch and README file, BranchHookService is executed via post_receive API which also creates protected branch rules for default branch with maintainer having both push and merge access.

Since these 2 execution are independent, they could run in any order. So, there are 2 different branch protection created for the default main branch sometimes: Screenshot_2021-06-29_at_12.32.09_PM

Sometimes branch protection with multiple push and merge accesses are created for default main branch: Screenshot_2021-07-09_at_1.16.01_PM because ProtectedBranch model has accepts_nested_attributes_for push_access_levels and merge_push_levels

Solution

  • Instead of updating the protected branch in Security::SecurityOrchestrationPolicies::ProjectCreateService, delete and recreate it with push and merge access rules

  • Wrap them in a transaction

  • We decided to fix this by extending ProtectDefaultBranchService to EE and create required rules if the project is a security policy management project

Edited by Sashi Kumar Kumaresan