Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions packages/core/src/agents/agentLoader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,6 @@ agent_card_url: https://example.com/card
auth:
type: apiKey
key: $MY_API_KEY
in: header
name: X-Custom-Key
---
`);
Expand All @@ -385,7 +384,6 @@ auth:
auth: {
type: 'apiKey',
key: '$MY_API_KEY',
in: 'header',
name: 'X-Custom-Key',
},
});
Expand Down Expand Up @@ -468,7 +466,7 @@ auth:
---
`);
await expect(parseAgentMarkdown(filePath)).rejects.toThrow(
/Basic scheme requires "username" and "password"/,
/Basic authentication requires "password"/,
);
});

Expand All @@ -494,7 +492,6 @@ auth:
auth: {
type: 'apiKey' as const,
key: '$API_KEY',
in: 'header' as const,
},
};

Expand All @@ -505,7 +502,6 @@ auth:
auth: {
type: 'apiKey',
key: '$API_KEY',
location: 'header',
},
});
});
Expand Down
40 changes: 20 additions & 20 deletions packages/core/src/agents/agentLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ interface FrontmatterAuthConfig {
agent_card_requires_auth?: boolean;
// API Key
key?: string;
in?: 'header' | 'query' | 'cookie';
name?: string;
// HTTP
scheme?: 'Bearer' | 'Basic';
Expand Down Expand Up @@ -129,7 +128,6 @@ const apiKeyAuthSchema = z.object({
...baseAuthFields,
type: z.literal('apiKey'),
key: z.string().min(1, 'API key is required'),
in: z.enum(['header', 'query', 'cookie']).optional(),
name: z.string().optional(),
});

Expand All @@ -138,24 +136,18 @@ const apiKeyAuthSchema = z.object({
* Note: Validation for scheme-specific fields is applied in authConfigSchema
* since discriminatedUnion doesn't support refined schemas directly.
*/
const httpAuthSchemaBase = z.object({
const httpAuthSchema = z.object({
...baseAuthFields,
type: z.literal('http'),
scheme: z.enum(['Bearer', 'Basic']),
token: z.string().optional(),
username: z.string().optional(),
password: z.string().optional(),
token: z.string().min(1).optional(),
username: z.string().min(1).optional(),
password: z.string().min(1).optional(),
});

/**
* Combined auth schema - discriminated union of all auth types.
* Note: We use the base schema for discriminatedUnion, then apply refinements
* via superRefine since discriminatedUnion doesn't support refined schemas directly.
*/
const authConfigSchema = z
.discriminatedUnion('type', [apiKeyAuthSchema, httpAuthSchemaBase])
.discriminatedUnion('type', [apiKeyAuthSchema, httpAuthSchema])
.superRefine((data, ctx) => {
// Apply HTTP auth validation after union parsing
if (data.type === 'http') {
if (data.scheme === 'Bearer' && !data.token) {
ctx.addIssue({
Expand All @@ -164,12 +156,21 @@ const authConfigSchema = z
path: ['token'],
});
}
if (data.scheme === 'Basic' && (!data.username || !data.password)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Basic scheme requires "username" and "password"',
path: data.username ? ['password'] : ['username'],
});
if (data.scheme === 'Basic') {
if (!data.username) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Basic authentication requires "username"',
path: ['username'],
});
}
if (!data.password) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Basic authentication requires "password"',
path: ['password'],
});
}
}
}
});
Expand Down Expand Up @@ -338,7 +339,6 @@ function convertFrontmatterAuthToConfig(
...base,
type: 'apiKey',
key: frontmatter.key,
location: frontmatter.in,
name: frontmatter.name,
};

Expand Down
180 changes: 180 additions & 0 deletions packages/core/src/agents/auth-provider/api-key-provider.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/

import { describe, it, expect, afterEach, vi } from 'vitest';
import { ApiKeyAuthProvider } from './api-key-provider.js';

