-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterNetXXmlGatewayClient.php
More file actions
620 lines (526 loc) · 22.8 KB
/
InterNetXXmlGatewayClient.php
File metadata and controls
620 lines (526 loc) · 22.8 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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
<?php
/**
* Low-level InterNetX XML gateway client.
* It owns auth_session XML requests and zone document mutation details.
*/
final class InterNetXXmlGatewayClient
{
private const TASK_AUTH_SESSION_CREATE = '1321001';
private const TASK_AUTH_SESSION_DELETE = '1321003';
private const TASK_ZONE_INQUIRY = '0205';
private const TASK_ZONE_UPDATE = '0202';
private Config $config;
private Logger $logger;
private ?string $sessionHash = null;
private string $stage = 'unknown';
public function __construct(Config $config, Logger $logger)
{
$this->config = $config;
$this->logger = $logger;
}
public function setStage(string $stage): void
{
$this->stage = $stage;
}
public function hasSession(): bool
{
return $this->sessionHash !== null;
}
public function createSession(): void
{
$this->config->validateProviderConfig();
$this->debug('Preparing InterNetX AuthSessionCreate request', array(
'stage' => $this->stage,
'auth_mode' => 'session_create',
'credentials_auth' => 'true',
));
$request = $this->buildSessionCreateRequest();
$response = $this->request(
$request->saveXML(),
'AuthSessionCreate',
self::TASK_AUTH_SESSION_CREATE,
'auth_session_create',
'session_create',
false,
);
$document = $this->loadXml($response, 'AuthSessionCreate response');
$diagnostics = $this->extractResponseDiagnostics($document);
$this->assertApiSuccess($diagnostics, 'Session login failed', 'AuthSessionCreate', false);
$hash = $this->firstText($document, '//auth_session/hash');
if ($hash === null || $hash === '') {
throw new InterNetXApiException('InterNetX authentication/session creation failed: response did not contain a session hash.', array(
'operation' => 'AuthSessionCreate',
'task_code' => self::TASK_AUTH_SESSION_CREATE,
'stage' => $this->stage,
'session_established' => 'false',
));
}
$this->sessionHash = $hash;
$this->logger->success('InterNetX session created', array(
'auth_mode' => 'auth_session',
'session_hash' => $this->maskSecret($hash),
'session_persisted' => 'false',
));
}
public function closeSession(): void
{
if ($this->sessionHash === null) {
$this->debug('No InterNetX session to close', array('stage' => $this->stage));
return;
}
$hash = $this->sessionHash;
$this->debug('Preparing InterNetX AuthSessionDelete request', array(
'stage' => $this->stage,
'auth_mode' => 'session_delete',
'session_hash' => $this->maskSecret($hash),
));
$request = $this->buildSessionDeleteRequest($hash);
$response = $this->request(
$request->saveXML(),
'AuthSessionDelete',
self::TASK_AUTH_SESSION_DELETE,
'session_cleanup',
'session_delete',
false,
);
$document = $this->loadXml($response, 'AuthSessionDelete response');
$diagnostics = $this->extractResponseDiagnostics($document);
$this->assertApiSuccess($diagnostics, 'Session cleanup failed', 'AuthSessionDelete', true);
$this->sessionHash = null;
$this->logger->success('InterNetX session closed', array(
'auth_mode' => 'session_delete',
'session_hash' => $this->maskSecret($hash),
));
}
public function updateZoneRecords(DOMDocument $zoneDocument, string $domain, array $targets, ?string $ipv4, ?string $ipv6): void
{
if ($this->config->dryRun()) {
throw new RuntimeException('Refusing XML zone update mutation because DRY_RUN is enabled.');
}
if ($ipv4 === null && $ipv6 === null) {
throw new RuntimeException('Refusing XML zone update mutation because no usable public IP address was detected.');
}
$this->assertSessionEstablished('live zone update');
$this->config->validateProviderConfig();
$requestDocument = $this->buildUpdateRequest($zoneDocument, $domain, $targets, $ipv4, $ipv6);
$result = $this->request(
$requestDocument->saveXML(),
'ZoneUpdate',
self::TASK_ZONE_UPDATE,
'live_mutation',
'auth_session',
true,
);
$resultDocument = $this->loadXml($result, 'update zone records response');
$diagnostics = $this->extractResponseDiagnostics($resultDocument);
$this->assertApiSuccess($diagnostics, 'Live zone update failed', 'ZoneUpdate', true);
}
public function inspectTargets(string $domain, array $targets, bool $requireIpv4, bool $requireIpv6): array
{
$this->assertSessionEstablished('read-only target validation');
$this->config->validateProviderConfig();
$zoneDocument = $this->fetchZone($domain);
$records = array();
foreach ($targets as $target) {
$records[$target->host()] = array(
'ipv4' => $this->recordValue($zoneDocument, $domain, $target->subdomain(), 'A', $requireIpv4),
'ipv6' => $this->recordValue($zoneDocument, $domain, $target->subdomain(), 'AAAA', $requireIpv6),
);
}
return array(
'zone_document' => $zoneDocument,
'records' => $records,
);
}
private function fetchZone(string $domain): DOMDocument
{
$this->assertSessionEstablished('read-only zone inquiry');
$request = $this->loadXmlTemplate($this->config->xmlGetZone());
$this->replaceWithSessionAuthentication($request);
$request->getElementsByTagName('name')->item(0)->nodeValue = $domain;
$this->applyOptionalSystemNs($request);
$this->logger->info('Fetching current InterNetX zone records', array(
'domain' => $domain,
'api_call_type' => 'read_only_preflight',
'auth_mode' => 'auth_session',
'mutation' => 'false',
));
$result = $this->request(
$request->saveXML(),
'ZoneInfo',
self::TASK_ZONE_INQUIRY,
'read_only_preflight',
'auth_session',
false,
);
$document = $this->loadXml($result, 'zone lookup response');
$diagnostics = $this->extractResponseDiagnostics($document);
$this->assertApiSuccess($diagnostics, 'Read-only zone validation failed after successful session login', 'ZoneInfo', true);
return $document;
}
private function buildSessionCreateRequest(): DOMDocument
{
return $this->loadXml(sprintf(
'<?xml version="1.0" encoding="utf-8"?><request><auth><user>%s</user><context>%s</context><password>%s</password></auth><task><code>%s</code></task></request>',
htmlspecialchars($this->config->user(), ENT_XML1),
htmlspecialchars($this->config->context(), ENT_XML1),
htmlspecialchars($this->config->password(), ENT_XML1),
self::TASK_AUTH_SESSION_CREATE
), 'AuthSessionCreate request');
}
private function buildSessionDeleteRequest(string $hash): DOMDocument
{
return $this->loadXml(sprintf(
'<?xml version="1.0" encoding="utf-8"?><request><auth><user>%s</user><context>%s</context><password>%s</password></auth><task><code>%s</code><auth_session><hash>%s</hash></auth_session></task></request>',
htmlspecialchars($this->config->user(), ENT_XML1),
htmlspecialchars($this->config->context(), ENT_XML1),
htmlspecialchars($this->config->password(), ENT_XML1),
self::TASK_AUTH_SESSION_DELETE,
htmlspecialchars($hash, ENT_XML1)
), 'AuthSessionDelete request');
}
private function applyOptionalSystemNs(DOMDocument $request): void
{
$nodes = $request->getElementsByTagName('system_ns');
if ($nodes->length === 0) {
return;
}
$node = $nodes->item(0);
if ($node === null) {
return;
}
if ($this->config->systemNs() !== '') {
$node->nodeValue = $this->config->systemNs();
return;
}
if ($node->parentNode !== null) {
$node->parentNode->removeChild($node);
}
}
private function buildUpdateRequest(
DOMDocument $zoneDocument,
string $domain,
array $targets,
?string $ipv4,
?string $ipv6
): DOMDocument {
$request = $this->loadXmlTemplate($this->config->xmlPutZone());
$this->replaceWithSessionAuthentication($request);
$zone = $zoneDocument->getElementsByTagName('zone')->item(0);
if ($zone === null) {
throw new RuntimeException(sprintf('No zone payload returned for domain %s.', $domain));
}
foreach (array('created', 'changed', 'domainsafe', 'owner', 'updated_by') as $tagName) {
$node = $zone->getElementsByTagName($tagName)->item(0);
if ($node !== null && $node->parentNode !== null) {
$node->parentNode->removeChild($node);
}
}
$fragment = $request->importNode($zone, true);
$request->getElementsByTagName('task')->item(0)->appendChild($fragment);
foreach ($this->uniqueSubdomains($targets) as $subdomain) {
if ($ipv4 !== null) {
$this->replaceRecordValue($request, $subdomain, 'A', $ipv4, $domain);
}
if ($ipv6 !== null) {
$this->replaceRecordValue($request, $subdomain, 'AAAA', $ipv6, $domain);
}
}
return $request;
}
private function replaceRecordValue(
DOMDocument $request,
string $subdomain,
string $type,
string $value,
string $domain
): void {
$xpath = new DOMXPath($request);
$query = sprintf("//task/zone/rr[name='%s' and type='%s']/value", $subdomain, $type);
$entries = $xpath->query($query);
if ($entries->length !== 1) {
throw new RuntimeException(sprintf(
'DNS target matching failed after successful authenticated zone read: expected exactly one %s record for %s.%s.',
$type,
$subdomain,
$domain
));
}
$entries->item(0)->nodeValue = $value;
}
private function recordValue(DOMDocument $document, string $domain, string $subdomain, string $type, bool $required): ?string
{
$xpath = new DOMXPath($document);
$query = sprintf("//zone/rr[name='%s' and type='%s']/value", $subdomain, $type);
$entries = $xpath->query($query);
if ($entries->length > 1) {
throw new RuntimeException(sprintf(
'DNS target matching failed after successful authenticated zone read: expected exactly one %s record for %s.%s.',
$type,
$subdomain,
$domain
));
}
if ($entries->length === 0) {
if ($required) {
throw new RuntimeException(sprintf(
'DNS target matching failed after successful authenticated zone read: expected exactly one %s record for %s.%s.',
$type,
$subdomain,
$domain
));
}
return null;
}
return trim($entries->item(0)->nodeValue);
}
private function request(
string $body,
string $operation,
string $taskCode,
string $apiCallType,
string $authMode,
bool $mutation
): string {
if ($mutation && $this->config->dryRun()) {
throw new RuntimeException('Refusing XML mutation request because DRY_RUN is enabled.');
}
$context = $this->requestContext($operation, $taskCode, $apiCallType, $authMode, $mutation);
$context['payload'] = $this->sanitizeXml($body);
$this->debug('InterNetX XML request prepared', $context);
$ch = curl_init($this->config->host());
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml; charset=utf-8'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->config->connectTimeout());
curl_setopt($ch, CURLOPT_TIMEOUT, $this->config->requestTimeout());
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$response = curl_exec($ch);
if ($response === false) {
$error = curl_error($ch);
curl_close($ch);
throw new InterNetXApiException('InterNetX transport request failed: ' . $error, array_merge(
$this->requestContext($operation, $taskCode, $apiCallType, $authMode, $mutation),
array(
'transport_success' => 'false',
'session_established' => $this->hasSession() ? 'true' : 'false',
)
));
}
$statusCode = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
$responseContext = $this->requestContext($operation, $taskCode, $apiCallType, $authMode, $mutation);
$responseContext['http_status'] = $statusCode;
$responseContext['transport_success'] = $statusCode >= 200 && $statusCode < 300 ? 'true' : 'false';
$responseContext['payload'] = $this->sanitizeXml($response);
$diagnostics = array();
try {
$diagnostics = $this->extractResponseDiagnostics($this->loadXml($response, $operation . ' response diagnostics'));
$responseContext = array_merge($responseContext, $diagnostics);
$businessSuccess = $this->apiBusinessSuccess($diagnostics);
$responseContext['api_business_success'] = $businessSuccess === null ? 'unknown' : ($businessSuccess ? 'true' : 'false');
} catch (Throwable $exception) {
$responseContext['response_parse_error'] = $exception->getMessage();
$responseContext['api_business_success'] = 'unknown';
}
$this->debug('InterNetX XML response received', $responseContext);
if ($statusCode < 200 || $statusCode >= 300) {
throw new InterNetXApiException(sprintf('InterNetX transport request returned HTTP %d.', $statusCode), array_merge(
$this->requestContext($operation, $taskCode, $apiCallType, $authMode, $mutation),
$diagnostics,
array(
'http_status' => (string) $statusCode,
'transport_success' => 'false',
'session_established' => $this->hasSession() ? 'true' : 'false',
)
));
}
return $response;
}
private function requestContext(
string $operation,
string $taskCode,
string $apiCallType,
string $authMode,
bool $mutation
): array {
return array(
'operation' => $operation,
'task_code' => $taskCode,
'api_call_type' => $apiCallType,
'stage' => $this->stage,
'mutation' => $mutation ? 'true' : 'false',
'dry_run' => $this->config->dryRun() ? 'true' : 'false',
'auth_mode' => $authMode,
'session_established' => $this->hasSession() ? 'true' : 'false',
);
}
private function replaceWithSessionAuthentication(DOMDocument $request): void
{
$this->assertSessionEstablished('session authentication replacement');
$root = $request->documentElement;
if ($root === null) {
throw new RuntimeException('XML request has no root element.');
}
foreach (array('auth', 'auth_session') as $tagName) {
$node = $request->getElementsByTagName($tagName)->item(0);
if ($node !== null && $node->parentNode !== null) {
$node->parentNode->removeChild($node);
}
}
$authSession = $request->createElement('auth_session');
$authSession->appendChild($request->createElement('hash', (string) $this->sessionHash));
$insertBefore = null;
foreach ($root->childNodes as $childNode) {
if ($childNode->nodeType === XML_ELEMENT_NODE) {
$insertBefore = $childNode;
break;
}
}
if ($insertBefore === null) {
$root->appendChild($authSession);
} else {
$root->insertBefore($authSession, $insertBefore);
}
}
private function uniqueSubdomains(array $targets): array
{
$subdomains = array();
foreach ($targets as $target) {
$subdomains[$target->subdomain()] = true;
}
return array_keys($subdomains);
}
private function assertSessionEstablished(string $operation): void
{
if ($this->sessionHash !== null) {
return;
}
throw new RuntimeException(sprintf('Cannot run %s before successful InterNetX AuthSessionCreate.', $operation));
}
private function extractResponseDiagnostics(DOMDocument $document): array
{
$diagnostics = array();
$this->addFirstText($diagnostics, 'response_result_status_code', $document, '//response/result/status/code');
$this->addFirstText($diagnostics, 'response_result_status_type', $document, '//response/result/status/type');
$this->addObjectText($diagnostics, 'response_result_status_object', $document, '//response/result/status/object');
$this->addFirstText($diagnostics, 'response_result_msg_code', $document, '//response/result/msg/code');
$this->addFirstText($diagnostics, 'response_result_msg_text', $document, '//response/result/msg/text');
$this->addFirstText($diagnostics, 'stid', $document, '//response/stid');
return $diagnostics;
}
private function assertApiSuccess(array $diagnostics, string $failurePrefix, string $operation, bool $sessionExpected): void
{
$businessSuccess = $this->apiBusinessSuccess($diagnostics);
$msgText = (string) ($diagnostics['response_result_msg_text'] ?? '');
if ($businessSuccess === null) {
throw new InterNetXApiException($failurePrefix . ': InterNetX response did not include result status diagnostics.', array_merge(
$diagnostics,
array(
'operation' => $operation,
'stage' => $this->stage,
'session_established' => $this->hasSession() || $sessionExpected ? 'true' : 'false',
)
));
}
if ($businessSuccess) {
return;
}
$errorText = $msgText !== '' ? $msgText : ($diagnostics['response_result_status_object'] ?? ($diagnostics['response_result_status_code'] ?? 'business failure'));
throw new InterNetXApiException(trim($failurePrefix . ': ' . $errorText), array_merge(
$diagnostics,
array(
'operation' => $operation,
'stage' => $this->stage,
'session_established' => $this->hasSession() || $sessionExpected ? 'true' : 'false',
)
));
}
private function apiBusinessSuccess(array $diagnostics): ?bool
{
$statusType = strtolower((string) ($diagnostics['response_result_status_type'] ?? ''));
$statusCode = (string) ($diagnostics['response_result_status_code'] ?? '');
$msgCode = (string) ($diagnostics['response_result_msg_code'] ?? '');
if ($statusType === '' && $statusCode === '' && $msgCode === '') {
return null;
}
if ($statusType !== '' && !in_array($statusType, array('success', 'successful'), true)) {
return false;
}
if ($statusCode !== '' && strtoupper($statusCode[0]) === 'E') {
return false;
}
if ($msgCode !== '' && strtoupper($msgCode[0]) === 'E') {
return false;
}
return true;
}
private function firstText(DOMDocument $document, string $query): ?string
{
$xpath = new DOMXPath($document);
$entries = $xpath->query($query);
if ($entries === false || $entries->length === 0) {
return null;
}
return trim($entries->item(0)->nodeValue);
}
private function addFirstText(array &$diagnostics, string $key, DOMDocument $document, string $query): void
{
$value = $this->firstText($document, $query);
if ($value !== null && $value !== '') {
$diagnostics[$key] = $value;
}
}
private function addObjectText(array &$diagnostics, string $key, DOMDocument $document, string $query): void
{
$type = $this->firstText($document, $query . '/type');
$value = $this->firstText($document, $query . '/value');
if ($type === null && $value === null) {
return;
}
$diagnostics[$key] = trim((string) $type . ':' . (string) $value, ':');
}
private function debug(string $message, array $context = array()): void
{
if (!$this->config->debug()) {
return;
}
$this->logger->debug($message, $context);
}
private function loadXmlTemplate(string $path): DOMDocument
{
if (!is_file($path)) {
throw new RuntimeException(sprintf('XML template not found: %s', $path));
}
return $this->loadXml((string) file_get_contents($path), basename($path));
}
private function loadXml(string $xml, string $context): DOMDocument
{
$previous = libxml_use_internal_errors(true);
$document = new DOMDocument();
$loaded = $document->loadXML($xml);
libxml_clear_errors();
libxml_use_internal_errors($previous);
if (!$loaded) {
throw new RuntimeException(sprintf('Invalid XML received while processing %s.', $context));
}
$document->formatOutput = true;
return $document;
}
private function sanitizeXml(string $xml): string
{
$sanitized = preg_replace('/<password>.*?<\/password>/is', '<password>[redacted]</password>', $xml);
$sanitized = preg_replace('/<user>.*?<\/user>/is', '<user>[redacted]</user>', (string) $sanitized);
$sanitized = preg_replace('/<hash>.*?<\/hash>/is', '<hash>[redacted]</hash>', (string) $sanitized);
return trim(str_replace(array("\n", "\r"), ' ', (string) $sanitized));
}
private function maskSecret(string $value): string
{
if (strlen($value) <= 8) {
return '[redacted]';
}
return substr($value, 0, 4) . '...' . substr($value, -4);
}
}