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
"""
synqro — Python 3.10+ ctypes wrapper for the Synqro Zero-Trust OTA Updater.
This module provides a complete, idiomatic Python binding to ``libsynqro``
using only Python standard-library modules (``ctypes``, ``os``, ``pathlib``,
``dataclasses``, ``enum``, ``platform``, ``typing``, ``logging``).
No third-party packages are required.
Platform Library Resolution
---------------------------
The shared library is located using the following search order:
1. The path given by the ``SYNQRO_LIB_PATH`` environment variable (exact path
or directory containing the library).
2. Directories listed in ``LD_LIBRARY_PATH`` (Linux) / ``DYLD_LIBRARY_PATH``
(macOS) / ``PATH`` (Windows).
3. The OS default search path (``ctypes.util.find_library``).
Quick Start
-----------
::
from synqro import SynqroClient, SynqroException, SynqroStatus
with SynqroClient() as client:
result = client.init("/etc/myapp/synqro_ota.yaml")
if result.status != SynqroStatus.OK:
raise SynqroException(result)
update = client.check_update()
print(f"Update check: {update.message}")
if "update_available" in update.message:
apply_result = client.apply_update()
if apply_result.status != SynqroStatus.OK:
client.rollback()
Thread Safety
-------------
``SynqroClient.init`` must complete on a single thread before concurrent use.
``apply_update`` and ``rollback`` must not be called concurrently; all other
methods are safe to call from multiple threads after ``init`` returns.
Memory Safety
-------------
All heap-allocated strings returned by the C library are freed via
``synqro_free_string`` inside ``try/finally`` blocks. ``SynqroResult``
structs returned by the C layer are freed via ``synqro_free_result`` before
the Python ``SynqroResult`` dataclass is returned to the caller.
Security Notes
--------------
- No ``shell=True`` is used anywhere in this module.
- No ``eval()`` or ``exec()`` is used.
- No secrets, tokens, or keys are hardcoded.
- SSL/TLS verification is handled entirely within the Rust engine; this
wrapper does not perform any network I/O itself.
"""
# ---------------------------------------------------------------------------
# Module-level logger
# ---------------------------------------------------------------------------
=
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
#: Maximum byte length (including the NUL terminator) accepted for any string
#: argument passed to the C library. Matches ``SYNQRO_MAX_INPUT_LEN`` in
#: ``synqro.h``.
: = 4096
# ---------------------------------------------------------------------------
# Status enum
# ---------------------------------------------------------------------------
"""Mirrors the C ``SynqroStatus`` enum defined in ``synqro.h``.
Integer values are stable across library releases; do not rely on the
ordering of values in source.
"""
#: Operation completed successfully.
= 0
#: A supplied parameter was ``None``, empty, or exceeded
#: :data:`SYNQRO_MAX_INPUT_LEN`.
= 1
#: A cryptographic operation failed (key load, AEAD decrypt, entropy).
= 2
#: A network operation failed (TLS, DNS, timeout).
= 3
#: Ed25519 signature verification of a payload or manifest failed.
= 4
#: Rollback failed; backup may be missing or corrupted.
= 5
#: The process lacks required OS permissions.
= 6
#: Unexpected internal error; correlate ``error_id`` with the audit log.
= 99
"""Map unknown integer values to :attr:`ERR_INTERNAL`."""
return
# ---------------------------------------------------------------------------
# C struct mirrors
# ---------------------------------------------------------------------------
"""ctypes mirror of the C ``SynqroResult`` struct.
This is an internal type; Python code should use :class:`SynqroResult`
instead.
Field layout must match the C definition in ``synqro.h`` exactly:
.. code-block:: c
typedef struct {
SynqroStatus status; // int32
const char* message; // pointer
uint64_t error_id; // uint64
} SynqroResult;
"""
: =
# ---------------------------------------------------------------------------
# Python-side result dataclass
# ---------------------------------------------------------------------------
"""Immutable Python representation of a ``SynqroResult`` from the C layer.
Instances are created by :class:`SynqroClient` methods after translating
the C struct and freeing the underlying C memory. Callers never manage
C resources directly.
Attributes
----------
status:
Outcome of the operation.
message:
Human-readable description. Empty string on success.
error_id:
Opaque 64-bit audit-log correlation ID. Zero on success.
"""
:
:
:
"""``True`` iff :attr:`status` is :attr:`SynqroStatus.OK`."""
return ==
return
# ---------------------------------------------------------------------------
# Exception
# ---------------------------------------------------------------------------
"""Raised by :class:`SynqroClient` when an operation returns an error.
Attributes
----------
status:
The :class:`SynqroStatus` error code.
message:
Human-readable error description.
error_id:
Audit-log correlation ID. Zero when not applicable.
Example
-------
::
try:
client.init("/etc/synqro_ota.yaml")
except SynqroException as exc:
logger.error("Init failed: %s (error_id=%d)", exc.message, exc.error_id)
"""
: =
: =
: =
=
=
=
# ---------------------------------------------------------------------------
# Library loading
# ---------------------------------------------------------------------------
"""Return the default shared-library file name for the current platform.
Raises
------
OSError
If the current platform is not supported.
"""
=
return
return
return
"""Locate and load the Synqro shared library.
Search order
------------
1. ``lib_path`` argument (if provided).
2. ``SYNQRO_LIB_PATH`` environment variable (exact path or directory).
3. OS default search path via ``ctypes.util.find_library``.
Parameters
----------
lib_path:
Explicit path to the shared library or a directory containing it.
``None`` triggers automatic resolution.
Returns
-------
ctypes.CDLL
The loaded library handle.
Raises
------
OSError
If the library cannot be found or loaded.
SynqroException
If ``lib_path`` exceeds :data:`SYNQRO_MAX_INPUT_LEN`.
"""
=
return
# --- 1. Explicit lib_path argument ----------------------------------------
=
return
return
# --- 2. SYNQRO_LIB_PATH environment variable ------------------------------
=
=
= /
return
return
# --- 3. OS default search (find_library + direct open) --------------------
=
return
# Last resort: let the OS loader resolve from its default paths.
return
# ---------------------------------------------------------------------------
# Argtypes / restype configuration
# ---------------------------------------------------------------------------
"""Bind argtypes and restype for every imported C function.
This is critical for correctness on 64-bit platforms where the C calling
convention differs from the Python default (``c_int``). All functions
must be configured before any call is made.
Parameters
----------
lib:
The loaded ctypes library handle.
"""
# synqro_init(const char* config_path) -> SynqroResult
=
=
# synqro_check_update(void) -> SynqroResult
=
=
# synqro_apply_update(void) -> SynqroResult
=
=
# synqro_rollback(void) -> SynqroResult
=
=
# synqro_version(void) -> const char*
=
=
# synqro_installation_id(void) -> char* (heap-allocated; caller frees)
=
= # avoid auto-free
# synqro_free_string(char* ptr) -> void
=
= None
# synqro_free_result(SynqroResult* result) -> void
=
= None
# synqro_audit_event(const char* event_type, const char* data_json) -> SynqroResult
=
=
# synqro_health_check(void) -> SynqroResult
=
=
# ---------------------------------------------------------------------------
# Internal helpers
# ---------------------------------------------------------------------------
"""Encode a Python string to UTF-8 bytes, validating the length.
Parameters
----------
value:
The string to encode.
name:
Parameter name used in the error message.
Returns
-------
bytes
NUL-terminated UTF-8 encoding suitable for passing to ``c_char_p``.
Raises
------
SynqroException
If the encoded byte length including the NUL terminator exceeds
:data:`SYNQRO_MAX_INPUT_LEN`.
"""
=
# +1 for the implicit NUL terminator added by ctypes
return
"""Translate a C ``_CResult`` to a Python :class:`SynqroResult`.
The C struct is freed via ``synqro_free_result`` before this function
returns. The ``message`` string is captured first.
Parameters
----------
c_result:
The raw C result struct (value, not pointer).
lib:
The loaded library handle (needed for ``synqro_free_result``).
Returns
-------
SynqroResult
The translated Python result.
"""
=
: | None =
=
=
# Free the C-side result struct.
=
return
# ---------------------------------------------------------------------------
# SynqroClient
# ---------------------------------------------------------------------------
"""High-level Python client for the Synqro OTA engine.
Wraps the C FFI interface exposed by ``libsynqro`` and provides a fully
idiomatic, type-annotated Python API. All C memory management is handled
internally; callers deal only with plain Python types.
Lifecycle
---------
1. Instantiate with :meth:`__init__` (loads the library).
2. Call :meth:`init` before any other method.
3. Call :meth:`close` or use as a context manager when done.
::
with SynqroClient() as client:
result = client.init("/etc/myapp/synqro_ota.yaml")
if not result.is_ok:
raise SynqroException(result)
update = client.check_update()
Thread Safety
-------------
:meth:`init` must complete on a single thread before concurrent use.
:meth:`apply_update` and :meth:`rollback` must not be called
concurrently; all other methods are thread-safe after :meth:`init`.
Parameters
----------
lib_path:
Optional explicit path to the Synqro shared library or a directory
containing it. ``None`` triggers automatic platform-based resolution.
"""
: =
: = False
# -------------------------------------------------------------------------
# Internal guards
# -------------------------------------------------------------------------
"""Raise :exc:`RuntimeError` if the client has been closed."""
# -------------------------------------------------------------------------
# Public API
# -------------------------------------------------------------------------
"""Initialise the Synqro OTA engine.
Must be called exactly once before any other method. Parses and
validates ``synqro_ota.yaml``, sets up the audit log, seeds the
CSPRNG, and loads trusted key material.
Parameters
----------
config_path:
Absolute or relative path to the ``synqro_ota.yaml`` configuration
file. Must not be empty. Maximum encoded length:
:data:`SYNQRO_MAX_INPUT_LEN` bytes (including NUL).
Returns
-------
SynqroResult
Indicates success or the reason for failure.
Raises
------
SynqroException
If ``config_path`` is empty or exceeds :data:`SYNQRO_MAX_INPUT_LEN`.
RuntimeError
If :meth:`close` has already been called.
"""
=
=
return
"""Check whether a software update is available.
Contacts the update endpoint from ``synqro_ota.yaml``, authenticates
the server via TLS, fetches the signed manifest, and verifies the
Ed25519 signature.
Returns
-------
SynqroResult
On success, :attr:`SynqroResult.message` indicates whether an
update is available (e.g. ``"update_available:1.2.3"`` vs
``"up_to_date"``).
Raises
------
RuntimeError
If :meth:`close` has already been called.
"""
=
return
"""Download and atomically apply the latest software update.
Downloads the update payload, verifies the Ed25519 signature, stages
it in ``.synqro_cache/staging/``, backs up the current installation
to ``.synqro_cache/backup/``, and atomically swaps the new version
into place.
On any failure the previous version is left completely intact.
.. warning::
Must not be called concurrently with :meth:`rollback` or another
:meth:`apply_update`.
Returns
-------
SynqroResult
Raises
------
RuntimeError
If :meth:`close` has already been called.
"""
=
return
"""Roll back to the previously installed version.
Restores the backup snapshot from ``.synqro_cache/backup/``. The
backup SHA-256 checksum is verified before restoration; a corrupted
backup is rejected with :attr:`SynqroStatus.ERR_ROLLBACK`.
.. warning::
Must not be called concurrently with :meth:`apply_update` or
another :meth:`rollback`.
Returns
-------
SynqroResult
Raises
------
RuntimeError
If :meth:`close` has already been called.
"""
=
return
"""Return the Synqro engine version string (e.g. ``"1.0.0"``).
The returned string comes from a static constant in the library and
never changes for a given process lifetime. Safe to call before
:meth:`init`.
Returns
-------
str
Version string in ``"MAJOR.MINOR.PATCH"`` format.
Raises
------
RuntimeError
If :meth:`close` has already been called.
"""
# synqro_version() returns a static string; ctypes c_char_p decodes
# it automatically. Do NOT pass through synqro_free_string.
: | None =
return
return
"""Return the unique installation identifier (UUID v4, no PII).
Calls ``synqro_installation_id()`` which returns a heap-allocated
string. The C string is freed via ``synqro_free_string`` inside a
``try/finally`` block before this method returns.
Returns
-------
str
UUID v4 string, or an empty string on error.
Raises
------
RuntimeError
If :meth:`close` has already been called.
"""
# restype is c_void_p to suppress ctypes auto-free behaviour.
: | None =
return
# Cast the raw address to c_char_p to read the string content.
=
: | None =
return
"""Record a custom event in the tamper-evident audit log.
Parameters
----------
event_type:
Event-type string. Should be one of the ``SYNQRO_EVENT_*``
constants or a reverse-DNS namespaced string for application-
defined events. Must not be empty. Maximum encoded length:
:data:`SYNQRO_MAX_INPUT_LEN` bytes (including NUL).
data_json:
Optional JSON string with supplementary event data. Pass
``None`` if there is no supplementary data. Maximum encoded
length: :data:`SYNQRO_MAX_INPUT_LEN` bytes (including NUL).
Must be valid JSON if provided.
Returns
-------
SynqroResult
Raises
------
SynqroException
If ``event_type`` is empty or either string exceeds
:data:`SYNQRO_MAX_INPUT_LEN`.
RuntimeError
If :meth:`close` has already been called.
"""
=
: | None = None
=
=
return
"""Perform an engine health check.
Verifies that the audit log is intact, cache directories are accessible,
and the update endpoint is reachable. Intended for liveness probes and
CI pipelines.
Returns
-------
SynqroResult
Raises
------
RuntimeError
If :meth:`close` has already been called.
"""
=
return
# -------------------------------------------------------------------------
# Lifecycle
# -------------------------------------------------------------------------
"""Release all resources held by this client.
After calling :meth:`close`, all method calls will raise
:exc:`RuntimeError`. Safe to call multiple times; subsequent calls
are no-ops.
"""
return
= True
# -------------------------------------------------------------------------
# Context manager protocol
# -------------------------------------------------------------------------
"""Return ``self`` to support use as a context manager."""
return
"""Call :meth:`close` and do not suppress any exception."""
return False
=
return f