google-cloud-storagegoogle-iamgoogle-cloud-iamgoogle-cloud-python

Using the Python API to read from Google Cloud Storage with minimal permissions


I would like to download blobs from a storage using Python. The examples show this code:

from google.cloud import storage
client = storage.Client()
bucket = client.get_bucket(BUCKETNAME)
blob = bucket.get_blob(BLOBNAME)
raw_bytes = blob.download_as_bytes()

While this works, it not only requires the storage.objects.get permission granted with the "Storage Object Viewer" role (roles/storage.objectViewer), but also the storage.buckets.get Permission to execute the get_bucket line. This permission is granted by other roles that sound either overly powerful or legacy, like "Storage Admin" or "Storage Legacy Bucket Reader".

Is there a way to change the Python code, such that only the storage.objects.get permission is required? It seems that the JSON API which is probably behind the Python API allows this: https://cloud.google.com/storage/docs/json_api/v1/objects/get

Best, Boris


Solution

  • In the sample code, the bucket statement bucket = client.get_bucket(BUCKETNAME) is used to list the bucket operation.

    If you are to output the value you get as a response, rather than performing the client.get_bucket, you can pass this as a static value. By using a static value, you would not be utilizing the client.get_bucket operation which requires the storage.buckets.get permission.

    You may also refer to a similar Stackoverflow case.