Verificando autenticación…

Skip to main content

Google API Gateway

Purpose and Scope

This project provides a template for configuring and deploying an API using Google Cloud API Gateway. The purpose is to serve as a foundation for exposing services (such as Google Cloud Functions or other HTTP backends) in a secure and managed way.

The API Gateway configuration is defined through an OpenAPI 2.0 (Swagger) file, allowing specification of paths, methods, backends, and security schemes.

Scope:

  • Definition of an API Gateway.
  • Integration with a backend (e.g., Google Cloud Function).
  • Configuration of authentication mechanisms: API Key, Google ID Token (OAuth2), Azure AD ID Token (OAuth2).
  • Automated deployment through a Jenkins pipeline.
  • Per-environment configuration (dev, intg, prod).

Architecture

The project implements an API Gateway layer on Google Cloud Platform. The general architecture consists of:

  1. Google API Gateway: Acts as the entry point for client requests. Manages authentication, routing, and other API policies.
  2. Backend Service: The actual service that processes business logic. Typically, this would be a Google Cloud Function, Cloud Run, or any other accessible HTTP service. The template is configured to point to a backend URL (e.g., <CLOUDFUNCTION-URL>).
  3. OpenAPI Definition (openapi.yaml.erb): An ERB (Embedded Ruby) template file that generates the OpenAPI 2.0 specification for the API Gateway. This file defines endpoints, methods, request/response parameters, and security configuration.
  4. Environment Configuration Files (deploy/env/*.yaml): YAML files containing environment-specific variables for each environment (development, integration, production), such as project IDs, service accounts, and token audiences.
  5. CI/CD Pipeline (Jenkins): Uses the Jenkinsfile to automate the API Gateway deployment process across different environments.

No visual diagram is provided, but the interaction is: Client -> Google API Gateway -> Backend Service (e.g., Cloud Function)

Technologies and Dependencies

  • Google Cloud API Gateway: Managed service for creating, securing, and monitoring APIs.
  • Google Cloud Functions (or similar): Backend for the APIs (implicit, not included in this template, but is the target).
  • OpenAPI Specification (Swagger) 2.0: Standard format for describing REST APIs.
  • YAML: Used for environment configuration files and the OpenAPI specification.
  • ERB (Embedded Ruby): Used for the openapi.yaml.erb template, allowing injection of environment variables.
  • Jenkins: For deployment automation (CI/CD) through the Jenkinsfile.
  • Git / GitLab: For version control and the project repository.
  • Repository: https://gitlab.com/latamairlines/tech/enterprise-architecture/arquitectura-central/tmpl_arq/corporate-architecture/templates/google-api-gateway.git

Local Configuration

Prerequisites

  • Git: To clone the repository.
  • gcloud CLI (Google Cloud SDK): Optional, but useful for interacting with GCP and testing configurations.
  • Ruby: Required if you want to process the openapi.yaml.erb file locally. However, processing usually occurs in the CI/CD pipeline.
  • Access to the GitLab repository.

Configuration and Understanding Steps

  1. Clone the repository: Follow the steps below

  2. Review the API Definition (deploy/gateway/openapi.yaml.erb): This file is the main template for the API Gateway configuration. It contains placeholders that will be replaced during deployment.

    swagger: "2.0"
    info:
    title: ${{ NAME }} # Will be replaced by the API name
    description: Sample API on API Gateway with a Google Cloud Functions backend
    version: 1.0.0
    schemes:
    - https
    # ... (rest of the file) ...
    paths:
    /path-name:
    get:
    summary: Greet a user
    operationId: hello
    x-google-backend:
    address: <CLOUDFUNCTION-URL> # Placeholder for the backend URL
    # ... (responses and security) ...
    securityDefinitions:
    api_key:
    type: "apiKey"
    name: "<% apikey_name %>" # Placeholder for the API key query param name
    in: "query"
    google_id_token:
    # ... (configuration for Google OAuth2)
    x-google-audiences: "<%= gsuite_client_id %>" # Placeholder
    azure_id_token:
    # ... (configuration for Azure AD OAuth2)
    x-google-audiences: "<% audiences %>" # Placeholder
  3. Review Environment Configuration Files (deploy/env/): These files (dev.yaml, intg.yaml, prod.yaml) define the variables that will be used to replace the placeholders in openapi.yaml.erb for each environment. Example from deploy/env/dev.yaml:

    service_account: <service-account-name>
    project_id: <project-id>
    environment: "dev"
    location: "us-east1"
    audiences: <audences> # Used by azure_id_token
    gsuite_client_id: <gsuite_client_id> # Used by google_id_token

    Note: The <placeholder> values must be replaced with real values for each environment. These are usually managed as secrets in the CI/CD system.

  4. "Local Execution": An API Gateway is a cloud service and is not "run" locally like a traditional application. Local configuration focuses on preparing the definition files. To test, the configuration must be deployed to a GCP environment.

Deployment

API Gateway deployment is automated through Jenkins.

  1. Jenkins Pipeline: The Jenkinsfile at the project root defines the pipeline to use:

    pipelineLatam('gcloud-api-gateway-deploy')

    This pipeline is responsible for:

    • Taking the openapi.yaml.erb template.
    • Processing the ERB template, injecting the corresponding variables from the environment file (dev.yaml, intg.yaml, or prod.yaml) according to the deployment environment.
    • Deploying the resulting OpenAPI configuration to Google Cloud API Gateway in the specified project and region.
  2. Environment Configuration (deploy/env/*.yaml): Before deploying to a new environment or making changes, ensure that the corresponding YAML file (dev.yaml, intg.yaml, prod.yaml) is correctly configured with the following parameters:

ParameterDescriptionExample (Placeholder)
service_accountThe GCP service account that the API Gateway will use.<service-account-name>
project_idThe Google Cloud project ID where the API Gateway will be deployed.<project-id>
environmentEnvironment identifier (e.g., "dev", "intg", "prod")."dev"
locationThe GCP region where the API Gateway will be deployed (e.g., "us-east1")."us-east1"
audiencesAudiences for Azure AD token validation (used in azure_id_token).<audiences>
gsuite_client_idGSuite Client ID for Google token validation (used in google_id_token).<gsuite_client_id>

Important: Sensitive or environment-specific values should be managed through secure mechanisms (e.g., environment variables or Jenkins secrets), not committed directly in the deploy/env/*.yaml files if they are critical.

API Endpoints

The openapi.yaml.erb template defines the following example endpoints. These can be modified or extended according to project needs.

MethodPathSummaryOperation IDBackend (Example)Security Applied
GET/path-nameGreet a userhello<CLOUDFUNCTION-URL>api_key, google_id_token, azure_id_token

Backend Details:

  • x-google-backend:
    • address: <CLOUDFUNCTION-URL> - This placeholder must be replaced with the actual backend service URL (e.g., the trigger URL of a Google Cloud Function).

Defined Responses (Example for GET /path-name):

  • 200 OK: Successful response.
    • Schema: type: string
  • 401 Unauthorized: Authentication error.
  • 403 Forbidden: Authorization error.
  • 404 Not Found: Resource not found.

Specific Components

1. Google API Gateway

  • Main Definition: The deploy/gateway/openapi.yaml.erb file is the heart of the configuration. It defines all aspects of the API.
  • Template Processing: Uses ERB to allow environment-specific values (from deploy/env/*.yaml) to be inserted into the final OpenAPI specification during deployment.
    • ${{ NAME }}: API name.
    • <CLOUDFUNCTION-URL>: Backend service URL.
    • <% apikey_name %>: Query parameter name for the API Key.
    • <%= gsuite_client_id %>: Audience for google_id_token.
    • <% audiences %>: Audience for azure_id_token.
  • Security Schemes: Configured in the securityDefinitions section of openapi.yaml.erb:
    • API Key (api_key):
      securityDefinitions:
      api_key:
      type: "apiKey"
      name: "<% apikey_name %>" # e.g., "key"
      in: "query"
    • Google ID Token (google_id_token): OAuth2 authentication using ID tokens issued by Google.
      securityDefinitions:
      google_id_token:
      authorizationUrl: ""
      flow: "implicit"
      type: "oauth2"
      x-google-issuer: "https://accounts.google.com"
      x-google-jwks_uri: "https://www.googleapis.com/oauth2/v3/certs"
      x-google-audiences: "<%= gsuite_client_id %>"
      x-google-jwt-locations:
      - header: "Authorization"
      value_prefix: "Bearer "
    • Azure AD ID Token (azure_id_token): OAuth2 authentication using ID tokens issued by Azure Active Directory.
      securityDefinitions:
      azure_id_token:
      authorizationUrl: ""
      flow: "implicit"
      type: "oauth2"
      x-google-issuer: "https://login.microsoftonline.com/99d911b9-6dc3-401c-9398-08fc6b377b74/v2.0" # Example Tenant ID, adjust as needed
      x-google-jwks_uri: "https://login.microsoftonline.com/99d911b9-6dc3-401c-9398-08fc6b377b74/discovery/v2.0/keys" # Example Tenant ID, adjust
      x-google-audiences: "<% audiences %>"
      x-google-jwt-locations:
      - header: "Authorization"
      value_prefix: "Bearer "

2. Backend Service (e.g., Google Cloud Function)

  • This template does not include the backend service implementation itself.
  • The API Gateway is configured to route requests to a backend URL specified in openapi.yaml.erb under x-google-backend: address: <CLOUDFUNCTION-URL>.
  • This backend must be an HTTP/S service accessible by the API Gateway.

Testing

  • Automated Unit/Integration Tests: No specific automated test scripts for the API Gateway are included within this template repository. Backend tests (e.g., Cloud Function) should be performed in their own development cycle.
  • Post-Deployment API Tests: Once the API Gateway is deployed in a GCP environment, tests can be performed using standard HTTP client tools such as:
    • cURL
    • Postman
    • Any other REST API client.
  • General Testing Steps:
    1. Obtain the deployed API Gateway URL.
    2. Build the request according to the OpenAPI definition (method, path, headers, body).
    3. If security is enabled for the endpoint:
      • For api_key: Include the key as a query parameter (e.g., ?key=YOUR_API_KEY).
      • For google_id_token or azure_id_token: Obtain a valid token and include it in the Authorization header (e.g., Authorization: Bearer YOUR_ID_TOKEN).
    4. Send the request and verify the response (status code, body, headers).

Security Considerations

  • Credential Management:
    • Sensitive variables such as service_account details, project_id, audiences, gsuite_client_id, and the API Key value should be managed securely. Avoid committing real values directly in the deploy/env/*.yaml files if they are sensitive. Use CI/CD secrets (e.g., Jenkins credentials, GCP Secret Manager) to inject them during deployment.
    • The repository URL in .git/config contains an access token (glpat-...). Ensure this token has the minimum necessary permissions and is rotated if needed. For public documentation, it is better to use the HTTPS URL without embedded credentials.
  • API Keys: Consider GCP API Key restriction policies to limit usage to specific IPs, APIs, or services.
  • OAuth2 Tokens (Google/Azure):
    • Ensure that audiences and issuer are correctly configured to validate tokens appropriately.
    • Use HTTPS for all communications.
  • Service Account Permissions: The service account (service_account) associated with the API Gateway and/or the backend must have the minimum necessary permissions (Principle of Least Privilege).
  • Input Validation: Although the API Gateway can perform some basic validations based on OpenAPI, the backend service must also implement robust validation of all inputs.