countersign-gateway 0.2.1

Forward proxy for user-approved client certificate authentication
Documentation
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
"""Exercise real Linux Gateway processes against a test-only grant authority and mTLS site.

Usage: python3 crates/countersign-gateway/tests/runtime.py target/debug/countersign-gateway
           [--worker-sandbox namespaces|filter] [--startup-fails LAYER]
Requires libnss-wrapper, curl with HTTPS proxy support, and python-cryptography, and bubblewrap
for the namespace sandbox. --startup-fails is for a host that refuses LAYER of the chosen worker
sandbox: the Gateway has to exit with the error that names the sandbox and that layer.
No host DNS or trust store modifications.
"""
import base64
import concurrent.futures
import contextlib
import datetime
import hashlib
import http.server
import json
import os
import re
from pathlib import Path
import signal
import socket
import ssl
import subprocess
import sys
import tempfile
import threading
import time

from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID


def identity(directory, name, issuer=None, hosts=()):
    key = ec.generate_private_key(ec.SECP256R1())
    subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)])
    signer, issuer_name = (key, subject) if issuer is None else (issuer[0], issuer[1].subject)
    now = datetime.datetime.now(datetime.timezone.utc)
    ca = issuer is None
    builder = (x509.CertificateBuilder().issuer_name(issuer_name).subject_name(subject)
               .public_key(key.public_key()).serial_number(x509.random_serial_number())
               .not_valid_before(now - datetime.timedelta(minutes=1))
               .not_valid_after(now + datetime.timedelta(days=1))
               .add_extension(x509.BasicConstraints(ca, 0 if ca else None), critical=True)
               .add_extension(x509.KeyUsage(True, False, False, False, False, ca, ca, False, False), True))
    if not ca:
        usage = ExtendedKeyUsageOID.SERVER_AUTH if hosts else ExtendedKeyUsageOID.CLIENT_AUTH
        builder = builder.add_extension(x509.ExtendedKeyUsage([usage]), False)
    if hosts:
        builder = builder.add_extension(x509.SubjectAlternativeName([x509.DNSName(h) for h in hosts]), False)
    cert = builder.sign(signer, hashes.SHA256())
    path = directory / f'{name}.pem'
    path.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
    (directory / f'{name}.key').write_bytes(key.private_bytes(serialization.Encoding.PEM,
        serialization.PrivateFormat.PKCS8, serialization.NoEncryption()))
    return key, cert


def publish_crl(path, ca, serial, deadline):
    key, issuer = ca
    now = datetime.datetime.now(datetime.timezone.utc)
    crl = (x509.CertificateRevocationListBuilder().issuer_name(issuer.subject)
           .last_update(now - datetime.timedelta(seconds=1)).next_update(deadline)
           .add_extension(x509.CRLNumber(serial), False)
           .add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()), False)
           .sign(key, hashes.SHA256()))
    temporary = path.with_suffix('.tmp')
    temporary.write_bytes(crl.public_bytes(serialization.Encoding.DER))
    temporary.replace(path)


def b64(data):
    return base64.b64encode(data).decode('ascii')


def token(workload):
    # The test authority accepts only these exact, pre-registered tokens.
    body = json.dumps({'aud': 'countersign:gateway:workload', 'binding': workload}).encode()
    return 'fixture.' + base64.urlsafe_b64encode(body).decode().rstrip('=') + '.fixture'


class Fixture(http.server.ThreadingHTTPServer):
    daemon_threads = True

    def handle_error(self, request, client_address):
        # Cancelling an outstanding poll or forcibly cutting off either TLS leg
        # can reset the fixture socket while the HTTP library is reading it.
        if not isinstance(sys.exc_info()[1], (BrokenPipeError, ConnectionResetError, ssl.SSLEOFError)):
            super().handle_error(request, client_address)


