codapact 0.1.0__tar.gz → 0.1.1__tar.gz

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.
Files changed (68) hide show
  1. codapact-0.1.1/.github/workflows/codeql.yml +35 -0
  2. {codapact-0.1.0 → codapact-0.1.1}/.github/workflows/mutation.yml +2 -2
  3. codapact-0.1.1/.release-please-manifest.json +1 -0
  4. codapact-0.1.1/CHANGELOG.md +32 -0
  5. {codapact-0.1.0 → codapact-0.1.1}/PKG-INFO +2 -1
  6. {codapact-0.1.0 → codapact-0.1.1}/README.md +1 -0
  7. {codapact-0.1.0 → codapact-0.1.1}/docs/architecture.md +8 -0
  8. {codapact-0.1.0 → codapact-0.1.1}/docs/mutation.md +37 -2
  9. codapact-0.1.1/docs/security.md +35 -0
  10. {codapact-0.1.0 → codapact-0.1.1}/docs/support.md +11 -0
  11. {codapact-0.1.0 → codapact-0.1.1}/pyproject.toml +1 -1
  12. {codapact-0.1.0 → codapact-0.1.1}/pyproject.toml.orig +1 -1
  13. {codapact-0.1.0 → codapact-0.1.1}/scripts/mutation_alerts.py +38 -4
  14. codapact-0.1.1/src/codapact/__init__.py +3 -0
  15. codapact-0.1.1/src/codapact/auth.py +68 -0
  16. {codapact-0.1.0 → codapact-0.1.1}/src/codapact/cli.py +6 -6
  17. {codapact-0.1.0 → codapact-0.1.1}/src/codapact/loading.py +14 -0
  18. {codapact-0.1.0 → codapact-0.1.1}/src/codapact/model.py +7 -2
  19. {codapact-0.1.0 → codapact-0.1.1}/src/codapact/net.py +10 -4
  20. {codapact-0.1.0 → codapact-0.1.1}/src/codapact/openapi.py +1 -1
  21. {codapact-0.1.0 → codapact-0.1.1}/src/codapact/profiles.py +6 -2
  22. {codapact-0.1.0 → codapact-0.1.1}/src/codapact/project.py +23 -14
  23. {codapact-0.1.0 → codapact-0.1.1}/src/codapact/runtime.py +21 -123
  24. codapact-0.1.1/src/codapact/validation.py +67 -0
  25. {codapact-0.1.0 → codapact-0.1.1}/tests/conftest.py +12 -6
  26. {codapact-0.1.0 → codapact-0.1.1}/tests/test_entrypoint.py +16 -0
  27. codapact-0.1.1/tests/test_generated_contracts.py +605 -0
  28. {codapact-0.1.0 → codapact-0.1.1}/tests/test_generation.py +8 -0
  29. {codapact-0.1.0 → codapact-0.1.1}/tests/test_loading.py +46 -0
  30. {codapact-0.1.0 → codapact-0.1.1}/tests/test_mutation_alerts.py +86 -0
  31. codapact-0.1.1/tests/test_mutation_contracts.py +1217 -0
  32. codapact-0.1.1/tests/test_net.py +271 -0
  33. codapact-0.1.1/tests/test_reference_text_budget.py +21 -0
  34. {codapact-0.1.0 → codapact-0.1.1}/uv.lock +1 -1
  35. codapact-0.1.0/.release-please-manifest.json +0 -1
  36. codapact-0.1.0/CHANGELOG.md +0 -14
  37. codapact-0.1.0/src/codapact/__init__.py +0 -3
  38. codapact-0.1.0/tests/test_net.py +0 -100
  39. {codapact-0.1.0 → codapact-0.1.1}/.github/workflows/ci.yml +0 -0
  40. {codapact-0.1.0 → codapact-0.1.1}/.github/workflows/mutation-alerts.yml +0 -0
  41. {codapact-0.1.0 → codapact-0.1.1}/.github/workflows/release.yml +0 -0
  42. {codapact-0.1.0 → codapact-0.1.1}/LICENSE +0 -0
  43. {codapact-0.1.0 → codapact-0.1.1}/branding/mark.svg +0 -0
  44. {codapact-0.1.0 → codapact-0.1.1}/branding/wordmark.svg +0 -0
  45. {codapact-0.1.0 → codapact-0.1.1}/docs/branding.md +0 -0
  46. {codapact-0.1.0 → codapact-0.1.1}/docs/configuration.md +0 -0
  47. {codapact-0.1.0 → codapact-0.1.1}/docs/releasing.md +0 -0
  48. {codapact-0.1.0 → codapact-0.1.1}/docs/verification.md +0 -0
  49. {codapact-0.1.0 → codapact-0.1.1}/examples/cli.json +0 -0
  50. {codapact-0.1.0 → codapact-0.1.1}/examples/pets.codapact.yaml +0 -0
  51. {codapact-0.1.0 → codapact-0.1.1}/examples/pets.yaml +0 -0
  52. {codapact-0.1.0 → codapact-0.1.1}/examples/runtime.json +0 -0
  53. {codapact-0.1.0 → codapact-0.1.1}/release-please-config.json +0 -0
  54. {codapact-0.1.0 → codapact-0.1.1}/schemas/cli.v1.schema.json +0 -0
  55. {codapact-0.1.0 → codapact-0.1.1}/scripts/mutation_report.py +0 -0
  56. {codapact-0.1.0 → codapact-0.1.1}/scripts/verify_dist.py +0 -0
  57. {codapact-0.1.0 → codapact-0.1.1}/src/codapact/__main__.py +0 -0
  58. {codapact-0.1.0 → codapact-0.1.1}/src/codapact/configuration.py +0 -0
  59. {codapact-0.1.0 → codapact-0.1.1}/src/codapact/errors.py +0 -0
  60. {codapact-0.1.0 → codapact-0.1.1}/src/codapact/generation.py +0 -0
  61. {codapact-0.1.0 → codapact-0.1.1}/src/codapact/py.typed +0 -0
  62. {codapact-0.1.0 → codapact-0.1.1}/src/codapact/schemas/generation.v1.json +0 -0
  63. {codapact-0.1.0 → codapact-0.1.1}/src/codapact/values.py +0 -0
  64. {codapact-0.1.0 → codapact-0.1.1}/tests/test_adversarial.py +0 -0
  65. {codapact-0.1.0 → codapact-0.1.1}/tests/test_configuration.py +0 -0
  66. {codapact-0.1.0 → codapact-0.1.1}/tests/test_distribution.py +0 -0
  67. {codapact-0.1.0 → codapact-0.1.1}/tests/test_openapi.py +0 -0
  68. {codapact-0.1.0 → codapact-0.1.1}/tests/test_runtime.py +0 -0
