-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcp.py
More file actions
1778 lines (1455 loc) · 70.2 KB
/
Copy pathcp.py
File metadata and controls
1778 lines (1455 loc) · 70.2 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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Minimal NCOS Config Store client for containers.
A container-focused replacement for the full NCOS SDK `cp.py`. Standard library
only: no `requests`, no third-party anything.
import cp
state = cp.get('status/wan/connection_state') # 'connected'
cp.put('config/system/gps/enabled', True)
cp.log(f'WAN is {state}')
Two transports, and the choice is always explicit
-------------------------------------------------
`socket` (the default) speaks the Config Store protocol over the Unix socket at
/var/tmp/cs.sock. This is how a container talks to the router it runs on, and it
needs no credentials -- only the `$CONFIG_STORE` volume on the service. Without
that volume there is no socket and every accessor returns None; call
`cp.config_store_available()` to tell that apart from the router simply having no
data at a path.
`rest` speaks the router's HTTP/REST API, for driving a *remote* router from a
development machine:
# credentials come from .env at the repo root; no export step
python3 -c "import cp; cp.use_rest(); print(cp.get_product_name())"
Every accessor in this module works over either transport, so code written
against the socket runs unchanged against a remote router.
Two rules keep the two apart, so that "on the router, always the socket" is
enforced rather than merely conventional:
1. **No automatic fallback.** A container whose `$CONFIG_STORE` volume is
missing fails visibly. It never quietly switches to REST, whatever is set
in the environment. `use_rest()` is the only way to leave socket mode.
2. **REST is refused when the Config Store socket exists.** On the router
there is local access, so REST would be strictly worse: it needs
credentials and can be aimed at the wrong device. `use_rest()` raises there
unless passed `force=True`, which exists only for the deliberate case of
reaching a *different* router.
REST is a development-host transport, and `.env` at the repo root is its only
credential source besides explicit arguments. `.env` is a development-host file --
gitignored, never copied into an image -- so it simply does not exist in a
container, which is correct: the socket needs no credentials and `use_rest()` is
refused on the router. Do not bake router credentials into an image to change
that. See `use_rest()` for the rest of the security notes.
Responses are unwrapped: `cp.get('status/system')` returns the data itself, so
never write `cp.get(...).get('data')`. The REST API wraps replies as
`{"success": true, "data": ...}`; this module unwraps them so both transports
present the same shape.
`alert()` sends a custom alert to NCM and works from a container -- verified on an
R980-5GD (NCOS 7.26.21) from a container holding only the $CONFIG_STORE volume,
with no SDK app registration. The Config Store replied `Alert added(...)`. That is
local acceptance; whether the alert reaches the NCM console is UNVERIFIED.
Not implemented, because there is no evidence they work from a container:
register() / on() / config store event subscriptions are said to
unregister() need the event socket, which containers are
said not to have. UNVERIFIED -- no test of
this is on record. Poll instead.
Stubs for those remain so that copied example code fails with a clear log line
instead of an AttributeError.
API documentation: docs/ncos-api/
Wire protocol: docs/cs-sock-protocol.md
Module reference: docs/ncos-sdk-reference.md
Tests: tests/test_cp.py (no router required)
"""
import base64
import hashlib
import hmac
import json
import os
import socket
import sys
import threading
import time
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
__all__ = [
# Core Config Store access
'get', 'put', 'post', 'delete', 'decrypt', 'log',
# Transport selection and diagnostics
'use_rest', 'use_socket', 'transport', 'RestTarget',
'config_store_available', 'config_store_status', 'last_transport_error',
# Application configuration
'get_appdata', 'put_appdata', 'post_appdata', 'delete_appdata',
# Device identity
'get_serial_number', 'get_mac', 'get_product_name', 'get_router_model',
'get_firmware_version', 'get_name', 'get_uptime',
# Readiness
'wait_for_uptime', 'wait_for_ntp', 'wait_for_wan_connection',
# Convenience wrappers documented in docs/ncos-api/
'get_connected_wans', 'get_sims', 'get_wan_profiles', 'get_gpio',
'get_lat_long', 'dec', 'validate_password',
# NCM alerts
'alert',
# Present but unimplemented in containers
'register', 'on', 'unregister',
]
# Name used as a log prefix. Set CP_APP_NAME to override -- an image with no
# WORKDIR runs at '/', where basename is empty, so without it every line is
# prefixed with the generic 'container:'.
APP_NAME = os.environ.get('CP_APP_NAME') or os.path.basename(os.getcwd()) or 'container'
# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
def log(value: Any = '') -> None:
"""Write a line to stdout, where the container runtime collects it.
Visible with `container logs <name>` on the router.
"""
stamp = time.strftime('%Y-%m-%dT%H:%M:%S')
try:
print(f'{stamp} {APP_NAME}: {value}', flush=True)
except (OSError, ValueError):
# stdout closed during shutdown; losing a log line is not worth raising.
pass
# ---------------------------------------------------------------------------
# Tunables
# ---------------------------------------------------------------------------
def _env_number(name: str, default: float) -> float:
"""Read a positive number from the environment, falling back on nonsense."""
raw = os.environ.get(name)
if not raw:
return default
try:
value = float(raw)
except ValueError:
log(f'{name}={raw!r} is not a number, using {default}')
return default
if value <= 0:
log(f'{name}={raw!r} must be positive, using {default}')
return default
return value
SOCKET_PATH = '/var/tmp/cs.sock'
_END_OF_HEADER = b"\r\n\r\n"
_MAX_PACKET_SIZE = 8192
# Applies to a whole request/response exchange, not to each recv(). A command
# with a missing field does not error, it hangs the socket waiting for the field
# that never arrives, so this timeout is what stops a malformed command blocking
# a poller forever.
_RECV_TIMEOUT = _env_number('CP_TIMEOUT', 2.0)
# Hard ceiling on a single response. `get` with tree=1 can return a very large
# subtree, and these routers have as little as 135 MB for all containers.
_MAX_RESPONSE_BYTES = int(_env_number('CP_MAX_RESPONSE_BYTES', 4 * 1024 * 1024))
# How long config_store_available() waits before re-probing a backend that has
# already failed. Without a re-probe, one failure at startup -- a container that
# beat the Config Store to readiness, say -- would latch for the life of the
# process.
_PROBE_COOLDOWN = _env_number('CP_PROBE_COOLDOWN', 30.0)
# Repeated failures are logged once, then at most this often. Throttling by
# elapsed time rather than by attempt count keeps the rate the same whether the
# caller polls every second or every five minutes.
_LOG_THROTTLE_SECONDS = 60.0
# Longest single time.sleep() inside a wait helper. Nothing to do with pacing:
# a signal handler that only sets a flag cannot shorten a sleep already in
# progress (PEP 475), so long sleeps delay shutdown.
_SLEEP_STEP = 1.0
# Synthetic statuses this module produces itself. The router never sends them,
# and they always mean the request failed.
_SYNTHETIC_STATUSES = ('timeout', 'malformed')
_UNSET = object()
_lock = threading.Lock()
_transport: Dict[str, Any] = {
'mode': 'socket', # 'socket' or 'rest'
'rest': None, # RestTarget when mode == 'rest'
'ok': None, # None until the backend has been tried
'error': None, # text of the most recent failure
'failures': 0,
'successes': 0,
'consecutive_failures': 0,
'last_probe': 0.0,
'last_failure_log': 0.0,
}
# Warnings that should be said once per process, not once per call.
_warned: set = set()
def _warn_once(key: str, message: str) -> None:
with _lock:
if key in _warned:
return
_warned.add(key)
log(message)
# ---------------------------------------------------------------------------
# Transport health
# ---------------------------------------------------------------------------
class _CommandError(Exception):
"""A caller-side problem with a request: a bad path, an unencodable value.
Kept distinct from a transport failure on purpose. Recording one of these
against the backend's health would blame the router for a mistake made here,
and would mark a perfectly reachable Config Store as unavailable.
"""
def _record(success: bool, error: Optional[str] = None) -> Tuple[int, bool]:
"""Update backend health. Returns (consecutive failures, should log now)."""
with _lock:
if success:
_transport['ok'] = True
_transport['error'] = None
_transport['successes'] += 1
_transport['consecutive_failures'] = 0
return 0, False
_transport['ok'] = False
_transport['error'] = error
_transport['failures'] += 1
_transport['consecutive_failures'] += 1
consecutive = _transport['consecutive_failures']
now = time.monotonic()
should_log = (
consecutive == 1
or (now - _transport['last_failure_log']) >= _LOG_THROTTLE_SECONDS
)
if should_log:
_transport['last_failure_log'] = now
return consecutive, should_log
def _fail(detail: str) -> Dict[str, Any]:
"""Record a transport failure, log it subject to throttling, return {}."""
consecutive, should_log = _record(False, detail)
if should_log:
target = _target_description()
if consecutive == 1:
log(f'router unreachable via {target}: {detail}')
if _mode() == 'socket' and not os.path.exists(SOCKET_PATH):
log('config store: socket does not exist -- is the '
'$CONFIG_STORE volume attached to this service?')
else:
log(f'router still unreachable via {target} after '
f'{consecutive} attempts: {detail}')
return {}
def _mode() -> str:
with _lock:
return _transport['mode']
def _target_description() -> str:
"""Human-readable target for a log line. Never includes the password."""
with _lock:
mode = _transport['mode']
target = _transport['rest']
if mode == 'rest' and target is not None:
return f'{target.scheme}://{target.host} as {target.username}'
return f'unix:{SOCKET_PATH}'
def transport() -> str:
"""Which transport is active: 'socket' or 'rest'."""
return _mode()
# ---------------------------------------------------------------------------
# Command construction
#
# One place builds and validates every request, so both transports reject the
# same input. Two failure classes matter here and neither is the router's fault:
# a field containing a newline, which would inject extra protocol fields, and a
# value that will not encode.
# ---------------------------------------------------------------------------
def _field(label: str, value: Any) -> str:
"""Validate one protocol field.
Newlines are rejected rather than stripped. The protocol is
newline-delimited, so an embedded newline in a path sends more fields than
the verb takes and desyncs the command -- but silently stripping it would
read or write a *different path* from the one the caller asked for, which is
worse than refusing. Callers interpolating anything into a path should
validate it upstream.
"""
text = '' if value is None else str(value)
for char, name in (('\n', 'newline'), ('\r', 'carriage return')):
if char in text:
raise _CommandError(
f'{label} contains a {name} ({text!r}). The Config Store '
'protocol is newline-delimited, so this would inject extra '
'protocol fields. Reject or encode it upstream.'
)
return text
def _path_field(path: Any) -> str:
checked = _field('path', path)
if not checked.strip():
raise _CommandError('path is empty')
return checked
def _value_field(value: Any) -> str:
"""JSON-encode a value for put/post.
Inside the command builder, and therefore inside the error handling: this
used to run in the caller's frame, so a non-serialisable value raised
straight past the module's "accessors do not raise" contract.
"""
try:
return json.dumps(value)
except (TypeError, ValueError) as exc:
raise _CommandError(f'value is not JSON-serialisable: {exc}') from None
def _command_fields(verb: str, path: Any, query: Any, tree: Any,
value: Any, name: Any) -> List[str]:
"""Fields for one verb, in order. See docs/cs-sock-protocol.md.
Field counts are exact: the Config Store blocks waiting for a missing field
rather than returning an error, so nothing here may be built conditionally.
"""
if verb == 'alert':
return [_field('alert name', name), _field('alert text', value)]
checked_path = _path_field(path)
checked_query = _field('query', query)
if verb == 'delete':
return [checked_path, checked_query]
if verb == 'post':
return [checked_path, checked_query, _value_field(value)]
if verb == 'put':
return [checked_path, checked_query, _field('tree', tree), _value_field(value)]
# get, decrypt
return [checked_path, checked_query, _field('tree', tree)]
def _encode_command(verb: str, fields: Sequence[str]) -> bytes:
command = verb + '\n' + ''.join(f'{field}\n' for field in fields)
try:
return command.encode('ascii')
except UnicodeEncodeError as exc:
raise _CommandError(
f'command contains a non-ASCII character at position {exc.start}. '
'Commands are ASCII-encoded; whether the Config Store accepts UTF-8 '
'is untested, so this is refused rather than risked.'
) from None
# ---------------------------------------------------------------------------
# Socket transport
# ---------------------------------------------------------------------------
def _recv_chunk(sock: socket.socket, deadline: float) -> Optional[bytes]:
"""One recv() bounded by the exchange deadline.
Returns b'' on an orderly close and None on timeout, so the caller can tell
a truncated response from a hung one.
"""
remaining = deadline - time.monotonic()
if remaining <= 0:
return None
sock.settimeout(remaining)
try:
return sock.recv(_MAX_PACKET_SIZE)
except socket.timeout:
return None
def _parse_headers(block: bytes) -> Tuple[str, int, Optional[str]]:
"""Parse the header block. Returns (status, content_length, error).
Header fields are separated by a bare LF even though the block itself is
terminated by CRLFCRLF, and they are not in a guaranteed order, so each is
matched independently. The status value is taken whole rather than as a
single word: the vocabulary beyond 'ok' is not catalogued and may contain
spaces.
"""
status: Optional[str] = None
length: Optional[int] = None
for line in block.split(b'\n'):
line = line.strip()
if not line or b':' not in line:
continue
raw_key, _, raw_value = line.partition(b':')
key = raw_key.strip().lower().decode('ascii', 'replace')
text = raw_value.strip().decode('utf-8', 'replace')
if key == 'status':
status = text
elif key == 'content-length':
try:
length = int(text)
except ValueError:
return '', 0, f'content-length is not a number: {text!r}'
if status is None:
return '', 0, 'response has no status header'
if length is None:
return '', 0, 'response has no content-length header'
if length < 0:
return '', 0, f'negative content-length: {length}'
if length > _MAX_RESPONSE_BYTES:
return '', 0, (f'content-length {length} exceeds the {_MAX_RESPONSE_BYTES} '
'byte cap (raise CP_MAX_RESPONSE_BYTES if this is expected)')
return status, length, None
def _receive(sock: socket.socket) -> Dict[str, Any]:
"""Read one Config Store response.
Wire format is an HTTP-like header block terminated by CRLFCRLF, with an
accurate content-length, followed by a body that is usually but not always
JSON. A timeout or a truncated response comes back as a synthetic status,
never as a partial success.
"""
deadline = time.monotonic() + _RECV_TIMEOUT
buffer = bytearray()
header_end = -1
while header_end < 0:
chunk = _recv_chunk(sock, deadline)
if chunk is None:
return {'status': 'timeout', 'data': None,
'detail': f'no complete header within {_RECV_TIMEOUT}s '
f'({len(buffer)} bytes read)'}
if not chunk:
return {'status': 'malformed', 'data': None,
'detail': f'connection closed after {len(buffer)} bytes, '
'before the CRLFCRLF header terminator'}
buffer += chunk
if len(buffer) > _MAX_RESPONSE_BYTES:
return {'status': 'malformed', 'data': None,
'detail': f'header exceeded the {_MAX_RESPONSE_BYTES} byte cap'}
header_end = buffer.find(_END_OF_HEADER)
status, content_length, error = _parse_headers(bytes(buffer[:header_end]))
if error is not None:
return {'status': 'malformed', 'data': None, 'detail': error}
body = bytearray(buffer[header_end + len(_END_OF_HEADER):])
while len(body) < content_length:
chunk = _recv_chunk(sock, deadline)
if chunk is None:
return {'status': 'timeout', 'data': None,
'detail': f'body truncated at {len(body)}/{content_length} '
f'bytes after {_RECV_TIMEOUT}s'}
if not chunk:
return {'status': 'malformed', 'data': None,
'detail': f'connection closed with {len(body)}/'
f'{content_length} body bytes received'}
body += chunk
text = bytes(body[:content_length]).decode('utf-8', 'replace')
try:
payload = json.loads(text)
except (ValueError, TypeError):
# Expected: alert replies, and some put errors, are plain strings.
payload = text.strip()
return {'status': status, 'data': payload}
def _socket_dispatch(command: bytes) -> Dict[str, Any]:
"""Send one command over cs.sock. Returns {} on any failure."""
try:
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
sock.settimeout(_RECV_TIMEOUT)
sock.connect(SOCKET_PATH)
sock.sendall(command)
response = _receive(sock)
except Exception as exc: # noqa: BLE001 - a poller must survive any failure
return _fail(f'{type(exc).__name__}: {exc}')
if response.get('status') in _SYNTHETIC_STATUSES:
# A hung or truncated exchange is a failed request. Recording it as a
# success would report a wedged Config Store as healthy, which is the
# one failure the health counters exist to catch.
return _fail(f"{response['status']}: {response.get('detail', '')}")
_record(True)
return response
# ---------------------------------------------------------------------------
# REST transport (development hosts)
# ---------------------------------------------------------------------------
class RestTarget:
"""Where the REST transport points, and how it authenticates.
`__repr__` is redacted deliberately: a default repr would print the password
into every traceback, debugger frame and stray print that touches this
object.
"""
__slots__ = ('host', 'username', 'password', 'scheme', 'verify_tls',
'timeout', 'sources')
def __init__(self, host: str, username: str, password: str,
scheme: str = 'auto', verify_tls: bool = False,
timeout: float = 10.0,
sources: Optional[Dict[str, str]] = None) -> None:
self.host = host
self.username = username
self.password = password
self.scheme = scheme
self.verify_tls = verify_tls
self.timeout = timeout
self.sources = sources or {}
def __repr__(self) -> str:
state = 'set' if self.password else 'empty'
return (f'RestTarget(host={self.host!r}, username={self.username!r}, '
f'password=<redacted:{state}>, scheme={self.scheme!r}, '
f'verify_tls={self.verify_tls!r}, timeout={self.timeout!r})')
def describe(self) -> Dict[str, Any]:
"""Safe to print or serve. Reports whether a password is set, never it."""
return {
'host': self.host,
'username': self.username,
'password': 'set' if self.password else 'NOT SET',
'scheme': self.scheme,
'verify_tls': self.verify_tls,
'timeout': self.timeout,
'sources': dict(self.sources),
}
def schemes(self) -> Tuple[str, ...]:
return ('https', 'http') if self.scheme == 'auto' else (self.scheme,)
# The keys read from `.env`, which is the only source of REST credentials besides
# explicit arguments. Process environment variables are deliberately not read:
# credentials belong in one place, and a second source that silently outranks the
# file makes a stale value indistinguishable from an unreachable router.
_REST_ENV_NAMES = {
'host': ('NCOS_DEV_HOST',),
'username': ('NCOS_DEV_USERNAME',),
'password': ('NCOS_DEV_PASSWORD',),
'scheme': ('NCOS_DEV_SCHEME',),
'verify_tls': ('NCOS_DEV_VERIFY_TLS',),
'timeout': ('NCOS_DEV_TIMEOUT',),
}
# `.env` lives at the repo root on a development host. It is gitignored and never
# copied into an image, so this path simply does not exist in a container -- which
# is correct: on the router the socket needs no credentials, and use_rest() is
# refused there anyway.
DOTENV_PATH = os.path.join(os.getcwd(), '.env')
def _read_dotenv(path: Optional[str] = None) -> Dict[str, str]:
"""Parse `.env` into a dict. Returns {} when it is absent or unreadable.
Deliberately tolerant: `#` is only a comment at the start of a line, since it
is an ordinary password character, and at most one matching outer quote pair
is stripped.
"""
values: Dict[str, str] = {}
try:
with open(path or DOTENV_PATH, 'r', encoding='utf-8', errors='replace') as handle:
lines = handle.readlines()
except OSError:
return values
for line in lines:
line = line.strip()
if not line or line.startswith('#') or '=' not in line:
continue
key, _, raw = line.partition('=')
key = key.strip()
raw = raw.strip()
if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in ('"', "'"):
raw = raw[1:-1]
values[key] = raw
return values
def _resolve_rest_setting(key: str) -> Tuple[Optional[str], str]:
from_file = _read_dotenv()
for name in _REST_ENV_NAMES[key]:
if from_file.get(name):
return from_file[name], f'.env:{name}'
return None, 'default'
def use_rest(host: Optional[str] = None, username: Optional[str] = None,
password: Optional[str] = None, scheme: Optional[str] = None,
verify_tls: Optional[bool] = None, timeout: Optional[float] = None,
force: bool = False) -> RestTarget:
"""Point this module at a remote router's HTTP/REST API.
For **development hosts**. A container talks to the router it runs on
through the Config Store socket, which needs no credentials at all -- do not
bake router credentials into an image to use this instead.
**Refused on the router.** If the Config Store socket exists, this raises
RuntimeError rather than switching: local access is available, so REST would
be strictly worse -- it needs credentials, and it can be aimed at the wrong
device. `force=True` overrides it for the one case that is not a mistake,
reaching a *different* router from this one, which means accepting
credentials inside the image.
Anything not passed explicitly is read from `.env` at the repo root -- the
same `NCOS_DEV_HOST` / `USERNAME` / `PASSWORD` / `SCHEME` / `VERIFY_TLS` /
`TIMEOUT` keys `tools/dev_router.py` uses. No export step is needed:
python3 -c "import cp; cp.use_rest(); print(cp.get_lat_long())"
`.env` is the only source besides explicit arguments. Process environment
variables are deliberately not read for credentials, so there is no second
place a stale router address can hide: edit the file and the next call uses
it. `RestTarget.describe()` reports the source of each value.
Note that `.env` is a development-host file -- gitignored, never copied into
an image -- so these variables are not normally present in a container at
all. Reaching REST from inside one takes all three of: credentials supplied
to the container, a call to this function, and either no Config Store socket
or `force=True`. The refusal above closes the third; the second is what
covers a container running without the `$CONFIG_STORE` volume, where there is
no socket to detect. See docs/ncos-sdk-reference.md for the full statement of
what this does and does not guard.
Raises ValueError, naming the variables that are unset, when it has no host
or no password. It never falls back to a default address: a tool that
defaults its target converts "you have not configured this" into "the router
is unreachable", against a router you may not have intended to contact.
Credential handling:
- The password is never logged and never placed in a command line. `curl -u`
and `sshpass -p` expose credentials to every local user via `ps`; this goes
through `urllib` in-process instead.
- `RestTarget.__repr__` is redacted, and `config_store_status()` reports only
whether a password is set.
- TLS verification is **off by default**, because routers ship a self-signed
certificate. The connection is encrypted but not authenticated, which is
fine on a trusted dev LAN and not fine over the internet. Pass
`verify_tls=True` once a certificate that validates is installed.
Not everything crosses this transport. `decrypt()` and `alert()` have no REST
equivalent, and `query`/`tree` are ignored; each logs plainly rather than
returning a quietly wrong answer. `validate_password()` cannot work either,
because REST returns masked `$0$` hashes.
Returns the resolved target, and switches this module to it process-wide.
"""
# Checked before any credential is resolved, so a refusal never reads or
# holds a password it was not going to use.
if not force and os.path.exists(SOCKET_PATH):
raise RuntimeError(
f'refusing to enable the REST transport: the Config Store socket '
f'exists at {SOCKET_PATH}, so this process has local access to the '
'router it is running on. Use the socket -- it needs no credentials '
'and cannot be aimed at the wrong device. Pass force=True only if '
'you really mean to reach a different router from here, which means '
'accepting router credentials inside this container.'
)
sources: Dict[str, str] = {}
def resolve(key: str, explicit: Any) -> Optional[str]:
if explicit is not None:
sources[key] = 'argument'
return str(explicit)
value, origin = _resolve_rest_setting(key)
sources[key] = origin
return value
resolved_host = (resolve('host', host) or '').strip().rstrip('/')
resolved_scheme = (resolve('scheme', scheme) or 'auto').strip().lower()
# Tolerate a scheme pasted into the host rather than failing later on a URL
# like https://https://192.168.0.1/api/...
for marker in ('https://', 'http://'):
if resolved_host.startswith(marker):
resolved_scheme = marker[:-3]
resolved_host = resolved_host[len(marker):]
sources['scheme'] = 'derived from host'
resolved_user = (resolve('username', username) or 'admin').strip()
resolved_password = resolve('password', password) or ''
missing = [name for name, value in (
(_REST_ENV_NAMES['host'][0], resolved_host),
(_REST_ENV_NAMES['password'][0], resolved_password),
) if not value]
if missing:
raise ValueError(
'the REST transport is not configured: '
+ ', '.join(f'{name} not set in {DOTENV_PATH}' for name in missing)
+ '. Set them in .env, or pass host=/password= explicitly. Not '
'defaulting to an address on purpose -- see use_rest() for why.'
)
if resolved_scheme not in ('auto', 'https', 'http'):
raise ValueError(f"scheme must be auto, https or http (got {resolved_scheme!r})")
if verify_tls is None:
raw_verify, origin = _resolve_rest_setting('verify_tls')
sources['verify_tls'] = origin
resolved_verify = str(raw_verify).strip().lower() in ('1', 'true', 'yes', 'on') \
if raw_verify else False
else:
sources['verify_tls'] = 'argument'
resolved_verify = bool(verify_tls)
if timeout is None:
raw_timeout, origin = _resolve_rest_setting('timeout')
sources['timeout'] = origin
try:
resolved_timeout = float(raw_timeout) if raw_timeout else 10.0
except ValueError:
raise ValueError(f'timeout must be a number (got {raw_timeout!r})') from None
else:
sources['timeout'] = 'argument'
resolved_timeout = float(timeout)
if resolved_timeout <= 0:
raise ValueError(f'timeout must be positive (got {resolved_timeout})')
target = RestTarget(resolved_host, resolved_user, resolved_password,
resolved_scheme, resolved_verify, resolved_timeout, sources)
with _lock:
_transport.update(mode='rest', rest=target, ok=None, error=None,
failures=0, successes=0, consecutive_failures=0,
last_probe=0.0, last_failure_log=0.0)
_warned.discard('rest_tls')
log(f'REST transport enabled for {target.scheme}://{target.host} '
f'as {target.username}')
if not target.verify_tls:
_warn_once('rest_tls',
'REST transport: TLS certificate verification is OFF. The '
'connection is encrypted but the router is not authenticated '
'-- acceptable on a trusted development LAN only.')
return target
def use_socket() -> None:
"""Return to the Config Store socket, discarding any REST credentials."""
with _lock:
_transport.update(mode='socket', rest=None, ok=None, error=None,
failures=0, successes=0, consecutive_failures=0,
last_probe=0.0, last_failure_log=0.0)
log(f'socket transport enabled ({SOCKET_PATH})')
_REST_METHODS = {'get': 'GET', 'put': 'PUT', 'post': 'POST', 'delete': 'DELETE'}
def _rest_once(target: 'RestTarget', scheme: str, method: str, path: str,
value: Any) -> Dict[str, Any]:
"""One REST call. Raises on transport failure, returns the unwrapped reply.
urllib and ssl are imported here rather than at module scope so a container
using the socket transport -- the common case, on a router with as little as
135 MB for all containers -- never pays for them.
"""
import ssl
import urllib.error
import urllib.parse
import urllib.request
url = f"{scheme}://{target.host}/api/{str(path).strip('/')}"
headers = {
# Built by hand rather than with HTTPBasicAuthHandler, which only sends
# credentials after a 401 round-trip.
'Authorization': 'Basic ' + base64.b64encode(
f'{target.username}:{target.password}'.encode()).decode(),
'Accept': 'application/json',
}
data = None
if value is not _UNSET:
# The API expects a form-encoded 'data' field holding JSON, not a JSON
# request body. See docs/ncos-api/config/README.md.
data = urllib.parse.urlencode({'data': json.dumps(value)}).encode()
headers['Content-Type'] = 'application/x-www-form-urlencoded'
if target.verify_tls:
context = ssl.create_default_context()
else:
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
request = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=target.timeout,
context=context) as response:
body = response.read(_MAX_RESPONSE_BYTES + 1)
except urllib.error.HTTPError as exc:
detail = exc.read().decode('utf-8', 'replace').strip()
if exc.code == 401:
raise OSError(
f'401 unauthorized for {target.username}@{target.host}. Check '
f'{_REST_ENV_NAMES["username"][0]} and '
f'{_REST_ENV_NAMES["password"][0]}.'
) from None
raise OSError(f'HTTP {exc.code} {exc.reason} for {method} {url}: '
f'{detail[:200]}') from None
if len(body) > _MAX_RESPONSE_BYTES:
raise OSError(f'response exceeded the {_MAX_RESPONSE_BYTES} byte cap')
text = body.decode('utf-8', 'replace')
if not text.strip():
return {'status': 'ok', 'data': None}
try:
payload = json.loads(text)
except ValueError:
# An HTML login page here means the router answered but did not treat
# this as an API call.
raise OSError(f'{method} {url} returned non-JSON ({text[:120]!r}). Is '
'this an NCOS router, and is the API on this scheme?') from None
# REST wraps replies; the socket does not. Unwrap so both transports present
# the same shape to every accessor above.
if isinstance(payload, dict) and 'success' in payload:
if not payload.get('success'):
return {'status': 'error', 'data': payload.get('data'),
'detail': json.dumps(payload)[:200]}
return {'status': 'ok', 'data': payload.get('data')}
return {'status': 'ok', 'data': payload}
def _rest_dispatch(verb: str, path: Any, query: Any, tree: Any,
value: Any, target: 'RestTarget') -> Dict[str, Any]:
if verb not in _REST_METHODS:
log(f'{verb}: not available over the REST transport. Only '
f'{"/".join(sorted(_REST_METHODS))} have a REST equivalent; '
'use the Config Store socket on the router for the rest.')
return {}
if query:
_warn_once(f'rest_query_{verb}',
f'{verb}: the REST transport ignores query={query!r}')
if tree not in (0, '0', '', None):
_warn_once(f'rest_tree_{verb}',
f'{verb}: the REST transport ignores tree={tree!r}')
errors = []
for scheme in target.schemes():
try:
response = _rest_once(target, scheme, _REST_METHODS[verb], path, value)
except OSError as exc:
message = str(exc)
errors.append(f'{scheme}: {message}')
# An auth failure is a definitive answer; retrying the other scheme
# would only bury it.
if '401 unauthorized' in message:
break
continue
except Exception as exc: # noqa: BLE001 - a poller must survive anything
errors.append(f'{scheme}: {type(exc).__name__}: {exc}')
continue
if response.get('status') == 'error':
# The router answered, so the transport is healthy; the request was
# rejected. Surfaced rather than silently returning None.
_record(True)
log(f'{verb} {path}: router rejected the request: '
f'{response.get("detail", "")}')
return response
_record(True)
return response
return _fail('; '.join(errors) or 'no scheme attempted')
# ---------------------------------------------------------------------------
# Dispatch
# ---------------------------------------------------------------------------
def _dispatch(verb: str, path: Any = '', query: Any = '', tree: Any = 0,
value: Any = _UNSET, name: Any = None) -> Dict[str, Any]:
"""Send one request and return {'status': str, 'data': Any}.
Returns an empty dict on any failure, so callers can use `.get('data')`
without a None check. Caller mistakes are logged and returned as {} without
touching backend health -- they say nothing about whether the router is
reachable.
"""
try:
fields = _command_fields(verb, path, query, tree, value, name)
# Encoded even for REST, so both transports enforce the same field
# validation and the same ASCII restriction.
command = _encode_command(verb, fields)
except _CommandError as exc:
log(f'{verb}: {exc}')
return {}
with _lock:
mode = _transport['mode']
target = _transport['rest']
if mode == 'rest':
if target is None: # defensive; use_rest sets both
return _fail('REST transport selected with no target configured')
return _rest_dispatch(verb, path, query, tree, value, target)
return _socket_dispatch(command)
# ---------------------------------------------------------------------------
# Diagnostics
# ---------------------------------------------------------------------------
def config_store_available() -> bool:
"""True when the active backend is reachable.
Every accessor returns None both when a path holds no data and when the
router cannot be reached at all. Use this to tell those apart and report the
real problem.
Probes `status/product_info` when nothing has been tried yet, and re-probes a
failed backend at most every `CP_PROBE_COOLDOWN` seconds (30 by default), so
a socket that appears after startup is picked up without a restart.
A poller that must recover from a late-appearing backend is still better
written as "attempt the read, then explain a None" than as "ask whether the
backend is up, then decide whether to read" -- within the cooldown window
this returns the last known answer, which is the point of the cooldown.
"""
now = time.monotonic()
with _lock:
state = _transport['ok']
if state is None:
probe = True # nothing tried yet
elif state is False:
probe = (now - _transport['last_probe']) >= _PROBE_COOLDOWN
else:
probe = False # already known good
if probe:
# Claim the probe slot before releasing the lock, so concurrent
# callers do not stampede the backend.
_transport['last_probe'] = now
if probe:
get('status/product_info')
with _lock:
state = _transport['ok']
return bool(state)
def config_store_status() -> Dict[str, Any]:
"""Connectivity detail, suitable for a status endpoint or health check.
Safe to serve: when the REST transport is active, `target` reports the host
and username but never the password.
"""
available = config_store_available()
with _lock:
mode = _transport['mode']
target = _transport['rest']
status = {
'transport': mode,
'available': available,
'socket_path': SOCKET_PATH,
'socket_exists': os.path.exists(SOCKET_PATH),
'last_error': _transport['error'],
'failures': _transport['failures'],
'successes': _transport['successes'],
}
if mode == 'rest' and target is not None:
status['target'] = target.describe()
else:
status['target'] = f'unix:{SOCKET_PATH}'
return status
def last_transport_error() -> Optional[str]:
"""Text of the most recent transport failure, or None."""
with _lock:
return _transport['error']
# ---------------------------------------------------------------------------
# Core access
# ---------------------------------------------------------------------------
def get(path: str, query: str = '', tree: int = 0) -> Any:
"""Read from the router tree.
Returns the data itself, already unwrapped -- do not call `.get('data')` on
the result. Returns None when the path holds no data or the router is
unreachable; `config_store_available()` tells those apart.