Cloud Functions のアクセス制御

○リカリさんのGCP記事って助かりますよね。
「その記事、知ってます!!」と話がスムーズに流れたり。
[参考] Google Cloud (GCP) Functionsの関数コール権をIAMで管理するためのテクニック
https://tech.mercari.com/entry/2019/03/28/171100
記事はGo版のサンプルなので、Python版を書いてみます。
Cloud Functions (Python 3.7)
def IsAuthorized(token):
credentials = google.oauth2.credentials.Credentials(token)
client = storage.Client('{project_id}', credentials)
bucket = storage.Bucket(client, '{bucket_name}')
authorizedPermission = bucket.test_iam_permissions(
["storage.buckets.get"], client)
return len(authorizedPermission) > 0
def main(req):
try:
if "Authorization" not in req.headers:
raise SystemError("Authorization Head Not Found")
if IsAuthorized(req.headers['Authorization']) is False:
raise FileNotFoundError("Not Authenticated")それではリクエストの準備をしましょう。
GCPパートナーらしく、GCPコンソールの操作ではなく、 gcloud コマンドでやる事にします。(らしいのか・・)
GCSにBucketを作成
gsutil mb -l asia-northeast1 gs://{bucket_name}サービスアカントを作成
gcloud beta iam service-accounts create gcf-auth --description "GCF認証用" --display-name "GCF-Auth"GCSのBucketのACLにREADERでサービスアカウントを追加
gsutil acl ch -u gcf-auth@{project_id}.iam.gserviceaccount.com:R gs://{bucket_name}サービスアカウントの鍵を作成
gcloud beta iam service-accounts keys create gcf-auth.json --iam-account gcf-auth@{project_id}.iam.gserviceaccount.com鍵からTokenを発行
GOOGLE_APPLICATION_CREDENTIALS=./gcf-auth.json gcloud auth application-default print-access-token準備が出来たので関数にリクエストをします。
curl -X POST https://asia-northeast1-{project_id}.cloudfunctions.net/{function_name} -H "Authorization: "$GOOGLE_APPLICATION_CREDENTIALSこれにて終了です。
これからも良い記事をお願いします。

