Search code examples
apiscopetwiliosendgridtwilio-api

SendGrid: Error when trying to add scopes with the API


I'm trying to add scopes to an API key with the API (actually to the same key I'm using to connect to the API). I'm following the example in the doc, and my current scopes do include the api_key_update permission.

However when I try to add more scopes to the API key, I always receive a 400 Bad Request error.

For example apparently this is the bare minimum of scopes when having set the "API Keys" permission to "Full Access" in the admin panel (retrieved via the GET v3/scopes API endpoint):

templates.read
api_keys.create
api_keys.read
api_keys.update
api_keys.delete
sender_verification_eligible
2fa_required

And when I now try to add a mail.send scope to it, I receive this error message:

{"errors":[{"field":null,"message":"unauthorized scopes: [mail.send]"}]}

When I just pass the already existing scopes, I receive a successful response. I can also remove scopes successfully by leaving them out of the passed array. But I cannot add them, no matter which scope I try to add.

I've tested with Node.JS and with curl, here are the curl test scripts:

Working:
curl -X PUT --header "Authorization: Bearer INSERT_API_KEY" --header "Content-Type: application/json" --data '{"name": "INSERT_API_KEY_NAME", "scopes": ["templates.read", "api_keys.create", "api_keys.read", "api_keys.update", "api_keys.delete", "sender_verification_eligible", "2fa_required"]}' https://api.sendgrid.com/v3/api_keys/INSERT_API_KEY_ID


Not working:
curl -X PUT --header "Authorization: Bearer INSERT_API_KEY" --header "Content-Type: application/json" --data '{"name": "INSERT_API_KEY_NAME", "scopes": ["templates.read", "api_keys.create", "api_keys.read", "api_keys.update", "api_keys.delete", "sender_verification_eligible", "2fa_required", "mail.send"]}' https://api.sendgrid.com/v3/api_keys/INSERT_API_KEY_ID

Solution

  • I got to the bottom of this.

    An API Key with permission to update other API keys can only give permissions that the API Key itself has. That's why an API key with full access was able to update the scopes on another API Key, but your API Key with only a few permissions including access to update other API keys couldn't add other scopes. This also leads to the conclusion that an API key cannot give itself further permissions too.

    This makes sense for limited scope API keys. The intention behind the limits are that you can limit the potential damage from leaking an API key if it can only perform certain actions. If you leaked a key and it was able to add permissions to itself, that would render the limited permission feature useless.

    We accept that this isn't clear in the documentation and we have raised an issue to update the documentation so this is more obvious.