-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhttps_a2a_server.php
More file actions
596 lines (514 loc) · 19.4 KB
/
Copy pathhttps_a2a_server.php
File metadata and controls
596 lines (514 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
<?php
declare(strict_types=1);
/**
* HTTPS-Enabled A2A Protocol Server Implementation
*
* This server provides HTTPS/TLS support for production security
* while maintaining backward compatibility with HTTP for development.
*
* Features:
* - Complete A2A Protocol v0.3.0 compliance
* - HTTPS/TLS support for production security
* - Automatic SSL certificate handling
* - HTTP to HTTPS redirect capability
* - Development/production mode switching
* - All existing functionality preserved
*
* Usage:
* # Development mode (HTTP)
* php -S localhost:8081 https_a2a_server.php
*
* # Production mode (HTTPS with certificates)
* A2A_MODE=production php -S localhost:8443 https_a2a_server.php
*/
require_once __DIR__ . '/vendor/autoload.php';
use A2A\A2AServer;
use A2A\Events\EventBusManager;
use A2A\Execution\DefaultAgentExecutor;
use A2A\Exceptions\A2AErrorCodes;
use A2A\Models\AgentCapabilities;
use A2A\Models\v030\AgentCard;
use A2A\PushNotificationManager;
use A2A\Storage\Storage;
use A2A\Streaming\StreamingServer;
use A2A\TaskManager;
use A2A\Utils\JsonRpc;
use Psr\Log\LoggerInterface;
/**
* HTTPS-aware Logger for A2A Server Operations
*/
class A2AHttpsServerLogger implements LoggerInterface
{
private string $logFile;
private bool $httpsMode;
public function __construct(string $logFile = 'a2a_server.log', bool $httpsMode = false)
{
$this->logFile = $logFile;
$this->httpsMode = $httpsMode;
}
public function emergency($message, array $context = []): void
{
$this->log('EMERGENCY', $message, $context);
}
public function alert($message, array $context = []): void
{
$this->log('ALERT', $message, $context);
}
public function critical($message, array $context = []): void
{
$this->log('CRITICAL', $message, $context);
}
public function error($message, array $context = []): void
{
$this->log('ERROR', $message, $context);
}
public function warning($message, array $context = []): void
{
$this->log('WARNING', $message, $context);
}
public function notice($message, array $context = []): void
{
$this->log('NOTICE', $message, $context);
}
public function info($message, array $context = []): void
{
$this->log('INFO', $message, $context);
}
public function debug($message, array $context = []): void
{
$this->log('DEBUG', $message, $context);
}
public function log($level, $message, array $context = []): void
{
$timestamp = date('Y-m-d H:i:s');
$protocol = $this->httpsMode ? 'HTTPS' : 'HTTP';
$contextStr = !empty($context) ? ' ' . json_encode($context) : '';
$logEntry = "[{$timestamp}] {$level}: {$message}{$contextStr} (Protocol: {$protocol})" . PHP_EOL;
file_put_contents($this->logFile, $logEntry, FILE_APPEND | LOCK_EX);
}
}
/**
* HTTPS/TLS Configuration Manager
*/
class HttpsConfigManager
{
private string $certDir;
private string $keyFile;
private string $certFile;
private LoggerInterface $logger;
public function __construct(LoggerInterface $logger, string $certDir = '/tmp/a2a_certs')
{
$this->logger = $logger;
$this->certDir = $certDir;
$this->keyFile = $certDir . '/server.key';
$this->certFile = $certDir . '/server.crt';
}
public function ensureCertificatesExist(): bool
{
if (!is_dir($this->certDir)) {
mkdir($this->certDir, 0755, true);
}
if (file_exists($this->keyFile) && file_exists($this->certFile)) {
$this->logger->info('Using existing SSL certificates', [
'key_file' => $this->keyFile,
'cert_file' => $this->certFile
]);
return true;
}
return $this->generateSelfSignedCertificate();
}
private function generateSelfSignedCertificate(): bool
{
$this->logger->info('Generating self-signed SSL certificate for development');
// Generate private key
$privateKey = openssl_pkey_new([
'private_key_bits' => 2048,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
]);
if (!$privateKey) {
$this->logger->error('Failed to generate private key');
return false;
}
// Generate certificate signing request
$csr = openssl_csr_new([
'countryName' => 'US',
'stateOrProvinceName' => 'Development',
'localityName' => 'A2A Server',
'organizationName' => 'A2A Development',
'organizationalUnitName' => 'IT Department',
'commonName' => 'localhost',
'emailAddress' => 'dev@a2a-server.local'
], $privateKey, [
'digest_alg' => 'sha256',
'x509_extensions' => 'v3_req',
'req_extensions' => 'v3_req',
]);
if (!$csr) {
$this->logger->error('Failed to generate certificate signing request');
return false;
}
// Generate self-signed certificate valid for 1 year
$cert = openssl_csr_sign($csr, null, $privateKey, 365, [
'digest_alg' => 'sha256',
]);
if (!$cert) {
$this->logger->error('Failed to generate self-signed certificate');
return false;
}
// Export private key
openssl_pkey_export($privateKey, $privateKeyOut);
file_put_contents($this->keyFile, $privateKeyOut);
// Export certificate
openssl_x509_export($cert, $certOut);
file_put_contents($this->certFile, $certOut);
// Set proper permissions
chmod($this->keyFile, 0600);
chmod($this->certFile, 0644);
$this->logger->info('Self-signed SSL certificate generated successfully', [
'key_file' => $this->keyFile,
'cert_file' => $this->certFile,
'valid_days' => 365
]);
return true;
}
public function getKeyFile(): string
{
return $this->keyFile;
}
public function getCertFile(): string
{
return $this->certFile;
}
}
/**
* Enhanced A2A Server with HTTPS Support
*/
class A2AHttpsServer
{
private A2AServer $server;
private TaskManager $taskManager;
private AgentCard $agentCard;
private A2AHttpsServerLogger $logger;
private bool $httpsMode;
private HttpsConfigManager $httpsConfig;
private int $port;
private PushNotificationManager $pushNotificationManager;
private EventBusManager $eventBusManager;
private DefaultAgentExecutor $executor;
private StreamingServer $streamingServer;
public function __construct()
{
// Determine if we're in HTTPS mode
$this->httpsMode = (getenv('A2A_MODE') === 'production') ||
(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ||
(isset($_SERVER['SERVER_PORT']) && (int)$_SERVER['SERVER_PORT'] === 8443);
// Detect the actual port being used
$this->port = (int)($_SERVER['SERVER_PORT'] ?? ($this->httpsMode ? 8443 : 8081));
$this->logger = new A2AHttpsServerLogger('a2a_server.log', $this->httpsMode);
if ($this->httpsMode) {
$this->httpsConfig = new HttpsConfigManager($this->logger);
$this->httpsConfig->ensureCertificatesExist();
}
$this->initializeServer();
$this->setupAgentCard();
$this->setupMessageHandlers();
}
private function initializeServer(): void
{
// Initialize shared storage and core components
$storage = new Storage('array');
$this->taskManager = new TaskManager($storage);
$this->pushNotificationManager = new PushNotificationManager($storage);
$this->eventBusManager = new EventBusManager();
$this->executor = new DefaultAgentExecutor();
$this->streamingServer = new StreamingServer();
$this->logger->info('A2A Server components initialized', [
'https_mode' => $this->httpsMode,
'port' => $this->port
]);
}
private function setupAgentCard(): void
{
$baseUrl = $this->httpsMode ? "https://localhost:{$this->port}" : "http://localhost:{$this->port}";
$capabilities = new AgentCapabilities(
true, // streaming
true, // pushNotifications
false, // stateTransitionHistory
[] // extensions
);
// Create skills
$skills = [
new \A2A\Models\AgentSkill(
'text-processing',
'Text Processing',
'Process and respond to text-based requests',
['text', 'general']
),
new \A2A\Models\AgentSkill(
'file-processing',
'File Processing',
'Process and analyze file-based content',
['file', 'data']
),
new \A2A\Models\AgentSkill(
'secure-communication',
'Secure Communication',
'HTTPS/TLS encrypted communication support',
['security', 'https', 'tls']
)
];
$this->agentCard = new AgentCard(
'complete-a2a-server', // name
'Complete A2A Server Implementation with HTTPS Support', // description
$baseUrl, // url
'1.0.0', // version
$capabilities, // capabilities
['text', 'file', 'data'], // defaultInputModes
['text', 'file', 'data'], // defaultOutputModes
$skills, // skills
'0.3.0' // protocolVersion
);
$this->agentCard->setSupportsAuthenticatedExtendedCard(true);
// Initialize server with enhanced components and shared TaskManager
// Enable A2A Protocol compliance mode for TCK tests
$protocol = new \A2A\A2AProtocol_v030(
$this->agentCard,
null,
$this->logger,
$this->taskManager,
$this->pushNotificationManager,
$this->eventBusManager,
$this->executor,
$this->streamingServer
);
$this->server = new A2AServer($protocol, $this->logger);
$this->logger->info('Agent card configured', [
'agent_id' => $this->agentCard->getName(),
'version' => $this->agentCard->getVersion(),
'base_url' => $baseUrl,
'https_enabled' => $this->httpsMode
]);
}
private function setupMessageHandlers(): void
{
$messageHandler = new class($this->logger, $this->taskManager, $this->httpsMode) implements \A2A\Interfaces\MessageHandlerInterface {
private $logger;
private $taskManager;
private $httpsMode;
public function __construct($logger, $taskManager, $httpsMode) {
$this->logger = $logger;
$this->taskManager = $taskManager;
$this->httpsMode = $httpsMode;
}
public function canHandle(\A2A\Models\v030\Message $message): bool {
return true;
}
public function handle(\A2A\Models\v030\Message $message, string $fromAgent): array {
$this->logger->info('Processing message', [
'from' => $fromAgent,
'message_id' => $message->getMessageId(),
'role' => $message->getRole(),
'https_mode' => $this->httpsMode
]);
$taskId = $message->getTaskId();
if ($taskId) {
$task = $this->taskManager->getTask($taskId);
if ($task) {
$this->logger->info('Message task ready for interaction', [
'task_id' => $taskId,
'message_id' => $message->getMessageId(),
'state' => $task->getStatus()->getState()->value,
'secure' => $this->httpsMode
]);
}
}
return [
'status' => [
'state' => 'completed',
'timestamp' => date('c')
],
'metadata' => [
'secure' => $this->httpsMode,
'message' => 'HTTPS server processed the request'
]
];
}
};
$this->server->addMessageHandler($messageHandler);
}
public function handleHttpsRedirect(): bool
{
// Only redirect in production mode and if not already HTTPS
if (!$this->httpsMode && getenv('A2A_FORCE_HTTPS') === 'true') {
$httpsUrl = 'https://' . $_SERVER['HTTP_HOST'] . ':8443' . $_SERVER['REQUEST_URI'];
header('Location: ' . $httpsUrl, true, 301);
echo json_encode([
'jsonrpc' => '2.0',
'error' => [
'code' => -32001,
'message' => 'HTTPS required for production. Redirecting...',
'data' => ['redirect_url' => $httpsUrl]
],
'id' => null
]);
return true;
}
return false;
}
public function getAgentCard(): array
{
return $this->agentCard->toArray();
}
public function handleRequest(): void
{
// Handle HTTPS redirect if needed
if ($this->handleHttpsRedirect()) {
return;
}
// Set CORS headers for cross-origin requests
$this->setCorsHeaders();
// Handle preflight requests
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
http_response_code(200);
return;
}
// Log security information
$this->logger->info('Request received', [
'method' => $_SERVER['REQUEST_METHOD'] ?? 'UNKNOWN',
'uri' => $_SERVER['REQUEST_URI'] ?? '/',
'https' => $this->httpsMode,
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
'remote_addr' => $_SERVER['REMOTE_ADDR'] ?? 'unknown'
]);
// Only accept POST requests for A2A protocol
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
$this->sendErrorResponse('Method not allowed', 405);
return;
}
// Get request body
$input = file_get_contents('php://input');
if ($input === false || empty($input)) {
$this->sendErrorResponse('Empty request body', 400);
return;
}
// Parse JSON request
$request = json_decode($input, true);
if (json_last_error() !== JSON_ERROR_NONE) {
$this->sendJsonRpcError(null, 'Parse error', A2AErrorCodes::PARSE_ERROR);
return;
}
$this->logger->info('Request received', [
'method' => $request['method'] ?? 'unknown',
'id' => $request['id'] ?? 'none',
'https_mode' => $this->httpsMode
]);
// Handle streaming requests through A2AServer for proper validation
if (isset($request['method']) && $request['method'] === 'message/stream') {
try {
$response = $this->server->handleRequest($request);
// If validation passes and no response returned, it means streaming was started
if (empty($response)) {
return;
}
// If response returned, it's an error
$this->sendJsonResponse($response);
return;
} catch (\Exception $e) {
$this->sendJsonRpcError(
$request['id'] ?? null,
'Streaming error: ' . $e->getMessage(),
A2AErrorCodes::INTERNAL_ERROR
);
return;
}
}
// Process regular requests through enhanced A2AServer
try {
$response = $this->server->handleRequest($request);
$this->sendJsonResponse($response);
} catch (\Exception $e) {
$this->logger->error('Request processing failed', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
'https_mode' => $this->httpsMode
]);
$this->sendJsonRpcError(
$request['id'] ?? null,
'Internal server error',
A2AErrorCodes::INTERNAL_ERROR
);
}
}
private function setCorsHeaders(): void
{
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Content-Type: application/json');
if ($this->httpsMode) {
header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
}
}
private function sendErrorResponse(string $message, int $httpCode): void
{
http_response_code($httpCode);
echo json_encode(['error' => $message]);
}
private function sendJsonRpcError($id, string $message, int $code): void
{
$response = [
'jsonrpc' => '2.0',
'error' => [
'code' => $code,
'message' => $message
],
'id' => $id
];
$this->sendJsonResponse($response);
}
private function sendJsonResponse(array $response): void
{
echo json_encode($response, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
public function getServerInfo(): array
{
return [
'https_mode' => $this->httpsMode,
'port' => $this->port,
'ssl_enabled' => $this->httpsMode,
'certificates' => $this->httpsMode ? [
'key_file' => $this->httpsConfig->getKeyFile(),
'cert_file' => $this->httpsConfig->getCertFile()
] : null,
'agent_card_url' => ($this->httpsMode ? 'https' : 'http') . "://localhost:{$this->port}/.well-known/agent-card.json"
];
}
}
// Initialize the HTTPS-enabled server
$server = new A2AHttpsServer();
// Handle well-known agent card endpoint
if (
($_SERVER['REQUEST_METHOD'] ?? '') === 'GET' &&
($_SERVER['REQUEST_URI'] ?? '') === '/.well-known/agent-card.json'
) {
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
exit;
}
echo json_encode($server->getAgentCard(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
exit;
}
// Handle server info endpoint for debugging
if (
($_SERVER['REQUEST_METHOD'] ?? '') === 'GET' &&
($_SERVER['REQUEST_URI'] ?? '') === '/server-info'
) {
header('Content-Type: application/json');
echo json_encode($server->getServerInfo(), JSON_PRETTY_PRINT);
exit;
}
// Handle A2A protocol requests
$server->handleRequest();