mkp-contracts 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.
@@ -0,0 +1,12 @@
1
+ """The contracts that cross component boundaries, as code.
2
+
3
+ `schema/` holds them as data; this holds the rules a schema cannot express — what a
4
+ bundle's canonical form is, therefore what its digest is, therefore what its identity
5
+ is. Both the builder and the control plane depend on this rather than on each other,
6
+ because "what is this bundle" must have one answer and neither of them owns it.
7
+
8
+ A library, deliberately: no CLI, no side effects, no I/O beyond reading a document it
9
+ was handed.
10
+ """
11
+
12
+ __version__ = "0.1.0"
@@ -0,0 +1,70 @@
1
+ """What is inside a bundle archive, and whether it is what it claims to be.
2
+
3
+ Here for the same reason `canonical.py` is: **a bundle's identity is the digest of its
4
+ manifest, not the hash of its archive**, so "does this archive belong under this
5
+ digest?" is not a question either the builder or the control plane can answer alone
6
+ without one of them defining the answer for the other.
7
+
8
+ The distinction bites the first time someone stores an archive. Two builds of identical
9
+ content produce byte-identical archives — that is what the `filename=""` in the gzip
10
+ header exists for — but the archive is still not the identity: the manifest inside it
11
+ is, and it is the manifest that `signature` covers and that `created` is excluded from.
12
+ An implementation that filed archives under `sha256(bytes)` would be filing them under a
13
+ name nothing else in the system uses.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import io
19
+ import json
20
+ import tarfile
21
+ from typing import Any
22
+
23
+ from .canonical import manifest_digest
24
+ from .errors import ContractError
25
+
26
+ MANIFEST_NAME = "manifest.json"
27
+
28
+ # A bundle is workflows, machines and small assets. Refusing to expand beyond this is
29
+ # what stops a crafted archive turning a read into a memory exhaustion — the check
30
+ # happens before the tar is walked, on a number the header states rather than on what
31
+ # it actually contains.
32
+ MAX_ARCHIVE_BYTES = 64 * 1024 * 1024
33
+
34
+
35
+ def manifest_of(archive: bytes) -> dict[str, Any]:
36
+ """The manifest at the root of an archive."""
37
+ if len(archive) > MAX_ARCHIVE_BYTES:
38
+ raise ContractError(f"archive is larger than {MAX_ARCHIVE_BYTES} bytes")
39
+ try:
40
+ with tarfile.open(fileobj=io.BytesIO(archive), mode="r:gz") as tar:
41
+ member = tar.extractfile(MANIFEST_NAME)
42
+ if member is None:
43
+ raise ContractError(f"no {MANIFEST_NAME} at the root of the archive")
44
+ return json.loads(member.read())
45
+ except tarfile.TarError as exc:
46
+ raise ContractError(f"not a readable bundle archive: {exc}") from exc
47
+ except ValueError as exc:
48
+ raise ContractError(f"{MANIFEST_NAME} is not JSON: {exc}") from exc
49
+
50
+
51
+ def digest_of(archive: bytes) -> str:
52
+ """The bundle identity this archive carries.
53
+
54
+ Read off the manifest inside, never off the bytes: the archive is a container and
55
+ the manifest is the thing with a name.
56
+ """
57
+ return manifest_digest(manifest_of(archive))
58
+
59
+
60
+ def belongs_under(archive: bytes, digest: str) -> bool:
61
+ return digest_of(archive) == digest
62
+
63
+
64
+ __all__ = [
65
+ "MANIFEST_NAME",
66
+ "MAX_ARCHIVE_BYTES",
67
+ "belongs_under",
68
+ "digest_of",
69
+ "manifest_of",
70
+ ]
@@ -0,0 +1,42 @@
1
+ """Canonical form and digests.
2
+
3
+ A bundle's identity is the digest of its content (ADR 0008), which only works if
4
+ building the same content twice produces the same digest. Three manifest fields
5
+ are therefore outside the canonical form:
6
+
7
+ - `created` is a build timestamp; including it would give identical content two
8
+ identities and defeat the whole model — promote-by-digest, "nothing is rebuilt",
9
+ and "a superseded bundle is retained until no run references it" all rest on
10
+ content and identity being the same thing.
11
+ - `source` is documented in `bundle.schema.json` as informational: "identity is
12
+ the content digest, not this".
13
+ - `signature` cannot be inside the bytes it signs.
14
+
15
+ The signature covers exactly these canonical bytes, so there is one canonical
16
+ form and not two.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import hashlib
22
+ import json
23
+ from typing import Any
24
+
25
+ EXCLUDED_FROM_IDENTITY = ("created", "source", "signature")
26
+
27
+
28
+ def canonical_bytes(document: dict[str, Any]) -> bytes:
29
+ """The bytes a digest and a signature are both computed over."""
30
+ stripped = {k: v for k, v in document.items() if k not in EXCLUDED_FROM_IDENTITY}
31
+ return json.dumps(stripped, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode(
32
+ "utf-8"
33
+ )
34
+
35
+
36
+ def manifest_digest(manifest: dict[str, Any]) -> str:
37
+ """The bundle's identity: sha256 over the canonical manifest, bare hex."""
38
+ return hashlib.sha256(canonical_bytes(manifest)).hexdigest()
39
+
40
+
41
+ def file_digest(data: bytes) -> str:
42
+ return hashlib.sha256(data).hexdigest()
@@ -0,0 +1,34 @@
1
+ """The CLI versions the control plane serves (ADR 0014, `C33`).
2
+
3
+ Here rather than in the api, because this package is where wire compatibility
4
+ already lives: the PR that changes a canonical form is the PR that moves
5
+ `CLI_MINIMUM`, reviewed as one change. `CLI_LATEST` moves in the commit that tags a
6
+ CLI release — `release-cli.yml` fails when the tag disagrees, so the two cannot
7
+ drift silently.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ # The oldest mkctl the wire still serves. Raised deliberately, in the same PR as the
13
+ # change that stops serving older ones — never as housekeeping.
14
+ CLI_MINIMUM = "0.1.0"
15
+
16
+ # What `mkctl upgrade` and the login advisory point at. 0.4.0 is the first version on
17
+ # PyPI: before it, `mkbundle` and this package shipped as `0.1.0` in three different
18
+ # GitHub releases, which is three builds behind one number — fine for assets fetched by
19
+ # tag, wrong for an index where a version is permanent.
20
+ CLI_LATEST = "0.4.0"
21
+
22
+
23
+ def parse(version: str) -> tuple[int, ...] | None:
24
+ """`"0.2.0"` → `(0, 2, 0)`; anything else → None.
25
+
26
+ None means "do not gate": a User-Agent this module cannot read belongs to a
27
+ client this contract does not cover, and refusing what you cannot parse would
28
+ gate curl and every future tool along with it.
29
+ """
30
+ parts = version.strip().split(".")
31
+ try:
32
+ return tuple(int(part) for part in parts)
33
+ except ValueError:
34
+ return None
@@ -0,0 +1,69 @@
1
+ """Failures, reported as data rather than raised one at a time.
2
+
3
+ A build reports every rule a bundle breaks, not the first. Fixing one problem
4
+ only to be told about the next is what makes a validator feel like an obstacle
5
+ instead of a tool.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass, field
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Failure:
15
+ """One broken rule, attributable to one place."""
16
+
17
+ rule: str
18
+ """Stable id, e.g. `machine-missing`. Cited in messages and in tests."""
19
+
20
+ message: str
21
+
22
+ path: str = ""
23
+ """Bundle-relative path of the document at fault, when there is one."""
24
+
25
+ location: str = ""
26
+ """Where inside the document, e.g. `steps[2].idempotency_key`."""
27
+
28
+ def __str__(self) -> str:
29
+ where = self.path or "<bundle>"
30
+ if self.location:
31
+ where = f"{where}:{self.location}"
32
+ return f"{where}: [{self.rule}] {self.message}"
33
+
34
+ def as_dict(self) -> dict[str, str]:
35
+ return {
36
+ "rule": self.rule,
37
+ "message": self.message,
38
+ "path": self.path,
39
+ "location": self.location,
40
+ }
41
+
42
+
43
+ @dataclass
44
+ class Report:
45
+ """The outcome of a validation or a build."""
46
+
47
+ failures: list[Failure] = field(default_factory=list)
48
+ skipped_rules: list[str] = field(default_factory=list)
49
+ """Rules that could not run. Never silent: a build says what it did not check."""
50
+
51
+ @property
52
+ def ok(self) -> bool:
53
+ return not self.failures
54
+
55
+ def fail(self, rule: str, message: str, path: str = "", location: str = "") -> None:
56
+ self.failures.append(Failure(rule, message, path, location))
57
+
58
+ def extend(self, other: Report) -> None:
59
+ self.failures.extend(other.failures)
60
+ self.skipped_rules.extend(other.skipped_rules)
61
+
62
+
63
+ class ContractError(Exception):
64
+ """A document cannot be read or placed against a contract at all.
65
+
66
+ Distinct from a `Failure`: a failure is a rule a document breaks, reported
67
+ alongside every other one. This is the case where there is nothing to report
68
+ on — an unparseable file, a missing schema, a document of no known kind.
69
+ """
@@ -0,0 +1,103 @@
1
+ """The `{{ … }}` grammar a workflow document may use.
2
+
3
+ The runner evaluates these and the builder must refuse the ones it cannot. Those two
4
+ answers have to be the same answer, or a bundle validates, signs, deploys, and then
5
+ dies on the first run that reaches the step — which is exactly what happened to
6
+ `schedule_mail`'s effect branches: `not a and b` is not in this grammar, and `a == 'x'
7
+ or b == 'y'` parsed as a comparison against the *literal* `"x' or b == 'y"`, so the
8
+ step silently never ran.
9
+
10
+ So the grammar lives here, beside the canonical form and the gate vocabulary, and
11
+ neither side owns it:
12
+
13
+ * **path** — `inputs.a.b`, `steps.<id>.<result_path>…`, `run.id`
14
+ * **comparison against a literal** — `<path> == 'routine'`, `!=`
15
+
16
+ No boolean operators, no arithmetic, no calls. A workflow that can compute is a
17
+ workflow that can compute its way around the control-flow guard (ADR 0005); anything
18
+ that genuinely needs computing belongs in a `code` step. Combining conditions is done
19
+ with nesting — an `if:` on a branch and a `when:` on its case.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import re
25
+
26
+ from .gates import scalar
27
+
28
+ TEMPLATE = re.compile(r"\{\{(.*?)\}\}", re.DOTALL)
29
+ COMPARISON = re.compile(r"^(?P<left>[\w.]+)\s*(?P<op>==|!=)\s*(?P<right>.+)$")
30
+ PATH = re.compile(r"[\w.]+")
31
+ #: `secrets` is accepted as a root here because `requires.secrets` and the
32
+ #: `undeclared-secret` rule treat `{{ secrets.x }}` as a legitimate document form.
33
+ #: The interpreter's own scope holds the other three.
34
+ ROOTS = ("inputs", "steps", "run", "secrets")
35
+
36
+ _REFUSED = object()
37
+
38
+ #: Words that read as operators but are not in the grammar. Named so the refusal can
39
+ #: say what to do instead rather than only that the expression is wrong.
40
+ _OPERATORS = ("not", "and", "or")
41
+
42
+
43
+ def refusal(expression: str) -> str | None:
44
+ """Why this expression cannot be evaluated, or ``None`` when it can.
45
+
46
+ The literal check matters as much as the shape: an unquoted or half-quoted
47
+ right-hand side is the failure that does not raise, it just compares false forever.
48
+ """
49
+ text = expression.strip()
50
+ if not text:
51
+ return "an empty expression reads nothing"
52
+
53
+ comparison = COMPARISON.match(text)
54
+ if comparison:
55
+ right = comparison.group("right").strip()
56
+ if _literal_refused(right):
57
+ return (
58
+ f"{right!r} is not a literal. The right-hand side of a comparison is a "
59
+ "quoted string, a number, true, false or null — never another "
60
+ "expression. Note that a value like \"'a' or x == 'b'\" is read as one "
61
+ "quoted string and compares false forever, in silence"
62
+ )
63
+ return _root_refusal(comparison.group("left"))
64
+
65
+ if not PATH.fullmatch(text):
66
+ for word in _OPERATORS:
67
+ if re.search(rf"\b{word}\b", text):
68
+ return (
69
+ f"{text!r} uses {word!r}, which this language does not have. An "
70
+ "expression is a path or a path compared against a literal; combine "
71
+ "conditions by nesting (`if:` on a branch, `when:` on its case) or "
72
+ "decide in a `code` step"
73
+ )
74
+ return (
75
+ f"{text!r} is not an expression this language has. A workflow may read a "
76
+ "path or compare one against a literal; anything more belongs in a code step"
77
+ )
78
+
79
+ return _root_refusal(text)
80
+
81
+
82
+ def _root_refusal(path: str) -> str | None:
83
+ root = path.split(".")[0]
84
+ if root not in ROOTS:
85
+ return f"unknown root {root!r} in {path!r}; an expression may read {', '.join(ROOTS)}"
86
+ return None
87
+
88
+
89
+ def _literal_refused(text: str) -> bool:
90
+ if len(text) >= 2 and text[0] == text[-1] and text[0] in "'\"":
91
+ # The delimiter must not reappear inside, or `'a' or x == 'b'` reads as the
92
+ # single string `a' or x == 'b` — which the evaluator accepts and compares
93
+ # false forever. That silence is the failure this rule exists to catch.
94
+ return text[0] in text[1:-1]
95
+ return scalar(text, default=_REFUSED) is _REFUSED
96
+
97
+
98
+ def expressions_in(text: str) -> list[str]:
99
+ """Every `{{ … }}` body in a string, in order."""
100
+ return [match.group(1) for match in TEMPLATE.finditer(text)]
101
+
102
+
103
+ __all__ = ["COMPARISON", "PATH", "ROOTS", "TEMPLATE", "expressions_in", "refusal"]
mkp_contracts/gates.py ADDED
@@ -0,0 +1,243 @@
1
+ """What a machine's gate may name, and therefore what a bundle may be built with.
2
+
3
+ A gate in a `.mkl` can carry `hook: <name>`, and mklang resolves that name against a
4
+ registry the host supplies — builtins, entry-point plugins, and whatever the host passes
5
+ as `extra`. That registry is where a tenant's Python would go, and ADR 0003 says it must
6
+ not:
7
+
8
+ > mklang steps run in the runner process — **there is no customer code in a `.mkl`, only
9
+ > data** — but get an ephemeral filesystem workspace per run.
10
+
11
+ That clause is the *reason* a machine runs in the runner process at all rather than in a
12
+ container like a code step. A bundle that carried Python for its gates would take the
13
+ reason away. And a gate is not business logic in the first place: it is where a judgement
14
+ is checked before it is allowed to matter, which ADR 0005 puts on the platform's side of
15
+ the line — the machinery a tenant cannot switch off.
16
+
17
+ So the vocabulary is closed, declarative, and defined here rather than in either component
18
+ that needs it. The builder refuses a bundle whose machine names something outside it; the
19
+ runner compiles what is inside it into predicates. Two definitions would mean a bundle that
20
+ builds and then halts at its first gate, which is the failure `mkbundle` exists to prevent
21
+ — mklang resolves an unknown hook to nothing and **halts when the gate is reached**.
22
+
23
+ ## The forms
24
+
25
+ mkp:eq:<path>:<literal> the value at <path> equals the literal
26
+ mkp:neq:<path>:<literal> it does not
27
+ mkp:has:<path>[,<path>…] every path is present and non-empty
28
+ mkp:in:<path>:<path> the first value is a member of the second, a list
29
+
30
+ Namespaced `mkp:` because that prefix is what the platform owns (`README.md`, "Naming"),
31
+ and because mklang has parametric forms of its own — `eq:` and `neq:` over a context key —
32
+ that a machine may keep using. Those two, plus `always_true` and `always_false`, are the
33
+ only names from mklang a bundle may gate on: the rest of that project's builtins are its
34
+ examples (`amount_le_100`, `has_receipt`), and a signed bundle should not depend on whether
35
+ somebody's example is installed next to the runner.
36
+
37
+ ## The paths
38
+
39
+ Rooted, like the workflow expression language beside it (`expressions.py`, whose roots are
40
+ `inputs`, `steps` and `run`):
41
+
42
+ output the value the state just produced, whole — a string, or a document
43
+ output.a.b a field of it, when it is a document
44
+ context.free_slots a machine context key
45
+ context.slots[].start `[]` maps over a list: the `start` of each element
46
+
47
+ `[]` is the one addition to a dotted path and it exists for a shape vendors actually
48
+ return: a list of objects, where the gate is about one field of each. It maps, it does not
49
+ filter or aggregate.
50
+
51
+ Deliberately absent: arithmetic, boolean combination, membership in a literal set, reading
52
+ a second state's output, and any form of call. The rule is the expression language's own —
53
+ whatever this accepts becomes something a bundle author can make the platform do — and the
54
+ consequence is stated rather than implied: **a gate that needs computing is a workflow that
55
+ needs a `code` step**, where computing is visible as what it is and runs in a sandbox.
56
+ """
57
+
58
+ from __future__ import annotations
59
+
60
+ import re
61
+ from dataclasses import dataclass
62
+ from typing import Any
63
+
64
+ NAMESPACE = "mkp"
65
+
66
+ # mklang's own, and the only ones from it a bundle may name. `eq:`/`neq:` are parametric
67
+ # over a *context* key; the rest of mklang's builtins are that project's examples.
68
+ MKLANG_NAMED = frozenset({"always_true", "always_false"})
69
+ MKLANG_PARAMETRIC = ("eq:", "neq:")
70
+
71
+ ROOTS = frozenset({"output", "context"})
72
+
73
+ KINDS = frozenset({"eq", "neq", "has", "in"})
74
+
75
+ # A path segment: a name, or `[]` meaning "each element of the list here".
76
+ SEGMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\[\])?$")
77
+
78
+ VOCABULARY = (
79
+ "mkp:eq:<path>:<literal>, mkp:neq:<path>:<literal>, mkp:has:<path>[,<path>...], "
80
+ "mkp:in:<path>:<path>, eq:<key>:<value>, neq:<key>:<value>, always_true, always_false"
81
+ )
82
+
83
+
84
+ class GateError(ValueError):
85
+ """The name is in the platform's namespace and is not one of its forms.
86
+
87
+ Distinct from a name outside the namespace, which may be mklang's and is not this
88
+ module's to judge — see `resolvable`.
89
+ """
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class Gate:
94
+ """A parsed platform gate. Data, so both the builder and the runner read one name the
95
+ same way: the builder to accept it, the runner to answer it."""
96
+
97
+ kind: str
98
+ paths: tuple[str, ...]
99
+ literal: str | None = None
100
+
101
+
102
+ def parse(name: str) -> Gate:
103
+ """Parse a `mkp:` gate name, or raise `GateError` saying what the vocabulary is.
104
+
105
+ Only for names in the platform's namespace. `resolvable` is the question a builder
106
+ asks about *any* hook name; this is the answer for the ones that are ours.
107
+ """
108
+ if not name.startswith(f"{NAMESPACE}:"):
109
+ raise GateError(f"{name!r} is not a {NAMESPACE}: gate name")
110
+
111
+ # Split at most four ways so a literal keeps its own colons: a time of "10:30" is a
112
+ # value, not a separator, and a vocabulary that could not express one would be a
113
+ # vocabulary nobody could gate a calendar on.
114
+ parts = name.split(":", 3)
115
+ kind = parts[1] if len(parts) > 1 else ""
116
+ if kind not in KINDS:
117
+ raise GateError(
118
+ f"{name!r} names no gate this platform has: {kind!r} is not one of "
119
+ f"{', '.join(sorted(KINDS))}. The vocabulary is {VOCABULARY}"
120
+ )
121
+
122
+ if kind in ("eq", "neq"):
123
+ if len(parts) != 4 or not parts[2]:
124
+ raise GateError(f"{name!r}: {NAMESPACE}:{kind} takes a path and a literal")
125
+ return Gate(kind=kind, paths=(_path(parts[2], name),), literal=parts[3])
126
+
127
+ if kind == "has":
128
+ if len(parts) != 3 or not parts[2]:
129
+ raise GateError(f"{name!r}: {NAMESPACE}:has takes one or more comma-separated paths")
130
+ paths = tuple(_path(part, name) for part in parts[2].split(",") if part)
131
+ if not paths:
132
+ raise GateError(f"{name!r}: {NAMESPACE}:has takes one or more comma-separated paths")
133
+ return Gate(kind=kind, paths=paths)
134
+
135
+ if len(parts) != 4 or not parts[2] or not parts[3]:
136
+ raise GateError(
137
+ f"{name!r}: {NAMESPACE}:in takes two paths — a value, and the list it must be in"
138
+ )
139
+ return Gate(kind=kind, paths=(_path(parts[2], name), _path(parts[3], name)))
140
+
141
+
142
+ def resolvable(name: str | None) -> bool:
143
+ """Whether a runner will be able to answer this gate.
144
+
145
+ The question a builder asks. `None` is a gate with no hook, which is judged by the
146
+ model and is not this module's business.
147
+ """
148
+ if not name:
149
+ return True
150
+ if name in MKLANG_NAMED or name.startswith(MKLANG_PARAMETRIC):
151
+ return True
152
+ if not name.startswith(f"{NAMESPACE}:"):
153
+ return False
154
+ try:
155
+ parse(name)
156
+ except GateError:
157
+ return False
158
+ return True
159
+
160
+
161
+ def reason(name: str) -> str:
162
+ """Why a name is not resolvable, for a message a bundle author can act on."""
163
+ if name.startswith(f"{NAMESPACE}:"):
164
+ try:
165
+ parse(name)
166
+ except GateError as exc:
167
+ return str(exc)
168
+ return ""
169
+ return (
170
+ f"hook {name!r} is not a gate this platform can resolve. A gate is data, not code "
171
+ f"(ADR 0003), so a machine may name: {VOCABULARY}"
172
+ )
173
+
174
+
175
+ def _path(text: str, name: str) -> str:
176
+ segments = text.split(".")
177
+ if segments[0] not in ROOTS:
178
+ raise GateError(
179
+ f"{name!r}: a gate path starts at {' or '.join(sorted(ROOTS))}, not {segments[0]!r}"
180
+ )
181
+ for segment in segments[1:]:
182
+ if not SEGMENT.match(segment):
183
+ raise GateError(
184
+ f"{name!r}: {segment!r} is not a path segment. A segment is a name, "
185
+ "optionally followed by `[]` to map over a list"
186
+ )
187
+ return text
188
+
189
+
190
+ _UNSET = object()
191
+
192
+
193
+ def scalar(text: str, *, default: Any = _UNSET) -> Any:
194
+ """`true`, `false`, `null` and numbers as themselves; anything else per `default`.
195
+
196
+ The half that two readers of the same syntax must agree on: a gate's right-hand side
197
+ here, and a workflow comparison's in the runner's expression language. They differ at
198
+ the edges only — the runner accepts quoted strings and refuses a bare word, a gate
199
+ takes a bare word as text — and those edges are the callers' to state. What "42" and
200
+ "true" mean is not, and it lived in two places until 2026-08-04.
201
+
202
+ With no `default`, an unrecognised value comes back as its own text.
203
+ """
204
+ lowered = text.lower()
205
+ if lowered in ("true", "false"):
206
+ return lowered == "true"
207
+ if lowered in ("null", "none"):
208
+ return None
209
+ try:
210
+ return int(text)
211
+ except ValueError:
212
+ pass
213
+ try:
214
+ return float(text)
215
+ except ValueError:
216
+ return text if default is _UNSET else default
217
+
218
+
219
+ def literal(text: str) -> Any:
220
+ """A gate's right-hand side, read the way the expression language reads one.
221
+
222
+ Unquoted, because a hook name is already a string inside a YAML document and a second
223
+ layer of quoting is a layer to get wrong. `true`, `false`, `null` and numbers are
224
+ themselves; everything else is text.
225
+ """
226
+ return scalar(text)
227
+
228
+
229
+ __all__ = [
230
+ "KINDS",
231
+ "MKLANG_NAMED",
232
+ "MKLANG_PARAMETRIC",
233
+ "NAMESPACE",
234
+ "ROOTS",
235
+ "VOCABULARY",
236
+ "Gate",
237
+ "GateError",
238
+ "literal",
239
+ "parse",
240
+ "reason",
241
+ "resolvable",
242
+ "scalar",
243
+ ]
mkp_contracts/py.typed ADDED
File without changes
mkp_contracts/roles.py ADDED
@@ -0,0 +1,35 @@
1
+ """The role names, which cross every boundary this platform has.
2
+
3
+ Here for the same reason `cli_versions` is here: the set of roles is not the control
4
+ plane's private business. `mkctl` names them in its help, the operator console decides
5
+ what to render from them, the glossary fixes them as vocabulary, and the API authorizes
6
+ against them. Four copies is what the repository had, and the fourth was wrong — `mkctl`
7
+ offered `developer`, which has never existed, while citing the ADR that lists the real
8
+ four. A help string is read *before* the API refuses, so the wrong name cost a round trip
9
+ and left the right one unsaid.
10
+
11
+ What is **not** here is `ROLE_ACTIONS`: which actions each role holds is policy, it is
12
+ answered in one table in `services/api/src/control_plane/authz.py`, and nothing outside
13
+ the control plane may have an opinion about it. This module owns the names and their
14
+ order — the smallest thing that has to agree everywhere.
15
+
16
+ `platform_admin` is deliberately absent. It is not a role a tenant can grant (ADR 0004
17
+ Amendment 3): it lives in its own table, is read by a different function, and putting it
18
+ in a list called ROLES is how it would eventually be offered in a grant menu.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ OWNER = "owner"
24
+ MAINTAINER = "maintainer"
25
+ OPERATOR = "operator"
26
+ VIEWER = "viewer"
27
+
28
+ # Ordered from most to least: it is the order a person expects in a help string and in a
29
+ # menu, and an arbitrary one would be re-sorted differently by each consumer.
30
+ ROLES: tuple[str, ...] = (OWNER, MAINTAINER, OPERATOR, VIEWER)
31
+
32
+
33
+ def is_role(name: str) -> bool:
34
+ """Whether `name` is one of the four a tenant can grant."""
35
+ return name in ROLES
@@ -0,0 +1,82 @@
1
+ """Schema loading, document-kind detection, and shape validation.
2
+
3
+ The schemas are the shape; `rules.py` holds the rules. A document that validates
4
+ here is well-formed, not necessarily deployable (`schema/README.md`).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import yaml
14
+ from jsonschema import Draft202012Validator
15
+
16
+ from .errors import ContractError, Report
17
+
18
+ KINDS = ("workflow", "connector", "bundle")
19
+
20
+ _SCHEMA_FILES = {
21
+ "workflow": "workflow.schema.json",
22
+ "connector": "connector.schema.json",
23
+ "bundle": "bundle.schema.json",
24
+ }
25
+
26
+
27
+ def schema_dir() -> Path:
28
+ """Locate `schema/` by walking up from this file, then from the cwd.
29
+
30
+ The tool lives in the same repository as the contracts it enforces, so it
31
+ finds them rather than carrying a copy that can drift.
32
+ """
33
+ for start in (Path(__file__).resolve(), Path.cwd().resolve() / "_"):
34
+ for parent in start.parents:
35
+ candidate = parent / "schema"
36
+ if (candidate / "bundle.schema.json").is_file():
37
+ return candidate
38
+ raise ContractError(
39
+ "cannot find the schema/ directory — run mkp from inside the mklang-platform repository"
40
+ )
41
+
42
+
43
+ def load_schema(kind: str) -> dict[str, Any]:
44
+ if kind not in _SCHEMA_FILES:
45
+ raise ContractError(f"unknown document kind {kind!r}; expected one of {', '.join(KINDS)}")
46
+ return json.loads((schema_dir() / _SCHEMA_FILES[kind]).read_text())
47
+
48
+
49
+ def load_document(path: Path) -> Any:
50
+ """Parse YAML or JSON. Both are validated after parsing, as mklang does for `.mkl`."""
51
+ text = path.read_text()
52
+ try:
53
+ return yaml.safe_load(text)
54
+ except yaml.YAMLError as exc:
55
+ raise ContractError(f"{path}: not parseable as YAML or JSON: {exc}") from exc
56
+
57
+
58
+ def detect_kind(document: Any) -> str | None:
59
+ """Infer the kind from the document's own shape.
60
+
61
+ Deliberately structural: the three contracts have disjoint required fields,
62
+ so a document does not need to announce what it is.
63
+ """
64
+ if not isinstance(document, dict):
65
+ return None
66
+ if "actions" in document and "auth" in document:
67
+ return "connector"
68
+ if "contents" in document and "lock" in document:
69
+ return "bundle"
70
+ if "steps" in document:
71
+ return "workflow"
72
+ return None
73
+
74
+
75
+ def validate_document(document: Any, kind: str, path: str = "") -> Report:
76
+ """Validate one document against its schema, reporting every violation."""
77
+ report = Report()
78
+ validator = Draft202012Validator(load_schema(kind))
79
+ for error in sorted(validator.iter_errors(document), key=lambda e: list(e.absolute_path)):
80
+ location = ".".join(str(part) for part in error.absolute_path)
81
+ report.fail("schema", error.message, path=path, location=location)
82
+ return report
@@ -0,0 +1,120 @@
1
+ """Verifying a bundle's signature. Signing stays with the builder.
2
+
3
+ The split is not symmetric and should not be: **signing is a build-time act and
4
+ verifying is a runtime one.** The builder signs and also verifies its own output;
5
+ the runner verifies at load and must never sign anything. Putting verification here
6
+ lets the runner do its half without depending on a build tool — the same argument
7
+ that moved `canonical.py` and `archive.py` out of `mkbundle`.
8
+
9
+ What is verified is exactly the canonical manifest bytes, which are also the bytes the
10
+ digest is taken over. One canonical form and not two, which is why signing a bundle
11
+ does not move its identity.
12
+
13
+ `signature.key_id` is minisign's 8-byte key id, not the public key. A verifier looks
14
+ that id up in a trust store it already holds. Taking the key from the artifact it is
15
+ meant to authenticate would verify only that the artifact signed itself.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import base64
21
+ import re
22
+ import shutil
23
+ import subprocess
24
+ import tempfile
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ from .errors import ContractError, Report
29
+
30
+ ALGORITHM = "minisign"
31
+ CANONICAL_NAME = "manifest.canonical"
32
+
33
+ # minisign prints the key id as a hexadecimal number, so it drops leading zeros: about
34
+ # one key in sixteen is written with fewer than sixteen digits. Requiring sixteen made
35
+ # `key_id` raise on those, which meant a build key that could not sign and a trust key a
36
+ # runner crashed on rather than refused with — both invisible until the wrong key was
37
+ # generated. Read one to sixteen digits and pad, so what is stored is always canonical.
38
+ _KEY_ID_RE = re.compile(r"minisign public key:?\s*([0-9A-Fa-f]{1,16})\b")
39
+
40
+
41
+ def available() -> bool:
42
+ return shutil.which(ALGORITHM) is not None
43
+
44
+
45
+ def require() -> None:
46
+ if not available():
47
+ raise ContractError("minisign is not on PATH; a bundle cannot be signed or verified")
48
+
49
+
50
+ def key_id(public_key: Path) -> str:
51
+ """minisign's key id, read from the public key file's comment, always 16 digits."""
52
+ match = _KEY_ID_RE.search(public_key.read_text())
53
+ if not match:
54
+ raise ContractError(f"{public_key}: cannot read a minisign key id out of this file")
55
+ return match.group(1).upper().rjust(16, "0")
56
+
57
+
58
+ def verify(canonical: bytes, signature: dict[str, Any], public_key: Path) -> Report:
59
+ """Check a manifest's signature against a public key held out of band."""
60
+ report = Report()
61
+ require()
62
+
63
+ algorithm = signature.get("algorithm")
64
+ if algorithm != ALGORITHM:
65
+ report.fail(
66
+ "signature-algorithm",
67
+ f"cannot verify {algorithm!r} signatures; this verifies {ALGORITHM}",
68
+ )
69
+ return report
70
+
71
+ expected = key_id(public_key)
72
+ # Padded on both sides: a bundle signed before the padding fix carries the short
73
+ # form, and rejecting it would be this fix inventing a signature failure.
74
+ if signature.get("key_id", "").upper().rjust(16, "0") != expected:
75
+ report.fail(
76
+ "signature-key",
77
+ f"signed by key {signature.get('key_id')!r}, but the key offered is {expected}",
78
+ )
79
+ return report
80
+
81
+ try:
82
+ payload = base64.b64decode(signature["value"], validate=True)
83
+ except (KeyError, ValueError) as exc:
84
+ report.fail("signature-malformed", f"signature.value is not base64: {exc}")
85
+ return report
86
+
87
+ with tempfile.TemporaryDirectory() as workspace:
88
+ target = Path(workspace) / CANONICAL_NAME
89
+ target.write_bytes(canonical)
90
+ signature_path = target.with_suffix(".minisig")
91
+ signature_path.write_bytes(payload)
92
+
93
+ # A fixed argv list and no shell: everything interpolated is a path this
94
+ # process just wrote into a temporary directory of its own.
95
+ completed = subprocess.run(
96
+ [
97
+ ALGORITHM,
98
+ "-V",
99
+ "-p",
100
+ str(public_key),
101
+ "-m",
102
+ str(target),
103
+ "-x",
104
+ str(signature_path),
105
+ "-q",
106
+ ],
107
+ capture_output=True,
108
+ text=True,
109
+ )
110
+
111
+ if completed.returncode != 0:
112
+ report.fail(
113
+ "signature-invalid",
114
+ "the signature does not verify against this key and these manifest bytes: "
115
+ f"{completed.stderr.strip() or completed.stdout.strip()}",
116
+ )
117
+ return report
118
+
119
+
120
+ __all__ = ["ALGORITHM", "CANONICAL_NAME", "available", "key_id", "require", "verify"]
@@ -0,0 +1,9 @@
1
+ Metadata-Version: 2.4
2
+ Name: mkp-contracts
3
+ Version: 0.2.0
4
+ Summary: The cross-boundary contracts as code: canonical form, digests, schema validation
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Python: <3.14,>=3.11
8
+ Requires-Dist: jsonschema>=4.21
9
+ Requires-Dist: pyyaml>=6.0
@@ -0,0 +1,15 @@
1
+ mkp_contracts/__init__.py,sha256=ksri1hSCLJ4bN-MRWI0w8JUmwO_DX80t-_bxVs7FeV4,523
2
+ mkp_contracts/archive.py,sha256=3WSxY7cjyFqKJudzxkdsC2NAw76YaCTBW-dRHgtLg3k,2627
3
+ mkp_contracts/canonical.py,sha256=csgkd6bUp8CO6EEtJoovNBzcP3dU121HcOnmq5zNwag,1555
4
+ mkp_contracts/cli_versions.py,sha256=V_oHHyOkrJxOVEJeFc6VumoHMBd6Od08fm8LoBb8sNw,1425
5
+ mkp_contracts/errors.py,sha256=bpVs4r4uOQv7QxH_Cr6z1VdAQo-ICz5PKMvhUjOwStU,2137
6
+ mkp_contracts/expressions.py,sha256=uquTYlP2n0emKkw2cMKPDnLGgxqOtHNp_0RXKjBAt8s,4353
7
+ mkp_contracts/gates.py,sha256=1EcNJUbnqxKJZXSw6QaUmmxHC28W15BifAdpG1hbntY,9506
8
+ mkp_contracts/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ mkp_contracts/roles.py,sha256=FP1ws1QpddtLGvnI8rOW61AJAWuL7MVZs5XJ_Jo6IIg,1677
10
+ mkp_contracts/schemas.py,sha256=7zMJOqBtoMZPyFjvKcW7xI1JxgEKN34OsJkUFTXcJXw,2829
11
+ mkp_contracts/signature.py,sha256=QqW9tPGmq0RPVZg8-avUhDHCxuCsXTZvO9bkKiARbe8,4483
12
+ mkp_contracts-0.2.0.dist-info/METADATA,sha256=iQXNkHyJksnSIpQ7v-fAiWxASjoPzBUM6nrPwgDd430,289
13
+ mkp_contracts-0.2.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
14
+ mkp_contracts-0.2.0.dist-info/licenses/LICENSE,sha256=OomESGL67ZXotKqNbTv84ga2xAp3zho0QQH_kjVDTxQ,11338
15
+ mkp_contracts-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Gianluca
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.