Files
supabase/apps/studio/components/interfaces/LogDrains/LogDrains.utils.ts
Jordi EnricandClaude Opus 4.8 34163fc0ca fix(studio): duplicate Content-Type on webhook log drains (#46673)
## Problem

Webhook log drains (project and org/audit) deliver requests with a
malformed, duplicated `Content-Type: application/jsonapplication/json`
header. On at least some receivers this breaks body parsing, so the
delivered body appears empty even though it is present (confirmed with
gzip both on and off).

Root cause: the create form seeds a default `Content-Type:
application/json` header for webhook drains, and the logflare webhook
adaptor's `Tesla.Middleware.JSON` also sets `content-type:
application/json` when it encodes the body. Both are sent, and the
receiver concatenates the two same-named headers.

## Fix

Stop seeding `Content-Type` in the webhook default headers
(`getDefaultHeadersByType`). The delivery side already sets it, so a
single clean header is sent. OTLP keeps its `application/x-protobuf`
default because the OTLP delivery path uses `json: false` and does not
set a content type itself.

Updated the form tests that assumed the seeded header (the added-header
row is now index 0 instead of 1, and the duplicate-header test now adds
two explicit rows).

## How to test

- Create a webhook (Custom Endpoint) audit log drain pointing at a
request bin.
- Trigger an audit event and inspect the delivered request:
`Content-Type` should be a single `application/json`, and the JSON body
should be visible.

## Note

This fixes the common case (the seeded default). A user who manually
adds a `Content-Type` header to a webhook drain would still hit the
duplication; the robust cross-team fix would be for the logflare webhook
adaptor to drop an incoming `content-type` before its JSON middleware
sets one. Flagging for the logs team.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Bug Fixes**
* Log Drain header handling corrected: webhook drains no longer add a
default Content-Type; other drain types retain their appropriate
defaults. Empty header rows are no longer submitted.
* **Tests**
* Updated tests to match new header indexing, validation behavior, and
submission expectations.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-05 17:55:23 +02:00

113 lines
3.4 KiB
TypeScript

/**
* Utility functions for log drain management
* Extracted for testability
*/
import { getKeyValueFieldArrayValidationIssues } from 'ui-patterns/form/KeyValueFieldArray/validation'
import { z } from 'zod'
import { LogDrainType } from './LogDrains.constants'
import { httpEndpointUrlSchema } from '@/lib/validation/http-url'
export type LogDrainHeaderRow = {
key: string
value: string
}
/**
* Get the description text for the custom headers section based on log drain type
*/
export function getHeadersSectionDescription(type: LogDrainType): string {
if (type === 'webhook') {
return 'Set custom headers when draining logs to the Endpoint URL'
}
if (type === 'loki') {
return 'Set custom headers when draining logs to the Loki HTTP(S) endpoint'
}
if (type === 'otlp') {
return 'Set custom headers for OTLP authentication (e.g., Authorization, X-API-Key)'
}
return ''
}
/**
* Validation errors for header management
*/
export const HEADER_VALIDATION_ERRORS = {
MAX_LIMIT: 'You can only have 20 custom headers',
DUPLICATE: 'Header name already exists',
KEY_REQUIRED: 'Header name is required',
VALUE_REQUIRED: 'Header value is required',
} as const
// Webhook drains intentionally omit a Content-Type default: the delivery side already sets
// `application/json`, and seeding it here produces a duplicated Content-Type header that can
// break body parsing on the receiver. OTLP needs it since its delivery does not set one.
const DEFAULT_HEADERS_BY_TYPE: Partial<Record<LogDrainType, Record<string, string>>> = {
otlp: { 'Content-Type': 'application/x-protobuf' },
}
export function getDefaultHeadersByType(type: LogDrainType): Record<string, string> {
return DEFAULT_HEADERS_BY_TYPE[type] ?? {}
}
export function headerRecordToRows(headers: Record<string, string> = {}): LogDrainHeaderRow[] {
return Object.entries(headers).map(([key, value]) => ({ key, value }))
}
export function headerRowsToRecord(rows: LogDrainHeaderRow[] = []): Record<string, string> {
return rows.reduce<Record<string, string>>((acc, row) => {
const key = row.key.trim()
const value = row.value.trim()
if (key && value) {
acc[key] = value
}
return acc
}, {})
}
export const logDrainHeaderEntriesSchema = z
.array(
z.object({
key: z.string().trim(),
value: z.string().trim(),
})
)
.max(20, HEADER_VALIDATION_ERRORS.MAX_LIMIT)
.superRefine((rows, ctx) => {
getKeyValueFieldArrayValidationIssues({
rows,
keyFieldName: 'key',
valueFieldName: 'value',
keyRequiredMessage: HEADER_VALIDATION_ERRORS.KEY_REQUIRED,
valueRequiredMessage: HEADER_VALIDATION_ERRORS.VALUE_REQUIRED,
duplicateKeyMessage: HEADER_VALIDATION_ERRORS.DUPLICATE,
}).forEach((issue) => {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: issue.message,
path: issue.path,
})
})
})
/**
* Zod schema for OTLP log drain configuration
* Extracted for testing purposes
*/
export const otlpConfigSchema = z.object({
type: z.literal('otlp'),
endpoint: httpEndpointUrlSchema({
requiredMessage: 'OTLP endpoint is required',
invalidMessage: 'OTLP endpoint must be a valid URL',
prefixMessage: 'OTLP endpoint must start with http:// or https://',
}),
protocol: z.string().optional().default('http/protobuf'),
gzip: z.boolean().optional().default(true),
headers: z.record(z.string(), z.string()).optional(),
})
export type OtlpConfig = z.infer<typeof otlpConfigSchema>