Explorar el Código

fix: honor MiniMax API custom authentication headers

Extend the approach proposed by basil-k-aji-dev in #195 to actual model resolution and SDK requests, with offline regression coverage. Based on the relay authentication report by tim-korso in #126.

Co-authored-by: basil-k-aji-dev <70605804+basil-k-aji-dev@users.noreply.github.com>
hetaoBackend hace 2 meses
padre
commit
1ed488cdf1

+ 12 - 0
docs/examples.md

@@ -66,6 +66,18 @@ pnpm mcode provider list --json
 
 `--api-key-env` reads the current environment variable value and stores that value in the active profile's `config.yaml`; it does not save an environment-variable reference. The file still contains plaintext credentials. On POSIX systems, config writes and temporary copies use `0600`. When loading existing files, MCode removes group/other access while preserving the owner's permissions; already-private files such as `0400` or `0600` do not require a permission change. Loading fails if an unsafe main config cannot be restricted. Older migration backups are also checked, but inspection or repair failures produce a warning identifying the directory or backup that needs manual attention rather than preventing the main config from loading. Windows file modes do not provide equivalent ACL protection; restrict access to the profile directory using Windows permissions.
 
+For a MiniMax API key routed through an Anthropic Messages-compatible relay, you can hand-edit the active profile's `config.yaml`:
+
+```yaml
+minimax_api:
+  apiKey: fixture-api-key
+  baseURL: https://relay.example/anthropic
+  headers:
+    Authorization: Bearer fixture-relay-key
+```
+
+Replace the synthetic credentials with the relay's credentials. `headers` applies to connection tests and actual MiniMax API conversations. Header names are case-insensitive: explicit `Authorization` suppresses the default `x-api-key`, while an explicitly configured `x-api-key` is preserved. Without header overrides, MiniMax API authentication remains unchanged. Header values are credentials; settings views expose names only, and editing headers invalidates cached connection results. This does not switch the provider to the OpenAI protocol or change mobile-channel model selection.
+
 [Live acceptance](verification.md) separately verified MiniMax Token Plan and one configured BYOK provider. This is not a guarantee for every compatible service.
 
 ## 3. Search and image input

+ 6 - 0
packages/config/src/byok-config.ts

@@ -23,6 +23,12 @@ export function parseMinimaxApiConfig(raw: unknown): MinimaxApiConfig | undefine
   const parsed: MinimaxApiConfig = {};
   if (typeof obj.apiKey === 'string') parsed.apiKey = obj.apiKey;
   if (typeof obj.baseURL === 'string') parsed.baseURL = obj.baseURL;
+  if (isPlainRecord(obj.headers)) {
+    const entries = Object.entries(obj.headers).filter(
+      (entry): entry is [string, string] => entry[0].length > 0 && typeof entry[1] === 'string',
+    );
+    if (entries.length > 0) parsed.headers = Object.fromEntries(entries);
+  }
   const modelContextLimits = parseModelContextLimits(obj.modelContextLimits);
   if (modelContextLimits) parsed.modelContextLimits = modelContextLimits;
   return Object.keys(parsed).length > 0 ? parsed : undefined;

+ 2 - 0
packages/config/src/config.ts

@@ -1159,6 +1159,8 @@ export interface MinimaxApiConfig {
   apiKey?: string;
   /** Optional endpoint override; defaults to the runtime's builtin MiniMax API endpoint. */
   baseURL?: string;
+  /** Hand-edited request headers; values may contain credentials and must not be displayed. */
+  headers?: Record<string, string>;
   /** User-owned context selections applied only to the independent MiniMax API catalog. */
   modelContextLimits?: Record<string, number>;
 }

+ 1 - 0
packages/local-runtime-v2/src/service/model-system/catalog/config-fingerprint.ts

@@ -47,6 +47,7 @@ function minimaxModelTestStatus(
       baseUrl: normalizeProviderBaseUrl('anthropic-messages', minimaxApiBaseUrl(config)),
       apiKey,
       modelId,
+      ...(config.minimax_api?.headers ? { headers: config.minimax_api.headers } : {}),
     },
     model,
   );

+ 20 - 9
packages/local-runtime-v2/src/service/model-system/catalog/provider-views.ts

@@ -16,7 +16,7 @@ import type {
   ModelProviderSource,
   ModelProviderView,
 } from '../contracts.js';
