Update IAM policies using optimistic concurrency control

Modifying Identity and Access Management (IAM) policies across Google Cloud services requires a read-modify-write cycle guarded by optimistic concurrency control (OCC). This document shows you how to update an IAM policy using an OCC retry loop in the Google Cloud client libraries for Swift.

Before you begin

This document uses the Secret Manager API and an existing secret as an example, though the same pattern applies to any Google Cloud service that exposes getIamPolicy and setIamPolicy. To prepare your environment, complete the following steps:

  1. Set up the Swift client libraries and enable the Secret Manager API by following Quickstart: Get started with Swift.
  2. If you don't have a secret, create one by following the Secret Manager quickstart.
  3. Verify that your principal has permission to read and update IAM policies on the secret, such as the Secret Manager Admin role (roles/secretmanager.admin).

Add required dependencies

In addition to the swift-google-cloud-secretmanager-v1 client library, you need types from the swift-google-iam-v1 and swift-google-gax packages on GitHub to update IAM policies and handle OCC conflicts. To add these packages and their GoogleIAMV1 and GoogleGax modules, follow these steps:

  1. Add the packages to your Package.swift dependencies:

    swift package add-dependency \
        https://github.com/googleapis/swift-google-iam-v1.git --from 0.6.0
    swift package add-dependency \
        https://github.com/googleapis/swift-google-gax.git --from 0.6.0
    
  2. Add the GoogleIAMV1 and GoogleGax modules to your target dependencies:

    swift package add-target-dependency \
        GoogleIAMV1 TARGET_NAME \
        --package swift-google-iam-v1
    swift package add-target-dependency \
        GoogleGax TARGET_NAME \
        --package swift-google-gax
    

    Replace TARGET_NAME with the name of your target.

Why IAM policy updates require an OCC loop

Google Cloud IAM policies update as a whole document rather than by patching individual role bindings on the server. To prevent concurrent writers from overwriting each other's changes, IAM uses OCC across three stages:

  • Read: your app calls getIamPolicy to fetch the current Policy object, which includes an etag field identifying the exact version of the policy stored on the server.
  • Modify: your app updates the bindings array on the returned Policy object in memory while preserving its etag field.
  • Write: your app calls setIamPolicy with the modified Policy object, and the server compares the etag value in your request against the current policy version.

If another process modifies the policy between your getIamPolicy and setIamPolicy calls, the etag value no longer matches. The server rejects the write with RequestError.service(let serviceError), where serviceError.code == .aborted (HTTP 409 Conflict).

The client library's built-in retry policy can't resolve this conflict because repeating the same setIamPolicy request with a stale etag value fails on every attempt. Instead, your app must catch .aborted, wait using exponential backoff with jitter, and repeat the read-modify-write cycle to apply your changes to the updated policy.

If you add, modify, or remove bindings on a policy that uses conditional role bindings, set policy.version = 3 before calling setIamPolicy.

Write an OCC read-modify-write loop

To add an IAM role binding using an OCC read-modify-write loop, follow these steps:

  1. Add the imports needed for the service client, GoogleGax, and GoogleIAMV1:

    import Foundation
    import GoogleCloudSecretManagerV1
    import GoogleGax
    import GoogleIAMV1

  2. Define a function that accepts the target resource identifiers, the IAM role, such as "roles/secretmanager.secretAccessor", and the member principal, such as "user:dana@example.com":

    func addIamMember(
      projectId: String,
      secretId: String,
      role: String,
      member: String
    ) async throws -> Policy {

  3. Initialize the client and configure an ExponentialBackoff policy to compute jittered delays between retry attempts:

    let client = try SecretManagerServiceClient()
    let backoff = ExponentialBackoff(
      clamping: .milliseconds(250),
      maximumDelay: .seconds(5),
      scaling: 2.0
    )
    let maxAttempts = 5
    let resource = "projects/\(projectId)/secrets/\(secretId)"

  4. Run a bounded loop that reads the current policy, applies the binding change, and writes the updated policy. If setIamPolicy fails with .aborted, wait for the backoff delay and retry the cycle from getIamPolicy:

    var attempt = 0
    while true {
      attempt += 1
      var policy = try await client.getIamPolicy(
        request: GetIamPolicyRequest().with {
          $0.resource = resource
          $0.options = GetPolicyOptions().with { options in
            options.requestedPolicyVersion = 3
          }
        })
    
      if let index = policy.bindings.firstIndex(where: { $0.role == role && $0.condition == nil }) {
        if policy.bindings[index].members.contains(member) {
          return policy
        }
        policy.bindings[index].members.append(member)
      } else {
        policy.bindings.append(
          Binding().with {
            $0.role = role
            $0.members = [member]
          })
      }
    
      do {
        return try await client.setIamPolicy(
          request: SetIamPolicyRequest().with {
            $0.resource = resource
            $0.policy = policy
          })
      } catch RequestError.service(let serviceError) where serviceError.code == .aborted {
        guard attempt < maxAttempts else {
          throw RequestError.service(serviceError)
        }
        let delay = backoff.backoffDelay(
          for: RetryState().with {
            $0.attemptCount = attempt
          })
        try await Task.sleep(for: delay)
      }
    }

When setIamPolicy succeeds, it returns the updated Policy with the new role binding. You can verify the updated policy by running gcloud secrets get-iam-policy:

gcloud secrets get-iam-policy SECRET_ID

Replace SECRET_ID with your secret ID.

Complete code

The following example shows the complete code for this document:

import Foundation
import GoogleCloudSecretManagerV1
import GoogleGax
import GoogleIAMV1

func addIamMember(
  projectId: String,
  secretId: String,
  role: String,
  member: String
) async throws -> Policy {
  let client = try SecretManagerServiceClient()
  let backoff = ExponentialBackoff(
    clamping: .milliseconds(250),
    maximumDelay: .seconds(5),
    scaling: 2.0
  )
  let maxAttempts = 5
  let resource = "projects/\(projectId)/secrets/\(secretId)"

  var attempt = 0
  while true {
    attempt += 1
    var policy = try await client.getIamPolicy(
      request: GetIamPolicyRequest().with {
        $0.resource = resource
        $0.options = GetPolicyOptions().with { options in
          options.requestedPolicyVersion = 3
        }
      })

    if let index = policy.bindings.firstIndex(where: { $0.role == role && $0.condition == nil }) {
      if policy.bindings[index].members.contains(member) {
        return policy
      }
      policy.bindings[index].members.append(member)
    } else {
      policy.bindings.append(
        Binding().with {
          $0.role = role
          $0.members = [member]
        })
    }

    do {
      return try await client.setIamPolicy(
        request: SetIamPolicyRequest().with {
          $0.resource = resource
          $0.policy = policy
        })
    } catch RequestError.service(let serviceError) where serviceError.code == .aborted {
      guard attempt < maxAttempts else {
        throw RequestError.service(serviceError)
      }
      let delay = backoff.backoffDelay(
        for: RetryState().with {
          $0.attemptCount = attempt
        })
      try await Task.sleep(for: delay)
    }
  }
}

What's next