Search code examples
javajsongoogle-app-enginegoogle-cloud-storageacl

google cloud object permission disappear


I am currently using JSON API Java library to upload objects to Google Cloud Storage and tried changing the permission of the object that is uploaded. When i first upload the file, there is 3 default file permission which is:

Project owners-projectId OWNER

Project editors-projectId OWNER

Project viewers-projectId OWNER

After uploading, i tried to use my code to add in a new file permission to make all user have access to it as reader and my code is:

StorageObject objectMetadata = new StorageObject();

// set access control
List<ObjectAccessControl> acl = Lists.newArrayList();
acl.add(new ObjectAccessControl().setEntity("allUsers").setRole("READER"));
objectMetadata.setAcl(acl);
Storage.Objects.Update req = client.objects().update(Bucket, file, objectMetadata);
req.execute();

However, after the code run successfully, the 3 default file permission is gone and instead, it is replace with:

User allUsers Reader

Although this is the file permission I wanted to set, the original 3 default file permission is gone. Is there any way to make it such that my 3 default file permission is retain as well as having this new file permission? Any help is appreciated.


Solution

  • The "objects.update()" call sets the entire metadata of your object. Your code creates a blank metadata, adds an "allUsers -> READER" permission, and sets the object's metadata to this new metadata, which is why all of your other permissions (and any other metadata you set on the object) all went away.

    What you wanted to do was add a permission without otherwise changing the metadata. There are several good ways to accomplish that, but the most direct is to call "objectAccessControls().insert()" instead:

    ObjectAccessControl newControl = new ObjectAccessControl()
        .setEntity("allUsers").setRole("READER");
    Storage.ObjectAccessControls.Insert request  = client.objectAccessControls().insert(
        Bucket, file, newControl);
    req.execute();