-import { modelConnectionTestFingerprint } from './config-fingerprint.js';
+import { byokModelTestStatus, modelConnectionTestFingerprint } from './config-fingerprint.js';
 import {
   MINIMAX_API_FORMAT,
   MINIMAX_API_PROVIDER_NAME,
@@ -92,6 +92,9 @@ export function buildMinimaxProviderView(
     enabled: true,
     baseUrl: minimaxApiBaseUrl(config),
     apiFormat: MINIMAX_API_FORMAT,
+    ...(config.minimax_api?.headers
+      ? { headerNames: Object.keys(config.minimax_api.headers).sort() }
+      : {}),
     hasApiKey: Boolean(apiKey),
     ...(apiKey ? { maskedApiKey: maskSecret(apiKey) } : {}),
     models: providerModelEntries(config, cache, {
@@ -100,8 +103,10 @@ export function buildMinimaxProviderView(
       providerSource: 'minimax_api',
       providerKind: 'minimax-api-key',
       providerName: MINIMAX_API_PROVIDER_NAME,
+      statusForModel: (modelId) =>
+        byokModelTestStatus(config, cache, MINIMAX_API_PROVIDER_ID, modelId),
     }),
-    ...(statusOf(cache, MINIMAX_API_PROVIDER_ID) ?? {}),
+    ...(minimaxProviderStatus(config, cache) ?? {}),
   };
 }
 
@@ -228,14 +233,20 @@ function customModelFingerprint(
   );
 }
 
