railid-native 4.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
railid/__init__.py
ADDED
|
@@ -0,0 +1,585 @@
|
|
|
1
|
+
"""Python bindings for RailID through the ``railid-capi`` C ABI.
|
|
2
|
+
|
|
3
|
+
The package is a thin, dependency-free ``ctypes`` wrapper. It never falls
|
|
4
|
+
back from the TPM profile to OS randomness: a missing TPM is reported as
|
|
5
|
+
:class:`RailidError` with code :attr:`ErrorCode.TpmUnavailable`.
|
|
6
|
+
|
|
7
|
+
The native shared library is loaded lazily on first use. Set
|
|
8
|
+
``RAILID_LIBRARY`` to its path (or to the directory containing it), or build
|
|
9
|
+
it into one of the conventional ``target/release`` directories documented in
|
|
10
|
+
the package README.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import ctypes
|
|
16
|
+
import ctypes.util
|
|
17
|
+
import os
|
|
18
|
+
import sys
|
|
19
|
+
import threading
|
|
20
|
+
from enum import Enum, IntEnum
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import List, NoReturn, Optional, Union
|
|
23
|
+
|
|
24
|
+
__version__ = "4.4.0"
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"ABI_VERSION",
|
|
28
|
+
"ENCODED_LEN",
|
|
29
|
+
"V4_ENCODED_LEN",
|
|
30
|
+
"MAX_TPM_BATCH_IDS",
|
|
31
|
+
"MAX_OS_ONLY_BATCH_IDS",
|
|
32
|
+
"Profile",
|
|
33
|
+
"ErrorCode",
|
|
34
|
+
"RailidError",
|
|
35
|
+
"LibraryError",
|
|
36
|
+
"PROFILE_TPM",
|
|
37
|
+
"PROFILE_OS_ONLY",
|
|
38
|
+
"PROFILE_TPM_HYBRID",
|
|
39
|
+
"PROFILE_OS_ONLY_DEGRADED",
|
|
40
|
+
"RAILID_PROFILE_TPM_HYBRID",
|
|
41
|
+
"RAILID_PROFILE_OS_ONLY",
|
|
42
|
+
"RAILID_OK",
|
|
43
|
+
"RAILID_ERROR_NULL_POINTER",
|
|
44
|
+
"RAILID_ERROR_BUFFER_TOO_SMALL",
|
|
45
|
+
"RAILID_ERROR_TIMESTAMP_OUT_OF_RANGE",
|
|
46
|
+
"RAILID_ERROR_TPM_UNAVAILABLE",
|
|
47
|
+
"RAILID_ERROR_TPM_RANDOM_FAILURE",
|
|
48
|
+
"RAILID_ERROR_OS_RANDOM_FAILURE",
|
|
49
|
+
"RAILID_ERROR_CAPACITY_OVERFLOW",
|
|
50
|
+
"RAILID_ERROR_INVALID_INPUT",
|
|
51
|
+
"RAILID_ERROR_INVALID_PROFILE",
|
|
52
|
+
"RAILID_ERROR_PANIC",
|
|
53
|
+
"OK",
|
|
54
|
+
"NULL_POINTER",
|
|
55
|
+
"BUFFER_TOO_SMALL",
|
|
56
|
+
"TIMESTAMP_OUT_OF_RANGE",
|
|
57
|
+
"TPM_UNAVAILABLE",
|
|
58
|
+
"TPM_RANDOM_FAILURE",
|
|
59
|
+
"OS_RANDOM_FAILURE",
|
|
60
|
+
"CAPACITY_OVERFLOW",
|
|
61
|
+
"INVALID_INPUT",
|
|
62
|
+
"INVALID_PROFILE",
|
|
63
|
+
"PANIC",
|
|
64
|
+
"TpmUnavailable",
|
|
65
|
+
"TpmRandomFailure",
|
|
66
|
+
"OsRandomFailure",
|
|
67
|
+
"CapacityOverflow",
|
|
68
|
+
"InvalidProfile",
|
|
69
|
+
"abi_version",
|
|
70
|
+
"version",
|
|
71
|
+
"error_message",
|
|
72
|
+
"generate",
|
|
73
|
+
"generate_v4",
|
|
74
|
+
"generate_many_encoded",
|
|
75
|
+
"reset_after_fork",
|
|
76
|
+
"library_path",
|
|
77
|
+
]
|
|
78
|
+
|
|
79
|
+
#: C ABI revision this wrapper expects (``RAILID_ABI_VERSION``).
|
|
80
|
+
ABI_VERSION = 4
|
|
81
|
+
#: Bytes in one v1 RailID (192 bits, unpadded Base64URL).
|
|
82
|
+
ENCODED_LEN = 32
|
|
83
|
+
#: Bytes in one v4 RailID (126 bits, unpadded Base64URL).
|
|
84
|
+
V4_ENCODED_LEN = 21
|
|
85
|
+
#: Largest TPM batch accepted by the C ABI.
|
|
86
|
+
MAX_TPM_BATCH_IDS = 1_024
|
|
87
|
+
#: Largest OS-only batch accepted by the C ABI.
|
|
88
|
+
MAX_OS_ONLY_BATCH_IDS = 1_000_000
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class ErrorCode(IntEnum):
|
|
92
|
+
"""A documented RailID status code.
|
|
93
|
+
|
|
94
|
+
Known codes compare and behave like ``int``. :class:`RailidError` stores
|
|
95
|
+
an unknown future code as a plain ``int`` instead of rejecting it.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
OK = 0
|
|
99
|
+
NullPointer = -1
|
|
100
|
+
BufferTooSmall = -2
|
|
101
|
+
TimestampOutOfRange = -3
|
|
102
|
+
TpmUnavailable = -4
|
|
103
|
+
TpmRandomFailure = -5
|
|
104
|
+
OsRandomFailure = -6
|
|
105
|
+
CapacityOverflow = -7
|
|
106
|
+
InvalidInput = -8
|
|
107
|
+
InvalidProfile = -9
|
|
108
|
+
Panic = -99
|
|
109
|
+
|
|
110
|
+
# Lower-case aliases for callers that prefer the Rust variant spelling.
|
|
111
|
+
Ok = OK
|
|
112
|
+
# Upper-case aliases for callers that follow the C header spelling.
|
|
113
|
+
NULL_POINTER = NullPointer
|
|
114
|
+
BUFFER_TOO_SMALL = BufferTooSmall
|
|
115
|
+
TIMESTAMP_OUT_OF_RANGE = TimestampOutOfRange
|
|
116
|
+
TPM_UNAVAILABLE = TpmUnavailable
|
|
117
|
+
TPM_RANDOM_FAILURE = TpmRandomFailure
|
|
118
|
+
OS_RANDOM_FAILURE = OsRandomFailure
|
|
119
|
+
CAPACITY_OVERFLOW = CapacityOverflow
|
|
120
|
+
INVALID_INPUT = InvalidInput
|
|
121
|
+
INVALID_PROFILE = InvalidProfile
|
|
122
|
+
PANIC = Panic
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
# C header names, useful when porting code from the C ABI.
|
|
126
|
+
RAILID_OK = ErrorCode.OK
|
|
127
|
+
RAILID_ERROR_NULL_POINTER = ErrorCode.NullPointer
|
|
128
|
+
RAILID_ERROR_BUFFER_TOO_SMALL = ErrorCode.BufferTooSmall
|
|
129
|
+
RAILID_ERROR_TIMESTAMP_OUT_OF_RANGE = ErrorCode.TimestampOutOfRange
|
|
130
|
+
RAILID_ERROR_TPM_UNAVAILABLE = ErrorCode.TpmUnavailable
|
|
131
|
+
RAILID_ERROR_TPM_RANDOM_FAILURE = ErrorCode.TpmRandomFailure
|
|
132
|
+
RAILID_ERROR_OS_RANDOM_FAILURE = ErrorCode.OsRandomFailure
|
|
133
|
+
RAILID_ERROR_CAPACITY_OVERFLOW = ErrorCode.CapacityOverflow
|
|
134
|
+
RAILID_ERROR_INVALID_INPUT = ErrorCode.InvalidInput
|
|
135
|
+
RAILID_ERROR_INVALID_PROFILE = ErrorCode.InvalidProfile
|
|
136
|
+
RAILID_ERROR_PANIC = ErrorCode.Panic
|
|
137
|
+
|
|
138
|
+
# Convenient short aliases for the most commonly tested codes.
|
|
139
|
+
OK = ErrorCode.OK
|
|
140
|
+
NULL_POINTER = ErrorCode.NullPointer
|
|
141
|
+
BUFFER_TOO_SMALL = ErrorCode.BufferTooSmall
|
|
142
|
+
TIMESTAMP_OUT_OF_RANGE = ErrorCode.TimestampOutOfRange
|
|
143
|
+
TPM_UNAVAILABLE = ErrorCode.TpmUnavailable
|
|
144
|
+
TPM_RANDOM_FAILURE = ErrorCode.TpmRandomFailure
|
|
145
|
+
OS_RANDOM_FAILURE = ErrorCode.OsRandomFailure
|
|
146
|
+
CAPACITY_OVERFLOW = ErrorCode.CapacityOverflow
|
|
147
|
+
INVALID_INPUT = ErrorCode.InvalidInput
|
|
148
|
+
INVALID_PROFILE = ErrorCode.InvalidProfile
|
|
149
|
+
PANIC = ErrorCode.Panic
|
|
150
|
+
TpmUnavailable = ErrorCode.TpmUnavailable
|
|
151
|
+
TpmRandomFailure = ErrorCode.TpmRandomFailure
|
|
152
|
+
OsRandomFailure = ErrorCode.OsRandomFailure
|
|
153
|
+
CapacityOverflow = ErrorCode.CapacityOverflow
|
|
154
|
+
InvalidProfile = ErrorCode.InvalidProfile
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class Profile(str, Enum):
|
|
158
|
+
"""Generation profile.
|
|
159
|
+
|
|
160
|
+
Members are strings, so ``Profile.TPM == "tpm"``. Plain strings
|
|
161
|
+
``"tpm"`` and ``"os-only"`` are accepted everywhere a profile is expected.
|
|
162
|
+
"""
|
|
163
|
+
|
|
164
|
+
TPM = "tpm"
|
|
165
|
+
OS_ONLY = "os-only"
|
|
166
|
+
# Aliases.
|
|
167
|
+
Tpm = TPM
|
|
168
|
+
OsOnly = OS_ONLY
|
|
169
|
+
TPM_HYBRID = TPM
|
|
170
|
+
OS_ONLY_DEGRADED = OS_ONLY
|
|
171
|
+
|
|
172
|
+
@classmethod
|
|
173
|
+
def _missing_(cls, value: object) -> Optional["Profile"]:
|
|
174
|
+
if isinstance(value, str):
|
|
175
|
+
normalized = _normalize_profile(value)
|
|
176
|
+
for member in cls:
|
|
177
|
+
if member.value == normalized:
|
|
178
|
+
return member
|
|
179
|
+
return None
|
|
180
|
+
|
|
181
|
+
@property
|
|
182
|
+
def code(self) -> int:
|
|
183
|
+
"""C ABI profile selector (0 = TPM hybrid, 1 = OS-only)."""
|
|
184
|
+
if self is Profile.TPM:
|
|
185
|
+
return 0
|
|
186
|
+
if self is Profile.OS_ONLY:
|
|
187
|
+
return 1
|
|
188
|
+
raise AssertionError("unhandled profile: %r" % (self,))
|
|
189
|
+
|
|
190
|
+
__str__ = str.__str__
|
|
191
|
+
|
|
192
|
+
def __repr__(self) -> str:
|
|
193
|
+
return "Profile.%s" % ("TPM" if self is Profile.TPM else "OS_ONLY")
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _normalize_profile(value: str) -> str:
|
|
197
|
+
text = value.strip().lower().replace("_", "-").replace(" ", "-")
|
|
198
|
+
aliases = {
|
|
199
|
+
"tpm": "tpm",
|
|
200
|
+
"tpm-hybrid": "tpm",
|
|
201
|
+
"hybrid": "tpm",
|
|
202
|
+
"os": "os-only",
|
|
203
|
+
"os-only": "os-only",
|
|
204
|
+
"os-only-degraded": "os-only",
|
|
205
|
+
"degraded": "os-only",
|
|
206
|
+
}
|
|
207
|
+
return aliases.get(text, text)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
PROFILE_TPM = Profile.TPM
|
|
211
|
+
PROFILE_TPM_HYBRID = Profile.TPM
|
|
212
|
+
PROFILE_OS_ONLY = Profile.OS_ONLY
|
|
213
|
+
PROFILE_OS_ONLY_DEGRADED = Profile.OS_ONLY
|
|
214
|
+
RAILID_PROFILE_TPM_HYBRID = Profile.TPM
|
|
215
|
+
RAILID_PROFILE_OS_ONLY = Profile.OS_ONLY
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
class RailidError(RuntimeError):
|
|
219
|
+
"""A failure reported by the RailID C ABI.
|
|
220
|
+
|
|
221
|
+
Attributes:
|
|
222
|
+
code: The numeric C status code (negative on failure).
|
|
223
|
+
message: The library's human-readable message, from
|
|
224
|
+
``railid_error_message``.
|
|
225
|
+
detail: Optional wrapper-added context (for example the rejected
|
|
226
|
+
profile string).
|
|
227
|
+
"""
|
|
228
|
+
|
|
229
|
+
def __init__(
|
|
230
|
+
self,
|
|
231
|
+
code: int,
|
|
232
|
+
message: Optional[str] = None,
|
|
233
|
+
detail: Optional[str] = None,
|
|
234
|
+
) -> None:
|
|
235
|
+
numeric = int(code)
|
|
236
|
+
try:
|
|
237
|
+
self.code = ErrorCode(numeric)
|
|
238
|
+
except ValueError:
|
|
239
|
+
# Preserve a future code from a newer library instead of failing
|
|
240
|
+
# while constructing the exception.
|
|
241
|
+
self.code = numeric
|
|
242
|
+
self.message = message if message is not None else error_message(numeric)
|
|
243
|
+
self.detail = detail
|
|
244
|
+
text = "%s (code %d)" % (self.message, self.code)
|
|
245
|
+
if detail:
|
|
246
|
+
text = "%s: %s" % (text, detail)
|
|
247
|
+
super().__init__(text)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
class LibraryError(RuntimeError):
|
|
251
|
+
"""The RailID shared library could not be found or loaded."""
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
# ---------------------------------------------------------------------------
|
|
255
|
+
# Native library loading
|
|
256
|
+
# ---------------------------------------------------------------------------
|
|
257
|
+
|
|
258
|
+
_LIBRARY: Optional[ctypes.CDLL] = None
|
|
259
|
+
_LIBRARY_PATH: Optional[str] = None
|
|
260
|
+
_LIBRARY_LOCK = threading.Lock()
|
|
261
|
+
_ALPHABET = frozenset(
|
|
262
|
+
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
|
|
263
|
+
)
|
|
264
|
+
_ALPHABET_BYTES = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _library_filename() -> str:
|
|
268
|
+
if sys.platform == "win32":
|
|
269
|
+
return "railid.dll"
|
|
270
|
+
if sys.platform == "darwin":
|
|
271
|
+
return "librailid.dylib"
|
|
272
|
+
return "librailid.so"
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _candidate_paths() -> List[str]:
|
|
276
|
+
"""Return candidate paths in discovery order, without duplicates."""
|
|
277
|
+
name = _library_filename()
|
|
278
|
+
package_dir = Path(__file__).resolve().parent
|
|
279
|
+
roots = [
|
|
280
|
+
package_dir,
|
|
281
|
+
package_dir.parent,
|
|
282
|
+
package_dir.parent.parent,
|
|
283
|
+
Path.cwd(),
|
|
284
|
+
]
|
|
285
|
+
candidates: List[str] = []
|
|
286
|
+
seen = set()
|
|
287
|
+
for root in roots:
|
|
288
|
+
for subdir in ("railid-capi/target/release", "target/release", ""):
|
|
289
|
+
candidate = (root / subdir / name).resolve()
|
|
290
|
+
key = str(candidate).lower() if os.name == "nt" else str(candidate)
|
|
291
|
+
if key not in seen:
|
|
292
|
+
seen.add(key)
|
|
293
|
+
candidates.append(str(candidate))
|
|
294
|
+
|
|
295
|
+
found = ctypes.util.find_library("railid")
|
|
296
|
+
if found:
|
|
297
|
+
candidates.append(found)
|
|
298
|
+
return candidates
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _configure(library: ctypes.CDLL) -> None:
|
|
302
|
+
"""Declare every signature we use before making a call."""
|
|
303
|
+
try:
|
|
304
|
+
library.railid_abi_version.argtypes = []
|
|
305
|
+
library.railid_abi_version.restype = ctypes.c_uint32
|
|
306
|
+
|
|
307
|
+
library.railid_version.argtypes = []
|
|
308
|
+
library.railid_version.restype = ctypes.c_char_p
|
|
309
|
+
|
|
310
|
+
library.railid_error_message.argtypes = [ctypes.c_int32]
|
|
311
|
+
library.railid_error_message.restype = ctypes.c_char_p
|
|
312
|
+
|
|
313
|
+
for function_name in (
|
|
314
|
+
"railid_generate_encoded",
|
|
315
|
+
"railid_generate_os_only_encoded",
|
|
316
|
+
"railid_v4_generate_encoded",
|
|
317
|
+
"railid_v4_generate_os_only_encoded",
|
|
318
|
+
):
|
|
319
|
+
function = getattr(library, function_name)
|
|
320
|
+
function.argtypes = [ctypes.POINTER(ctypes.c_ubyte), ctypes.c_size_t]
|
|
321
|
+
function.restype = ctypes.c_int32
|
|
322
|
+
|
|
323
|
+
library.railid_generate_many_encoded.argtypes = [
|
|
324
|
+
ctypes.c_uint32,
|
|
325
|
+
ctypes.c_size_t,
|
|
326
|
+
ctypes.POINTER(ctypes.c_ubyte),
|
|
327
|
+
ctypes.c_size_t,
|
|
328
|
+
]
|
|
329
|
+
library.railid_generate_many_encoded.restype = ctypes.c_int32
|
|
330
|
+
|
|
331
|
+
library.railid_reset_after_fork.argtypes = []
|
|
332
|
+
library.railid_reset_after_fork.restype = None
|
|
333
|
+
except AttributeError as exc:
|
|
334
|
+
raise AttributeError("missing RailID C ABI symbol: %s" % (exc,)) from exc
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _try_load(path: str) -> ctypes.CDLL:
|
|
338
|
+
library = ctypes.CDLL(path)
|
|
339
|
+
_configure(library)
|
|
340
|
+
abi = int(library.railid_abi_version())
|
|
341
|
+
if abi != ABI_VERSION:
|
|
342
|
+
raise RuntimeError(
|
|
343
|
+
"unsupported RailID C ABI version %d (this package requires %d)"
|
|
344
|
+
% (abi, ABI_VERSION)
|
|
345
|
+
)
|
|
346
|
+
return library
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _library() -> ctypes.CDLL:
|
|
350
|
+
"""Load and cache the native library."""
|
|
351
|
+
global _LIBRARY, _LIBRARY_PATH
|
|
352
|
+
if _LIBRARY is not None:
|
|
353
|
+
return _LIBRARY
|
|
354
|
+
|
|
355
|
+
with _LIBRARY_LOCK:
|
|
356
|
+
if _LIBRARY is not None:
|
|
357
|
+
return _LIBRARY
|
|
358
|
+
|
|
359
|
+
env_path = os.environ.get("RAILID_LIBRARY")
|
|
360
|
+
strict_env = bool(env_path)
|
|
361
|
+
if env_path:
|
|
362
|
+
expanded = os.path.expanduser(os.path.expandvars(env_path))
|
|
363
|
+
if os.path.isdir(expanded):
|
|
364
|
+
expanded = os.path.join(expanded, _library_filename())
|
|
365
|
+
candidates = [expanded]
|
|
366
|
+
else:
|
|
367
|
+
candidates = _candidate_paths()
|
|
368
|
+
|
|
369
|
+
failures: List[str] = []
|
|
370
|
+
for candidate in candidates:
|
|
371
|
+
try:
|
|
372
|
+
library = _try_load(candidate)
|
|
373
|
+
except (OSError, AttributeError, RuntimeError) as exc:
|
|
374
|
+
failures.append("%s: %s" % (candidate, exc))
|
|
375
|
+
continue
|
|
376
|
+
_LIBRARY = library
|
|
377
|
+
_LIBRARY_PATH = candidate
|
|
378
|
+
return library
|
|
379
|
+
|
|
380
|
+
tried = "\n ".join(failures) if failures else " (no candidates)"
|
|
381
|
+
if strict_env:
|
|
382
|
+
raise LibraryError(
|
|
383
|
+
"RAILID_LIBRARY is set but the RailID shared library could not "
|
|
384
|
+
"be loaded from %r:\n %s" % (env_path, tried)
|
|
385
|
+
)
|
|
386
|
+
raise LibraryError(
|
|
387
|
+
"could not load the RailID shared library (%s). Build it with "
|
|
388
|
+
"`cargo build --manifest-path railid-capi/Cargo.toml --release` and "
|
|
389
|
+
"set RAILID_LIBRARY to the resulting file or directory. Tried:\n %s"
|
|
390
|
+
% (_library_filename(), tried)
|
|
391
|
+
)
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def library_path() -> str:
|
|
395
|
+
"""Return the path of the loaded shared library."""
|
|
396
|
+
_library()
|
|
397
|
+
assert _LIBRARY_PATH is not None
|
|
398
|
+
return _LIBRARY_PATH
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
# ---------------------------------------------------------------------------
|
|
402
|
+
# Output validation
|
|
403
|
+
# ---------------------------------------------------------------------------
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _validate_encoded_text(text: str, expected: int, what: str) -> None:
|
|
407
|
+
if len(text) != expected:
|
|
408
|
+
raise RuntimeError(
|
|
409
|
+
"unexpected %s length from RailID: expected %d, got %d"
|
|
410
|
+
% (what, expected, len(text))
|
|
411
|
+
)
|
|
412
|
+
for index, character in enumerate(text):
|
|
413
|
+
if character not in _ALPHABET:
|
|
414
|
+
raise RuntimeError(
|
|
415
|
+
"invalid Base64URL character in %s at offset %d: %r"
|
|
416
|
+
% (what, index, character)
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _decode_output(raw: bytes, expected: int, what: str) -> str:
|
|
421
|
+
if len(raw) != expected:
|
|
422
|
+
raise RuntimeError(
|
|
423
|
+
"unexpected %s length from RailID: expected %d, got %d"
|
|
424
|
+
% (what, expected, len(raw))
|
|
425
|
+
)
|
|
426
|
+
try:
|
|
427
|
+
text = raw.decode("ascii")
|
|
428
|
+
except UnicodeDecodeError as exc:
|
|
429
|
+
raise RuntimeError("non-ASCII %s returned by RailID" % (what,)) from exc
|
|
430
|
+
_validate_encoded_text(text, expected, what)
|
|
431
|
+
return text
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def _decode_batch(raw: bytes, count: int) -> bytes:
|
|
435
|
+
expected = count * ENCODED_LEN
|
|
436
|
+
if len(raw) != expected:
|
|
437
|
+
raise RuntimeError(
|
|
438
|
+
"unexpected batch length from RailID: expected %d, got %d"
|
|
439
|
+
% (expected, len(raw))
|
|
440
|
+
)
|
|
441
|
+
# Validate the whole block in one C-level translate call instead of
|
|
442
|
+
# looping over every 32-byte segment in Python. The alphabet is ASCII, so
|
|
443
|
+
# an invalid byte is also a non-ASCII/invalid-character failure.
|
|
444
|
+
invalid = raw.translate(None, _ALPHABET_BYTES)
|
|
445
|
+
if invalid:
|
|
446
|
+
offset = next(
|
|
447
|
+
index for index, byte in enumerate(raw) if byte not in _ALPHABET_BYTES
|
|
448
|
+
)
|
|
449
|
+
raise RuntimeError(
|
|
450
|
+
"invalid Base64URL character in v1 batch at offset %d: %r"
|
|
451
|
+
% (offset, chr(raw[offset]))
|
|
452
|
+
)
|
|
453
|
+
return raw
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def _check(status: int) -> None:
|
|
457
|
+
if int(status) != 0:
|
|
458
|
+
raise RailidError(int(status))
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _raise_error(code: int, detail: Optional[str] = None) -> NoReturn:
|
|
462
|
+
raise RailidError(code, detail=detail)
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def _coerce_profile(profile: Union[Profile, str]) -> Profile:
|
|
466
|
+
if isinstance(profile, Profile):
|
|
467
|
+
return profile
|
|
468
|
+
if not isinstance(profile, str):
|
|
469
|
+
_raise_error(
|
|
470
|
+
ErrorCode.InvalidProfile,
|
|
471
|
+
"expected Profile or str, got %s" % (type(profile).__name__,),
|
|
472
|
+
)
|
|
473
|
+
try:
|
|
474
|
+
return Profile(profile)
|
|
475
|
+
except (TypeError, ValueError):
|
|
476
|
+
_raise_error(ErrorCode.InvalidProfile, repr(profile))
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
# ---------------------------------------------------------------------------
|
|
480
|
+
# Public API
|
|
481
|
+
# ---------------------------------------------------------------------------
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def abi_version() -> int:
|
|
485
|
+
"""Return the C ABI revision of the loaded library."""
|
|
486
|
+
return int(_library().railid_abi_version())
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def version() -> str:
|
|
490
|
+
"""Return the native library's crate version (for example ``"4.4.0"``)."""
|
|
491
|
+
raw = _library().railid_version()
|
|
492
|
+
if not raw:
|
|
493
|
+
raise RuntimeError("railid_version returned a null pointer")
|
|
494
|
+
return raw.decode("utf-8")
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def error_message(code: int) -> str:
|
|
498
|
+
"""Return the library's message for a C status code."""
|
|
499
|
+
raw = _library().railid_error_message(ctypes.c_int32(int(code)))
|
|
500
|
+
if not raw:
|
|
501
|
+
raise RuntimeError("railid_error_message returned a null pointer")
|
|
502
|
+
return raw.decode("utf-8", "replace")
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def generate(profile: Union[Profile, str] = Profile.TPM) -> str:
|
|
506
|
+
"""Generate one 32-character RailID v1 value.
|
|
507
|
+
|
|
508
|
+
The TPM profile is fail-closed: if no usable TPM is available this raises
|
|
509
|
+
:class:`RailidError` with :attr:`ErrorCode.TpmUnavailable`. It never
|
|
510
|
+
silently uses the OS-only profile.
|
|
511
|
+
"""
|
|
512
|
+
library = _library()
|
|
513
|
+
selected = _coerce_profile(profile)
|
|
514
|
+
buffer = (ctypes.c_ubyte * ENCODED_LEN)()
|
|
515
|
+
if selected.code == 0:
|
|
516
|
+
status = library.railid_generate_encoded(buffer, ENCODED_LEN)
|
|
517
|
+
else:
|
|
518
|
+
status = library.railid_generate_os_only_encoded(buffer, ENCODED_LEN)
|
|
519
|
+
_check(status)
|
|
520
|
+
return _decode_output(bytes(buffer), ENCODED_LEN, "v1 ID")
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def generate_v4(profile: Union[Profile, str] = Profile.TPM) -> str:
|
|
524
|
+
"""Generate one 21-character RailID v4 value (126 bits)."""
|
|
525
|
+
library = _library()
|
|
526
|
+
selected = _coerce_profile(profile)
|
|
527
|
+
buffer = (ctypes.c_ubyte * V4_ENCODED_LEN)()
|
|
528
|
+
if selected.code == 0:
|
|
529
|
+
status = library.railid_v4_generate_encoded(buffer, V4_ENCODED_LEN)
|
|
530
|
+
else:
|
|
531
|
+
status = library.railid_v4_generate_os_only_encoded(
|
|
532
|
+
buffer, V4_ENCODED_LEN
|
|
533
|
+
)
|
|
534
|
+
_check(status)
|
|
535
|
+
return _decode_output(bytes(buffer), V4_ENCODED_LEN, "v4 ID")
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def generate_many_encoded(
|
|
539
|
+
profile: Union[Profile, str] = Profile.TPM, count: int = 0
|
|
540
|
+
) -> bytes:
|
|
541
|
+
"""Generate ``count`` v1 IDs as one contiguous ``32 * count`` byte block.
|
|
542
|
+
|
|
543
|
+
A zero count is a successful no-op, matching the C ABI. The C ABI's
|
|
544
|
+
per-profile batch caps are enforced before allocating, and violations
|
|
545
|
+
raise :class:`RailidError` with
|
|
546
|
+
:attr:`ErrorCode.CapacityOverflow`.
|
|
547
|
+
"""
|
|
548
|
+
if isinstance(count, bool) or not isinstance(count, int):
|
|
549
|
+
raise TypeError("count must be an integer")
|
|
550
|
+
if count < 0:
|
|
551
|
+
raise ValueError("count must be non-negative")
|
|
552
|
+
if count == 0:
|
|
553
|
+
return b""
|
|
554
|
+
|
|
555
|
+
library = _library()
|
|
556
|
+
selected = _coerce_profile(profile)
|
|
557
|
+
limit = (
|
|
558
|
+
MAX_TPM_BATCH_IDS if selected.code == 0 else MAX_OS_ONLY_BATCH_IDS
|
|
559
|
+
)
|
|
560
|
+
if count > limit:
|
|
561
|
+
_raise_error(
|
|
562
|
+
ErrorCode.CapacityOverflow,
|
|
563
|
+
"count %d exceeds the %s C ABI limit of %d"
|
|
564
|
+
% (
|
|
565
|
+
count,
|
|
566
|
+
"TPM" if selected.code == 0 else "OS-only",
|
|
567
|
+
limit,
|
|
568
|
+
),
|
|
569
|
+
)
|
|
570
|
+
|
|
571
|
+
total = count * ENCODED_LEN
|
|
572
|
+
buffer = (ctypes.c_ubyte * total)()
|
|
573
|
+
status = library.railid_generate_many_encoded(
|
|
574
|
+
ctypes.c_uint32(selected.code),
|
|
575
|
+
ctypes.c_size_t(count),
|
|
576
|
+
buffer,
|
|
577
|
+
ctypes.c_size_t(total),
|
|
578
|
+
)
|
|
579
|
+
_check(status)
|
|
580
|
+
return _decode_batch(bytes(buffer), count)
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def reset_after_fork() -> None:
|
|
584
|
+
"""Discard cached randomness/timestamps after a ``fork()``."""
|
|
585
|
+
_library().railid_reset_after_fork()
|
railid/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: railid-native
|
|
3
|
+
Version: 4.4.0
|
|
4
|
+
Summary: Dependency-free Python bindings for RailID via the railid-capi C ABI
|
|
5
|
+
Author: Nekomakura
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/LunaLaboratory/Rail-ID
|
|
8
|
+
Project-URL: Issues, https://github.com/LunaLaboratory/Rail-ID/issues
|
|
9
|
+
Keywords: railid,identifier,uuid,tpm,ctypes
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.9
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# railid-native (Python)
|
|
27
|
+
|
|
28
|
+
Dependency-free Python bindings for [RailID](https://github.com/LunaLaboratory/Rail-ID),
|
|
29
|
+
implemented with the standard library's `ctypes` module on top of the
|
|
30
|
+
`railid-capi` C ABI (ABI revision 4).
|
|
31
|
+
|
|
32
|
+
The distribution is named `railid-native`; the import package is `railid`.
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
import railid
|
|
36
|
+
|
|
37
|
+
print(railid.version(), railid.abi_version()) # e.g. 4.4.0 4
|
|
38
|
+
print(railid.generate("os-only")) # 32-char RailID v1
|
|
39
|
+
print(railid.generate_v4("os-only")) # 21-char RailID v4
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Requirements
|
|
43
|
+
|
|
44
|
+
- Python 3.9 or newer (CPython; other ctypes-capable implementations may work).
|
|
45
|
+
- A built `railid` shared library:
|
|
46
|
+
- Windows: `railid.dll`
|
|
47
|
+
- Linux: `librailid.so`
|
|
48
|
+
- macOS: `librailid.dylib`
|
|
49
|
+
|
|
50
|
+
Build the C ABI from the repository root:
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
cargo build --manifest-path railid-capi/Cargo.toml --release
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Add `--features tpm` to include the TPM 2.0 hybrid backend. Linux TPM builds
|
|
57
|
+
need `pkg-config` and `libtss2-dev`; Windows TPM builds use TBS.
|
|
58
|
+
|
|
59
|
+
## Installation
|
|
60
|
+
|
|
61
|
+
From a checkout (no PyPI release is produced):
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
python -m pip install ./python
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
For development use an editable install:
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
python -m pip install -e ./python
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
The wheel contains only this package and `py.typed` (the sdist also carries
|
|
74
|
+
the tests and packaging metadata); it does **not** bundle a native library.
|
|
75
|
+
Install or build the C ABI separately and point `RAILID_LIBRARY` at it.
|
|
76
|
+
|
|
77
|
+
## Library discovery
|
|
78
|
+
|
|
79
|
+
The loader is lazy and uses the first library that loads successfully:
|
|
80
|
+
|
|
81
|
+
1. `RAILID_LIBRARY` Ea path to the shared library, or to a directory
|
|
82
|
+
containing it. If this variable is set, it is authoritative: a load
|
|
83
|
+
failure raises `LibraryError` instead of falling back.
|
|
84
|
+
2. Platform names (`railid.dll`, `librailid.so`, `librailid.dylib`) in
|
|
85
|
+
`railid-capi/target/release` and `target/release` directories relative to
|
|
86
|
+
the package and repository roots, then the current directory.
|
|
87
|
+
3. `ctypes.util.find_library("railid")`.
|
|
88
|
+
|
|
89
|
+
A library with an ABI revision other than 4 is rejected with `LibraryError`.
|
|
90
|
+
`railid.library_path()` reports the file that was loaded.
|
|
91
|
+
|
|
92
|
+
Examples:
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
# Linux/macOS
|
|
96
|
+
export RAILID_LIBRARY="$PWD/railid-capi/target/release/librailid.so"
|
|
97
|
+
|
|
98
|
+
# Windows PowerShell
|
|
99
|
+
$env:RAILID_LIBRARY = "$PWD\railid-capi\target\release\railid.dll"
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## API
|
|
103
|
+
|
|
104
|
+
| Function | Result |
|
|
105
|
+
| --- | --- |
|
|
106
|
+
| `abi_version() -> int` | C ABI revision (4). |
|
|
107
|
+
| `version() -> str` | Native crate version, e.g. `"4.4.0"`. |
|
|
108
|
+
| `generate(profile="tpm") -> str` | One 32-character v1 ID. |
|
|
109
|
+
| `generate_v4(profile="tpm") -> str` | One 21-character v4 ID (126 bits). |
|
|
110
|
+
| `generate_many_encoded(profile="tpm", count=0) -> bytes` | `count * 32` v1 IDs, contiguous, no separators. |
|
|
111
|
+
| `error_message(code) -> str` | The C ABI message for a status code. |
|
|
112
|
+
| `reset_after_fork() -> None` | Discard cached randomness/timestamps after `fork()`. |
|
|
113
|
+
| `library_path() -> str` | Path of the loaded shared library. |
|
|
114
|
+
|
|
115
|
+
Profiles are `"tpm"` (TPM 2.0 hybrid) and `"os-only"` (explicitly degraded OS
|
|
116
|
+
CSPRNG). `Profile.TPM`, `Profile.OS_ONLY`, `PROFILE_TPM`, and
|
|
117
|
+
`PROFILE_OS_ONLY` are provided, and plain strings may be used anywhere a
|
|
118
|
+
profile is accepted.
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
import railid
|
|
122
|
+
|
|
123
|
+
blob = railid.generate_many_encoded("os-only", 3)
|
|
124
|
+
assert len(blob) == 3 * railid.ENCODED_LEN
|
|
125
|
+
ids = [blob[i * 32:(i + 1) * 32].decode("ascii") for i in range(3)]
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
`generate_many_encoded` returns raw bytes; the C ABI has no v4 batch or decode
|
|
129
|
+
entry point, so neither is invented here.
|
|
130
|
+
|
|
131
|
+
## Errors
|
|
132
|
+
|
|
133
|
+
All native failures raise `RailidError`, a `RuntimeError` subclass with:
|
|
134
|
+
|
|
135
|
+
- `code` Ethe negative C status code (`ErrorCode.TpmUnavailable`, etc.);
|
|
136
|
+
- `message` Ethe library's `railid_error_message` text;
|
|
137
|
+
- `detail` Eoptional wrapper context.
|
|
138
|
+
|
|
139
|
+
The TPM profile is fail-closed. If the library was built without `--features
|
|
140
|
+
tpm`, or no usable TPM 2.0 device exists, `generate("tpm")`,
|
|
141
|
+
`generate_v4("tpm")`, and `generate_many_encoded("tpm", n)` raise
|
|
142
|
+
`RailidError` with code `-4` (`ErrorCode.TpmUnavailable`). They never fall
|
|
143
|
+
back to OS randomness.
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
try:
|
|
147
|
+
value = railid.generate("tpm")
|
|
148
|
+
except railid.RailidError as error:
|
|
149
|
+
if error.code == railid.ErrorCode.TpmUnavailable:
|
|
150
|
+
print("no TPM; falling back explicitly")
|
|
151
|
+
value = railid.generate("os-only")
|
|
152
|
+
else:
|
|
153
|
+
raise
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
Invalid profile strings raise `RailidError` with `ErrorCode.InvalidProfile`.
|
|
157
|
+
`generate_many_encoded` enforces the C ABI batch caps
|
|
158
|
+
(`MAX_TPM_BATCH_IDS = 1024`, `MAX_OS_ONLY_BATCH_IDS = 1_000_000`) before
|
|
159
|
+
allocating and raises `ErrorCode.CapacityOverflow` above them. Negative
|
|
160
|
+
counts raise `ValueError`; non-integer counts raise `TypeError`.
|
|
161
|
+
|
|
162
|
+
Outputs are validated: v1 must be exactly 32 characters, v4 exactly 21, and
|
|
163
|
+
every character must belong to the unpadded Base64URL alphabet
|
|
164
|
+
(`A-Z`, `a-z`, `0-9`, `-`, `_`). Unexpected length or characters raise
|
|
165
|
+
`RuntimeError` rather than returning corrupt data.
|
|
166
|
+
|
|
167
|
+
If the shared library cannot be found, `LibraryError` (a `RuntimeError`) is
|
|
168
|
+
raised with the paths that were tried.
|
|
169
|
+
|
|
170
|
+
## Limitations
|
|
171
|
+
|
|
172
|
+
- No bundled native binaries and no PyPI publication; build `railid-capi`
|
|
173
|
+
yourself.
|
|
174
|
+
- The wrapper targets C ABI 4 and refuses other revisions.
|
|
175
|
+
- No v4 batch generation and no decode/parse functions (not exposed by the C
|
|
176
|
+
ABI).
|
|
177
|
+
- TPM availability depends on the native build (`--features tpm`), the OS
|
|
178
|
+
backend, and the machine. TPM failures are never masked.
|
|
179
|
+
- `ctypes` adds a small call overhead per ID; use the batch API for bulk
|
|
180
|
+
generation.
|
|
181
|
+
- Only OS randomness is available when the `tpm` feature is off, and that
|
|
182
|
+
profile is explicitly degraded.
|
|
183
|
+
|
|
184
|
+
## Tests
|
|
185
|
+
|
|
186
|
+
```bash
|
|
187
|
+
cargo build --manifest-path railid-capi/Cargo.toml --release
|
|
188
|
+
RAILID_LIBRARY="$PWD/railid-capi/target/release/librailid.so" \
|
|
189
|
+
pytest python/tests
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
On Windows PowerShell:
|
|
193
|
+
|
|
194
|
+
```powershell
|
|
195
|
+
$env:RAILID_LIBRARY = "$PWD\railid-capi\target\release\railid.dll"
|
|
196
|
+
pytest python/tests
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
`pytest` is the only test dependency; the runtime package itself imports only
|
|
200
|
+
the Python standard library.
|
|
201
|
+
|
|
202
|
+
## Repository packaging note
|
|
203
|
+
|
|
204
|
+
The root Rust package should exclude this directory so the Python sources are
|
|
205
|
+
not shipped in the crate archive:
|
|
206
|
+
|
|
207
|
+
```toml
|
|
208
|
+
exclude = ["python/**"]
|
|
209
|
+
```
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
railid/__init__.py,sha256=qlrty6w5XfrBxcuVkDqBpO2E-aZrLQDr2wnKyM3j3Lw,19444
|
|
2
|
+
railid/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
railid_native-4.4.0.dist-info/METADATA,sha256=MJC9bA_hcmxfisDM11hREeRJcyHqhZ46vn47Byq4RR4,7463
|
|
4
|
+
railid_native-4.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
railid_native-4.4.0.dist-info/top_level.txt,sha256=YSRWlfMmA3r6ELUa4BsSBK_ihAjztVTMsQbNQ55vcTY,7
|
|
6
|
+
railid_native-4.4.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
railid
|