class Site(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        fingerprint = hashlib.sha256(self.connection.getpeercert(binary_form=True)).hexdigest().encode()
        if self.path == '/slow':
            self.send_response(200)
            self.send_header('content-length', '1000000')
            self.end_headers()
            self.wfile.write(b'x')
            self.server.slow_started.set()
            self.connection.settimeout(25)
            # Any end of the upstream leg counts as cutoff; only a read that
            # times out with the leg still open does not. Why (2026-11-20, #29):
            # under load on an aarch64 host, recv on a leg the Gateway had
            # closed raised BrokenPipeError on 4 of 10 runs.
            try:
                ended = not self.connection.recv(1)
            except TimeoutError:
                ended = False
            except OSError:  # ssl.SSLError is an OSError too
                ended = True
            if ended:
                self.server.cutoff.set()
            return
        self.send_response(200)
        self.send_header('content-length', str(len(fingerprint)))
        self.end_headers()
        self.wfile.write(fingerprint)

    def log_message(self, *args):
        pass


class Broker(http.server.BaseHTTPRequestHandler):
    def do_POST(self):
        authority = self.server
        token = self.headers.get('Authorization', '').removeprefix('Bearer ')
        if token not in authority.accounts or not self.headers.get('X-Countersign-Gateway-Instance'):
            self.send_error(403)
            return
        user, key, grant = authority.accounts[token]
        if authority.shared and self.headers.get('X-Countersign-Gateway') != authority.service_secret:
            self.send_error(403)
            return
        frame = json.loads(self.rfile.read(int(self.headers['content-length'])))
        body = frame['body']
        now = int(time.time() * 1000)
        msg = frame['type']
        if msg in ('connect', 'lookup') and body['workload'] == grant['workload'] and body['host'] == authority.host:
            kind = 'activate'
            value = {'activation': {'grant': grant, 'offer': user, 'approval': user,
                                     'expires_at_ms': authority.expires_at},
                     'chain': [authority.public[user]]}
        elif msg == 'watch' and body == grant:
            retired = authority.retired[user].wait(5)
            kind, value = ('retire' if retired else 'no_change'), grant
        elif msg == 'observed' and body['grant'] == grant and body['host'] == authority.host:
            kind = 'observed'
            value = body
            with authority.observation_change:
                received = authority.observations.setdefault((user,body['tls_connection']),set())
                received.add(body['observation'])
                authority.observation_change.notify_all()
        elif msg == 'renew_lease' and body['grant'] == grant:
            kind = 'lease'
            budget = 2000 if user == 'alice' else 30000
            value = {'binding': body, 'disposition': {'granted': {'budget_ms': budget, 'valid_until_ms': now + budget}}}
        elif msg == 'sign' and body['binding']['grant'] == grant and body['binding']['host'] == authority.host:
            assert body['tls'] == 'tls13' and body['scheme'] == 'ecdsa_nistp256_sha256'
            transcript = base64.b64decode(body['certificate_verify'], validate=True)
            assert transcript.startswith(b' ' * 64 + b'TLS 1.3, client CertificateVerify\x00')
            kind = 'signed'
            value = {'binding': body['binding'], 'signature': b64(key.sign(transcript, ec.ECDSA(hashes.SHA256())))}
        else:
            self.send_error(403)
            return
        reply = json.dumps({'version': 1, 'request_id': frame['request_id'], 'type': kind, 'body': value}).encode()
        self.send_response(200)
        self.send_header('content-length', str(len(reply)))
        self.end_headers()
        self.wfile.write(reply)

    def log_message(self, *args):
        pass


@contextlib.contextmanager
def server(addr, handler, tls):
    httpd = Fixture((addr, 0), handler)
    httpd.socket = tls.wrap_socket(httpd.socket, server_side=True)
    thread = threading.Thread(target=httpd.serve_forever, daemon=True)
    thread.start()
    try:
        yield httpd
    finally:
        httpd.shutdown()
        httpd.server_close()
        thread.join()


def startup_failure(binary, config, sandbox, layer):
    """A host that refuses the chosen worker sandbox stops the Gateway at startup."""
    other = {'namespaces': 'filter', 'filter': 'namespaces'}[sandbox]
    result = subprocess.run([binary, 'serve', str(config)], capture_output=True, text=True, timeout=20)
    sys.stderr.write(result.stderr)
    assert result.returncode != 0, 'The Gateway started under a worker sandbox this host was expected to refuse'
    assert not result.stdout, result.stdout
    lines = result.stderr.splitlines()
    assert len(lines) == 2, lines
    # The sandbox, the layer that failed, then the cause.
    assert re.fullmatch(rf'worker sandbox "{sandbox}" failed: {re.escape(layer)}: \S.*', lines[0]), lines
    assert 'operate/#choose-a-worker-sandbox' in lines[1], lines
    # Neither a fallback nor a hint at one: the other value is never named.
    assert f'"{other}"' not in result.stderr, lines


def configuration_loading(dir, binary, config):
    """`worker_sandbox` is optional and takes two values. Anything else fails loading."""
    path = dir / 'worker-sandbox.json'
    without = {key: value for key, value in config.items() if key != 'worker_sandbox'}
    def loads(**field):
        path.write_text(json.dumps({**without, **field}))
        return subprocess.run([binary, 'env', str(path)], capture_output=True, timeout=10).returncode == 0
    assert loads()
    for value in ('namespaces', 'filter'):
        assert loads(worker_sandbox=value), value
    for value in ('seccomp', 'Filter', 'none', '', None, True, ['filter']):
        assert not loads(worker_sandbox=value), value


def do_test(dir, binary, ip,site, broker, identities, ca, shared, filter_kill=False, sandbox=None,
            startup_fails=None):
    host = f'site.test:{site.server_port}'
    broker.host = host
    broker.accounts = {}
    broker.retired = {user: threading.Event() for user in identities}
    broker.public = {}
    broker.observations = {}
    broker.observation_change = threading.Condition()
    broker.shared = shared
    broker.service_secret = 'secret-' * 8
    broker.expires_at = int(time.time()*1000) + 90000
    (dir/'service').write_text(broker.service_secret)
    bindings = {}
    for user, (key, cert) in identities.items():
        principal = 'alice' if user == 'alice-other-context' else user
        workload = {'integrator':'local','user':principal,'context':user,'workload':user,'workload_generation':1}
        der = cert.public_bytes(serialization.Encoding.DER)
        grant = {'workload':workload,'grant':user,'grant_version':1,'worker':user,'worker_generation':1,
                 'scope':{'entry_id':'site','entry_version':1,'pattern':host},
                 'device':{'pairing':user,'key':user,'channel_generation':1}, 'cert_sha256':b64(hashlib.sha256(der).digest())}
        bindings[user] = workload
        broker.public[user] = b64(der)
        broker.accounts[token(workload)] = (user,key,grant)
    with socket.socket() as tmp:
        tmp.bind(('127.0.0.1',0))
        port = tmp.getsockname()[1]
    pub = dir / ('ca.pem' if shared else 'public.pem')
    proxy = ('https' if shared else 'http') + f'://localhost:{port}'
    config = {'listen':f'127.0.0.1:{port}', 'proxy_url':proxy,'ca_output':str(pub),
              'broker_url':f'https://localhost:{broker.server_port}', 'broker_ca':str(dir/'ca.pem'),
              'clock_uncertainty_ms':100,
              'destinations':[{'id':'site','version':1,'pattern':host,'roots':str(dir/'ca.pem'),'private_networks':[ip+'/32']}]}
    if shared:
        crl = dir / 'site.crl'
        publish_crl(crl, ca, 1, datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=5))
        config['destinations'][0]['revocation'] = {'kind':'crl', 'files':[str(crl)]}
        config['shared']={'listener_cert':str(dir/'listener.pem'),'listener_key':str(dir/'listener.key'),
                          'gateway_token':str(dir/'service'),
                          'ca':{'type':'local','cert':str(dir/'ca.pem'),'key':str(dir/'ca.key')}}
    else:
        (dir/'sidecar.token').write_text(token(bindings['alice']))
        config.update(workload=bindings['alice'],workload_token=str(dir/'sidecar.token'))
    if sandbox:
        config['worker_sandbox'] = sandbox
    (dir/'config.json').write_text(json.dumps(config))
    if startup_fails:
        return startup_failure(binary, dir/'config.json', sandbox or 'namespaces', startup_fails)
    configuration_loading(dir, binary, config)
    hosts = dir/'hosts'
    hosts.write_text('127.0.0.1 localhost\n'+ip+' site.test\n')
    # Override /etc/hosts only for the Gateway parent. Grant workers are then
    # isolated by the production launcher and receive only preconnected streams.
    library = os.environ.get('NSS_WRAPPER_LIBRARY') or str(next(Path('/usr/lib').glob('*/libnss_wrapper.so')))
    with subprocess.Popen([binary,'serve',str(dir/'config.json')], stderr=subprocess.PIPE, text=True,
                          env={**os.environ,'LD_PRELOAD':library,'NSS_WRAPPER_HOSTS':str(hosts)}) as child:
        log = []
        logged = threading.Condition()
        def follow():
            for line in child.stderr:
                sys.stderr.write(line)
                with logged:
                    log.append(line.rstrip('\n'))
                    logged.notify_all()
        threading.Thread(target=follow, daemon=True).start()
        def wait_for_log(pattern, timeout=4):
            with logged:
                return logged.wait_for(lambda: any(re.fullmatch(pattern, line) for line in log), timeout)
        def alive(pid):
            # A killed process stays listed until its new parent collects it.
            try:
                return Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()[0] != 'Z'
            except FileNotFoundError:
                return False
        def descendants(pid):
            child_list = Path(f'/proc/{pid}/task/{pid}/children')
            direct = [int(c) for c in child_list.read_text().split()]
            return direct + [p for c in direct for p in descendants(c)]
        try:
            for _ in range(100):
                if child.poll() is not None:
                    raise RuntimeError(f'Gateway exited {child.returncode}')
                try:
                    with socket.create_connection(('127.0.0.1',port),timeout=.2):
                        break
                except OSError:
                    threading.Event().wait(.05)
            else:
                raise RuntimeError('Gateway did not start')
            # Startup names the worker sandbox and every layer its probe worker applied.
            assert wait_for_log(('Gateway worker sandbox "filter": ' if sandbox == 'filter' else
                                 'Gateway worker sandbox "namespaces": namespaces, ') + 'non-dumpable, '
                                r'Landlock (ABI v[1-9]\d*|unavailable), seccomp allow-list'), log
            def request(user,extra=(),path='/', timeout=8):
                args=['curl','--silent','--show-error','--fail','--max-time',str(timeout),'--noproxy','','--proxy',proxy,
                      '--proxy-cacert',str(dir/'ca.pem'),'--cacert',str(pub)]
                if shared:
                    args+=['--proxy-header','Proxy-Authorization: Bearer '+token(bindings[user])]
                return subprocess.run(args + list(extra) + ['https://'+host+path], capture_output=True, timeout=timeout+2)
            users = list(identities) if shared else ['alice']
            def launched_directly():
                # The filter sandbox starts each grant worker itself: every process
                # under the Gateway runs the Gateway's executable, started by the Gateway.
                workers = descendants(child.pid)
                assert workers, 'grant worker missing'
                for pid in workers:
                    status = Path(f'/proc/{pid}/status').read_text()
                    assert re.search(rf'^PPid:\t{child.pid}$', status, re.M), status
                    assert re.search(r'^Name:\tcountersign-gat', status, re.M), status
            if filter_kill:
                # Only Alice's grant worker runs. A grant worker the allow-list
                # kills dies of SIGSYS, so deliver that signal to it: the
                # supervisor cannot tell the two apart.
                first = request('alice')
                assert first.returncode == 0, first.stderr
                if sandbox == 'filter':
                    launched_directly()
                leaves = [pid for pid in descendants(child.pid) if not descendants(pid)]
                assert len(leaves) == 1, leaves
                os.kill(leaves[0], signal.SIGSYS)
                assert wait_for_log(r"Gateway grant alice: grant worker killed by the worker sandbox's filter \(SIGSYS\); "
                                    r'grant fenced'), log
                assert request('alice').returncode != 0, 'A grant whose worker the filter killed was served again'
                assert request('bob').returncode == 0, "Alice's killed grant worker affected Bob"
                # A fresh approval is a new grant, which gets a new grant worker.
                broker.accounts[token(bindings['alice'])][2].update(grant='alice-approved-again')
                assert request('alice').returncode == 0, 'A fresh approval did not restore service'
                # No grant worker outlives its supervisor, however the supervisor ends.
                workers = descendants(child.pid)
                assert len(workers) >= 2, workers
                child.kill()
                for _ in range(40):
                    if not any(alive(pid) for pid in workers):
                        break
                    threading.Event().wait(.05)
                else:
                    raise AssertionError('A grant worker outlived its supervisor')
                return
            with concurrent.futures.ThreadPoolExecutor(max_workers=len(users)) as pool:
                results = list(pool.map(request,users))
            for user,res in zip(users,results):
                assert res.returncode==0,(user,res.stderr)
                expected=identities[user][1].fingerprint(hashes.SHA256()).hex().encode()
                assert res.stdout==expected,(user,res.stdout)
            if sandbox == 'filter':
                launched_directly()
            expected_events = {'mtls_accepted','ingress_closed','egress_closed'}
            with broker.observation_change:
                for user in users:
                    assert broker.observation_change.wait_for(
                        lambda: any(owner == user and events == expected_events
                                    for (owner, _), events in broker.observations.items()), timeout=4
                    ), (user, broker.observations)
            res=request(users[0],['-H','Host: forbidden.test'])
            assert res.returncode!=0, res.stdout
            site.cutoff = threading.Event()
            site.slow_started = threading.Event()
            begin = time.monotonic()
            with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
                future = pool.submit(request,'alice',(),'/slow')
                assert site.slow_started.wait(4), 'TLS connection did not reach site'
                if not shared:
                    # The only grant belongs to Alice. Stop all of this launcher's
                    # descendants, including the worker. Both network relays must
                    # still enforce cutoff, without help from any child process.
                    workers = descendants(child.pid)
                    assert workers, 'isolated worker missing'
                    for pid in workers:
                        os.kill(pid,signal.SIGSTOP)
                alice = future.result(timeout=6)
            assert alice.returncode != 0 and len(alice.stdout) < 2, (alice.returncode, alice.stdout)
            assert site.cutoff.wait(1), 'upstream leg survived cutoff'
            assert time.monotonic() - begin < 4, 'cutoff exceeded lease and test scheduling budget'
            assert request('alice').returncode != 0, 'Lapsed worker reused old grant'
            if shared:
                assert request('bob').returncode == 0, 'Alice cutoff affected Bob'
                assert request('alice-other-context').returncode == 0, 'Cutoff crossed Contexts using the same identity'
                # Bob's 30s authority remains valid on both legs. A retirement
                # notification accelerates cutoff without waiting for renewal.
                site.cutoff = threading.Event()
                site.slow_started = threading.Event()
                with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
                    future = pool.submit(request,'bob',(),'/slow')
                    assert site.slow_started.wait(4)
                    broker.retired['bob'].set()
                    assert future.result(timeout=4).returncode != 0
                    assert site.cutoff.wait(1)
                # Revalidation at 10s imports a new, shorter evidence deadline.
                # The idle transport must close at that deadline ahead of the
                # next periodic check and its still-current 30-second leases.
                site.cutoff = threading.Event()
                site.slow_started = threading.Event()
                with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
                    future = pool.submit(request,'alice-other-context',(),'/slow',24)
                    assert site.slow_started.wait(4)
                    deadline = datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0) + datetime.timedelta(seconds=14)
                    publish_crl(crl, ca, 2, deadline)
                    assert site.cutoff.wait(deadline.timestamp() - time.time() + 2), 'Idle upstream survived shortened CRL validity'
                    assert time.time() >= deadline.timestamp() - 1, 'Idle upstream closed before shortened validity'
                    result = future.result(timeout=1)
                    assert result.returncode not in (0, 28), (result.returncode, result.stderr)
        finally:
            child.terminate()
            child.wait(timeout=6)