-// Unvalidated read, reserved for the MiniMax API view returned straight after a
-// key write. The badge the settings UI renders comes from
-// `getMinimaxApiKeyStatus`, which does check the fingerprint. BYOK provider
-// views must use `fingerprintedProviderStatus` instead.
-function statusOf(
+// Provider tests use the first catalog model. Ignore per-model cache entries here.
+function minimaxProviderStatus(
+  config: LocalRuntimeConfig,
   cache: ModelCacheData,
-  providerId: string,
 ): { status: ModelCacheStatusView } | undefined {
-  const view = cacheStatusView(cache.provider_status[providerId]);
+  const modelId = Object.keys(minimaxApiModels(config))[0];
+  if (!modelId) return undefined;
+  const view = cacheStatusView(
+    byokModelTestStatus(
+      config,
+      { ...cache, model_status: {} },
+      MINIMAX_API_PROVIDER_ID,
+      modelId,
+    ),
+  );
   return view ? { status: view } : undefined;
 }

+ 5 - 0
packages/local-runtime-v2/src/service/model-system/connectivity/provider-request.ts

@@ -31,6 +31,11 @@ export function buildProviderHeaders(input: {
   for (const [name, value] of Object.entries(attributedHeaders ?? {})) {
     headers.set(name, value);
   }
+  // Explicit Authorization replaces the default API key, but explicit dual auth is preserved.
+  const supplied = new Headers(input.headers);
+  if (supplied.has('authorization') && !supplied.has('x-api-key')) {
+    headers.delete('x-api-key');
+  }
   return headers;
 }
 

+ 2 - 0
packages/local-runtime-v2/src/service/model-system/contracts.ts

@@ -94,6 +94,8 @@ export type LocalModelsConfig = Record<string, LocalProviderConfig>;
 export interface LocalMinimaxApiConfig {
   apiKey?: string;
   baseURL?: string;
+  /** Hand-edited request headers; values may contain credentials and must not be displayed. */
+  headers?: Record<string, string>;
   modelContextLimits?: Record<string, number>;
 }
 

+ 35 - 0
packages/local-runtime-v2/src/service/model-system/management/service-context.test.ts

@@ -3,6 +3,7 @@ import { tmpdir } from 'node:os';
 import { join } from 'node:path';
 import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
 
+import { buildMinimaxProviderView } from '../catalog/provider-views.js';
 import { LocalModelCache } from '../catalog/model-cache.js';
 import type {
   LocalByokConfigDraft,
@@ -122,6 +123,40 @@ describe('LocalModelProviderService context', () => {
     expect(harness.selectModel).not.toHaveBeenCalled();
   });
 
+  it('tests MiniMax headers, hides values, and expires cached verdicts after header changes', async () => {
+    const headers = {
+      Authorization: 'Bearer fixture-relay-secret',
+      'X-Tenant': 'fixture-tenant',
+    };
+    const harness = createHarness({
+      minimax_api: {
+        apiKey: MINIMAX_KEY,
+        baseURL: 'https://relay.example/anthropic',
+        headers,
+      },
+      minimaxModelSource: 'minimax_api_key',
+    });
+    const providerView = () => buildMinimaxProviderView(harness.config, harness.cache.load());
+    const modelId = providerView()!.models[0]!.modelId;
+    await harness.service.testProvider('minimax_api');
+    await harness.service.testModel('minimax_api', modelId);
+    expect(harness.testCalls.length).toBeGreaterThan(0);
+    for (const call of harness.testCalls) expect(call.target.headers).toEqual(headers);
+    expect(harness.service.getMinimaxApiKeyStatus().cachedStatus?.state).toBe('available');
+    expect(providerView()?.status?.state).toBe('available');
+    expect(providerView()?.headerNames).toEqual(['Authorization', 'X-Tenant']);
+    expect(JSON.stringify(providerView())).not.toContain('fixture-relay-secret');
+    expect(JSON.stringify(providerView())).not.toContain('fixture-tenant');
+    expect(JSON.stringify(providerView())).not.toContain(MINIMAX_KEY);
+    expect(providerView()?.models[0]?.status?.state).toBe('available');
+
+    headers.Authorization = 'Bearer fixture-rotated-secret';
+    expect(harness.service.getMinimaxApiKeyStatus().cachedStatus).toBeUndefined();
+    expect(providerView()?.status).toBeUndefined();
+    expect(providerView()?.models[0]?.status).toBeUndefined();
+    expect(JSON.stringify(harness.cache.load())).not.toContain('fixture-relay-secret');
+  });
+
   it('creates and updates a custom Provider through the same Model System owner', async () => {
     const harness = createHarness({}, { implicitCustomProviderThinking: true });
 

+ 1 - 0
packages/local-runtime-v2/src/service/model-system/management/service-context.ts

@@ -420,6 +420,7 @@ export class ModelProviderServiceContext {
       apiKey,
       modelId: chosenModelId,
       outputLimit,
+      ...(config.minimax_api?.headers ? { headers: config.minimax_api.headers } : {}),
     };
     return {
       cacheKey: providerTestCacheKey(MINIMAX_API_PROVIDER_ID, modelId),

+ 131 - 0
packages/local-runtime-v2/src/service/model-system/resolution/minimax-auth-headers.test.ts

@@ -0,0 +1,131 @@
+import { describe, expect, it, vi } from 'vitest';
+import { streamSimple } from '@earendil-works/pi-ai';
+import { parseMinimaxApiConfig } from '../../../../../config/src/byok-config.js';
+import { planMinimaxApiResolution as legacyPlan } from '../../../../../local-runtime/src/runtime/model-resolver-byok.js';
+import { planMinimaxApiResolution } from './model-resolver-byok.js';
+import { LocalModelResolver } from './local-model-resolver.js';
+import {
+  buildProviderHeaders,
+  buildModelDiscoveryHeaders,
+} from '../connectivity/provider-request.js';
+
+const apiKey = 'fixture-default-key';
+const authorization = 'Bearer fixture-relay-key';
+
+describe('MiniMax API custom authentication headers', () => {
+  it('parses only string header values without exposing mutable input records', () => {
+    const raw = {
+      apiKey,
+      headers: {
+        Authorization: authorization,
+        count: 1,
+        nested: {},
+        '': 'bad',
+      },
+    };
+    const parsed = parseMinimaxApiConfig(raw);
+    expect(parsed).toEqual({
+      apiKey,
+      headers: { Authorization: authorization },
+    });
+    expect(parsed?.headers).not.toBe(raw.headers);
+    for (const headers of [null, [], 'bad', { count: 1 }]) {
+      expect(parseMinimaxApiConfig({ apiKey, headers })).toEqual({ apiKey });
+    }
+  });
+
+  it.each([planMinimaxApiResolution, legacyPlan])(
+    'propagates headers through each BYOK planner',
+    (plan) => {
+      expect(
+        plan({
+          byok: {
+            minimax_api: { apiKey, headers: { Authorization: authorization } },
+          },
+          providerConfig: undefined,
+          modelId: 'MiniMax-M3',
+          catalog: {
+            contextWindow: 200_000,
+            maxTokens: 16_384,
+            fromCatalog: false,
+          },
+        }),
+      ).toMatchObject({ configHeaders: { Authorization: authorization } });
+    },
+  );
+
+  const cases: Array<[Record<string, string> | undefined, string | null, string | null]> = [
+    [undefined, null, apiKey],
+    [{ Authorization: authorization }, authorization, null],
+    [{ AUTHORIZATION: authorization }, authorization, null],
+    [{ 'x-api-key': 'fixture-override' }, null, 'fixture-override'],
+    [{ authorization, 'X-Api-Key': 'fixture-explicit' }, authorization, 'fixture-explicit'],
+  ];
+  it.each(cases)(
+    'uses the same auth headers for probes and real SDK requests: %j',
+    async (headers, expectedAuth, expectedKey) => {
+      const parsed = parseMinimaxApiConfig({
+        apiKey,
+        baseURL: 'https://relay.example/anthropic',
+        headers,
+      });
+      const resolver = new LocalModelResolver({
+        byokConfigGetter: () => ({ minimax_api: parsed }),
+      });
+      const resolved = await resolver.resolveModel({
+        sessionId: 'fixture-session',
+        turnId: 'fixture-turn',
+        agentConfig: {
+          system_prompt: 'Be brief.',
+          agent_id: 'fixture-agent',
+          tools: [],
+          skills: [],
+          model: {
+            provider: 'minimax_api',
+            model_id: 'MiniMax-M3',
+            context_window: 200_000,
+          },
+        },
+      });
+      const probe = buildProviderHeaders({
+        api: 'anthropic-messages',
+        apiKey,
+        headers,
+      });
+      expect(probe.get('authorization')).toBe(expectedAuth);
+      expect(probe.get('x-api-key')).toBe(expectedKey);
+      const fetchImpl = vi.fn<typeof fetch>(async (_url, init) => {
+        const actual = new Headers(init?.headers);
+        expect(actual.get('authorization')).toBe(expectedAuth);
+        expect(actual.get('x-api-key')).toBe(expectedKey);
+        return new Response(
+          'event: message_start\ndata: {"type":"message_start","message":{"id":"fixture","type":"message","role":"assistant","content":[],"model":"MiniMax-M3","usage":{"input_tokens":1,"output_tokens":0}}}\n\nevent: message_delta\ndata: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":0}}\n\nevent: message_stop\ndata: {"type":"message_stop"}\n\n',
+          { headers: { 'content-type': 'text/event-stream' } },
+        );
+      });
+      const result = await streamSimple(
+        resolved.model,
+        {
+          messages: [{ role: 'user', content: 'Hi', timestamp: 0 }],
+        },
+        {
+          apiKey: resolved.apiKey,
+          headers: resolved.headers,
+          fetch: fetchImpl,
+        },
+      ).result();
+      expect(fetchImpl).toHaveBeenCalledOnce();
+      expect(result.stopReason).not.toBe('error');
+    },
+  );
+
+  it('preserves discovery probes that intentionally send both authentication schemes', () => {
+    const headers = buildModelDiscoveryHeaders({
+      api: 'anthropic-messages',
+      apiKey,
+      headers: { Authorization: authorization },
+    });
+    expect(headers.get('authorization')).toBe(authorization);
+    expect(headers.get('x-api-key')).toBe(apiKey);
+  });
+});

+ 2 - 0
packages/local-runtime-v2/src/service/model-system/resolution/model-resolver-byok.ts

@@ -50,6 +50,7 @@ export function planMinimaxApiResolution(input: {
   if (!apiKey) {
     throw new Error('LocalModelResolver: minimax_api apiKey is not configured.');
   }
+  const configHeaders = readStringRecord(config.headers);
   const catalogModel = MINIMAX_API_MODEL_CATALOG[input.modelId];
   const contextOverride = config.modelContextLimits?.[input.modelId];
   const contextLimit =
@@ -60,6 +61,7 @@ export function planMinimaxApiResolution(input: {
     provider: MINIMAX_API_PROVIDER_ID,
     api: 'anthropic-messages',
     apiKey,
+    ...(configHeaders ? { configHeaders } : {}),
     baseUrl: config.baseURL?.trim() || defaultMinimaxApiBaseUrl(),
     contextWindow:
       contextLimit ??

+ 2 - 0
packages/local-runtime/src/config/types.ts

@@ -49,6 +49,8 @@ export type LocalModelsConfig = Record<string, LocalProviderConfig>;
 export interface LocalMinimaxApiConfig {
   apiKey?: string;
   baseURL?: string;
+  /** Hand-edited request headers; values may contain credentials and must not be displayed. */
+  headers?: Record<string, string>;
   modelContextLimits?: Record<string, number>;
 }
 

+ 1 - 0
packages/local-runtime/src/model-provider/config-fingerprint.ts

@@ -30,6 +30,7 @@ export function byokModelTestStatus(
         baseUrl: normalizeProviderBaseUrl('anthropic-messages', minimaxApiBaseUrl(config)),
         apiKey,
         modelId,
+        ...(config.minimax_api?.headers ? { headers: config.minimax_api.headers } : {}),
       },
       model,
     );

+ 5 - 0
packages/local-runtime/src/model-provider/provider-request.ts

@@ -29,6 +29,11 @@ export function buildProviderHeaders(input: {
   for (const [name, value] of Object.entries(attributedHeaders ?? {})) {
     headers.set(name, value);
   }
+  // Explicit Authorization replaces the default API key, but explicit dual auth is preserved.
+  const supplied = new Headers(input.headers);
+  if (supplied.has('authorization') && !supplied.has('x-api-key')) {
+    headers.delete('x-api-key');
+  }
   return headers;
 }
 

+ 2 - 0
packages/local-runtime/src/runtime/model-resolver-byok.ts

@@ -77,6 +77,7 @@ export function planMinimaxApiResolution(input: {
   if (!apiKey) {
     throw new Error('LocalModelResolver: minimax_api apiKey is not configured.');
   }
+  const configHeaders = readStringRecord(cfg.headers);
   const catalogModel = MINIMAX_API_MODEL_CATALOG[input.modelId];
   const contextOverride = cfg.modelContextLimits?.[input.modelId];
   const contextLimit =
@@ -87,6 +88,7 @@ export function planMinimaxApiResolution(input: {
     provider: 'minimax_api',
     api: 'anthropic-messages',
     apiKey,
+    ...(configHeaders ? { configHeaders } : {}),
     baseUrl: normalizeProviderBaseUrl(
       'anthropic-messages',
       cfg.baseURL?.trim() || MINIMAX_API_DEFAULT_BASE_URL,

+ 1 - 0
release/public-source.json

@@ -935,6 +935,7 @@
     "packages/local-runtime-v2/src/service/model-system/resolution/file-api-gateway-auth.ts",
     "packages/local-runtime-v2/src/service/model-system/resolution/local-model-resolver.test.ts",
     "packages/local-runtime-v2/src/service/model-system/resolution/local-model-resolver.ts",
+    "packages/local-runtime-v2/src/service/model-system/resolution/minimax-auth-headers.test.ts",
     "packages/local-runtime-v2/src/service/model-system/resolution/model-key.ts",
     "packages/local-runtime-v2/src/service/model-system/resolution/model-ref.test.ts",
     "packages/local-runtime-v2/src/service/model-system/resolution/model-ref.ts",

+ 1 - 0
test/vitest-suites.json

@@ -59,6 +59,7 @@
       "packages/local-runtime-v2/src/service/model-system/resolution/local-model-resolver.test.ts",
       "packages/local-runtime-v2/src/service/model-system/resolution/model-ref.test.ts",
       "packages/local-runtime-v2/src/service/model-system/resolution/model-resolver-byok.test.ts",
+      "packages/local-runtime-v2/src/service/model-system/resolution/minimax-auth-headers.test.ts",
       "packages/local-runtime/test/unit/child-bash-lifecycle.test.ts",
       "packages/local-runtime/test/unit/local-background-task-task-output-polling-reminder.test.ts",
       "packages/mcode-tools-host/test/unit/resource-manifest.test.ts",

+ 4 - 1
third_party/pi-mono/packages/ai/src/providers/anthropic.ts

@@ -949,7 +949,9 @@ function createClient(
 		return { client, isOAuthToken: true };
 	}
 
-	// API key auth
+	// API key auth. An explicit Authorization header replaces the SDK default key.
+	const configuredAuthHeaders = new Headers({ ...model.headers, ...optionsHeaders });
+	const omitDefaultApiKey = configuredAuthHeaders.has("authorization") && !configuredAuthHeaders.has("x-api-key");
 	const sessionAffinityHeaders: Record<string, string | null> =
 		sessionId && getAnthropicCompat(model).sendSessionAffinityHeaders ? { "x-session-affinity": sessionId } : {};
 	const client = new Anthropic({
@@ -964,6 +966,7 @@ function createClient(
 				"anthropic-dangerous-direct-browser-access": "true",
 				...(betaFeatures.length > 0 ? { "anthropic-beta": betaFeatures.join(",") } : {}),
 			},
+			...(omitDefaultApiKey ? [{ "x-api-key": null }] : []),
 			sessionAffinityHeaders,
 			model.headers,
 			optionsHeaders,