Created
August 10, 2021 10:12
-
-
Save jhanley-com/3fca04a065ebf54cf42bcc70be98b387 to your computer and use it in GitHub Desktop.
The following example first processes a bucket. If uniform access is not enabled then the object is processed. If public access enabled on the bucket or the object, the object is Public. Refer to https://stackoverflow.com/questions/68722565/how-to-check-if-a-file-in-gcp-storage-is-public-or-not
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
from google.cloud import storage | |
# Replace with valid bucket and object names | |
bucket_name = 'example_bucket_name' | |
object_name = 'example_object_name' | |
# Instantiates a client | |
storage_client = storage.Client() | |
# Process bucket level access | |
def process_bucket(bucketName): | |
bucket = storage_client.get_bucket(bucketName) | |
configuration = bucket.iam_configuration | |
uniformEnabled = configuration['uniformBucketLevelAccess']['enabled'] | |
public = False | |
policy = bucket.get_iam_policy() | |
for binding in policy.bindings: | |
for m in binding['members']: | |
if m == 'allUsers': | |
public = True | |
print('Bucket:', bucketName) | |
print(' Uniform Access:', uniformEnabled) | |
print(' Public:', public) | |
return uniformEnabled | |
# Process blob level access | |
def process_object(bucketName, objectName): | |
bucket = storage_client.get_bucket(bucketName) | |
blob = bucket.blob(objectName) | |
policy = blob.get_iam_policy() | |
public = False | |
for binding in policy.bindings: | |
for m in binding['members']: | |
if m == 'allUsers': | |
public = True | |
print('Object: gs://{0}/{1}'.format(bucketName, objectName)) | |
print(' Public:', public) | |
if __name__ == '__main__': | |
try: | |
uniform_enabled = process_bucket(bucket_name) | |
if uniform_enabled is False: | |
process_object(bucket_name, object_name) | |
except Exception as ex: | |
print("Exception: {}".format(ex), file=sys.stderr) | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment