Skip to content
TypeScript

Allow setting T3CODE_OTLP_HEADERS (#11218)

Arne Bahlo494cfac24940
diff --git a/apps/desktop/scripts/electron-launcher.mjs b/apps/desktop/scripts/electron-launcher.mjs
index eedfff9744f..f1c1f57822a 100644
--- a/apps/desktop/scripts/electron-launcher.mjs
+++ b/apps/desktop/scripts/electron-launcher.mjs
@@ -116,6 +116,7 @@ export function makeDevelopmentEnvironmentScript(environment) {
["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH],
["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL],
["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.T3CODE_OTLP_EXPORT_INTERVAL_MS],
+ ["T3CODE_OTLP_HEADERS", environment.T3CODE_OTLP_HEADERS],
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
return [
diff --git a/apps/desktop/src/app/DesktopConfig.ts b/apps/desktop/src/app/DesktopConfig.ts
index d157a4c6ba4..21062d3c0fa 100644
--- a/apps/desktop/src/app/DesktopConfig.ts
+++ b/apps/desktop/src/app/DesktopConfig.ts
@@ -1,3 +1,4 @@
+import { OtlpHeadersFromString } from "@t3tools/shared/observability";
import * as Config from "effect/Config";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Option from "effect/Option";
@@ -48,6 +49,7 @@ export const DesktopConfig = Config.all({
otlpExportIntervalMs: Config.int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe(
Config.withDefault(10_000),
),
+ otlpHeaders: Config.schema(OtlpHeadersFromString, "T3CODE_OTLP_HEADERS").pipe(Config.option),
appImagePath: trimmedString("APPIMAGE"),
disableAutoUpdate: optionalBoolean("T3CODE_DISABLE_AUTO_UPDATE"),
mockUpdates: optionalBoolean("T3CODE_DESKTOP_MOCK_UPDATES"),
diff --git a/apps/desktop/src/app/DesktopEnvironment.test.ts b/apps/desktop/src/app/DesktopEnvironment.test.ts
index 1ebd5dae56c..e34ae0b00a1 100644
--- a/apps/desktop/src/app/DesktopEnvironment.test.ts
+++ b/apps/desktop/src/app/DesktopEnvironment.test.ts
@@ -52,6 +52,7 @@ describe("DesktopEnvironment", () => {
T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH: " /remote/server.mjs ",
T3CODE_OTLP_TRACES_URL: " http://127.0.0.1:4318/v1/traces ",
T3CODE_OTLP_EXPORT_INTERVAL_MS: "2500",
+ T3CODE_OTLP_HEADERS: "authorization=Basic%20abc%3D%3D,x-tenant=t3",
},
);
@@ -85,6 +86,13 @@ describe("DesktopEnvironment", () => {
assert.deepEqual(environment.commitHashOverride, Option.some("0123456789abcdef"));
assert.deepEqual(environment.otlpTracesUrl, Option.some("http://127.0.0.1:4318/v1/traces"));
assert.equal(environment.otlpExportIntervalMs, 2500);
+ assert.deepEqual(
+ environment.otlpHeaders,
+ Option.some({
+ authorization: "Basic abc==",
+ "x-tenant": "t3",
+ }),
+ );
}),
);
diff --git a/apps/desktop/src/app/DesktopEnvironment.ts b/apps/desktop/src/app/DesktopEnvironment.ts
index e604cb767f3..f5cfbc0e7cb 100644
--- a/apps/desktop/src/app/DesktopEnvironment.ts
+++ b/apps/desktop/src/app/DesktopEnvironment.ts
@@ -72,6 +72,7 @@ export class DesktopEnvironment extends Context.Service<
readonly commitHashOverride: Option.Option<string>;
readonly otlpTracesUrl: Option.Option<string>;
readonly otlpExportIntervalMs: number;
+ readonly otlpHeaders: Option.Option<Record<string, string>>;
readonly branding: DesktopAppBranding;
readonly displayName: string;
readonly appUserModelId: string;
@@ -225,6 +226,7 @@ const make = Effect.fn("desktop.environment.make")(function* (
commitHashOverride: config.commitHashOverride,
otlpTracesUrl: config.otlpTracesUrl,
otlpExportIntervalMs: config.otlpExportIntervalMs,
+ otlpHeaders: config.otlpHeaders,
branding,
displayName,
appUserModelId: Option.getOrElse(config.appUserModelIdOverride, () =>
diff --git a/apps/desktop/src/app/DesktopObservability.ts b/apps/desktop/src/app/DesktopObservability.ts
index d2ff0b4e2ad..4f9b18d7396 100644
--- a/apps/desktop/src/app/DesktopObservability.ts
+++ b/apps/desktop/src/app/DesktopObservability.ts
@@ -584,6 +584,7 @@ const tracerLayer = Layer.unwrap(
: yield* OtlpTracer.make({
url: otlpTracesUrl.value,
exportInterval: `${environment.otlpExportIntervalMs} millis`,
+ headers: Option.getOrUndefined(environment.otlpHeaders),
resource: {
serviceName: "desktop",
attributes: {
diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
index edc71973491..2994c9e2d31 100644
--- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
@@ -853,10 +853,12 @@ describe("DesktopBackendConfiguration", () => {
const previousWslEnv = process.env.WSLENV;
const previousOpenAiKey = process.env.OPENAI_API_KEY;
const previousAnthropicKey = process.env.ANTHROPIC_API_KEY;
+ const previousOtlpHeaders = process.env.T3CODE_OTLP_HEADERS;
try {
process.env.WSLENV = "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u";
process.env.OPENAI_API_KEY = "openai-key";
process.env.ANTHROPIC_API_KEY = "anthropic-key";
+ process.env.T3CODE_OTLP_HEADERS = 'authorization="Bearer%20my-token"';
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
@@ -882,7 +884,7 @@ describe("DesktopBackendConfiguration", () => {
// already declared, so it isn't forwarded twice.
assert.equal(
config.env.WSLENV,
- "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY",
+ "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY:T3CODE_OTLP_HEADERS",
);
}).pipe(
Effect.provide(
@@ -905,6 +907,7 @@ describe("DesktopBackendConfiguration", () => {
restoreEnv("WSLENV", previousWslEnv);
restoreEnv("OPENAI_API_KEY", previousOpenAiKey);
restoreEnv("ANTHROPIC_API_KEY", previousAnthropicKey);
+ restoreEnv("T3CODE_OTLP_HEADERS", previousOtlpHeaders);
}
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts
index 09014add865..531557d1dac 100644
--- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts
+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts
@@ -91,7 +91,11 @@ const DESKTOP_BACKEND_ENV_NAMES = [
// forward across the wsl.exe boundary without WSLENV. The dev-server URL is
// handled separately via a `--dev-url` CLI flag because WSLENV translation of
// URL-shaped values (colons / slashes) is unreliable.
-const WSL_FORWARDED_ENV_NAMES = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY"] as const;
+const WSL_FORWARDED_ENV_NAMES = [
+ "OPENAI_API_KEY",
+ "ANTHROPIC_API_KEY",
+ "T3CODE_OTLP_HEADERS",
+] as const;
const WSL_SERVER_SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
diff --git a/apps/server/src/bin.test.ts b/apps/server/src/bin.test.ts
index e1a13d4ce8e..f1e1e3d8d73 100644
--- a/apps/server/src/bin.test.ts
+++ b/apps/server/src/bin.test.ts
@@ -101,6 +101,7 @@ const makeCliTestServerConfig = (baseDir: string) =>
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
+ otlpHeaders: undefined,
mode: "web",
port: 0,
host: "127.0.0.1",
diff --git a/apps/server/src/cli/config.test.ts b/apps/server/src/cli/config.test.ts
index 0c28bce28ae..f68142168bc 100644
--- a/apps/server/src/cli/config.test.ts
+++ b/apps/server/src/cli/config.test.ts
@@ -52,6 +52,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
+ otlpHeaders: undefined,
devAllowedOrigins: [],
} as const;
@@ -719,4 +720,92 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
});
}),
);
+
+ it.effect("decodes percent-encoded OTLP headers from env", () =>
+ Effect.gen(function* () {
+ const { join } = yield* Path.Path;
+ const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-otlp-headers-base");
+
+ const resolved = yield* resolveServerConfig(
+ {
+ mode: Option.some("web"),
+ port: Option.some(3773),
+ host: Option.none(),
+ baseDir: Option.some(baseDir),
+ cwd: Option.none(),
+ devUrl: Option.none(),
+ noBrowser: Option.none(),
+ bootstrapFd: Option.none(),
+ autoBootstrapProjectFromCwd: Option.none(),
+ logWebSocketEvents: Option.none(),
+ tailscaleServeEnabled: Option.none(),
+ tailscaleServePort: Option.none(),
+ },
+ Option.none(),
+ ).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ ConfigProvider.layer(
+ ConfigProvider.fromEnv({
+ env: {
+ T3CODE_OTLP_HEADERS: "authorization=Basic%20abc%3D%3D,x-tenant=t3",
+ },
+ }),
+ ),
+ NetService.layer,
+ ),
+ ),
+ );
+
+ expect(resolved.otlpHeaders).toEqual({
+ authorization: "Basic abc==",
+ "x-tenant": "t3",
+ });
+ }),
+ );
+
+ it.effect("keeps whitespace-separated pairs and literal equals signs in OTLP headers", () =>
+ Effect.gen(function* () {
+ const { join } = yield* Path.Path;
+ const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-otlp-headers-loose-base");
+
+ const resolved = yield* resolveServerConfig(
+ {
+ mode: Option.some("web"),
+ port: Option.some(3773),
+ host: Option.none(),
+ baseDir: Option.some(baseDir),
+ cwd: Option.none(),
+ devUrl: Option.none(),
+ noBrowser: Option.none(),
+ bootstrapFd: Option.none(),
+ autoBootstrapProjectFromCwd: Option.none(),
+ logWebSocketEvents: Option.none(),
+ tailscaleServeEnabled: Option.none(),
+ tailscaleServePort: Option.none(),
+ },
+ Option.none(),
+ ).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ ConfigProvider.layer(
+ ConfigProvider.fromEnv({
+ env: {
+ T3CODE_OTLP_HEADERS: "authorization=Bearer abc==, x-tenant=t3",
+ T3CODE_OTLP_TRACES_URL: "http://collector.internal:4318",
+ },
+ }),
+ ),
+ NetService.layer,
+ ),
+ ),
+ );
+
+ expect(resolved.otlpHeaders).toEqual({
+ authorization: "Bearer abc==",
+ "x-tenant": "t3",
+ });
+ expect(resolved.otlpTracesUrl).toBe("http://collector.internal:4318");
+ }),
+ );
});
diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts
index 1759b4b0383..4881b76ce94 100644
--- a/apps/server/src/cli/config.ts
+++ b/apps/server/src/cli/config.ts
@@ -1,4 +1,5 @@
import * as NetService from "@t3tools/shared/Net";
+import { OtlpHeadersFromString } from "@t3tools/shared/observability";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import { DesktopBackendBootstrap, PortSchema } from "@t3tools/contracts";
import * as Config from "effect/Config";
@@ -99,6 +100,10 @@ const EnvServerConfig = Config.all({
Config.withDefault(10_000),
),
otlpServiceName: Config.string("T3CODE_OTLP_SERVICE_NAME").pipe(Config.withDefault("t3-server")),
+ otlpHeaders: Config.schema(OtlpHeadersFromString, "T3CODE_OTLP_HEADERS").pipe(
+ Config.option,
+ Config.map(Option.getOrUndefined),
+ ),
mode: Config.schema(ServerConfig.RuntimeMode, "T3CODE_MODE").pipe(
Config.option,
Config.map(Option.getOrUndefined),
@@ -387,6 +392,7 @@ export const resolveServerConfig = (
persistedObservabilitySettings.otlpMetricsUrl,
otlpExportIntervalMs: env.otlpExportIntervalMs,
otlpServiceName: env.otlpServiceName,
+ otlpHeaders: env.otlpHeaders,
mode,
port,
cwd,
diff --git a/apps/server/src/cli/pair.ts b/apps/server/src/cli/pair.ts
index 7fd376c6f88..353fc9ad598 100644
--- a/apps/server/src/cli/pair.ts
+++ b/apps/server/src/cli/pair.ts
@@ -322,6 +322,7 @@ const makePairServerConfig = Effect.fn(function* (input: {
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
+ otlpHeaders: undefined,
mode: "web",
port: state.port,
host: state.host,
diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts
index b0544ef30ae..2f6c522d962 100644
--- a/apps/server/src/config.ts
+++ b/apps/server/src/config.ts
@@ -73,6 +73,7 @@ export class ServerConfig extends Context.Service<
readonly otlpMetricsUrl: string | undefined;
readonly otlpExportIntervalMs: number;
readonly otlpServiceName: string;
+ readonly otlpHeaders: Readonly<Record<string, string>> | undefined;
readonly mode: RuntimeMode;
readonly port: number;
readonly host: string | undefined;
@@ -197,6 +198,7 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
+ otlpHeaders: undefined,
cwd,
baseDir,
...derivedPaths,
diff --git a/apps/server/src/environment/ServerEnvironment.test.ts b/apps/server/src/environment/ServerEnvironment.test.ts
index a12a8242b0d..2f39e7832e4 100644
--- a/apps/server/src/environment/ServerEnvironment.test.ts
+++ b/apps/server/src/environment/ServerEnvironment.test.ts
@@ -54,6 +54,7 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
+ otlpHeaders: undefined,
cwd: process.cwd(),
baseDir,
mode: "web",
diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts
index 4d2dac73542..37494cb60ad 100644
--- a/apps/server/src/http.ts
+++ b/apps/server/src/http.ts
@@ -319,6 +319,7 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(
const request = yield* HttpServerRequest.HttpServerRequest;
const config = yield* ServerConfig.ServerConfig;
const otlpTracesUrl = config.otlpTracesUrl;
+ const otlpHeaders = config.otlpHeaders;
const browserTraceCollector = yield* BrowserTraceCollector.BrowserTraceCollector;
const httpClient = yield* HttpClient.HttpClient;
const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);
@@ -343,6 +344,7 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(
return yield* httpClient
.post(otlpTracesUrl, {
body: HttpBody.jsonUnsafe(bodyJson),
+ headers: otlpHeaders,
})
.pipe(
Effect.flatMap(HttpClientResponse.filterStatusOk),
diff --git a/apps/server/src/observability/Layers/Observability.ts b/apps/server/src/observability/Layers/Observability.ts
index 8aac0927534..9250d231dfb 100644
--- a/apps/server/src/observability/Layers/Observability.ts
+++ b/apps/server/src/observability/Layers/Observability.ts
@@ -49,6 +49,7 @@ export const ObservabilityLive = Layer.unwrap(
: yield* OtlpTracer.make({
url: config.otlpTracesUrl,
exportInterval: `${config.otlpExportIntervalMs} millis`,
+ headers: config.otlpHeaders,
resource: {
serviceName: config.otlpServiceName,
attributes: {
@@ -80,6 +81,7 @@ export const ObservabilityLive = Layer.unwrap(
: OtlpMetrics.layer({
url: config.otlpMetricsUrl,
exportInterval: `${config.otlpExportIntervalMs} millis`,
+ headers: config.otlpHeaders,
resource: {
serviceName: config.otlpServiceName,
attributes: {
diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts
index 3eb40a1b990..d842cd3d4d2 100644
--- a/apps/server/src/server.test.ts
+++ b/apps/server/src/server.test.ts
@@ -576,6 +576,7 @@ const buildAppUnderTest = (options?: {
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
+ otlpHeaders: undefined,
mode: "desktop",
port: 0,
host: "127.0.0.1",
diff --git a/docs/operations/observability.md b/docs/operations/observability.md
index 966eab112c6..287520459c6 100644
--- a/docs/operations/observability.md
+++ b/docs/operations/observability.md
@@ -528,6 +528,8 @@ OTLP export:
- `T3CODE_OTLP_METRICS_URL`: OTLP metric endpoint
- `T3CODE_OTLP_EXPORT_INTERVAL_MS`: export interval, default `10000`
- `T3CODE_OTLP_SERVICE_NAME`: service name, default `t3-server`
+- `T3CODE_OTLP_HEADERS`: extra headers for both exporters, same format as
+ `OTEL_EXPORTER_OTLP_HEADERS`: comma-separated `key=value` pairs with percent-encoded values.
If the OTLP URLs are unset, local tracing still works and metrics stay in-process only.
diff --git a/packages/shared/src/observability.test.ts b/packages/shared/src/observability.test.ts
index c58395393d3..081291f34b8 100644
--- a/packages/shared/src/observability.test.ts
+++ b/packages/shared/src/observability.test.ts
@@ -1,4 +1,4 @@
-import { assert, describe, it } from "@effect/vitest";
+import { assert, describe, expect, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Arr from "effect/Array";
import * as Cause from "effect/Cause";
@@ -21,6 +21,7 @@ import {
makeTraceSink,
type TraceRecord,
type TraceSinkFlushStats,
+ OtlpHeadersFromString,
truncateTraceAttributes,
} from "./observability.ts";
@@ -459,3 +460,40 @@ describe("observability", () => {
);
});
});
+
+describe("OtlpHeadersFromString", () => {
+ const decode = Schema.decodeUnknownSync(OtlpHeadersFromString);
+
+ it.each([
+ {
+ name: "decodes percent-encoded values",
+ input: "authorization=Basic%20abc%3D%3D,x-tenant=t3",
+ expected: { authorization: "Basic abc==", "x-tenant": "t3" },
+ },
+ {
+ name: "ignores whitespace around separators",
+ input: "authorization=Basic%20abc%3D%3D, x-tenant = t3 ,",
+ expected: { authorization: "Basic abc==", "x-tenant": "t3" },
+ },
+ {
+ name: "keeps literal equals signs inside a value",
+ input: "authorization=Bearer abc==",
+ expected: { authorization: "Bearer abc==" },
+ },
+ {
+ name: "keeps an empty value",
+ input: "x-empty=",
+ expected: { "x-empty": "" },
+ },
+ ])("$name", ({ input, expected }) => {
+ expect(decode(input)).toEqual(expected);
+ });
+
+ it.each([
+ { name: "rejects a pair without a separator", input: "authorization" },
+ { name: "rejects a pair without a key", input: "=value" },
+ { name: "rejects a malformed percent-encoding", input: "authorization=%E0" },
+ ])("$name", ({ input }) => {
+ expect(() => decode(input)).toThrow();
+ });
+});
diff --git a/packages/shared/src/observability.ts b/packages/shared/src/observability.ts
index 9692a05f759..b17ee253a78 100644
--- a/packages/shared/src/observability.ts
+++ b/packages/shared/src/observability.ts
@@ -3,6 +3,9 @@ import * as Effect from "effect/Effect";
import type * as Exit from "effect/Exit";
import * as ExitRuntime from "effect/Exit";
import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
+import * as SchemaIssue from "effect/SchemaIssue";
+import * as SchemaTransformation from "effect/SchemaTransformation";
import * as Tracer from "effect/Tracer";
import { OtlpResource, OtlpTracer } from "effect/unstable/observability";
@@ -683,3 +686,51 @@ function parseBigInt(input: string): bigint {
return 0n;
}
}
+
+/**
+ * Parses the `OTEL_EXPORTER_OTLP_HEADERS` wire format used by
+ * `T3CODE_OTLP_HEADERS`: W3C Baggage `key=value` pairs joined by commas, with
+ * percent-encoded values. Each pair splits at its first `=` so an encoded or
+ * literal `=` inside a value survives, and whitespace around the separators is
+ * ignored.
+ */
+export const OtlpHeadersFromString = Schema.String.pipe(
+ Schema.decodeTo(
+ Schema.Record(Schema.String, Schema.String),
+ SchemaTransformation.transformOrFail({
+ decode: (input) => {
+ const headers: Record<string, string> = {};
+ for (const pair of input.split(",")) {
+ if (pair.trim() === "") {
+ continue;
+ }
+ const separator = pair.indexOf("=");
+ const key = separator === -1 ? "" : pair.slice(0, separator).trim();
+ if (key === "") {
+ return Effect.fail(
+ new SchemaIssue.InvalidValue({
+ message: `Expected key=value but received ${JSON.stringify(pair.trim())}.`,
+ }),
+ );
+ }
+ try {
+ headers[key] = decodeURIComponent(pair.slice(separator + 1).trim());
+ } catch {
+ return Effect.fail(
+ new SchemaIssue.InvalidValue({
+ message: `Header ${JSON.stringify(key)} has a malformed percent-encoded value.`,
+ }),
+ );
+ }
+ }
+ return Effect.succeed(headers);
+ },
+ encode: (headers) =>
+ Effect.succeed(
+ Object.entries(headers)
+ .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
+ .join(","),
+ ),
+ }),
+ ),
+);