使用樂觀並行控制更新 IAM 政策

如要修改 Google Cloud服務的身分與存取權管理 (IAM) 政策,必須執行受開放式並行控制 (OCC) 保護的讀取-修改-寫入週期。本文說明如何在 Swift 的 Google Cloud 用戶端程式庫中,使用 OCC 重試迴圈更新 IAM 政策。

事前準備

本文以 Secret Manager API 和現有 Secret 為例,但相同模式適用於任何公開 getIamPolicy 和 setIamPolicy 的 Google Cloud 服務。如要準備環境,請完成下列步驟:

  1. 按照「快速入門導覽課程:開始使用 Swift」中的說明,設定 Swift 用戶端程式庫並啟用 Secret Manager API。
  2. 如果沒有 Secret,請按照 Secret Manager 快速入門導覽課程建立。
  3. 確認主體有權讀取及更新密鑰的 IAM 政策,例如 Secret Manager 管理員角色 (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,使用指數輪詢和抖動等待,並重複讀取-修改-寫入週期,將變更套用至更新後的政策。

如果您在採用條件式角色繫結的政策中新增、修改或移除繫結,請先設定 policy.version = 3,再呼叫 setIamPolicy。

編寫 OCC 讀取-修改-寫入迴圈

如要使用 OCC 讀取-修改-寫入迴圈新增 IAM 角色繫結,請按照下列步驟操作:

  1. 新增服務用戶端、GoogleGax 和 GoogleIAMV1 所需的匯入項目:

    import Foundation
    import GoogleCloudSecretManagerV1
    import GoogleGax
    import GoogleIAMV1

  2. 定義函式,接受目標資源 ID、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)
    }
  }
}

後續步驟