使用乐观并发控制更新 IAM 政策

修改跨 Google Cloud服务的 Identity and Access Management (IAM) 政策需要由乐观并发控制 (OCC) 保护的读取-修改-写入周期。本文档介绍了如何在 Google Cloud Swift 客户端库中使用 OCC 重试循环更新 IAM 政策。

准备工作

本文档以 Secret Manager API 和现有 Secret 为例,但相同的模式适用于公开 getIamPolicy 和 setIamPolicy 的任何 Google Cloud 服务。如需准备环境,请完成以下步骤:

  1. 按照快速入门:Swift 使用入门中的说明设置 Swift 客户端库并启用 Secret Manager API。
  2. 如果您没有 Secret,请按照 Secret Manager 快速入门中的说明创建一个。
  3. 验证您的主账号是否有权读取和更新 Secret 的 IAM 政策,例如 Secret Manager Admin 角色 (roles/secretmanager.admin)。

添加所需的依赖项

除了 swift-google-cloud-secretmanager-v1 客户端库之外,您还需要 GitHub 上的 swift-google-iam-v1 和 swift-google-gax 软件包中的类型,才能更新 IAM 政策和处理 OCC 冲突。如需添加这些软件包及其 GoogleIAMV1 和 GoogleGax 模块,请按以下步骤操作:

  1. 将这些软件包添加到 Package.swift 依赖项中:

    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. 将 GoogleIAMV1 和 GoogleGax 模块添加到目标依赖项中:

    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
    

    将 TARGET_NAME 替换为目标的名称。

为什么 IAM 政策更新需要 OCC 循环

Google Cloud IAM 政策会作为一个整体文档进行更新,而不是通过在服务器上修补单个角色绑定来更新。为了防止并发写入者相互覆盖彼此的更改,IAM 在三个阶段使用 OCC:

  • 读取:您的应用调用 getIamPolicy 来提取当前的 Policy 对象,其中包括一个 etag 字段,用于标识存储在服务器上的确切政策版本。
  • 修改:您的应用会更新内存中返回的 Policy 对象上的 bindings 数组,同时保留其 etag 字段。
  • 写入:您的应用使用修改后的 Policy 对象调用 setIamPolicy,服务器会将请求中的 etag 值与当前政策版本进行比较。

如果另一个进程在您的 getIamPolicy 和 setIamPolicy 调用之间修改了政策,则 etag 值将不再匹配。服务器拒绝写入并返回 RequestError.service(let serviceError),其中 serviceError.code == .aborted (HTTP 409 Conflict)。

客户端库的内置重试政策无法解决此冲突,因为每次尝试使用过时的 etag 值重复相同的 setIamPolicy 请求都会失败。相反,您的应用必须捕获 .aborted,使用带抖动的指数退避算法等待,然后重复读取-修改-写入周期,以将更改应用于更新后的政策。

如果您在使用了条件角色绑定的政策中添加、修改或移除绑定,请在调用 setIamPolicy 之前设置 policy.version = 3。

编写 OCC 读取-修改-写入循环

如需使用 OCC 读取-修改-写入循环添加 IAM 角色绑定,请按照以下步骤操作:

  1. 添加服务客户端 GoogleGax 和 GoogleIAMV1 所需的导入:

    import Foundation
    import GoogleCloudSecretManagerV1
    import GoogleGax
    import GoogleIAMV1

  2. 定义一个函数,该函数接受目标资源标识符、IAM role(例如 "roles/secretmanager.secretAccessor")和 member 主账号(例如 "user:dana@example.com"):

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

  3. 初始化客户端并配置 ExponentialBackoff 政策,以计算重试尝试之间的抖动延迟:

    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. 运行一个有界循环,该循环会读取当前政策、应用绑定更改并写入更新后的政策。如果 setIamPolicy 失败并显示 .aborted,请等待退避延迟时间,然后从 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)
      }
    }

setIamPolicy 成功后,它会返回更新后的 Policy 以及新的角色绑定。您可以通过运行 gcloud secrets get-iam-policy 来验证更新后的政策:

gcloud secrets get-iam-policy SECRET_ID

将 SECRET_ID 替换为您的密钥 ID。

完整代码

以下示例显示了本文档的完整代码:

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

后续步骤