def main():
    binary=str(Path(sys.argv[1]).resolve())
    options = sys.argv[2:]
    assert len(options) % 2 == 0 and set(options[::2]) <= {'--worker-sandbox', '--startup-fails'}, __doc__
    options = dict(zip(options[::2], options[1::2]))
    sandbox = options.get('--worker-sandbox')
    assert sandbox in (None, 'namespaces', 'filter'), __doc__
    startup_fails = options.get('--startup-fails')
    with tempfile.TemporaryDirectory(prefix='countersign-gateway-test-') as td:
        os.umask(0o077)
        dir=Path(td)
        ca=identity(dir,'ca')
        for name,hosts in [('broker',['localhost']),('listener',['localhost']),('upstream',['site.test'])]:
            identity(dir,name,ca,hosts)
        identities={u: identity(dir,u,ca) for u in ('alice','bob')}
        identities['alice-other-context'] = identities['alice']
        def tls(name):
            ctx=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
            ctx.load_cert_chain(dir/f'{name}.pem',dir/f'{name}.key')
            return ctx
        site_tls=tls('upstream')
        site_tls.verify_mode=ssl.CERT_REQUIRED
        site_tls.load_verify_locations(dir/'ca.pem')
        # Ask the kernel for its default interface, without sending any datagram.
        with socket.socket(socket.AF_INET,socket.SOCK_DGRAM) as s:
            s.connect(('192.0.2.1',9))
            ip=s.getsockname()[0]
        with server(ip,Site,site_tls) as site, server('127.0.0.1',Broker,tls('broker')) as broker:
            for shared in (False,True):
                do_test(dir,binary,ip,site,broker,identities,ca,shared,sandbox=sandbox,startup_fails=startup_fails)
                print(('shared' if shared else 'sidecar')+(' Gateway refused to start' if startup_fails
                                                           else ' Gateway mTLS passed'))
            if startup_fails:
                return
            do_test(dir,binary,ip,site,broker,identities,ca,True,filter_kill=True,sandbox=sandbox)
            print('filter-killed grant worker fenced')


if __name__ == '__main__':
    main()