feat(api): add HTTP and WebSocket APIs (API Gateway v2) to the API Gateway page
CI / checks (pull_request) Successful in 26m49s

API Gateway v2 is a separate AWS API from REST APIs, so HTTP and WebSocket APIs
made with the SDK, SAM, CDK or Terraform never showed up. The API Gateway page
now lists all three kinds with a Type column, creates each from the same form,
and opens HTTP and WebSocket APIs in their own panel:

- Quick create: an HTTP API with a Lambda gets a catch-all route on an
  auto-deployed $default stage, plus the Lambda permission.
- Routes to Lambda (payload 2.0) or HTTP backends; deleting a route removes
  the integration and Lambda permission only it used.
- Stages with or without automatic deployment, and deploy on demand.
- JWT authorizers filled in from a Cognito pool's OpenID Connect discovery
  document and an app client, or from any issuer; protect routes with them.
- CORS configuration.
- A tester that sends a real request to a stage, and for WebSocket APIs one
  that connects, sends a message and collects the replies.

Capabilities are advertised under a new httpApiActions group, covered by the
cloudProxy guard test. Verified end to end against TheCloud's runtime.
This commit is contained in:
Zakaria
2026-10-25 09:18:50 -04:00
parent 6acd3656a1
commit bb5ca85a88
22 changed files with 2410 additions and 68 deletions
+24
View File
@@ -130,6 +130,19 @@ export const apiEndpointKeys = {
messages: {send: "clouds.services.messaging.messages.send", receive: "clouds.services.messaging.messages.receive", delete: "clouds.services.messaging.messages.delete", purge: "clouds.services.messaging.messages.purge"},
moveTasks: "clouds.services.messaging.move-tasks",
},
httpApi: {
describe: "clouds.services.apigateway.http-api.describe",
createRoute: "clouds.services.apigateway.http-api.routes.create",
deleteRoute: "clouds.services.apigateway.http-api.routes.delete",
setRouteAuthorizer: "clouds.services.apigateway.http-api.routes.authorizer",
createStage: "clouds.services.apigateway.http-api.stages.create",
deleteStage: "clouds.services.apigateway.http-api.stages.delete",
deploy: "clouds.services.apigateway.http-api.stages.deploy",
createAuthorizer: "clouds.services.apigateway.http-api.authorizers.create",
deleteAuthorizer: "clouds.services.apigateway.http-api.authorizers.delete",
cors: "clouds.services.apigateway.http-api.cors",
webSocketTest: "clouds.services.apigateway.http-api.websocket-test",
},
monitoring: {
metrics: "clouds.services.monitoring.metrics",
metricData: "clouds.services.monitoring.metric-data",
@@ -897,6 +910,17 @@ export const endpointRegistry: EndpointRegistry = new Map([
method: "POST",
},
],
[apiEndpointKeys.clouds.httpApi.describe, {path: "/clouds/:cloud/services/apigateway/resources/:id/http-api", method: "GET"}],
[apiEndpointKeys.clouds.httpApi.createRoute, {path: "/clouds/:cloud/services/apigateway/resources/:id/http-api/routes", method: "POST"}],
[apiEndpointKeys.clouds.httpApi.deleteRoute, {path: "/clouds/:cloud/services/apigateway/resources/:id/http-api/routes/:routeId", method: "DELETE"}],
[apiEndpointKeys.clouds.httpApi.setRouteAuthorizer, {path: "/clouds/:cloud/services/apigateway/resources/:id/http-api/routes/:routeId/authorizer", method: "PUT"}],
[apiEndpointKeys.clouds.httpApi.createStage, {path: "/clouds/:cloud/services/apigateway/resources/:id/http-api/stages", method: "POST"}],
[apiEndpointKeys.clouds.httpApi.deleteStage, {path: "/clouds/:cloud/services/apigateway/resources/:id/http-api/stages/:stageName", method: "DELETE"}],
[apiEndpointKeys.clouds.httpApi.deploy, {path: "/clouds/:cloud/services/apigateway/resources/:id/http-api/stages/:stageName/deployments", method: "POST"}],
[apiEndpointKeys.clouds.httpApi.createAuthorizer, {path: "/clouds/:cloud/services/apigateway/resources/:id/http-api/authorizers", method: "POST"}],
[apiEndpointKeys.clouds.httpApi.deleteAuthorizer, {path: "/clouds/:cloud/services/apigateway/resources/:id/http-api/authorizers/:authorizerId", method: "DELETE"}],
[apiEndpointKeys.clouds.httpApi.cors, {path: "/clouds/:cloud/services/apigateway/resources/:id/http-api/cors", method: "PUT"}],
[apiEndpointKeys.clouds.httpApi.webSocketTest, {path: "/clouds/:cloud/services/apigateway/resources/:id/http-api/websocket-test", method: "POST"}],
[apiEndpointKeys.clouds.monitoring.metrics, {path: "/clouds/:cloud/services/monitoring/metrics", method: "GET"}],
[apiEndpointKeys.clouds.monitoring.metricData, {path: "/clouds/:cloud/services/monitoring/metric-data", method: "POST"}],
[apiEndpointKeys.clouds.monitoring.history, {path: "/clouds/:cloud/services/monitoring/resources/:id/history", method: "GET"}],
@@ -1546,6 +1546,139 @@ export async function setAlarmActionsEnabled(
);
}
export type HttpApiProtocol = "HTTP" | "WEBSOCKET";
export interface HttpApiIntegrationOverview {
integrationId: string;
type: string;
uri: string | null;
functionName: string | null;
payloadFormatVersion: string | null;
}
export interface HttpApiRouteOverview {
routeId: string;
routeKey: string;
integration: HttpApiIntegrationOverview | null;
authorizationType: string;
authorizerId: string | null;
authorizationScopes: string[];
returnsResponse: boolean;
}
export interface HttpApiStageOverview {
stageName: string;
autoDeploy: boolean;
deploymentId: string | null;
lastUpdatedAt: string | null;
invokePath: string;
}
export interface HttpApiAuthorizerOverview {
authorizerId: string;
name: string;
type: string;
identitySource: string[];
issuer: string | null;
audience: string[];
}
export interface HttpApiCors {
allowOrigins: string[];
allowMethods: string[];
allowHeaders: string[];
exposeHeaders: string[];
maxAgeSeconds: number | null;
allowCredentials: boolean;
}
export interface HttpApiOverview {
apiId: string;
protocol: HttpApiProtocol;
apiEndpoint: string | null;
routeSelectionExpression: string | null;
routes: HttpApiRouteOverview[];
stages: HttpApiStageOverview[];
authorizers: HttpApiAuthorizerOverview[];
cors: HttpApiCors | null;
}
export interface HttpApiRouteInput {
routeKey: string;
functionName?: string;
httpUrl?: string;
authorizerId?: string;
returnsResponse?: boolean;
}
export interface HttpApiAuthorizerInput {
name: string;
userPoolId?: string;
userPoolClientId?: string;
issuer?: string;
audience?: string[];
}
export interface HttpApiWebSocketTestResult {
connected: boolean;
messages: string[];
closeCode: number | null;
error: string | null;
durationMs: number;
}
export async function describeHttpApi(cloud: CloudProvider, apiId: string, signal?: AbortSignal): Promise<HttpApiOverview> {
const res = await apiClient.call<HttpApiOverview>(apiEndpointKeys.clouds.httpApi.describe, requestOptions(cloud, "apigateway", { signal }), { cloud, id: apiId });
return res.data;
}
export async function createHttpApiRoute(cloud: CloudProvider, apiId: string, input: HttpApiRouteInput): Promise<HttpApiRouteOverview> {
const res = await apiClient.call<HttpApiRouteOverview, HttpApiRouteInput>(apiEndpointKeys.clouds.httpApi.createRoute, requestOptions(cloud, "apigateway", { body: input }), { cloud, id: apiId });
return res.data;
}
export async function deleteHttpApiRoute(cloud: CloudProvider, apiId: string, routeId: string): Promise<void> {
await apiClient.call<void>(apiEndpointKeys.clouds.httpApi.deleteRoute, requestOptions(cloud, "apigateway"), { cloud, id: apiId, routeId });
}
export async function setHttpApiRouteAuthorizer(cloud: CloudProvider, apiId: string, routeId: string, authorizerId: string | null): Promise<HttpApiRouteOverview> {
const res = await apiClient.call<HttpApiRouteOverview, { authorizerId: string | null }>(apiEndpointKeys.clouds.httpApi.setRouteAuthorizer, requestOptions(cloud, "apigateway", { body: { authorizerId } }), { cloud, id: apiId, routeId });
return res.data;
}
export async function createHttpApiStage(cloud: CloudProvider, apiId: string, input: { stageName: string; autoDeploy: boolean }): Promise<HttpApiStageOverview> {
const res = await apiClient.call<HttpApiStageOverview, typeof input>(apiEndpointKeys.clouds.httpApi.createStage, requestOptions(cloud, "apigateway", { body: input }), { cloud, id: apiId });
return res.data;
}
export async function deleteHttpApiStage(cloud: CloudProvider, apiId: string, stageName: string): Promise<void> {
await apiClient.call<void>(apiEndpointKeys.clouds.httpApi.deleteStage, requestOptions(cloud, "apigateway"), { cloud, id: apiId, stageName });
}
export async function deployHttpApi(cloud: CloudProvider, apiId: string, stageName: string): Promise<HttpApiStageOverview> {
const res = await apiClient.call<HttpApiStageOverview>(apiEndpointKeys.clouds.httpApi.deploy, requestOptions(cloud, "apigateway"), { cloud, id: apiId, stageName });
return res.data;
}
export async function createHttpApiAuthorizer(cloud: CloudProvider, apiId: string, input: HttpApiAuthorizerInput): Promise<HttpApiAuthorizerOverview> {
const res = await apiClient.call<HttpApiAuthorizerOverview, HttpApiAuthorizerInput>(apiEndpointKeys.clouds.httpApi.createAuthorizer, requestOptions(cloud, "apigateway", { body: input }), { cloud, id: apiId });
return res.data;
}
export async function deleteHttpApiAuthorizer(cloud: CloudProvider, apiId: string, authorizerId: string): Promise<void> {
await apiClient.call<void>(apiEndpointKeys.clouds.httpApi.deleteAuthorizer, requestOptions(cloud, "apigateway"), { cloud, id: apiId, authorizerId });
}
export async function updateHttpApiCors(cloud: CloudProvider, apiId: string, cors: HttpApiCors | null): Promise<HttpApiCors | null> {
const res = await apiClient.call<{ cors: HttpApiCors | null }, { cors: HttpApiCors | null }>(apiEndpointKeys.clouds.httpApi.cors, requestOptions(cloud, "apigateway", { body: { cors } }), { cloud, id: apiId });
return res.data.cors;
}
export async function testWebSocketApi(cloud: CloudProvider, apiId: string, input: { stage: string; message: string; query?: string }): Promise<HttpApiWebSocketTestResult> {
const res = await apiClient.call<HttpApiWebSocketTestResult, typeof input>(apiEndpointKeys.clouds.httpApi.webSocketTest, requestOptions(cloud, "apigateway", { body: input }), { cloud, id: apiId });
return res.data;
}
export async function setDistributionEnabled(
cloud: CloudProvider,
distributionId: string,
@@ -8,6 +8,7 @@ import type {CloudResource} from '@/types/resource'
import {CopyValueButton} from './CopyValueButton'
import {LogsQueryPanel} from './LogsQueryPanel'
import {ServiceIcon} from '@/components/serviceIcons'
import {formatResponseBody, invokeEndpoint, parseHeaders} from '@/lib/apiGateway'
interface ApiGatewayRoutePanelProps {
cloud: CloudProvider
@@ -138,8 +139,8 @@ export function ApiGatewayRoutePanel({cloud, resource, runtimeReachable, runtime
return (
<section className="table-panel">
<div className="empty compact">
<h3>Select a REST API</h3>
<p>Select an API Gateway REST API to connect a route to a Lambda function.</p>
<h3>Select an API</h3>
<p>Select an API to see its routes, or create one.</p>
</div>
</section>
)
@@ -513,49 +514,6 @@ function MethodTestResponse({result, dismiss}: {result?: ApiGatewayMethodTestRes
</div>
}
function invokeEndpoint(runtimeEndpoint?: string): string | null {
if (!runtimeEndpoint) return null
try {
const endpoint = new URL(runtimeEndpoint)
if (isDockerBridgeAddress(endpoint.hostname) && typeof window !== 'undefined') {
endpoint.hostname = window.location.hostname
}
return endpoint.toString().replace(/\/$/, '')
} catch {
return runtimeEndpoint.replace(/\/$/, '')
}
}
function isDockerBridgeAddress(hostname: string): boolean {
const octets = hostname.split('.').map(Number)
return octets.length === 4
&& octets.every((octet) => Number.isInteger(octet) && octet >= 0 && octet <= 255)
&& octets[0] === 172
&& octets[1] >= 16
&& octets[1] <= 31
}
function parseHeaders(value: string): Record<string, string> {
let parsed: unknown
try {
parsed = JSON.parse(value || '{}')
} catch {
throw new Error('Request headers must be valid JSON.')
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || Object.values(parsed).some((header) => typeof header !== 'string')) {
throw new Error('Request headers must be a JSON object with string values.')
}
return parsed as Record<string, string>
}
function formatResponseBody(body: string): string {
try {
return JSON.stringify(JSON.parse(body), null, 2)
} catch {
return body || '(empty response body)'
}
}
function buildCurlCommand(apiId: string, stage: string, path: string, method: string, headersText: string, query: string, body: string): string {
let headers: Record<string, string> = {}
try {
@@ -48,6 +48,7 @@ import { DatabaseLaunchProgress } from "@/components/DatabaseLaunchProgress";
import { AppConfigPanel } from "@/components/AppConfigPanel";
import { KmsCryptoPanel } from "@/components/KmsCryptoPanel";
import { ApiGatewayRoutePanel } from "@/components/ApiGatewayRoutePanel";
import { HttpApiPanel } from "@/components/HttpApiPanel";
import { S3LambdaTriggerPanel } from "@/components/S3LambdaTriggerPanel";
import { ScheduledLambdaTriggerPanel } from "@/components/ScheduledLambdaTriggerPanel";
import { SqsLambdaTriggerPanel } from "@/components/SqsLambdaTriggerPanel";
@@ -1037,14 +1038,21 @@ export function DynamicResourceView({
)}
</>
)}
{service === "apigateway" && (
{service === "apigateway" && (activeSelected && ["http", "websocket"].includes(String(activeSelected.metadata.apigatewayService)) ? (
<HttpApiPanel
cloud={cloud}
resource={activeSelected}
runtimeReachable={canUseRuntime}
runtimeEndpoint={cloudStatus?.endpoint ?? undefined}
/>
) : (
<ApiGatewayRoutePanel
cloud={cloud}
resource={activeSelected}
runtimeReachable={canUseRuntime}
runtimeEndpoint={cloudStatus?.endpoint ?? undefined}
/>
)}
))}
{service === "events" && (
<EventBridgeRulePanel
cloud={cloud}
@@ -0,0 +1,126 @@
import {QueryClient, QueryClientProvider} from '@tanstack/react-query'
import {render, screen, within} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import {beforeEach, expect, test, vi} from 'vitest'
import {HttpApiPanel} from './HttpApiPanel'
import type {HttpApiOverview} from '@/api/cloudProxyClient'
import type {CloudResource} from '@/types/resource'
const api = vi.hoisted(() => ({
describeHttpApi: vi.fn(),
listCloudResources: vi.fn(),
createHttpApiRoute: vi.fn(),
deleteHttpApiRoute: vi.fn(),
setHttpApiRouteAuthorizer: vi.fn(),
createHttpApiStage: vi.fn(),
deleteHttpApiStage: vi.fn(),
deployHttpApi: vi.fn(),
createHttpApiAuthorizer: vi.fn(),
deleteHttpApiAuthorizer: vi.fn(),
updateHttpApiCors: vi.fn(),
testApiGatewayRoute: vi.fn(),
testWebSocketApi: vi.fn(),
}))
vi.mock('@/api/cloudProxyClient', () => api)
const httpResource: CloudResource = {
id: 'h1', name: 'notes-api', cloud: 'aws', service: 'apigateway', type: 'http-api', region: null, createdAt: null,
metadata: {apigatewayService: 'http', protocol: 'HTTP'},
}
const httpOverview: HttpApiOverview = {
apiId: 'h1', protocol: 'HTTP', apiEndpoint: null, routeSelectionExpression: null,
routes: [
{routeId: 'r1', routeKey: 'GET /notes/{id}', integration: {integrationId: 'i1', type: 'AWS_PROXY', uri: 'arn', functionName: 'notes', payloadFormatVersion: '2.0'}, authorizationType: 'NONE', authorizerId: null, authorizationScopes: [], returnsResponse: false},
{routeId: 'r2', routeKey: 'GET /me', integration: {integrationId: 'i1', type: 'AWS_PROXY', uri: 'arn', functionName: 'notes', payloadFormatVersion: '2.0'}, authorizationType: 'JWT', authorizerId: 'a1', authorizationScopes: [], returnsResponse: false},
],
stages: [{stageName: '$default', autoDeploy: true, deploymentId: null, lastUpdatedAt: null, invokePath: '/execute-api/h1/$default'}],
authorizers: [{authorizerId: 'a1', name: 'cognito', type: 'JWT', identitySource: ['$request.header.Authorization'], issuer: 'http://floci:4566/us-east-1_pool', audience: ['client1']}],
cors: null,
}
function renderPanel(resource: CloudResource = httpResource) {
const client = new QueryClient({defaultOptions: {queries: {retry: false}}})
return render(<QueryClientProvider client={client}><HttpApiPanel cloud="aws" resource={resource} runtimeReachable runtimeEndpoint="http://localhost:4566"/></QueryClientProvider>)
}
beforeEach(() => {
vi.clearAllMocks()
api.describeHttpApi.mockResolvedValue(httpOverview)
api.listCloudResources.mockImplementation(async (_cloud: string, service: string) => service === 'serverless'
? [{id: 'notes', name: 'notes', type: 'lambda', cloud: 'aws', service: 'serverless', region: null, createdAt: null, metadata: {}}]
: [{id: 'us-east-1_pool', name: 'notes-users', type: 'user-pool', cloud: 'aws', service: 'userpools', region: null, createdAt: null, metadata: {appClients: [{clientId: 'client1', clientName: 'web'}]}}])
api.createHttpApiRoute.mockResolvedValue(httpOverview.routes[0])
api.setHttpApiRouteAuthorizer.mockResolvedValue(httpOverview.routes[0])
api.createHttpApiAuthorizer.mockResolvedValue(httpOverview.authorizers[0])
api.updateHttpApiCors.mockResolvedValue({allowOrigins: ['*'], allowMethods: ['GET'], allowHeaders: [], exposeHeaders: [], maxAgeSeconds: null, allowCredentials: false})
api.testApiGatewayRoute.mockResolvedValue({statusCode: 200, headers: {}, body: '{"ok":true}', durationMs: 12})
})
test('shows the stage URL, routes with their targets and who may call them', async () => {
renderPanel()
expect(await screen.findByText('http://localhost:4566/execute-api/h1/$default')).toBeInTheDocument()
const routes = within(screen.getByRole('region', {name: 'Routes'}))
expect(routes.getByText('GET /notes/{id}')).toBeInTheDocument()
expect(routes.getAllByText('Lambda: notes')).toHaveLength(2)
expect(routes.getByRole('combobox', {name: 'Access for GET /me'})).toHaveValue('a1')
expect(routes.getByRole('combobox', {name: 'Access for GET /notes/{id}'})).toHaveValue('')
})
test('adds a Lambda route and protects an existing one', async () => {
renderPanel()
const routes = within(await screen.findByRole('region', {name: 'Routes'}))
await userEvent.selectOptions(routes.getByRole('combobox', {name: 'Method'}), 'POST')
await userEvent.clear(routes.getByRole('textbox', {name: 'Path'}))
await userEvent.type(routes.getByRole('textbox', {name: 'Path'}), '/notes')
await routes.findByRole('option', {name: 'notes'})
await userEvent.selectOptions(routes.getByRole('combobox', {name: 'Lambda function'}), 'notes')
await userEvent.click(routes.getByRole('button', {name: 'Add route'}))
expect(api.createHttpApiRoute).toHaveBeenCalledWith('aws', 'h1', {routeKey: 'POST /notes', functionName: 'notes', httpUrl: undefined, authorizerId: undefined, returnsResponse: undefined})
await userEvent.selectOptions(routes.getByRole('combobox', {name: 'Access for GET /notes/{id}'}), 'a1')
expect(api.setHttpApiRouteAuthorizer).toHaveBeenCalledWith('aws', 'h1', 'r1', 'a1')
})
test('creates a JWT authorizer from a Cognito pool and app client', async () => {
renderPanel()
const security = within(await screen.findByRole('region', {name: 'Security'}))
await security.findByRole('option', {name: 'notes-users'})
await userEvent.selectOptions(security.getByRole('combobox', {name: 'User pool'}), 'us-east-1_pool')
await userEvent.selectOptions(security.getByRole('combobox', {name: 'App client'}), 'client1')
await userEvent.click(security.getByRole('button', {name: 'Add authorizer'}))
expect(api.createHttpApiAuthorizer).toHaveBeenCalledWith('aws', 'h1', {name: 'cognito', userPoolId: 'us-east-1_pool', userPoolClientId: 'client1'})
})
test('sends a request to the stage and shows the response', async () => {
renderPanel()
const tester = within(await screen.findByRole('region', {name: 'Send a request'}))
expect(tester.getByRole('textbox', {name: 'Request path'})).toHaveValue('/notes/1')
await userEvent.click(tester.getByRole('button', {name: 'Send request'}))
expect(api.testApiGatewayRoute).toHaveBeenCalledWith('aws', 'h1', expect.objectContaining({stage: '$default', method: 'GET', path: '/notes/1'}))
expect(await tester.findByText('200')).toBeInTheDocument()
})
test('a WebSocket API shows its wss URL and sends a message, without HTTP-only security', async () => {
api.describeHttpApi.mockResolvedValue({
apiId: 'w1', protocol: 'WEBSOCKET', apiEndpoint: null, routeSelectionExpression: '$request.body.action',
routes: [{routeId: 'r1', routeKey: 'sendMessage', integration: null, authorizationType: 'NONE', authorizerId: null, authorizationScopes: [], returnsResponse: true}],
stages: [{stageName: 'dev', autoDeploy: true, deploymentId: null, lastUpdatedAt: null, invokePath: '/ws/w1/dev'}],
authorizers: [], cors: null,
} satisfies HttpApiOverview)
api.testWebSocketApi.mockResolvedValue({connected: true, messages: ['{"echo":"hello"}'], closeCode: null, error: null, durationMs: 40})
renderPanel({...httpResource, id: 'w1', type: 'websocket-api', metadata: {apigatewayService: 'websocket', protocol: 'WEBSOCKET'}})
expect(await screen.findByText('ws://localhost:4566/ws/w1/dev')).toBeInTheDocument()
expect(screen.queryByRole('region', {name: 'Security'})).not.toBeInTheDocument()
const tester = within(screen.getByRole('region', {name: 'Send a message'}))
expect(tester.getByRole('textbox', {name: 'Message'})).toHaveValue(JSON.stringify({action: 'sendMessage', data: 'hello'}, null, 2))
await userEvent.click(tester.getByRole('button', {name: 'Connect and send'}))
expect(api.testWebSocketApi).toHaveBeenCalledWith('aws', 'w1', expect.objectContaining({stage: 'dev'}))
expect(await tester.findByText('Connected')).toBeInTheDocument()
})
@@ -0,0 +1,610 @@
import {useEffect, useState} from 'react'
import {Loader2, Plus, RefreshCw, Rocket, Send, ShieldCheck, Trash2} from 'lucide-react'
import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query'
import {
createHttpApiAuthorizer,
createHttpApiRoute,
createHttpApiStage,
deleteHttpApiAuthorizer,
deleteHttpApiRoute,
deleteHttpApiStage,
deployHttpApi,
describeHttpApi,
listCloudResources,
setHttpApiRouteAuthorizer,
testApiGatewayRoute,
testWebSocketApi,
updateHttpApiCors,
} from '@/api/cloudProxyClient'
import type {HttpApiAuthorizerOverview, HttpApiCors, HttpApiOverview, HttpApiRouteOverview, HttpApiStageOverview} from '@/api/cloudProxyClient'
import type {CloudProvider} from '@/types/cloud'
import type {CloudResource} from '@/types/resource'
import {formatDateTime} from '@/lib/format'
import {CopyValueButton} from './CopyValueButton'
import {formatResponseBody, invokeEndpoint, parseHeaders} from '@/lib/apiGateway'
interface HttpApiPanelProps {
cloud: CloudProvider
resource: CloudResource
runtimeReachable: boolean
runtimeEndpoint?: string
}
const ROUTE_METHODS = ['ANY', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']
const TEST_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD']
const CORS_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', '*']
const WEBSOCKET_SYSTEM_ROUTES = ['$connect', '$disconnect', '$default']
/** API Gateway v2: an HTTP or WebSocket API's routes, stages, security and a live tester. */
export function HttpApiPanel({cloud, resource, runtimeReachable, runtimeEndpoint}: HttpApiPanelProps) {
const queryKey = ['http-api', cloud, resource.id]
const query = useQuery({
queryKey,
queryFn: ({signal}) => describeHttpApi(cloud, resource.id, signal),
enabled: runtimeReachable,
})
const api = query.data
const endpoint = invokeEndpoint(runtimeEndpoint)
const isWebSocket = (api?.protocol ?? resource.metadata.protocol) === 'WEBSOCKET'
return <div className="http-api-workspace">
<section className="table-panel" aria-label={`${isWebSocket ? 'WebSocket' : 'HTTP'} API ${resource.name}`}>
<div className="input-row resource-table-bar">
<div>
<p className="eyebrow">{isWebSocket ? 'WebSocket API' : 'HTTP API'}</p>
<span className="muted">{isWebSocket
? <>Messages are routed by <code>{api?.routeSelectionExpression ?? String(resource.metadata.routeSelectionExpression ?? '')}</code>.</>
: 'Routes send requests to Lambda functions or HTTP backends.'}</span>
</div>
<button className="button" type="button" disabled={!runtimeReachable || query.isFetching} onClick={() => void query.refetch()}><RefreshCw size={14}/>{query.isFetching ? 'Loading' : 'Refresh'}</button>
</div>
{query.isLoading && <p className="muted padded">Loading the API</p>}
{query.error instanceof Error && <p className="error-text compact-text padded" role="alert">{query.error.message}</p>}
{api && <StageUrls api={api} endpoint={endpoint}/>}
</section>
{api && <>
<RoutesSection cloud={cloud} api={api} runtimeReachable={runtimeReachable} queryKey={queryKey}/>
<StagesSection cloud={cloud} api={api} runtimeReachable={runtimeReachable} queryKey={queryKey}/>
{api.protocol === 'HTTP' && <SecuritySection cloud={cloud} api={api} runtimeReachable={runtimeReachable} queryKey={queryKey}/>}
{api.protocol === 'HTTP'
? <HttpTester cloud={cloud} api={api} runtimeReachable={runtimeReachable}/>
: <WebSocketTester cloud={cloud} api={api} runtimeReachable={runtimeReachable}/>}
</>}
</div>
}
function StageUrls({api, endpoint}: {api: HttpApiOverview; endpoint: string | null}) {
if (api.stages.length === 0) return <p className="muted padded">No stages yet. Add one below to serve the API.</p>
return <div className="http-api-urls">
{api.stages.map((stage) => {
const url = stageUrl(api, stage, endpoint)
return <div className="dynamic-field" key={stage.stageName}>
<span>{stage.stageName} {stage.autoDeploy && <small className="muted">· deploys automatically</small>}</span>
{url ? <div className="copy-value"><code>{url}</code><CopyValueButton value={url} label={`${stage.stageName} URL`}/></div> : <code>{stage.invokePath}</code>}
</div>
})}
</div>
}
type SectionProps = {cloud: CloudProvider; api: HttpApiOverview; runtimeReachable: boolean; queryKey: unknown[]}
function RoutesSection({cloud, api, runtimeReachable, queryKey}: SectionProps) {
const queryClient = useQueryClient()
const isWebSocket = api.protocol === 'WEBSOCKET'
const [method, setMethod] = useState('GET')
const [path, setPath] = useState('/hello')
const [catchAll, setCatchAll] = useState(false)
const [webSocketKey, setWebSocketKey] = useState('$default')
const [targetKind, setTargetKind] = useState<'lambda' | 'http'>('lambda')
const [functionName, setFunctionName] = useState('')
const [httpUrl, setHttpUrl] = useState('')
const [authorizerId, setAuthorizerId] = useState('')
const [returnsResponse, setReturnsResponse] = useState(true)
const [confirmDelete, setConfirmDelete] = useState<string | null>(null)
useEffect(() => {
setConfirmDelete(null)
setAuthorizerId('')
}, [api.apiId])
const functionsQuery = useQuery({
queryKey: ['cloud-resources', cloud, 'serverless'],
queryFn: ({signal}) => listCloudResources(cloud, 'serverless', undefined, signal),
enabled: runtimeReachable,
})
const functions = functionsQuery.data?.filter((item) => item.type === 'lambda') ?? []
const refresh = () => queryClient.invalidateQueries({queryKey})
const routeKey = isWebSocket ? webSocketKey.trim() : catchAll ? '$default' : `${method} ${path.trim()}`
const createMutation = useMutation({
mutationFn: () => createHttpApiRoute(cloud, api.apiId, {
routeKey,
functionName: targetKind === 'lambda' ? functionName : undefined,
httpUrl: targetKind === 'http' ? httpUrl.trim() : undefined,
authorizerId: authorizerId || undefined,
returnsResponse: isWebSocket ? returnsResponse : undefined,
}),
onSuccess: refresh,
})
const deleteMutation = useMutation({
mutationFn: (routeId: string) => deleteHttpApiRoute(cloud, api.apiId, routeId),
onSuccess: () => {
setConfirmDelete(null)
return refresh()
},
})
const authorizerMutation = useMutation({
mutationFn: ({routeId, authorizer}: {routeId: string; authorizer: string | null}) => setHttpApiRouteAuthorizer(cloud, api.apiId, routeId, authorizer),
onSuccess: refresh,
})
const target = targetKind === 'lambda' ? functionName : httpUrl.trim()
const canCreate = runtimeReachable && Boolean(routeKey && target) && !createMutation.isPending
const authorizerName = (id: string | null) => api.authorizers.find((authorizer) => authorizer.authorizerId === id)?.name ?? id
const error = createMutation.error ?? deleteMutation.error ?? authorizerMutation.error
return <section className="table-panel" aria-label="Routes">
<div className="input-row resource-table-bar">
<div>
<p className="eyebrow">Routes</p>
<span className="muted">{isWebSocket
? '$connect and $disconnect run when a client connects and leaves; other messages go to the route their action names, or $default.'
: 'The most specific route wins; $default catches every request no other route matches.'}</span>
</div>
</div>
{api.routes.length === 0 && <p className="muted padded">No routes yet.</p>}
{api.routes.length > 0 && <div className="cognito-table"><table className="table">
<thead><tr><th>Route</th><th>Target</th>{!isWebSocket && <th>Access</th>}<th aria-label="Actions"/></tr></thead>
<tbody>{api.routes.map((route) => <tr key={route.routeId}>
<td><code>{route.routeKey}</code>{isWebSocket && route.returnsResponse && <small className="muted"> · replies</small>}</td>
<td>{describeTarget(route)}</td>
{!isWebSocket && <td>
<select className="input http-api-access" aria-label={`Access for ${route.routeKey}`} value={route.authorizerId ?? ''} disabled={!runtimeReachable || authorizerMutation.isPending}
onChange={(event) => authorizerMutation.mutate({routeId: route.routeId, authorizer: event.target.value || null})}>
<option value="">Open to anyone</option>
{api.authorizers.map((authorizer) => <option key={authorizer.authorizerId} value={authorizer.authorizerId}>JWT: {authorizer.name}</option>)}
</select>
{route.authorizerId && !api.authorizers.some((authorizer) => authorizer.authorizerId === route.authorizerId) && <small className="muted">Authorizer {authorizerName(route.authorizerId)}</small>}
</td>}
<td className="cognito-row-actions-cell">
{confirmDelete === route.routeId
? <span className="apigateway-route-confirm">
<span>Delete {route.routeKey}?</span>
<button className="button danger compact" type="button" disabled={deleteMutation.isPending} onClick={() => deleteMutation.mutate(route.routeId)}>Delete</button>
<button className="button compact" type="button" disabled={deleteMutation.isPending} onClick={() => setConfirmDelete(null)}>Cancel</button>
</span>
: <button className="icon-btn" type="button" aria-label={`Delete ${route.routeKey}`} disabled={!runtimeReachable} onClick={() => setConfirmDelete(route.routeId)}><Trash2 size={13}/></button>}
</td>
</tr>)}</tbody>
</table></div>}
<form className="dynamic-form" aria-label="Add a route" onSubmit={(event) => {
event.preventDefault()
if (canCreate) createMutation.mutate()
}}>
{isWebSocket ? <label className="dynamic-field">
<span>Route key</span>
<input className="input" list="websocket-route-keys" value={webSocketKey} onChange={(event) => setWebSocketKey(event.target.value)} placeholder="sendMessage"/>
<datalist id="websocket-route-keys">{WEBSOCKET_SYSTEM_ROUTES.map((key) => <option key={key} value={key}/>)}</datalist>
<small>$connect, $disconnect, $default, or an action such as sendMessage.</small>
</label> : <>
<label className="dynamic-field">
<span>Method</span>
<select className="input" value={method} disabled={catchAll} onChange={(event) => setMethod(event.target.value)}>
{ROUTE_METHODS.map((value) => <option key={value} value={value}>{value}</option>)}
</select>
</label>
<label className="dynamic-field">
<span>Path</span>
<input className="input" aria-label="Path" value={path} disabled={catchAll} onChange={(event) => setPath(event.target.value)} placeholder="/notes/{id}"/>
<small>Use {'{id}'} for a path parameter and a final {'{proxy+}'} for everything below.</small>
</label>
<label className="dynamic-field http-api-check-field">
<input type="checkbox" checked={catchAll} onChange={(event) => setCatchAll(event.target.checked)}/>
<span>Catch-all ($default)</span>
</label>
</>}
{!isWebSocket && <label className="dynamic-field">
<span>Target</span>
<select className="input" value={targetKind} onChange={(event) => setTargetKind(event.target.value as 'lambda' | 'http')}>
<option value="lambda">Lambda function</option>
<option value="http">HTTP backend</option>
</select>
</label>}
{targetKind === 'lambda' || isWebSocket
? <label className="dynamic-field">
<span>Lambda function</span>
<select className="input" aria-label="Lambda function" value={functionName} onChange={(event) => setFunctionName(event.target.value)}>
<option value="">Select a Lambda function</option>
{functions.map((fn) => <option key={fn.id} value={fn.name}>{fn.name}</option>)}
</select>
<small>{functionsQuery.isLoading ? 'Loading functions' : functions.length === 0 ? 'Create a Lambda function first.' : isWebSocket ? 'Receives the message as a WebSocket event.' : 'Receives a version 2.0 proxy event.'}</small>
</label>
: <label className="dynamic-field">
<span>Backend URL</span>
<input className="input" value={httpUrl} onChange={(event) => setHttpUrl(event.target.value)} placeholder="https://backend.example.com/{proxy}"/>
<small>Requests are proxied here as they are.</small>
</label>}
{!isWebSocket && api.authorizers.length > 0 && <label className="dynamic-field">
<span>Access</span>
<select className="input" aria-label="Access for the new route" value={authorizerId} onChange={(event) => setAuthorizerId(event.target.value)}>
<option value="">Open to anyone</option>
{api.authorizers.map((authorizer) => <option key={authorizer.authorizerId} value={authorizer.authorizerId}>JWT: {authorizer.name}</option>)}
</select>
</label>}
{isWebSocket && <label className="dynamic-field http-api-check-field">
<input type="checkbox" checked={returnsResponse} onChange={(event) => setReturnsResponse(event.target.checked)}/>
<span>Send the function's response back to the client</span>
</label>}
<button className="button primary" type="submit" disabled={!canCreate}>
{createMutation.isPending ? <Loader2 size={13}/> : <Plus size={13}/>}{createMutation.isPending ? 'Adding' : 'Add route'}
</button>
</form>
{error instanceof Error && <p className="error-text compact-text padded" role="alert">{error.message}</p>}
</section>
}
function StagesSection({cloud, api, runtimeReachable, queryKey}: SectionProps) {
const queryClient = useQueryClient()
const [stageName, setStageName] = useState('prod')
const [autoDeploy, setAutoDeploy] = useState(true)
const [confirmDelete, setConfirmDelete] = useState<string | null>(null)
const [notice, setNotice] = useState('')
const refresh = () => queryClient.invalidateQueries({queryKey})
useEffect(() => {
setConfirmDelete(null)
setNotice('')
}, [api.apiId])
const createMutation = useMutation({
mutationFn: () => createHttpApiStage(cloud, api.apiId, {stageName: stageName.trim(), autoDeploy}),
onSuccess: (stage) => {
setNotice(stage.autoDeploy ? `${stage.stageName} deploys every change automatically.` : `${stage.stageName} is deployed. Deploy it again after changing routes.`)
return refresh()
},
})
const deployMutation = useMutation({
mutationFn: (name: string) => deployHttpApi(cloud, api.apiId, name),
onSuccess: (stage) => {
setNotice(`Deployed the current routes to ${stage.stageName}.`)
return refresh()
},
})
const deleteMutation = useMutation({
mutationFn: (name: string) => deleteHttpApiStage(cloud, api.apiId, name),
onSuccess: () => {
setConfirmDelete(null)
return refresh()
},
})
const error = createMutation.error ?? deployMutation.error ?? deleteMutation.error
const busy = !runtimeReachable || createMutation.isPending || deployMutation.isPending || deleteMutation.isPending
return <section className="table-panel" aria-label="Stages">
<div className="input-row resource-table-bar">
<div>
<p className="eyebrow">Stages</p>
<span className="muted">A stage serves a deployment of the routes. With automatic deployment, every change is live right away.</span>
</div>
</div>
{api.stages.length > 0 && <div className="cognito-table"><table className="table">
<thead><tr><th>Stage</th><th>Deployment</th><th>Updated</th><th aria-label="Actions"/></tr></thead>
<tbody>{api.stages.map((stage) => <tr key={stage.stageName}>
<td><code>{stage.stageName}</code></td>
<td>{stage.autoDeploy ? 'Automatic' : stage.deploymentId ? <code>{stage.deploymentId}</code> : 'Not deployed'}</td>
<td>{formatDateTime(stage.lastUpdatedAt) ?? '—'}</td>
<td className="cognito-row-actions-cell">
{!stage.autoDeploy && <button className="button compact" type="button" disabled={busy} onClick={() => deployMutation.mutate(stage.stageName)}><Rocket size={13}/>Deploy</button>}
{confirmDelete === stage.stageName
? <span className="apigateway-route-confirm">
<span>Delete {stage.stageName}?</span>
<button className="button danger compact" type="button" disabled={busy} onClick={() => deleteMutation.mutate(stage.stageName)}>Delete</button>
<button className="button compact" type="button" onClick={() => setConfirmDelete(null)}>Cancel</button>
</span>
: <button className="icon-btn" type="button" aria-label={`Delete stage ${stage.stageName}`} disabled={busy} onClick={() => setConfirmDelete(stage.stageName)}><Trash2 size={13}/></button>}
</td>
</tr>)}</tbody>
</table></div>}
<form className="dynamic-form" aria-label="Add a stage" onSubmit={(event) => {
event.preventDefault()
setNotice('')
if (stageName.trim()) createMutation.mutate()
}}>
<label className="dynamic-field"><span>Stage name</span><input className="input" value={stageName} onChange={(event) => setStageName(event.target.value)} placeholder="prod"/></label>
<label className="dynamic-field http-api-check-field">
<input type="checkbox" checked={autoDeploy} onChange={(event) => setAutoDeploy(event.target.checked)}/>
<span>Deploy changes automatically</span>
</label>
<button className="button primary" type="submit" disabled={busy || !stageName.trim()}><Plus size={13}/>{createMutation.isPending ? 'Adding' : 'Add stage'}</button>
</form>
{notice && <p className="cognito-outcome cognito-outcome--ok" role="status">{notice}</p>}
{error instanceof Error && <p className="error-text compact-text padded" role="alert">{error.message}</p>}
</section>
}
function SecuritySection({cloud, api, runtimeReachable, queryKey}: SectionProps) {
return <section className="table-panel" aria-label="Security">
<div className="input-row resource-table-bar">
<div>
<p className="eyebrow"><ShieldCheck size={13}/> Security</p>
<span className="muted">A JWT authorizer checks each request's bearer token; protect a route by choosing it under Access above.</span>
</div>
</div>
<AuthorizersSection cloud={cloud} api={api} runtimeReachable={runtimeReachable} queryKey={queryKey}/>
<CorsSection cloud={cloud} api={api} runtimeReachable={runtimeReachable} queryKey={queryKey}/>
</section>
}
function AuthorizersSection({cloud, api, runtimeReachable, queryKey}: SectionProps) {
const queryClient = useQueryClient()
const [source, setSource] = useState<'cognito' | 'issuer'>('cognito')
const [name, setName] = useState('cognito')
const [userPoolId, setUserPoolId] = useState('')
const [clientId, setClientId] = useState('')
const [issuer, setIssuer] = useState('')
const [audience, setAudience] = useState('')
const refresh = () => queryClient.invalidateQueries({queryKey})
const poolsQuery = useQuery({
queryKey: ['cloud-resources', cloud, 'userpools'],
queryFn: ({signal}) => listCloudResources(cloud, 'userpools', undefined, signal),
enabled: runtimeReachable,
})
const pools = poolsQuery.data ?? []
const pool = pools.find((candidate) => candidate.id === userPoolId)
const clients = Array.isArray(pool?.metadata.appClients) ? pool.metadata.appClients as Array<{clientId: string; clientName: string}> : []
const createMutation = useMutation({
mutationFn: () => createHttpApiAuthorizer(cloud, api.apiId, source === 'cognito'
? {name: name.trim(), userPoolId, userPoolClientId: clientId}
: {name: name.trim(), issuer: issuer.trim(), audience: audience.split(',').map((value) => value.trim()).filter(Boolean)}),
onSuccess: refresh,
})
const deleteMutation = useMutation({
mutationFn: (authorizerId: string) => deleteHttpApiAuthorizer(cloud, api.apiId, authorizerId),
onSuccess: refresh,
})
const ready = source === 'cognito' ? Boolean(userPoolId && clientId) : Boolean(issuer.trim() && audience.trim())
const error = createMutation.error ?? deleteMutation.error
return <>
{api.authorizers.length > 0 && <div className="cognito-table"><table className="table">
<thead><tr><th>Authorizer</th><th>Issuer</th><th>Audience</th><th aria-label="Actions"/></tr></thead>
<tbody>{api.authorizers.map((authorizer: HttpApiAuthorizerOverview) => <tr key={authorizer.authorizerId}>
<td>{authorizer.name} <small className="muted">· {authorizer.type}</small></td>
<td className="mono http-api-wrap">{authorizer.issuer ?? '—'}</td>
<td className="mono http-api-wrap">{authorizer.audience.join(', ') || '—'}</td>
<td className="cognito-row-actions-cell"><button className="icon-btn" type="button" aria-label={`Delete authorizer ${authorizer.name}`} disabled={!runtimeReachable || deleteMutation.isPending} onClick={() => deleteMutation.mutate(authorizer.authorizerId)}><Trash2 size={13}/></button></td>
</tr>)}</tbody>
</table></div>}
<form className="dynamic-form" aria-label="Add a JWT authorizer" onSubmit={(event) => {
event.preventDefault()
if (ready && name.trim()) createMutation.mutate()
}}>
<label className="dynamic-field"><span>Name</span><input className="input" value={name} onChange={(event) => setName(event.target.value)}/></label>
<label className="dynamic-field">
<span>Tokens from</span>
<select className="input" value={source} onChange={(event) => setSource(event.target.value as 'cognito' | 'issuer')}>
<option value="cognito">A Cognito user pool</option>
<option value="issuer">Another OpenID Connect issuer</option>
</select>
</label>
{source === 'cognito' ? <>
<label className="dynamic-field">
<span>User pool</span>
<select className="input" aria-label="User pool" value={userPoolId} onChange={(event) => { setUserPoolId(event.target.value); setClientId('') }}>
<option value="">Select a user pool</option>
{pools.map((candidate) => <option key={candidate.id} value={candidate.id}>{candidate.name}</option>)}
</select>
{poolsQuery.isSuccess && pools.length === 0 && <small>Create a Cognito user pool first.</small>}
</label>
<label className="dynamic-field">
<span>App client</span>
<select className="input" aria-label="App client" value={clientId} disabled={!pool} onChange={(event) => setClientId(event.target.value)}>
<option value="">Select an app client</option>
{clients.map((client) => <option key={client.clientId} value={client.clientId}>{client.clientName || client.clientId}</option>)}
</select>
<small>Only this client's tokens are accepted.</small>
</label>
</> : <>
<label className="dynamic-field"><span>Issuer URL</span><input className="input" value={issuer} onChange={(event) => setIssuer(event.target.value)} placeholder="https://login.example.com/"/></label>
<label className="dynamic-field"><span>Audience</span><input className="input" value={audience} onChange={(event) => setAudience(event.target.value)} placeholder="client-id, another-client-id"/></label>
</>}
<button className="button primary" type="submit" disabled={!runtimeReachable || !ready || !name.trim() || createMutation.isPending}><Plus size={13}/>{createMutation.isPending ? 'Adding' : 'Add authorizer'}</button>
</form>
{error instanceof Error && <p className="error-text compact-text padded" role="alert">{error.message}</p>}
</>
}
function CorsSection({cloud, api, runtimeReachable, queryKey}: SectionProps) {
const queryClient = useQueryClient()
const [origins, setOrigins] = useState('')
const [methods, setMethods] = useState<string[]>([])
const [headers, setHeaders] = useState('')
const [exposeHeaders, setExposeHeaders] = useState('')
const [maxAge, setMaxAge] = useState('')
const [credentials, setCredentials] = useState(false)
const [notice, setNotice] = useState('')
useEffect(() => {
const cors = api.cors
setOrigins(cors?.allowOrigins.join(', ') ?? '*')
setMethods(cors?.allowMethods ?? ['GET', 'POST', 'OPTIONS'])
setHeaders(cors?.allowHeaders.join(', ') ?? 'content-type, authorization')
setExposeHeaders(cors?.exposeHeaders.join(', ') ?? '')
setMaxAge(cors?.maxAgeSeconds === null || cors?.maxAgeSeconds === undefined ? '' : String(cors.maxAgeSeconds))
setCredentials(cors?.allowCredentials ?? false)
setNotice('')
}, [api.apiId, api.cors])
const mutation = useMutation({
mutationFn: (cors: HttpApiCors | null) => updateHttpApiCors(cloud, api.apiId, cors),
onSuccess: (cors) => {
setNotice(cors ? 'CORS saved. API Gateway now answers preflight requests itself.' : 'CORS removed.')
return queryClient.invalidateQueries({queryKey})
},
})
const split = (value: string) => value.split(',').map((item) => item.trim()).filter(Boolean)
return <>
<div className="input-row resource-table-bar"><div>
<p className="eyebrow">CORS</p>
<span className="muted">{api.cors ? 'On: browsers on the allowed origins can call this API.' : 'Off: browsers on other sites cannot call this API.'}</span>
</div></div>
<form className="dynamic-form" aria-label="CORS" onSubmit={(event) => {
event.preventDefault()
setNotice('')
mutation.mutate({allowOrigins: split(origins), allowMethods: methods, allowHeaders: split(headers), exposeHeaders: split(exposeHeaders), maxAgeSeconds: maxAge.trim() ? Number(maxAge) : null, allowCredentials: credentials})
}}>
<label className="dynamic-field"><span>Allowed origins</span><input className="input" value={origins} onChange={(event) => setOrigins(event.target.value)} placeholder="https://app.example.com"/><small>Comma separated, or * for any site.</small></label>
<div className="dynamic-field"><span>Allowed methods</span><div className="http-api-checks">{CORS_METHODS.map((value) => <label key={value}><input type="checkbox" checked={methods.includes(value)} onChange={() => setMethods((current) => current.includes(value) ? current.filter((item) => item !== value) : [...current, value])}/>{value}</label>)}</div></div>
<label className="dynamic-field"><span>Allowed headers</span><input className="input" value={headers} onChange={(event) => setHeaders(event.target.value)}/></label>
<label className="dynamic-field"><span>Exposed headers</span><input className="input" value={exposeHeaders} onChange={(event) => setExposeHeaders(event.target.value)} placeholder="x-request-id"/></label>
<label className="dynamic-field"><span>Max age (seconds)</span><input className="input" inputMode="numeric" value={maxAge} onChange={(event) => setMaxAge(event.target.value)} placeholder="300"/></label>
<label className="dynamic-field http-api-check-field"><input type="checkbox" checked={credentials} onChange={(event) => setCredentials(event.target.checked)}/><span>Allow credentials (cookies)</span></label>
<div className="cloudwatch-form-actions">
<button className="button primary" type="submit" disabled={!runtimeReachable || mutation.isPending}>{mutation.isPending ? 'Saving' : 'Save CORS'}</button>
{api.cors && <button className="button" type="button" disabled={!runtimeReachable || mutation.isPending} onClick={() => { setNotice(''); mutation.mutate(null) }}>Remove CORS</button>}
</div>
</form>
{notice && <p className="cognito-outcome cognito-outcome--ok" role="status">{notice}</p>}
{mutation.error instanceof Error && <p className="error-text compact-text padded" role="alert">{mutation.error.message}</p>}
</>
}
function HttpTester({cloud, api, runtimeReachable}: {cloud: CloudProvider; api: HttpApiOverview; runtimeReachable: boolean}) {
const [stage, setStage] = useState(api.stages[0]?.stageName ?? '$default')
const [method, setMethod] = useState('GET')
const [path, setPath] = useState(suggestedPath(api.routes))
const [query, setQuery] = useState('')
const [headers, setHeaders] = useState('{\n "content-type": "application/json"\n}')
const [body, setBody] = useState('')
useEffect(() => {
setStage(api.stages[0]?.stageName ?? '$default')
setPath(suggestedPath(api.routes))
// Only when another API is opened; keep what the user typed while this one refreshes.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [api.apiId])
const mutation = useMutation({
mutationFn: () => testApiGatewayRoute(cloud, api.apiId, {path: path.trim(), method, stage, body, headers: parseHeaders(headers), query}),
})
const result = mutation.data
return <section className="table-panel apigateway-test-panel" aria-label="Send a request">
<div className="input-row resource-table-bar"><div>
<p className="eyebrow"><Send size={13}/> Send a request</p>
<span className="muted">Sends a real request to the stage, through its routes and authorizers. For a protected route, add an <code>authorization</code> header with <code>Bearer</code> and a token.</span>
</div></div>
<div className="apigateway-test-workspace">
<form className="apigateway-test-form" onSubmit={(event) => {
event.preventDefault()
if (!mutation.isPending) mutation.mutate()
}}>
<label className="dynamic-field"><span>Stage</span>
<select className="input" value={stage} onChange={(event) => setStage(event.target.value)}>
{api.stages.map((item) => <option key={item.stageName} value={item.stageName}>{item.stageName}</option>)}
</select>
</label>
<label className="dynamic-field"><span>Method</span>
<select className="input" value={method} onChange={(event) => setMethod(event.target.value)}>{TEST_METHODS.map((value) => <option key={value} value={value}>{value}</option>)}</select>
</label>
<label className="dynamic-field"><span>Path</span><input className="input" aria-label="Request path" value={path} onChange={(event) => setPath(event.target.value)} placeholder="/notes/123"/></label>
<label className="dynamic-field"><span>Query string</span><input className="input" value={query} onChange={(event) => setQuery(event.target.value)} placeholder="page=1"/></label>
<label className="dynamic-field"><span>Headers (JSON)</span><textarea className="textarea code-textarea small" value={headers} onChange={(event) => setHeaders(event.target.value)} spellCheck={false}/></label>
{!['GET', 'HEAD'].includes(method) && <label className="dynamic-field"><span>Body</span><textarea className="textarea code-textarea" aria-label="Request body" value={body} onChange={(event) => setBody(event.target.value)} spellCheck={false}/></label>}
<button className="button primary" type="submit" disabled={!runtimeReachable || api.stages.length === 0 || mutation.isPending}>
{mutation.isPending ? <Loader2 size={13}/> : <Send size={13}/>}{mutation.isPending ? 'Sending' : 'Send request'}
</button>
{api.stages.length === 0 && <small className="muted">Add a stage first.</small>}
{mutation.error instanceof Error && <p className="error-text compact-text" role="alert">{mutation.error.message}</p>}
</form>
<div className="apigateway-test-response">
{result ? <div className="apigateway-test-result">
<div className="apigateway-test-result-header">
<strong>Response <span className={result.statusCode < 400 ? 'status-success' : 'status-error'}>{result.statusCode}</span></strong>
<small>{result.durationMs} ms</small>
</div>
<details><summary>Response headers</summary><pre>{JSON.stringify(result.headers, null, 2)}</pre></details>
<pre>{formatResponseBody(result.body)}</pre>
</div> : <p className="muted compact-text">Send a request to see the response.</p>}
</div>
</div>
</section>
}
function WebSocketTester({cloud, api, runtimeReachable}: {cloud: CloudProvider; api: HttpApiOverview; runtimeReachable: boolean}) {
const actionField = api.routeSelectionExpression?.match(/^\$request\.body\.(.+)$/)?.[1] ?? 'action'
const firstAction = api.routes.find((route) => !WEBSOCKET_SYSTEM_ROUTES.includes(route.routeKey))?.routeKey ?? 'sendMessage'
const [stage, setStage] = useState(api.stages[0]?.stageName ?? '')
const [message, setMessage] = useState(JSON.stringify({[actionField]: firstAction, data: 'hello'}, null, 2))
const [query, setQuery] = useState('')
useEffect(() => {
setStage(api.stages[0]?.stageName ?? '')
// Only when another API is opened.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [api.apiId])
const mutation = useMutation({mutationFn: () => testWebSocketApi(cloud, api.apiId, {stage, message, query})})
const result = mutation.data
return <section className="table-panel apigateway-test-panel" aria-label="Send a message">
<div className="input-row resource-table-bar"><div>
<p className="eyebrow"><Send size={13}/> Send a message</p>
<span className="muted">Connects to the stage like a client would, sends one message, and shows what comes back. Replies need a route that sends the function's response back.</span>
</div></div>
<div className="apigateway-test-workspace">
<form className="apigateway-test-form" onSubmit={(event) => {
event.preventDefault()
if (!mutation.isPending && stage) mutation.mutate()
}}>
<label className="dynamic-field"><span>Stage</span>
<select className="input" value={stage} onChange={(event) => setStage(event.target.value)}>
{api.stages.map((item) => <option key={item.stageName} value={item.stageName}>{item.stageName}</option>)}
</select>
</label>
<label className="dynamic-field"><span>Connection query string</span><input className="input" value={query} onChange={(event) => setQuery(event.target.value)} placeholder="token=abc"/><small>Passed to $connect.</small></label>
<label className="dynamic-field"><span>Message</span><textarea className="textarea code-textarea" aria-label="Message" value={message} onChange={(event) => setMessage(event.target.value)} spellCheck={false}/></label>
<button className="button primary" type="submit" disabled={!runtimeReachable || !stage || mutation.isPending}>
{mutation.isPending ? <Loader2 size={13}/> : <Send size={13}/>}{mutation.isPending ? 'Connecting' : 'Connect and send'}
</button>
{api.stages.length === 0 && <small className="muted">Add a stage first.</small>}
{mutation.error instanceof Error && <p className="error-text compact-text" role="alert">{mutation.error.message}</p>}
</form>
<div className="apigateway-test-response">
{result ? <div className="apigateway-test-result">
<div className="apigateway-test-result-header">
<strong>{result.connected ? <span className="status-success">Connected</span> : <span className="status-error">Not connected</span>}</strong>
<small>{result.durationMs} ms</small>
</div>
{result.error && <p className="error-text compact-text">{result.error}</p>}
{result.connected && result.messages.length === 0 && <p className="muted compact-text">No reply. Check the route sends the function's response back.</p>}
{result.messages.map((reply, index) => <pre key={index}>{formatResponseBody(reply)}</pre>)}
</div> : <p className="muted compact-text">Send a message to see the replies.</p>}
</div>
</div>
</section>
}
function describeTarget(route: HttpApiRouteOverview): string {
const integration = route.integration
if (!integration) return 'No target'
if (integration.functionName) return `Lambda: ${integration.functionName}`
if (integration.type === 'HTTP_PROXY') return `HTTP: ${integration.uri ?? ''}`
return integration.type
}
function stageUrl(api: HttpApiOverview, stage: HttpApiStageOverview, endpoint: string | null): string | null {
if (!endpoint) return null
return `${api.protocol === 'WEBSOCKET' ? endpoint.replace(/^http/, 'ws') : endpoint}${stage.invokePath}`
}
/** A path to try first: the first route's path with its parameters filled in. */
function suggestedPath(routes: HttpApiRouteOverview[]): string {
const path = routes.map((route) => route.routeKey.split(' ')[1]).find(Boolean)
if (!path || path === '/') return '/hello'
return path.replace(/\{[^}]+\+\}/g, 'anything').replace(/\{[^}]+\}/g, '1')
}
+13
View File
@@ -6566,6 +6566,19 @@ tr[aria-current="true"] td { background: var(--hover-md); }
.cloudwatch-form-actions { display: flex; flex-wrap: wrap; gap: 8px; align-self: end; }
.cognito-row-actions-cell { text-align: right; }
/* API Gateway v2 (HTTP and WebSocket APIs): one column of sections, unlike the REST API's two. */
.http-api-workspace { display: grid; gap: 16px; min-width: 0; }
.http-api-workspace .dynamic-form { padding: 4px 16px 16px; }
.http-api-workspace .apigateway-test-workspace { padding: 0 16px 16px; }
.http-api-urls { display: grid; gap: 8px; padding: 0 16px 12px; }
.http-api-urls .copy-value { overflow-wrap: anywhere; min-width: 0; }
.http-api-check-field { display: flex; align-items: center; gap: 8px; align-self: end; min-height: 36px; }
.http-api-check-field span { text-transform: none; font-size: 13px; font-weight: 500; color: var(--text-1); }
.http-api-checks { display: flex; flex-wrap: wrap; gap: 4px 12px; }
.http-api-checks label { display: inline-flex; align-items: center; gap: 4px; }
.http-api-access { min-width: 0; max-width: 220px; }
.http-api-wrap { overflow-wrap: anywhere; }
.metric-chart { position: relative; width: 100%; min-width: 0; }
.metric-chart svg { display: block; max-width: 100%; height: auto; overflow: visible; }
.metric-chart svg:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 4px; }
+45
View File
@@ -0,0 +1,45 @@
// Shared by the REST API and HTTP/WebSocket API panels.
/** The runtime endpoint as the browser can reach it, for building invoke URLs. */
export function invokeEndpoint(runtimeEndpoint?: string): string | null {
if (!runtimeEndpoint) return null
try {
const endpoint = new URL(runtimeEndpoint)
if (isDockerBridgeAddress(endpoint.hostname) && typeof window !== 'undefined') {
endpoint.hostname = window.location.hostname
}
return endpoint.toString().replace(/\/$/, '')
} catch {
return runtimeEndpoint.replace(/\/$/, '')
}
}
function isDockerBridgeAddress(hostname: string): boolean {
const octets = hostname.split('.').map(Number)
return octets.length === 4
&& octets.every((octet) => Number.isInteger(octet) && octet >= 0 && octet <= 255)
&& octets[0] === 172
&& octets[1] >= 16
&& octets[1] <= 31
}
export function parseHeaders(value: string): Record<string, string> {
let parsed: unknown
try {
parsed = JSON.parse(value || '{}')
} catch {
throw new Error('Request headers must be valid JSON.')
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || Object.values(parsed).some((header) => typeof header !== 'string')) {
throw new Error('Request headers must be a JSON object with string values.')
}
return parsed as Record<string, string>
}
export function formatResponseBody(body: string): string {
try {
return JSON.stringify(JSON.parse(body), null, 2)
} catch {
return body || '(empty response body)'
}
}