google-apigoogle-cloud-platformgoogle-cloud-console

Google Cloud Resource Manager API: Test IAM Permissions


I am trying to use the Google Cloud Resource Manager API to test whether the authenticated user has permissions to a given project. I have read the [Google Cloud Resource Manager API documentation][1] and have tried sending requests, all which fail with the following error:

{  "error": {   "code": 400,   "message": "Request contains an invalid argument.",   "status": "INVALID_ARGUMENT"  } }

The POST request is:

https://cloudresourcemanager.googleapis.com/v1/projects/{projectId}:testIamPermissions

where {projectId} is a defined projectId from the Google Cloud Developer Console. I am aware that I can use the project.list method and determine if the given projectId is present in the list of projects for the user. I want to understand how to use the project.testIamPermissions request and determine which permission the user has on the project. [1]: https://cloud.google.com/resource-manager/reference/rest/v1/projects/testIamPermissions


Solution

  • In order to use the Cloud Resource Manager API methods organizations.testIamPermissions or projects.testIamPermissions, you need to provide the resource you'd like to check in the URL and then the permissions you'd like to check in the body.

    So, for example, if I want to test if I, the authenticated user, have access to a particular permission (ex. compute.instances.create) on a particular project (ex. my-project) then, I would POST this:

    {
     "permissions": [
      "compute.instances.create"
     ]
    }
    

    to the URL:

    https://cloudresourcemanager.googleapis.com/v1/projects/my-project:testIamPermissions
    

    which would give me the following response:

    {
     "permissions": [
      "compute.instances.create"
     ]
    }
    

    because I do in fact have permissions to create new instances in my-project. However, if I did not have permission to create new instances, the response would look like:

    {
    }
    

    Try it here via the API Explorer.

    If your goal is to find the test of all permissions that the user has on the project, then you have to provide the full list of all project level permissions in your request body and the response will include the subset of those permissions that the user has.

    Hope this helps!