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:
- Google API Gateway: Acts as the entry point for client requests. Manages authentication, routing, and other API policies.
- 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>). - 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. - 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. - CI/CD Pipeline (Jenkins): Uses the
Jenkinsfileto 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.erbtemplate, 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.erbfile locally. However, processing usually occurs in the CI/CD pipeline. - Access to the GitLab repository.
Configuration and Understanding Steps
-
Clone the repository: Follow the steps below
-
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 namedescription: Sample API on API Gateway with a Google Cloud Functions backendversion: 1.0.0schemes:- https# ... (rest of the file) ...paths:/path-name:get:summary: Greet a useroperationId: hellox-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 namein: "query"google_id_token:# ... (configuration for Google OAuth2)x-google-audiences: "<%= gsuite_client_id %>" # Placeholderazure_id_token:# ... (configuration for Azure AD OAuth2)x-google-audiences: "<% audiences %>" # Placeholder -
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 inopenapi.yaml.erbfor each environment. Example fromdeploy/env/dev.yaml:service_account: <service-account-name>project_id: <project-id>environment: "dev"location: "us-east1"audiences: <audences> # Used by azure_id_tokengsuite_client_id: <gsuite_client_id> # Used by google_id_tokenNote: The
<placeholder>values must be replaced with real values for each environment. These are usually managed as secrets in the CI/CD system. -
"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.
-
Jenkins Pipeline: The
Jenkinsfileat the project root defines the pipeline to use:pipelineLatam('gcloud-api-gateway-deploy')This pipeline is responsible for:
- Taking the
openapi.yaml.erbtemplate. - Processing the ERB template, injecting the corresponding variables from the environment file (
dev.yaml,intg.yaml, orprod.yaml) according to the deployment environment. - Deploying the resulting OpenAPI configuration to Google Cloud API Gateway in the specified project and region.
- Taking the
-
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:
| Parameter | Description | Example (Placeholder) |
|---|---|---|
service_account | The GCP service account that the API Gateway will use. | <service-account-name> |
project_id | The Google Cloud project ID where the API Gateway will be deployed. | <project-id> |
environment | Environment identifier (e.g., "dev", "intg", "prod"). | "dev" |
location | The GCP region where the API Gateway will be deployed (e.g., "us-east1"). | "us-east1" |
audiences | Audiences for Azure AD token validation (used in azure_id_token). | <audiences> |
gsuite_client_id | GSuite 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.
| Method | Path | Summary | Operation ID | Backend (Example) | Security Applied |
|---|---|---|---|---|---|
GET | /path-name | Greet a user | hello | <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
- Schema:
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.erbfile 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 forgoogle_id_token.<% audiences %>: Audience forazure_id_token.
- Security Schemes: Configured in the
securityDefinitionssection ofopenapi.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 neededx-google-jwks_uri: "https://login.microsoftonline.com/99d911b9-6dc3-401c-9398-08fc6b377b74/discovery/v2.0/keys" # Example Tenant ID, adjustx-google-audiences: "<% audiences %>"x-google-jwt-locations:- header: "Authorization"value_prefix: "Bearer "
- API Key (
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.erbunderx-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:
- Obtain the deployed API Gateway URL.
- Build the request according to the OpenAPI definition (method, path, headers, body).
- 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_tokenorazure_id_token: Obtain a valid token and include it in theAuthorizationheader (e.g.,Authorization: Bearer YOUR_ID_TOKEN).
- For
- Send the request and verify the response (status code, body, headers).
Security Considerations
- Credential Management:
- Sensitive variables such as
service_accountdetails,project_id,audiences,gsuite_client_id, and the API Key value should be managed securely. Avoid committing real values directly in thedeploy/env/*.yamlfiles 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/configcontains 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.
- Sensitive variables such as
- API Keys: Consider GCP API Key restriction policies to limit usage to specific IPs, APIs, or services.
- OAuth2 Tokens (Google/Azure):
- Ensure that
audiencesandissuerare correctly configured to validate tokens appropriately. - Use HTTPS for all communications.
- Ensure that
- 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.