The open-source agent harness - the runtime layer that turns an LLM into a working agent.
add mtls for controller and server communication (#589)
Sujai Kumar Gupta49164e795568
diff --git a/.changeset/controller-server-mtls.md b/.changeset/controller-server-mtls.mdnew file mode 100644index 000000000..e4015d966--- /dev/null+++ b/.changeset/controller-server-mtls.md@@ -0,0 +1,5 @@+---+"@truefoundry/trueforge": minor+---++Add optional mutual TLS for the HTTPS listener and schedule controller→server hop via `TRUEFORGE_MTLS_ENABLED` / `TRUEFORGE_MTLS_CERTS_DIR`. Off by default; independent of ServiceFoundry `TRUEFOUNDRY_MTLS_*`.diff --git a/charts/trueforge/README.md b/charts/trueforge/README.mdindex 129d09abe..d1122ead7 100644--- a/charts/trueforge/README.md+++ b/charts/trueforge/README.md@@ -211,6 +211,9 @@ extraObjects:| `podSecurityContext` | non-root UID/GID `10001` | Pod-level restricted security defaults. || `securityContext` | read-only root FS + drop all capabilities | Container-level restricted security defaults. || `resources` | 100m/256Mi requests, 200m/512Mi limits | Container CPU, memory, and ephemeral-storage requests/limits. |+| `mtls.enabled` | `false` | HTTPS listener + controller→server mTLS (`TRUEFORGE_MTLS_*`). When true, probes use `scheme: HTTPS`. |+| `mtls.secretName` | `""` | Secret with `tls.crt` / `tls.key` / `ca.crt` (required when `mtls.enabled`). |+| `mtls.certsDir` | `/etc/tls` | Mount path / `TRUEFORGE_MTLS_CERTS_DIR`. |The server uses a RollingUpdate strategy by default (`server.strategy`); thecontroller is fixed to a single replica with `Recreate` and exposes neither.@@ -232,6 +235,7 @@ also sets the `/tmp` `emptyDir.sizeLimit`.- Set `server.publicBaseUrl` to the real public origin before using MCP OAuth or OIDC.- Prefer `valueFrom.secretKeyRef` for Postgres password, Redis URL, and OIDC client secret; do not commit secrets in values files.- Prefer external managed Postgres/Redis over the bundled subcharts for production HA.+- If enabling `mtls`, set `mtls.secretName` and ensure any reverse proxy dials HTTPS with a trusted client cert (see Caddy `internal_mtls`).- Tune container `resources` (especially CPU requests) before enabling HPA.- Default `tfy.jfrog.io` images and the Helm chart are anonymously pullable — set `imagePullSecrets` only if you override to a private registry.- Enable `podDisruptionBudget` when running multiple replicas (defaults to `minAvailable: 1`; set exactly one of `minAvailable` or `maxUnavailable`).diff --git a/charts/trueforge/templates/_helpers.tpl b/charts/trueforge/templates/_helpers.tplindex eee2de050..c7817bc12 100644--- a/charts/trueforge/templates/_helpers.tpl+++ b/charts/trueforge/templates/_helpers.tpl@@ -231,5 +231,46 @@ fields, wires bundled Postgres/Redis, optional OIDC, then server.extraEnv.{{- $env = append $env . -}}{{- end -}}+{{- if .Values.mtls.enabled -}}+{{- $_ := required "mtls.secretName is required when mtls.enabled is true" .Values.mtls.secretName -}}+{{- $env = append $env (dict "name" "TRUEFORGE_MTLS_ENABLED" "value" "true") -}}+{{- $env = append $env (dict "name" "TRUEFORGE_MTLS_CERTS_DIR" "value" .Values.mtls.certsDir) -}}+{{- end -}}+{{- toYaml $env -}}{{- end }}++{{/*+httpGet probe with scheme HTTPS when mtls.enabled (kubelet speaks TLS without a client cert).+Expects dict: probe (values probe object), root (chart root context).+*/}}+{{- define "trueforge.httpProbe" -}}+{{- $probe := deepCopy (index . "probe") -}}+{{- $root := index . "root" -}}+{{- if and $root.Values.mtls.enabled $probe.httpGet -}}+{{- $_ := set $probe.httpGet "scheme" "HTTPS" -}}+{{- end -}}+{{- toYaml $probe -}}+{{- end }}++{{/*+mTLS secret volume when mtls.enabled.+*/}}+{{- define "trueforge.mtlsVolume" -}}+{{- if .Values.mtls.enabled -}}+- name: mtls+ secret:+ secretName: {{ .Values.mtls.secretName | quote }}+{{- end -}}+{{- end }}++{{/*+mTLS secret volumeMount when mtls.enabled.+*/}}+{{- define "trueforge.mtlsVolumeMount" -}}+{{- if .Values.mtls.enabled -}}+- name: mtls+ mountPath: {{ .Values.mtls.certsDir | quote }}+ readOnly: true+{{- end -}}+{{- end }}diff --git a/charts/trueforge/templates/controller-deployment.yaml b/charts/trueforge/templates/controller-deployment.yamlindex d0f59ab0a..3e74dcdd1 100644--- a/charts/trueforge/templates/controller-deployment.yaml+++ b/charts/trueforge/templates/controller-deployment.yaml@@ -64,6 +64,7 @@ spec:volumeMounts:- name: tmpmountPath: /tmp+ {{- include "trueforge.mtlsVolumeMount" . | nindent 12 }}{{- with .Values.extraVolumeMounts }}{{- toYaml . | nindent 12 }}{{- end }}@@ -77,6 +78,7 @@ spec:{{- else }}emptyDir: {}{{- end }}+ {{- include "trueforge.mtlsVolume" . | nindent 8 }}{{- with .Values.extraVolumes }}{{- toYaml . | nindent 8 }}{{- end }}diff --git a/charts/trueforge/templates/deployment.yaml b/charts/trueforge/templates/deployment.yamlindex d749fd3f0..6b98e060a 100644--- a/charts/trueforge/templates/deployment.yaml+++ b/charts/trueforge/templates/deployment.yaml@@ -61,15 +61,15 @@ spec:{{- include "trueforge.server.env" . | nindent 12 }}{{- with .Values.startupProbe }}startupProbe:- {{- toYaml . | nindent 12 }}+ {{- include "trueforge.httpProbe" (dict "probe" . "root" $) | nindent 12 }}{{- end }}{{- with .Values.livenessProbe }}livenessProbe:- {{- toYaml . | nindent 12 }}+ {{- include "trueforge.httpProbe" (dict "probe" . "root" $) | nindent 12 }}{{- end }}{{- with .Values.readinessProbe }}readinessProbe:- {{- toYaml . | nindent 12 }}+ {{- include "trueforge.httpProbe" (dict "probe" . "root" $) | nindent 12 }}{{- end }}{{- with .Values.resources }}resources:@@ -78,6 +78,7 @@ spec:volumeMounts:- name: tmpmountPath: /tmp+ {{- include "trueforge.mtlsVolumeMount" . | nindent 12 }}{{- with .Values.extraVolumeMounts }}{{- toYaml . | nindent 12 }}{{- end }}@@ -94,6 +95,7 @@ spec:{{- else }}emptyDir: {}{{- end }}+ {{- include "trueforge.mtlsVolume" . | nindent 8 }}{{- with .Values.extraVolumes }}{{- toYaml . | nindent 8 }}{{- end }}diff --git a/charts/trueforge/values.yaml b/charts/trueforge/values.yamlindex 74c4d061d..d8a34182b 100644--- a/charts/trueforge/values.yaml+++ b/charts/trueforge/values.yaml@@ -227,6 +227,13 @@ resources:cpu: 200mmemory: 512Miephemeral-storage: 512Mi+# Mutual TLS for the server HTTPS listener and controller→server hop.+# When enabled, chart probes use scheme HTTPS (same pattern as deltafusion-ingestor).+# Secret must contain tls.crt / tls.key / ca.crt (e.g. truefoundry-internal-tls).+mtls:+ enabled: false+ secretName: ""+ certsDir: /etc/tls# startupProbe runs until success before liveness/readiness; sized for migrate + Redis connect.startupProbe:httpGet:diff --git a/packages/trueforge/.env.example b/packages/trueforge/.env.exampleindex 5f6198325..3d97eafca 100644--- a/packages/trueforge/.env.example+++ b/packages/trueforge/.env.example@@ -32,6 +32,12 @@ PORT=8790## Max ms for ServiceFoundry agent create/update/delete calls. Default 3000.# TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS=3000+## Mutual TLS for this process's HTTPS listener and controller→server. Off by default (plain HTTP).+## When true, serves HTTPS with client-cert enforcement (except /healthz) and the controller+## presents tls.crt/tls.key from TRUEFORGE_MTLS_CERTS_DIR. Chart probes must use scheme HTTPS.+# TRUEFORGE_MTLS_ENABLED=false+# TRUEFORGE_MTLS_CERTS_DIR=/etc/tls+## Internal mutual TLS for calls to the ServiceFoundry server. When true, trueforge presents its client## certificate (and upgrades a mesh-direct http:// peer URL to https://). Only meaningful in-cluster,## where TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL points at the ServiceFoundry server Service directly.diff --git a/packages/trueforge/src/app.ts b/packages/trueforge/src/app.tsindex be537c5fb..e3a6b7ffd 100644--- a/packages/trueforge/src/app.ts+++ b/packages/trueforge/src/app.ts@@ -40,6 +40,7 @@ import type { IScheduleStore } from './db/scheduleStore';import type { ISessionMetricsStore } from './db/sessionMetricsStore';import type { ISkillStore } from './db/skillStore';import type { WithTransaction } from './db/transaction';+import { createClientCertificateMiddleware } from './http/tls';import type { IOAuthTokenStore } from './mcp/auth/types';import { PACKAGE_VERSION } from './packageVersion';import { OPENAPI_DOCUMENT_TAGS } from './routes/openapiTags';@@ -213,6 +214,9 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {if (configuration.ACCESS_LOGS) {app.use('*', createAccessLogMiddleware(deps.logger));}+ if (!configuration.STANDALONE && configuration.TRUEFORGE_MTLS_ENABLED) {+ app.use('*', createClientCertificateMiddleware(deps.logger));+ }app.use('*', createRequestBodyLimitMiddleware(configuration.MAX_REQUEST_BODY_BYTES));app.get('/healthz', c => c.json({ status: 'ok', version: PACKAGE_VERSION }));diff --git a/packages/trueforge/src/config.ts b/packages/trueforge/src/config.tsindex b156c53e6..0c87a9579 100644--- a/packages/trueforge/src/config.ts+++ b/packages/trueforge/src/config.ts@@ -478,11 +478,24 @@ export interface SharedServerConfiguration {/*** Base URL the controller uses to reach the server's HTTP API when it runs as its* own process (`STANDALONE=false`, `dist/controller-main.js`). The control loops call- * the server over HTTP. Env: `SERVER_URL`. Default: `http://localhost:$PORT`,- * so in-cluster deployments MUST point this at the server Service. Unused in standalone- * mode, where the server process owns the controller and targets itself on localhost.+ * the server over HTTP(S); when `TRUEFORGE_MTLS_ENABLED` is true the controller upgrades an+ * `http://` URL to `https://` and presents the client cert. Env: `SERVER_URL`.+ * Default: `http://localhost:$PORT`, so in-cluster deployments MUST point this at+ * the server Service. Unused in standalone mode, where the server process owns the+ * controller and targets itself on localhost.*/SERVER_URL: string;+ /**+ * Mutual TLS for this process's HTTPS listener and controller→server. When true, serves HTTPS+ * with client-cert enforcement (except `/healthz`) and the controller presents a client cert.+ * Env: `TRUEFORGE_MTLS_ENABLED`. Default false.+ */+ TRUEFORGE_MTLS_ENABLED: boolean;+ /**+ * Directory holding the TLS cert triple (`tls.crt` / `tls.key` / `ca.crt`) when+ * `TRUEFORGE_MTLS_ENABLED` is true. Env: `TRUEFORGE_MTLS_CERTS_DIR`. Default `/etc/tls`.+ */+ TRUEFORGE_MTLS_CERTS_DIR: string;/*** When set, models are listed from the TrueFoundry ServiceFoundry server and invoked* via the AI Gateway with the caller's token. Unset = local model-provider store.@@ -667,6 +680,12 @@ const shared: SharedServerConfiguration = {PUBLIC_BASE_URL: getEnv('PUBLIC_BASE_URL', { defaultValue: '' }) ?? '',SERVER_URL:getEnv('SERVER_URL', { defaultValue: `http://localhost:${String(port)}` }) ?? `http://localhost:${String(port)}`,+ TRUEFORGE_MTLS_ENABLED: parseBoolean({+ envKey: 'TRUEFORGE_MTLS_ENABLED',+ raw: getEnv('TRUEFORGE_MTLS_ENABLED'),+ defaultValue: false,+ }),+ TRUEFORGE_MTLS_CERTS_DIR: getEnv('TRUEFORGE_MTLS_CERTS_DIR', { defaultValue: '/etc/tls' }) ?? '/etc/tls',TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL: getEnv('TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL', { required: false }),TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS: parsePositiveInt({envKey: 'TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS',diff --git a/packages/trueforge/src/controller-main.ts b/packages/trueforge/src/controller-main.tsindex 63fd27aec..0fb07018e 100644--- a/packages/trueforge/src/controller-main.ts+++ b/packages/trueforge/src/controller-main.ts@@ -9,8 +9,8 @@** Migrations are owned by the server (`main.ts`). This process only connects to the* already-migrated database; the loops have per-pass error boundaries, so they retry- * each tick until the schema is present. The loops call the server over HTTP at- * `SERVER_URL`, so no Redis peering is wired here.+ * each tick until the schema is present. The loops call the server over HTTP(S) at+ * `SERVER_URL` (mutual TLS when `TRUEFORGE_MTLS_ENABLED`), so no Redis peering is wired here.*/import configuration from './config';import { runController } from './controller';@@ -41,8 +41,14 @@ try {idleInTransactionSessionTimeoutMs: configuration.POSTGRES_IDLE_IN_TRANSACTION_SESSION_TIMEOUT_MS,});+ const mtls = {+ enabled: configuration.TRUEFORGE_MTLS_ENABLED,+ dir: configuration.TRUEFORGE_MTLS_CERTS_DIR,+ };+logger.info('Controller starting', {serverUrl: configuration.SERVER_URL,+ mTlsEnabled: mtls.enabled,});runController({@@ -50,6 +56,7 @@ try {withTransaction: callback => db.transaction().execute(callback),logger,baseUrl: configuration.SERVER_URL,+ tls: mtls,gracefulTimeoutSeconds: configuration.GRACEFUL_TIMEOUT_SECONDS,onStopped: () => db.destroy(),});diff --git a/packages/trueforge/src/controller.ts b/packages/trueforge/src/controller.tsindex 159e7bc66..68d210ec8 100644--- a/packages/trueforge/src/controller.ts+++ b/packages/trueforge/src/controller.ts@@ -4,6 +4,17 @@ import { Controller } from './controller/Controller';import { scheduleDispatchLoop } from './controller/scheduleDispatch';import type { IScheduleStore } from './db/scheduleStore';import type { WithTransaction } from './db/transaction';+import { createTlsFetch, normalizeTlsUrl, type TlsOptions } from './http/tls';++function createScheduleApiClient(params: { baseUrl: string; tls: TlsOptions }): TrueForge {+ const baseUrl = normalizeTlsUrl({ url: params.baseUrl, enabled: params.tls.enabled });+ const fetchImpl = createTlsFetch(params.tls);+ return new TrueForge({+ baseUrl,+ auth: false,+ ...(fetchImpl !== undefined ? { fetch: fetchImpl } : {}),+ });+}/*** The loops the controller runs.@@ -13,13 +24,15 @@ export function createController<TTransaction>(params: {withTransaction: WithTransaction<TTransaction>;logger: Logger;baseUrl: string;+ tls?: TlsOptions;}): Controller {const { scheduleStore, withTransaction, logger, baseUrl } = params;+ const tls = params.tls ?? { enabled: false, dir: '' };return new Controller({loops: [scheduleDispatchLoop({scheduleStore,- client: new TrueForge({ baseUrl, auth: false }),+ client: createScheduleApiClient({ baseUrl, tls }),withTransaction,logger,}),@@ -36,6 +49,7 @@ export function runController<TTransaction>(params: {withTransaction: WithTransaction<TTransaction>;logger: Logger;baseUrl: string;+ tls?: TlsOptions;gracefulTimeoutSeconds: number;/** Releases what the caller opened for the loops, e.g. its database pool. */onStopped?: () => Promise<void>;diff --git a/packages/trueforge/src/http/tls.ts b/packages/trueforge/src/http/tls.tsnew file mode 100644index 000000000..648547cfa--- /dev/null+++ b/packages/trueforge/src/http/tls.ts@@ -0,0 +1,140 @@+/**+ * Shared mutual-TLS helpers: outbound undici (controller → server, ServiceFoundry client) and+ * this process's HTTPS listener + client-cert middleware.+ *+ * Cert triple under the configured dir: `tls.crt` / `tls.key` / `ca.crt`.+ */+import type { HttpBindings } from '@hono/node-server';+import type { MiddlewareHandler } from 'hono';+import { readFileSync } from 'node:fs';+import { createServer as createHttpsServer, type ServerOptions as HttpsServerOptions } from 'node:https';+import { join } from 'node:path';+import { rootCertificates, TLSSocket } from 'node:tls';++import { Agent, fetch as undiciFetch, type Dispatcher } from 'undici';+import type { Logger } from 'winston';++const TLS_CERT_FILE = 'tls.crt';+const TLS_KEY_FILE = 'tls.key';+const TLS_CA_FILE = 'ca.crt';++export interface TlsOptions {+ enabled: boolean;+ dir: string;+}++function readTlsFile(input: { dir: string; fileName: string; enabledEnvKey: string }): string {+ const filePath = join(input.dir, input.fileName);+ try {+ return readFileSync(filePath, 'utf8');+ } catch (error) {+ throw new Error(+ `${input.enabledEnvKey} is true but ${filePath} could not be read. Check that the mTLS secret ` ++ `is mounted at the configured certs directory, or set ${input.enabledEnvKey}=false.`,+ { cause: error },+ );+ }+}++function isTlsSocket(socket: unknown): socket is TLSSocket {+ return socket instanceof TLSSocket;+}++/**+ * True when the peer presented a client certificate that our CA already verified.+ * Only meaningful when the listener was started with `requestCert: true`.+ */+export function hasAuthorizedClientCertificate(socket: unknown): boolean {+ return isTlsSocket(socket) && socket.authorized;+}++/** Upgrades http → https when mTLS is on. */+export function normalizeTlsUrl(input: { url: string; enabled: boolean }): string {+ if (!input.enabled) {+ return input.url;+ }+ const parsed = new URL(input.url);+ if (parsed.protocol === 'http:') {+ parsed.protocol = 'https:';+ }+ return parsed.href;+}++/** undici dispatcher presenting this process's client cert and trusting the CA (+ system roots). */+export function createTlsDispatcher(options: TlsOptions & { enabledEnvKey: string }): Dispatcher | undefined {+ if (!options.enabled) {+ return undefined;+ }+ const read = (fileName: string) => readTlsFile({ dir: options.dir, fileName, enabledEnvKey: options.enabledEnvKey });+ return new Agent({+ connect: {+ // Appended to the default roots, not replacing them: passing `ca` alone would override Node's+ // entire trust store for this dispatcher (breaks public HTTPS peers on the same agent).+ ca: [...rootCertificates, read(TLS_CA_FILE)],+ cert: read(TLS_CERT_FILE),+ key: read(TLS_KEY_FILE),+ },+ });+}++/** Resolves `fetch`'s first argument (`string | URL | Request`) to a URL string. */+function requestUrlFromFetchInput(input: Parameters<typeof fetch>[0]): string {+ if (typeof input === 'string') {+ return input;+ }+ if (input instanceof URL) {+ return input.href;+ }+ return input.url;+}++/** `fetch` for the schedule controller SDK client. Undefined when mTLS is off. */+export function createTlsFetch(options: TlsOptions): typeof fetch | undefined {+ const dispatcher = createTlsDispatcher({+ ...options,+ enabledEnvKey: 'TRUEFORGE_MTLS_ENABLED',+ });+ if (dispatcher === undefined) {+ return undefined;+ }+ // Casts bridge undici ↔ DOM fetch types (Fern only needs string URL + init + dispatcher).+ return (input, init) => undiciFetch(requestUrlFromFetchInput(input), { ...(init as object), dispatcher });+}++/** HTTPS `serve` options when mTLS is on; undefined → plain HTTP. */+export function serverTlsServeOptions(+ options: TlsOptions,+): { createServer: typeof createHttpsServer; serverOptions: HttpsServerOptions } | undefined {+ if (!options.enabled) {+ return undefined;+ }+ const read = (fileName: string) =>+ readTlsFile({ dir: options.dir, fileName, enabledEnvKey: 'TRUEFORGE_MTLS_ENABLED' });+ return {+ createServer: createHttpsServer,+ serverOptions: {+ key: Buffer.from(read(TLS_KEY_FILE)),+ cert: Buffer.from(read(TLS_CERT_FILE)),+ ca: Buffer.from(read(TLS_CA_FILE)),+ requestCert: true,+ // Do not reject at handshake so /healthz probes without a cert still connect.+ rejectUnauthorized: false,+ },+ };+}++/** Rejects certless requests except `/healthz`. Mount only when mTLS is enabled. */+export function createClientCertificateMiddleware(logger: Logger): MiddlewareHandler {+ return async (c, next) => {+ if (c.req.path === '/healthz') {+ await next();+ return;+ }+ if (hasAuthorizedClientCertificate((c.env as HttpBindings).incoming.socket)) {+ await next();+ return;+ }+ logger.warn('Rejected request without a valid client certificate', { path: c.req.path });+ return c.json({ error: { message: 'Client certificate required' } }, 403);+ };+}diff --git a/packages/trueforge/src/main.ts b/packages/trueforge/src/main.tsindex aab5f2be0..2c17cc5f2 100644--- a/packages/trueforge/src/main.ts+++ b/packages/trueforge/src/main.ts@@ -79,6 +79,7 @@ import type { ISkillStore } from './db/skillStore';import type { Database as SqliteDatabase } from './db/sqlite/types';import type { WithTransaction } from './db/transaction';import { mountFrontend } from './frontend';+import { serverTlsServeOptions } from './http/tls';import { createServerLogger, shouldColorize } from './logger';import type { IOAuthTokenStore } from './mcp/auth/types';import { PACKAGE_VERSION } from './packageVersion';@@ -534,11 +535,26 @@ try {await requestReplyExecutor.init();}- const server = serve({ fetch: app.fetch, port: configuration.PORT, hostname: configuration.HOST }, info => {- logger.info(`Agent server listening on http://${configuration.HOST}:${String(info.port)} (docs at /api/v1/docs)`);- // The controller calls this server over HTTP.- controller?.start();+ const tlsServe = serverTlsServeOptions({+ enabled: !configuration.STANDALONE && configuration.TRUEFORGE_MTLS_ENABLED,+ dir: configuration.TRUEFORGE_MTLS_CERTS_DIR,});+ const server = serve(+ {+ fetch: app.fetch,+ port: configuration.PORT,+ hostname: configuration.HOST,+ ...(tlsServe ?? {}),+ },+ info => {+ const scheme = tlsServe !== undefined ? 'https' : 'http';+ logger.info(+ `Agent server listening on ${scheme}://${configuration.HOST}:${String(info.port)} (docs at /api/v1/docs)`,+ );+ // The controller calls this server over HTTP(S).+ controller?.start();+ },+ );server.on('error', (error: unknown) => {console.error('Failed to start server:', error instanceof Error ? error.message : error);diff --git a/packages/trueforge/src/truefoundry/internalTls.ts b/packages/trueforge/src/truefoundry/internalTls.tsindex 260f910da..9119b7f81 100644--- a/packages/trueforge/src/truefoundry/internalTls.ts+++ b/packages/trueforge/src/truefoundry/internalTls.ts@@ -1,60 +1,22 @@/**- * Client-side (outbound) mutual TLS for calling the TrueFoundry ServiceFoundry server. The cert triple- * (`tls.crt` / `tls.key` / `ca.crt`) is mounted under `TRUEFOUNDRY_MTLS_CERTS_DIR`. The dispatcher is- * scoped to the ServiceFoundry server client, so the internal certificate is never presented to the- * external MCP servers or LLM providers trueforge also reaches over `fetch`.+ * Outbound mutual TLS for the ServiceFoundry server client. Certs under+ * `TRUEFOUNDRY_MTLS_CERTS_DIR`; reuses shared helpers in `http/tls.ts`.*/-import { readFileSync } from 'node:fs';-import { join } from 'node:path';-import { rootCertificates } from 'node:tls';+import type { Dispatcher } from 'undici';-import { Agent, type Dispatcher } from 'undici';+import { createTlsDispatcher, normalizeTlsUrl, type TlsOptions } from '../http/tls';-const TLS_CERT_FILE = 'tls.crt';-const TLS_KEY_FILE = 'tls.key';-const TLS_CA_FILE = 'ca.crt';--export interface InternalTlsOptions {- enabled: boolean;- dir: string;-}--function readTlsFile(input: { dir: string; fileName: string }): string {- const filePath = join(input.dir, input.fileName);- try {- return readFileSync(filePath, 'utf8');- } catch (error) {- throw new Error(- `TRUEFOUNDRY_MTLS_ENABLED is true but ${filePath} could not be read. Check that the mTLS secret ` +- 'is mounted at TRUEFOUNDRY_MTLS_CERTS_DIR, or set TRUEFOUNDRY_MTLS_ENABLED=false.',- { cause: error },- );- }-}+export type InternalTlsOptions = TlsOptions;/** Upgrades an internal peer URL from http to https when mTLS is on; no-op otherwise. */export function normalizeInternalTlsUrl(input: { url: string; enabled: boolean }): string {- if (!input.enabled) {- return input.url;- }- return input.url.startsWith('http://') ? `https://${input.url.slice('http://'.length)}` : input.url;+ return normalizeTlsUrl(input);}-/** undici dispatcher presenting this pod's client cert and trusting the internal CA, or `undefined` when TLS is off. */+/** undici dispatcher presenting this pod's client cert, or `undefined` when TLS is off. */export function createInternalTlsDispatcher(options: InternalTlsOptions): Dispatcher | undefined {- if (!options.enabled) {- return undefined;- }- const ca = readTlsFile({ dir: options.dir, fileName: TLS_CA_FILE });- const cert = readTlsFile({ dir: options.dir, fileName: TLS_CERT_FILE });- const key = readTlsFile({ dir: options.dir, fileName: TLS_KEY_FILE });- return new Agent({- connect: {- // Appended to the default roots, not replacing them: passing `ca` alone would override Node's- // entire trust store for this dispatcher, breaking verification of the public ServiceFoundry edge.- ca: [...rootCertificates, ca],- cert,- key,- },+ return createTlsDispatcher({+ ...options,+ enabledEnvKey: 'TRUEFOUNDRY_MTLS_ENABLED',});}