An issue with restricting access to a cloud function based on API key through Cloud Endpoints

93 Views Asked by At

I try to restrict access to Google cloud function by defining API KEY in openapi.yaml

schemes:
  - https
produces:
  - application/json
security:
  - api_key: []
securityDefinitions:
  api_key:
    type: "apiKey"
    name: "mot"
    in: "query"  
paths:
  /:
    get:
      summary: Greet a user
      operationId: hello

Deployment steps:

1. gcloud run deploy apikeytst1 --image="gcr.io/endpoints-release/endpoints-runtime-serverless:2" --allow-unauthenticated --platform managed --project=xxxx
2. gcloud endpoints services deploy apikeytst.yaml --project xxxx
3. ./gcloud_build_image -s apikeytst1-yyyyyyyyy-ew.a.run.app -c 2020-10-08r0 -p xxxx
4. gcloud run deploy apikeytst1 --image="gcr.io/xxxxx/endpoints-runtime-serverless:apikeytst1-yyyyyyyyyy-ew.a.run.app-2020-10-08r0" --allow-unauthenticated --platform managed  --project=xxxx

But anyone can invoice the function without the key.

2

There are 2 best solutions below

4
On

It seems like you followed the information provided by google in setting up the Swagger specification. It probably has to do something with your cloud endpoints deployment or permissions. I would advise you to go through all the cloud endpoints steps again carefully. If you correctly deployed cloud endpoints as a wrapper around your cloud function, you should not be able to invoke the cloud function directly. Instead, use the cloud endpoints endpoint with an API key as a query parameter. One crucial step is to remove the allUsers invoker permissions from your cloud function and add the following:

gcloud functions add-iam-policy-binding FUNCTION_NAME \
   --region FUNCTION_REGION \
   --member "serviceAccount:[email protected]" \
   --role "roles/cloudfunctions.invoker" \
   --project FUNCTIONS_PROJECT_ID
0
On

Google requests that the first key must be a key with the name "key" or "api_key". After that (on the second etc positions), we can add keys with arbitrary names.