describe('ApiKeyAuthProvider', () => {
afterEach(() => {
vi.unstubAllEnvs();
});

describe('initialization', () => {
it('should initialize with literal API key', async () => {
const provider = new ApiKeyAuthProvider({
type: 'apiKey',
key: 'my-api-key',
});
await provider.initialize();

const headers = await provider.headers();
expect(headers).toEqual({ 'X-API-Key': 'my-api-key' });
});

it('should resolve API key from environment variable', async () => {
vi.stubEnv('TEST_API_KEY', 'env-api-key');

const provider = new ApiKeyAuthProvider({
type: 'apiKey',
key: '$TEST_API_KEY',
});
await provider.initialize();

const headers = await provider.headers();
expect(headers).toEqual({ 'X-API-Key': 'env-api-key' });
});

it('should throw if environment variable is not set', async () => {
const provider = new ApiKeyAuthProvider({
type: 'apiKey',
key: '$MISSING_KEY_12345',
});

await expect(provider.initialize()).rejects.toThrow(
"Environment variable 'MISSING_KEY_12345' is not set",
);
});
});

describe('headers', () => {
it('should throw if not initialized', async () => {
const provider = new ApiKeyAuthProvider({
type: 'apiKey',
key: 'test-key',
});

await expect(provider.headers()).rejects.toThrow('not initialized');
});

it('should use custom header name', async () => {
const provider = new ApiKeyAuthProvider({
type: 'apiKey',
key: 'my-key',
name: 'X-Custom-Auth',
});
await provider.initialize();

const headers = await provider.headers();
expect(headers).toEqual({ 'X-Custom-Auth': 'my-key' });
});

it('should use default header name X-API-Key', async () => {
const provider = new ApiKeyAuthProvider({
type: 'apiKey',
key: 'my-key',
});
await provider.initialize();

const headers = await provider.headers();
expect(headers).toEqual({ 'X-API-Key': 'my-key' });
});
});

describe('shouldRetryWithHeaders', () => {
it('should return undefined for non-auth errors', async () => {
const provider = new ApiKeyAuthProvider({
type: 'apiKey',
key: 'test-key',
});
await provider.initialize();

const result = await provider.shouldRetryWithHeaders(
{},
new Response(null, { status: 500 }),
);
expect(result).toBeUndefined();
});

it('should return undefined for literal keys on 401 (same headers would fail again)', async () => {
const provider = new ApiKeyAuthProvider({
type: 'apiKey',
key: 'test-key',
});
await provider.initialize();

const result = await provider.shouldRetryWithHeaders(
{},
new Response(null, { status: 401 }),
);
expect(result).toBeUndefined();
});

it('should return undefined for env-var keys on 403', async () => {
vi.stubEnv('RETRY_TEST_KEY', 'some-key');
const provider = new ApiKeyAuthProvider({
type: 'apiKey',
key: '$RETRY_TEST_KEY',
});
await provider.initialize();

const result = await provider.shouldRetryWithHeaders(
{},
new Response(null, { status: 403 }),
);
expect(result).toBeUndefined();
});

it('should re-resolve and return headers for command keys on 401', async () => {
const provider = new ApiKeyAuthProvider({
type: 'apiKey',
key: '!echo refreshed-key',
});
await provider.initialize();

const result = await provider.shouldRetryWithHeaders(
{},
new Response(null, { status: 401 }),
);
expect(result).toEqual({ 'X-API-Key': 'refreshed-key' });
});

it('should stop retrying after MAX_AUTH_RETRIES', async () => {
const provider = new ApiKeyAuthProvider({
type: 'apiKey',
key: '!echo rotating-key',
});
await provider.initialize();

const r1 = await provider.shouldRetryWithHeaders(
{},
new Response(null, { status: 401 }),
);
expect(r1).toBeDefined();

const r2 = await provider.shouldRetryWithHeaders(
{},
new Response(null, { status: 401 }),
);
expect(r2).toBeDefined();

const r3 = await provider.shouldRetryWithHeaders(
{},
new Response(null, { status: 401 }),
);
expect(r3).toBeUndefined();
});
});

describe('type property', () => {
it('should have type apiKey', () => {
const provider = new ApiKeyAuthProvider({
type: 'apiKey',
key: 'test',
});
expect(provider.type).toBe('apiKey');
});
});
});
85 changes: 85 additions & 0 deletions packages/core/src/agents/auth-provider/api-key-provider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/

import type { HttpHeaders } from '@a2a-js/sdk/client';
import { BaseA2AAuthProvider } from './base-provider.js';
import type { ApiKeyAuthConfig } from './types.js';
import { resolveAuthValue, needsResolution } from './value-resolver.js';
import { debugLogger } from '../../utils/debugLogger.js';

const DEFAULT_HEADER_NAME = 'X-API-Key';

/**
* Authentication provider for API Key authentication.
* Sends the API key as an HTTP header.
*
* The API key value can be:
* - A literal string
* - An environment variable reference ($ENV_VAR)
* - A shell command (!command)
*/
export class ApiKeyAuthProvider extends BaseA2AAuthProvider {
readonly type = 'apiKey' as const;

private resolvedKey: string | undefined;
private readonly headerName: string;

constructor(private readonly config: ApiKeyAuthConfig) {
super();
this.headerName = config.name ?? DEFAULT_HEADER_NAME;
}

override async initialize(): Promise<void> {
if (needsResolution(this.config.key)) {
this.resolvedKey = await resolveAuthValue(this.config.key);
Comment thread
adamfweidman marked this conversation as resolved.
debugLogger.debug(
`[ApiKeyAuthProvider] Resolved API key from: ${this.config.key.startsWith('$') ? 'env var' : 'command'}`,
);
} else {
this.resolvedKey = this.config.key;
}
}

async headers(): Promise<HttpHeaders> {
if (!this.resolvedKey) {
throw new Error(
'ApiKeyAuthProvider not initialized. Call initialize() first.',
);
}
return { [this.headerName]: this.resolvedKey };
}

/**
* Re-resolve command-based API keys on auth failure.
*/
override async shouldRetryWithHeaders(
_req: RequestInit,
res: Response,
): Promise<HttpHeaders | undefined> {
if (res.status !== 401 && res.status !== 403) {
this.authRetryCount = 0;
return undefined;
}

// Only retry for command-based keys that may resolve to a new value.
// Literal and env-var keys would just resend the same failing headers.
if (!this.config.key.startsWith('!') || this.config.key.startsWith('!!')) {
return undefined;
}

if (this.authRetryCount >= BaseA2AAuthProvider.MAX_AUTH_RETRIES) {
return undefined;
}
this.authRetryCount++;

debugLogger.debug(
'[ApiKeyAuthProvider] Re-resolving API key after auth failure',
);
this.resolvedKey = await resolveAuthValue(this.config.key);
Comment thread
adamfweidman marked this conversation as resolved.

return this.headers();
}
}
Loading
Loading