pyjwt-aws-kms 0.2.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.
- pyjwt_aws_kms/__init__.py +4 -0
- pyjwt_aws_kms/algorithms.py +167 -0
- pyjwt_aws_kms/key.py +55 -0
- pyjwt_aws_kms/py.typed +0 -0
- pyjwt_aws_kms-0.2.0.dist-info/METADATA +285 -0
- pyjwt_aws_kms-0.2.0.dist-info/RECORD +8 -0
- pyjwt_aws_kms-0.2.0.dist-info/WHEEL +4 -0
- pyjwt_aws_kms-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""PyJWT algorithms that sign with AWS KMS."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, override
|
|
6
|
+
|
|
7
|
+
import jwt
|
|
8
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
9
|
+
from jwt.algorithms import Algorithm
|
|
10
|
+
from jwt.exceptions import InvalidKeyError
|
|
11
|
+
from jwt.utils import der_to_raw_signature
|
|
12
|
+
|
|
13
|
+
from .key import KMSKey
|
|
14
|
+
|
|
15
|
+
# JWT alg -> (KMS SigningAlgorithm, EC curve for DER -> raw r||s conversion)
|
|
16
|
+
_SPECS: dict[str, tuple[str, type[ec.EllipticCurve] | None]] = {
|
|
17
|
+
"RS256": ("RSASSA_PKCS1_V1_5_SHA_256", None),
|
|
18
|
+
"RS384": ("RSASSA_PKCS1_V1_5_SHA_384", None),
|
|
19
|
+
"RS512": ("RSASSA_PKCS1_V1_5_SHA_512", None),
|
|
20
|
+
"PS256": ("RSASSA_PSS_SHA_256", None),
|
|
21
|
+
"PS384": ("RSASSA_PSS_SHA_384", None),
|
|
22
|
+
"PS512": ("RSASSA_PSS_SHA_512", None),
|
|
23
|
+
"ES256": ("ECDSA_SHA_256", ec.SECP256R1),
|
|
24
|
+
"ES384": ("ECDSA_SHA_384", ec.SECP384R1),
|
|
25
|
+
"ES512": ("ECDSA_SHA_512", ec.SECP521R1),
|
|
26
|
+
"ES256K": ("ECDSA_SHA_256", ec.SECP256K1),
|
|
27
|
+
"EdDSA": ("ED25519_SHA_512", None),
|
|
28
|
+
}
|
|
29
|
+
# Ed25519 is the only algorithm here without a KMS DIGEST mode, so it is sent RAW.
|
|
30
|
+
# Everything else is hashed locally and sent as DIGEST.
|
|
31
|
+
_RAW_MESSAGE_ALGORITHMS = {"ED25519_SHA_512"}
|
|
32
|
+
# ES256 and ES256K both use this, and KMS accepts it for P-256 and secp256k1 keys alike,
|
|
33
|
+
# so it cannot catch a mix-up. It rejects every other key/algorithm mismatch itself.
|
|
34
|
+
_AMBIGUOUS_SIGNING_ALGORITHM = "ECDSA_SHA_256"
|
|
35
|
+
# KMS limit for MessageType=RAW.
|
|
36
|
+
_MAX_RAW_MESSAGE_BYTES = 4096
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class KMSAlgorithm(Algorithm):
|
|
40
|
+
"""Signs with KMS when given a :class:`KMSKey`; otherwise behaves like ``delegate``.
|
|
41
|
+
|
|
42
|
+
Verification with a :class:`KMSKey` uses the key's cached public key locally,
|
|
43
|
+
so no KMS call (or cost) is made per verification.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def __init__(
|
|
47
|
+
self,
|
|
48
|
+
delegate: Algorithm,
|
|
49
|
+
signing_algorithm: str,
|
|
50
|
+
curve: type[ec.EllipticCurve] | None = None,
|
|
51
|
+
) -> None:
|
|
52
|
+
self._delegate = delegate
|
|
53
|
+
self.signing_algorithm = signing_algorithm
|
|
54
|
+
self._curve = curve
|
|
55
|
+
|
|
56
|
+
def _checked_public_key(self, key: KMSKey) -> Any:
|
|
57
|
+
"""The KMS key's public half, validated for this algorithm.
|
|
58
|
+
|
|
59
|
+
The delegate's ``prepare_key`` checks the key family and (for ECDSA) the
|
|
60
|
+
curve, raising :class:`jwt.InvalidKeyError` on a mismatch.
|
|
61
|
+
"""
|
|
62
|
+
try:
|
|
63
|
+
return self._delegate.prepare_key(key.public_key())
|
|
64
|
+
except TypeError as e:
|
|
65
|
+
# Delegates raise TypeError for a cryptography key of the wrong family.
|
|
66
|
+
raise InvalidKeyError(
|
|
67
|
+
f"{key!r} has the wrong key type for this algorithm"
|
|
68
|
+
) from e
|
|
69
|
+
|
|
70
|
+
@override
|
|
71
|
+
def prepare_key(self, key: Any) -> Any:
|
|
72
|
+
if isinstance(key, KMSKey):
|
|
73
|
+
return key
|
|
74
|
+
return self._delegate.prepare_key(key)
|
|
75
|
+
|
|
76
|
+
@override
|
|
77
|
+
def check_key_length(self, key: Any) -> str | None:
|
|
78
|
+
if isinstance(key, KMSKey):
|
|
79
|
+
# KMS has no undersized keys (its RSA minimum is 2048 bits), so don't
|
|
80
|
+
# fetch the public key, which signing may not have permission to do.
|
|
81
|
+
return None
|
|
82
|
+
return self._delegate.check_key_length(key)
|
|
83
|
+
|
|
84
|
+
@override
|
|
85
|
+
def sign(self, msg: bytes, key: Any) -> bytes:
|
|
86
|
+
if not isinstance(key, KMSKey):
|
|
87
|
+
return self._delegate.sign(msg, key)
|
|
88
|
+
|
|
89
|
+
if (
|
|
90
|
+
key.check_curve_on_sign
|
|
91
|
+
and self.signing_algorithm == _AMBIGUOUS_SIGNING_ALGORITHM
|
|
92
|
+
):
|
|
93
|
+
self._checked_public_key(key)
|
|
94
|
+
|
|
95
|
+
if self.signing_algorithm in _RAW_MESSAGE_ALGORITHMS:
|
|
96
|
+
if len(msg) > _MAX_RAW_MESSAGE_BYTES:
|
|
97
|
+
raise ValueError(
|
|
98
|
+
f"{self.signing_algorithm} can sign at most "
|
|
99
|
+
f"{_MAX_RAW_MESSAGE_BYTES} bytes in KMS; got {len(msg)}"
|
|
100
|
+
)
|
|
101
|
+
message, message_type = msg, "RAW"
|
|
102
|
+
else:
|
|
103
|
+
# Hash locally: no size limit, and the message never leaves the process.
|
|
104
|
+
message, message_type = self._delegate.compute_hash_digest(msg), "DIGEST"
|
|
105
|
+
|
|
106
|
+
response = key.client.sign(
|
|
107
|
+
KeyId=key.key_id,
|
|
108
|
+
Message=message,
|
|
109
|
+
MessageType=message_type, # type: ignore[arg-type]
|
|
110
|
+
SigningAlgorithm=self.signing_algorithm, # type: ignore[arg-type]
|
|
111
|
+
)
|
|
112
|
+
signature = response["Signature"]
|
|
113
|
+
if self._curve is not None:
|
|
114
|
+
# KMS returns DER; JWS requires fixed-width r || s.
|
|
115
|
+
return der_to_raw_signature(signature, self._curve())
|
|
116
|
+
return signature
|
|
117
|
+
|
|
118
|
+
@override
|
|
119
|
+
def verify(self, msg: bytes, key: Any, sig: bytes) -> bool:
|
|
120
|
+
if not isinstance(key, KMSKey):
|
|
121
|
+
return self._delegate.verify(msg, key, sig)
|
|
122
|
+
return self._delegate.verify(msg, self._checked_public_key(key), sig)
|
|
123
|
+
|
|
124
|
+
# Instance methods rather than static ones, so JWK import/export keeps working
|
|
125
|
+
# for non-KMS keys through the registry (jwt.get_algorithm_by_name(...)).
|
|
126
|
+
@override
|
|
127
|
+
def to_jwk(self, key_obj: Any, as_dict: bool = False) -> Any: # type: ignore[override]
|
|
128
|
+
if isinstance(key_obj, KMSKey):
|
|
129
|
+
raise NotImplementedError(
|
|
130
|
+
"KMSAlgorithm does not support JWK export of a KMSKey; "
|
|
131
|
+
"export key.public_key() instead"
|
|
132
|
+
)
|
|
133
|
+
if as_dict:
|
|
134
|
+
return self._delegate.to_jwk(key_obj, as_dict=True)
|
|
135
|
+
return self._delegate.to_jwk(key_obj, as_dict=False)
|
|
136
|
+
|
|
137
|
+
@override
|
|
138
|
+
def from_jwk(self, jwk: Any) -> Any: # type: ignore[override]
|
|
139
|
+
return self._delegate.from_jwk(jwk)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _registry(jws: jwt.PyJWS | None) -> dict[str, Algorithm]:
|
|
143
|
+
# PyJWT has no public "replace" operation; unregister + register would leave a
|
|
144
|
+
# window in which the name is missing for other threads. Swapping the dict
|
|
145
|
+
# entry is a single atomic assignment.
|
|
146
|
+
target = jws if jws is not None else jwt.api_jws._jws_global_obj
|
|
147
|
+
return target._algorithms
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def register_algorithms(jws: jwt.PyJWS | None = None) -> None:
|
|
151
|
+
"""Make PyJWT accept :class:`KMSKey` for the asymmetric algorithms.
|
|
152
|
+
|
|
153
|
+
Registers over the standard names (RS256, ES256, ...). Each wrapper falls back
|
|
154
|
+
to the algorithm it replaced for non-KMS keys, so existing behaviour is kept.
|
|
155
|
+
Names not enabled on ``jws`` (e.g. ``PyJWS(algorithms=[...])``) are skipped.
|
|
156
|
+
|
|
157
|
+
:param jws: A ``PyJWS`` instance to register on. Defaults to the global
|
|
158
|
+
registry used by ``jwt.encode`` / ``jwt.decode``.
|
|
159
|
+
"""
|
|
160
|
+
algorithms = _registry(jws)
|
|
161
|
+
for name, (signing_algorithm, curve) in _SPECS.items():
|
|
162
|
+
existing = algorithms.get(name)
|
|
163
|
+
if existing is None:
|
|
164
|
+
continue
|
|
165
|
+
if isinstance(existing, KMSAlgorithm):
|
|
166
|
+
existing = existing._delegate
|
|
167
|
+
algorithms[name] = KMSAlgorithm(existing, signing_algorithm, curve)
|
pyjwt_aws_kms/key.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""A reference to an asymmetric AWS KMS key, usable as a PyJWT key."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING
|
|
6
|
+
|
|
7
|
+
import boto3
|
|
8
|
+
from cryptography.hazmat.primitives.serialization import load_der_public_key
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from cryptography.hazmat.primitives.asymmetric.types import PublicKeyTypes
|
|
12
|
+
from mypy_boto3_kms import KMSClient
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class KMSKey:
|
|
16
|
+
"""Identifies an asymmetric KMS key and the client used to reach it.
|
|
17
|
+
|
|
18
|
+
Pass an instance as the ``key`` argument of ``jwt.encode`` / ``jwt.decode``.
|
|
19
|
+
|
|
20
|
+
:param key_id: A key ID, key ARN, alias name or alias ARN.
|
|
21
|
+
:param client: A boto3 KMS client. If omitted, one is created on first use
|
|
22
|
+
with boto3's default configuration.
|
|
23
|
+
:param check_curve_on_sign: Check the key's curve before signing with ES256 or
|
|
24
|
+
ES256K, which KMS cannot tell apart. Needs ``kms:GetPublicKey`` (called once,
|
|
25
|
+
then cached). Set to ``False`` to sign with only ``kms:Sign``, if you are sure
|
|
26
|
+
the key matches the algorithm. Verification always checks the key.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
key_id: str,
|
|
32
|
+
client: KMSClient | None = None,
|
|
33
|
+
*,
|
|
34
|
+
check_curve_on_sign: bool = True,
|
|
35
|
+
) -> None:
|
|
36
|
+
self.key_id = key_id
|
|
37
|
+
self.check_curve_on_sign = check_curve_on_sign
|
|
38
|
+
self._client = client
|
|
39
|
+
self._public_key: PublicKeyTypes | None = None
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def client(self) -> KMSClient:
|
|
43
|
+
if self._client is None:
|
|
44
|
+
self._client = boto3.client("kms")
|
|
45
|
+
return self._client
|
|
46
|
+
|
|
47
|
+
def public_key(self) -> PublicKeyTypes:
|
|
48
|
+
"""The key's public half, fetched once with ``kms:GetPublicKey`` and cached."""
|
|
49
|
+
if self._public_key is None:
|
|
50
|
+
response = self.client.get_public_key(KeyId=self.key_id)
|
|
51
|
+
self._public_key = load_der_public_key(response["PublicKey"])
|
|
52
|
+
return self._public_key
|
|
53
|
+
|
|
54
|
+
def __repr__(self) -> str:
|
|
55
|
+
return f"KMSKey(key_id={self.key_id!r})"
|
pyjwt_aws_kms/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pyjwt-aws-kms
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Sign JWTs with PyJWT using asymmetric keys held in AWS KMS
|
|
5
|
+
Project-URL: Homepage, https://github.com/nsmithuk/pyjwt-aws-kms
|
|
6
|
+
Project-URL: Repository, https://github.com/nsmithuk/pyjwt-aws-kms
|
|
7
|
+
Project-URL: Issues, https://github.com/nsmithuk/pyjwt-aws-kms/issues
|
|
8
|
+
Author-email: Neil Smith <neil@nsmith.net>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Python: >=3.12
|
|
12
|
+
Requires-Dist: boto3>=1.44.6
|
|
13
|
+
Requires-Dist: pyjwt[crypto]>=2.15.1
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# pyjwt-aws-kms
|
|
17
|
+
|
|
18
|
+
Sign JSON Web Tokens with [PyJWT](https://pyjwt.readthedocs.io/) using an asymmetric key held in
|
|
19
|
+
[AWS KMS](https://aws.amazon.com/kms/). The private key never leaves KMS: your application sends
|
|
20
|
+
KMS the data to sign and gets a signature back.
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
import jwt
|
|
24
|
+
from pyjwt_aws_kms import KMSKey, register_algorithms
|
|
25
|
+
|
|
26
|
+
register_algorithms()
|
|
27
|
+
|
|
28
|
+
key = KMSKey("alias/my-signing-key")
|
|
29
|
+
token = jwt.encode(
|
|
30
|
+
{"sub": "user-123"}, key, algorithm="ES256", headers={"kid": key.key_id}
|
|
31
|
+
)
|
|
32
|
+
claims = jwt.decode(token, key, algorithms=["ES256"])
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
- Requires Python 3.12+ and PyJWT 2.15.1+ (with the `cryptography` extra, which is installed for you).
|
|
36
|
+
- Signing calls KMS. Verification does not: it uses the key's public half, fetched once and cached.
|
|
37
|
+
- Asymmetric algorithms only. HMAC (HS256/384/512) is not supported yet.
|
|
38
|
+
|
|
39
|
+
## Install
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
pip install pyjwt-aws-kms
|
|
43
|
+
# or
|
|
44
|
+
uv add pyjwt-aws-kms
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Usage
|
|
48
|
+
|
|
49
|
+
### 1. Register the algorithms
|
|
50
|
+
|
|
51
|
+
Call `register_algorithms()` once at start-up, before you encode or decode:
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from pyjwt_aws_kms import register_algorithms
|
|
55
|
+
|
|
56
|
+
register_algorithms()
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
This extends PyJWT's standard algorithms (`RS256`, `ES256`, ...) so they also accept a KMS key.
|
|
60
|
+
Anything else keeps working exactly as before: if you pass a normal key (a PEM string, a
|
|
61
|
+
`cryptography` key object, a `PyJWK`), PyJWT handles it as it always did. You can mix KMS and
|
|
62
|
+
local keys in the same application.
|
|
63
|
+
|
|
64
|
+
### 2. Create a `KMSKey`
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from pyjwt_aws_kms import KMSKey
|
|
68
|
+
|
|
69
|
+
key = KMSKey("alias/my-signing-key")
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
The first argument is anything KMS accepts as a `KeyId`: a key ID, a key ARN, an alias name or an
|
|
73
|
+
alias ARN.
|
|
74
|
+
|
|
75
|
+
A `KMSKey` creates a default boto3 KMS client on first use. To control the region, credentials,
|
|
76
|
+
retries or endpoint, pass your own:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
import boto3
|
|
80
|
+
|
|
81
|
+
client = boto3.client("kms", region_name="eu-west-2")
|
|
82
|
+
key = KMSKey("alias/my-signing-key", client)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Reuse one `KMSKey` per KMS key rather than creating one per request, so the cached public key is
|
|
86
|
+
reused.
|
|
87
|
+
|
|
88
|
+
> **Signing with `ES256` or `ES256K`** needs `kms:GetPublicKey` as well as `kms:Sign`, unless you
|
|
89
|
+
> opt out with `KMSKey(..., check_curve_on_sign=False)`. See
|
|
90
|
+
> [Signing with ES256 and ES256K](#signing-with-es256-and-es256k).
|
|
91
|
+
|
|
92
|
+
### 3. Sign and verify
|
|
93
|
+
|
|
94
|
+
Use the key as the `key` argument of `jwt.encode` and `jwt.decode`, with an `algorithm` that
|
|
95
|
+
matches the KMS key's type (see below):
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
token = jwt.encode(
|
|
99
|
+
{"sub": "user-123", "iss": "https://example.com"},
|
|
100
|
+
key,
|
|
101
|
+
algorithm="RS256",
|
|
102
|
+
headers={"kid": key.key_id},
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
claims = jwt.decode(token, key, algorithms=["RS256"], issuer="https://example.com")
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
All the usual PyJWT behaviour (claim validation, `options`, `PyJWT` instances) is unchanged.
|
|
109
|
+
|
|
110
|
+
`kid` is not set automatically. If you want a key identifier in the header, pass it as above.
|
|
111
|
+
|
|
112
|
+
### Verifying without KMS
|
|
113
|
+
|
|
114
|
+
Because KMS keys are asymmetric, anyone with the public key can verify your tokens. They don't need
|
|
115
|
+
AWS access or this library. You can fetch the public key once and give it to them (or publish it
|
|
116
|
+
yourself, for example in a JWKS endpoint):
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
public_key = key.public_key() # a cryptography public key object
|
|
120
|
+
jwt.decode(token, public_key, algorithms=["RS256"])
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
## Supported algorithms
|
|
124
|
+
|
|
125
|
+
The JWT `algorithm` must match the KMS key's key spec:
|
|
126
|
+
|
|
127
|
+
| JWT `alg` | KMS key spec | KMS signing algorithm |
|
|
128
|
+
|-------------------------|---------------------------------------------|------------------------------------------|
|
|
129
|
+
| `RS256` `RS384` `RS512` | `RSA_2048` / `RSA_3072` / `RSA_4096` | `RSASSA_PKCS1_V1_5_SHA_256` / `384` / `512` |
|
|
130
|
+
| `PS256` `PS384` `PS512` | `RSA_2048` / `RSA_3072` / `RSA_4096` | `RSASSA_PSS_SHA_256` / `384` / `512` |
|
|
131
|
+
| `ES256` | `ECC_NIST_P256` | `ECDSA_SHA_256` |
|
|
132
|
+
| `ES384` | `ECC_NIST_P384` | `ECDSA_SHA_384` |
|
|
133
|
+
| `ES512` | `ECC_NIST_P521` | `ECDSA_SHA_512` |
|
|
134
|
+
| `ES256K` | `ECC_SECG_P256K1` | `ECDSA_SHA_256` |
|
|
135
|
+
| `EdDSA` | `ECC_NIST_EDWARDS25519` | `ED25519_SHA_512` |
|
|
136
|
+
|
|
137
|
+
The KMS key's usage must be `SIGN_VERIFY`. Signing with an algorithm that doesn't match the key (for
|
|
138
|
+
example `RS256` with an EC key) makes KMS reject the request, and boto3 raises its usual
|
|
139
|
+
`ClientError`. `ES256` and `ES256K` are checked before KMS is called, as described next.
|
|
140
|
+
|
|
141
|
+
### Signing with ES256 and ES256K
|
|
142
|
+
|
|
143
|
+
`ES256` and `ES256K` use the same KMS signing algorithm (`ECDSA_SHA_256`), so KMS can't tell them
|
|
144
|
+
apart. Given an `ECC_SECG_P256K1` key and `ES256` (or an `ECC_NIST_P256` key and `ES256K`), it would
|
|
145
|
+
sign without complaint, producing a token that correct verifiers reject.
|
|
146
|
+
|
|
147
|
+
To prevent that, the library checks the key's curve before signing with either algorithm, and raises
|
|
148
|
+
`jwt.InvalidKeyError` if it doesn't match. This needs **`kms:GetPublicKey` as well as `kms:Sign`**.
|
|
149
|
+
The public key is fetched once per `KMSKey`, then cached.
|
|
150
|
+
|
|
151
|
+
If you're sure the key matches the algorithm, you can opt out and sign with only `kms:Sign`:
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
key = KMSKey("alias/my-signing-key", check_curve_on_sign=False)
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
Opting out only affects signing. Verification always checks the key type and curve. The setting has
|
|
158
|
+
no effect on other algorithms, which never fetch the public key to sign.
|
|
159
|
+
|
|
160
|
+
Not supported: HMAC (`HS*`), RSA-OAEP / encryption keys, ML-DSA, and JWK export of a `KMSKey`
|
|
161
|
+
itself (export `key.public_key()` instead). JWK import/export of ordinary keys through the
|
|
162
|
+
registered algorithms keeps working.
|
|
163
|
+
|
|
164
|
+
## Permissions
|
|
165
|
+
|
|
166
|
+
The IAM principal needs, on the KMS key:
|
|
167
|
+
|
|
168
|
+
| To do this | Permission |
|
|
169
|
+
|------------|------------|
|
|
170
|
+
| Sign (`jwt.encode`) with `ES256` or `ES256K` | `kms:Sign` and `kms:GetPublicKey` (called once per `KMSKey`, then cached) |
|
|
171
|
+
| Sign with `ES256` or `ES256K`, using `check_curve_on_sign=False` | `kms:Sign` |
|
|
172
|
+
| Sign with any other algorithm | `kms:Sign` |
|
|
173
|
+
| Verify with the `KMSKey` (`jwt.decode`) | `kms:GetPublicKey` (called once per `KMSKey`, then cached) |
|
|
174
|
+
|
|
175
|
+
Example policy statement:
|
|
176
|
+
|
|
177
|
+
```json
|
|
178
|
+
{
|
|
179
|
+
"Effect": "Allow",
|
|
180
|
+
"Action": ["kms:Sign", "kms:GetPublicKey"],
|
|
181
|
+
"Resource": "arn:aws:kms:eu-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
|
|
182
|
+
}
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
A service that only issues tokens needs just `kms:Sign`, unless it uses `ES256` or `ES256K` without
|
|
186
|
+
[opting out of the curve check](#signing-with-es256-and-es256k). One that only verifies needs just
|
|
187
|
+
`kms:GetPublicKey`, or no AWS access at all if you hand it the public key.
|
|
188
|
+
|
|
189
|
+
IAM resource ARNs refer to the key, not its alias, so use the key ARN in policies even if your
|
|
190
|
+
code uses an alias.
|
|
191
|
+
|
|
192
|
+
## How signing works
|
|
193
|
+
|
|
194
|
+
- **Hashing is done locally.** For every algorithm except EdDSA, the library hashes the JWT's
|
|
195
|
+
signing input and sends KMS the digest (`MessageType=DIGEST`). KMS therefore never sees your
|
|
196
|
+
token contents, and there is no size limit on the payload.
|
|
197
|
+
- **EdDSA** is the exception: KMS has no digest mode for Ed25519, so the raw signing input is sent
|
|
198
|
+
(`MessageType=RAW`). KMS limits that to 4096 bytes, so a larger token raises `ValueError`
|
|
199
|
+
before any request is made.
|
|
200
|
+
- **ECDSA** signatures come back from KMS in DER form. They are converted to the fixed-width
|
|
201
|
+
`r || s` form that JWS requires.
|
|
202
|
+
- **Verification** is done locally with `cryptography`, using the public key from
|
|
203
|
+
`GetPublicKey`. It does not call KMS's `Verify` API, so it costs nothing and isn't subject to KMS
|
|
204
|
+
request quotas. The key family and (for ECDSA) curve are checked against the algorithm, so a
|
|
205
|
+
token can't be verified with a key of the wrong type.
|
|
206
|
+
|
|
207
|
+
## Using your own `PyJWT` / `PyJWS` instance
|
|
208
|
+
|
|
209
|
+
By default `register_algorithms()` registers on PyJWT's global registry, which is what
|
|
210
|
+
`jwt.encode` and `jwt.decode` use. To keep it contained, register on a `PyJWS` instance instead:
|
|
211
|
+
|
|
212
|
+
```python
|
|
213
|
+
import jwt
|
|
214
|
+
from pyjwt_aws_kms import register_algorithms
|
|
215
|
+
|
|
216
|
+
jws = jwt.PyJWS()
|
|
217
|
+
register_algorithms(jws)
|
|
218
|
+
|
|
219
|
+
jws.encode(b'{"sub":"x"}', key, algorithm="ES256")
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
Calling `register_algorithms()` more than once is safe, as is calling it while other threads are
|
|
223
|
+
encoding or decoding. On a `PyJWS(algorithms=[...])` instance, only the enabled algorithms are
|
|
224
|
+
wrapped.
|
|
225
|
+
|
|
226
|
+
## Local development against Local KMS
|
|
227
|
+
|
|
228
|
+
[Local KMS](https://github.com/nsmithuk/local-kms) emulates KMS for development and tests. Point
|
|
229
|
+
the boto3 client at it:
|
|
230
|
+
|
|
231
|
+
```python
|
|
232
|
+
client = boto3.client(
|
|
233
|
+
"kms",
|
|
234
|
+
endpoint_url="http://localhost:8080",
|
|
235
|
+
region_name="eu-west-2",
|
|
236
|
+
aws_access_key_id="local", # any value; Local KMS doesn't check them
|
|
237
|
+
aws_secret_access_key="local",
|
|
238
|
+
)
|
|
239
|
+
key = KMSKey("alias/seed_ecc_nist_p256_sign_verify", client)
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
> **Note:** use Local KMS 4.0.0-rc.2 or later. Earlier releases signed `PS256`/`PS384`/`PS512` with
|
|
243
|
+
> the wrong RSA-PSS salt length, so those tokens failed verification in standard libraries.
|
|
244
|
+
|
|
245
|
+
## Development
|
|
246
|
+
|
|
247
|
+
The project uses [uv](https://docs.astral.sh/uv/) and hatchling.
|
|
248
|
+
|
|
249
|
+
```sh
|
|
250
|
+
uv sync # create .venv and install dependencies
|
|
251
|
+
uv run pytest # unit tests (+ functional tests if Local KMS is running)
|
|
252
|
+
uv run ruff check .
|
|
253
|
+
uv run mypy src
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
There are two kinds of test:
|
|
257
|
+
|
|
258
|
+
- **Unit tests** (`tests/test_kms.py`) use an in-process fake KMS client, so they need nothing
|
|
259
|
+
running.
|
|
260
|
+
- **Functional tests** (`tests/test_local_kms.py`) run against a real KMS endpoint and are skipped
|
|
261
|
+
if none is reachable.
|
|
262
|
+
|
|
263
|
+
To run the functional tests against Local KMS, start it with the seed file, then run pytest:
|
|
264
|
+
|
|
265
|
+
```sh
|
|
266
|
+
./run-local-kms.sh # needs Docker; listens on 127.0.0.1:8080
|
|
267
|
+
uv run pytest tests/test_local_kms.py
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
To run the same tests against real AWS KMS, set `REAL_KMS=true` and provide credentials the usual
|
|
271
|
+
way (environment variables, a profile, SSO). The region defaults to `eu-west-2`, or set
|
|
272
|
+
`AWS_REGION`:
|
|
273
|
+
|
|
274
|
+
```sh
|
|
275
|
+
REAL_KMS=true uv run pytest tests/test_local_kms.py
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
The aliases listed in `CASES` in `tests/test_local_kms.py` (for example
|
|
279
|
+
`alias/seed_rsa_2048_sign_verify`) must exist in that account and region. They match the keys
|
|
280
|
+
seeded into the Local KMS image. The identity needs `kms:DescribeKey`, `kms:GetPublicKey` and
|
|
281
|
+
`kms:Sign` on them.
|
|
282
|
+
|
|
283
|
+
## Licence
|
|
284
|
+
|
|
285
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
pyjwt_aws_kms/__init__.py,sha256=PpCspNomcKO5zltUm5URHMv4eeuNScZpQVtaPVCmjbo,143
|
|
2
|
+
pyjwt_aws_kms/algorithms.py,sha256=4KyDVHSiP763AEt3oWwDamw0OrrumyGDKdcBztU3Hyo,6709
|
|
3
|
+
pyjwt_aws_kms/key.py,sha256=2dKMZgPBJU7xpUjVrMzK9l6DsHymJXhE4mR0nrIEi4g,1984
|
|
4
|
+
pyjwt_aws_kms/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
pyjwt_aws_kms-0.2.0.dist-info/METADATA,sha256=cFMgi5VDO5kgdwSjneFkuaErsA-B__ksGBnhpifuwWY,10924
|
|
6
|
+
pyjwt_aws_kms-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
pyjwt_aws_kms-0.2.0.dist-info/licenses/LICENSE,sha256=SfZNm46XRSaiilNYUJCa0nhpUd5tGHWo5apQnlzC41k,1067
|
|
8
|
+
pyjwt_aws_kms-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Neil Smith
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|