--- tags: Blue 的學習紀錄 --- # GCP - Workload Identity Federation x GitHub Action 影片: [How to use GitHub Actions with Google's Workload Identity Federation](https://youtu.be/ZgVhU5qvK1M?si=JfCNqfx0-iNBY-b6) 文件: [Workload Identity Federation](https://cloud.google.com/iam/docs/workload-identity-federation) ![image](https://hackmd.io/_uploads/rkPiZtcpC.png) 傳統的使用方式中 想像 GCP 是一台車子,需要有 key(token) 才能使用 GCP 的服務 但這樣會造成的問題是: - long-lived 的 key 並不安全 - 無論是誰,任何人取得 key 就能使用 Workload Identity Federation 解決了這個問題 讓使用權不再依賴於 key,而是會驗證使用者是誰 ![image](https://hackmd.io/_uploads/SyMTzF9TR.png) 驗證使用者是誰後,發配一次性的 token 給使用者使用 ## 建立 Workload Identity Pool pool 可以想像成鑰匙圈 pool 上的每個 provider 就是鑰匙,例如 GitHub ## 在 Pool 中建立 GitHub Provider ### Provider 以 GitHub Action 為例 provider 屬於 `OIDC` 的類型 Issuer 是 `https://token.actions.githubusercontent.com` ### Attribute Mapping :::info **IAM:** <https://cloud.google.com/iam/docs/overview> IAM 在定義 *who (identity/principal)* 擁有 *what access (role)* 去存取 *which resource* principals 例如是 Google 帳號、Service Account 或 **workload identity pool** ::: <https://cloud.google.com/iam/docs/workload-identity-federation#mapping> 每個 workload identity pool 都會有一個 IAM principal 的值,用於讓 IAM 識別這個 principal ![image](https://hackmd.io/_uploads/rJo4ZTcpA.png) Attribute Mapping 主要在設定的就是上圖 IAM principal 中的 `SUBJECT_ATTRIBUTE_VALUE` ![image](https://hackmd.io/_uploads/SkNsZT96C.png) 這樣設定的意思是,GCP 會從 GitHub Action 提交的 OIDC token 中映射 `sub` 欄位的值到 `google.subject`,也就是 `SUBJECT_ATTRIBUTE_VALUE` 在預設情形下 GitHub Action OIDC token 的 `sub` 值是特定 repo 的名稱 例如 `"repo:myorg/myproject"` 除了 `google.subject` 是必填項目以外 在這裡也可以自定義新增要映射的欄位做為更進階的管理使用 ### Attribute Conditions [GitHub OIDC token](https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/about-security-hardening-with-openid-connect#understanding-the-oidc-token) 連結列表中定義了 GitHub OIDC token 各欄位的含意 在 Attribute Conditions 中可以對這些欄位值做進一步的檢查 例如: ``` assertion.repository=='Taiwan-Outdoor-Safety-Association/Line-Web-Bot' && assertion.ref=='refs/heads/main' && assertion.job_workflow_ref=='Taiwan-Outdoor-Safety-Association/Line-Web-Bot/.github/workflows/update-chatbot-token.yaml@refs/heads/main' ``` `assertion` 在這裡表示 GitHub Action OIDC token 所以 `assertion.repository` 是在指定只有特定的 repo 可以通過驗證;`assertion.job_workflow_ref` 在設定指有特定的 workflow 可以通過驗證 詳細用法可以參考官方文件: <https://cloud.google.com/iam/docs/reference/rest/v1/projects.locations.workloadIdentityPools.providers#WorkloadIdentityPoolProvider.FIELDS.attribute_condition> ###