@@ -0,0 +1,35 @@
1
+ name: CodeQL
2
+ on:
3
+ pull_request:
4
+ push:
5
+ branches: [main]
6
+ schedule:
7
+ - cron: '23 6 * * 1'
8
+ workflow_dispatch:
9
+ permissions:
10
+ contents: read
11
+ concurrency:
12
+ group: codeql-${{ github.event.pull_request.number || github.ref }}
13
+ cancel-in-progress: true
14
+ jobs:
15
+ analyze:
16
+ name: Analyze (${{ matrix.language }})
17
+ runs-on: ubuntu-latest
18
+ permissions:
19
+ contents: read
20
+ security-events: write
21
+ strategy:
22
+ fail-fast: false
23
+ matrix:
24
+ language: [python, actions]
25
+ steps:
26
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
27
+ with:
28
+ persist-credentials: false
29
+ - uses: github/codeql-action/init@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2
30
+ with:
31
+ languages: ${{ matrix.language }}
32
+ queries: security-and-quality
33
+ - uses: github/codeql-action/analyze@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2
34
+ with:
35
+ category: /language:${{ matrix.language }}
@@ -20,7 +20,7 @@ jobs:
20
20
  needs: validate-ref
21
21
  if: github.ref == 'refs/heads/main'
22
22
  runs-on: ubuntu-latest
23
- timeout-minutes: 25
23
+ timeout-minutes: 40
24
24
  steps:
25
25
  - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
26
26
  with:
@@ -34,7 +34,7 @@ jobs:
34
34
  run: |
35
35
  mkdir -p mutation-report
36
36
  set +e
37
- timeout --signal=TERM --kill-after=10s 18m uv run --group mutation mutmut run --max-children 2 > mutation-report/run.log 2>&1
37
+ timeout --signal=TERM --kill-after=10s 30m uv run --group mutation mutmut run --max-children 2 > mutation-report/run.log 2>&1
38
38
  code=$?
39
39
  uv run --group mutation mutmut export-cicd-stats >> mutation-report/run.log 2>&1
40
40
  uv run --group mutation mutmut results --all true > mutation-report/results.txt 2>&1
