forked from Haroldwonder/AnchorKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_config_validation.py
More file actions
837 lines (696 loc) · 39.8 KB
/
Copy pathtest_config_validation.py
File metadata and controls
837 lines (696 loc) · 39.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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
#!/usr/bin/env python3
"""
Configuration Validation Test Suite for AnchorKit
Tests parsing of TOML/JSON/env configs and validates:
- Missing required fields
- Invalid URLs
- Unsupported assets
Ensures invalid configs fail safely with proper error handling.
"""
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
from typing import Dict, Any, List, Optional
# Try to import toml/tomllib, prefer built-in for Python 3.11+
try:
import tomllib
TOML_AVAILABLE = True
except ImportError:
try:
import toml
TOML_AVAILABLE = True
except ImportError:
TOML_AVAILABLE = False
class ConfigValidationError(Exception):
"""Raised when configuration validation fails"""
pass
class ConfigValidator:
"""Validates AnchorKit configuration files"""
# Supported networks
VALID_NETWORKS = ['stellar-testnet', 'stellar-mainnet', 'stellar-futurenet', 'stellar-public']
# Supported roles for attestors
VALID_ROLES = ['kyc-issuer', 'transfer-verifier', 'compliance-approver',
'rate-provider', 'attestor', 'identity-verifier',
'settlement-bank', 'corridor-manager', 'compliance-checker',
'reserve-verifier', 'collateral-custodian', 'treasury-operator',
'risk-analyst']
# Supported asset types (for stablecoin configs)
VALID_ASSET_TYPES = ['ETH', 'BTC', 'XLM', 'USD', 'EUR', 'GBP', 'USDC', 'USDT']
# Supported currencies
VALID_CURRENCIES = ['USD', 'EUR', 'GBP', 'JPY', 'MXN', 'NGN', 'PKR']
def __init__(self, config: Dict[str, Any]):
self.config = config
self.errors: List[str] = []
self.warnings: List[str] = []
def validate(self) -> bool:
"""Run all validations and return True if valid"""
self.errors = []
self.warnings = []
self._validate_contract()
self._validate_attestors()
self._validate_sessions()
self._validate_assets()
return len(self.errors) == 0
def get_errors(self) -> List[str]:
"""Return list of validation errors"""
return self.errors
def get_warnings(self) -> List[str]:
"""Return list of validation warnings"""
return self.warnings
def _add_error(self, message: str):
"""Add an error message"""
self.errors.append(message)
def _add_warning(self, message: str):
"""Add a warning message"""
self.warnings.append(message)
def _validate_contract(self):
"""Validate contract section"""
contract = self.config.get('contract')
if contract is None:
self._add_error("Missing required section: 'contract'")
return
# Validate name
name = contract.get('name')
if name is None:
self._add_error("Missing required field: contract.name")
elif not isinstance(name, str):
self._add_error("contract.name must be a string")
elif len(name) < 1 or len(name) > 64:
self._add_error(f"contract.name must be 1-64 characters, got {len(name)}")
elif not self._is_valid_name_format(name):
self._add_error("contract.name must contain only lowercase letters, numbers, and hyphens")
# Validate version
version = contract.get('version')
if version is None:
self._add_error("Missing required field: contract.version")
elif not isinstance(version, str):
self._add_error("contract.version must be a string")
elif not self._is_valid_version(version):
self._add_error("contract.version must follow semantic versioning (e.g., 1.0.0)")
# Validate network
network = contract.get('network')
if network is None:
self._add_error("Missing required field: contract.network")
elif network not in self.VALID_NETWORKS:
self._add_error(f"contract.network must be one of: {', '.join(self.VALID_NETWORKS)}, got '{network}'")
def _validate_attestors(self):
"""Validate attestors section"""
attestors = self.config.get('attestors')
if attestors is None:
self._add_error("Missing required section: 'attestors'")
return
registry = attestors.get('registry')
if registry is None:
self._add_error("Missing required field: attestors.registry")
return
if not isinstance(registry, list):
self._add_error("attestors.registry must be an array")
return
if len(registry) == 0:
self._add_error("attestors.registry cannot be empty")
return
if len(registry) > 100:
self._add_error(f"attestors.registry cannot exceed 100 items, got {len(registry)}")
# Track names and addresses for duplicate checking
names = []
addresses = []
for idx, attestor in enumerate(registry):
self._validate_single_attestor(attestor, idx)
name = attestor.get('name')
address = attestor.get('address')
if name:
names.append(name)
if address:
addresses.append(address)
# Check for duplicates
duplicates = self._find_duplicates(names)
if duplicates:
self._add_error(f"Duplicate attestor names: {', '.join(duplicates)}")
dup_addresses = self._find_duplicates(addresses)
if dup_addresses:
self._add_error(f"Duplicate attestor addresses: {', '.join(dup_addresses)}")
# Check for at least one enabled attestor
enabled = [a for a in registry if a.get('enabled', False)]
if not enabled:
self._add_error("At least one attestor must be enabled")
def _validate_single_attestor(self, attestor: Dict[str, Any], index: int):
"""Validate a single attestor entry"""
prefix = f"attestors.registry[{index}]"
# Validate name
name = attestor.get('name')
if name is None:
self._add_error(f"{prefix}: Missing required field 'name'")
elif not isinstance(name, str):
self._add_error(f"{prefix}.name must be a string")
elif len(name) < 1 or len(name) > 64:
self._add_error(f"{prefix}.name must be 1-64 characters")
# Validate address
address = attestor.get('address')
if address is None:
self._add_error(f"{prefix}: Missing required field 'address'")
elif not isinstance(address, str):
self._add_error(f"{prefix}.address must be a string")
elif not self._is_valid_stellar_address(address):
self._add_error(f"{prefix}.address is not a valid Stellar address")
# Validate endpoint (optional but if present must be valid URL)
endpoint = attestor.get('endpoint')
if endpoint is not None:
if not isinstance(endpoint, str):
self._add_error(f"{prefix}.endpoint must be a string")
else:
url_error = self._validate_endpoint_url(endpoint)
if url_error:
self._add_error(
f"{prefix}.endpoint '{endpoint}' is not a valid URL: {url_error}"
)
# Validate role
role = attestor.get('role')
if role is None:
self._add_error(f"{prefix}: Missing required field 'role'")
elif role not in self.VALID_ROLES:
self._add_warning(f"{prefix}.role '{role}' is not a standard role")
def _validate_sessions(self):
"""Validate sessions section"""
sessions = self.config.get('sessions')
if sessions is None:
# Sessions are optional, just warn
self._add_warning("Optional section 'sessions' not provided, using defaults")
return
timeout = sessions.get('session_timeout_seconds')
if timeout is not None:
if not isinstance(timeout, int):
self._add_error("sessions.session_timeout_seconds must be an integer")
elif timeout < 1:
self._add_error(f"sessions.session_timeout_seconds must be at least 1, got {timeout}")
elif timeout > 86400:
self._add_error(f"sessions.session_timeout_seconds cannot exceed 86400, got {timeout}")
max_ops = sessions.get('operations_per_session')
if max_ops is not None:
if not isinstance(max_ops, int):
self._add_error("sessions.operations_per_session must be an integer")
elif max_ops < 1:
self._add_error(f"sessions.operations_per_session must be at least 1, got {max_ops}")
elif max_ops > 10000:
self._add_error(f"sessions.operations_per_session cannot exceed 10000, got {max_ops}")
def _validate_assets(self):
"""Validate assets in various config sections"""
# Check stablecoin collateral types
stablecoin = self.config.get('stablecoin')
if stablecoin:
collateral_types = stablecoin.get('collateral_types', [])
for idx, ct in enumerate(collateral_types):
symbol = ct.get('symbol')
if symbol and symbol not in self.VALID_ASSET_TYPES:
self._add_warning(f"stablecoin.collateral_types[{idx}].symbol '{symbol}' is not a standard asset")
# Check compliance currencies
compliance = self.config.get('compliance')
if compliance:
supported_currencies = compliance.get('supported_currencies', [])
for currency in supported_currencies:
if currency not in self.VALID_CURRENCIES:
self._add_warning(f"compliance.supported_currencies contains unsupported currency: {currency}")
def _is_valid_name_format(self, name: str) -> bool:
"""Check if name contains only allowed characters"""
import re
return bool(re.match(r'^[a-z0-9-]+$', name))
def _is_valid_version(self, version: str) -> bool:
"""Check if version follows semantic versioning"""
import re
return bool(re.match(r'^\d+\.\d+\.\d+$', version))
def _is_valid_stellar_address(self, address: str) -> bool:
"""Validate Stellar address format"""
if not address:
return False
if not address.startswith('G'):
return False
if len(address) < 54 or len(address) > 56:
return False
# Allow placeholder addresses (X, Y, Z used in example configs)
# Check remaining characters are alphanumeric or +/
return all(c.isalnum() or c in ['+', '/', 'X', 'Y', 'Z'] for c in address[1:])
def _validate_endpoint_url(self, url: str) -> str:
"""Validate endpoint URL using the same rules as validate_anchor_domain.
Returns an empty string on success, or a human-readable reason on failure.
"""
if not url or not url.strip():
return "URL must not be empty"
if len(url) < 10:
return "URL too short (minimum 10 characters, e.g. https://a.b)"
if len(url) > 2048:
return "URL too long (maximum 2048 characters)"
# HTTPS is required — http:// and other schemes are rejected
if not url.startswith("https://"):
return "URL must use HTTPS (http:// and other schemes are not allowed)"
# Reject control characters and forbidden chars anywhere in the URL
if "%00" in url:
return "URL must not contain a null byte"
for ch in url:
if ch < '\x20' or ch == '\x7f' or ch in '<>{}|\\':
return f"URL contains forbidden character {ch!r}"
# Isolate the host (strip scheme, path, query, fragment)
after_scheme = url[8:] # skip "https://"
host_part = after_scheme.split('/')[0].split('?')[0].split('#')[0]
if not host_part:
return "URL has no host after scheme"
if ' ' in host_part:
return "URL host must not contain spaces"
# Optional port
domain = host_part
if ':' in host_part:
colon = host_part.rfind(':')
port_str = host_part[colon + 1:]
if not port_str:
return "URL port is empty after colon"
if not port_str.isdigit():
return f"URL port '{port_str}' is not numeric"
port = int(port_str)
if port == 0 or port > 65535:
return f"URL port {port} is out of valid range (1-65535)"
domain = host_part[:colon]
if not domain:
return "URL has no domain"
# Reject loopback
lower = domain.lower()
if (lower == "localhost"
or lower.startswith("localhost.")
or lower.endswith(".localhost")):
return "URL must not use loopback address (localhost)"
# Must have a TLD (at least one dot, two non-empty labels)
if '.' not in domain:
return "URL domain must have a TLD (e.g. example.com, not just 'example')"
if domain.startswith('.') or domain.endswith('.'):
return "URL domain must not start or end with a dot"
if '..' in domain:
return "URL domain must not contain consecutive dots"
labels = domain.split('.')
non_empty = [l for l in labels if l]
if len(non_empty) < 2:
return "URL domain must have at least two labels (e.g. example.com)"
# Reject raw IPv4 (all-numeric labels)
if all(l.isdigit() for l in labels):
return "URL must use a domain name, not a raw IP address"
for label in labels:
if not label:
return "URL domain contains an empty label"
if len(label) > 63:
return f"URL domain label '{label}' exceeds 63 characters"
if not label[0].isascii() or not label[0].isalnum():
return f"URL domain label '{label}' must start with an alphanumeric character"
if not label[-1].isascii() or not label[-1].isalnum():
return f"URL domain label '{label}' must end with an alphanumeric character"
# Reject Punycode (homograph attack vector)
if label.lower().startswith("xn--"):
return f"URL domain label '{label}' uses Punycode (xn--), which is not allowed"
for ch in label:
if not (ch.isascii() and (ch.isalnum() or ch == '-')):
return f"URL domain label '{label}' contains invalid character {ch!r}"
return "" # valid
def _find_duplicates(self, items: List[str]) -> List[str]:
"""Find duplicate items in a list"""
seen = set()
duplicates = set()
for item in items:
if item in seen:
duplicates.add(item)
seen.add(item)
return list(duplicates)
def load_config(file_path: str) -> Dict[str, Any]:
"""Load configuration from file (TOML or JSON)"""
path = Path(file_path)
if not path.exists():
raise ConfigValidationError(f"Config file not found: {file_path}")
suffix = path.suffix.lower()
if suffix == '.toml':
if not TOML_AVAILABLE:
raise ConfigValidationError("TOML parsing not available. Install with: pip install toml")
with open(path, 'rb') as f:
try:
return tomllib.load(f)
except NameError:
# Fallback to toml library
with open(path, 'r') as f_toml:
return toml.load(f_toml)
elif suffix == '.json':
with open(path, 'r') as f:
return json.load(f)
else:
raise ConfigValidationError(f"Unsupported file format: {suffix}")
def validate_config_file(file_path: str) -> tuple[bool, List[str], List[str]]:
"""Validate a configuration file and return (is_valid, errors, warnings)"""
try:
config = load_config(file_path)
validator = ConfigValidator(config)
is_valid = validator.validate()
return is_valid, validator.get_errors(), validator.get_warnings()
except ConfigValidationError as e:
return False, [str(e)], []
except Exception as e:
return False, [f"Unexpected error: {str(e)}"], []
# ============================================================
# TEST CASES
# ============================================================
class TestConfigValidation(unittest.TestCase):
"""Test cases for configuration validation"""
def test_valid_toml_config(self):
"""Test that a valid TOML config parses correctly"""
config = {
"contract": {
"name": "test-anchor",
"version": "1.0.0",
"network": "stellar-testnet"
},
"attestors": {
"registry": [
{
"name": "test-attestor",
"address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF",
"endpoint": "https://example.com/verify",
"role": "attestor",
"enabled": True
}
]
}
}
validator = ConfigValidator(config)
is_valid = validator.validate()
self.assertTrue(is_valid, f"Expected valid config but got errors: {validator.get_errors()}")
self.assertEqual(len(validator.get_errors()), 0)
def test_valid_json_config(self):
"""Test that a valid JSON config parses correctly"""
config = {
"contract": {
"name": "json-anchor",
"version": "1.0.0",
"network": "stellar-mainnet"
},
"attestors": {
"registry": [
{
"name": "json-attestor",
"address": "GBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
"endpoint": "https://json.example.com/verify",
"role": "kyc-issuer",
"enabled": True
}
]
},
"sessions": {
"session_timeout_seconds": 3600,
"operations_per_session": 1000
}
}
validator = ConfigValidator(config)
is_valid = validator.validate()
self.assertTrue(is_valid, f"Expected valid config but got errors: {validator.get_errors()}")
# Missing required fields tests
def test_missing_contract_section(self):
"""Test that missing contract section fails validation"""
config = {"attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://example.com", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
self.assertTrue(any("contract" in e.lower() for e in validator.get_errors()))
def test_missing_contract_name(self):
"""Test that missing contract.name fails validation"""
config = {"contract": {"version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://example.com", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
self.assertTrue(any("name" in e.lower() for e in validator.get_errors()))
def test_missing_contract_version(self):
"""Test that missing contract.version fails validation"""
config = {"contract": {"name": "test", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://example.com", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
self.assertTrue(any("version" in e.lower() for e in validator.get_errors()))
def test_missing_contract_network(self):
"""Test that missing contract.network fails validation"""
config = {"contract": {"name": "test", "version": "1.0.0"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://example.com", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
self.assertTrue(any("network" in e.lower() for e in validator.get_errors()))
def test_missing_attestors_section(self):
"""Test that missing attestors section fails validation"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
self.assertTrue(any("attestors" in e.lower() for e in validator.get_errors()))
def test_missing_attestor_name(self):
"""Test that missing attestor name fails validation"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://example.com", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
self.assertTrue(any("name" in e.lower() for e in validator.get_errors()))
def test_missing_attestor_address(self):
"""Test that missing attestor address fails validation"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "endpoint": "https://example.com", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
self.assertTrue(any("address" in e.lower() for e in validator.get_errors()))
def test_missing_attestor_role(self):
"""Test that missing attestor role fails validation"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://example.com", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
self.assertTrue(any("role" in e.lower() for e in validator.get_errors()))
# Invalid URLs tests
def test_invalid_endpoint_url_too_short(self):
"""Test that URL too short fails validation"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "http://a.b", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
self.assertTrue(any("url" in e.lower() for e in validator.get_errors()))
def test_invalid_endpoint_url_no_protocol(self):
"""Test that URL without http/https fails validation"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "example.com/verify", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
self.assertTrue(any("url" in e.lower() for e in validator.get_errors()))
def test_invalid_endpoint_url_wrong_format(self):
"""Test that URL with wrong format fails validation"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "not-a-url-at-all", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
self.assertTrue(any("url" in e.lower() for e in validator.get_errors()))
def test_invalid_endpoint_url_http_rejected(self):
"""http:// must be rejected — HTTPS is required"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "http://example.com/verify", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
errors = validator.get_errors()
self.assertTrue(any("url" in e.lower() for e in errors))
# Error message must include the invalid URL
self.assertTrue(any("http://example.com/verify" in e for e in errors))
def test_invalid_endpoint_url_localhost_rejected(self):
"""Loopback addresses must be rejected"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://localhost/verify", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
errors = validator.get_errors()
self.assertTrue(any("url" in e.lower() for e in errors))
self.assertTrue(any("https://localhost/verify" in e for e in errors))
def test_invalid_endpoint_url_no_tld(self):
"""Single-label domain with no TLD must be rejected"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://intranet/verify", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
errors = validator.get_errors()
self.assertTrue(any("url" in e.lower() for e in errors))
self.assertTrue(any("https://intranet/verify" in e for e in errors))
def test_invalid_endpoint_url_consecutive_dots(self):
"""Consecutive dots in domain must be rejected"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://example..com/verify", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
errors = validator.get_errors()
self.assertTrue(any("url" in e.lower() for e in errors))
self.assertTrue(any("https://example..com/verify" in e for e in errors))
def test_invalid_endpoint_url_invalid_port(self):
"""Out-of-range port must be rejected"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://example.com:99999/verify", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
errors = validator.get_errors()
self.assertTrue(any("url" in e.lower() for e in errors))
self.assertTrue(any("https://example.com:99999/verify" in e for e in errors))
def test_invalid_endpoint_url_raw_ip(self):
"""Raw IPv4 addresses must be rejected"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://192.168.1.1/verify", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
errors = validator.get_errors()
self.assertTrue(any("url" in e.lower() for e in errors))
self.assertTrue(any("https://192.168.1.1/verify" in e for e in errors))
def test_valid_endpoint_url_with_port(self):
"""Valid HTTPS URL with a port must pass"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://example.com:8443/verify", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertTrue(validator.validate(), f"Expected valid but got: {validator.get_errors()}")
def test_valid_endpoint_url_with_path_and_query(self):
"""Valid HTTPS URL with path and query string must pass"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://api.example.com/v1/verify?asset=USDC", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertTrue(validator.validate(), f"Expected valid but got: {validator.get_errors()}")
# Unsupported assets tests
def test_unsupported_collateral_asset(self):
"""Test that unsupported collateral asset generates warning"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://example.com", "role": "attestor", "enabled": True}]}, "stablecoin": {"collateral_types": [{"name": "unknown", "symbol": "UNSUPPORTED", "liquidation_ratio": 1.5}]}}
validator = ConfigValidator(config)
is_valid = validator.validate()
self.assertTrue(is_valid)
self.assertTrue(len(validator.get_warnings()) > 0)
def test_unsupported_currency(self):
"""Test that unsupported currency generates warning"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://example.com", "role": "attestor", "enabled": True}]}, "compliance": {"supported_currencies": ["USD", "UNKNOWN_CURRENCY"]}}
validator = ConfigValidator(config)
is_valid = validator.validate()
self.assertTrue(is_valid)
self.assertTrue(len(validator.get_warnings()) > 0)
# Invalid network tests
def test_invalid_network(self):
"""Test that invalid network fails validation"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "invalid-network"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://example.com", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
self.assertTrue(any("network" in e.lower() for e in validator.get_errors()))
# Invalid Stellar address tests
def test_invalid_stellar_address_wrong_prefix(self):
"""Test that Stellar address with wrong prefix fails validation"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "ABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", "endpoint": "https://example.com", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
self.assertTrue(any("stellar" in e.lower() or "address" in e.lower() for e in validator.get_errors()))
def test_invalid_stellar_address_wrong_length(self):
"""Test that Stellar address with wrong length fails validation"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GBBBBBB", "endpoint": "https://example.com", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
self.assertTrue(any("address" in e.lower() for e in validator.get_errors()))
# Invalid session config tests
def test_invalid_session_timeout_too_low(self):
"""Test that session timeout of 0 or any value below 1 fails validation"""
base_config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://example.com", "role": "attestor", "enabled": True}]}}
for bad_timeout in [0, -1, -100]:
with self.subTest(session_timeout_seconds=bad_timeout):
config = {**base_config, "sessions": {"session_timeout_seconds": bad_timeout}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
self.assertTrue(any("timeout" in e.lower() for e in validator.get_errors()))
def test_invalid_session_timeout_too_high(self):
"""Test that session timeout too high fails validation"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://example.com", "role": "attestor", "enabled": True}]}, "sessions": {"session_timeout_seconds": 100000}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
self.assertTrue(any("timeout" in e.lower() for e in validator.get_errors()))
# Empty registry tests
def test_empty_attestor_registry(self):
"""Test that empty attestor registry fails validation"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": []}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
self.assertTrue(any("empty" in e.lower() for e in validator.get_errors()))
def test_no_enabled_attestor(self):
"""Test that no enabled attestor fails validation"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "test", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://example.com", "role": "attestor", "enabled": False}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
self.assertTrue(any("enabled" in e.lower() for e in validator.get_errors()))
# Duplicate tests
def test_duplicate_attestor_names(self):
"""Test that duplicate attestor names fail validation"""
config = {"contract": {"name": "test", "version": "1.0.0", "network": "stellar-testnet"}, "attestors": {"registry": [{"name": "duplicate", "address": "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", "endpoint": "https://example1.com", "role": "attestor", "enabled": True}, {"name": "duplicate", "address": "GBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", "endpoint": "https://example2.com", "role": "attestor", "enabled": True}]}}
validator = ConfigValidator(config)
self.assertFalse(validator.validate())
self.assertTrue(any("duplicate" in e.lower() for e in validator.get_errors()))
# Safe failure tests - invalid configs should fail safely
def test_invalid_config_fails_safely_with_errors(self):
"""Test that invalid config fails safely with clear error messages"""
config = {}
validator = ConfigValidator(config)
is_valid = validator.validate()
self.assertFalse(is_valid)
errors = validator.get_errors()
self.assertTrue(len(errors) > 0)
for error in errors:
self.assertTrue(len(error) > 0)
def test_malformed_json_fails_safely(self):
"""Test that malformed JSON fails safely"""
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
f.write('{ invalid json }')
temp_path = f.name
try:
is_valid, errors, warnings = validate_config_file(temp_path)
self.assertFalse(is_valid)
self.assertTrue(len(errors) > 0)
finally:
os.unlink(temp_path)
def test_missing_config_file_fails_safely(self):
"""Test that missing config file fails safely"""
is_valid, errors, warnings = validate_config_file('/nonexistent/path/config.json')
self.assertFalse(is_valid)
self.assertTrue(len(errors) > 0)
def main():
"""Main function to run tests and validate configs"""
import argparse
parser = argparse.ArgumentParser(description='Validate AnchorKit configurations')
parser.add_argument('--test', action='store_true', help='Run unit tests')
parser.add_argument('--validate-all', action='store_true', help='Validate all config files')
parser.add_argument('config_file', nargs='?', help='Config file to validate')
args = parser.parse_args()
if args.test:
print("Running configuration validation tests...")
print("=" * 60)
unittest.main(argv=[''], exit=False, verbosity=2)
return
if args.validate_all:
config_dir = Path('configs')
if not config_dir.exists():
print(f"Error: configs directory not found")
sys.exit(1)
config_files = list(config_dir.glob('*.toml')) + list(config_dir.glob('*.json'))
if not config_files:
print("No config files found")
sys.exit(1)
print(f"Validating {len(config_files)} configuration files...")
print("=" * 60)
errors_found = []
for config_file in config_files:
is_valid, errors, warnings = validate_config_file(str(config_file))
if warnings:
print(f"\n⚠️ {config_file.name}:")
for warning in warnings:
print(f" {warning}")
if is_valid:
print(f"✅ {config_file.name}")
else:
print(f"❌ {config_file.name}:")
for error in errors:
print(f" • {error}")
errors_found.append(config_file.name)
print("\n" + "=" * 60)
if errors_found:
print(f"❌ Validation failed for: {', '.join(errors_found)}")
sys.exit(1)
else:
print(f"✅ All {len(config_files)} configuration files are valid")
return
if args.config_file:
is_valid, errors, warnings = validate_config_file(args.config_file)
print(f"Validating {args.config_file}...")
print("=" * 60)
if warnings:
print("\n⚠️ Warnings:")
for warning in warnings:
print(f" {warning}")
if is_valid:
print("\n✅ Configuration is valid")
sys.exit(0)
else:
print("\n❌ Configuration is invalid:")
for error in errors:
print(f" • {error}")
sys.exit(1)
parser.print_help()
if __name__ == '__main__':
main()