pythongoogle-cloud-storage

Least privilege principle to create files in a bucket


I'm trying to grant a service account a limited set of permissions and allow it to create files on a specific bucket. Instead of creating a custom role, I thought on using the roles/storage.objectCreator predefined one on the bucket.

After that, I run the following lines of code by impersonating the SA:

storage_client = storage.Client("project")
bucket_name = "bucket"
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob("test.txt")
blob.upload_from_string("Hello World")

However, when I execute the workflow I receive a permission denied error saying:

sa-name@project.iam.gserviceaccount.com does not have storage.buckets.get access to the Google Cloud Storage bucket. Permission 'storage.buckets.get' denied on resource (or it may not exist)

I was expecting this to be enough, but it seems it isn't. I know I can create a custom role and define the set of permissions I want to give it. However, is it possible to upload the file while keeping the scope limited to the objectCreator role? Maybe by editing the python code and not instantiating the bucket object?


Solution

  • The roles/storage.objectCreator is sufficient.

    And you're correct to want to try to use predefined roles whenever possible.

    The issue is that you're using get_bucket which requires storage.buckets.get permission which is not included in the roles/storage.objectCreator role.

    See the sample code (click 'Client Libraries' and then select 'Python') that shows you how to upload a file to Cloud Storage using Python with that role.