requisition-aws 0.1.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.
- requisition_aws/__init__.py +3 -0
- requisition_aws/_vendor/LICENSE.mldsa +10 -0
- requisition_aws/_vendor/mldsa.py +443 -0
- requisition_aws/caller.py +165 -0
- requisition_aws/canonical.py +641 -0
- requisition_aws/catalog.py +138 -0
- requisition_aws/client.py +435 -0
- requisition_aws/demo_flow.py +270 -0
- requisition_aws/fence.py +93 -0
- requisition_aws/gate.py +500 -0
- requisition_aws/interceptor.py +605 -0
- requisition_aws/keys.py +364 -0
- requisition_aws/mcp_target.py +619 -0
- requisition_aws/pq.py +57 -0
- requisition_aws/registry.py +71 -0
- requisition_aws/scripted_model.py +51 -0
- requisition_aws/store.py +316 -0
- requisition_aws/strands_hook.py +255 -0
- requisition_aws/target_flow.py +158 -0
- requisition_aws-0.1.0.dist-info/METADATA +299 -0
- requisition_aws-0.1.0.dist-info/RECORD +25 -0
- requisition_aws-0.1.0.dist-info/WHEEL +4 -0
- requisition_aws-0.1.0.dist-info/licenses/LICENSE +202 -0
- requisition_aws-0.1.0.dist-info/licenses/NOTICE +9 -0
- requisition_aws-0.1.0.dist-info/licenses/bin/vendor/LICENSE.mldsa +10 -0
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
Permission to use, copy, modify, and/or distribute this software for
|
|
2
|
+
any purpose with or without fee is hereby granted.
|
|
3
|
+
|
|
4
|
+
THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL
|
|
5
|
+
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
|
|
6
|
+
OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE
|
|
7
|
+
FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY
|
|
8
|
+
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
|
|
9
|
+
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
|
|
10
|
+
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
# mldsa-py by Filippo Valsorda is marked CC0 1.0 Universal. To view a copy of
|
|
2
|
+
# this mark, visit https://creativecommons.org/publicdomain/zero/1.0/
|
|
3
|
+
#
|
|
4
|
+
# Alternatively, you may use this source code under the terms of the 0BSD
|
|
5
|
+
# license that can be found in the LICENSE file.
|
|
6
|
+
|
|
7
|
+
"""Pure-Python implementation of ML-DSA (FIPS 204) signature verification."""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import sys
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from enum import Enum
|
|
14
|
+
from hashlib import shake_128, shake_256
|
|
15
|
+
from typing import TYPE_CHECKING
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from typing_extensions import Buffer, Self, override
|
|
19
|
+
elif sys.version_info >= (3, 12):
|
|
20
|
+
from typing import override
|
|
21
|
+
else:
|
|
22
|
+
from typing import Any, Callable
|
|
23
|
+
|
|
24
|
+
def override(method: Callable[..., Any]) -> Callable[..., Any]:
|
|
25
|
+
return method
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"InvalidContextError",
|
|
30
|
+
"InvalidVerificationKeyError",
|
|
31
|
+
"ParameterSet",
|
|
32
|
+
"VerificationError",
|
|
33
|
+
"VerificationKey",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
Q = 8380417
|
|
37
|
+
N = 256
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class _Parameters:
|
|
42
|
+
name: str
|
|
43
|
+
verification_key_size: int
|
|
44
|
+
signature_size: int
|
|
45
|
+
k: int
|
|
46
|
+
l: int
|
|
47
|
+
η: int
|
|
48
|
+
γ1: int
|
|
49
|
+
γ2: int
|
|
50
|
+
λ: int
|
|
51
|
+
τ: int
|
|
52
|
+
ω: int
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ParameterSet(Enum):
|
|
56
|
+
"""ML-DSA parameter sets as defined in FIPS 204."""
|
|
57
|
+
|
|
58
|
+
ML_DSA_44 = _Parameters(name="ML-DSA-44", verification_key_size=1312, signature_size=2420,
|
|
59
|
+
k=4, l=4, η=2, γ1=17, γ2=(Q - 1) // 88, λ=128, τ=39, ω=80) # fmt: skip
|
|
60
|
+
ML_DSA_65 = _Parameters(name="ML-DSA-65", verification_key_size=1952, signature_size=3309,
|
|
61
|
+
k=6, l=5, η=4, γ1=19, γ2=(Q - 1) // 32, λ=192, τ=49, ω=55) # fmt: skip
|
|
62
|
+
ML_DSA_87 = _Parameters(name="ML-DSA-87", verification_key_size=2592, signature_size=4627,
|
|
63
|
+
k=8, l=7, η=2, γ1=19, γ2=(Q - 1) // 32, λ=256, τ=60, ω=75) # fmt: skip
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def verification_key_size(self) -> int:
|
|
67
|
+
"""The encoded verification key size in bytes."""
|
|
68
|
+
return self.value.verification_key_size
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def signature_size(self) -> int:
|
|
72
|
+
"""The signature size in bytes."""
|
|
73
|
+
return self.value.signature_size
|
|
74
|
+
|
|
75
|
+
@override
|
|
76
|
+
def __str__(self) -> str:
|
|
77
|
+
"""Return the human-readable parameter set name, e.g. ``ML-DSA-44``."""
|
|
78
|
+
return self.value.name
|
|
79
|
+
|
|
80
|
+
@override
|
|
81
|
+
def __repr__(self) -> str:
|
|
82
|
+
"""Return a concise representation, e.g. ``<ParameterSet.ML_DSA_44>``."""
|
|
83
|
+
return f"<{type(self).__name__}.{self.name}>"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class VerificationError(Exception):
|
|
87
|
+
"""Raised when signature verification fails."""
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class InvalidVerificationKeyError(ValueError):
|
|
91
|
+
"""Raised when a verification key is invalid."""
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class InvalidContextError(ValueError):
|
|
95
|
+
"""Raised when a context string is invalid."""
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class VerificationKey:
|
|
99
|
+
"""An ML-DSA verification key."""
|
|
100
|
+
|
|
101
|
+
_p: _Parameters
|
|
102
|
+
|
|
103
|
+
def __init__(self, pk: Buffer, /, *, parameters: ParameterSet | None = None) -> None:
|
|
104
|
+
"""Decode an ML-DSA verification key.
|
|
105
|
+
|
|
106
|
+
If *parameters* is ``None``, the parameter set is inferred from
|
|
107
|
+
the length of *pk*.
|
|
108
|
+
|
|
109
|
+
Raises:
|
|
110
|
+
InvalidVerificationKeyError: If the key is the wrong size or doesn't
|
|
111
|
+
match the specified parameter set.
|
|
112
|
+
"""
|
|
113
|
+
pk = memoryview(pk).cast("B")
|
|
114
|
+
if parameters is None:
|
|
115
|
+
size_to_params = {p.verification_key_size: p for p in ParameterSet}
|
|
116
|
+
if len(pk) not in size_to_params:
|
|
117
|
+
raise InvalidVerificationKeyError(f"unexpected verification key size {len(pk)}")
|
|
118
|
+
parameters = size_to_params[len(pk)]
|
|
119
|
+
self._p = parameters.value
|
|
120
|
+
|
|
121
|
+
if len(pk) != self._p.verification_key_size:
|
|
122
|
+
raise InvalidVerificationKeyError(
|
|
123
|
+
f"expected {self._p.verification_key_size} bytes, got {len(pk)}"
|
|
124
|
+
)
|
|
125
|
+
self._enc = bytes(pk)
|
|
126
|
+
self._tr = public_key_hash(pk)
|
|
127
|
+
ρ = bytes(pk[:32])
|
|
128
|
+
pkv = memoryview(pk[32:])
|
|
129
|
+
|
|
130
|
+
self._t1: list[NTTPoly] = [] # NTT(t₁ ⋅ 2ᵈ)
|
|
131
|
+
for _ in range(self._p.k):
|
|
132
|
+
self._t1.append(ntt(Poly([F(z.v << 13) for z in unpack(bytes(pkv[:320]), N, 10)])))
|
|
133
|
+
pkv = pkv[320:]
|
|
134
|
+
|
|
135
|
+
self._A: list[list[NTTPoly]] = [[] for _ in range(self._p.k)]
|
|
136
|
+
for r in range(self._p.k):
|
|
137
|
+
for s in range(self._p.l):
|
|
138
|
+
self._A[r].append(sample_ntt(ρ, s, r))
|
|
139
|
+
|
|
140
|
+
def __bytes__(self) -> bytes:
|
|
141
|
+
"""Return the encoded verification key."""
|
|
142
|
+
return self._enc
|
|
143
|
+
|
|
144
|
+
@override
|
|
145
|
+
def __repr__(self) -> str:
|
|
146
|
+
"""Return a concise representation, e.g. ``<VerificationKey ML-DSA-44>``."""
|
|
147
|
+
return f"<{type(self).__name__} {self._p.name}>"
|
|
148
|
+
|
|
149
|
+
@property
|
|
150
|
+
def parameters(self) -> ParameterSet:
|
|
151
|
+
"""The parameter set of this key."""
|
|
152
|
+
return ParameterSet(self._p)
|
|
153
|
+
|
|
154
|
+
def verify(self, signature: Buffer, message: Buffer, *, context: Buffer = b"") -> None:
|
|
155
|
+
"""Verify a signature over *message*.
|
|
156
|
+
|
|
157
|
+
Raises:
|
|
158
|
+
VerificationError: If the signature is invalid.
|
|
159
|
+
InvalidContextError: If the context is too long (more than 255 bytes).
|
|
160
|
+
"""
|
|
161
|
+
signature = memoryview(signature).cast("B")
|
|
162
|
+
μ = message_hash(self._tr, message, context)
|
|
163
|
+
|
|
164
|
+
if len(signature) != self._p.signature_size:
|
|
165
|
+
raise VerificationError(
|
|
166
|
+
f"invalid signature size: expected {self._p.signature_size} bytes, got {len(signature)}"
|
|
167
|
+
)
|
|
168
|
+
ch = bytes(signature[: self._p.λ // 4])
|
|
169
|
+
sigv = memoryview(signature[self._p.λ // 4 :])
|
|
170
|
+
z: list[Poly] = []
|
|
171
|
+
for _ in range(self._p.l):
|
|
172
|
+
length = (self._p.γ1 + 1) * N // 8
|
|
173
|
+
z.append(Poly(unpack_signed(bytes(sigv[:length]), N, self._p.γ1 + 1)))
|
|
174
|
+
sigv = sigv[length:]
|
|
175
|
+
h: list[list[int]] = [[0] * N for _ in range(self._p.k)]
|
|
176
|
+
idx = 0
|
|
177
|
+
for i in range(self._p.k):
|
|
178
|
+
limit = sigv[self._p.ω + i]
|
|
179
|
+
if limit < idx or limit > self._p.ω:
|
|
180
|
+
raise VerificationError("invalid signature encoding")
|
|
181
|
+
first = idx
|
|
182
|
+
while idx < limit:
|
|
183
|
+
if idx > first and sigv[idx - 1] >= sigv[idx]:
|
|
184
|
+
raise VerificationError("invalid signature encoding")
|
|
185
|
+
h[i][sigv[idx]] = 1
|
|
186
|
+
idx += 1
|
|
187
|
+
for i in range(idx, self._p.ω):
|
|
188
|
+
if sigv[i] != 0:
|
|
189
|
+
raise VerificationError("invalid signature encoding")
|
|
190
|
+
|
|
191
|
+
c = ntt(sample_in_ball(ch, self._p))
|
|
192
|
+
|
|
193
|
+
z_hat = [ntt(x) for x in z]
|
|
194
|
+
w: list[Poly] = [] # Â ∘ NTT(z) − NTT(c) ∘ NTT(t₁ ⋅ 2ᵈ)
|
|
195
|
+
for i in range(self._p.k):
|
|
196
|
+
w_hat = NTTPoly.zero()
|
|
197
|
+
for j in range(self._p.l):
|
|
198
|
+
w_hat += z_hat[j] * self._A[i][j]
|
|
199
|
+
w_hat -= c * self._t1[i]
|
|
200
|
+
w.append(inverse_ntt(w_hat))
|
|
201
|
+
|
|
202
|
+
w1 = [use_hint(w[i], h[i], self._p) for i in range(self._p.k)]
|
|
203
|
+
|
|
204
|
+
H = shake_256()
|
|
205
|
+
H.update(μ)
|
|
206
|
+
w1_bit_length = ((Q - 1) // (2 * self._p.γ2) - 1).bit_length()
|
|
207
|
+
for i in range(self._p.k):
|
|
208
|
+
H.update(pack(w1[i], w1_bit_length))
|
|
209
|
+
if H.digest(self._p.λ // 4) != ch:
|
|
210
|
+
raise VerificationError("invalid signature")
|
|
211
|
+
|
|
212
|
+
β = self._p.τ * self._p.η
|
|
213
|
+
γ1 = 1 << self._p.γ1
|
|
214
|
+
γ1β = γ1 - β
|
|
215
|
+
|
|
216
|
+
for v in z:
|
|
217
|
+
if any(x.infinity_norm() >= γ1β for x in v.cs):
|
|
218
|
+
raise VerificationError("invalid signature")
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def public_key_hash(pk: Buffer) -> bytes:
|
|
222
|
+
h = shake_256()
|
|
223
|
+
h.update(pk)
|
|
224
|
+
return h.digest(64)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def message_hash(tr: bytes, m: Buffer, ctx: Buffer) -> bytes:
|
|
228
|
+
ctx = memoryview(ctx).cast("B")
|
|
229
|
+
if len(ctx) > 255:
|
|
230
|
+
raise InvalidContextError(f"expected context of at most 255 bytes, got {len(ctx)}")
|
|
231
|
+
h = shake_256()
|
|
232
|
+
h.update(tr)
|
|
233
|
+
h.update(b"\x00")
|
|
234
|
+
h.update(bytes([len(ctx)]))
|
|
235
|
+
h.update(ctx)
|
|
236
|
+
h.update(m)
|
|
237
|
+
return h.digest(64)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
class F:
|
|
241
|
+
__slots__ = ("v",)
|
|
242
|
+
|
|
243
|
+
def __init__(self, v: int) -> None:
|
|
244
|
+
assert 0 <= v < Q
|
|
245
|
+
self.v = v
|
|
246
|
+
|
|
247
|
+
@classmethod
|
|
248
|
+
def reduce(cls, v: int) -> F:
|
|
249
|
+
return cls(v % Q)
|
|
250
|
+
|
|
251
|
+
def __add__(self, other: F) -> F:
|
|
252
|
+
return F.reduce(self.v + other.v)
|
|
253
|
+
|
|
254
|
+
def __sub__(self, other: F) -> F:
|
|
255
|
+
return F.reduce(self.v - other.v)
|
|
256
|
+
|
|
257
|
+
def __mul__(self, other: F) -> F:
|
|
258
|
+
return F.reduce(self.v * other.v)
|
|
259
|
+
|
|
260
|
+
def infinity_norm(self) -> int:
|
|
261
|
+
return self.v if self.v <= Q // 2 else Q - self.v
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def centered_mod(v: int, m: int) -> int:
|
|
265
|
+
r = v % m
|
|
266
|
+
if r > m // 2:
|
|
267
|
+
r -= m
|
|
268
|
+
return r
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def decompose(r: F, p: _Parameters) -> tuple[int, int]:
|
|
272
|
+
r0 = centered_mod(r.v, 2 * p.γ2)
|
|
273
|
+
if r.v - r0 == Q - 1:
|
|
274
|
+
return 0, r0 - 1
|
|
275
|
+
r1 = (r.v - r0) // (2 * p.γ2)
|
|
276
|
+
return r1, r0
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def unpack(buf: bytes, n: int, bit_length: int) -> list[F]:
|
|
280
|
+
assert n * bit_length == len(buf) * 8
|
|
281
|
+
res: list[F] = []
|
|
282
|
+
acc = 0
|
|
283
|
+
acc_len = 0
|
|
284
|
+
for b in buf:
|
|
285
|
+
acc |= b << acc_len
|
|
286
|
+
acc_len += 8
|
|
287
|
+
while acc_len >= bit_length:
|
|
288
|
+
res.append(F(acc & ((1 << bit_length) - 1)))
|
|
289
|
+
acc >>= bit_length
|
|
290
|
+
acc_len -= bit_length
|
|
291
|
+
return res
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def unpack_signed(buf: bytes, n: int, bit_length: int) -> list[F]:
|
|
295
|
+
b = F(1 << (bit_length - 1))
|
|
296
|
+
return [b - x for x in unpack(buf, n, bit_length)]
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def pack(cs: list[int], bit_length: int) -> bytes:
|
|
300
|
+
acc = 0
|
|
301
|
+
acc_len = 0
|
|
302
|
+
res = bytearray()
|
|
303
|
+
for c in cs:
|
|
304
|
+
acc |= c << acc_len
|
|
305
|
+
acc_len += bit_length
|
|
306
|
+
while acc_len >= 8:
|
|
307
|
+
res.append(acc & 0xFF)
|
|
308
|
+
acc >>= 8
|
|
309
|
+
acc_len -= 8
|
|
310
|
+
if acc_len > 0:
|
|
311
|
+
res.append(acc & 0xFF)
|
|
312
|
+
return bytes(res)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
class Poly:
|
|
316
|
+
__slots__ = ("cs",)
|
|
317
|
+
cs: list[F]
|
|
318
|
+
|
|
319
|
+
def __init__(self, cs: list[F]) -> None:
|
|
320
|
+
assert len(cs) == N
|
|
321
|
+
self.cs = cs
|
|
322
|
+
|
|
323
|
+
def __add__(self, other: Self) -> Self:
|
|
324
|
+
if type(self) is not type(other):
|
|
325
|
+
return NotImplemented
|
|
326
|
+
return type(self)([a + b for a, b in zip(self.cs, other.cs)])
|
|
327
|
+
|
|
328
|
+
def __sub__(self, other: Self) -> Self:
|
|
329
|
+
if type(self) is not type(other):
|
|
330
|
+
return NotImplemented
|
|
331
|
+
return type(self)([a - b for a, b in zip(self.cs, other.cs)])
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
class NTTPoly:
|
|
335
|
+
__slots__ = ("cs",)
|
|
336
|
+
cs: list[int] # don't use F to avoid function call overhead in hot loops
|
|
337
|
+
|
|
338
|
+
def __init__(self, cs: list[int]) -> None:
|
|
339
|
+
assert len(cs) == N
|
|
340
|
+
self.cs = cs
|
|
341
|
+
|
|
342
|
+
@classmethod
|
|
343
|
+
def zero(cls) -> Self:
|
|
344
|
+
return cls([0 for _ in range(N)])
|
|
345
|
+
|
|
346
|
+
def __iadd__(self, other: Self) -> Self:
|
|
347
|
+
if type(self) is not type(other):
|
|
348
|
+
return NotImplemented
|
|
349
|
+
for i in range(N):
|
|
350
|
+
self.cs[i] = (self.cs[i] + other.cs[i]) % Q
|
|
351
|
+
return self
|
|
352
|
+
|
|
353
|
+
def __isub__(self, other: Self) -> Self:
|
|
354
|
+
if type(self) is not type(other):
|
|
355
|
+
return NotImplemented
|
|
356
|
+
for i in range(N):
|
|
357
|
+
self.cs[i] = (self.cs[i] - other.cs[i]) % Q
|
|
358
|
+
return self
|
|
359
|
+
|
|
360
|
+
def __mul__(self, other: NTTPoly) -> NTTPoly:
|
|
361
|
+
if type(self) is not type(other):
|
|
362
|
+
return NotImplemented
|
|
363
|
+
return NTTPoly([a * b % Q for a, b in zip(self.cs, other.cs)])
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def ntt(f: Poly) -> NTTPoly:
|
|
367
|
+
m = 0
|
|
368
|
+
w = [c.v for c in f.cs]
|
|
369
|
+
for len in [128, 64, 32, 16, 8, 4, 2, 1]:
|
|
370
|
+
for start in range(0, N, 2 * len):
|
|
371
|
+
m += 1
|
|
372
|
+
zeta = ZETAS[m]
|
|
373
|
+
for j in range(start, start + len):
|
|
374
|
+
t = zeta * w[j + len] % Q
|
|
375
|
+
w[j + len] = (w[j] - t) % Q
|
|
376
|
+
w[j] = (w[j] + t) % Q
|
|
377
|
+
return NTTPoly(w)
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def inverse_ntt(f: NTTPoly) -> Poly:
|
|
381
|
+
m = 255
|
|
382
|
+
w = [c for c in f.cs]
|
|
383
|
+
for len in [1, 2, 4, 8, 16, 32, 64, 128]:
|
|
384
|
+
for start in range(0, N, 2 * len):
|
|
385
|
+
zeta = ZETAS[m]
|
|
386
|
+
m -= 1
|
|
387
|
+
for j in range(start, start + len):
|
|
388
|
+
t = w[j]
|
|
389
|
+
w[j] = (t + w[j + len]) % Q
|
|
390
|
+
w[j + len] = zeta * (w[j + len] - t) % Q
|
|
391
|
+
return Poly([F(v * 8347681 % Q) for v in w])
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def sample_ntt(ρ: bytes, s: int, r: int) -> NTTPoly:
|
|
395
|
+
G = shake_128()
|
|
396
|
+
G.update(ρ)
|
|
397
|
+
G.update(bytes([s, r]))
|
|
398
|
+
buf = G.digest(894)
|
|
399
|
+
|
|
400
|
+
a: list[int] = []
|
|
401
|
+
while len(a) < N:
|
|
402
|
+
v = int.from_bytes(buf[:3], "little") & 0x7FFFFF
|
|
403
|
+
buf = buf[3:]
|
|
404
|
+
if v < Q:
|
|
405
|
+
a.append(v)
|
|
406
|
+
return NTTPoly(a)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def sample_in_ball(rho: bytes, p: _Parameters) -> Poly:
|
|
410
|
+
G = shake_256()
|
|
411
|
+
G.update(rho)
|
|
412
|
+
buf = G.digest(221)
|
|
413
|
+
s = buf[:8]
|
|
414
|
+
j = memoryview(buf)[8:]
|
|
415
|
+
|
|
416
|
+
c = [F(0) for _ in range(N)]
|
|
417
|
+
for i in range(256 - p.τ, 256):
|
|
418
|
+
while j[0] > i:
|
|
419
|
+
j = j[1:]
|
|
420
|
+
c[i] = c[j[0]]
|
|
421
|
+
bit_idx = i + p.τ - 256
|
|
422
|
+
bit = (s[bit_idx // 8] >> (bit_idx % 8)) & 1
|
|
423
|
+
c[j[0]] = F(1) if bit == 0 else F(Q - 1)
|
|
424
|
+
j = j[1:]
|
|
425
|
+
|
|
426
|
+
return Poly(c)
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def use_hint(w: Poly, h: list[int], p: _Parameters) -> list[int]:
|
|
430
|
+
m = (Q - 1) // (2 * p.γ2)
|
|
431
|
+
w1: list[int] = []
|
|
432
|
+
for i in range(N):
|
|
433
|
+
r1, r0 = decompose(w.cs[i], p)
|
|
434
|
+
if h[i] == 0:
|
|
435
|
+
w1.append(r1)
|
|
436
|
+
elif r0 > 0:
|
|
437
|
+
w1.append((r1 + 1) % m)
|
|
438
|
+
else:
|
|
439
|
+
w1.append((r1 - 1) % m)
|
|
440
|
+
return w1
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
ZETAS = [1, 4808194, 3765607, 3761513, 5178923, 5496691, 5234739, 5178987, 7778734, 3542485, 2682288, 2129892, 3764867, 7375178, 557458, 7159240, 5010068, 4317364, 2663378, 6705802, 4855975, 7946292, 676590, 7044481, 5152541, 1714295, 2453983, 1460718, 7737789, 4795319, 2815639, 2283733, 3602218, 3182878, 2740543, 4793971, 5269599, 2101410, 3704823, 1159875, 394148, 928749, 1095468, 4874037, 2071829, 4361428, 3241972, 2156050, 3415069, 1759347, 7562881, 4805951, 3756790, 6444618, 6663429, 4430364, 5483103, 3192354, 556856, 3870317, 2917338, 1853806, 3345963, 1858416, 3073009, 1277625, 5744944, 3852015, 4183372, 5157610, 5258977, 8106357, 2508980, 2028118, 1937570, 4564692, 2811291, 5396636, 7270901, 4158088, 1528066, 482649, 1148858, 5418153, 7814814, 169688, 2462444, 5046034, 4213992, 4892034, 1987814, 5183169, 1736313, 235407, 5130263, 3258457, 5801164, 1787943, 5989328, 6125690, 3482206, 4197502, 7080401, 6018354, 7062739, 2461387, 3035980, 621164, 3901472, 7153756, 2925816, 3374250, 1356448, 5604662, 2683270, 5601629, 4912752, 2312838, 7727142, 7921254, 348812, 8052569, 1011223, 6026202, 4561790, 6458164, 6143691, 1744507, 1753, 6444997, 5720892, 6924527, 2660408, 6600190, 8321269, 2772600, 1182243, 87208, 636927, 4415111, 4423672, 6084020, 5095502, 4663471, 8352605, 822541, 1009365, 5926272, 6400920, 1596822, 4423473, 4620952, 6695264, 4969849, 2678278, 4611469, 4829411, 635956, 8129971, 5925040, 4234153, 6607829, 2192938, 6653329, 2387513, 4768667, 8111961, 5199961, 3747250, 2296099, 1239911, 4541938, 3195676, 2642980, 1254190, 8368000, 2998219, 141835, 8291116, 2513018, 7025525, 613238, 7070156, 6161950, 7921677, 6458423, 4040196, 4908348, 2039144, 6500539, 7561656, 6201452, 6757063, 2105286, 6006015, 6346610, 586241, 7200804, 527981, 5637006, 6903432, 1994046, 2491325, 6987258, 507927, 7192532, 7655613, 6545891, 5346675, 8041997, 2647994, 3009748, 5767564, 4148469, 749577, 4357667, 3980599, 2569011, 6764887, 1723229, 1665318, 2028038, 1163598, 5011144, 3994671, 8368538, 7009900, 3020393, 3363542, 214880, 545376, 7609976, 3105558, 7277073, 508145, 7826699, 860144, 3430436, 140244, 6866265, 6195333, 3123762, 2358373, 6187330, 5365997, 6663603, 2926054, 7987710, 8077412, 3531229, 4405932, 4606686, 1900052, 7598542, 1054478, 7648983] # fmt: skip # ruff: ignore[line-too-long]
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Sudo Apt Holdings LLC (Script Kitty OS & Labs)
|
|
3
|
+
"""Who is calling: the caller-key sources of the Gateway REQUEST interceptor (G1).
|
|
4
|
+
|
|
5
|
+
An MCP-target interceptor's input has no identity field. Its only caller-bound material is the
|
|
6
|
+
``Authorization`` header, and only with ``passRequestHeaders`` true
|
|
7
|
+
(gateway-interceptors-types.html, read 2026-11-10). The Gateway authenticates the inbound request
|
|
8
|
+
BEFORE it invokes the interceptor (AWS ML blog, "Apply fine-grained access control with Bedrock
|
|
9
|
+
AgentCore Gateway interceptors": "AgentCore Gateway authenticates the inbound request. AgentCore
|
|
10
|
+
Gateway invokes the custom interceptor."). Three sources, chosen by configuration
|
|
11
|
+
(``REQUISITION_CALLER_SOURCE``):
|
|
12
|
+
|
|
13
|
+
* ``legacy_session`` (:class:`LegacySessionCaller`, the DEFAULT until a live call measures what the
|
|
14
|
+
Gateway forwards under AWS_IAM): the pre-G1 behaviour, the ``Mcp-Session-Id`` header. It is not a
|
|
15
|
+
caller identity; MCP 2026-07-28 removes it.
|
|
16
|
+
* ``sigv4`` (:class:`SigV4Caller`): the access-key id of the SigV4 ``Authorization`` header, for an
|
|
17
|
+
``AWS_IAM`` gateway. The Gateway checked the signature; this function cannot (it holds no secret).
|
|
18
|
+
An access-key id names a credential, not a principal: one principal with two keys is two callers
|
|
19
|
+
(that direction fails closed), and temporary (ASIA) keys rotate.
|
|
20
|
+
* ``jwt`` (:class:`JwtCaller`): a bearer JWT verified HERE against a pinned issuer and JWKS
|
|
21
|
+
(RS256 only), for a ``CUSTOM_JWT`` gateway: defence in depth, and the only sound source on a
|
|
22
|
+
gateway whose authorizer is NONE.
|
|
23
|
+
|
|
24
|
+
``clientInfo`` is never the caller (MCP 2026-07-28 basic: "self-reported … SHOULD NOT rely on them
|
|
25
|
+
for security decisions").
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import base64
|
|
31
|
+
import binascii
|
|
32
|
+
import hashlib
|
|
33
|
+
import re
|
|
34
|
+
import time
|
|
35
|
+
from typing import Any, Callable
|
|
36
|
+
|
|
37
|
+
from cryptography.exceptions import InvalidSignature
|
|
38
|
+
from cryptography.hazmat.primitives import hashes
|
|
39
|
+
from cryptography.hazmat.primitives.asymmetric import padding, rsa
|
|
40
|
+
|
|
41
|
+
from . import canonical
|
|
42
|
+
from .client import loads_strict
|
|
43
|
+
|
|
44
|
+
SESSION_NAMESPACE = "requisition-aws/caller-session"
|
|
45
|
+
_SIGV4 = re.compile(
|
|
46
|
+
r"\AAWS4-HMAC-SHA256 Credential=(A[KS]IA[A-Z0-9]{12,124})/[0-9]{8}/[a-z0-9-]+/[a-z0-9-]+/aws4_request(?:,|\Z)")
|
|
47
|
+
_B64URL = re.compile(r"\A[A-Za-z0-9_-]*\Z")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def header_values(headers: Any, name: str) -> list:
|
|
51
|
+
"""Every value of a request header by case-insensitive name (RFC 9110)."""
|
|
52
|
+
if not isinstance(headers, dict):
|
|
53
|
+
return []
|
|
54
|
+
return [value for key, value in headers.items() if isinstance(key, str) and key.lower() == name]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def header(headers: Any, name: str) -> str | None:
|
|
58
|
+
"""A request header by case-insensitive name, or None: absent, not a string, or AMBIGUOUS (more
|
|
59
|
+
than one case variant; the first one is never chosen)."""
|
|
60
|
+
values = header_values(headers, name)
|
|
61
|
+
return values[0] if len(values) == 1 and isinstance(values[0], str) else None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def caller_session(caller_key: str, client_id: str | None) -> str:
|
|
65
|
+
"""The signed ``session`` member: the client's own id (or none) namespaced by the caller key.
|
|
66
|
+
Deterministic, at most 64 characters, never the raw key; stable across the pending call and
|
|
67
|
+
the re-call, so the act hash matches; a new caller key (a rotated credential) is a new act."""
|
|
68
|
+
digest = hashlib.sha256(canonical.encode([SESSION_NAMESPACE, caller_key, client_id])).hexdigest()
|
|
69
|
+
return "caller-" + digest[:48]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class LegacySessionCaller:
|
|
73
|
+
"""The pre-G1 source: the raw ``Mcp-Session-Id`` is the signed session and part of the call key."""
|
|
74
|
+
|
|
75
|
+
source = "legacy_session"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class SigV4Caller:
|
|
79
|
+
source = "sigv4"
|
|
80
|
+
|
|
81
|
+
def key(self, headers: Any) -> str | None:
|
|
82
|
+
value = header(headers, "authorization")
|
|
83
|
+
# two credentials, in any spelling (``credential=`` too): ambiguous, fail closed
|
|
84
|
+
if not value or value.lower().count("credential=") != 1:
|
|
85
|
+
return None
|
|
86
|
+
match = _SIGV4.match(value)
|
|
87
|
+
return f"sigv4:{match.group(1)}" if match else None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _b64url(part: str) -> bytes:
|
|
91
|
+
if not _B64URL.match(part):
|
|
92
|
+
raise ValueError("not base64url")
|
|
93
|
+
return base64.urlsafe_b64decode(part + "=" * (-len(part) % 4))
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _b64url_int(value: Any) -> int:
|
|
97
|
+
if not isinstance(value, str) or not value:
|
|
98
|
+
raise ValueError("not a base64url integer")
|
|
99
|
+
return int.from_bytes(_b64url(value), "big")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class JwtCaller:
|
|
103
|
+
"""A bearer JWT verified against a pinned issuer and JWKS: ``jwt:<iss>|<sub>`` (``client_id``
|
|
104
|
+
when the token has no ``sub``, the M2M case), or None for anything else."""
|
|
105
|
+
|
|
106
|
+
source = "jwt"
|
|
107
|
+
|
|
108
|
+
def __init__(self, issuer: str, jwks: dict, *, audiences=(), clients=(),
|
|
109
|
+
clock: Callable[[], float] = time.time, leeway: int = 60):
|
|
110
|
+
if not isinstance(issuer, str) or not issuer:
|
|
111
|
+
raise ValueError("a JWT caller needs its issuer")
|
|
112
|
+
audiences, clients = tuple(audiences or ()), tuple(clients or ())
|
|
113
|
+
if not audiences and not clients:
|
|
114
|
+
raise ValueError("a JWT caller pins its audiences or its client ids (neither given)")
|
|
115
|
+
self.issuer, self.audiences, self.clients = issuer, audiences, clients
|
|
116
|
+
self.clock, self.leeway = clock, leeway
|
|
117
|
+
self.keys: dict[str, rsa.RSAPublicKey] = {}
|
|
118
|
+
for jwk in (jwks or {}).get("keys", []):
|
|
119
|
+
if isinstance(jwk, dict) and jwk.get("kty") == "RSA" and isinstance(jwk.get("kid"), str) \
|
|
120
|
+
and jwk.get("alg", "RS256") == "RS256" and jwk.get("use", "sig") == "sig":
|
|
121
|
+
numbers = rsa.RSAPublicNumbers(_b64url_int(jwk["e"]), _b64url_int(jwk["n"]))
|
|
122
|
+
self.keys[jwk["kid"]] = numbers.public_key()
|
|
123
|
+
if not self.keys:
|
|
124
|
+
raise ValueError("the pinned JWKS holds no RS256 signing key")
|
|
125
|
+
|
|
126
|
+
def key(self, headers: Any) -> str | None:
|
|
127
|
+
try:
|
|
128
|
+
return self._key(headers)
|
|
129
|
+
except (ValueError, TypeError, KeyError, binascii.Error, InvalidSignature, UnicodeDecodeError):
|
|
130
|
+
return None
|
|
131
|
+
|
|
132
|
+
def _key(self, headers: Any) -> str | None:
|
|
133
|
+
value = header(headers, "authorization")
|
|
134
|
+
if not value or not value.startswith("Bearer "):
|
|
135
|
+
return None
|
|
136
|
+
parts = value[len("Bearer "):].split(".")
|
|
137
|
+
if len(parts) != 3:
|
|
138
|
+
return None
|
|
139
|
+
head = loads_strict(_b64url(parts[0]))
|
|
140
|
+
if not isinstance(head, dict) or head.get("alg") != "RS256" or head.get("kid") not in self.keys:
|
|
141
|
+
return None
|
|
142
|
+
self.keys[head["kid"]].verify(_b64url(parts[2]), f"{parts[0]}.{parts[1]}".encode("ascii"),
|
|
143
|
+
padding.PKCS1v15(), hashes.SHA256())
|
|
144
|
+
claims = loads_strict(_b64url(parts[1])) # a duplicate claim is refused, never "the last one"
|
|
145
|
+
if not isinstance(claims, dict) or claims.get("iss") != self.issuer:
|
|
146
|
+
return None
|
|
147
|
+
now = self.clock()
|
|
148
|
+
exp, nbf = claims.get("exp"), claims.get("nbf")
|
|
149
|
+
if isinstance(exp, bool) or not isinstance(exp, (int, float)) or exp <= now - self.leeway:
|
|
150
|
+
return None
|
|
151
|
+
if nbf is not None and (isinstance(nbf, bool) or not isinstance(nbf, (int, float)) or nbf > now + self.leeway):
|
|
152
|
+
return None
|
|
153
|
+
aud = claims.get("aud")
|
|
154
|
+
auds = [aud] if isinstance(aud, str) else aud if isinstance(aud, list) else []
|
|
155
|
+
client_id = claims.get("client_id")
|
|
156
|
+
if not (any(a in self.audiences for a in auds if isinstance(a, str))
|
|
157
|
+
or (isinstance(client_id, str) and client_id in self.clients)):
|
|
158
|
+
return None
|
|
159
|
+
if "sub" in claims:
|
|
160
|
+
subject = claims["sub"]
|
|
161
|
+
else:
|
|
162
|
+
subject = client_id
|
|
163
|
+
if not isinstance(subject, str) or not subject:
|
|
164
|
+
return None
|
|
165
|
+
return f"jwt:{self.issuer}|{subject}"
|