Ошибка развертывания файла конфигурации yaml Google cloud API Gateway с проверкой подлинности

#google-cloud-platform #google-cloud-api-gateway

#google-облачная платформа #google-cloud-api-gateway

Вопрос:

Я новичок в API Gateway и пытаюсь включить безопасность в своем API. Я следую некоторым инструкциям, которые я нашел в Интернете, следующим образом: https://medium.com/swlh/manage-serverless-apis-with-api-gateway-in-gcp-b7f906efec1a

Вот мой файл YAML:

 # openapi2-functions.yaml
swagger: '2.0'
info:
  title: simple-test
  description: Sample API on API Gateway with a Google Cloud Functions backend
  version: 1.0.0
schemes:
  - https
produces:
  - application/json
paths:
  /direcciones:
    get:
      summary: get direcciones
      operationId: direcciones
      x-google-backend:
        address: http://publicIP/api/v1/app/catalogos/direcciones
        security:
        - api_key: []
      responses:
        '200':
          description: A successful response
          schema:
            type: string
securityDefinitions:
 api_key:
    type: "apiKey"
    name: "key"
    in: "query"
  

При развертывании этого файла конфигурации в конфигурации API gateway я получаю следующую ошибку:

 INVALID_ARGUMENT Cannot convert to service config. 'location: "evva.yaml: x-google-backend" kind: ERROR message: "Extension x-google-backend cannot be converted into proto type google.api.BackendRule. Details: Cannot find field: security in message google.api.BackendRule" location: "evva.yaml: x-google-backend" message: "Address field in extension x-google-backend is empty. In this case, the backend address must be provided to the proxy via a runtime flag." location: "evva.yaml: Operation 'get' in path '/direcciones'" message: "Operation does not require an API key; callers may invoke the method without specifying an associated API-consuming project. To enable API key all the SecurityRequirement Objects (https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#security-requirement-object) inside security definition must reference at least one SecurityDefinition of type : 'apiKey'." ' com.google.apps.framework.request.BadRequestException: Cannot convert to service config. 'location: "evva.yaml: x-google-backend" kind: ERROR message: "Extension x-google-backend cannot be converted into proto type google.api.BackendRule. Details: Cannot find field: security in message google.api.BackendRule" location: "evva.yaml: x-google-backend" message: "Address field in extension x-google-backend is empty. In this case, the backend address must be provided to the proxy via a runtime flag." location: "evva.yaml: Operation 'get' in path '/direcciones'" message: "Operation does not require an API key; callers may invoke the method without specifying an associated API-consuming project. To enable API key all the SecurityRequirement Objects (https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#security-requirement-object) inside security definition must reference at least one SecurityDefinition of type : 'apiKey'." ' 
  

Я не понимаю эту ошибку, какие изменения мне нужно внести в файл YAML, чтобы сделать его приемлемым при развертывании.

Ответ №1:

Запись безопасности не должна быть «в» x-google-backend , но ниже get: . Вот так.

 paths:
  /direcciones:
    get:
      summary: get direcciones
      operationId: direcciones
      x-google-backend:
        address: http://publicIP/api/v1/app/catalogos/direcciones
      security:
        - api_key: []
  

Комментарии:

1. Это странно, несколько пробелов меняют семантику : (

2. Yaml, как и Python, основан на отступах. Меньше символов для печати / ввода / сохранения, но более слабая структура.

3. еще один вопрос: возможно ли сопоставить API с локальным IP-адресом, который выполняется в вычислительном экземпляре в GCP? Я пытался использовать локальный адрес, но затем вызов из шлюза API завершается неудачно. Есть идеи по этому поводу?

4. Нет, API Gateway (и другие бессерверные продукты, такие как Cloud Scheduler, Cloud Task или PubSub) не совместимы с бессерверным VPC connector и не подключены к VPC, поэтому не могут взаимодействовать с частным IP-адресом вашего VPC.

5. Единственное решение — обернуть вызов в облачную функцию или запустить облачный запуск, чтобы построить эту цепочку: API Gateway -> OAuth2 id_token -> Облачная функция / Run -> Бессерверный VPC Connector -> частный IP ComputeEngine.