@@ -0,0 +1 @@
1
+ {".":"0.1.1"}
@@ -0,0 +1,32 @@
1
+ # Changelog
2
+
3
+ <!-- markdownlint-configure-file { "MD024": { "siblings_only": true } } -->
4
+
5
+ ## [0.1.1](https://github.com/mikejhill/codapact/compare/v0.1.0...v0.1.1) (2026-10-29)
6
+
7
+ ### Bug Fixes
8
+
9
+ * Reject whitespace and DEL in literal OpenAPI operation paths during translation.
10
+ * Validate and bound ownership manifests before regeneration writes, including malformed roots,
11
+ non-integer versions, and oversized inventories.
12
+ * Honor explicit base URL, timeout, and private-network flags in wrappers without discovery profiles;
13
+ preserve configured values when flags are omitted.
14
+ * Reject all ASCII control characters and DEL in parameter and custom-auth request headers before
15
+ transport, with redacted diagnostics.
16
+
17
+ * Bound expanded reference text, counting repeated large string keys and values before serialization.
18
+
19
+ The first four fixes are included in [3e21fd7](https://github.com/mikejhill/codapact/commit/3e21fd7b42dc370e27bfa7617c6ed9174d2cb284).
20
+
21
+ ## 0.1.0 (2026-10-29)
22
+
23
+ ### Features
24
+
25
+ * add generation manifests and XDG runtime profiles ([cd0e6a2](https://github.com/mikejhill/codapact/commit/cd0e6a20e813423d3b33ca5ba277a036c482dd8c))
26
+ * initialize codapact ([7daa7e2](https://github.com/mikejhill/codapact/commit/7daa7e2534bdd59bcd555dc90ec2e97a002f130c))
27
+
28
+ ### Bug Fixes
29
+
30
+ * document generated commands and release handoff ([9ea472c](https://github.com/mikejhill/codapact/commit/9ea472ca5e3cfe9fdf4bbc94bb22511d87eece22))
31
+ * harden contracts and add mutation alerts ([b4b1a06](https://github.com/mikejhill/codapact/commit/b4b1a06d2029a53fa68783f6ecd1c0dedb7854e2))
32
+ * reconcile asynchronous mutation alerts ([ba1737d](https://github.com/mikejhill/codapact/commit/ba1737d33f9e6157a7d9fe6f6c8b1d2878917dec))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codapact
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: Contracts into callable tools: pluggable API client and CLI generation.
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -53,6 +53,7 @@ guide for precedence, credential-file permissions, and every generation override
53
53
  - [Supported features and safety boundaries](docs/support.md)
54
54
  - [CLI definition and runtime configuration](docs/configuration.md)
55
55
  - [Release process](docs/releasing.md)
56
+ - [Security analysis](docs/security.md)
56
57
  - [Verification evidence and limits](docs/verification.md)
57
58
  - [Asynchronous mutation testing and open alerts](docs/mutation.md)
58
59
 
@@ -38,6 +38,7 @@ guide for precedence, credential-file permissions, and every generation override
38
38
  - [Supported features and safety boundaries](docs/support.md)
39
39
  - [CLI definition and runtime configuration](docs/configuration.md)
40
40
  - [Release process](docs/releasing.md)
41
+ - [Security analysis](docs/security.md)
41
42
  - [Verification evidence and limits](docs/verification.md)
42
43
  - [Asynchronous mutation testing and open alerts](docs/mutation.md)
43
44
 
@@ -72,3 +72,11 @@ the next run fails closed on mismatched ownership. Preserve edited files and
72
72
  generate into a new directory to recover. Concurrent generation into the same
73
73
  directory is unsupported. Local plugins and users able to race filesystem
74
74
  mutations are trusted; this is not an operating-system sandbox.
75
+
76
+ Authentication and policy contracts live in `auth.py`; data-only JSON/runtime
77
+ validation lives in `validation.py`. Neither depends on execution or filesystem
78
+ credential discovery. `profiles.py` composes these services without importing
79
+ `runtime.py`; the execution layer can therefore validate profiles without an
80
+ import cycle. Existing runtime imports of the auth/policy/validation services
81
+ remain available for compatibility. Protocol methods are explicit abstract
82
+ contracts; incomplete nominal implementations cannot silently satisfy them.
@@ -9,14 +9,17 @@ manual dispatch. It never runs as a PR check, is not part of `CI passed`, and is
9
9
  not a merge or release prerequisite. This is a retained project setup preference.
10
10
  Other formatting, lint, typing, test, coverage, and package checks remain gates.
11
11
 
12
- The Linux job runs mutmut with two workers and an eighteen-minute process budget.
12
+ The Linux job runs mutmut with two workers and a thirty-minute process budget.
13
13
  The normal suite includes fresh package installation; mutation selection omits
14
14
  that expensive distribution test while retaining the runtime/generation tests.
15
15
  Runs start clean; source, test, dependency, and configuration changes cannot reuse
16
16
  stale cached mutation verdicts. Evidence is retained as a thirty-day artifact.
17
17
  The artifact includes named mutant verdicts and an archive of generated source
18
18
  and metadata for inspection. Survivor details are retained even when the complete
19
- score passes. Missing required evidence is an execution failure, not a pass.
19
+ score passes. Missing required evidence is an execution failure, not a pass. The bounded
20
+ budget was increased after the manifest slice reached 3,845 mutants: an actual
21
+ eighteen-minute run completed only 3,271. Worker count remains two; the job has a
22
+ forty-minute outer limit so it can preserve evidence after a process timeout.
20
23
 
21
24
  ## Durable alerts
22
25
 
@@ -37,6 +40,11 @@ Each active class has one deduplicated issue assigned to `mikejhill`:
37
40
  timeouts, suspicious outcomes, skipped mutants, or crashed workers.
38
41
  Infrastructure means tool/baseline/setup failure, missing or malformed evidence.
39
42
  The subtype remains explicit in the report and issue. Neither subtype passes.
43
+ The producer workflow conclusion is checked even when
44
+ its artifact is valid: cancelled, timed-out, skipped, and unknown conclusions
45
+ override artifact claims as incomplete. A failed producer cannot establish a
46
+ passing recovery. A complete below-floor report is still valid regression
47
+ evidence when its producer fails because the score is below the floor.
40
48
 
41
49
  Issues contain first/last seen, commit and run links, recent evidence, the score
42
50
  and floor, completion state, and triage instructions. Repeated observations update
@@ -69,3 +77,30 @@ recovery. No deliberately broken production code is required.
69
77
  For a local Linux or WSL run: `uv run --group mutation mutmut run`. Native Windows
70
78
  does not provide mutmut's required fork support. A partial local experiment is
71
79
  reported as partial evidence, not a complete project score.
80
+
81
+ ## Bounded first triage
82
+
83
+ The complete run at commit `d9679f3622f0e14caa3c0dfb65c8fac7a654dced`
84
+ reported 1,822 killed and 941 surviving mutants (65.94%). This is historical
85
+ evidence for that revision, not a score for the later manifest/runtime changes.
86
+ The manifest run `40808278696` timed out after 3,271 of 3,845 mutants and has no
87
+ complete score. Neither result establishes a current-main passing score.
88
+
89
+ A bounded review selected network and portable-path boundaries. Regression
90
+ tests now cover username-only URLs, port zero, control/DEL characters, raw Unicode
91
+ queries, query-free base URLs, mixed public/private DNS answers, empty DNS,
92
+ public plaintext HTTP, socket/connection timeout propagation, root request paths,
93
+ and trailing-dot/reserved output names. These were assertion gaps; the original
94
+ production behavior already rejected or handled the cases correctly.
95
+
96
+ Some survivors remove a guard already covered by another guard. For example,
97
+ `project.x__safe_path__mutmut_6` weakens the backslash/colon predicate while the
98
+ path allowlist still rejects both characters. No threshold or exclusion is
99
+ changed to hide these survivors. New tests are not claimed to improve the full
100
+ mutation score until a complete comparable asynchronous run measures it.
101
+
102
+ Separately, entry-point tests reproduced an alert recovery defect: a valid
103
+ passing artifact could close incidents after a cancelled producer. Producer
104
+ conclusion now overrides such artifact claims. Tests invoke production `main()`
105
+ with an in-memory GitHub adapter and assert incident states; they perform no
106
+ network writes and create no synthetic production alerts.
@@ -0,0 +1,35 @@
1
+ # Security analysis
2
+
3
+ The CodeQL workflow analyzes Python and GitHub Actions with the
4
+ `security-and-quality` queries. It runs on PRs, main pushes, Monday at 06:23 UTC,
5
+ and manual dispatch. Actions are pinned to the same immutable revisions used by
6
+ VerdiClip's current workflow. No project credentials are required.
7
+
8
+ The workflow grants `contents: read` globally. Only its analysis jobs receive
9
+ `security-events: write` to upload findings. Checkout does not persist credentials;
10
+ there is no privileged PR trigger or untrusted artifact execution. CodeQL
11
+ concurrency is separate from mutation testing and cannot cancel a mutation run.
12
+
13
+ Expected job names are `Analyze (python)` and `Analyze (actions)`. The code-scanning
14
+ tool name is verified from successful uploaded analyses before configuring a
15
+ merge rule. A successful workflow means analysis completed; alert counts must be
16
+ inspected separately. No broad query exclusions or severity suppression are used.
17
+
18
+ Repository rules are a separate persistent setting. The configured standard is PRs
19
+ for all contributors, `CI passed` from GitHub Actions, linear history, no
20
+ force-push/deletion, resolved review threads, and no mandatory approving review.
21
+ The owner may bypass the CI rule through PRs only. The active CodeQL all-alerts rule has no
22
+ bypass. These persistent rules were configured separately after successful scan
23
+ verification and explicit approval. Workflow installation itself does not change
24
+ rulesets or default-setup settings. No mandatory reviewer approvals are required.
25
+
26
+ Mutation remains asynchronous and is never a required merge or release check.
27
+ See [mutation testing](mutation.md) for score evidence, execution incidents, and
28
+ triage ownership. Credentials should never be committed; runtime credential
29
+ storage guidance is in [configuration](configuration.md).
30
+
31
+ The HTTP transport explicitly requires TLS 1.2 or newer while retaining normal
32
+ certificate and hostname verification and preserving a stricter existing minimum.
33
+ This makes the modern Python default
34
+ minimum explicit for both static analysis and future maintainers. Baseline
35
+ quality findings are addressed in code rather than through query suppression.
@@ -67,3 +67,14 @@ characters; literal non-ASCII path/query text must be URI-encoded.
67
67
  Use contracts only when you intend to call their declared server. A public
68
68
  server is still an external destination; inspect contracts and override the base
69
69
  URL when needed. Custom plugins are trusted executable application code.
70
+
71
+ Ownership manifests are bounded JSON objects of at most 2 MB with integer schema
72
+ version 1 and validated file hashes. Malformed roots, unknown fields, and
73
+ excessive input fail before writes. Generation also rejects ownership inventories
74
+ that would exceed that bound, so it cannot create an unreadable regeneration
75
+ manifest. Literal operation paths reject whitespace and control characters.
76
+
77
+ Reference resolution limits expanded string keys and values to eight million
78
+ characters, counting repeated references each time. This complements the node
79
+ and depth budgets and stops small contracts from producing oversized serialized
80
+ payloads through repeated large strings. The input document limit remains 2 MB.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "codapact"
3
- version = "0.1.0"
3
+ version = "0.1.1"
4
4
  description = "Contracts into callable tools: pluggable API client and CLI generation."
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "codapact"
3
- version = "0.1.0"
3
+ version = "0.1.1"
4
4
  description = "Contracts into callable tools: pluggable API client and CLI generation."
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -6,6 +6,7 @@ import math
6
6
  import os
7
7
  import re
8
8
  import subprocess
9
+ from abc import abstractmethod
9
10
  from datetime import UTC, datetime, timedelta
10
11
  from pathlib import Path
11
12
  from typing import Any, Protocol
@@ -17,10 +18,21 @@ RESULT_STATUSES = ("regression", "incomplete", "infrastructure", "pass")
17
18
 
18
19
 
19
20
  class IssueAPI(Protocol):
20
- def list(self) -> list[dict[str, Any]]: ...
21
- def create(self, title: str, body: str) -> dict[str, Any]: ...
22
- def update(self, number: int, body: str, state: str) -> None: ...
23
- def comment(self, number: int, body: str) -> None: ...
21
+ @abstractmethod
22
+ def list(self) -> list[dict[str, Any]]:
23
+ raise NotImplementedError
24
+
25
+ @abstractmethod
26
+ def create(self, title: str, body: str) -> dict[str, Any]:
27
+ raise NotImplementedError
28
+
29
+ @abstractmethod
30
+ def update(self, number: int, body: str, state: str) -> None:
31
+ raise NotImplementedError
32
+
33
+ @abstractmethod
34
+ def comment(self, number: int, body: str) -> None:
35
+ raise NotImplementedError
24
36
 
25
37
 
26
38
  class GitHub:
@@ -368,6 +380,28 @@ def main() -> None:
368
380
  "scope": SCOPE,
369
381
  "run_attempt": attempt,
370
382
  }
383
+ # Workflow conclusion is independent evidence. A valid artifact cannot
384
+ # turn a cancelled, skipped, unknown, or failed producer into a pass.
385
+ conclusion = os.environ.get("MUTATION_CONCLUSION", "unknown")
386
+ if conclusion not in {"success", "failure"}:
387
+ report = {
388
+ **report,
389
+ "status": "incomplete",
390
+ "complete": False,
391
+ "score": None,
392
+ "counts": {},
393
+ "reason": "producer workflow was cancelled, timed out, "
394
+ "skipped, or ended with an unsupported conclusion",
395
+ }
396
+ elif conclusion == "failure" and report["status"] == "pass":
397
+ report = {
398
+ **report,
399
+ "status": "infrastructure",
400
+ "complete": False,
401
+ "score": None,
402
+ "counts": {},
403
+ "reason": "failed producer cannot establish passing recovery",
404
+ }
371
405
  numbers = reconcile(api, report)
372
406
  summary = (
373
407
  f"Mutation alert lifecycle verified: {numbers}"
@@ -0,0 +1,3 @@
1
+ """CodaPact: contracts into callable tools."""
2
+
3
+ __version__ = "0.1.1" # x-release-please-version
@@ -0,0 +1,68 @@
1
+ """Authentication and client-side authorization contracts independent of execution."""
2
+
3
+ import base64
4
+ import os
5
+ import re
6
+ from abc import abstractmethod
7
+ from collections.abc import Mapping
8
+ from typing import Any, Protocol
9
+
10
+ from codapact.errors import AuthError, PolicyError
11
+
12
+
13
+ class AuthProvider(Protocol):
14
+ """Return scheme-specific headers or raise AuthError if unavailable."""
15
+
16
+ @abstractmethod
17
+ def headers(self, name: str, scheme: dict[str, Any]) -> dict[str, str]:
18
+ raise NotImplementedError
19
+
20
+
21
+ class AuthorizationPolicy(Protocol):
22
+ """Client-side guard only. The server remains the authorization authority."""
23
+
24
+ @abstractmethod
25
+ def authorize(self, operation: Mapping[str, Any]) -> None:
26
+ raise NotImplementedError
27
+
28
+
29
+ class OperationPolicy:
30
+ def __init__(self, *, allow: list[str] | None = None, deny: list[str] | None = None) -> None:
31
+ self.allow = None if allow is None else frozenset(allow)
32
+ self.deny = frozenset(deny or [])
33
+
34
+ def authorize(self, operation: Mapping[str, Any]) -> None:
35
+ name = operation["id"]
36
+ if name in self.deny or (self.allow is not None and name not in self.allow):
37
+ raise PolicyError(f"client policy denies operation {name}")
38
+
39
+
40
+ class EnvironmentAuth:
41
+ """Credentials are resolved at execution time, never written into generated files."""
42
+
43
+ def __init__(self, settings: dict[str, dict[str, str]] | None = None) -> None:
44
+ self.settings = settings or {}
45
+
46
+ @staticmethod
47
+ def _secret(entry: dict[str, str], key: str) -> str:
48
+ reference = entry.get(key, "")
49
+ if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", reference):
50
+ raise AuthError("auth requires an environment variable reference")
51
+ value = os.environ.get(reference)
52
+ if value is None or value == "" or any(ord(c) < 32 or ord(c) == 127 for c in value):
53
+ raise AuthError("required credential is missing or invalid")
54
+ return value
55
+
56
+ def headers(self, name: str, scheme: dict[str, Any]) -> dict[str, str]:
57
+ entry = self.settings.get(name, {})
58
+ if scheme["type"] == "apiKey":
59
+ return {scheme["name"]: self._secret(entry, "env")}
60
+ if scheme["scheme"] == "bearer":
61
+ return {"Authorization": "Bearer " + self._secret(entry, "env")}
62
+ username = self._secret(entry, "username_env")
63
+ if ":" in username:
64
+ raise AuthError("basic auth username cannot contain a colon")
65
+ token = base64.b64encode(
66
+ (username + ":" + self._secret(entry, "password_env")).encode()
67
+ ).decode()
68
+ return {"Authorization": "Basic " + token}
@@ -54,17 +54,17 @@ def run_cli(
54
54
  try:
55
55
  if args.config and args.config.startswith(("http://", "https://")):
56
56
  raise CodaError("runtime configuration must be local")
57
+ overrides = {
58
+ key: getattr(args, key)
59
+ for key in ("base_url", "timeout", "allow_private")
60
+ if getattr(args, key) is not None
61
+ }
57
62
  if profile is None:
58
63
  settings = load(args.config) if args.config else {}
59
64
  if args.config_dir or args.auth_file or args.no_auth_file:
60
65
  raise CodaError("configuration discovery requires a generated runtime profile")
61
- client = factory(settings=settings)
66
+ client = factory(settings={**settings, **overrides})
62
67
  else:
63
- overrides = {
64
- key: getattr(args, key)
65
- for key in ("base_url", "timeout", "allow_private")
66
- if getattr(args, key) is not None
67
- }
68
68
  settings, directory = runtime_settings(profile, args.config_dir, args.config, overrides)
69
69
  if args.auth_file and args.no_auth_file:
70
70
  raise CodaError("--auth-file and --no-auth-file conflict")
@@ -11,6 +11,8 @@ from yaml.tokens import AliasToken, AnchorToken
11
11
  from codapact.errors import CodaError
12
12
  from codapact.net import MAX_BYTES, HttpTransport, Transport
13
13
 
14
+ MAX_EXPANDED_TEXT = 8_000_000
15
+
14
16
 
15
17
  class UniqueLoader(yaml.SafeLoader):
16
18
  """Reject ambiguous duplicate keys instead of accepting the last one."""
@@ -85,6 +87,13 @@ def load(source: str, *, transport: Transport | None = None) -> dict[str, Any]:
85
87
  def resolve(document: dict[str, Any]) -> dict[str, Any]:
86
88
  """Resolve internal refs only; refuse recursion, siblings, and external fetches."""
87
89
  budget = 0
90
+ expanded_text = 0
91
+
92
+ def charge_text(text: str) -> None:
93
+ nonlocal expanded_text
94
+ expanded_text += len(text)
95
+ if expanded_text > MAX_EXPANDED_TEXT:
96
+ raise CodaError("reference expansion text limit exceeded")
88
97
 
89
98
  def walk(node: Any, stack: tuple[str, ...] = (), depth: int = 0) -> Any:
90
99
  nonlocal budget
@@ -94,6 +103,8 @@ def resolve(document: dict[str, Any]) -> dict[str, Any]:
94
103
  if isinstance(node, list):
95
104
  return [walk(child, stack, depth + 1) for child in node]
96
105
  if not isinstance(node, dict):
106
+ if isinstance(node, str):
107
+ charge_text(node)
97
108
  return node
98
109
  if "$ref" in node:
99
110
  ref = node["$ref"]
@@ -116,6 +127,9 @@ def resolve(document: dict[str, Any]) -> dict[str, Any]:
116
127
  except (KeyError, IndexError, TypeError, ValueError):
117
128
  raise CodaError("unresolved internal reference") from None
118
129
  return walk(target, (*stack, ref), depth + 1)
130
+ for key in node:
131
+ if isinstance(key, str):
132
+ charge_text(key)
119
133
  return {key: walk(child, stack, depth + 1) for key, child in node.items()}
120
134
 
121
135
  return walk(document)
@@ -1,5 +1,6 @@
1
1
  """Versioned source-neutral intermediate representation and plugin contracts."""
2
2
 
3
+ from abc import abstractmethod
3
4
  from dataclasses import asdict, dataclass, field
4
5
  from typing import Any, Protocol
5
6
 
@@ -40,14 +41,18 @@ class Translator(Protocol):
40
41
  api_version: int
41
42
  capabilities: frozenset[str]
42
43
 
43
- def translate(self, document: dict[str, Any]) -> Contract: ...
44
+ @abstractmethod
45
+ def translate(self, document: dict[str, Any]) -> Contract:
46
+ raise NotImplementedError
44
47
 
45
48
 
46
49
  class Generator(Protocol):
47
50
  api_version: int
48
51
  requires: frozenset[str]
49
52
 
50
- def generate(self, contract: Contract, package: str) -> dict[str, str]: ...
53
+ @abstractmethod
54
+ def generate(self, contract: Contract, package: str) -> dict[str, str]:
55
+ raise NotImplementedError
51
56
 
52
57
 
53
58
  class Registry:
@@ -4,6 +4,7 @@ import http.client
4
4
  import ipaddress
5
5
  import socket
6
6
  import ssl
7
+ from abc import abstractmethod
7
8
  from dataclasses import dataclass
8
9
  from typing import Protocol, cast
9
10
  from urllib.parse import SplitResult, urlsplit
@@ -50,9 +51,9 @@ class Response:
50
51
  class Transport(Protocol):
51
52
  """Implementations must not follow redirects or log credentials."""
52
53
 
53
- def send(
54
- self, method: str, url: str, headers: dict[str, str], body: bytes | None
55
- ) -> Response: ...
54
+ @abstractmethod
55
+ def send(self, method: str, url: str, headers: dict[str, str], body: bytes | None) -> Response:
56
+ raise NotImplementedError
56
57
 
57
58
 
58
59
  class HttpTransport:
@@ -82,7 +83,12 @@ class HttpTransport:
82
83
  sock = socket.create_connection((ips[0], port), timeout=self.timeout)
83
84
  try:
84
85
  if parts.scheme == "https":
85
- sock = ssl.create_default_context().wrap_socket(sock, server_hostname=hostname)
86
+ context = ssl.create_default_context()
87
+ minimum = context.minimum_version
88
+ context.minimum_version = (
89
+ ssl.TLSVersion.TLSv1_2 if minimum < ssl.TLSVersion.TLSv1_2 else minimum
90
+ )
91
+ sock = context.wrap_socket(sock, server_hostname=hostname)
86
92
  connection.sock = sock
87
93
  target = (parts.path or "/") + ("?" + parts.query if parts.query else "")
88
94
  connection.request(method, target, body, headers)
@@ -152,7 +152,7 @@ class OpenAPITranslator:
152
152
  or "#" in path
153
153
  or "\\" in path
154
154
  or "%" in path
155
- or any(ord(c) < 32 for c in path)
155
+ or any(c.isspace() or ord(c) < 32 or ord(c) == 127 for c in path)
156
156
  or not path.isascii()
157
157
  or "{" in re.sub(r"\{[A-Za-z][A-Za-z0-9_-]*\}", "", path)
158
158
  or "}" in re.sub(r"\{[A-Za-z][A-Za-z0-9_-]*\}", "", path)
@@ -4,12 +4,14 @@ import base64
4
4
  import json
5
5
  import os
6
6
  import stat
7
+ from abc import abstractmethod
7
8
  from pathlib import Path
8
9
  from typing import Any, Protocol
9
10
 
11
+ from codapact.auth import EnvironmentAuth
10
12
  from codapact.errors import AuthError, CodaError
11
13
  from codapact.loading import parse
12
- from codapact.runtime import EnvironmentAuth, config, validate
14
+ from codapact.validation import config, validate
13
15
  from codapact.values import merge, slug_name
14
16
 
15
17
 
@@ -84,7 +86,9 @@ def read_file(path: Path, *, optional: bool = False, json_only: bool = False) ->
84
86
  class CredentialStore(Protocol):
85
87
  """Explicit dependency injection boundary for future keyring providers."""
86
88
 
87
- def get(self, name: str) -> dict[str, str] | None: ...
89
+ @abstractmethod
90
+ def get(self, name: str) -> dict[str, str] | None:
91
+ raise NotImplementedError
88
92
 
89
93
 
90
94
  class JsonFileStore:
@@ -14,7 +14,7 @@ from codapact.errors import CodaError
14
14
  from codapact.generation import ArgparseGenerator, PythonGenerator, canonical, package_name
15
15
  from codapact.loading import load
16
16
  from codapact.model import Registry
17
- from codapact.net import Transport
17
+ from codapact.net import MAX_BYTES, Transport
18
18
  from codapact.openapi import OpenAPITranslator
19
19
 
20
20
  MANIFEST = ".codapact-manifest.json"
@@ -68,9 +68,18 @@ def write_project(root: Path, files: dict[str, str]) -> None:
68
68
  previous = {}
69
69
  if manifest.exists():
70
70
  try:
71
- state = json.loads(manifest.read_text("utf-8"))
71
+ if not manifest.is_file():
72
+ raise ValueError
73
+ with manifest.open("rb") as handle:
74
+ content = handle.read(MAX_BYTES + 1)
75
+ if len(content) > MAX_BYTES:
76
+ raise ValueError
77
+ state = json.loads(content)
72
78
  if (
73
- state["version"] != 1
79
+ not isinstance(state, dict)
80
+ or set(state) - {"version", "generator", "files"}
81
+ or type(state.get("version")) is not int
82
+ or state["version"] != 1
74
83
  or not isinstance(state["files"], dict)
75
84
  or any(
76
85
  not isinstance(k, str)
@@ -81,9 +90,18 @@ def write_project(root: Path, files: dict[str, str]) -> None:
81
90
  ):
82
91
  raise ValueError
83
92
  previous = state["files"]
84
- except (ValueError, KeyError, OSError):
93
+ except (ValueError, KeyError, OSError, RecursionError):
85
94
  raise CodaError("invalid ownership manifest") from None
86
95
  encoded = {name: value.encode("utf-8") for name, value in files.items()}
96
+ ownership = canonical(
97
+ {
98
+ "version": 1,
99
+ "generator": f"codapact/{__version__}",
100
+ "files": {name: digest(data) for name, data in encoded.items()},
101
+ }
102
+ ).encode()
103
+ if len(ownership) > MAX_BYTES:
104
+ raise CodaError("generated ownership manifest exceeds 2 MB limit")
87
105
  names = {name.casefold() for name in encoded}
88
106
  if len(names) != len(encoded) or any(
89
107
  parent.as_posix().casefold() in names
@@ -109,16 +127,7 @@ def write_project(root: Path, files: dict[str, str]) -> None:
109
127
  _atomic(path, data)
110
128
  for name in previous.keys() - encoded.keys():
111
129
  _safe_path(root, name).unlink(missing_ok=True)
112
- _atomic(
113
- manifest,
114
- canonical(
115
- {
116
- "version": 1,
117
- "generator": f"codapact/{__version__}",
118
- "files": {name: digest(data) for name, data in encoded.items()},
119
- }
120
- ).encode(),
121
- )
130
+ _atomic(manifest, ownership)
122
131
 
123
132
 
124
133
  def _atomic(path: Path, data: bytes) -> None: