diff --git a/docs/src/content/docs/en/guides/fastapi.mdx b/docs/src/content/docs/en/guides/fastapi.mdx
index a09dc700..7e28a1be 100644
--- a/docs/src/content/docs/en/guides/fastapi.mdx
+++ b/docs/src/content/docs/en/guides/fastapi.mdx
@@ -490,6 +490,8 @@ This sets up:
5. X-Ray tracing configuration
6. CloudWatch metrics namespace
+
+
:::note
If you selected to use `Cognito` authentication, you will need to supply the `identity` property to the API construct:
@@ -542,6 +544,8 @@ This sets up:
5. X-Ray tracing configuration
6. CORS configuration
+
+
:::note
If you selected to use `Cognito` authentication, you will need to supply the Cognito configuration:
diff --git a/docs/src/content/docs/en/guides/trpc.mdx b/docs/src/content/docs/en/guides/trpc.mdx
index 69ebaaf0..89d29177 100644
--- a/docs/src/content/docs/en/guides/trpc.mdx
+++ b/docs/src/content/docs/en/guides/trpc.mdx
@@ -425,6 +425,8 @@ export class ExampleStack extends Stack {
This sets up your API infrastructure, including an AWS API Gateway REST or HTTP API, AWS Lambda functions for business logic, and authentication based on your chosen `auth` method.
+
+
:::note
If you selected to use `Cognito` authentication, you will need to supply the `identity` property to the API construct:
@@ -477,6 +479,8 @@ This sets up:
5. X-Ray tracing configuration
6. CORS configuration
+
+
:::note
If you selected to use `Cognito` authentication, you will need to supply the Cognito configuration:
diff --git a/docs/src/content/docs/en/guides/ts-smithy-api.mdx b/docs/src/content/docs/en/guides/ts-smithy-api.mdx
index 571e8bdb..7b5e7559 100644
--- a/docs/src/content/docs/en/guides/ts-smithy-api.mdx
+++ b/docs/src/content/docs/en/guides/ts-smithy-api.mdx
@@ -405,6 +405,8 @@ This sets up:
4. CloudWatch log group
5. X-Ray tracing configuration
+
+
:::note
If you selected `Cognito` authentication, you will need to supply the `identity` property to the API construct:
@@ -457,6 +459,8 @@ This sets up:
5. X-Ray tracing configuration
6. CORS configuration
+
+
:::note
If you selected `Cognito` authentication, you will need to supply the Cognito configuration:
diff --git a/docs/src/content/docs/en/snippets/api/cors-configuration-cdk-note.mdx b/docs/src/content/docs/en/snippets/api/cors-configuration-cdk-note.mdx
new file mode 100644
index 00000000..448922a3
--- /dev/null
+++ b/docs/src/content/docs/en/snippets/api/cors-configuration-cdk-note.mdx
@@ -0,0 +1,25 @@
+---
+title: CORS configuration CDK
+---
+import Link from '@components/link.astro';
+
+:::note
+If your solution includes a website you can configure its CloudFront distribution as the only permitted CORS origin in the API gateway / API AWS Lambda integrations for HTTP / REST APIs. Note that this restriction is not applied to preflight OPTIONS for REST APIs - please +1 [this GitHub issue](https://github.com/awslabs/nx-plugin-for-aws/issues/377) to help prioritise addressing this.
+You will need to create the API and then call the API `restrictCorsTo` method with the created website.
+
+```ts
+import { MyApi, MyWebsite } from ':my-scope/common-constructs';
+
+export class ExampleStack extends Stack {
+ constructor(scope: Construct, id: string) {
+ const api = new MyApi(this, 'MyApi', {
+ integrations: MyApi.defaultIntegrations(this).build(),
+ });
+ const website = new MyWebsite(this, 'MyWebsite');
+ api.restrictCorsTo(website);
+ }
+}
+```
+
+The `MyWebsite` construct can be generated using the `ts#react-website` generator
+:::
\ No newline at end of file
diff --git a/docs/src/content/docs/en/snippets/api/cors-configuration-terraform-note.mdx b/docs/src/content/docs/en/snippets/api/cors-configuration-terraform-note.mdx
new file mode 100644
index 00000000..65591d7a
--- /dev/null
+++ b/docs/src/content/docs/en/snippets/api/cors-configuration-terraform-note.mdx
@@ -0,0 +1,26 @@
+---
+title: CORS configuration Terraform
+---
+import Link from '@components/link.astro';
+
+:::note
+If your solution includes a Terraform website module then you can use its CloudFront domain name to restrict CORS.
+Given a CloudFront domain name ``, within the Terraform module for deploying your API add
+- a `cors_allow_origins` property, set to `["http://localhost:4200", "http://localhost:4300", "https://"]`, for HTTP APIs. This restricts the API gateway CORS to this distribution and local host.
+- an `ALLOWED_ORIGINS` environment variable, set to `"https://"`, for REST APIs. This sets the CloudFront distribution as the only permitted CORS origin (other than local host) in AWS Lambda integrations. Note that this restriction is not applied to preflight OPTIONS - please +1 [this GitHub issue](https://github.com/awslabs/nx-plugin-for-aws/issues/377) to help prioritise addressing this.
+
+```hcl {4,7}
+module "my_api" {
+ source = "../../common/terraform/src/app/apis/my-api"
+
+ cors_allow_origins = ["http://localhost:4200", "http://localhost:4300", "https://"] // Only required for HTTP API
+
+ env = {
+ ALLOWED_ORIGINS = "https://" // Only required for REST API
+ ENVIRONMENT = var.environment
+ LOG_LEVEL = "INFO"
+ }
+}
+```
+The `MyWebsite` construct can be generated using the `ts#react-website` generator
+:::
\ No newline at end of file
diff --git a/docs/src/content/docs/es/guides/fastapi.mdx b/docs/src/content/docs/es/guides/fastapi.mdx
index 43e59187..71e3146f 100644
--- a/docs/src/content/docs/es/guides/fastapi.mdx
+++ b/docs/src/content/docs/es/guides/fastapi.mdx
@@ -3,8 +3,6 @@ title: "FastAPI"
description: "Documentación de referencia para FastAPI"
---
-
-
import { FileTree, AnchorHeading, Tabs, TabItem } from '@astrojs/starlight/components';
import Link from '@components/link.astro';
import RunGenerator from '@components/run-generator.astro';
@@ -249,7 +247,7 @@ export class MyApi extends Construct {
new CfnOutput(this, 'MyApiUrl', { value: functionUrl.url });
- // Registrar la URL en la configuración para descubrimiento de clientes
+ // Registrar la URL de la API en la configuración de runtime para descubrimiento del cliente
RuntimeConfig.ensure(this).config.apis = {
...RuntimeConfig.ensure(this).config.apis!,
MyApi: functionUrl.url,
@@ -295,7 +293,7 @@ resource "aws_lambda_function" "my_api_handler" {
timeout = 30
source_code_hash = filebase64sha256("../../../../../../dist/packages/my_api/bundle.zip")
- # Habilitar X-Ray
+ # Habilitar trazado X-Ray
tracing_config {
mode = "Active"
}
@@ -310,7 +308,7 @@ resource "aws_lambda_function" "my_api_handler" {
}
}
- # Capa de Lambda Web Adapter
+ # Añadir capa de Lambda Web Adapter
layers = [
"arn:aws:lambda:${data.aws_region.current.name}:753240598075:layer:LambdaAdapterLayerX86:24"
]
@@ -321,7 +319,7 @@ resource "aws_lambda_function" "my_api_handler" {
]
}
-# Grupo de logs de CloudWatch
+# Grupo de logs de CloudWatch para la función Lambda
resource "aws_cloudwatch_log_group" "lambda_logs" {
name = "/aws/lambda/my-api-handler"
retention_in_days = 14
@@ -351,7 +349,7 @@ resource "aws_iam_role_policy_attachment" "lambda_logs" {
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}
-# Adjuntar política de X-Ray
+# Adjuntar política de trazado X-Ray
resource "aws_iam_role_policy_attachment" "lambda_xray" {
role = aws_iam_role.lambda_execution_role.name
policy_arn = "arn:aws:iam::aws:policy/AWSXRayDaemonWriteAccess"
@@ -379,13 +377,13 @@ resource "aws_lambda_function_url" "my_api_url" {
}
}
-# Output de la URL
+# Output de la URL de la función
output "my_api_url" {
description = "URL para la función Lambda de FastAPI con streaming"
value = aws_lambda_function_url.my_api_url.function_url
}
-# Opcional: Crear parámetro SSM para configuración
+# Opcional: Crear parámetro SSM para configuración de runtime
resource "aws_ssm_parameter" "my_api_url" {
name = "/runtime-config/apis/MyApi"
type = "String"
@@ -397,10 +395,10 @@ resource "aws_ssm_parameter" "my_api_url" {
}
}
-# Política IAM para conceder acceso de invocación
+# Política IAM para conceder acceso de invocación a la Function URL
resource "aws_iam_policy" "my_api_invoke_policy" {
name = "my-api-invoke-policy"
- description = "Política para permitir invocar la función Lambda con streaming"
+ description = "Política para permitir invocar la Lambda Function URL de FastAPI con streaming"
policy = jsonencode({
Version = "2012-10-17"
@@ -419,7 +417,7 @@ resource "aws_iam_policy" "my_api_invoke_policy" {
})
}
-# Ejemplo: Adjuntar política a un rol (descomentar y modificar)
+# Ejemplo: Adjuntar la política de invocación a un rol (descomentar y modificar según sea necesario)
# resource "aws_iam_role_policy_attachment" "my_api_invoke_access" {
# role = var.authenticated_role_name
# policy_arn = aws_iam_policy.my_api_invoke_policy.arn
@@ -436,10 +434,10 @@ resource "aws_iam_policy" "my_api_invoke_policy" {
Una vez actualizada la infraestructura para soportar streaming, puedes implementar una API de streaming en FastAPI. La API debe:
- Devolver un [`StreamingResponse`](https://fastapi.tiangolo.com/reference/responses/?h=streaming#fastapi.responses.StreamingResponse)
-- Declarar el tipo de cada fragmento de respuesta
-- Añadir la extensión OpenAPI `x-streaming: true` si planeas usar API Connection.
+- Declarar el tipo de retorno de cada fragmento de respuesta
+- Añadir la extensión de proveedor OpenAPI `x-streaming: true` si planeas usar API Connection.
-Por ejemplo, para transmitir una serie de objetos JSON:
+Por ejemplo, si deseas transmitir una serie de objetos JSON desde tu API, puedes implementarlo de la siguiente manera:
```py /return (StreamingResponse)/ /openapi_extra[^)]*/ /-> (Chunk)/
from pydantic import BaseModel
@@ -460,15 +458,15 @@ def my_stream() -> Chunk:
#### Consumo
-Para consumir un stream de respuestas, puedes usar el generador API Connection que provee un método tipado para iterar sobre los fragmentos.
+Para consumir un stream de respuestas, puedes usar el generador API Connection que provee un método tipado para iterar sobre los fragmentos transmitidos.
## Desplegando tu API FastAPI
-El generador crea código de infraestructura CDK o Terraform según tu `iacProvider`. Puedes usarlo para desplegar tu API.
+El generador de FastAPI crea código de infraestructura CDK o Terraform según tu `iacProvider` seleccionado. Puedes usarlo para desplegar tu API FastAPI.
-El constructo CDK para desplegar tu API está en `common/constructs`. Puedes usarlo en una aplicación CDK:
+El constructo CDK para desplegar tu API está en la carpeta `common/constructs`. Puedes usarlo en una aplicación CDK:
```ts {6-8}
import { MyApi } from ':my-scope/common-constructs';
@@ -485,15 +483,17 @@ export class ExampleStack extends Stack {
Esto configura:
-1. Una función AWS Lambda por cada operación
-2. API Gateway HTTP/REST API como trigger
+1. Una función AWS Lambda por cada operación en la aplicación FastAPI
+2. API Gateway HTTP/REST API como trigger de la función
3. Roles y permisos IAM
4. Grupo de logs de CloudWatch
5. Configuración de trazado X-Ray
6. Namespace de métricas CloudWatch
+
+
:::note
-Si seleccionaste autenticación `Cognito`, debes proveer la propiedad `identity`:
+Si seleccionaste autenticación `Cognito`, debes proveer la propiedad `identity` al constructo de la API:
```ts {9}
import { MyApi, UserIdentity } from ':my-scope/common-constructs';
@@ -514,21 +514,21 @@ El constructo `UserIdentity` puede generarse con el
-Los módulos Terraform para desplegar tu API están en `common/terraform`. Puedes usarlos en una configuración Terraform:
+Los módulos Terraform para desplegar tu API están en la carpeta `common/terraform`. Puedes usarlos en una configuración Terraform:
```hcl {2}
module "my_api" {
source = "../../common/terraform/src/app/apis/my-api"
- # Variables de entorno para Lambda
+ # Variables de entorno para la función Lambda
env = {
ENVIRONMENT = var.environment
LOG_LEVEL = "INFO"
}
- # Políticas IAM adicionales
+ # Políticas IAM adicionales si es necesario
additional_iam_policy_statements = [
- # Permisos adicionales necesarios
+ # Añade los permisos adicionales que tu API necesite
]
tags = local.common_tags
@@ -537,13 +537,15 @@ module "my_api" {
Esto configura:
-1. Función Lambda que sirve todas las rutas
-2. API Gateway HTTP/REST API como trigger
+1. Una función Lambda que sirve todas las rutas de FastAPI
+2. API Gateway HTTP/REST API como trigger de la función
3. Roles y permisos IAM
4. Grupo de logs CloudWatch
5. Configuración de trazado X-Ray
6. Configuración CORS
+
+
:::note
Si seleccionaste autenticación `Cognito`, debes proveer su configuración:
@@ -563,29 +565,29 @@ module "my_api" {
}
```
-Puedes configurar Cognito User Pool y Client usando recursos Terraform.
+Puedes configurar Cognito User Pool y Client usando los recursos o módulos Terraform apropiados.
:::
-El módulo Terraform provee varios outputs:
+El módulo Terraform provee varios outputs que puedes usar:
```hcl
-# Acceder al endpoint
+# Acceder al endpoint de la API
output "api_url" {
value = module.my_api.stage_invoke_url
}
-# Detalles de la función Lambda
+# Acceder a los detalles de la función Lambda
output "lambda_function_name" {
value = module.my_api.lambda_function_name
}
-# Rol IAM para permisos adicionales
+# Acceder al rol IAM para conceder permisos adicionales
output "lambda_execution_role_arn" {
value = module.my_api.lambda_execution_role_arn
}
```
-Puedes personalizar CORS:
+Puedes personalizar la configuración CORS pasando variables al módulo:
```hcl
module "my_api" {
@@ -605,7 +607,7 @@ module "my_api" {
```
:::caution
-Si seleccionaste `None` para `auth`, puedes ver fallos en checks de Checkov:
+Si seleccionaste `None` para `auth` al ejecutar el generador, puedes ver fallos en checks de Checkov como:
@@ -622,7 +624,7 @@ Check: CKV_AWS_59: "Ensure there is no open access to back-end resources through
-Puedes [añadir un comentario de supresión](https://www.checkov.io/2.Basics/Suppressing%20and%20Skipping%20Policies.html) si deseas que tu API sea pública.
+Puedes [añadir un comentario de supresión](https://www.checkov.io/2.Basics/Suppressing%20and%20Skipping%20Policies.html) si estás seguro de que deseas que tu API sea pública.
:::
@@ -635,18 +637,18 @@ Puedes [añadir un comentario de supresión](https://www.checkov.io/2.Basics/Sup
-Dado que las operaciones en FastAPI se definen en Python y la infraestructura CDK en TypeScript, instrumentamos generación de código para proveer metadatos al constructo CDK.
+Dado que las operaciones en FastAPI se definen en Python y la infraestructura CDK en TypeScript, instrumentamos generación de código para proveer metadatos al constructo CDK y proporcionar una interfaz tipada para las integraciones.
-Se añade un target `generate:-metadata` al `project.json` de los constructos para generar código que emite archivos como `packages/common/constructs/src/generated/my-api/metadata.gen.ts`. Este archivo se ignora en control de versiones.
+Se añade un target `generate:-metadata` al `project.json` de los constructos comunes para facilitar esta generación de código, que emite un archivo como `packages/common/constructs/src/generated/my-api/metadata.gen.ts`. Dado que esto se genera en tiempo de build, se ignora en control de versiones.
:::note
-Debes ejecutar un build tras cambiar tu API para actualizar los tipos:
+Debes ejecutar un build cada vez que cambies tu API para asegurar que los tipos consumidos por el constructo CDK estén actualizados.
:::
:::tip
-Si trabajas simultáneamente en CDK y FastAPI, puedes usar [`nx watch`](https://nx.dev/nx-api/nx/documents/watch) para regenerar tipos automáticamente:
+Si trabajas activamente en tu infraestructura CDK y FastAPI simultáneamente, puedes usar [`nx watch`](https://nx.dev/nx-api/nx/documents/watch) para regenerar estos tipos cada vez que hagas cambios en la API:
@@ -675,10 +677,10 @@ api.grantInvokeAccess(myIdentityPool.authenticatedRole);
```hcl
-# Crear política IAM para invocar la API
+# Crear una política IAM para permitir invocar la API
resource "aws_iam_policy" "api_invoke_policy" {
name = "MyApiInvokePolicy"
- description = "Política para invocar la API FastAPI"
+ description = "Política para permitir invocar la FastAPI"
policy = jsonencode({
Version = "2012-10-17"
@@ -692,24 +694,24 @@ resource "aws_iam_policy" "api_invoke_policy" {
})
}
-# Adjuntar política a un rol IAM
+# Adjuntar la política a un rol IAM (por ejemplo, para usuarios autenticados)
resource "aws_iam_role_policy_attachment" "api_invoke_access" {
role = aws_iam_role.authenticated_user_role.name
policy_arn = aws_iam_policy.api_invoke_policy.arn
}
-# O adjuntar a un rol existente
+# O adjuntar a un rol existente por nombre
resource "aws_iam_role_policy_attachment" "api_invoke_access_existing" {
role = "MyExistingRole"
policy_arn = aws_iam_policy.api_invoke_policy.arn
}
```
-Outputs clave del módulo API:
+Los outputs clave del módulo API que puedes usar para políticas IAM son:
-- `module.my_api.api_execution_arn` - Para permisos execute-api:Invoke
-- `module.my_api.api_arn` - ARN de API Gateway
-- `module.my_api.lambda_function_arn` - ARN de la función Lambda
+- `module.my_api.api_execution_arn` - Para conceder permisos execute-api:Invoke
+- `module.my_api.api_arn` - El ARN de API Gateway
+- `module.my_api.lambda_function_arn` - El ARN de la función Lambda
@@ -719,12 +721,12 @@ El generador configura un servidor de desarrollo local que puedes ejecutar con:
-Esto inicia un servidor de desarrollo FastAPI con:
+Esto inicia un servidor de desarrollo FastAPI local con:
-- Recarga automática
-- Documentación interactiva en `/docs` o `/redoc`
+- Recarga automática al cambiar el código
+- Documentación interactiva de la API en `/docs` o `/redoc`
- Esquema OpenAPI en `/openapi.json`
## Invocando tu API FastAPI
-Para invocar tu API desde un sitio React, puedes usar el generador `api-connection`.
\ No newline at end of file
+Para invocar tu API desde un sitio React, puedes usar el generador `api-connection`.
\ No newline at end of file
diff --git a/docs/src/content/docs/es/guides/trpc.mdx b/docs/src/content/docs/es/guides/trpc.mdx
index 3e33f3db..063ddedc 100644
--- a/docs/src/content/docs/es/guides/trpc.mdx
+++ b/docs/src/content/docs/es/guides/trpc.mdx
@@ -3,8 +3,6 @@ title: "tRPC"
description: "Documentación de referencia para tRPC"
---
-
-
import { FileTree, Tabs, TabItem } from '@astrojs/starlight/components';
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
import Link from '@components/link.astro';
@@ -428,6 +426,8 @@ export class ExampleStack extends Stack {
Esto configura la infraestructura de tu API, incluyendo un AWS API Gateway REST o HTTP API, funciones AWS Lambda para lógica de negocio, y autenticación basada en tu método `auth` elegido.
+
+
:::note
Si seleccionaste usar autenticación `Cognito`, necesitarás proporcionar la propiedad `identity` al constructo de la API:
@@ -480,6 +480,8 @@ Esto configura:
5. Configuración de trazado X-Ray
6. Configuración CORS
+
+
:::note
Si seleccionaste usar autenticación `Cognito`, necesitarás proporcionar la configuración de Cognito:
diff --git a/docs/src/content/docs/es/guides/ts-smithy-api.mdx b/docs/src/content/docs/es/guides/ts-smithy-api.mdx
index 377511a1..0229df8b 100644
--- a/docs/src/content/docs/es/guides/ts-smithy-api.mdx
+++ b/docs/src/content/docs/es/guides/ts-smithy-api.mdx
@@ -3,8 +3,6 @@ title: "Smithy TypeScript API"
description: "Documentación de referencia para Smithy TypeScript API"
---
-
-
import { FileTree, AnchorHeading, Tabs, TabItem } from '@astrojs/starlight/components';
import Link from '@components/link.astro';
import RunGenerator from '@components/run-generator.astro';
@@ -407,6 +405,8 @@ Esto configura:
4. Grupo de logs de CloudWatch
5. Configuración de trazado X-Ray
+
+
:::note
Si seleccionaste autenticación `Cognito`, necesitarás proveer la propiedad `identity` al constructo de la API:
@@ -459,6 +459,8 @@ Esto configura:
5. Configuración de trazado X-Ray
6. Configuración CORS
+
+
:::note
Si seleccionaste autenticación `Cognito`, necesitarás proveer la configuración de Cognito:
diff --git a/docs/src/content/docs/es/snippets/api/cors-configuration-cdk-note.mdx b/docs/src/content/docs/es/snippets/api/cors-configuration-cdk-note.mdx
new file mode 100644
index 00000000..9b078a35
--- /dev/null
+++ b/docs/src/content/docs/es/snippets/api/cors-configuration-cdk-note.mdx
@@ -0,0 +1,26 @@
+---
+title: "Configuración de CORS en CDK"
+---
+
+import Link from '@components/link.astro';
+
+:::note
+Si tu solución incluye un sitio web, puedes configurar su distribución de CloudFront como el único origen CORS permitido en el API gateway / integraciones de API AWS Lambda para APIs HTTP / REST. Ten en cuenta que esta restricción no se aplica a las solicitudes preflight OPTIONS para APIs REST - por favor +1 [this GitHub issue](https://github.com/awslabs/nx-plugin-for-aws/issues/377) para ayudar a priorizar la solución de esto.
+Necesitarás crear la API y luego llamar al método `restrictCorsTo` de la API con el sitio web creado.
+
+```ts
+import { MyApi, MyWebsite } from ':my-scope/common-constructs';
+
+export class ExampleStack extends Stack {
+ constructor(scope: Construct, id: string) {
+ const api = new MyApi(this, 'MyApi', {
+ integrations: MyApi.defaultIntegrations(this).build(),
+ });
+ const website = new MyWebsite(this, 'MyWebsite');
+ api.restrictCorsTo(website);
+ }
+}
+```
+
+El constructo `MyWebsite` puede ser generado usando el generador `ts#react-website`
+:::
\ No newline at end of file
diff --git a/docs/src/content/docs/es/snippets/api/cors-configuration-terraform-note.mdx b/docs/src/content/docs/es/snippets/api/cors-configuration-terraform-note.mdx
new file mode 100644
index 00000000..53866c3d
--- /dev/null
+++ b/docs/src/content/docs/es/snippets/api/cors-configuration-terraform-note.mdx
@@ -0,0 +1,27 @@
+---
+title: "Configuración de CORS en Terraform"
+---
+
+import Link from '@components/link.astro';
+
+:::note
+Si su solución incluye un módulo de sitio web de Terraform, entonces puede usar su nombre de dominio de CloudFront para restringir CORS.
+Dado un nombre de dominio de CloudFront ``, dentro del módulo de Terraform para implementar su API agregue
+- una propiedad `cors_allow_origins`, establecida en `["http://localhost:4200", "http://localhost:4300", "https://"]`, para APIs HTTP. Esto restringe el CORS del gateway de API a esta distribución y host local.
+- una variable de entorno `ALLOWED_ORIGINS`, establecida en `"https://"`, para APIs REST. Esto establece la distribución de CloudFront como el único origen CORS permitido (aparte de host local) en las integraciones de AWS Lambda. Tenga en cuenta que esta restricción no se aplica a las solicitudes preflight OPTIONS - por favor +1 [este issue de GitHub](https://github.com/awslabs/nx-plugin-for-aws/issues/377) para ayudar a priorizar la resolución de esto.
+
+```hcl {4,7}
+module "my_api" {
+ source = "../../common/terraform/src/app/apis/my-api"
+
+ cors_allow_origins = ["http://localhost:4200", "http://localhost:4300", "https://"] // Only required for HTTP API
+
+ env = {
+ ALLOWED_ORIGINS = "https://" // Only required for REST API
+ ENVIRONMENT = var.environment
+ LOG_LEVEL = "INFO"
+ }
+}
+```
+El constructo `MyWebsite` puede ser generado usando el generador `ts#react-website`
+:::
\ No newline at end of file
diff --git a/docs/src/content/docs/fr/guides/fastapi.mdx b/docs/src/content/docs/fr/guides/fastapi.mdx
index 5f618534..ee0e6594 100644
--- a/docs/src/content/docs/fr/guides/fastapi.mdx
+++ b/docs/src/content/docs/fr/guides/fastapi.mdx
@@ -3,8 +3,6 @@ title: "FastAPI"
description: "Documentation de référence pour FastAPI"
---
-
-
import { FileTree, AnchorHeading, Tabs, TabItem } from '@astrojs/starlight/components';
import Link from '@components/link.astro';
import RunGenerator from '@components/run-generator.astro';
@@ -492,6 +490,8 @@ Ceci configure :
5. La configuration de traçage X-Ray
6. Un espace de noms pour les métriques CloudWatch
+
+
:::note
Si vous avez choisi l'authentification `Cognito`, vous devrez fournir la propriété `identity` au construct API :
@@ -544,6 +544,8 @@ Ceci configure :
5. La configuration de traçage X-Ray
6. La configuration CORS
+
+
:::note
Si vous avez choisi l'authentification `Cognito`, vous devrez fournir la configuration Cognito :
diff --git a/docs/src/content/docs/fr/guides/trpc.mdx b/docs/src/content/docs/fr/guides/trpc.mdx
index a1815a9f..a512fed3 100644
--- a/docs/src/content/docs/fr/guides/trpc.mdx
+++ b/docs/src/content/docs/fr/guides/trpc.mdx
@@ -3,8 +3,6 @@ title: "tRPC"
description: "Documentation de référence pour tRPC"
---
-
-
import { FileTree, Tabs, TabItem } from '@astrojs/starlight/components';
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
import Link from '@components/link.astro';
@@ -428,6 +426,8 @@ export class ExampleStack extends Stack {
Ceci configure l'infrastructure de votre API, incluant une API REST ou HTTP AWS API Gateway, des fonctions AWS Lambda pour la logique métier, et l'authentification selon la méthode `auth` choisie.
+
+
:::note
Si vous avez choisi d'utiliser l'authentification `Cognito`, vous devrez fournir la propriété `identity` au construct de l'API :
@@ -480,6 +480,8 @@ Ceci configure :
5. La configuration du tracing X-Ray
6. La configuration CORS
+
+
:::note
Si vous avez choisi d'utiliser l'authentification `Cognito`, vous devrez fournir la configuration Cognito :
diff --git a/docs/src/content/docs/fr/guides/ts-smithy-api.mdx b/docs/src/content/docs/fr/guides/ts-smithy-api.mdx
index 62e6e0b0..cbde695a 100644
--- a/docs/src/content/docs/fr/guides/ts-smithy-api.mdx
+++ b/docs/src/content/docs/fr/guides/ts-smithy-api.mdx
@@ -1,10 +1,8 @@
---
-title: "Documentation de l'API Smithy TypeScript"
+title: "API Smithy TypeScript"
description: "Documentation de référence pour l'API Smithy TypeScript"
---
-
-
import { FileTree, AnchorHeading, Tabs, TabItem } from '@astrojs/starlight/components';
import Link from '@components/link.astro';
import RunGenerator from '@components/run-generator.astro';
@@ -407,6 +405,8 @@ Ceci configure :
4. Un groupe de logs CloudWatch
5. La configuration de traçage X-Ray
+
+
:::note
Si vous avez sélectionné l'authentification `Cognito`, vous devrez fournir la propriété `identity` au construct API :
@@ -459,6 +459,8 @@ Ceci configure :
5. La configuration de traçage X-Ray
6. La configuration CORS
+
+
:::note
Si vous avez sélectionné l'authentification `Cognito`, vous devrez fournir la configuration Cognito :
diff --git a/docs/src/content/docs/fr/snippets/api/cors-configuration-cdk-note.mdx b/docs/src/content/docs/fr/snippets/api/cors-configuration-cdk-note.mdx
new file mode 100644
index 00000000..d226e6ed
--- /dev/null
+++ b/docs/src/content/docs/fr/snippets/api/cors-configuration-cdk-note.mdx
@@ -0,0 +1,26 @@
+---
+title: "Configuration CORS CDK"
+---
+
+import Link from '@components/link.astro';
+
+:::note
+Si votre solution inclut un site web, vous pouvez configurer sa distribution CloudFront comme seule origine CORS autorisée dans les intégrations API gateway / API AWS Lambda pour les API HTTP / REST. Notez que cette restriction ne s'applique pas aux requêtes OPTIONS de preflight pour les API REST - merci de +1 [this GitHub issue](https://github.com/awslabs/nx-plugin-for-aws/issues/377) pour aider à prioriser la résolution de ce problème.
+Vous devrez créer l'API puis appeler la méthode `restrictCorsTo` de l'API avec le site web créé.
+
+```ts
+import { MyApi, MyWebsite } from ':my-scope/common-constructs';
+
+export class ExampleStack extends Stack {
+ constructor(scope: Construct, id: string) {
+ const api = new MyApi(this, 'MyApi', {
+ integrations: MyApi.defaultIntegrations(this).build(),
+ });
+ const website = new MyWebsite(this, 'MyWebsite');
+ api.restrictCorsTo(website);
+ }
+}
+```
+
+Le construct `MyWebsite` peut être généré en utilisant le générateur `ts#react-website`
+:::
\ No newline at end of file
diff --git a/docs/src/content/docs/fr/snippets/api/cors-configuration-terraform-note.mdx b/docs/src/content/docs/fr/snippets/api/cors-configuration-terraform-note.mdx
new file mode 100644
index 00000000..42d3e8fd
--- /dev/null
+++ b/docs/src/content/docs/fr/snippets/api/cors-configuration-terraform-note.mdx
@@ -0,0 +1,27 @@
+---
+title: "Configuration CORS Terraform"
+---
+
+import Link from '@components/link.astro';
+
+:::note
+Si votre solution inclut un module de site web Terraform, vous pouvez utiliser son nom de domaine CloudFront pour restreindre CORS.
+Étant donné un nom de domaine CloudFront ``, dans le module Terraform pour déployer votre API, ajoutez
+- une propriété `cors_allow_origins`, définie sur `["http://localhost:4200", "http://localhost:4300", "https://"]`, pour les API HTTP. Cela restreint le CORS de la passerelle API à cette distribution et à l'hôte local.
+- une variable d'environnement `ALLOWED_ORIGINS`, définie sur `"https://"`, pour les API REST. Cela définit la distribution CloudFront comme la seule origine CORS autorisée (autre que l'hôte local) dans les intégrations AWS Lambda. Notez que cette restriction ne s'applique pas aux OPTIONS de pré-vérification - veuillez +1 [ce problème GitHub](https://github.com/awslabs/nx-plugin-for-aws/issues/377) pour aider à prioriser la résolution de ce point.
+
+```hcl {4,7}
+module "my_api" {
+ source = "../../common/terraform/src/app/apis/my-api"
+
+ cors_allow_origins = ["http://localhost:4200", "http://localhost:4300", "https://"] // Only required for HTTP API
+
+ env = {
+ ALLOWED_ORIGINS = "https://" // Only required for REST API
+ ENVIRONMENT = var.environment
+ LOG_LEVEL = "INFO"
+ }
+}
+```
+Le construct `MyWebsite` peut être généré en utilisant le générateur `ts#react-website`
+:::
\ No newline at end of file
diff --git a/docs/src/content/docs/it/guides/fastapi.mdx b/docs/src/content/docs/it/guides/fastapi.mdx
index 9ca53c8a..fdc58910 100644
--- a/docs/src/content/docs/it/guides/fastapi.mdx
+++ b/docs/src/content/docs/it/guides/fastapi.mdx
@@ -3,8 +3,6 @@ title: "FastAPI"
description: "Documentazione di riferimento per FastAPI"
---
-
-
import { FileTree, AnchorHeading, Tabs, TabItem } from '@astrojs/starlight/components';
import Link from '@components/link.astro';
import RunGenerator from '@components/run-generator.astro';
@@ -492,6 +490,8 @@ Questo configura:
5. Configurazione del tracciamento X-Ray
6. Namespace per le metriche CloudWatch
+
+
:::note
Se hai selezionato l'autenticazione `Cognito`, dovrai fornire la proprietà `identity` al costrutto API:
@@ -544,6 +544,8 @@ Questo configura:
5. Configurazione del tracciamento X-Ray
6. Configurazione CORS
+
+
:::note
Se hai selezionato l'autenticazione `Cognito`, dovrai fornire la configurazione Cognito:
diff --git a/docs/src/content/docs/it/guides/trpc.mdx b/docs/src/content/docs/it/guides/trpc.mdx
index 4a836bd2..180ef94b 100644
--- a/docs/src/content/docs/it/guides/trpc.mdx
+++ b/docs/src/content/docs/it/guides/trpc.mdx
@@ -3,8 +3,6 @@ title: "tRPC"
description: "Documentazione di riferimento per tRPC"
---
-
-
import { FileTree, Tabs, TabItem } from '@astrojs/starlight/components';
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
import Link from '@components/link.astro';
@@ -428,6 +426,8 @@ export class ExampleStack extends Stack {
Questo configura l'infrastruttura della tua API, inclusa un'API AWS API Gateway REST o HTTP, funzioni AWS Lambda per la business logic e autenticazione basata sul metodo `auth` scelto.
+
+
:::note
Se hai selezionato l'autenticazione `Cognito`, dovrai fornire la proprietà `identity` al costrutto API:
@@ -480,6 +480,8 @@ Questo configura:
5. Configurazione tracciamento X-Ray
6. Configurazione CORS
+
+
:::note
Se hai selezionato l'autenticazione `Cognito`, dovrai fornire la configurazione Cognito:
diff --git a/docs/src/content/docs/it/guides/ts-smithy-api.mdx b/docs/src/content/docs/it/guides/ts-smithy-api.mdx
index 6b074992..446ea937 100644
--- a/docs/src/content/docs/it/guides/ts-smithy-api.mdx
+++ b/docs/src/content/docs/it/guides/ts-smithy-api.mdx
@@ -3,8 +3,6 @@ title: "Smithy TypeScript API"
description: "Documentazione di riferimento per Smithy TypeScript API"
---
-
-
import { FileTree, AnchorHeading, Tabs, TabItem } from '@astrojs/starlight/components';
import Link from '@components/link.astro';
import RunGenerator from '@components/run-generator.astro';
@@ -407,6 +405,8 @@ Questo configura:
4. Log group CloudWatch
5. Configurazione del tracciamento X-Ray
+
+
:::note
Se hai selezionato autenticazione `Cognito`, dovrai fornire la proprietà `identity` al costrutto API:
@@ -459,6 +459,8 @@ Questo configura:
5. Configurazione del tracciamento X-Ray
6. Configurazione CORS
+
+
:::note
Se hai selezionato autenticazione `Cognito`, dovrai fornire la configurazione Cognito:
diff --git a/docs/src/content/docs/it/snippets/api/cors-configuration-cdk-note.mdx b/docs/src/content/docs/it/snippets/api/cors-configuration-cdk-note.mdx
new file mode 100644
index 00000000..96fb30b2
--- /dev/null
+++ b/docs/src/content/docs/it/snippets/api/cors-configuration-cdk-note.mdx
@@ -0,0 +1,26 @@
+---
+title: "Configurazione CORS CDK"
+---
+
+import Link from '@components/link.astro';
+
+:::note
+Se la tua soluzione include un sito web, puoi configurare la sua distribuzione CloudFront come unica origine CORS consentita nelle integrazioni API gateway / API AWS Lambda per le API HTTP / REST. Nota che questa restrizione non viene applicata alle richieste preflight OPTIONS per le API REST - per favore aggiungi un +1 a [questo issue su GitHub](https://github.com/awslabs/nx-plugin-for-aws/issues/377) per aiutare a dare priorità alla risoluzione di questo problema.
+Dovrai creare l'API e poi chiamare il metodo `restrictCorsTo` dell'API con il sito web creato.
+
+```ts
+import { MyApi, MyWebsite } from ':my-scope/common-constructs';
+
+export class ExampleStack extends Stack {
+ constructor(scope: Construct, id: string) {
+ const api = new MyApi(this, 'MyApi', {
+ integrations: MyApi.defaultIntegrations(this).build(),
+ });
+ const website = new MyWebsite(this, 'MyWebsite');
+ api.restrictCorsTo(website);
+ }
+}
+```
+
+Il costrutto `MyWebsite` può essere generato utilizzando il generatore `ts#react-website`
+:::
\ No newline at end of file
diff --git a/docs/src/content/docs/it/snippets/api/cors-configuration-terraform-note.mdx b/docs/src/content/docs/it/snippets/api/cors-configuration-terraform-note.mdx
new file mode 100644
index 00000000..e40512b4
--- /dev/null
+++ b/docs/src/content/docs/it/snippets/api/cors-configuration-terraform-note.mdx
@@ -0,0 +1,27 @@
+---
+title: "Configurazione CORS con Terraform"
+---
+
+import Link from '@components/link.astro';
+
+:::note
+Se la tua soluzione include un modulo Terraform per il sito web, puoi utilizzare il suo nome di dominio CloudFront per limitare CORS.
+Dato un nome di dominio CloudFront ``, all'interno del modulo Terraform per il deployment della tua API aggiungi
+- una proprietà `cors_allow_origins`, impostata a `["http://localhost:4200", "http://localhost:4300", "https://"]`, per le API HTTP. Questo limita il CORS dell'API gateway a questa distribuzione e al local host.
+- una variabile d'ambiente `ALLOWED_ORIGINS`, impostata a `"https://"`, per le API REST. Questo imposta la distribuzione CloudFront come unica origine CORS consentita (oltre al local host) nelle integrazioni AWS Lambda. Nota che questa restrizione non viene applicata al preflight OPTIONS - per favore metti +1 a [questa issue su GitHub](https://github.com/awslabs/nx-plugin-for-aws/issues/377) per aiutare a dare priorità alla risoluzione di questo problema.
+
+```hcl {4,7}
+module "my_api" {
+ source = "../../common/terraform/src/app/apis/my-api"
+
+ cors_allow_origins = ["http://localhost:4200", "http://localhost:4300", "https://"] // Only required for HTTP API
+
+ env = {
+ ALLOWED_ORIGINS = "https://" // Only required for REST API
+ ENVIRONMENT = var.environment
+ LOG_LEVEL = "INFO"
+ }
+}
+```
+Il costrutto `MyWebsite` può essere generato utilizzando il generatore `ts#react-website`
+:::
\ No newline at end of file
diff --git a/docs/src/content/docs/jp/guides/fastapi.mdx b/docs/src/content/docs/jp/guides/fastapi.mdx
index 3caa6286..df836bb8 100644
--- a/docs/src/content/docs/jp/guides/fastapi.mdx
+++ b/docs/src/content/docs/jp/guides/fastapi.mdx
@@ -3,8 +3,6 @@ title: "FastAPI"
description: "FastAPIのリファレンスドキュメント"
---
-
-
import { FileTree, AnchorHeading, Tabs, TabItem } from '@astrojs/starlight/components';
import Link from '@components/link.astro';
import RunGenerator from '@components/run-generator.astro';
@@ -492,6 +490,8 @@ export class ExampleStack extends Stack {
5. X-Ray トレーシング設定
6. CloudWatch メトリクスネームスペース
+
+
:::note
`Cognito` 認証を選択した場合、API コンストラクトに `identity` プロパティを指定する必要があります:
@@ -544,6 +544,8 @@ module "my_api" {
5. X-Rayトレーシング設定
6. CORS設定
+
+
:::note
`Cognito` 認証を選択した場合、Cognito設定を指定する必要があります:
diff --git a/docs/src/content/docs/jp/guides/trpc.mdx b/docs/src/content/docs/jp/guides/trpc.mdx
index cee13942..89d71ee2 100644
--- a/docs/src/content/docs/jp/guides/trpc.mdx
+++ b/docs/src/content/docs/jp/guides/trpc.mdx
@@ -3,8 +3,6 @@ title: "tRPC"
description: "tRPCのリファレンスドキュメント"
---
-
-
import { FileTree, Tabs, TabItem } from '@astrojs/starlight/components';
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
import Link from '@components/link.astro';
@@ -268,12 +266,134 @@ export const createIdentityPlugin = () => {
```ts
-// REST API 向け実装(原文のコードを保持)
+import { CognitoIdentityProvider } from '@aws-sdk/client-cognito-identity-provider';
+import { initTRPC, TRPCError } from '@trpc/server';
+import { CreateAWSLambdaContextOptions } from '@trpc/server/adapters/aws-lambda';
+import { APIGatewayProxyEvent } from 'aws-lambda';
+
+export interface IIdentityContext {
+ identity?: {
+ sub: string;
+ username: string;
+ };
+}
+
+export const createIdentityPlugin = () => {
+ const t = initTRPC.context>().create();
+
+ const cognito = new CognitoIdentityProvider();
+
+ return t.procedure.use(async (opts) => {
+ const cognitoAuthenticationProvider = opts.ctx.event.requestContext?.identity?.cognitoAuthenticationProvider;
+
+ let sub: string | undefined = undefined;
+ if (cognitoAuthenticationProvider) {
+ const providerParts = cognitoAuthenticationProvider.split(':');
+ sub = providerParts[providerParts.length - 1];
+ }
+
+ if (!sub) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: `Unable to determine calling user`,
+ });
+ }
+
+ const { Users } = await cognito.listUsers({
+ // Assumes user pool id is configured in lambda environment
+ UserPoolId: process.env.USER_POOL_ID!,
+ Limit: 1,
+ Filter: `sub="${sub}"`,
+ });
+
+ if (!Users || Users.length !== 1) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: `No user found with subjectId ${sub}`,
+ });
+ }
+
+ // Provide the identity to other procedures in the context
+ return await opts.next({
+ ctx: {
+ ...opts.ctx,
+ identity: {
+ sub,
+ username: Users[0].Username!,
+ },
+ },
+ });
+ });
+};
```
```ts
-// HTTP API 向け実装(原文のコードを保持)
+import { CognitoIdentityProvider } from '@aws-sdk/client-cognito-identity-provider';
+import { initTRPC, TRPCError } from '@trpc/server';
+import { CreateAWSLambdaContextOptions } from '@trpc/server/adapters/aws-lambda';
+import { APIGatewayProxyEventV2WithIAMAuthorizer } from 'aws-lambda';
+
+export interface IIdentityContext {
+ identity?: {
+ sub: string;
+ username: string;
+ };
+}
+
+export const createIdentityPlugin = () => {
+ const t = initTRPC.context>().create();
+
+ const cognito = new CognitoIdentityProvider();
+
+ return t.procedure.use(async (opts) => {
+ const cognitoIdentity = opts.ctx.event.requestContext?.authorizer?.iam
+ ?.cognitoIdentity as unknown as
+ | {
+ amr: string[];
+ }
+ | undefined;
+
+ const sub = (cognitoIdentity?.amr ?? [])
+ .flatMap((s) => (s.includes(':CognitoSignIn:') ? [s] : []))
+ .map((s) => {
+ const parts = s.split(':');
+ return parts[parts.length - 1];
+ })?.[0];
+
+ if (!sub) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: `Unable to determine calling user`,
+ });
+ }
+
+ const { Users } = await cognito.listUsers({
+ // Assumes user pool id is configured in lambda environment
+ UserPoolId: process.env.USER_POOL_ID!,
+ Limit: 1,
+ Filter: `sub="${sub}"`,
+ });
+
+ if (!Users || Users.length !== 1) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: `No user found with subjectId ${sub}`,
+ });
+ }
+
+ // Provide the identity to other procedures in the context
+ return await opts.next({
+ ctx: {
+ ...opts.ctx,
+ identity: {
+ sub,
+ username: Users[0].Username!,
+ },
+ },
+ });
+ });
+};
```
@@ -287,30 +407,155 @@ tRPC API ジェネレータは選択した `iacProvider` に基づき CDK また
CDK コンストラクトの使用例:
```ts {6-8}
-// CDK 実装例(原文のコードを保持)
+import { MyApi } from ':my-scope/common-constructs`;
+
+export class ExampleStack extends Stack {
+ constructor(scope: Construct, id: string) {
+ // Add the api to your stack
+ const api = new MyApi(this, 'MyApi', {
+ integrations: MyApi.defaultIntegrations(this).build(),
+ });
+ }
+}
```
+これにより、選択した `auth` 方法に基づく認証、ビジネスロジック用の AWS Lambda 関数、AWS API Gateway REST または HTTP API を含む API インフラストラクチャが設定されます。
+
+
+
:::note
-Cognito 認証を選択した場合の設定例:
+`Cognito` 認証を選択した場合、API コンストラクトに `identity` プロパティを指定する必要があります:
```ts {9}
-// Cognito 認証設定例(原文のコードを保持)
+import { MyApi, UserIdentity } from ':my-scope/common-constructs';
+
+export class ExampleStack extends Stack {
+ constructor(scope: Construct, id: string) {
+ const identity = new UserIdentity(this, 'Identity');
+
+ const api = new MyApi(this, 'MyApi', {
+ integrations: MyApi.defaultIntegrations(this).build(),
+ identity,
+ });
+ }
+}
```
+
+`UserIdentity` コンストラクトは `ts#react-website-auth` ジェネレータ を使用して生成できます
:::
Terraform モジュールの使用例:
```hcl {6-8}
-// Terraform 実装例(原文のコードを保持)
+module "my_api" {
+ source = "../../common/terraform/src/app/apis/my-api"
+
+ # Environment variables for the Lambda function
+ env = {
+ ENVIRONMENT = var.environment
+ LOG_LEVEL = "INFO"
+ }
+
+ # Additional IAM policies if needed
+ additional_iam_policy_statements = [
+ # Add any additional permissions your API needs
+ ]
+
+ tags = local.common_tags
+}
```
+これにより以下が設定されます:
+
+1. すべての tRPC プロシージャを提供する AWS Lambda 関数
+2. 関数トリガーとしての API Gateway HTTP/REST API
+3. IAM ロールと権限
+4. CloudWatch ロググループ
+5. X-Ray トレーシング設定
+6. CORS 設定
+
+
+
:::note
-Cognito 認証を選択した場合の設定例:
+`Cognito` 認証を選択した場合、Cognito 設定を指定する必要があります:
```hcl {4-5}
-// Cognito 認証設定例(原文のコードを保持)
+module "my_api" {
+ source = "../../common/terraform/src/app/apis/my-api"
+
+ user_pool_id = local.user_pool_id
+ user_pool_client_ids = [local.client_id]
+
+ env = {
+ ENVIRONMENT = var.environment
+ LOG_LEVEL = "INFO"
+ }
+
+ tags = local.common_tags
+}
+```
+
+適切な Terraform リソースまたはモジュールを使用して Cognito User Pool と Client を設定できます。
+:::
+
+Terraform モジュールは使用可能ないくつかの出力を提供します:
+
+```hcl
+# API エンドポイントへのアクセス
+output "api_url" {
+ value = module.my_api.stage_invoke_url
+}
+
+# Lambda 関数の詳細へのアクセス
+output "lambda_function_name" {
+ value = module.my_api.lambda_function_name
+}
+
+# 追加権限付与用の IAM ロールへのアクセス
+output "lambda_execution_role_arn" {
+ value = module.my_api.lambda_execution_role_arn
+}
+```
+
+モジュールに変数を渡すことで CORS 設定をカスタマイズできます:
+
+```hcl
+module "my_api" {
+ source = "../../common/terraform/src/app/apis/my-api"
+
+ # カスタム CORS 設定
+ cors_allow_origins = ["https://myapp.com", "https://staging.myapp.com"]
+ cors_allow_methods = ["GET", "POST", "PUT", "DELETE"]
+ cors_allow_headers = [
+ "authorization",
+ "content-type",
+ "x-custom-header"
+ ]
+
+ tags = local.common_tags
+}
+```
+
+:::caution
+ジェネレータ実行時に `auth` に `None` を選択した場合、以下のような Checkov チェックの失敗が表示される可能性があります:
+
+
+
+```
+Check: CKV_AWS_309: "Ensure API GatewayV2 routes specify an authorization type"
+ FAILED for resource: aws_apigatewayv2_route.proxy_routes["PUT"]
```
+
+
+```
+Check: CKV_AWS_59: "Ensure there is no open access to back-end resources through API"
+ FAILED for resource: aws_api_gateway_method.proxy_method
+```
+
+
+
+API を公開したい場合は、[抑制コメントを追加](https://www.checkov.io/2.Basics/Suppressing%20and%20Skipping%20Policies.html) できます。
:::
@@ -320,12 +565,12 @@ Cognito 認証を選択した場合の設定例:
:::tip
-CDK を選択した場合、tRPC API でプロシージャを追加/削除すると、再ビルドなしで CDK コンストラクトに即時反映されます
+`iacProvider` に CDK を選択した場合、tRPC API でプロシージャを追加/削除すると、再ビルドなしで CDK コンストラクトに即座に反映されます
:::
### アクセス権付与(IAM 認証時)
-IAM 認証を選択した場合のアクセス権付与:
+`IAM` 認証を選択した場合のアクセス権付与:
@@ -335,8 +580,41 @@ api.grantInvokeAccess(myIdentityPool.authenticatedRole);
```hcl
-# IAM ポリシー作成例(原文のコードを保持)
+# API 呼び出しを許可する IAM ポリシーを作成
+resource "aws_iam_policy" "api_invoke_policy" {
+ name = "MyApiInvokePolicy"
+ description = "Policy to allow invoking the tRPC API"
+
+ policy = jsonencode({
+ Version = "2012-10-17"
+ Statement = [
+ {
+ Effect = "Allow"
+ Action = "execute-api:Invoke"
+ Resource = "${module.my_api.api_execution_arn}/*/*"
+ }
+ ]
+ })
+}
+
+# IAM ロールにポリシーをアタッチ(例: 認証済みユーザー用)
+resource "aws_iam_role_policy_attachment" "api_invoke_access" {
+ role = aws_iam_role.authenticated_user_role.name
+ policy_arn = aws_iam_policy.api_invoke_policy.arn
+}
+
+# または既存のロールに名前でアタッチ
+resource "aws_iam_role_policy_attachment" "api_invoke_access_existing" {
+ role = "MyExistingRole"
+ policy_arn = aws_iam_policy.api_invoke_policy.arn
+}
```
+
+IAM ポリシーに使用できる API モジュールの主要な出力:
+
+- `module.my_api.api_execution_arn` - execute-api:Invoke 権限の付与用
+- `module.my_api.api_arn` - API Gateway ARN
+- `module.my_api.lambda_function_arn` - Lambda 関数 ARN
diff --git a/docs/src/content/docs/jp/guides/ts-smithy-api.mdx b/docs/src/content/docs/jp/guides/ts-smithy-api.mdx
index f781069b..756eaeb6 100644
--- a/docs/src/content/docs/jp/guides/ts-smithy-api.mdx
+++ b/docs/src/content/docs/jp/guides/ts-smithy-api.mdx
@@ -3,8 +3,6 @@ title: "Smithy TypeScriptのAPI"
description: "Smithy TypeScript APIのリファレンスドキュメント"
---
-
-
import { FileTree, AnchorHeading, Tabs, TabItem } from '@astrojs/starlight/components';
import Link from '@components/link.astro';
import RunGenerator from '@components/run-generator.astro';
@@ -407,6 +405,8 @@ export class ExampleStack extends Stack {
4. CloudWatchロググループ
5. X-Rayトレーシング設定
+
+
:::note
`Cognito`認証を選択した場合、APIコンストラクトに`identity`プロパティを指定する必要があります:
@@ -459,6 +459,8 @@ module "my_api" {
5. X-Rayトレーシング設定
6. CORS設定
+
+
:::note
`Cognito`認証を選択した場合、Cognito設定を指定する必要があります:
diff --git a/docs/src/content/docs/jp/snippets/api/cors-configuration-cdk-note.mdx b/docs/src/content/docs/jp/snippets/api/cors-configuration-cdk-note.mdx
new file mode 100644
index 00000000..d8f9094c
--- /dev/null
+++ b/docs/src/content/docs/jp/snippets/api/cors-configuration-cdk-note.mdx
@@ -0,0 +1,26 @@
+---
+title: "CORS設定CDK"
+---
+
+import Link from '@components/link.astro';
+
+:::note
+ソリューションにウェブサイトが含まれている場合、HTTP / REST API用のAPIゲートウェイ / API AWS Lambda統合において、CloudFrontディストリビューションを唯一許可されたCORSオリジンとして設定できます。この制限はREST APIのプリフライトOPTIONSには適用されないことに注意してください - この問題に対処する優先順位を上げるために、[このGitHub issue](https://github.com/awslabs/nx-plugin-for-aws/issues/377)に+1をお願いします。
+APIを作成してから、作成したウェブサイトを使用してAPIの`restrictCorsTo`メソッドを呼び出す必要があります。
+
+```ts
+import { MyApi, MyWebsite } from ':my-scope/common-constructs';
+
+export class ExampleStack extends Stack {
+ constructor(scope: Construct, id: string) {
+ const api = new MyApi(this, 'MyApi', {
+ integrations: MyApi.defaultIntegrations(this).build(),
+ });
+ const website = new MyWebsite(this, 'MyWebsite');
+ api.restrictCorsTo(website);
+ }
+}
+```
+
+`MyWebsite`コンストラクトは、`ts#react-website`ジェネレーターを使用して生成できます
+:::
\ No newline at end of file
diff --git a/docs/src/content/docs/jp/snippets/api/cors-configuration-terraform-note.mdx b/docs/src/content/docs/jp/snippets/api/cors-configuration-terraform-note.mdx
new file mode 100644
index 00000000..5c4581dc
--- /dev/null
+++ b/docs/src/content/docs/jp/snippets/api/cors-configuration-terraform-note.mdx
@@ -0,0 +1,27 @@
+---
+title: "CORS設定 Terraform"
+---
+
+import Link from '@components/link.astro';
+
+:::note
+ソリューションに Terraform ウェブサイトモジュールが含まれている場合、その CloudFront ドメイン名を使用して CORS を制限できます。
+CloudFront ドメイン名 `` が与えられた場合、API をデプロイするための Terraform モジュール内に以下を追加します
+- HTTP API の場合、`cors_allow_origins` プロパティを `["http://localhost:4200", "http://localhost:4300", "https://"]` に設定します。これにより、API ゲートウェイの CORS がこのディストリビューションとローカルホストに制限されます。
+- REST API の場合、`ALLOWED_ORIGINS` 環境変数を `"https://"` に設定します。これにより、AWS Lambda 統合において CloudFront ディストリビューションが(ローカルホスト以外の)唯一許可される CORS オリジンとして設定されます。なお、この制限はプリフライト OPTIONS には適用されません - この問題の優先順位付けを支援するために、[この GitHub issue](https://github.com/awslabs/nx-plugin-for-aws/issues/377) に +1 をお願いします。
+
+```hcl {4,7}
+module "my_api" {
+ source = "../../common/terraform/src/app/apis/my-api"
+
+ cors_allow_origins = ["http://localhost:4200", "http://localhost:4300", "https://"] // Only required for HTTP API
+
+ env = {
+ ALLOWED_ORIGINS = "https://" // Only required for REST API
+ ENVIRONMENT = var.environment
+ LOG_LEVEL = "INFO"
+ }
+}
+```
+`MyWebsite` コンストラクトは、`ts#react-website` ジェネレーターを使用して生成できます
+:::
\ No newline at end of file
diff --git a/docs/src/content/docs/ko/guides/fastapi.mdx b/docs/src/content/docs/ko/guides/fastapi.mdx
index a8d5c606..e285529e 100644
--- a/docs/src/content/docs/ko/guides/fastapi.mdx
+++ b/docs/src/content/docs/ko/guides/fastapi.mdx
@@ -3,8 +3,6 @@ title: "FastAPI"
description: "FastAPI에 대한 참조 문서"
---
-
-
import { FileTree, AnchorHeading, Tabs, TabItem } from '@astrojs/starlight/components';
import Link from '@components/link.astro';
import RunGenerator from '@components/run-generator.astro';
@@ -492,6 +490,8 @@ export class ExampleStack extends Stack {
5. X-Ray 추적 구성
6. CloudWatch 메트릭 네임스페이스
+
+
:::note
`Cognito` 인증을 선택한 경우 API 구성에 `identity` 속성을 제공해야 합니다:
@@ -544,6 +544,8 @@ module "my_api" {
5. X-Ray 추적 구성
6. CORS 구성
+
+
:::note
`Cognito` 인증을 선택한 경우 Cognito 구성을 제공해야 합니다:
@@ -706,6 +708,7 @@ resource "aws_iam_role_policy_attachment" "api_invoke_access_existing" {
```
API 모듈의 주요 출력:
+
- `module.my_api.api_execution_arn` - execute-api:Invoke 권한 부여용
- `module.my_api.api_arn` - API Gateway ARN
- `module.my_api.lambda_function_arn` - Lambda 함수 ARN
diff --git a/docs/src/content/docs/ko/guides/trpc.mdx b/docs/src/content/docs/ko/guides/trpc.mdx
index 25e91126..9b606191 100644
--- a/docs/src/content/docs/ko/guides/trpc.mdx
+++ b/docs/src/content/docs/ko/guides/trpc.mdx
@@ -3,8 +3,6 @@ title: "tRPC"
description: "tRPC에 대한 참조 문서"
---
-
-
import { FileTree, Tabs, TabItem } from '@astrojs/starlight/components';
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
import Link from '@components/link.astro';
@@ -235,7 +233,7 @@ export const echo = publicProcedure
예를 들어, API 호출 사용자에 대한 세부 정보를 추출하는 미들웨어를 `src/middleware/identity.ts`에 구현해 보겠습니다.
:::warning
-이 예제는 `auth`가 `IAM`으로 설정되었다고 가정합니다. Cognito 인증의 경우 이벤트에서 관련 클레임을 추출하는 것이 더 간단합니다.
+이 예제는 `auth`가 `IAM`으로 설정되었다고 가정합니다. Cognito 인증의 경우 `event`에서 관련 클레임을 추출하는 identity 미들웨어가 더 간단합니다.
:::
먼저 컨텍스트에 추가할 내용을 정의합니다:
@@ -249,7 +247,7 @@ export interface IIdentityContext {
}
```
-이 추가 _선택적_ 속성이 올바르게 이 미들웨어를 구성한 프로시저에서 정의됨을 tRPC가 관리합니다.
+컨텍스트에 추가 _선택적_ 속성을 정의한다는 점에 주목하세요. tRPC는 이 미들웨어를 올바르게 구성한 프로시저에서 이것이 정의되도록 관리합니다.
다음으로 미들웨어 자체를 구현합니다. 이는 다음 구조를 가집니다:
@@ -268,7 +266,7 @@ export const createIdentityPlugin = () => {
};
```
-이 경우 API Gateway 이벤트에서 사용자의 주체 ID("sub")를 추출하고 Cognito에서 사용자 세부 정보를 검색하려고 합니다. 구현은 이벤트가 REST API 또는 HTTP API에 의해 제공되었는지에 따라 약간 다릅니다:
+이 경우 호출하는 Cognito 사용자에 대한 세부 정보를 추출하려고 합니다. API Gateway 이벤트에서 사용자의 주체 ID("sub")를 추출하고 Cognito에서 사용자 세부 정보를 검색하여 이를 수행합니다. 구현은 이벤트가 REST API 또는 HTTP API에 의해 함수에 제공되었는지에 따라 약간 다릅니다:
@@ -428,6 +426,8 @@ export class ExampleStack extends Stack {
이 설정은 선택한 `auth` 방법을 기반으로 AWS API Gateway REST 또는 HTTP API, 비즈니스 로직을 위한 AWS Lambda 함수 및 인증을 포함한 API 인프라를 구성합니다.
+
+
:::note
`Cognito` 인증을 선택한 경우 API 구성에 `identity` 속성을 제공해야 합니다:
@@ -480,6 +480,8 @@ module "my_api" {
5. X-Ray 추적 구성
6. CORS 구성
+
+
:::note
`Cognito` 인증을 선택한 경우 Cognito 구성을 제공해야 합니다:
@@ -614,6 +616,7 @@ resource "aws_iam_role_policy_attachment" "api_invoke_access_existing" {
```
API 모듈에서 IAM 정책에 사용할 수 있는 주요 출력:
+
- `module.my_api.api_execution_arn` - execute-api:Invoke 권한 부여용
- `module.my_api.api_arn` - API Gateway ARN
- `module.my_api.lambda_function_arn` - Lambda 함수 ARN
diff --git a/docs/src/content/docs/ko/guides/ts-smithy-api.mdx b/docs/src/content/docs/ko/guides/ts-smithy-api.mdx
index c2f90bc1..a36ec7b8 100644
--- a/docs/src/content/docs/ko/guides/ts-smithy-api.mdx
+++ b/docs/src/content/docs/ko/guides/ts-smithy-api.mdx
@@ -3,8 +3,6 @@ title: "Smithy TypeScript API"
description: "Smithy TypeScript API 참조 문서"
---
-
-
import { FileTree, AnchorHeading, Tabs, TabItem } from '@astrojs/starlight/components';
import Link from '@components/link.astro';
import RunGenerator from '@components/run-generator.astro';
@@ -354,10 +352,11 @@ Smithy 모델 프로젝트는 [Docker](https://www.docker.com/)를 사용하여
:build']} />
이 과정은 다음을 수행합니다:
-1. Smithy 모델 컴파일 및 검증
-2. Smithy 모델에서 OpenAPI 명세 생성
-3. 타입 안전 오퍼레이션 인터페이스가 포함된 TypeScript Server SDK 생성
-4. `dist//build/`에 빌드 아티팩트 출력
+
+1. **Smithy 모델 컴파일** 및 검증
+2. Smithy 모델에서 **OpenAPI 명세 생성**
+3. 타입 안전 오퍼레이션 인터페이스가 포함된 **TypeScript Server SDK 생성**
+4. `dist//build/`에 **빌드 아티팩트 출력**
백엔드 프로젝트는 컴파일 시 생성된 SDK를 자동 복사합니다:
@@ -399,12 +398,15 @@ export class ExampleStack extends Stack {
```
이 설정은 다음을 구성합니다:
+
1. Smithy 서비스를 위한 AWS Lambda 함수
2. 함수 트리거로 API Gateway REST API
3. IAM 역할 및 권한
4. CloudWatch 로그 그룹
5. X-Ray 트레이싱 설정
+
+
:::note
`Cognito` 인증을 선택한 경우 API 구문에 `identity` 속성 제공 필요:
@@ -449,6 +451,7 @@ module "my_api" {
```
이 설정은 다음을 구성합니다:
+
1. Smithy API를 서비스하는 AWS Lambda 함수
2. 함수 트리거로 API Gateway REST API
3. IAM 역할 및 권한
@@ -456,6 +459,8 @@ module "my_api" {
5. X-Ray 트레이싱 설정
6. CORS 설정
+
+
:::note
`Cognito` 인증을 선택한 경우 Cognito 설정 제공 필요:
diff --git a/docs/src/content/docs/ko/snippets/api/cors-configuration-cdk-note.mdx b/docs/src/content/docs/ko/snippets/api/cors-configuration-cdk-note.mdx
new file mode 100644
index 00000000..0312ef64
--- /dev/null
+++ b/docs/src/content/docs/ko/snippets/api/cors-configuration-cdk-note.mdx
@@ -0,0 +1,26 @@
+---
+title: "CORS 구성 CDK"
+---
+
+import Link from '@components/link.astro';
+
+:::note
+솔루션에 웹사이트가 포함된 경우, HTTP / REST API용 API gateway / API AWS Lambda 통합에서 CloudFront 배포를 유일하게 허용되는 CORS 원본으로 구성할 수 있습니다. 이 제한은 REST API의 프리플라이트 OPTIONS에는 적용되지 않습니다 - 이 문제 해결의 우선순위를 높이는 데 도움이 되도록 [this GitHub issue](https://github.com/awslabs/nx-plugin-for-aws/issues/377)에 +1을 눌러주세요.
+API를 생성한 다음 생성된 웹사이트와 함께 API `restrictCorsTo` 메서드를 호출해야 합니다.
+
+```ts
+import { MyApi, MyWebsite } from ':my-scope/common-constructs';
+
+export class ExampleStack extends Stack {
+ constructor(scope: Construct, id: string) {
+ const api = new MyApi(this, 'MyApi', {
+ integrations: MyApi.defaultIntegrations(this).build(),
+ });
+ const website = new MyWebsite(this, 'MyWebsite');
+ api.restrictCorsTo(website);
+ }
+}
+```
+
+`MyWebsite` 구성요소는 `ts#react-website` generator를 사용하여 생성할 수 있습니다
+:::
\ No newline at end of file
diff --git a/docs/src/content/docs/ko/snippets/api/cors-configuration-terraform-note.mdx b/docs/src/content/docs/ko/snippets/api/cors-configuration-terraform-note.mdx
new file mode 100644
index 00000000..9cc8b38f
--- /dev/null
+++ b/docs/src/content/docs/ko/snippets/api/cors-configuration-terraform-note.mdx
@@ -0,0 +1,27 @@
+---
+title: "CORS 구성 Terraform"
+---
+
+import Link from '@components/link.astro';
+
+:::note
+솔루션에 Terraform 웹사이트 모듈이 포함되어 있다면 CloudFront 도메인 이름을 사용하여 CORS를 제한할 수 있습니다.
+CloudFront 도메인 이름 ``이 주어졌을 때, API 배포를 위한 Terraform 모듈 내에 다음을 추가하세요
+- HTTP API의 경우 `cors_allow_origins` 속성을 `["http://localhost:4200", "http://localhost:4300", "https://"]`로 설정합니다. 이는 API 게이트웨이 CORS를 이 배포와 로컬 호스트로 제한합니다.
+- REST API의 경우 `ALLOWED_ORIGINS` 환경 변수를 `"https://"`로 설정합니다. 이는 AWS Lambda 통합에서 CloudFront 배포를 유일하게 허용된 CORS 원본(로컬 호스트 제외)으로 설정합니다. 이 제한은 사전 확인(preflight) OPTIONS에는 적용되지 않습니다 - 이 문제 해결의 우선순위를 높이는 데 도움이 되도록 [이 GitHub 이슈](https://github.com/awslabs/nx-plugin-for-aws/issues/377)에 +1을 눌러주세요.
+
+```hcl {4,7}
+module "my_api" {
+ source = "../../common/terraform/src/app/apis/my-api"
+
+ cors_allow_origins = ["http://localhost:4200", "http://localhost:4300", "https://"] // Only required for HTTP API
+
+ env = {
+ ALLOWED_ORIGINS = "https://" // Only required for REST API
+ ENVIRONMENT = var.environment
+ LOG_LEVEL = "INFO"
+ }
+}
+```
+`MyWebsite` 구성체는 `ts#react-website` 생성기를 사용하여 생성할 수 있습니다
+:::
\ No newline at end of file
diff --git a/docs/src/content/docs/pt/guides/fastapi.mdx b/docs/src/content/docs/pt/guides/fastapi.mdx
index 4121b926..95022f27 100644
--- a/docs/src/content/docs/pt/guides/fastapi.mdx
+++ b/docs/src/content/docs/pt/guides/fastapi.mdx
@@ -3,8 +3,6 @@ title: "FastAPI"
description: "Documentação de referência para FastAPI"
---
-
-
import { FileTree, AnchorHeading, Tabs, TabItem } from '@astrojs/starlight/components';
import Link from '@components/link.astro';
import RunGenerator from '@components/run-generator.astro';
@@ -160,7 +158,7 @@ Exceções não tratadas são capturadas pelo middleware e:
3. Retornam resposta 500 segura ao cliente
4. Preservam o ID de correlação
-:::dica
+:::tip
Recomenda-se especificar modelos de resposta para operações da API para melhor geração de código ao usar o `api-connection`. Veja detalhes aqui.
:::
@@ -272,10 +270,10 @@ export class MyApi extends Construct {
-Para configurar com Terraform, substitua a infraestrutura do API Gateway por Lambda Function URL.
+Para configurar com Terraform, substitua a infraestrutura do API Gateway por Lambda Function URL que suporta streaming de respostas.
-Exemplo de Configuração Terraform para Function URL
+Exemplo de Configuração Lambda Function URL para Streaming
```hcl
data "aws_caller_identity" "current" {}
@@ -351,7 +349,9 @@ resource "aws_lambda_function_url" "my_api_url" {
invoke_mode = "RESPONSE_STREAM"
cors {
+ allow_credentials = false
allow_origins = ["*"]
+ allow_methods = ["*"]
allow_headers = [
"authorization",
"content-type",
@@ -359,10 +359,13 @@ resource "aws_lambda_function_url" "my_api_url" {
"x-amz-date",
"x-amz-security-token"
]
+ expose_headers = ["date", "keep-alive"]
+ max_age = 86400
}
}
output "my_api_url" {
+ description = "URL para a FastAPI Lambda Function com streaming"
value = aws_lambda_function_url.my_api_url.function_url
}
@@ -379,6 +382,7 @@ resource "aws_ssm_parameter" "my_api_url" {
resource "aws_iam_policy" "my_api_invoke_policy" {
name = "my-api-invoke-policy"
+ description = "Política para permitir invocar a FastAPI Lambda Function URL com streaming"
policy = jsonencode({
Version = "2012-10-17"
@@ -396,6 +400,11 @@ resource "aws_iam_policy" "my_api_invoke_policy" {
]
})
}
+
+# resource "aws_iam_role_policy_attachment" "my_api_invoke_access" {
+# role = var.authenticated_role_name
+# policy_arn = aws_iam_policy.my_api_invoke_policy.arn
+# }
```
@@ -405,13 +414,13 @@ resource "aws_iam_policy" "my_api_invoke_policy" {
#### Implementação
-Após atualizar a infraestrutura, você pode implementar streaming no FastAPI. A API deve:
+Após atualizar a infraestrutura para suportar streaming, você pode implementar uma API de streaming no FastAPI. A API deve:
- Retornar [`StreamingResponse`](https://fastapi.tiangolo.com/reference/responses/?h=streaming#fastapi.responses.StreamingResponse)
-- Declarar o tipo de retorno de cada chunk
+- Declarar o tipo de retorno de cada chunk de resposta
- Adicionar a extensão OpenAPI `x-streaming: true` se usar API Connection.
-Exemplo de streaming de objetos JSON:
+Por exemplo, para transmitir uma série de objetos JSON da API:
```py /return (StreamingResponse)/ /openapi_extra[^)]*/ /-> (Chunk)/
from pydantic import BaseModel
@@ -432,11 +441,11 @@ def my_stream() -> Chunk:
#### Consumo
-Para consumir streams, utilize o Gerador de Conexão de API.
+Para consumir streams, utilize o Gerador de Conexão de API, que fornece um método type-safe para iterar sobre os chunks transmitidos.
## Implantando sua API FastAPI
-O gerador cria código de infraestrutura CDK/Terraform baseado no `iacProvider`. Use para implantar:
+O gerador cria código de infraestrutura CDK ou Terraform baseado no `iacProvider`. Use para implantar:
@@ -463,6 +472,8 @@ Isso configura:
5. Configuração de X-Ray
6. Namespace de métricas
+
+
:::note
Se usar `Cognito`, forneça a propriedade `identity`:
@@ -474,6 +485,7 @@ export class ExampleStack extends Stack {
const identity = new UserIdentity(this, 'Identity');
const api = new MyApi(this, 'MyApi', {
+ integrations: MyApi.defaultIntegrations(this).build(),
identity,
});
}
@@ -509,7 +521,10 @@ Isso configura:
2. API Gateway HTTP/REST
3. Permissões IAM
4. Log group no CloudWatch
-5. Configuração de CORS
+5. Configuração de X-Ray
+6. Configuração de CORS
+
+
:::note
Para `Cognito`, forneça:
@@ -530,6 +545,7 @@ module "my_api" {
}
```
+Você pode configurar Cognito User Pool e Client usando recursos ou módulos Terraform apropriados.
:::
Saídas do módulo:
@@ -554,13 +570,19 @@ Personalize CORS:
module "my_api" {
source = "../../common/terraform/src/app/apis/my-api"
- cors_allow_origins = ["https://myapp.com"]
- cors_allow_methods = ["GET", "POST"]
- cors_allow_headers = ["authorization"]
+ cors_allow_origins = ["https://myapp.com", "https://staging.myapp.com"]
+ cors_allow_methods = ["GET", "POST", "PUT", "DELETE"]
+ cors_allow_headers = [
+ "authorization",
+ "content-type",
+ "x-custom-header"
+ ]
+
+ tags = local.common_tags
}
```
-:::cuidado
+:::caution
Se selecionar `None` para `auth`, Checkov pode reportar falhas:
@@ -601,7 +623,7 @@ Execute um build após alterar a API:
:::
-:::dica
+:::tip
Use [`nx watch`](https://nx.dev/nx-api/nx/documents/watch) para regenerar tipos automaticamente:
diff --git a/docs/src/content/docs/pt/guides/trpc.mdx b/docs/src/content/docs/pt/guides/trpc.mdx
index 179ae956..e77ace31 100644
--- a/docs/src/content/docs/pt/guides/trpc.mdx
+++ b/docs/src/content/docs/pt/guides/trpc.mdx
@@ -3,8 +3,6 @@ title: "tRPC"
description: "Documentação de referência para tRPC"
---
-
-
import { FileTree, Tabs, TabItem } from '@astrojs/starlight/components';
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
import Link from '@components/link.astro';
@@ -421,6 +419,8 @@ export class ExampleStack extends Stack {
Isso configura infraestrutura incluindo AWS API Gateway, AWS Lambda e autenticação.
+
+
:::note
Para autenticação Cognito, forneça a propriedade `identity`:
@@ -432,6 +432,7 @@ export class ExampleStack extends Stack {
const identity = new UserIdentity(this, 'Identity');
const api = new MyApi(this, 'MyApi', {
+ integrations: MyApi.defaultIntegrations(this).build(),
identity,
});
}
@@ -469,6 +470,8 @@ Configura:
5. X-Ray
6. CORS
+
+
:::note
Para Cognito, forneça:
@@ -478,6 +481,13 @@ module "my_api" {
user_pool_id = local.user_pool_id
user_pool_client_ids = [local.client_id]
+
+ env = {
+ ENVIRONMENT = var.environment
+ LOG_LEVEL = "INFO"
+ }
+
+ tags = local.common_tags
}
```
@@ -508,11 +518,35 @@ module "my_api" {
cors_allow_origins = ["https://myapp.com", "https://staging.myapp.com"]
cors_allow_methods = ["GET", "POST", "PUT", "DELETE"]
+ cors_allow_headers = [
+ "authorization",
+ "content-type",
+ "x-custom-header"
+ ]
+
+ tags = local.common_tags
}
```
:::caution
-Se `auth` for `None`, Checkov pode reportar falhas. Suprima conforme necessário.
+Se `auth` for `None`, Checkov pode reportar falhas:
+
+
+
+```
+Check: CKV_AWS_309: "Ensure API GatewayV2 routes specify an authorization type"
+ FAILED for resource: aws_apigatewayv2_route.proxy_routes["PUT"]
+```
+
+
+```
+Check: CKV_AWS_59: "Ensure there is no open access to back-end resources through API"
+ FAILED for resource: aws_api_gateway_method.proxy_method
+```
+
+
+
+Adicione [comentário de supressão](https://www.checkov.io/2.Basics/Suppressing%20and%20Skipping%20Policies.html) se desejar API pública.
:::
@@ -539,7 +573,10 @@ api.grantInvokeAccess(myIdentityPool.authenticatedRole);
```hcl
resource "aws_iam_policy" "api_invoke_policy" {
name = "MyApiInvokePolicy"
+ description = "Policy to allow invoking the tRPC API"
+
policy = jsonencode({
+ Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
@@ -554,7 +591,18 @@ resource "aws_iam_role_policy_attachment" "api_invoke_access" {
role = aws_iam_role.authenticated_user_role.name
policy_arn = aws_iam_policy.api_invoke_policy.arn
}
+
+resource "aws_iam_role_policy_attachment" "api_invoke_access_existing" {
+ role = "MyExistingRole"
+ policy_arn = aws_iam_policy.api_invoke_policy.arn
+}
```
+
+Saídas úteis do módulo:
+
+- `module.my_api.api_execution_arn` - Para permissões execute-api:Invoke
+- `module.my_api.api_arn` - ARN do API Gateway
+- `module.my_api.lambda_function_arn` - ARN da função Lambda
diff --git a/docs/src/content/docs/pt/guides/ts-smithy-api.mdx b/docs/src/content/docs/pt/guides/ts-smithy-api.mdx
index 6b1ca32c..9e591d40 100644
--- a/docs/src/content/docs/pt/guides/ts-smithy-api.mdx
+++ b/docs/src/content/docs/pt/guides/ts-smithy-api.mdx
@@ -3,8 +3,6 @@ title: "API TypeScript do Smithy"
description: "Documentação de referência para a API TypeScript do Smithy"
---
-
-
import { FileTree, AnchorHeading, Tabs, TabItem } from '@astrojs/starlight/components';
import Link from '@components/link.astro';
import RunGenerator from '@components/run-generator.astro';
@@ -407,6 +405,8 @@ Isso configura:
4. Grupo de logs CloudWatch
5. Configuração de rastreamento X-Ray
+
+
:::note
Se você selecionou autenticação `Cognito`, precisará fornecer a propriedade `identity` ao construct da API:
@@ -459,6 +459,8 @@ Isso configura:
5. Configuração de rastreamento X-Ray
6. Configuração CORS
+
+
:::note
Se você selecionou autenticação `Cognito`, precisará fornecer a configuração Cognito:
diff --git a/docs/src/content/docs/pt/snippets/api/cors-configuration-cdk-note.mdx b/docs/src/content/docs/pt/snippets/api/cors-configuration-cdk-note.mdx
new file mode 100644
index 00000000..6c609628
--- /dev/null
+++ b/docs/src/content/docs/pt/snippets/api/cors-configuration-cdk-note.mdx
@@ -0,0 +1,26 @@
+---
+title: "Configuração CORS CDK"
+---
+
+import Link from '@components/link.astro';
+
+:::note
+Se a sua solução incluir um website, você pode configurar a sua distribuição CloudFront como a única origem CORS permitida nas integrações API gateway / API AWS Lambda para APIs HTTP / REST. Note que esta restrição não é aplicada ao preflight OPTIONS para APIs REST - por favor, dê +1 nesta [issue do GitHub](https://github.com/awslabs/nx-plugin-for-aws/issues/377) para ajudar a priorizar a resolução disto.
+Você precisará criar a API e então chamar o método `restrictCorsTo` da API com o website criado.
+
+```ts
+import { MyApi, MyWebsite } from ':my-scope/common-constructs';
+
+export class ExampleStack extends Stack {
+ constructor(scope: Construct, id: string) {
+ const api = new MyApi(this, 'MyApi', {
+ integrations: MyApi.defaultIntegrations(this).build(),
+ });
+ const website = new MyWebsite(this, 'MyWebsite');
+ api.restrictCorsTo(website);
+ }
+}
+```
+
+O construtor `MyWebsite` pode ser gerado usando o gerador `ts#react-website`
+:::
\ No newline at end of file
diff --git a/docs/src/content/docs/pt/snippets/api/cors-configuration-terraform-note.mdx b/docs/src/content/docs/pt/snippets/api/cors-configuration-terraform-note.mdx
new file mode 100644
index 00000000..965cb049
--- /dev/null
+++ b/docs/src/content/docs/pt/snippets/api/cors-configuration-terraform-note.mdx
@@ -0,0 +1,27 @@
+---
+title: "Configuração CORS Terraform"
+---
+
+import Link from '@components/link.astro';
+
+:::note
+Se sua solução incluir um módulo de website Terraform, você pode usar seu nome de domínio CloudFront para restringir CORS.
+Dado um nome de domínio CloudFront ``, dentro do módulo Terraform para implantar sua API adicione
+- uma propriedade `cors_allow_origins`, definida como `["http://localhost:4200", "http://localhost:4300", "https://"]`, para APIs HTTP. Isso restringe o CORS do gateway de API a esta distribuição e ao host local.
+- uma variável de ambiente `ALLOWED_ORIGINS`, definida como `"https://"`, para APIs REST. Isso define a distribuição CloudFront como a única origem CORS permitida (além do host local) nas integrações AWS Lambda. Observe que essa restrição não é aplicada ao preflight OPTIONS - por favor +1 [neste issue do GitHub](https://github.com/awslabs/nx-plugin-for-aws/issues/377) para ajudar a priorizar a solução deste problema.
+
+```hcl {4,7}
+module "my_api" {
+ source = "../../common/terraform/src/app/apis/my-api"
+
+ cors_allow_origins = ["http://localhost:4200", "http://localhost:4300", "https://"] // Only required for HTTP API
+
+ env = {
+ ALLOWED_ORIGINS = "https://" // Only required for REST API
+ ENVIRONMENT = var.environment
+ LOG_LEVEL = "INFO"
+ }
+}
+```
+O construtor `MyWebsite` pode ser gerado usando o gerador `ts#react-website`
+:::
\ No newline at end of file
diff --git a/docs/src/content/docs/vi/guides/fastapi.mdx b/docs/src/content/docs/vi/guides/fastapi.mdx
index 4339df47..1ab5bf36 100644
--- a/docs/src/content/docs/vi/guides/fastapi.mdx
+++ b/docs/src/content/docs/vi/guides/fastapi.mdx
@@ -490,6 +490,8 @@ export class ExampleStack extends Stack {
5. Cấu hình X-Ray tracing
6. CloudWatch metrics namespace
+
+
:::note
Nếu bạn chọn sử dụng xác thực `Cognito`, bạn sẽ cần cung cấp thuộc tính `identity` cho API construct:
@@ -542,6 +544,8 @@ module "my_api" {
5. Cấu hình X-Ray tracing
6. Cấu hình CORS
+
+
:::note
Nếu bạn chọn sử dụng xác thực `Cognito`, bạn sẽ cần cung cấp cấu hình Cognito:
diff --git a/docs/src/content/docs/vi/guides/trpc.mdx b/docs/src/content/docs/vi/guides/trpc.mdx
index b3544509..041b1321 100644
--- a/docs/src/content/docs/vi/guides/trpc.mdx
+++ b/docs/src/content/docs/vi/guides/trpc.mdx
@@ -426,6 +426,8 @@ export class ExampleStack extends Stack {
Điều này thiết lập cơ sở hạ tầng API của bạn, bao gồm AWS API Gateway REST hoặc HTTP API, các hàm AWS Lambda cho logic nghiệp vụ, và xác thực dựa trên phương thức `auth` bạn đã chọn.
+
+
:::note
Nếu bạn đã chọn sử dụng xác thực `Cognito`, bạn sẽ cần cung cấp thuộc tính `identity` cho API construct:
@@ -478,6 +480,8 @@ module "my_api" {
5. Cấu hình X-Ray tracing
6. Cấu hình CORS
+
+
:::note
Nếu bạn đã chọn sử dụng xác thực `Cognito`, bạn sẽ cần cung cấp cấu hình Cognito:
diff --git a/docs/src/content/docs/vi/guides/ts-smithy-api.mdx b/docs/src/content/docs/vi/guides/ts-smithy-api.mdx
index 431ac178..9c4e4f22 100644
--- a/docs/src/content/docs/vi/guides/ts-smithy-api.mdx
+++ b/docs/src/content/docs/vi/guides/ts-smithy-api.mdx
@@ -405,6 +405,8 @@ export class ExampleStack extends Stack {
4. CloudWatch log group
5. Cấu hình X-Ray tracing
+
+
:::note
Nếu bạn đã chọn xác thực `Cognito`, bạn sẽ cần cung cấp thuộc tính `identity` cho API construct:
@@ -457,6 +459,8 @@ module "my_api" {
5. Cấu hình X-Ray tracing
6. Cấu hình CORS
+
+
:::note
Nếu bạn đã chọn xác thực `Cognito`, bạn sẽ cần cung cấp cấu hình Cognito:
diff --git a/docs/src/content/docs/vi/snippets/api/cors-configuration-cdk-note.mdx b/docs/src/content/docs/vi/snippets/api/cors-configuration-cdk-note.mdx
new file mode 100644
index 00000000..69de2227
--- /dev/null
+++ b/docs/src/content/docs/vi/snippets/api/cors-configuration-cdk-note.mdx
@@ -0,0 +1,26 @@
+---
+title: "Cấu hình CORS CDK"
+---
+
+import Link from '@components/link.astro';
+
+:::note
+Nếu giải pháp của bạn bao gồm một trang web, bạn có thể cấu hình phân phối CloudFront của nó làm nguồn gốc CORS duy nhất được phép trong API gateway / tích hợp API AWS Lambda cho HTTP / REST APIs. Lưu ý rằng hạn chế này không được áp dụng cho preflight OPTIONS đối với REST APIs - vui lòng +1 [GitHub issue này](https://github.com/awslabs/nx-plugin-for-aws/issues/377) để giúp ưu tiên giải quyết vấn đề này.
+Bạn sẽ cần tạo API và sau đó gọi phương thức `restrictCorsTo` của API với trang web đã tạo.
+
+```ts
+import { MyApi, MyWebsite } from ':my-scope/common-constructs';
+
+export class ExampleStack extends Stack {
+ constructor(scope: Construct, id: string) {
+ const api = new MyApi(this, 'MyApi', {
+ integrations: MyApi.defaultIntegrations(this).build(),
+ });
+ const website = new MyWebsite(this, 'MyWebsite');
+ api.restrictCorsTo(website);
+ }
+}
+```
+
+Construct `MyWebsite` có thể được tạo bằng cách sử dụng generator `ts#react-website`
+:::
\ No newline at end of file
diff --git a/docs/src/content/docs/vi/snippets/api/cors-configuration-terraform-note.mdx b/docs/src/content/docs/vi/snippets/api/cors-configuration-terraform-note.mdx
new file mode 100644
index 00000000..f170f082
--- /dev/null
+++ b/docs/src/content/docs/vi/snippets/api/cors-configuration-terraform-note.mdx
@@ -0,0 +1,27 @@
+---
+title: "Cấu hình CORS với Terraform"
+---
+
+import Link from '@components/link.astro';
+
+:::note
+Nếu giải pháp của bạn bao gồm một module website Terraform thì bạn có thể sử dụng tên miền CloudFront của nó để hạn chế CORS.
+Với tên miền CloudFront ``, trong module Terraform để triển khai API của bạn, hãy thêm
+- một thuộc tính `cors_allow_origins`, đặt thành `["http://localhost:4200", "http://localhost:4300", "https://"]`, cho HTTP APIs. Điều này hạn chế CORS của API gateway đối với phân phối này và local host.
+- một biến môi trường `ALLOWED_ORIGINS`, đặt thành `"https://"`, cho REST APIs. Điều này đặt phân phối CloudFront là nguồn gốc CORS duy nhất được phép (ngoài local host) trong các tích hợp AWS Lambda. Lưu ý rằng hạn chế này không được áp dụng cho preflight OPTIONS - vui lòng +1 [GitHub issue này](https://github.com/awslabs/nx-plugin-for-aws/issues/377) để giúp ưu tiên giải quyết vấn đề này.
+
+```hcl {4,7}
+module "my_api" {
+ source = "../../common/terraform/src/app/apis/my-api"
+
+ cors_allow_origins = ["http://localhost:4200", "http://localhost:4300", "https://"] // Only required for HTTP API
+
+ env = {
+ ALLOWED_ORIGINS = "https://" // Only required for REST API
+ ENVIRONMENT = var.environment
+ LOG_LEVEL = "INFO"
+ }
+}
+```
+Cấu trúc `MyWebsite` có thể được tạo bằng cách sử dụng trình tạo `ts#react-website`
+:::
\ No newline at end of file
diff --git a/docs/src/content/docs/zh/guides/fastapi.mdx b/docs/src/content/docs/zh/guides/fastapi.mdx
index 9324cc9c..b6be61a7 100644
--- a/docs/src/content/docs/zh/guides/fastapi.mdx
+++ b/docs/src/content/docs/zh/guides/fastapi.mdx
@@ -3,8 +3,6 @@ title: "FastAPI"
description: "FastAPI 参考文档"
---
-
-
import { FileTree, AnchorHeading, Tabs, TabItem } from '@astrojs/starlight/components';
import Link from '@components/link.astro';
import RunGenerator from '@components/run-generator.astro';
@@ -15,13 +13,13 @@ import Snippet from '@components/snippet.astro';
[FastAPI](https://fastapi.tiangolo.com/) 是一个用于构建 Python API 的框架。
-FastAPI 生成器可创建带有 AWS CDK 或 Terraform 基础设施配置的新 FastAPI 项目。生成的后端使用 AWS Lambda 进行无服务器部署,通过 AWS API Gateway API 暴露接口。它配置了 [AWS Lambda Powertools](https://docs.powertools.aws.dev/lambda/python/latest/) 用于可观测性,包括日志记录、AWS X-Ray 追踪和 Cloudwatch 指标。
+FastAPI 生成器可创建带有 AWS CDK 或 Terraform 基础设施配置的新 FastAPI 项目。生成的后端使用 AWS Lambda 进行无服务器部署,通过 AWS API Gateway API 暴露接口。它配置了 [AWS Lambda Powertools](https://docs.powertools.aws.dev/lambda/python/latest/) 用于可观测性,包括日志记录、AWS X-Ray 追踪和 Cloudwatch 指标。
## 使用方式
### 生成 FastAPI
-您可以通过两种方式生成新的 FastAPI:
+您可以通过两种方式生成新的 FastAPI:
@@ -33,7 +31,7 @@ FastAPI 生成器可创建带有 AWS CDK 或 Terraform 基础设施配置的新
## 生成器输出
-生成器将在 `/` 目录下创建以下项目结构:
+生成器将在 `/` 目录下创建以下项目结构:
@@ -56,7 +54,7 @@ FastAPI 生成器可创建带有 AWS CDK 或 Terraform 基础设施配置的新
## 实现 FastAPI
-主要的 API 实现位于 `main.py`。这是定义 API 路由及其实现的地方。示例如下:
+主要的 API 实现位于 `main.py`。这是定义 API 路由及其实现的地方。示例如下:
```python
from .init import app, tracer
@@ -74,7 +72,7 @@ def create_item(item: Item):
return ...
```
-生成器自动配置了以下功能:
+生成器自动配置了以下功能:
1. 用于可观测性的 AWS Lambda Powertools 集成
2. 错误处理中间件
@@ -86,7 +84,7 @@ def create_item(item: Item):
#### 日志记录
-生成器使用 AWS Lambda Powertools 配置结构化日志记录。您可以在路由处理程序中访问日志记录器:
+生成器使用 AWS Lambda Powertools 配置结构化日志记录。您可以在路由处理程序中访问日志记录器:
```python
from .init import app, logger
@@ -97,7 +95,7 @@ def read_item(item_id: int):
return {"item_id": item_id}
```
-日志记录器自动包含:
+日志记录器自动包含:
- 用于请求追踪的关联 ID
- 请求路径和方法
@@ -106,7 +104,7 @@ def read_item(item_id: int):
#### 追踪
-自动配置 AWS X-Ray 追踪。您可以为追踪添加自定义子段:
+自动配置 AWS X-Ray 追踪。您可以为追踪添加自定义子段:
```python
from .init import app, tracer
@@ -122,7 +120,7 @@ def read_item(item_id: int):
#### 指标
-自动收集每个请求的 CloudWatch 指标。您可以添加自定义指标:
+自动收集每个请求的 CloudWatch 指标。您可以添加自定义指标:
```python
from .init import app, metrics
@@ -134,7 +132,7 @@ def read_item(item_id: int):
return {"item_id": item_id}
```
-默认指标包括:
+默认指标包括:
- 请求计数
- 成功/失败计数
@@ -143,7 +141,7 @@ def read_item(item_id: int):
### 错误处理
-生成器包含全面的错误处理:
+生成器包含全面的错误处理:
```python
from fastapi import HTTPException
@@ -155,7 +153,7 @@ def read_item(item_id: int):
return {"item_id": item_id}
```
-未捕获的异常会被中间件捕获并:
+未捕获的异常会被中间件捕获并:
1. 记录完整异常和堆栈跟踪
2. 记录失败指标
@@ -163,20 +161,20 @@ def read_item(item_id: int):
4. 保留关联 ID
:::tip
-如果使用 `api-connection` 生成器,建议为 API 操作指定响应模型以获得更好的代码生成效果。详见此处。
+如果使用 `api-connection` 生成器,建议为 API 操作指定响应模型以获得更好的代码生成效果。详见此处。
:::
### 流式传输
-使用 FastAPI 时,您可以通过 [`StreamingResponse`](https://fastapi.tiangolo.com/reference/responses/?h=streaming#fastapi.responses.StreamingResponse) 响应类型向调用方流式传输响应。
+使用 FastAPI 时,您可以通过 [`StreamingResponse`](https://fastapi.tiangolo.com/reference/responses/?h=streaming#fastapi.responses.StreamingResponse) 响应类型向调用方流式传输响应。
#### 基础设施变更
-由于 AWS API Gateway 不支持流式响应,您需要将 FastAPI 部署到支持此功能的平台。最简单的选择是使用 AWS Lambda 函数 URL。
+由于 AWS API Gateway 不支持流式响应,您需要将 FastAPI 部署到支持此功能的平台。最简单的选择是使用 AWS Lambda 函数 URL。
-要实现此功能,可以替换生成的 `common/constructs/src/app/apis/-api.ts` 构造,改用支持流式传输的函数 URL。
+要实现此功能,可以替换生成的 `common/constructs/src/app/apis/-api.ts` 构造,改用支持流式传输的函数 URL。
流式传输 FunctionURL 构造示例
@@ -275,7 +273,7 @@ export class MyApi extends Construct {
-要在 Terraform 中实现此功能,可以替换生成的 API Gateway 基础设施为支持响应流式传输的 Lambda 函数 URL。
+要在 Terraform 中实现此功能,可以替换生成的 API Gateway 基础设施为支持响应流式传输的 Lambda 函数 URL。
流式传输 Lambda 函数 URL 配置示例
@@ -385,7 +383,7 @@ output "my_api_url" {
value = aws_lambda_function_url.my_api_url.function_url
}
-# 可选:为运行时配置创建 SSM 参数
+# 可选:为运行时配置创建 SSM 参数
resource "aws_ssm_parameter" "my_api_url" {
name = "/runtime-config/apis/MyApi"
type = "String"
@@ -419,7 +417,7 @@ resource "aws_iam_policy" "my_api_invoke_policy" {
})
}
-# 示例:将调用策略附加到角色(根据需要取消注释并修改)
+# 示例:将调用策略附加到角色(根据需要取消注释并修改)
# resource "aws_iam_role_policy_attachment" "my_api_invoke_access" {
# role = var.authenticated_role_name
# policy_arn = aws_iam_policy.my_api_invoke_policy.arn
@@ -433,13 +431,13 @@ resource "aws_iam_policy" "my_api_invoke_policy" {
#### 实现
-更新基础设施以支持流式传输后,您可以在 FastAPI 中实现流式 API。API 应:
+更新基础设施以支持流式传输后,您可以在 FastAPI 中实现流式 API。API 应:
- 返回 [`StreamingResponse`](https://fastapi.tiangolo.com/reference/responses/?h=streaming#fastapi.responses.StreamingResponse)
- 声明每个响应块的返回类型
-- 如果计划使用 API 连接,需添加 OpenAPI 供应商扩展 `x-streaming: true`
+- 如果计划使用 API 连接,需添加 OpenAPI 供应商扩展 `x-streaming: true`
-例如,如果要从 API 流式传输一系列 JSON 对象,可以按如下方式实现:
+例如,如果要从 API 流式传输一系列 JSON 对象,可以按如下方式实现:
```py /return (StreamingResponse)/ /openapi_extra[^)]*/ /-> (Chunk)/
from pydantic import BaseModel
@@ -460,7 +458,7 @@ def my_stream() -> Chunk:
#### 消费
-要消费流式响应,可以使用 API 连接生成器,该生成器将提供类型安全的方法来迭代流式数据块。
+要消费流式响应,可以使用 API 连接生成器,该生成器将提供类型安全的方法来迭代流式数据块。
## 部署 FastAPI
@@ -468,7 +466,7 @@ FastAPI 生成器根据您选择的 `iacProvider` 创建 CDK 或 Terraform 基
-CDK 构造位于 `common/constructs` 文件夹中,可用于 CDK 应用程序:
+CDK 构造位于 `common/constructs` 文件夹中,可用于 CDK 应用程序:
```ts {6-8}
import { MyApi } from ':my-scope/common-constructs';
@@ -483,7 +481,7 @@ export class ExampleStack extends Stack {
}
```
-此配置设置:
+此配置设置:
1. 为 FastAPI 应用中的每个操作创建 AWS Lambda 函数
2. 将 API Gateway HTTP/REST API 作为函数触发器
@@ -492,8 +490,10 @@ export class ExampleStack extends Stack {
5. X-Ray 追踪配置
6. CloudWatch 指标命名空间
+
+
:::note
-如果选择使用 `Cognito` 身份验证,需要向 API 构造提供 `identity` 属性:
+如果选择使用 `Cognito` 身份验证,需要向 API 构造提供 `identity` 属性:
```ts {9}
import { MyApi, UserIdentity } from ':my-scope/common-constructs';
@@ -514,7 +514,7 @@ export class ExampleStack extends Stack {
:::
-Terraform 模块位于 `common/terraform` 文件夹中,可用于 Terraform 配置:
+Terraform 模块位于 `common/terraform` 文件夹中,可用于 Terraform 配置:
```hcl {2}
module "my_api" {
@@ -526,7 +526,7 @@ module "my_api" {
LOG_LEVEL = "INFO"
}
- # 额外的 IAM 策略(如有需要)
+ # 额外的 IAM 策略(如有需要)
additional_iam_policy_statements = [
# 添加 API 需要的任何额外权限
]
@@ -535,7 +535,7 @@ module "my_api" {
}
```
-此配置设置:
+此配置设置:
1. 服务所有 FastAPI 路由的 AWS Lambda 函数
2. 将 API Gateway HTTP/REST API 作为函数触发器
@@ -544,8 +544,10 @@ module "my_api" {
5. X-Ray 追踪配置
6. CORS 配置
+
+
:::note
-如果选择使用 `Cognito` 身份验证,需要提供 Cognito 配置:
+如果选择使用 `Cognito` 身份验证,需要提供 Cognito 配置:
```hcl {4-5}
module "my_api" {
@@ -566,7 +568,7 @@ module "my_api" {
可以使用适当的 Terraform 资源或模块设置 Cognito 用户池和客户端。
:::
-Terraform 模块提供多个输出可供使用:
+Terraform 模块提供多个输出可供使用:
```hcl
# 访问 API 端点
@@ -585,7 +587,7 @@ output "lambda_execution_role_arn" {
}
```
-可以通过传递变量来自定义 CORS 设置:
+可以通过传递变量来自定义 CORS 设置:
```hcl
module "my_api" {
@@ -605,7 +607,7 @@ module "my_api" {
```
:::caution
-如果在运行生成器时选择 `None` 作为 `auth` 选项,可能会看到 Checkov 检查失败,例如:
+如果在运行生成器时选择 `None` 作为 `auth` 选项,可能会看到 Checkov 检查失败,例如:
@@ -622,7 +624,7 @@ Check: CKV_AWS_59: "Ensure there is no open access to back-end resources through
-如果确定需要 API 公开访问,可以[添加抑制注释](https://www.checkov.io/2.Basics/Suppressing%20and%20Skipping%20Policies.html)。
+如果确定需要 API 公开访问,可以[添加抑制注释](https://www.checkov.io/2.Basics/Suppressing%20and%20Skipping%20Policies.html)。
:::
@@ -635,18 +637,18 @@ Check: CKV_AWS_59: "Ensure there is no open access to back-end resources through
-由于 FastAPI 的操作在 Python 中定义而 CDK 基础设施在 TypeScript 中实现,我们通过代码生成工具向 CDK 构造提供元数据,以实现类型安全的集成接口。
+由于 FastAPI 的操作在 Python 中定义而 CDK 基础设施在 TypeScript 中实现,我们通过代码生成工具向 CDK 构造提供元数据,以实现类型安全的集成接口。
-在公共构造的 `project.json` 中添加了 `generate:-metadata` 目标以促进此代码生成,该目标会生成类似 `packages/common/constructs/src/generated/my-api/metadata.gen.ts` 的文件。由于这是在构建时生成的,因此版本控制中会忽略此文件。
+在公共构造的 `project.json` 中添加了 `generate:-metadata` 目标以促进此代码生成,该目标会生成类似 `packages/common/constructs/src/generated/my-api/metadata.gen.ts` 的文件。由于这是在构建时生成的,因此版本控制中会忽略此文件。
:::note
-每当更改 API 时都需要运行构建,以确保 CDK 构造使用的类型是最新的。
+每当更改 API 时都需要运行构建,以确保 CDK 构造使用的类型是最新的。
:::
:::tip
-如果同时进行 CDK 基础设施和 FastAPI 开发,可以使用 [`nx watch`](https://nx.dev/nx-api/nx/documents/watch) 在每次 API 更改时重新生成这些类型:
+如果同时进行 CDK 基础设施和 FastAPI 开发,可以使用 [`nx watch`](https://nx.dev/nx-api/nx/documents/watch) 在每次 API 更改时重新生成这些类型:
:::note
-如果选择 Terraform 作为 `iacProvider`,我们不支持类型安全集成,因此不会配置代码生成目标。
+如果选择 Terraform 作为 `iacProvider`,我们不支持类型安全集成,因此不会配置代码生成目标。
:::
-### 授予访问权限(仅限 IAM)
+### 授予访问权限(仅限 IAM)
-如果选择使用 `IAM` 身份验证,可以使用 `grantInvokeAccess` 方法授予 API 访问权限:
+如果选择使用 `IAM` 身份验证,可以使用 `grantInvokeAccess` 方法授予 API 访问权限:
@@ -692,7 +694,7 @@ resource "aws_iam_policy" "api_invoke_policy" {
})
}
-# 将策略附加到 IAM 角色(例如已验证用户角色)
+# 将策略附加到 IAM 角色(例如已验证用户角色)
resource "aws_iam_role_policy_attachment" "api_invoke_access" {
role = aws_iam_role.authenticated_user_role.name
policy_arn = aws_iam_policy.api_invoke_policy.arn
@@ -705,7 +707,7 @@ resource "aws_iam_role_policy_attachment" "api_invoke_access_existing" {
}
```
-API 模块的关键输出可用于 IAM 策略:
+API 模块的关键输出可用于 IAM 策略:
- `module.my_api.api_execution_arn` - 用于授予 execute-api:Invoke 权限
- `module.my_api.api_arn` - API Gateway ARN
@@ -715,11 +717,11 @@ API 模块的关键输出可用于 IAM 策略:
## 本地开发
-生成器配置了本地开发服务器,可通过以下命令运行:
+生成器配置了本地开发服务器,可通过以下命令运行:
-这将启动本地 FastAPI 开发服务器,包含:
+这将启动本地 FastAPI 开发服务器,包含:
- 代码更改时自动重载
- 在 `/docs` 或 `/redoc` 提供交互式 API 文档
@@ -727,4 +729,4 @@ API 模块的关键输出可用于 IAM 策略:
## 调用 FastAPI
-要从 React 网站调用 API,可以使用 `api-connection` 生成器。
\ No newline at end of file
+要从 React 网站调用 API,可以使用 `api-connection` 生成器。
\ No newline at end of file
diff --git a/docs/src/content/docs/zh/guides/trpc.mdx b/docs/src/content/docs/zh/guides/trpc.mdx
index 8d2dcf05..314ff3ed 100644
--- a/docs/src/content/docs/zh/guides/trpc.mdx
+++ b/docs/src/content/docs/zh/guides/trpc.mdx
@@ -3,8 +3,6 @@ title: "tRPC"
description: "tRPC 参考文档"
---
-
-
import { FileTree, Tabs, TabItem } from '@astrojs/starlight/components';
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
import Link from '@components/link.astro';
@@ -14,15 +12,15 @@ import NxCommands from '@components/nx-commands.astro';
import Infrastructure from '@components/infrastructure.astro';
import Snippet from '@components/snippet.astro';
-[tRPC](https://trpc.io/) 是一个用于在 TypeScript 中构建端到端类型安全 API 的框架。使用 tRPC 时,API 操作输入输出的更新会立即反映在客户端代码中,并可在 IDE 中直接查看,无需重新构建项目。
+[tRPC](https://trpc.io/) 是一个用于在 TypeScript 中构建端到端类型安全 API 的框架。使用 tRPC 时,API 操作输入输出的更新会立即反映在客户端代码中,并可在 IDE 中直接查看,无需重新构建项目。
-tRPC API 生成器会创建一个新的 tRPC API,并配置 AWS CDK 或 Terraform 基础设施。生成的后端使用 AWS Lambda 进行无服务器部署,通过 AWS API Gateway API 暴露,并包含使用 [Zod](https://zod.dev/) 的模式验证。它配置了 [AWS Lambda Powertools](https://docs.powertools.aws.dev/lambda/typescript/latest/) 用于可观测性,包括日志记录、AWS X-Ray 追踪和 Cloudwatch 指标。
+tRPC API 生成器会创建一个新的 tRPC API,并配置 AWS CDK 或 Terraform 基础设施。生成的后端使用 AWS Lambda 进行无服务器部署,通过 AWS API Gateway API 暴露,并包含使用 [Zod](https://zod.dev/) 的模式验证。它配置了 [AWS Lambda Powertools](https://docs.powertools.aws.dev/lambda/typescript/latest/) 用于可观测性,包括日志记录、AWS X-Ray 追踪和 Cloudwatch 指标。
## 用法
### 生成 tRPC API
-您可以通过两种方式生成新的 tRPC API:
+您可以通过两种方式生成新的 tRPC API:
@@ -34,7 +32,7 @@ tRPC API 生成器会创建一个新的 tRPC API,并配置 AWS CDK 或 Terrafo
## 生成器输出
-生成器将在 `/` 目录中创建以下项目结构:
+生成器将在 `/` 目录中创建以下项目结构:
- src
@@ -54,6 +52,7 @@ tRPC API 生成器会创建一个新的 tRPC API,并配置 AWS CDK 或 Terrafo
- index.ts 用于机器间 API 调用的类型安全客户端
- tsconfig.json TypeScript 配置
- project.json 项目配置和构建目标
+
### 基础设施
@@ -64,13 +63,13 @@ tRPC API 生成器会创建一个新的 tRPC API,并配置 AWS CDK 或 Terrafo
## 实现 tRPC API
-从高层次来看,tRPC API 由将请求委托给特定过程的路由器组成。每个过程都有使用 Zod 模式定义的输入和输出。
+从高层次来看,tRPC API 由将请求委托给特定过程的路由器组成。每个过程都有使用 Zod 模式定义的输入和输出。
### 模式
-`src/schema` 目录包含客户端和服务器代码共享的类型。在本包中,这些类型使用 [Zod](https://zod.dev/)(一个 TypeScript 优先的模式声明和验证库)定义。
+`src/schema` 目录包含客户端和服务器代码共享的类型。在本包中,这些类型使用 [Zod](https://zod.dev/)(一个 TypeScript 优先的模式声明和验证库)定义。
-示例模式可能如下所示:
+示例模式可能如下所示:
```ts
import { z } from 'zod';
@@ -86,7 +85,7 @@ export const UserSchema = z.object({
export type User = z.TypeOf;
```
-根据上述模式,`User` 类型等效于以下 TypeScript:
+根据上述模式,`User` 类型等效于以下 TypeScript:
```ts
interface User {
@@ -96,17 +95,17 @@ interface User {
}
```
-模式在服务器和客户端代码之间共享,当需要修改 API 使用的结构时,只需在此处更新即可。
+模式在服务器和客户端代码之间共享,当需要修改 API 使用的结构时,只需在此处更新即可。
-tRPC API 在运行时自动验证模式,无需在后端手工编写验证逻辑。
+tRPC API 在运行时自动验证模式,无需在后端手工编写验证逻辑。
-Zod 提供了强大的工具来组合或派生模式,如 `.merge`、`.pick`、`.omit` 等。更多信息请参阅 [Zod 文档网站](https://zod.dev/?id=basic-usage)。
+Zod 提供了强大的工具来组合或派生模式,如 `.merge`、`.pick`、`.omit` 等。更多信息请参阅 [Zod 文档网站](https://zod.dev/?id=basic-usage)。
### 路由与过程
-您可以在 `src/router.ts` 中找到 API 的入口点。该文件包含 Lambda 处理程序,根据调用的操作将请求路由到"过程"。每个过程定义预期的输入、输出和实现。
+您可以在 `src/router.ts` 中找到 API 的入口点。该文件包含 Lambda 处理程序,根据调用的操作将请求路由到"过程"。每个过程定义预期的输入、输出和实现。
-生成的示例路由器有一个名为 `echo` 的单一操作:
+生成的示例路由器有一个名为 `echo` 的单一操作:
```ts
import { echo } from './procedures/echo.js';
@@ -116,7 +115,7 @@ export const appRouter = router({
});
```
-示例 `echo` 过程在 `src/procedures/echo.ts` 中生成:
+示例 `echo` 过程在 `src/procedures/echo.ts` 中生成:
```ts
export const echo = publicProcedure
@@ -125,22 +124,22 @@ export const echo = publicProcedure
.query((opts) => ({ result: opts.input.message }));
```
-分解上述代码:
+分解上述代码:
-- `publicProcedure` 定义 API 的公共方法,包含在 `src/middleware` 中设置的中间件。该中间件包括用于日志记录、追踪和指标的 AWS Lambda Powertools 集成
+- `publicProcedure` 定义 API 的公共方法,包含在 `src/middleware` 中设置的中间件。该中间件包括用于日志记录、追踪和指标的 AWS Lambda Powertools 集成
- `input` 接受定义操作预期输入的 Zod 模式。发送到此操作的请求会自动根据此模式验证
-- `output` 接受定义操作预期输出的 Zod 模式。如果返回不符合模式的输出,实现中会出现类型错误
-- `query` 接受定义 API 实现的函数。该实现接收包含操作输入的 `opts`,以及中间件设置的上下文(通过 `opts.ctx` 访问)。传递给 `query` 的函数必须返回符合 `output` 模式的输出
+- `output` 接受定义操作预期输出的 Zod 模式。如果返回不符合模式的输出,实现中会出现类型错误
+- `query` 接受定义 API 实现的函数。该实现接收包含操作输入的 `opts`,以及中间件设置的上下文(通过 `opts.ctx` 访问)。传递给 `query` 的函数必须返回符合 `output` 模式的输出
-使用 `query` 定义实现表示该操作是非变更性的。使用此方法来定义数据检索方法。要实现变更性操作,请改用 `mutation` 方法。
+使用 `query` 定义实现表示该操作是非变更性的。使用此方法来定义数据检索方法。要实现变更性操作,请改用 `mutation` 方法。
-如果添加新过程,请确保在 `src/router.ts` 的路由器中注册它。
+如果添加新过程,请确保在 `src/router.ts` 的路由器中注册它。
## 自定义 tRPC API
### 错误处理
-在实现中,您可以通过抛出 `TRPCError` 向客户端返回错误响应。这些错误接受表示错误类型的 `code`,例如:
+在实现中,您可以通过抛出 `TRPCError` 向客户端返回错误响应。这些错误接受表示错误类型的 `code`,例如:
```ts
throw new TRPCError({
@@ -151,9 +150,9 @@ throw new TRPCError({
### 组织操作
-随着 API 的增长,您可能希望将相关操作分组。
+随着 API 的增长,您可能希望将相关操作分组。
-您可以使用嵌套路由器对操作进行分组,例如:
+您可以使用嵌套路由器对操作进行分组,例如:
```ts
import { getUser } from './procedures/users/get.js';
@@ -168,7 +167,7 @@ const appRouter = router({
})
```
-客户端将接收此操作分组,例如在此情况下调用 `listUsers` 操作可能如下所示:
+客户端将接收此操作分组,例如在此情况下调用 `listUsers` 操作可能如下所示:
```ts
client.users.list.query();
@@ -176,7 +175,7 @@ client.users.list.query();
### 日志记录
-AWS Lambda Powertools 日志记录器在 `src/middleware/logger.ts` 中配置,可通过 `opts.ctx.logger` 在 API 实现中访问。您可以使用此记录器向 CloudWatch Logs 记录日志,并/或控制每个结构化日志消息中包含的额外值。例如:
+AWS Lambda Powertools 日志记录器在 `src/middleware/logger.ts` 中配置,可通过 `opts.ctx.logger` 在 API 实现中访问。您可以使用此记录器向 CloudWatch Logs 记录日志,并/或控制每个结构化日志消息中包含的额外值。例如:
```ts {5}
export const echo = publicProcedure
@@ -189,11 +188,11 @@ export const echo = publicProcedure
});
```
-有关日志记录器的更多信息,请参阅 [AWS Lambda Powertools 日志记录器文档](https://docs.powertools.aws.dev/lambda/typescript/latest/core/logger/)。
+有关日志记录器的更多信息,请参阅 [AWS Lambda Powertools 日志记录器文档](https://docs.powertools.aws.dev/lambda/typescript/latest/core/logger/)。
### 记录指标
-AWS Lambda Powertools 指标在 `src/middleware/metrics.ts` 中配置,可通过 `opts.ctx.metrics` 在 API 实现中访问。您可以使用此功能在 CloudWatch 中记录指标,而无需导入和使用 AWS SDK,例如:
+AWS Lambda Powertools 指标在 `src/middleware/metrics.ts` 中配置,可通过 `opts.ctx.metrics` 在 API 实现中访问。您可以使用此功能在 CloudWatch 中记录指标,而无需导入和使用 AWS SDK,例如:
```ts {5}
export const echo = publicProcedure
@@ -210,7 +209,7 @@ export const echo = publicProcedure
### 微调 X-Ray 追踪
-AWS Lambda Powertools 追踪器在 `src/middleware/tracer.ts` 中配置,可通过 `opts.ctx.tracer` 在 API 实现中访问。您可以使用此功能添加 AWS X-Ray 追踪,以提供 API 请求性能和流程的详细洞察。例如:
+AWS Lambda Powertools 追踪器在 `src/middleware/tracer.ts` 中配置,可通过 `opts.ctx.tracer` 在 API 实现中访问。您可以使用此功能添加 AWS X-Ray 追踪,以提供 API 请求性能和流程的详细洞察。例如:
```ts {5-7}
export const echo = publicProcedure
@@ -231,13 +230,13 @@ export const echo = publicProcedure
您可以通过实现中间件向过程提供的上下文中添加额外值。
-例如,让我们在 `src/middleware/identity.ts` 中实现一些中间件来从 API 中提取调用用户的详细信息。
+例如,让我们在 `src/middleware/identity.ts` 中实现一些中间件来从 API 中提取调用用户的详细信息。
:::warning
-此示例假设 `auth` 设置为 `IAM`。对于 Cognito 身份验证,身份中间件更简单,直接从 `event` 中提取相关声明。
+此示例假设 `auth` 设置为 `IAM`。对于 Cognito 身份验证,身份中间件更简单,直接从 `event` 中提取相关声明。
:::
-首先,我们定义要添加到上下文中的内容:
+首先,我们定义要添加到上下文中的内容:
```ts
export interface IIdentityContext {
@@ -248,9 +247,9 @@ export interface IIdentityContext {
}
```
-注意,我们向上下文定义了一个额外的 _可选_ 属性。tRPC 会管理确保在正确配置此中间件的过程中有此定义。
+注意,我们向上下文定义了一个额外的 _可选_ 属性。tRPC 会管理确保在正确配置此中间件的过程中有此定义。
-接下来,我们将实现中间件本身。其结构如下:
+接下来,我们将实现中间件本身。其结构如下:
```ts
export const createIdentityPlugin = () => {
@@ -267,7 +266,7 @@ export const createIdentityPlugin = () => {
};
```
-在我们的案例中,我们希望提取调用 Cognito 用户的详细信息。我们将通过从 API Gateway 事件中提取用户的主题 ID(或 "sub"),并从 Cognito 检索用户详细信息来实现。具体实现根据事件是由 REST API 还是 HTTP API 提供给我们的函数而略有不同:
+在我们的案例中,我们希望提取调用 Cognito 用户的详细信息。我们将通过从 API Gateway 事件中提取用户的主题 ID(或 "sub"),并从 Cognito 检索用户详细信息来实现。具体实现根据事件是由 REST API 还是 HTTP API 提供给我们的函数而略有不同:
@@ -410,7 +409,7 @@ tRPC API 生成器根据您选择的 `iacProvider` 创建 CDK 或 Terraform 基
-`common/constructs` 文件夹中包含用于部署 API 的 CDK 构造。您可以在 CDK 应用程序中使用此构造,例如:
+`common/constructs` 文件夹中包含用于部署 API 的 CDK 构造。您可以在 CDK 应用程序中使用此构造,例如:
```ts {6-8}
import { MyApi } from ':my-scope/common-constructs`;
@@ -425,10 +424,12 @@ export class ExampleStack extends Stack {
}
```
-这将设置您的 API 基础设施,包括 AWS API Gateway REST 或 HTTP API、用于业务逻辑的 AWS Lambda 函数,以及根据您选择的 `auth` 方法配置的身份验证。
+这将设置您的 API 基础设施,包括 AWS API Gateway REST 或 HTTP API、用于业务逻辑的 AWS Lambda 函数,以及根据您选择的 `auth` 方法配置的身份验证。
+
+
:::note
-如果选择使用 `Cognito` 身份验证,您需要向 API 构造提供 `identity` 属性:
+如果选择使用 `Cognito` 身份验证,您需要向 API 构造提供 `identity` 属性:
```ts {9}
import { MyApi, UserIdentity } from ':my-scope/common-constructs';
@@ -449,7 +450,7 @@ export class ExampleStack extends Stack {
:::
-`common/terraform` 文件夹中包含用于部署 API 的 Terraform 模块。您可以在 Terraform 配置中使用此模块:
+`common/terraform` 文件夹中包含用于部署 API 的 Terraform 模块。您可以在 Terraform 配置中使用此模块:
```hcl {6-8}
module "my_api" {
@@ -470,7 +471,7 @@ module "my_api" {
}
```
-这将设置:
+这将设置:
1. 服务所有 tRPC 过程的 AWS Lambda 函数
2. 作为函数触发器的 API Gateway HTTP/REST API
@@ -479,8 +480,10 @@ module "my_api" {
5. X-Ray 追踪配置
6. CORS 配置
+
+
:::note
-如果选择使用 `Cognito` 身份验证,您需要提供 Cognito 配置:
+如果选择使用 `Cognito` 身份验证,您需要提供 Cognito 配置:
```hcl {4-5}
module "my_api" {
@@ -501,7 +504,7 @@ module "my_api" {
您可以使用适当的 Terraform 资源或模块设置 Cognito 用户池和客户端。
:::
-Terraform 模块提供多个输出供您使用:
+Terraform 模块提供多个输出供您使用:
```hcl
# 访问 API 端点
@@ -520,7 +523,7 @@ output "lambda_execution_role_arn" {
}
```
-您可以通过传递变量自定义 CORS 设置:
+您可以通过传递变量自定义 CORS 设置:
```hcl
module "my_api" {
@@ -540,7 +543,7 @@ module "my_api" {
```
:::caution
-如果在运行生成器时为 `auth` 选择 `None`,可能会看到 Checkov 检查失败,例如:
+如果在运行生成器时为 `auth` 选择 `None`,可能会看到 Checkov 检查失败,例如:
@@ -557,7 +560,7 @@ Check: CKV_AWS_59: "Ensure there is no open access to back-end resources through
-如果确定需要 API 公开访问,可以[添加抑制注释](https://www.checkov.io/2.Basics/Suppressing%20and%20Skipping%20Policies.html)。
+如果确定需要 API 公开访问,可以[添加抑制注释](https://www.checkov.io/2.Basics/Suppressing%20and%20Skipping%20Policies.html)。
:::
@@ -567,12 +570,12 @@ Check: CKV_AWS_59: "Ensure there is no open access to back-end resources through
:::tip
-如果为 `iacProvider` 选择 CDK,当在 tRPC API 中添加或删除过程时,这些更改将立即反映在 CDK 构造中,无需重新构建。
+如果为 `iacProvider` 选择 CDK,当在 tRPC API 中添加或删除过程时,这些更改将立即反映在 CDK 构造中,无需重新构建。
:::
### 授予访问权限(仅限 IAM)
-如果选择使用 `IAM` 身份验证,可以授予 API 访问权限:
+如果选择使用 `IAM` 身份验证,可以授予 API 访问权限:
@@ -612,7 +615,7 @@ resource "aws_iam_role_policy_attachment" "api_invoke_access_existing" {
}
```
-API 模块的关键输出可用于 IAM 策略:
+API 模块的关键输出可用于 IAM 策略:
- `module.my_api.api_execution_arn` - 用于授予 execute-api:Invoke 权限
- `module.my_api.api_arn` - API Gateway ARN
@@ -626,17 +629,17 @@ API 模块的关键输出可用于 IAM 策略:
## 本地 tRPC 服务器
-您可以使用 `serve` 目标运行 API 的本地服务器,例如:
+您可以使用 `serve` 目标运行 API 的本地服务器,例如:
本地服务器的入口点是 `src/local-server.ts`。
-当对 API 进行更改时,此服务器会自动重新加载。
+当对 API 进行更改时,此服务器会自动重新加载。
## 调用 tRPC API
-您可以创建 tRPC 客户端以类型安全的方式调用 API。如果从其他后端调用 tRPC API,可以使用 `src/client/index.ts` 中的客户端,例如:
+您可以创建 tRPC 客户端以类型安全的方式调用 API。如果从其他后端调用 tRPC API,可以使用 `src/client/index.ts` 中的客户端,例如:
```ts
import { createMyApiClient } from ':my-scope/my-api';
@@ -646,8 +649,8 @@ const client = createMyApiClient({ url: 'https://my-api-url.example.com/' });
await client.echo.query({ message: 'Hello world!' });
```
-如果从 React 网站调用 API,请考虑使用 API 连接 生成器来配置客户端。
+如果从 React 网站调用 API,请考虑使用 API 连接 生成器来配置客户端。
## 更多信息
-有关 tRPC 的更多信息,请参阅 [tRPC 文档](https://trpc.io/docs)。
\ No newline at end of file
+有关 tRPC 的更多信息,请参阅 [tRPC 文档](https://trpc.io/docs)。
\ No newline at end of file
diff --git a/docs/src/content/docs/zh/guides/ts-smithy-api.mdx b/docs/src/content/docs/zh/guides/ts-smithy-api.mdx
index eff316da..76fb3357 100644
--- a/docs/src/content/docs/zh/guides/ts-smithy-api.mdx
+++ b/docs/src/content/docs/zh/guides/ts-smithy-api.mdx
@@ -3,8 +3,6 @@ title: "Smithy TypeScript API 参考文档"
description: "Smithy TypeScript API 参考文档"
---
-
-
import { FileTree, AnchorHeading, Tabs, TabItem } from '@astrojs/starlight/components';
import Link from '@components/link.astro';
import RunGenerator from '@components/run-generator.astro';
@@ -407,6 +405,8 @@ export class ExampleStack extends Stack {
4. CloudWatch 日志组
5. X-Ray 追踪配置
+
+
:::note
如果选择 `Cognito` 认证,需向 API 构造提供 `identity` 属性:
@@ -459,6 +459,8 @@ module "my_api" {
5. X-Ray 追踪配置
6. CORS 配置
+
+
:::note
如果选择 `Cognito` 认证,需提供 Cognito 配置:
diff --git a/docs/src/content/docs/zh/snippets/api/cors-configuration-cdk-note.mdx b/docs/src/content/docs/zh/snippets/api/cors-configuration-cdk-note.mdx
new file mode 100644
index 00000000..0076caa0
--- /dev/null
+++ b/docs/src/content/docs/zh/snippets/api/cors-configuration-cdk-note.mdx
@@ -0,0 +1,26 @@
+---
+title: "CORS 配置 CDK"
+---
+
+import Link from '@components/link.astro';
+
+:::note
+如果您的解决方案包含网站,您可以将其 CloudFront 分发配置为 API 网关 / API AWS Lambda 集成中 HTTP / REST API 唯一允许的 CORS 源。请注意,此限制不适用于 REST API 的预检 OPTIONS 请求 - 请为 [this GitHub issue](https://github.com/awslabs/nx-plugin-for-aws/issues/377) 点赞以帮助优先解决此问题。
+您需要先创建 API,然后使用创建的网站调用 API 的 `restrictCorsTo` 方法。
+
+```ts
+import { MyApi, MyWebsite } from ':my-scope/common-constructs';
+
+export class ExampleStack extends Stack {
+ constructor(scope: Construct, id: string) {
+ const api = new MyApi(this, 'MyApi', {
+ integrations: MyApi.defaultIntegrations(this).build(),
+ });
+ const website = new MyWebsite(this, 'MyWebsite');
+ api.restrictCorsTo(website);
+ }
+}
+```
+
+`MyWebsite` 构造可以使用 `ts#react-website` generator 生成
+:::
\ No newline at end of file
diff --git a/docs/src/content/docs/zh/snippets/api/cors-configuration-terraform-note.mdx b/docs/src/content/docs/zh/snippets/api/cors-configuration-terraform-note.mdx
new file mode 100644
index 00000000..6a50a115
--- /dev/null
+++ b/docs/src/content/docs/zh/snippets/api/cors-configuration-terraform-note.mdx
@@ -0,0 +1,27 @@
+---
+title: "CORS 配置 Terraform"
+---
+
+import Link from '@components/link.astro';
+
+:::note
+如果您的解决方案包含 Terraform 网站模块,那么您可以使用其 CloudFront 域名来限制 CORS。
+给定一个 CloudFront 域名 ``,在用于部署 API 的 Terraform 模块中添加
+- 对于 HTTP API,添加一个 `cors_allow_origins` 属性,设置为 `["http://localhost:4200", "http://localhost:4300", "https://"]`。这会将 API 网关 CORS 限制为此分发和本地主机。
+- 对于 REST API,添加一个 `ALLOWED_ORIGINS` 环境变量,设置为 `"https://"`。这会将 CloudFront 分发设置为 AWS Lambda 集成中唯一允许的 CORS 源(除本地主机外)。请注意,此限制不适用于预检 OPTIONS 请求 - 请为 [this GitHub issue](https://github.com/awslabs/nx-plugin-for-aws/issues/377) 点赞以帮助优先解决此问题。
+
+```hcl {4,7}
+module "my_api" {
+ source = "../../common/terraform/src/app/apis/my-api"
+
+ cors_allow_origins = ["http://localhost:4200", "http://localhost:4300", "https://"] // Only required for HTTP API
+
+ env = {
+ ALLOWED_ORIGINS = "https://" // Only required for REST API
+ ENVIRONMENT = var.environment
+ LOG_LEVEL = "INFO"
+ }
+}
+```
+`MyWebsite` 构造可以使用 `ts#react-website` 生成器生成
+:::
\ No newline at end of file
diff --git a/packages/nx-plugin/src/py/fast-api/__snapshots__/generator.spec.ts.snap b/packages/nx-plugin/src/py/fast-api/__snapshots__/generator.spec.ts.snap
index d0b60fa9..cc8eb900 100644
--- a/packages/nx-plugin/src/py/fast-api/__snapshots__/generator.spec.ts.snap
+++ b/packages/nx-plugin/src/py/fast-api/__snapshots__/generator.spec.ts.snap
@@ -7,11 +7,11 @@ exports[`fastapi project generator > should match snapshot > main-snapshot 1`] =
"apps/test_api/proj_test_api/init.py": "import os
import uuid
from collections.abc import Callable
+from urllib.parse import urlparse
from aws_lambda_powertools import Logger, Metrics, Tracer
from aws_lambda_powertools.metrics import MetricUnit
from fastapi import FastAPI, Request, Response
-from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.utils import get_openapi
from fastapi.responses import JSONResponse
from fastapi.routing import APIRoute
@@ -46,10 +46,25 @@ lambda_handler = logger.inject_lambda_context(lambda_handler, clear_state=True)
lambda_handler = metrics.log_metrics(lambda_handler, capture_cold_start_metric=True)
# Add cors middleware
-app.add_middleware(CORSMiddleware,
- allow_origins=['*'],
- allow_methods=['*'],
- allow_headers=['*'])
+@app.middleware("http")
+async def cors_middleware(request: Request, call_next):
+ response = await call_next(request)
+
+ origin = request.headers.get("origin")
+ allowed_origins = os.environ.get('ALLOWED_ORIGINS', '').split(',') if os.environ.get('ALLOWED_ORIGINS') else []
+
+ is_localhost = origin and urlparse(origin).hostname in ['localhost', '127.0.0.1']
+ is_allowed_origin = origin and origin in allowed_origins
+
+ cors_origin = '*'
+ if allowed_origins and not is_localhost:
+ cors_origin = origin if is_allowed_origin else allowed_origins[0]
+
+ response.headers["Access-Control-Allow-Origin"] = cors_origin
+ response.headers["Access-Control-Allow-Methods"] = "*"
+ response.headers["Access-Control-Allow-Headers"] = "*"
+
+ return response
# Add exception middleware(s)
app.add_middleware(ExceptionMiddleware, handlers=app.exception_handlers)
@@ -311,6 +326,7 @@ export class HttpApi<
exports[`fastapi project generator > should set up shared constructs for http > test-api.ts 1`] = `
"import { Construct } from 'constructs';
import * as url from 'url';
+import { Distribution } from 'aws-cdk-lib/aws-cloudfront';
import {
Code,
Runtime,
@@ -319,7 +335,7 @@ import {
Tracing,
} from 'aws-cdk-lib/aws-lambda';
import { Duration } from 'aws-cdk-lib';
-import { CorsHttpMethod } from 'aws-cdk-lib/aws-apigatewayv2';
+import { CorsHttpMethod, CfnApi } from 'aws-cdk-lib/aws-apigatewayv2';
import { HttpIamAuthorizer } from 'aws-cdk-lib/aws-apigatewayv2-authorizers';
import { HttpLambdaIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';
import { Grant, IGrantable } from 'aws-cdk-lib/aws-iam';
@@ -419,6 +435,48 @@ export class TestApi<
});
}
+ /**
+ * Restricts CORS to the website CloudFront distribution domains
+ *
+ * Configures the CloudFront distribution domains as the only permitted CORS origins
+ * (other than local host with default ports) in the API gateway
+ * The CORS origins are not configured within the AWS Lambda integrations since
+ * the associated header is controlled by API Gateway v2
+ *
+ * @param cloudFrontDistribution - The CloudFront distribution to grant CORS from
+ */
+ public restrictCorsTo(
+ ...websites: { cloudFrontDistribution: Distribution }[]
+ ) {
+ const allowedOrigins = websites.map(
+ ({ cloudFrontDistribution }) =>
+ \`https://\${cloudFrontDistribution.distributionDomainName}\`,
+ );
+
+ const cfnApi = this.api.node.defaultChild;
+ if (!(cfnApi instanceof CfnApi)) {
+ throw new Error(
+ 'Unable to configure CORS: API default child is not a CfnApi instance',
+ );
+ }
+
+ cfnApi.corsConfiguration = {
+ allowOrigins: [
+ 'http://localhost:4200',
+ 'http://localhost:4300',
+ ...allowedOrigins,
+ ],
+ allowMethods: [CorsHttpMethod.ANY],
+ allowHeaders: [
+ 'authorization',
+ 'content-type',
+ 'x-amz-content-sha256',
+ 'x-amz-date',
+ 'x-amz-security-token',
+ ],
+ };
+ }
+
/**
* Grants IAM permissions to invoke any method on this API.
*
@@ -801,6 +859,7 @@ export class RestApi<
exports[`fastapi project generator > should set up shared constructs for rest > test-api.ts 1`] = `
"import { Construct } from 'constructs';
import * as url from 'url';
+import { Distribution } from 'aws-cdk-lib/aws-cloudfront';
import {
Code,
Runtime,
@@ -921,6 +980,34 @@ export class TestApi<
});
}
+ /**
+ * Restricts CORS to the website CloudFront distribution domains
+ *
+ * Configures the CloudFront distribution domains as the only permitted CORS origins
+ * (other than local host) in the AWS Lambda integrations
+ *
+ * Note that this restriction is not applied to preflight OPTIONS
+ *
+ * @param websites - The CloudFront distribution to grant CORS from
+ */
+ public restrictCorsTo(
+ ...websites: { cloudFrontDistribution: Distribution }[]
+ ) {
+ const allowedOrigins = websites
+ .map(
+ ({ cloudFrontDistribution }) =>
+ \`https://\${cloudFrontDistribution.distributionDomainName}\`,
+ )
+ .join(',');
+
+ // Set ALLOWED_ORIGINS environment variable for all Lambda integrations
+ Object.values(this.integrations).forEach((integration) => {
+ if ('handler' in integration && integration.handler instanceof Function) {
+ integration.handler.addEnvironment('ALLOWED_ORIGINS', allowedOrigins);
+ }
+ });
+ }
+
/**
* Grants IAM permissions to invoke any method on this API.
*
diff --git a/packages/nx-plugin/src/py/fast-api/files/app/__name__/init.py.template b/packages/nx-plugin/src/py/fast-api/files/app/__name__/init.py.template
index 58165b5b..019b98b0 100644
--- a/packages/nx-plugin/src/py/fast-api/files/app/__name__/init.py.template
+++ b/packages/nx-plugin/src/py/fast-api/files/app/__name__/init.py.template
@@ -1,11 +1,11 @@
import os
import uuid
from collections.abc import Callable
+from urllib.parse import urlparse
from aws_lambda_powertools import Logger, Metrics, Tracer
from aws_lambda_powertools.metrics import MetricUnit
from fastapi import FastAPI, Request, Response
-from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.utils import get_openapi
from fastapi.responses import JSONResponse
from fastapi.routing import APIRoute
@@ -40,10 +40,25 @@ lambda_handler = logger.inject_lambda_context(lambda_handler, clear_state=True)
lambda_handler = metrics.log_metrics(lambda_handler, capture_cold_start_metric=True)
# Add cors middleware
-app.add_middleware(CORSMiddleware,
- allow_origins=['*'],
- allow_methods=['*'],
- allow_headers=['*'])
+@app.middleware("http")
+async def cors_middleware(request: Request, call_next):
+ response = await call_next(request)
+
+ origin = request.headers.get("origin")
+ allowed_origins = os.environ.get('ALLOWED_ORIGINS', '').split(',') if os.environ.get('ALLOWED_ORIGINS') else []
+
+ is_localhost = origin and urlparse(origin).hostname in ['localhost', '127.0.0.1']
+ is_allowed_origin = origin and origin in allowed_origins
+
+ cors_origin = '*'
+ if allowed_origins and not is_localhost:
+ cors_origin = origin if is_allowed_origin else allowed_origins[0]
+
+ response.headers["Access-Control-Allow-Origin"] = cors_origin
+ response.headers["Access-Control-Allow-Methods"] = "*"
+ response.headers["Access-Control-Allow-Headers"] = "*"
+
+ return response
# Add exception middleware(s)
app.add_middleware(ExceptionMiddleware, handlers=app.exception_handlers)
diff --git a/packages/nx-plugin/src/py/fast-api/generator.spec.ts b/packages/nx-plugin/src/py/fast-api/generator.spec.ts
index 43fdae1b..53600f7e 100644
--- a/packages/nx-plugin/src/py/fast-api/generator.spec.ts
+++ b/packages/nx-plugin/src/py/fast-api/generator.spec.ts
@@ -342,13 +342,10 @@ describe('fastapi project generator', () => {
'utf-8',
);
- // Verify CORS middleware import is included
+ // Verify CORS origin is configured
expect(initPyContent).toContain(
- 'from fastapi.middleware.cors import CORSMiddleware',
+ 'response.headers["Access-Control-Allow-Origin"] = cors_origin',
);
-
- // Verify CORS middleware is added with correct configuration
- expect(initPyContent).toContain('app.add_middleware(CORSMiddleware,');
},
);
diff --git a/packages/nx-plugin/src/smithy/ts/api/__snapshots__/generator.spec.ts.snap b/packages/nx-plugin/src/smithy/ts/api/__snapshots__/generator.spec.ts.snap
index 3ce7765d..be64a494 100644
--- a/packages/nx-plugin/src/smithy/ts/api/__snapshots__/generator.spec.ts.snap
+++ b/packages/nx-plugin/src/smithy/ts/api/__snapshots__/generator.spec.ts.snap
@@ -34,6 +34,7 @@ exports[`tsSmithyApiGenerator > should configure git and eslint ignores for gene
exports[`tsSmithyApiGenerator > should generate smithy ts api with Cognito auth > cognito-auth-infra.ts 1`] = `
"import { Construct } from 'constructs';
import * as url from 'url';
+import { Distribution } from 'aws-cdk-lib/aws-cloudfront';
import {
Code,
Runtime,
@@ -162,6 +163,34 @@ export class TestApi<
...props,
});
}
+
+ /**
+ * Restricts CORS to the website CloudFront distribution domains
+ *
+ * Configures the CloudFront distribution domains as the only permitted CORS origins
+ * (other than local host) in the AWS Lambda integrations
+ *
+ * Note that this restriction is not applied to preflight OPTIONS
+ *
+ * @param websites - The CloudFront distribution to grant CORS from
+ */
+ public restrictCorsTo(
+ ...websites: { cloudFrontDistribution: Distribution }[]
+ ) {
+ const allowedOrigins = websites
+ .map(
+ ({ cloudFrontDistribution }) =>
+ \`https://\${cloudFrontDistribution.distributionDomainName}\`,
+ )
+ .join(',');
+
+ // Set ALLOWED_ORIGINS environment variable for all Lambda integrations
+ Object.values(this.integrations).forEach((integration) => {
+ if ('handler' in integration && integration.handler instanceof Function) {
+ integration.handler.addEnvironment('ALLOWED_ORIGINS', allowedOrigins);
+ }
+ });
+ }
}
"
`;
@@ -169,6 +198,7 @@ export class TestApi<
exports[`tsSmithyApiGenerator > should generate smithy ts api with IAM auth > iam-auth-infra.ts 1`] = `
"import { Construct } from 'constructs';
import * as url from 'url';
+import { Distribution } from 'aws-cdk-lib/aws-cloudfront';
import {
Code,
Runtime,
@@ -289,6 +319,34 @@ export class TestApi<
});
}
+ /**
+ * Restricts CORS to the website CloudFront distribution domains
+ *
+ * Configures the CloudFront distribution domains as the only permitted CORS origins
+ * (other than local host) in the AWS Lambda integrations
+ *
+ * Note that this restriction is not applied to preflight OPTIONS
+ *
+ * @param websites - The CloudFront distribution to grant CORS from
+ */
+ public restrictCorsTo(
+ ...websites: { cloudFrontDistribution: Distribution }[]
+ ) {
+ const allowedOrigins = websites
+ .map(
+ ({ cloudFrontDistribution }) =>
+ \`https://\${cloudFrontDistribution.distributionDomainName}\`,
+ )
+ .join(',');
+
+ // Set ALLOWED_ORIGINS environment variable for all Lambda integrations
+ Object.values(this.integrations).forEach((integration) => {
+ if ('handler' in integration && integration.handler instanceof Function) {
+ integration.handler.addEnvironment('ALLOWED_ORIGINS', allowedOrigins);
+ }
+ });
+ }
+
/**
* Grants IAM permissions to invoke any method on this API.
*
@@ -1110,13 +1168,26 @@ export const lambdaHandler = async (
return {
...apiGatewayResponse,
headers: {
- 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Origin': getAllowedOrigin(event),
'Access-Control-Allow-Methods': '*',
...apiGatewayResponse.headers,
},
};
};
+const getAllowedOrigin = (event: APIGatewayProxyEvent) => {
+ const origin = event.headers?.origin ?? event.headers?.Origin;
+ const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(',') ?? [];
+ const isLocalHost =
+ origin && new Set(['localhost', '127.0.0.1']).has(new URL(origin).hostname);
+ const isAllowedOrigin = origin && allowedOrigins.includes(origin);
+ let corsOrigin = '*';
+ if (allowedOrigins.length > 0 && !isLocalHost) {
+ corsOrigin = isAllowedOrigin ? origin : allowedOrigins[0];
+ }
+ return corsOrigin;
+};
+
export const handler = middy()
.use(captureLambdaHandler(tracer))
.use(injectLambdaContext(logger))
@@ -1255,13 +1326,26 @@ export const lambdaHandler = async (
return {
...apiGatewayResponse,
headers: {
- 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Origin': getAllowedOrigin(event),
'Access-Control-Allow-Methods': '*',
...apiGatewayResponse.headers,
},
};
};
+const getAllowedOrigin = (event: APIGatewayProxyEvent) => {
+ const origin = event.headers?.origin ?? event.headers?.Origin;
+ const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(',') ?? [];
+ const isLocalHost =
+ origin && new Set(['localhost', '127.0.0.1']).has(new URL(origin).hostname);
+ const isAllowedOrigin = origin && allowedOrigins.includes(origin);
+ let corsOrigin = '*';
+ if (allowedOrigins.length > 0 && !isLocalHost) {
+ corsOrigin = isAllowedOrigin ? origin : allowedOrigins[0];
+ }
+ return corsOrigin;
+};
+
export const handler = middy()
.use(captureLambdaHandler(tracer))
.use(injectLambdaContext(logger))
diff --git a/packages/nx-plugin/src/smithy/ts/api/files/handler.ts.template b/packages/nx-plugin/src/smithy/ts/api/files/handler.ts.template
index ca98d9ab..89a0215c 100644
--- a/packages/nx-plugin/src/smithy/ts/api/files/handler.ts.template
+++ b/packages/nx-plugin/src/smithy/ts/api/files/handler.ts.template
@@ -36,13 +36,26 @@ export const lambdaHandler = async (
return {
...apiGatewayResponse,
headers: {
- 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Origin': getAllowedOrigin(event),
'Access-Control-Allow-Methods': '*',
...apiGatewayResponse.headers,
},
};
};
+const getAllowedOrigin = (event: APIGatewayProxyEvent) => {
+ const origin = event.headers?.origin ?? event.headers?.Origin;
+ const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(',') ?? [];
+ const isLocalHost =
+ origin && new Set(['localhost', '127.0.0.1']).has(new URL(origin).hostname);
+ const isAllowedOrigin = origin && allowedOrigins.includes(origin);
+ let corsOrigin = '*';
+ if (allowedOrigins.length > 0 && !isLocalHost) {
+ corsOrigin = isAllowedOrigin ? origin : allowedOrigins[0];
+ }
+ return corsOrigin;
+};
+
export const handler = middy()
.use(captureLambdaHandler(tracer))
.use(injectLambdaContext(logger))
diff --git a/packages/nx-plugin/src/trpc/backend/__snapshots__/generator.spec.ts.snap b/packages/nx-plugin/src/trpc/backend/__snapshots__/generator.spec.ts.snap
index d79e3a48..b49b404e 100644
--- a/packages/nx-plugin/src/trpc/backend/__snapshots__/generator.spec.ts.snap
+++ b/packages/nx-plugin/src/trpc/backend/__snapshots__/generator.spec.ts.snap
@@ -347,6 +347,7 @@ exports[`trpc backend generator > should generate with cognito auth for a REST A
exports[`trpc backend generator > should generate with cognito auth for a REST API > packages/common/constructs/src/app/apis/test-api.ts 1`] = `
"import { Construct } from 'constructs';
import * as url from 'url';
+import { Distribution } from 'aws-cdk-lib/aws-cloudfront';
import {
Code,
Runtime,
@@ -476,6 +477,34 @@ export class TestApi<
...props,
});
}
+
+ /**
+ * Restricts CORS to the website CloudFront distribution domains
+ *
+ * Configures the CloudFront distribution domains as the only permitted CORS origins
+ * (other than local host) in the AWS Lambda integrations
+ *
+ * Note that this restriction is not applied to preflight OPTIONS
+ *
+ * @param websites - The CloudFront distribution to grant CORS from
+ */
+ public restrictCorsTo(
+ ...websites: { cloudFrontDistribution: Distribution }[]
+ ) {
+ const allowedOrigins = websites
+ .map(
+ ({ cloudFrontDistribution }) =>
+ \`https://\${cloudFrontDistribution.distributionDomainName}\`,
+ )
+ .join(',');
+
+ // Set ALLOWED_ORIGINS environment variable for all Lambda integrations
+ Object.values(this.integrations).forEach((integration) => {
+ if ('handler' in integration && integration.handler instanceof Function) {
+ integration.handler.addEnvironment('ALLOWED_ORIGINS', allowedOrigins);
+ }
+ });
+ }
}
"
`;
@@ -511,6 +540,7 @@ exports[`trpc backend generator > should generate with cognito auth for an HTTP
exports[`trpc backend generator > should generate with cognito auth for an HTTP API > packages/common/constructs/src/app/apis/test-api.ts 1`] = `
"import { Construct } from 'constructs';
import * as url from 'url';
+import { Distribution } from 'aws-cdk-lib/aws-cloudfront';
import {
Code,
Runtime,
@@ -519,7 +549,7 @@ import {
Tracing,
} from 'aws-cdk-lib/aws-lambda';
import { Duration } from 'aws-cdk-lib';
-import { CorsHttpMethod } from 'aws-cdk-lib/aws-apigatewayv2';
+import { CorsHttpMethod, CfnApi } from 'aws-cdk-lib/aws-apigatewayv2';
import { HttpUserPoolAuthorizer } from 'aws-cdk-lib/aws-apigatewayv2-authorizers';
import { HttpLambdaIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';
import { IUserPool, IUserPoolClient } from 'aws-cdk-lib/aws-cognito';
@@ -632,6 +662,48 @@ export class TestApi<
...props,
});
}
+
+ /**
+ * Restricts CORS to the website CloudFront distribution domains
+ *
+ * Configures the CloudFront distribution domains as the only permitted CORS origins
+ * (other than local host with default ports) in the API gateway
+ * The CORS origins are not configured within the AWS Lambda integrations since
+ * the associated header is controlled by API Gateway v2
+ *
+ * @param cloudFrontDistribution - The CloudFront distribution to grant CORS from
+ */
+ public restrictCorsTo(
+ ...websites: { cloudFrontDistribution: Distribution }[]
+ ) {
+ const allowedOrigins = websites.map(
+ ({ cloudFrontDistribution }) =>
+ \`https://\${cloudFrontDistribution.distributionDomainName}\`,
+ );
+
+ const cfnApi = this.api.node.defaultChild;
+ if (!(cfnApi instanceof CfnApi)) {
+ throw new Error(
+ 'Unable to configure CORS: API default child is not a CfnApi instance',
+ );
+ }
+
+ cfnApi.corsConfiguration = {
+ allowOrigins: [
+ 'http://localhost:4200',
+ 'http://localhost:4300',
+ ...allowedOrigins,
+ ],
+ allowMethods: [CorsHttpMethod.ANY],
+ allowHeaders: [
+ 'authorization',
+ 'content-type',
+ 'x-amz-content-sha256',
+ 'x-amz-date',
+ 'x-amz-security-token',
+ ],
+ };
+ }
}
"
`;
@@ -663,6 +735,7 @@ exports[`trpc backend generator > should generate with no auth for a REST API >
exports[`trpc backend generator > should generate with no auth for a REST API > packages/common/constructs/src/app/apis/test-api.ts 1`] = `
"import { Construct } from 'constructs';
import * as url from 'url';
+import { Distribution } from 'aws-cdk-lib/aws-cloudfront';
import {
Code,
Runtime,
@@ -781,6 +854,34 @@ export class TestApi<
...props,
});
}
+
+ /**
+ * Restricts CORS to the website CloudFront distribution domains
+ *
+ * Configures the CloudFront distribution domains as the only permitted CORS origins
+ * (other than local host) in the AWS Lambda integrations
+ *
+ * Note that this restriction is not applied to preflight OPTIONS
+ *
+ * @param websites - The CloudFront distribution to grant CORS from
+ */
+ public restrictCorsTo(
+ ...websites: { cloudFrontDistribution: Distribution }[]
+ ) {
+ const allowedOrigins = websites
+ .map(
+ ({ cloudFrontDistribution }) =>
+ \`https://\${cloudFrontDistribution.distributionDomainName}\`,
+ )
+ .join(',');
+
+ // Set ALLOWED_ORIGINS environment variable for all Lambda integrations
+ Object.values(this.integrations).forEach((integration) => {
+ if ('handler' in integration && integration.handler instanceof Function) {
+ integration.handler.addEnvironment('ALLOWED_ORIGINS', allowedOrigins);
+ }
+ });
+ }
}
"
`;
@@ -812,6 +913,7 @@ exports[`trpc backend generator > should generate with no auth for an HTTP API >
exports[`trpc backend generator > should generate with no auth for an HTTP API > packages/common/constructs/src/app/apis/test-api.ts 1`] = `
"import { Construct } from 'constructs';
import * as url from 'url';
+import { Distribution } from 'aws-cdk-lib/aws-cloudfront';
import {
Code,
Runtime,
@@ -822,6 +924,7 @@ import {
import { Duration } from 'aws-cdk-lib';
import {
CorsHttpMethod,
+ CfnApi,
HttpNoneAuthorizer,
} from 'aws-cdk-lib/aws-apigatewayv2';
import { HttpLambdaIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';
@@ -921,6 +1024,48 @@ export class TestApi<
...props,
});
}
+
+ /**
+ * Restricts CORS to the website CloudFront distribution domains
+ *
+ * Configures the CloudFront distribution domains as the only permitted CORS origins
+ * (other than local host with default ports) in the API gateway
+ * The CORS origins are not configured within the AWS Lambda integrations since
+ * the associated header is controlled by API Gateway v2
+ *
+ * @param cloudFrontDistribution - The CloudFront distribution to grant CORS from
+ */
+ public restrictCorsTo(
+ ...websites: { cloudFrontDistribution: Distribution }[]
+ ) {
+ const allowedOrigins = websites.map(
+ ({ cloudFrontDistribution }) =>
+ \`https://\${cloudFrontDistribution.distributionDomainName}\`,
+ );
+
+ const cfnApi = this.api.node.defaultChild;
+ if (!(cfnApi instanceof CfnApi)) {
+ throw new Error(
+ 'Unable to configure CORS: API default child is not a CfnApi instance',
+ );
+ }
+
+ cfnApi.corsConfiguration = {
+ allowOrigins: [
+ 'http://localhost:4200',
+ 'http://localhost:4300',
+ ...allowedOrigins,
+ ],
+ allowMethods: [CorsHttpMethod.ANY],
+ allowHeaders: [
+ 'authorization',
+ 'content-type',
+ 'x-amz-content-sha256',
+ 'x-amz-date',
+ 'x-amz-security-token',
+ ],
+ };
+ }
}
"
`;
@@ -1065,6 +1210,7 @@ export class HttpApi<
exports[`trpc backend generator > should set up shared constructs for http > test-api.ts 1`] = `
"import { Construct } from 'constructs';
import * as url from 'url';
+import { Distribution } from 'aws-cdk-lib/aws-cloudfront';
import {
Code,
Runtime,
@@ -1073,7 +1219,7 @@ import {
Tracing,
} from 'aws-cdk-lib/aws-lambda';
import { Duration } from 'aws-cdk-lib';
-import { CorsHttpMethod } from 'aws-cdk-lib/aws-apigatewayv2';
+import { CorsHttpMethod, CfnApi } from 'aws-cdk-lib/aws-apigatewayv2';
import { HttpIamAuthorizer } from 'aws-cdk-lib/aws-apigatewayv2-authorizers';
import { HttpLambdaIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';
import { Grant, IGrantable } from 'aws-cdk-lib/aws-iam';
@@ -1174,6 +1320,48 @@ export class TestApi<
});
}
+ /**
+ * Restricts CORS to the website CloudFront distribution domains
+ *
+ * Configures the CloudFront distribution domains as the only permitted CORS origins
+ * (other than local host with default ports) in the API gateway
+ * The CORS origins are not configured within the AWS Lambda integrations since
+ * the associated header is controlled by API Gateway v2
+ *
+ * @param cloudFrontDistribution - The CloudFront distribution to grant CORS from
+ */
+ public restrictCorsTo(
+ ...websites: { cloudFrontDistribution: Distribution }[]
+ ) {
+ const allowedOrigins = websites.map(
+ ({ cloudFrontDistribution }) =>
+ \`https://\${cloudFrontDistribution.distributionDomainName}\`,
+ );
+
+ const cfnApi = this.api.node.defaultChild;
+ if (!(cfnApi instanceof CfnApi)) {
+ throw new Error(
+ 'Unable to configure CORS: API default child is not a CfnApi instance',
+ );
+ }
+
+ cfnApi.corsConfiguration = {
+ allowOrigins: [
+ 'http://localhost:4200',
+ 'http://localhost:4300',
+ ...allowedOrigins,
+ ],
+ allowMethods: [CorsHttpMethod.ANY],
+ allowHeaders: [
+ 'authorization',
+ 'content-type',
+ 'x-amz-content-sha256',
+ 'x-amz-date',
+ 'x-amz-security-token',
+ ],
+ };
+ }
+
/**
* Grants IAM permissions to invoke any method on this API.
*
@@ -1627,6 +1815,7 @@ export class RestApi<
exports[`trpc backend generator > should set up shared constructs for rest > test-api.ts 1`] = `
"import { Construct } from 'constructs';
import * as url from 'url';
+import { Distribution } from 'aws-cdk-lib/aws-cloudfront';
import {
Code,
Runtime,
@@ -1748,6 +1937,34 @@ export class TestApi<
});
}
+ /**
+ * Restricts CORS to the website CloudFront distribution domains
+ *
+ * Configures the CloudFront distribution domains as the only permitted CORS origins
+ * (other than local host) in the AWS Lambda integrations
+ *
+ * Note that this restriction is not applied to preflight OPTIONS
+ *
+ * @param websites - The CloudFront distribution to grant CORS from
+ */
+ public restrictCorsTo(
+ ...websites: { cloudFrontDistribution: Distribution }[]
+ ) {
+ const allowedOrigins = websites
+ .map(
+ ({ cloudFrontDistribution }) =>
+ \`https://\${cloudFrontDistribution.distributionDomainName}\`,
+ )
+ .join(',');
+
+ // Set ALLOWED_ORIGINS environment variable for all Lambda integrations
+ Object.values(this.integrations).forEach((integration) => {
+ if ('handler' in integration && integration.handler instanceof Function) {
+ integration.handler.addEnvironment('ALLOWED_ORIGINS', allowedOrigins);
+ }
+ });
+ }
+
/**
* Grants IAM permissions to invoke any method on this API.
*
diff --git a/packages/nx-plugin/src/trpc/backend/files/src/router.ts.template b/packages/nx-plugin/src/trpc/backend/files/src/router.ts.template
index 149a2a97..0f7ca543 100644
--- a/packages/nx-plugin/src/trpc/backend/files/src/router.ts.template
+++ b/packages/nx-plugin/src/trpc/backend/files/src/router.ts.template
@@ -16,13 +16,30 @@ export const handler = awsLambdaRequestHandler({
router: appRouter,
createContext: (ctx: CreateAWSLambdaContextOptions<<%- apiGatewayEventType %>>) => ctx,
<%_ if (computeType === 'ServerlessApiGatewayRestApi') { _%>
- responseMeta: () => ({
- headers: {
- 'Access-Control-Allow-Origin': '*',
- 'Access-Control-Allow-Methods': '*',
- },
- }),
+ responseMeta: ({ ctx }) => {
+ return {
+ headers: {
+ 'Access-Control-Allow-Origin': getAllowedOrigin(ctx?.event),
+ 'Access-Control-Allow-Methods': '*',
+ },
+ };
+ },
<%_ } _%>
});
+<%_ if (computeType === 'ServerlessApiGatewayRestApi') { _%>
+const getAllowedOrigin = (event: <%- apiGatewayEventType %> | undefined) => {
+ const origin = event?.headers?.origin ?? event?.headers?.Origin;
+ const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(',') ?? [];
+ const isLocalHost =
+ origin && new Set(['localhost', '127.0.0.1']).has(new URL(origin).hostname);
+ const isAllowedOrigin = origin && allowedOrigins.includes(origin);
+ let corsOrigin = '*';
+ if (allowedOrigins.length > 0 && !isLocalHost) {
+ corsOrigin = isAllowedOrigin ? origin : allowedOrigins[0];
+ }
+ return corsOrigin;
+};
+<%_ } _%>
+
export type AppRouter = typeof appRouter;
diff --git a/packages/nx-plugin/src/trpc/backend/generator.spec.ts b/packages/nx-plugin/src/trpc/backend/generator.spec.ts
index f50e8115..ee14ca56 100644
--- a/packages/nx-plugin/src/trpc/backend/generator.spec.ts
+++ b/packages/nx-plugin/src/trpc/backend/generator.spec.ts
@@ -325,8 +325,8 @@ describe('trpc backend generator', () => {
const routerTsContent = tree.read('apps/test-api/src/router.ts', 'utf-8');
// Verify CORS headers are included in responseMeta
- expect(routerTsContent).toContain('responseMeta: () => ({');
- expect(routerTsContent).toContain("'Access-Control-Allow-Origin': '*'");
+ expect(routerTsContent).toContain('responseMeta: ({ ctx }) => {');
+ expect(routerTsContent).toContain("'Access-Control-Allow-Origin':");
expect(routerTsContent).toContain("'Access-Control-Allow-Methods': '*'");
});
diff --git a/packages/nx-plugin/src/utils/api-constructs/files/cdk/app/apis/http/__apiNameKebabCase__.ts.template b/packages/nx-plugin/src/utils/api-constructs/files/cdk/app/apis/http/__apiNameKebabCase__.ts.template
index 84f0fefa..71055366 100644
--- a/packages/nx-plugin/src/utils/api-constructs/files/cdk/app/apis/http/__apiNameKebabCase__.ts.template
+++ b/packages/nx-plugin/src/utils/api-constructs/files/cdk/app/apis/http/__apiNameKebabCase__.ts.template
@@ -1,5 +1,6 @@
import { Construct } from 'constructs';
import * as url from 'url';
+import { Distribution } from 'aws-cdk-lib/aws-cloudfront';
import {
Code,
Runtime,
@@ -10,6 +11,7 @@ import {
import { Duration } from 'aws-cdk-lib';
import {
CorsHttpMethod,
+ CfnApi,
<%_ if (auth === 'None') { _%>
HttpNoneAuthorizer,
<%_ } _%>
@@ -168,6 +170,49 @@ export class <%= apiNameClassName %><
...props,
});
}
+
+ /**
+ * Restricts CORS to the website CloudFront distribution domains
+ *
+ * Configures the CloudFront distribution domains as the only permitted CORS origins
+ * (other than local host with default ports) in the API gateway
+ * The CORS origins are not configured within the AWS Lambda integrations since
+ * the associated header is controlled by API Gateway v2
+ *
+ * @param cloudFrontDistribution - The CloudFront distribution to grant CORS from
+ */
+ public restrictCorsTo(
+ ...websites: { cloudFrontDistribution: Distribution }[]
+ ) {
+ const allowedOrigins = websites
+ .map(
+ ({ cloudFrontDistribution }) =>
+ `https://${cloudFrontDistribution.distributionDomainName}`,
+ );
+
+ const cfnApi = this.api.node.defaultChild;
+ if (!(cfnApi instanceof CfnApi)) {
+ throw new Error(
+ 'Unable to configure CORS: API default child is not a CfnApi instance',
+ );
+ }
+
+ cfnApi.corsConfiguration = {
+ allowOrigins: [
+ 'http://localhost:4200',
+ 'http://localhost:4300',
+ ...allowedOrigins,
+ ],
+ allowMethods: [CorsHttpMethod.ANY],
+ allowHeaders: [
+ 'authorization',
+ 'content-type',
+ 'x-amz-content-sha256',
+ 'x-amz-date',
+ 'x-amz-security-token',
+ ],
+ };
+ }
<%_ if (auth === 'IAM') { _%>
/**
diff --git a/packages/nx-plugin/src/utils/api-constructs/files/cdk/app/apis/rest/__apiNameKebabCase__.ts.template b/packages/nx-plugin/src/utils/api-constructs/files/cdk/app/apis/rest/__apiNameKebabCase__.ts.template
index 61f19a7d..564c167b 100644
--- a/packages/nx-plugin/src/utils/api-constructs/files/cdk/app/apis/rest/__apiNameKebabCase__.ts.template
+++ b/packages/nx-plugin/src/utils/api-constructs/files/cdk/app/apis/rest/__apiNameKebabCase__.ts.template
@@ -1,5 +1,6 @@
import { Construct } from 'constructs';
import * as url from 'url';
+import { Distribution } from 'aws-cdk-lib/aws-cloudfront';
import {
Code,
Runtime,
@@ -183,6 +184,34 @@ export class <%= apiNameClassName %><
...props,
});
}
+
+ /**
+ * Restricts CORS to the website CloudFront distribution domains
+ *
+ * Configures the CloudFront distribution domains as the only permitted CORS origins
+ * (other than local host) in the AWS Lambda integrations
+ *
+ * Note that this restriction is not applied to preflight OPTIONS
+ *
+ * @param websites - The CloudFront distribution to grant CORS from
+ */
+ public restrictCorsTo(
+ ...websites: { cloudFrontDistribution: Distribution }[]
+ ) {
+ const allowedOrigins = websites
+ .map(
+ ({ cloudFrontDistribution }) =>
+ `https://${cloudFrontDistribution.distributionDomainName}`,
+ )
+ .join(',');
+
+ // Set ALLOWED_ORIGINS environment variable for all Lambda integrations
+ Object.values(this.integrations).forEach((integration) => {
+ if ('handler' in integration && integration.handler instanceof Function) {
+ integration.handler.addEnvironment('ALLOWED_ORIGINS', allowedOrigins);
+ }
+ });
+ }
<%_ if (auth === 'IAM') { _%>
/**