isolation-check 0.3.0a2__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.
- isolation_check/__init__.py +4 -0
- isolation_check/__main__.py +6 -0
- isolation_check/cli.py +422 -0
- isolation_check/collect/__init__.py +1 -0
- isolation_check/collect/compose.py +251 -0
- isolation_check/create/__init__.py +1 -0
- isolation_check/create/generator.py +216 -0
- isolation_check/create/manager.py +322 -0
- isolation_check/create/spec.py +219 -0
- isolation_check/create/validate.py +314 -0
- isolation_check/create/verify.py +132 -0
- isolation_check/create/worktree.py +158 -0
- isolation_check/models.py +179 -0
- isolation_check/normalize/__init__.py +1 -0
- isolation_check/normalize/compose.py +283 -0
- isolation_check/py.typed +1 -0
- isolation_check/report.py +110 -0
- isolation_check/rules/__init__.py +1 -0
- isolation_check/rules/ports.py +247 -0
- isolation_check/rules/volumes.py +195 -0
- isolation_check/runtime/__init__.py +1 -0
- isolation_check/runtime/capabilities.py +78 -0
- isolation_check/runtime/concurrency.py +313 -0
- isolation_check/runtime/lifecycle.py +858 -0
- isolation_check/runtime/port_allocator.py +189 -0
- isolation_check/runtime/validation.py +240 -0
- isolation_check/version.py +21 -0
- isolation_check-0.3.0a2.dist-info/METADATA +333 -0
- isolation_check-0.3.0a2.dist-info/RECORD +33 -0
- isolation_check-0.3.0a2.dist-info/WHEEL +5 -0
- isolation_check-0.3.0a2.dist-info/entry_points.txt +2 -0
- isolation_check-0.3.0a2.dist-info/licenses/LICENSE +190 -0
- isolation_check-0.3.0a2.dist-info/top_level.txt +1 -0
isolation_check/cli.py
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
"""Command-line interface for isolation-check."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import sys
|
|
7
|
+
from typing import Sequence
|
|
8
|
+
|
|
9
|
+
from isolation_check.collect.compose import (
|
|
10
|
+
ComposeCollectorError,
|
|
11
|
+
collect_compose_config,
|
|
12
|
+
load_compose_json_file,
|
|
13
|
+
resolve_compose_target,
|
|
14
|
+
)
|
|
15
|
+
from isolation_check.models import EngineScope, Finding, HostScope
|
|
16
|
+
from isolation_check.normalize.compose import normalize_compose_model
|
|
17
|
+
from isolation_check.report import build_report, format_json_report, format_text_report
|
|
18
|
+
from isolation_check.rules.ports import check_ports
|
|
19
|
+
from isolation_check.rules.volumes import check_volumes
|
|
20
|
+
from isolation_check.version import get_package_version
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
|
|
24
|
+
raw_args = list(argv if argv is not None else sys.argv[1:])
|
|
25
|
+
|
|
26
|
+
# Default to 'check' subcommand if running `isolation-check <left> <right>` directly
|
|
27
|
+
if raw_args and not raw_args[0].startswith("-") and raw_args[0] not in (
|
|
28
|
+
"check", "create", "up", "status", "down", "help"
|
|
29
|
+
):
|
|
30
|
+
raw_args.insert(0, "check")
|
|
31
|
+
|
|
32
|
+
parser = argparse.ArgumentParser(
|
|
33
|
+
prog="isolation-check",
|
|
34
|
+
description="Inspect and prepare isolated local development environments.",
|
|
35
|
+
)
|
|
36
|
+
parser.add_argument(
|
|
37
|
+
"-V",
|
|
38
|
+
"--version",
|
|
39
|
+
action="version",
|
|
40
|
+
version=f"%(prog)s {get_package_version()}",
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
subparsers = parser.add_subparsers(dest="command")
|
|
44
|
+
|
|
45
|
+
check_parser = subparsers.add_parser(
|
|
46
|
+
"check",
|
|
47
|
+
help="Compare two Docker Compose configurations for resource collisions.",
|
|
48
|
+
)
|
|
49
|
+
check_parser.add_argument(
|
|
50
|
+
"left",
|
|
51
|
+
nargs="?",
|
|
52
|
+
help="Path to first Compose environment directory, compose file, or JSON fixture.",
|
|
53
|
+
)
|
|
54
|
+
check_parser.add_argument(
|
|
55
|
+
"right",
|
|
56
|
+
nargs="?",
|
|
57
|
+
help="Path to second Compose environment directory, compose file, or JSON fixture.",
|
|
58
|
+
)
|
|
59
|
+
check_parser.add_argument(
|
|
60
|
+
"--format",
|
|
61
|
+
choices=["text", "json"],
|
|
62
|
+
default="text",
|
|
63
|
+
help="Output format (default: text).",
|
|
64
|
+
)
|
|
65
|
+
check_parser.add_argument(
|
|
66
|
+
"--strict",
|
|
67
|
+
action="store_true",
|
|
68
|
+
help="Treat UNKNOWN findings as exit code 2 if there is no FAIL.",
|
|
69
|
+
)
|
|
70
|
+
check_parser.add_argument(
|
|
71
|
+
"--engine-scope",
|
|
72
|
+
default="local-docker-engine",
|
|
73
|
+
help="Explicit identifier for the Docker engine scope (default: local-docker-engine).",
|
|
74
|
+
)
|
|
75
|
+
check_parser.add_argument(
|
|
76
|
+
"--no-shared-engine",
|
|
77
|
+
action="store_true",
|
|
78
|
+
help="Do not assume a shared Docker engine scope (treat scopes as distinct/unknown).",
|
|
79
|
+
)
|
|
80
|
+
check_parser.add_argument(
|
|
81
|
+
"--host-scope",
|
|
82
|
+
default="local-host",
|
|
83
|
+
help="Explicit identifier for the host machine scope (default: local-host).",
|
|
84
|
+
)
|
|
85
|
+
check_parser.add_argument(
|
|
86
|
+
"--no-shared-host",
|
|
87
|
+
action="store_true",
|
|
88
|
+
help="Do not assume a shared host scope (treat host scopes as distinct/unknown).",
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
create_parser = subparsers.add_parser(
|
|
92
|
+
"create",
|
|
93
|
+
help="Safely prepare a Git worktree with a generated Docker Compose environment.",
|
|
94
|
+
)
|
|
95
|
+
create_parser.add_argument(
|
|
96
|
+
"name",
|
|
97
|
+
help="Name of the environment to create (e.g. feature-payments).",
|
|
98
|
+
)
|
|
99
|
+
create_parser.add_argument(
|
|
100
|
+
"--dry-run",
|
|
101
|
+
action="store_true",
|
|
102
|
+
help="Validate inputs and configuration and display proposed plan without making changes.",
|
|
103
|
+
)
|
|
104
|
+
create_parser.add_argument(
|
|
105
|
+
"--repo",
|
|
106
|
+
help="Source Git repository path (default: current working directory).",
|
|
107
|
+
)
|
|
108
|
+
create_parser.add_argument(
|
|
109
|
+
"--base-ref",
|
|
110
|
+
help="Base git revision/commit/branch to branch from (default: HEAD).",
|
|
111
|
+
)
|
|
112
|
+
create_parser.add_argument(
|
|
113
|
+
"--branch",
|
|
114
|
+
help="Name of the branch to create in the worktree (default: matches environment name).",
|
|
115
|
+
)
|
|
116
|
+
create_parser.add_argument(
|
|
117
|
+
"--worktree-path",
|
|
118
|
+
help="Path where the worktree should be created (default: sibling of repo).",
|
|
119
|
+
)
|
|
120
|
+
create_parser.add_argument(
|
|
121
|
+
"-f",
|
|
122
|
+
"--compose-file",
|
|
123
|
+
action="append",
|
|
124
|
+
dest="compose_files",
|
|
125
|
+
help="Compose file(s) in merge order (can be specified multiple times).",
|
|
126
|
+
)
|
|
127
|
+
create_parser.add_argument(
|
|
128
|
+
"--app-service",
|
|
129
|
+
help="Explicitly configured application service name.",
|
|
130
|
+
)
|
|
131
|
+
create_parser.add_argument(
|
|
132
|
+
"--db-service",
|
|
133
|
+
help="Explicitly configured PostgreSQL service name.",
|
|
134
|
+
)
|
|
135
|
+
create_parser.add_argument(
|
|
136
|
+
"--db-env-var",
|
|
137
|
+
help="Application's database connection environment variable name (e.g. DATABASE_URL).",
|
|
138
|
+
)
|
|
139
|
+
create_parser.add_argument(
|
|
140
|
+
"--app-port",
|
|
141
|
+
type=int,
|
|
142
|
+
help="Application container target port (e.g. 3000).",
|
|
143
|
+
)
|
|
144
|
+
create_parser.add_argument(
|
|
145
|
+
"--publish-db",
|
|
146
|
+
action="store_true",
|
|
147
|
+
default=None,
|
|
148
|
+
help="Publish PostgreSQL database to the host (default: false, internal container network only).",
|
|
149
|
+
)
|
|
150
|
+
create_parser.add_argument(
|
|
151
|
+
"--config",
|
|
152
|
+
help="Path to TOML configuration file specifying environment creation parameters.",
|
|
153
|
+
)
|
|
154
|
+
create_parser.add_argument(
|
|
155
|
+
"--format",
|
|
156
|
+
choices=["text", "json"],
|
|
157
|
+
default="text",
|
|
158
|
+
help="Output format (default: text).",
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
up_parser = subparsers.add_parser(
|
|
162
|
+
"up",
|
|
163
|
+
help="Start a managed environment's Docker Compose project.",
|
|
164
|
+
)
|
|
165
|
+
up_parser.add_argument(
|
|
166
|
+
"environment",
|
|
167
|
+
help="Name of the managed environment to start.",
|
|
168
|
+
)
|
|
169
|
+
up_parser.add_argument(
|
|
170
|
+
"--repo",
|
|
171
|
+
help="Path to source Git repository or worktree (default: current directory).",
|
|
172
|
+
)
|
|
173
|
+
up_parser.add_argument(
|
|
174
|
+
"--json",
|
|
175
|
+
action="store_true",
|
|
176
|
+
dest="output_json",
|
|
177
|
+
help="Output result as structured JSON.",
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
status_parser = subparsers.add_parser(
|
|
181
|
+
"status",
|
|
182
|
+
help="Query runtime state and health of a managed environment.",
|
|
183
|
+
)
|
|
184
|
+
status_parser.add_argument(
|
|
185
|
+
"environment",
|
|
186
|
+
help="Name of the managed environment.",
|
|
187
|
+
)
|
|
188
|
+
status_parser.add_argument(
|
|
189
|
+
"--repo",
|
|
190
|
+
help="Path to source Git repository or worktree (default: current directory).",
|
|
191
|
+
)
|
|
192
|
+
status_parser.add_argument(
|
|
193
|
+
"--json",
|
|
194
|
+
action="store_true",
|
|
195
|
+
dest="output_json",
|
|
196
|
+
help="Output status as structured JSON.",
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
down_parser = subparsers.add_parser(
|
|
200
|
+
"down",
|
|
201
|
+
help="Stop a managed environment while preserving data volumes.",
|
|
202
|
+
description="Stop a managed environment while preserving data volumes.",
|
|
203
|
+
)
|
|
204
|
+
down_parser.add_argument(
|
|
205
|
+
"environment",
|
|
206
|
+
help="Name of the managed environment to stop.",
|
|
207
|
+
)
|
|
208
|
+
down_parser.add_argument(
|
|
209
|
+
"--repo",
|
|
210
|
+
help="Path to source Git repository or worktree (default: current directory).",
|
|
211
|
+
)
|
|
212
|
+
down_parser.add_argument(
|
|
213
|
+
"--json",
|
|
214
|
+
action="store_true",
|
|
215
|
+
dest="output_json",
|
|
216
|
+
help="Output result as structured JSON.",
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
return parser.parse_args(raw_args)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _load_env_config(path_str: str) -> tuple[dict, str, str]:
|
|
223
|
+
"""Loads raw Compose config for an environment path.
|
|
224
|
+
|
|
225
|
+
Returns (raw_config_dict, label, root_str).
|
|
226
|
+
Detects if the input is already a JSON fixture or needs Docker Compose resolution.
|
|
227
|
+
"""
|
|
228
|
+
p = Path(path_str).resolve()
|
|
229
|
+
if not p.exists():
|
|
230
|
+
raise ComposeCollectorError(f"Target path does not exist: {path_str}")
|
|
231
|
+
|
|
232
|
+
if p.is_file() and p.suffix.lower() == ".json":
|
|
233
|
+
# Pre-rendered Compose JSON fixture (offline mode)
|
|
234
|
+
raw_config = load_compose_json_file(p)
|
|
235
|
+
label = p.stem
|
|
236
|
+
root = str(p.parent)
|
|
237
|
+
return raw_config, label, root
|
|
238
|
+
|
|
239
|
+
# Standard Docker Compose environment
|
|
240
|
+
project_dir, compose_file = resolve_compose_target(p)
|
|
241
|
+
raw_config = collect_compose_config(project_dir, compose_file)
|
|
242
|
+
label = project_dir.name
|
|
243
|
+
root = str(project_dir)
|
|
244
|
+
return raw_config, label, root
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
248
|
+
args = parse_args(argv)
|
|
249
|
+
|
|
250
|
+
if args.command == "up":
|
|
251
|
+
from isolation_check.runtime.lifecycle import execute_up
|
|
252
|
+
return execute_up(
|
|
253
|
+
env_name=args.environment,
|
|
254
|
+
repo_hint=args.repo,
|
|
255
|
+
output_json=getattr(args, "output_json", False),
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
if args.command == "status":
|
|
259
|
+
from isolation_check.runtime.lifecycle import execute_status
|
|
260
|
+
return execute_status(
|
|
261
|
+
env_name=args.environment,
|
|
262
|
+
repo_hint=args.repo,
|
|
263
|
+
output_json=getattr(args, "output_json", False),
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
if args.command == "down":
|
|
267
|
+
from isolation_check.runtime.lifecycle import execute_down
|
|
268
|
+
return execute_down(
|
|
269
|
+
env_name=args.environment,
|
|
270
|
+
repo_hint=args.repo,
|
|
271
|
+
output_json=getattr(args, "output_json", False),
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
if args.command == "create":
|
|
275
|
+
from isolation_check.create.manager import execute_create, execute_dry_run
|
|
276
|
+
from isolation_check.create.spec import SpecError, load_spec_from_cli
|
|
277
|
+
|
|
278
|
+
try:
|
|
279
|
+
spec = load_spec_from_cli(
|
|
280
|
+
name=args.name,
|
|
281
|
+
repo_arg=args.repo,
|
|
282
|
+
base_ref_arg=args.base_ref,
|
|
283
|
+
branch_arg=args.branch,
|
|
284
|
+
worktree_path_arg=args.worktree_path,
|
|
285
|
+
compose_files_arg=args.compose_files,
|
|
286
|
+
app_service_arg=args.app_service,
|
|
287
|
+
db_service_arg=args.db_service,
|
|
288
|
+
db_env_var_arg=args.db_env_var,
|
|
289
|
+
app_port_arg=getattr(args, "app_port", None),
|
|
290
|
+
publish_db_arg=args.publish_db,
|
|
291
|
+
dry_run=args.dry_run,
|
|
292
|
+
output_format=args.format,
|
|
293
|
+
config_path_arg=args.config,
|
|
294
|
+
)
|
|
295
|
+
except SpecError as exc:
|
|
296
|
+
if getattr(args, "format", "text") == "json":
|
|
297
|
+
import json
|
|
298
|
+
print(json.dumps({
|
|
299
|
+
"schema_version": "1.0",
|
|
300
|
+
"tool_version": get_package_version(),
|
|
301
|
+
"success": False,
|
|
302
|
+
"error": str(exc),
|
|
303
|
+
}, indent=2))
|
|
304
|
+
else:
|
|
305
|
+
sys.stderr.write(f"Configuration Error: {exc}\n")
|
|
306
|
+
return 2
|
|
307
|
+
|
|
308
|
+
if spec.dry_run:
|
|
309
|
+
return execute_dry_run(spec)
|
|
310
|
+
return execute_create(spec)
|
|
311
|
+
|
|
312
|
+
if not getattr(args, "left", None) or not getattr(args, "right", None):
|
|
313
|
+
sys.stderr.write("Error: Two environment paths ('left' and 'right') are required.\n")
|
|
314
|
+
sys.stderr.write("Usage: isolation-check check <path1> <path2> [--format {text,json}] [--strict]\n")
|
|
315
|
+
return 2
|
|
316
|
+
|
|
317
|
+
# Determine declared engine scope
|
|
318
|
+
if args.no_shared_engine:
|
|
319
|
+
left_engine_scope = EngineScope(scope_id=None, basis="unspecified engine scope")
|
|
320
|
+
right_engine_scope = EngineScope(scope_id=None, basis="unspecified engine scope")
|
|
321
|
+
else:
|
|
322
|
+
left_engine_scope = EngineScope(
|
|
323
|
+
scope_id=args.engine_scope,
|
|
324
|
+
basis="explicit shared local-engine assumption",
|
|
325
|
+
)
|
|
326
|
+
right_engine_scope = EngineScope(
|
|
327
|
+
scope_id=args.engine_scope,
|
|
328
|
+
basis="explicit shared local-engine assumption",
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
# Determine declared host scope
|
|
332
|
+
if args.no_shared_host:
|
|
333
|
+
left_host_scope = HostScope(scope_id=None, basis="unspecified host scope")
|
|
334
|
+
right_host_scope = HostScope(scope_id=None, basis="unspecified host scope")
|
|
335
|
+
else:
|
|
336
|
+
left_host_scope = HostScope(
|
|
337
|
+
scope_id=args.host_scope,
|
|
338
|
+
basis="explicit shared local-host assumption",
|
|
339
|
+
)
|
|
340
|
+
right_host_scope = HostScope(
|
|
341
|
+
scope_id=args.host_scope,
|
|
342
|
+
basis="explicit shared local-host assumption",
|
|
343
|
+
)
|
|
344
|
+
|
|
345
|
+
try:
|
|
346
|
+
left_raw, left_label, left_root = _load_env_config(args.left)
|
|
347
|
+
right_raw, right_label, right_root = _load_env_config(args.right)
|
|
348
|
+
except ComposeCollectorError as exc:
|
|
349
|
+
# Sanitized error message without leaking sensitive data
|
|
350
|
+
err_msg = str(exc)
|
|
351
|
+
if args.format == "json":
|
|
352
|
+
import json
|
|
353
|
+
print(json.dumps({
|
|
354
|
+
"schema_version": "1.0",
|
|
355
|
+
"tool_version": get_package_version(),
|
|
356
|
+
"complete": False,
|
|
357
|
+
"error": err_msg,
|
|
358
|
+
}, indent=2))
|
|
359
|
+
else:
|
|
360
|
+
sys.stderr.write(f"Collection Error: {err_msg}\n")
|
|
361
|
+
return 2
|
|
362
|
+
except Exception:
|
|
363
|
+
# Do not leak stack traces or secret variables
|
|
364
|
+
sys.stderr.write("Unexpected error occurred during environment collection.\n")
|
|
365
|
+
return 2
|
|
366
|
+
|
|
367
|
+
# Normalization
|
|
368
|
+
left_env = normalize_compose_model(
|
|
369
|
+
left_raw, left_label, left_root, left_engine_scope, left_host_scope
|
|
370
|
+
)
|
|
371
|
+
right_env = normalize_compose_model(
|
|
372
|
+
right_raw, right_label, right_root, right_engine_scope, right_host_scope
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
# Rule evaluations
|
|
376
|
+
findings: list[Finding] = []
|
|
377
|
+
# 1. Volume collisions (VOL001)
|
|
378
|
+
findings.extend(check_volumes(left_env, right_env, include_coverage=False))
|
|
379
|
+
# 2. Host-port collisions (PORT001)
|
|
380
|
+
findings.extend(check_ports(left_env, right_env))
|
|
381
|
+
# 3. Overall coverage disclaimer
|
|
382
|
+
findings.append(
|
|
383
|
+
Finding(
|
|
384
|
+
rule_id="COVERAGE",
|
|
385
|
+
status="unknown",
|
|
386
|
+
severity="info",
|
|
387
|
+
confidence="high",
|
|
388
|
+
basis="partial evaluation",
|
|
389
|
+
message=(
|
|
390
|
+
"Bind mounts, databases, project namespaces, and runtime state were not evaluated. "
|
|
391
|
+
"Exit 0 does not prove complete environment isolation."
|
|
392
|
+
),
|
|
393
|
+
environments=[left_env.label, right_env.label],
|
|
394
|
+
)
|
|
395
|
+
)
|
|
396
|
+
|
|
397
|
+
# Report generation
|
|
398
|
+
report = build_report(
|
|
399
|
+
findings=findings,
|
|
400
|
+
environments=[left_env.label, right_env.label],
|
|
401
|
+
engine_scope=left_engine_scope,
|
|
402
|
+
host_scope=left_host_scope,
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
if args.format == "json":
|
|
406
|
+
print(format_json_report(report))
|
|
407
|
+
else:
|
|
408
|
+
print(format_text_report(report))
|
|
409
|
+
|
|
410
|
+
# Exit code determination
|
|
411
|
+
has_fail = any(f.status == "fail" for f in findings)
|
|
412
|
+
has_unknown = any(f.status == "unknown" for f in findings)
|
|
413
|
+
|
|
414
|
+
if has_fail:
|
|
415
|
+
return 1
|
|
416
|
+
if args.strict and has_unknown:
|
|
417
|
+
return 2
|
|
418
|
+
return 0
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
if __name__ == "__main__":
|
|
422
|
+
sys.exit(main())
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Collection layer for isolation-check."""
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""Docker Compose configuration collector.
|
|
2
|
+
|
|
3
|
+
Executes `docker compose config --format json` safely using bounded streams,
|
|
4
|
+
subprocess argument lists, timeouts, and sanitized error messages.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
import subprocess
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
# Maximum allowed size for Compose JSON output (1 MB) to prevent memory exhaustion
|
|
15
|
+
DEFAULT_OUTPUT_LIMIT = 1_048_576
|
|
16
|
+
DEFAULT_TIMEOUT_SECONDS = 15.0
|
|
17
|
+
|
|
18
|
+
COMPOSE_FILE_CANDIDATES = (
|
|
19
|
+
"compose.yaml",
|
|
20
|
+
"compose.yml",
|
|
21
|
+
"docker-compose.yaml",
|
|
22
|
+
"docker-compose.yml",
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ComposeCollectorError(Exception):
|
|
27
|
+
"""Base exception for Compose collection failures."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ComposeFileNotFoundError(ComposeCollectorError):
|
|
31
|
+
"""Raised when Compose configuration file cannot be found."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ComposeExecutionError(ComposeCollectorError):
|
|
35
|
+
"""Raised when `docker compose` execution fails."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ComposeOutputLimitExceededError(ComposeCollectorError):
|
|
39
|
+
"""Raised when Compose output exceeds safety threshold."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def resolve_compose_target(path: str | Path) -> tuple[Path, list[Path]]:
|
|
43
|
+
"""Resolves an environment path to (project_directory, compose_files).
|
|
44
|
+
|
|
45
|
+
If the directory contains an isolation-check manifest (.isolation-check/manifest.json),
|
|
46
|
+
resolves the full set of base files and generated override file.
|
|
47
|
+
Otherwise searches for standard Compose candidates and optional override file.
|
|
48
|
+
"""
|
|
49
|
+
target = Path(path).resolve()
|
|
50
|
+
if not target.exists():
|
|
51
|
+
raise ComposeFileNotFoundError(f"Target path does not exist: {target}")
|
|
52
|
+
|
|
53
|
+
if target.is_file():
|
|
54
|
+
return target.parent, [target]
|
|
55
|
+
|
|
56
|
+
if target.is_dir():
|
|
57
|
+
# Check if managed by isolation-check with manifest.json
|
|
58
|
+
manifest_file = target / ".isolation-check" / "manifest.json"
|
|
59
|
+
if manifest_file.is_file():
|
|
60
|
+
try:
|
|
61
|
+
import json
|
|
62
|
+
m_data = json.loads(manifest_file.read_text(encoding="utf-8"))
|
|
63
|
+
compose_info = m_data.get("compose", {})
|
|
64
|
+
base_files = compose_info.get("base_compose_files", [])
|
|
65
|
+
override_file = compose_info.get("override_file")
|
|
66
|
+
files: list[Path] = []
|
|
67
|
+
for bf in base_files:
|
|
68
|
+
bf_path = (target / bf).resolve()
|
|
69
|
+
if bf_path.is_file():
|
|
70
|
+
files.append(bf_path)
|
|
71
|
+
if override_file:
|
|
72
|
+
ov_path = (target / override_file).resolve()
|
|
73
|
+
if ov_path.is_file():
|
|
74
|
+
files.append(ov_path)
|
|
75
|
+
if files:
|
|
76
|
+
return target, files
|
|
77
|
+
except Exception:
|
|
78
|
+
pass
|
|
79
|
+
|
|
80
|
+
# Standard discovery
|
|
81
|
+
found_base: Path | None = None
|
|
82
|
+
for candidate in COMPOSE_FILE_CANDIDATES:
|
|
83
|
+
candidate_path = target / candidate
|
|
84
|
+
if candidate_path.is_file():
|
|
85
|
+
found_base = candidate_path
|
|
86
|
+
break
|
|
87
|
+
|
|
88
|
+
if found_base is not None:
|
|
89
|
+
files = [found_base]
|
|
90
|
+
for ov_name in ("compose.override.yaml", "compose.override.yml", "docker-compose.override.yaml", "docker-compose.override.yml"):
|
|
91
|
+
ov_path = target / ov_name
|
|
92
|
+
if ov_path.is_file():
|
|
93
|
+
files.append(ov_path)
|
|
94
|
+
break
|
|
95
|
+
return target, files
|
|
96
|
+
|
|
97
|
+
candidates_str = ", ".join(COMPOSE_FILE_CANDIDATES)
|
|
98
|
+
raise ComposeFileNotFoundError(
|
|
99
|
+
f"No Compose file found in directory '{target}'. Searched for: {candidates_str}"
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
raise ComposeFileNotFoundError(f"Target is neither a file nor a directory: {target}")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _build_safe_env() -> dict[str, str]:
|
|
106
|
+
"""Constructs a minimal, sanitized environment for Docker Compose execution.
|
|
107
|
+
|
|
108
|
+
Avoids passing arbitrary application environment variables that might contain
|
|
109
|
+
secrets or alter compose interpolation unintentionally, while retaining
|
|
110
|
+
necessary system paths and Docker host/context variables.
|
|
111
|
+
"""
|
|
112
|
+
allowed_keys = {
|
|
113
|
+
# System & execution paths
|
|
114
|
+
"PATH",
|
|
115
|
+
"PATHEXT",
|
|
116
|
+
"SYSTEMROOT",
|
|
117
|
+
"SYSTEMDRIVE",
|
|
118
|
+
"WINDIR",
|
|
119
|
+
"COMSPEC",
|
|
120
|
+
"TEMP",
|
|
121
|
+
"TMP",
|
|
122
|
+
# User home & profile
|
|
123
|
+
"USER",
|
|
124
|
+
"USERNAME",
|
|
125
|
+
"HOME",
|
|
126
|
+
"USERPROFILE",
|
|
127
|
+
"HOMEPATH",
|
|
128
|
+
"HOMEDRIVE",
|
|
129
|
+
"APPDATA",
|
|
130
|
+
"LOCALAPPDATA",
|
|
131
|
+
# Platform program directories (required for Docker CLI plugin discovery)
|
|
132
|
+
"PROGRAMFILES",
|
|
133
|
+
"PROGRAMFILES(X86)",
|
|
134
|
+
"PROGRAMDATA",
|
|
135
|
+
"COMMONPROGRAMFILES",
|
|
136
|
+
# Docker configuration & context
|
|
137
|
+
"DOCKER_HOST",
|
|
138
|
+
"DOCKER_CONFIG",
|
|
139
|
+
"DOCKER_CONTEXT",
|
|
140
|
+
"DOCKER_CERT_PATH",
|
|
141
|
+
"DOCKER_TLS_VERIFY",
|
|
142
|
+
"DOCKER_CLI_PLUGIN_PATH",
|
|
143
|
+
}
|
|
144
|
+
return {k: v for k, v in os.environ.items() if k in allowed_keys}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def collect_compose_config(
|
|
148
|
+
project_dir: str | Path,
|
|
149
|
+
compose_file: str | Path | Sequence[str | Path],
|
|
150
|
+
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
|
|
151
|
+
max_bytes: int = DEFAULT_OUTPUT_LIMIT,
|
|
152
|
+
) -> dict[str, Any]:
|
|
153
|
+
"""Invokes `docker compose config --format json` and returns the parsed model.
|
|
154
|
+
|
|
155
|
+
Safety controls applied:
|
|
156
|
+
- Fixed argument list; shell=False.
|
|
157
|
+
- Explicit working/project directory and file options.
|
|
158
|
+
- Sanitized inherited environment.
|
|
159
|
+
- Hard bounded output buffer to prevent memory exhaustion.
|
|
160
|
+
- Strict execution timeout.
|
|
161
|
+
- Sanitized error reporting without raw secret echoing.
|
|
162
|
+
"""
|
|
163
|
+
p_dir = Path(project_dir).resolve()
|
|
164
|
+
|
|
165
|
+
cmd = [
|
|
166
|
+
"docker",
|
|
167
|
+
"compose",
|
|
168
|
+
"--project-directory",
|
|
169
|
+
str(p_dir),
|
|
170
|
+
]
|
|
171
|
+
|
|
172
|
+
if isinstance(compose_file, (list, tuple)):
|
|
173
|
+
for f in compose_file:
|
|
174
|
+
cmd.extend(["-f", str(Path(f).resolve())])
|
|
175
|
+
else:
|
|
176
|
+
cmd.extend(["-f", str(Path(compose_file).resolve())])
|
|
177
|
+
|
|
178
|
+
cmd.extend(["config", "--format", "json"])
|
|
179
|
+
|
|
180
|
+
try:
|
|
181
|
+
proc = subprocess.Popen(
|
|
182
|
+
cmd,
|
|
183
|
+
stdout=subprocess.PIPE,
|
|
184
|
+
stderr=subprocess.PIPE,
|
|
185
|
+
env=_build_safe_env(),
|
|
186
|
+
cwd=str(p_dir),
|
|
187
|
+
)
|
|
188
|
+
except FileNotFoundError as exc:
|
|
189
|
+
raise ComposeExecutionError(
|
|
190
|
+
"The 'docker' executable was not found on PATH. Ensure Docker Compose is installed."
|
|
191
|
+
) from exc
|
|
192
|
+
except Exception as exc:
|
|
193
|
+
raise ComposeExecutionError("Failed to spawn docker compose subprocess.") from exc
|
|
194
|
+
|
|
195
|
+
try:
|
|
196
|
+
# Bounded read to avoid memory exhaustion
|
|
197
|
+
stdout_bytes, stderr_bytes = proc.communicate(timeout=timeout_seconds)
|
|
198
|
+
except subprocess.TimeoutExpired:
|
|
199
|
+
proc.kill()
|
|
200
|
+
proc.wait()
|
|
201
|
+
raise ComposeExecutionError(
|
|
202
|
+
f"Command 'docker compose config' timed out after {timeout_seconds}s."
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
if len(stdout_bytes) > max_bytes:
|
|
206
|
+
raise ComposeOutputLimitExceededError(
|
|
207
|
+
f"Compose configuration output exceeded limit of {max_bytes} bytes."
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
if proc.returncode != 0:
|
|
211
|
+
# Sanitize stderr: do not print raw output that might echo environment values
|
|
212
|
+
# Extract generic summary line if available without secret leakage
|
|
213
|
+
err_msg = (
|
|
214
|
+
f"docker compose config exited with status {proc.returncode}."
|
|
215
|
+
)
|
|
216
|
+
raise ComposeExecutionError(err_msg)
|
|
217
|
+
|
|
218
|
+
try:
|
|
219
|
+
data = json.loads(stdout_bytes.decode("utf-8"))
|
|
220
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
221
|
+
raise ComposeExecutionError("Invalid JSON returned by docker compose config.") from exc
|
|
222
|
+
|
|
223
|
+
if not isinstance(data, dict):
|
|
224
|
+
raise ComposeExecutionError("Root of Compose config JSON must be an object.")
|
|
225
|
+
|
|
226
|
+
return data
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def load_compose_json_file(file_path: str | Path, max_bytes: int = DEFAULT_OUTPUT_LIMIT) -> dict[str, Any]:
|
|
230
|
+
"""Loads a pre-rendered Compose configuration JSON file (useful for offline testing)."""
|
|
231
|
+
p = Path(file_path).resolve()
|
|
232
|
+
if not p.is_file():
|
|
233
|
+
raise ComposeFileNotFoundError(f"JSON fixture file not found: {p}")
|
|
234
|
+
|
|
235
|
+
with p.open("rb") as stream:
|
|
236
|
+
raw = stream.read(max_bytes + 1)
|
|
237
|
+
|
|
238
|
+
if len(raw) > max_bytes:
|
|
239
|
+
raise ComposeOutputLimitExceededError(
|
|
240
|
+
f"JSON fixture file exceeded limit of {max_bytes} bytes: {p}"
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
try:
|
|
244
|
+
data = json.loads(raw.decode("utf-8"))
|
|
245
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
246
|
+
raise ComposeExecutionError(f"Invalid JSON in fixture: {p.name}") from exc
|
|
247
|
+
|
|
248
|
+
if not isinstance(data, dict):
|
|
249
|
+
raise ComposeExecutionError(f"Root of Compose config JSON must be an object: {p.name}")
|
|
250
|
+
|
|
251
|
+
return data
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Environment creation module for isolation-check."""
|