arctiq-cli 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.
arctiq_cli/project.py ADDED
@@ -0,0 +1,100 @@
1
+ """This folder: its GitHub repository (from git's `origin`) and its `.arctiq.yml`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import subprocess
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ CONFIG = ".arctiq.yml"
11
+ _GITHUB = re.compile(
12
+ r"^(?:https://github\.com/|git@github\.com:|ssh://git@github\.com/)"
13
+ r"(?P<owner>[A-Za-z0-9-]{1,39})/(?P<name>[A-Za-z0-9._-]{1,100}?)(?:\.git)?/?$"
14
+ )
15
+
16
+
17
+ class ProjectError(Exception):
18
+ pass
19
+
20
+
21
+ def root(start: Path | None = None) -> Path:
22
+ try:
23
+ out = subprocess.run( # noqa: S603
24
+ ["git", "rev-parse", "--show-toplevel"], # noqa: S607
25
+ cwd=start or Path.cwd(), capture_output=True, text=True, check=True,
26
+ ) # fmt: skip
27
+ except (OSError, subprocess.CalledProcessError):
28
+ raise ProjectError("This folder isn't a git repository.") from None
29
+ return Path(out.stdout.strip())
30
+
31
+
32
+ def github_of(folder: Path) -> tuple[str, str]:
33
+ """(owner, name) of the GitHub repository `origin` points to."""
34
+ try:
35
+ out = subprocess.run( # noqa: S603
36
+ ["git", "config", "--get", "remote.origin.url"], # noqa: S607
37
+ cwd=folder, capture_output=True, text=True, check=True,
38
+ ) # fmt: skip
39
+ except (OSError, subprocess.CalledProcessError):
40
+ raise ProjectError("This repository has no 'origin' remote on GitHub.") from None
41
+ found = _GITHUB.match(out.stdout.strip())
42
+ if not found:
43
+ raise ProjectError("'origin' isn't a GitHub repository.")
44
+ return found["owner"], found["name"]
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class Linked:
49
+ organisation: str
50
+ repository: str
51
+
52
+
53
+ def read(folder: Path) -> Linked | None:
54
+ """The organisation and repository `arctiq link` wrote. Only those two top-level keys are
55
+ read here; the server reads the rest (the check's settings)."""
56
+ path = folder / CONFIG
57
+ if not path.exists():
58
+ return None
59
+ found: dict[str, str] = {}
60
+ for line in path.read_text().splitlines():
61
+ match = re.match(
62
+ r"^(organisation|repository):\s*['\"]?([A-Za-z0-9._-]+)['\"]?\s*(#.*)?$", line
63
+ )
64
+ if match:
65
+ found[match[1]] = match[2]
66
+ if "organisation" in found and "repository" in found:
67
+ return Linked(found["organisation"], found["repository"])
68
+ return None
69
+
70
+
71
+ TEMPLATE = """# ARCTIQ: written by `arctiq link`. The check on pull requests reads `check`.
72
+ organisation: {organisation}
73
+ repository: {repository}
74
+ check:
75
+ linked: true
76
+ pinned: true
77
+ commits: true
78
+ licences: true
79
+ report_only: true
80
+ """
81
+
82
+
83
+ def write(folder: Path, linked: Linked) -> None:
84
+ """Write `.arctiq.yml`, keeping a file that is already there apart from the two keys."""
85
+ path = folder / CONFIG
86
+ if not path.exists():
87
+ path.write_text(
88
+ TEMPLATE.format(organisation=linked.organisation, repository=linked.repository)
89
+ )
90
+ return
91
+ lines, seen = [], set()
92
+ for line in path.read_text().splitlines():
93
+ key = line.split(":", 1)[0]
94
+ if key in ("organisation", "repository") and not line.startswith((" ", "\t")):
95
+ lines.append(f"{key}: {getattr(linked, key)}")
96
+ seen.add(key)
97
+ else:
98
+ lines.append(line)
99
+ head = [f"{k}: {getattr(linked, k)}" for k in ("organisation", "repository") if k not in seen]
100
+ path.write_text("\n".join(head + lines) + "\n")
arctiq_cli/seal.py ADDED
@@ -0,0 +1,217 @@
1
+ """Sealing a file for a dataset sealed for enclaves, on your side (ADR 0031, phase 4).
2
+
3
+ Needs `arctiq-cli[seal]` (the `cryptography` and `cbor2` packages).
4
+
5
+ Before anything is sealed, the dataset's enclave key is checked: ARCTIQ gives its public part
6
+ with the attestation the enclave made when it made the key. This tool checks that document
7
+ itself: its signature, its chain to a root this tool trusts, that the image it names is one the
8
+ owner allows, and that the key it names is the key given. Only then is the file sealed, with a
9
+ key made for it alone, in ARCTIQ's frames (AES-256-GCM, 1 MiB frames, each bound to the file's
10
+ place, its position and whether it is the last), and that key wrapped to the dataset's hybrid
11
+ key: RSA-3072 and ML-KEM-768 (FIPS 203) at once, so it stays sealed if either holds, against a
12
+ quantum computer that would break RSA too. ARCTIQ never has the file's key.
13
+
14
+ The roots: AWS Nitro Enclaves' root, carried with this tool (`aws_nitro_root_g1.pem`, checked
15
+ against the fingerprint AWS publishes); the local stand-in's own root only when you say so
16
+ (`--local-stand-in`), because the stand-in runs in ARCTIQ's own process and protects nothing from
17
+ ARCTIQ.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import base64
23
+ import datetime as dt
24
+ import hashlib
25
+ import json
26
+ import os
27
+ import struct
28
+ from collections.abc import Iterator
29
+ from dataclasses import dataclass
30
+ from pathlib import Path
31
+
32
+ FRAME = 1024 * 1024
33
+ KEY_BYTES = 32
34
+ NONCE_BYTES = 12
35
+ TAG_BYTES = 16
36
+ FRAME_EXTRA = 4 + NONCE_BYTES + TAG_BYTES
37
+ ES384 = -35
38
+ COSE_SIGN1_TAG = 18
39
+ #: What binds the key that seals a file's key to this use (as ARCTIQ's `spaces/sealing.py`).
40
+ INFO = b"arctiq-hybrid-wrap-v1"
41
+
42
+
43
+ class SealFailed(Exception):
44
+ """The dataset's key didn't check out, or sealing isn't possible here; said in words."""
45
+
46
+
47
+ #: AWS Nitro Enclaves' root (G1), as AWS publishes its SHA-256 fingerprint ("Verifying the root of
48
+ #: trust", Nitro Enclaves User Guide). The file beside this module was downloaded from
49
+ #: aws-nitro-enclaves.amazonaws.com/AWS_NitroEnclaves_Root-G1.zip and matched it on 4 Dec 2026.
50
+ NITRO_ROOT_SHA256 = "641a0321a3e244efe456463195d606317ed7cdcc3c1756e09893f3c68f79bb5b"
51
+
52
+
53
+ def nitro_root():
54
+ """AWS Nitro Enclaves' root, checked against its published fingerprint each time it is read."""
55
+ from pathlib import Path
56
+
57
+ from cryptography import x509
58
+ from cryptography.hazmat.primitives import hashes
59
+
60
+ root = x509.load_pem_x509_certificate(
61
+ Path(__file__).with_name("aws_nitro_root_g1.pem").read_bytes()
62
+ )
63
+ if root.fingerprint(hashes.SHA256()).hex() != NITRO_ROOT_SHA256:
64
+ raise SealFailed("The AWS Nitro root this tool carries isn't the one AWS publishes.")
65
+ return root
66
+
67
+
68
+ def _need():
69
+ try:
70
+ import cbor2
71
+ from cryptography.hazmat.primitives.asymmetric import mlkem # noqa: F401 - 47 or later
72
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM # noqa: F401
73
+ except ImportError:
74
+ raise SealFailed(
75
+ "Sealing needs the seal extra, with cryptography 47 or later: "
76
+ 'pip install -U "arctiq-cli[seal]"'
77
+ ) from None
78
+ return cbor2
79
+
80
+
81
+ def sealed_size(size: int) -> int:
82
+ return size + max(1, -(-size // FRAME)) * FRAME_EXTRA
83
+
84
+
85
+ def _aad(blob_key: str, index: int, last: bool) -> bytes:
86
+ return blob_key.encode() + struct.pack(">QB", index, 1 if last else 0)
87
+
88
+
89
+ def frames(secret: bytes, blob_key: str, path: Path) -> Iterator[bytes]:
90
+ """The file sealed, frame by frame (an empty file is one empty frame)."""
91
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
92
+
93
+ aead = AESGCM(secret)
94
+ size = path.stat().st_size
95
+ count = max(1, -(-size // FRAME))
96
+ with path.open("rb") as f:
97
+ for index in range(count):
98
+ plain = f.read(FRAME)
99
+ nonce = os.urandom(NONCE_BYTES)
100
+ body = nonce + aead.encrypt(nonce, plain, _aad(blob_key, index, index == count - 1))
101
+ yield struct.pack(">I", len(body)) + body
102
+
103
+
104
+ def wrap(public: bytes, secret: bytes) -> str:
105
+ """The file's key, wrapped to the dataset's hybrid enclave key (its public bundle), as ARCTIQ's
106
+ `spaces/sealing.py` does: one secret encrypted to its RSA-3072 part (OAEP, SHA-256), another
107
+ encapsulated to its ML-KEM-768 part, and the key that seals the file's key derived from both
108
+ (HKDF-SHA256). It takes both private parts to open: it stays sealed if either holds."""
109
+ from cryptography.hazmat.primitives import hashes, serialization
110
+ from cryptography.hazmat.primitives.asymmetric import mlkem, padding, rsa
111
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
112
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
113
+
114
+ try:
115
+ data = json.loads(public)
116
+ r = serialization.load_pem_public_key(data["rsa"].encode())
117
+ m = mlkem.MLKEM768PublicKey.from_public_bytes(base64.b64decode(data["ml_kem_768"]))
118
+ except (KeyError, ValueError, TypeError):
119
+ raise SealFailed("The dataset's enclave key isn't one this tool knows.") from None
120
+ if data.get("v") != 1 or not isinstance(r, rsa.RSAPublicKey) or r.key_size != 3072:
121
+ raise SealFailed("The dataset's enclave key isn't one this tool knows.")
122
+ rsa_secret = os.urandom(32)
123
+ rsa_ct = r.encrypt(rsa_secret, padding.OAEP(mgf=padding.MGF1(hashes.SHA256()),
124
+ algorithm=hashes.SHA256(), label=None)) # fmt: skip
125
+ kem_secret, kem_ct = m.encapsulate()
126
+ info = INFO + hashlib.sha256(rsa_ct + kem_ct).digest()
127
+ kek = HKDF(algorithm=hashes.SHA256(), length=32, salt=bytes(32), info=info).derive(
128
+ rsa_secret + kem_secret
129
+ )
130
+ nonce = os.urandom(NONCE_BYTES)
131
+ boxed = AESGCM(kek).encrypt(nonce, secret, INFO)
132
+ blob = bytes([1]) + struct.pack(">H", len(rsa_ct)) + rsa_ct + kem_ct + nonce + boxed
133
+ return base64.b64encode(blob).decode()
134
+
135
+
136
+ def new_key() -> bytes:
137
+ return os.urandom(KEY_BYTES)
138
+
139
+
140
+ @dataclass(frozen=True)
141
+ class Checked:
142
+ image: str # the allowed image's name
143
+ pcr0: str
144
+ root: str # "AWS Nitro Enclaves" or "the local stand-in"
145
+
146
+
147
+ def check_key(
148
+ key: dict, *, local_stand_in: bool = False, now: dt.datetime | None = None
149
+ ) -> Checked:
150
+ """Check the dataset's enclave key (as `GET .../enclave-key` gives it) before sealing to it."""
151
+ cbor2 = _need()
152
+ from cryptography import x509
153
+ from cryptography.exceptions import InvalidSignature
154
+ from cryptography.hazmat.primitives import hashes
155
+ from cryptography.hazmat.primitives.asymmetric import ec
156
+ from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature
157
+
158
+ if key.get("root") == "local":
159
+ if not local_stand_in:
160
+ raise SealFailed("This ARCTIQ runs its enclaves on a local stand-in, which protects "
161
+ "nothing from ARCTIQ. To seal to it anyway: --local-stand-in") # fmt: skip
162
+ roots = [x509.load_pem_x509_certificate(key["local_root"].encode())]
163
+ root_name = "the local stand-in"
164
+ elif key.get("root") == "aws-nitro":
165
+ roots = [nitro_root()]
166
+ root_name = "AWS Nitro Enclaves"
167
+ else:
168
+ raise SealFailed("ARCTIQ didn't give an enclave key this tool knows how to check.")
169
+ try:
170
+ outer = cbor2.loads(base64.b64decode(key["attestation"]))
171
+ if isinstance(outer, cbor2.CBORTag):
172
+ outer = outer.value
173
+ protected, _unprotected, payload, signature = outer
174
+ header, body = cbor2.loads(protected), cbor2.loads(payload)
175
+ leaf = x509.load_der_x509_certificate(body["certificate"])
176
+ bundle = [x509.load_der_x509_certificate(c) for c in body["cabundle"]]
177
+ except (KeyError, ValueError, TypeError, cbor2.CBORDecodeError):
178
+ raise SealFailed("The enclave key's attestation can't be read.") from None
179
+ if header.get(1) != ES384:
180
+ raise SealFailed("The enclave key's attestation isn't signed with ES384.")
181
+ trusted = {r.fingerprint(hashes.SHA256()) for r in roots}
182
+ if not bundle or bundle[0].fingerprint(hashes.SHA256()) not in trusted:
183
+ raise SealFailed("The enclave key's attestation doesn't lead to a root this tool trusts.")
184
+ at = dt.datetime.fromtimestamp(int(body["timestamp"]) / 1000, dt.timezone.utc)
185
+ chain = [*bundle, leaf]
186
+ for parent, child in zip(chain, chain[1:], strict=False):
187
+ try:
188
+ child.verify_directly_issued_by(parent)
189
+ except (ValueError, TypeError, InvalidSignature):
190
+ raise SealFailed("The enclave key's attestation has a broken chain.") from None
191
+ for cert in chain:
192
+ if not cert.not_valid_before_utc <= at <= cert.not_valid_after_utc:
193
+ raise SealFailed("A certificate in the attestation's chain wasn't valid when it "
194
+ "was made.") # fmt: skip
195
+ if len(signature) != 96:
196
+ raise SealFailed("The enclave key's attestation has a signature of the wrong length.")
197
+ der = encode_dss_signature(int.from_bytes(signature[:48], "big"),
198
+ int.from_bytes(signature[48:], "big")) # fmt: skip
199
+ public = leaf.public_key()
200
+ if not isinstance(public, ec.EllipticCurvePublicKey):
201
+ raise SealFailed("The attestation's signing key isn't an elliptic curve key.")
202
+ try:
203
+ public.verify(der, cbor2.dumps(["Signature1", protected, b"", payload]),
204
+ ec.ECDSA(hashes.SHA384())) # fmt: skip
205
+ except InvalidSignature:
206
+ raise SealFailed("The enclave key's attestation doesn't match its signature.") from None
207
+ if now is not None and at > now + dt.timedelta(minutes=5):
208
+ raise SealFailed("The enclave key's attestation is dated in the future.")
209
+ pcr0 = bytes((body.get("pcrs") or {}).get(0, b"")).hex()
210
+ allowed = {i["pcr0"]: i["name"] for i in key.get("images") or []}
211
+ if pcr0 not in allowed:
212
+ raise SealFailed("The enclave that made this key ran an image the owner doesn't allow.")
213
+ made = json.loads(body.get("user_data") or b"{}")
214
+ given = key["public_key"].encode()
215
+ if made.get("public_key") != hashlib.sha256(given).hexdigest():
216
+ raise SealFailed("The key given isn't the key the enclave made.")
217
+ return Checked(allowed[pcr0], pcr0, root_name)
@@ -0,0 +1,19 @@
1
+ """`arctiq tui` (ADR 0027): the terminal app, in the `tui` extra (`pip install "arctiq-cli[tui]"`).
2
+
3
+ Importing this package needs Textual; `arctiq_cli.main` imports it only when `arctiq tui` runs,
4
+ so the plain CLI stays standard-library only.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+
11
+ from arctiq_cli.client import Api
12
+ from arctiq_cli.tui.app import ArctiqApp
13
+ from arctiq_cli.tui.source import Source
14
+
15
+ __all__ = ["ArctiqApp", "Source", "run"]
16
+
17
+
18
+ def run(api: Api, org: str, *, linked_repo: str | None, folder: Path | None) -> None:
19
+ ArctiqApp(Source(api, org), linked_repo=linked_repo, folder_path=folder).run()