fix(engine): unify manifest parsing with core_manifest and fail closed on errors
- Delegate workload manifest parsing strictly to core_manifest.parse_manifest - Remove duplicate SourceConfig and HomepageConfig dataclasses in appctl_engine - Fail closed in cmd_resolve on corrupted manifests or missing app.yaml - Display manifest errors explicitly in cmd_list and cmd_info without fallback - Add unit tests verifying schema delegation, env validation, and fail-closed resolution
This commit is contained in:
1 parent
93feb0d3f2
commit
5ed61acf32
3 files changed
+197
-156
No files matched your search
+111
-155
@@ -19,7 +19,13 @@ from pathlib import Path
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import yaml
|
import yaml
|
||||||
from core_manifest import Manifest, ManifestValidationError, parse_manifest
|
from core_manifest import (
|
||||||
|
HomepageConfig,
|
||||||
|
Manifest,
|
||||||
|
ManifestValidationError,
|
||||||
|
SourceConfig,
|
||||||
|
parse_manifest,
|
||||||
|
)
|
||||||
from provenance import (
|
from provenance import (
|
||||||
get_local_checkout_status,
|
get_local_checkout_status,
|
||||||
inspect_workload_two_axis,
|
inspect_workload_two_axis,
|
||||||
@@ -64,39 +70,15 @@ def validate_environment() -> None:
|
|||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
class ManifestError(Exception):
|
ManifestError = ManifestValidationError
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class HomepageConfig:
|
|
||||||
title: str
|
|
||||||
group: str = "Applications"
|
|
||||||
icon: str = "default.png"
|
|
||||||
container: str = ""
|
|
||||||
weight: int = 50
|
|
||||||
|
|
||||||
def to_dict(self) -> dict[str, Any]:
|
|
||||||
return asdict(self)
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class SourceConfig:
|
|
||||||
"""Upstream source provenance descriptor."""
|
|
||||||
type: str = "git" # "git"
|
|
||||||
url: str = "" # e.g., "https://git.roadtotech.me/kiskaadee/bitetrack.git"
|
|
||||||
ref: str = "main" # Branch (e.g. "main"), tag (e.g. "v1.0.0"), or commit SHA
|
|
||||||
|
|
||||||
def to_dict(self) -> dict[str, Any]:
|
|
||||||
return asdict(self)
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class App:
|
class App:
|
||||||
name: str # Canonical identifier (e.g., "traefik", "jellyfin")
|
name: str # Canonical identifier (e.g., "traefik", "jellyfin")
|
||||||
description: str # Human-readable summary for dashboards and CLI info
|
description: str = "" # Human-readable summary for dashboards and CLI info
|
||||||
domain: str # Routing FQDN (e.g., "auth.roadtotech.me") or "internal".
|
domain: str = "" # Routing FQDN (e.g., "auth.roadtotech.me") or "internal".
|
||||||
dir_path: str # Filesystem directory (CORE_DIR for Core, or ~/Sites/<app> for Sites).
|
dir_path: str = "" # Filesystem directory (CORE_DIR for Core, or ~/Sites/<app> for Sites).
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def is_internal(self) -> bool:
|
def is_internal(self) -> bool:
|
||||||
@@ -131,116 +113,74 @@ class SitesApp(App):
|
|||||||
env: dict[str, Any] = field(default_factory=dict) # Environment variable overrides
|
env: dict[str, Any] = field(default_factory=dict) # Environment variable overrides
|
||||||
homepage: HomepageConfig | None = None # Dashboard Card Configuration
|
homepage: HomepageConfig | None = None # Dashboard Card Configuration
|
||||||
manifest_error: str | None = None # Captured syntax/loading errors
|
manifest_error: str | None = None # Captured syntax/loading errors
|
||||||
|
manifest_obj: Manifest | None = None # Parsed authoritative Manifest
|
||||||
app_type: str = "app"
|
app_type: str = "app"
|
||||||
|
|
||||||
|
def to_dict(self) -> dict[str, Any]:
|
||||||
def load_manifest(manifest_path: str) -> dict[str, Any]:
|
"""Serialize for JSON consumption by scripts/appctl"""
|
||||||
"""Load and parse the app manifest file."""
|
data = asdict(self)
|
||||||
if not os.path.isfile(manifest_path):
|
data.pop("manifest_obj", None)
|
||||||
raise FileNotFoundError(f"Manifest file not found at {manifest_path}")
|
data["type"] = getattr(self, "app_type", "app")
|
||||||
|
return data
|
||||||
try:
|
|
||||||
with open(manifest_path, "r", encoding="utf-8") as file:
|
|
||||||
manifest_data = yaml.safe_load(file) or {}
|
|
||||||
except (yaml.YAMLError, OSError) as err:
|
|
||||||
raise ManifestError(f"YAML parsing failed: {err}") from err
|
|
||||||
|
|
||||||
if not isinstance(manifest_data, dict):
|
|
||||||
raise ManifestError(f"Invalid manifest root: expected `dict`, got `{type(manifest_data).__name__}`")
|
|
||||||
|
|
||||||
return manifest_data
|
|
||||||
|
|
||||||
|
|
||||||
def sites_app_from_manifest(
|
def sites_app_from_manifest(
|
||||||
app_dir: str,
|
app_dir: str,
|
||||||
manifest: dict[str, Any],
|
manifest: Manifest | dict[str, Any] | None = None,
|
||||||
manifest_error: str | None = None,
|
manifest_error: str | None = None,
|
||||||
) -> SitesApp:
|
) -> SitesApp:
|
||||||
"""Construct and normalize a SitesApp domain model from raw manifest data."""
|
"""Construct and normalize a SitesApp domain model from an authoritative Manifest or raw data."""
|
||||||
raw_dir_name = os.path.basename(app_dir)
|
raw_dir_name = os.path.basename(app_dir)
|
||||||
canonical_name = str(manifest.get("name") or raw_dir_name.replace("homelab-", ""))
|
|
||||||
|
|
||||||
# Normalize aliases into list[str]
|
if isinstance(manifest, Manifest):
|
||||||
raw_aliases = manifest.get("aliases") or []
|
has_compose = (
|
||||||
if isinstance(raw_aliases, str):
|
os.path.isfile(os.path.join(app_dir, "docker-compose.yaml")) or
|
||||||
aliases = [raw_aliases]
|
os.path.isfile(os.path.join(app_dir, "docker-compose.yml"))
|
||||||
elif isinstance(raw_aliases, list):
|
)
|
||||||
aliases = [str(alias) for alias in raw_aliases]
|
canonical_name = manifest.name
|
||||||
else:
|
domain = manifest.domain or f"{canonical_name}.{HOMELAB_DOMAIN}"
|
||||||
aliases = []
|
return SitesApp(
|
||||||
|
name=canonical_name,
|
||||||
# Homepage card normalization
|
dir_name=raw_dir_name,
|
||||||
homepage_config: HomepageConfig | None = None
|
source=manifest.source,
|
||||||
raw_hp = manifest.get("homepage")
|
description=manifest.description,
|
||||||
if isinstance(raw_hp, dict):
|
domain=domain,
|
||||||
homepage_config = HomepageConfig(
|
dir_path=app_dir,
|
||||||
title=str(raw_hp.get("title") or canonical_name),
|
has_compose=has_compose,
|
||||||
group=str(raw_hp.get("group") or "Applications"),
|
aliases=list(manifest.aliases),
|
||||||
icon=str(raw_hp.get("icon") or "default.png"),
|
visible=manifest.visible,
|
||||||
container=str(raw_hp.get("container") or canonical_name),
|
auth=manifest.auth,
|
||||||
weight=int(raw_hp.get("weight", 50)),
|
networks=list(manifest.networks),
|
||||||
|
env=dict(manifest.env),
|
||||||
|
homepage=manifest.homepage,
|
||||||
|
manifest_error=manifest_error,
|
||||||
|
manifest_obj=manifest,
|
||||||
)
|
)
|
||||||
|
|
||||||
has_compose = (
|
if isinstance(manifest, dict):
|
||||||
os.path.isfile(os.path.join(app_dir, "docker-compose.yaml")) or
|
try:
|
||||||
os.path.isfile(os.path.join(app_dir, "docker-compose.yml"))
|
parsed = parse_manifest(manifest)
|
||||||
)
|
return sites_app_from_manifest(app_dir, parsed, manifest_error)
|
||||||
|
except ManifestValidationError as err:
|
||||||
# Manifest Data parsing
|
manifest_error = f"{manifest_error}; {err}" if manifest_error else str(err)
|
||||||
raw_desc = manifest.get("description")
|
canonical_name = str(manifest.get("name") or raw_dir_name.replace("homelab-", ""))
|
||||||
app_desc: str = str(raw_desc) if raw_desc is not None else ""
|
return SitesApp(
|
||||||
|
name=canonical_name,
|
||||||
raw_dom = manifest.get("domain")
|
dir_name=raw_dir_name,
|
||||||
app_dom = str(raw_dom) if raw_dom is not None else f"{canonical_name}.{HOMELAB_DOMAIN}"
|
domain=f"{canonical_name}.{HOMELAB_DOMAIN}",
|
||||||
|
description=str(manifest.get("description", "")),
|
||||||
app_net = manifest.get("networks")
|
dir_path=app_dir,
|
||||||
if not isinstance(app_net, list):
|
manifest_error=manifest_error,
|
||||||
app_net = ["proxy-net"]
|
)
|
||||||
|
|
||||||
app_env = manifest.get("env")
|
|
||||||
if not isinstance(app_env, dict):
|
|
||||||
app_env = {}
|
|
||||||
|
|
||||||
def _as_bool(value: Any, default: bool) -> bool:
|
|
||||||
if isinstance(value, bool):
|
|
||||||
return value
|
|
||||||
return default
|
|
||||||
|
|
||||||
app_vis = _as_bool(manifest.get("visible"), True)
|
|
||||||
app_auth = _as_bool(manifest.get("auth"), True)
|
|
||||||
|
|
||||||
# Source provenance normalization
|
|
||||||
source_config: SourceConfig | None = None
|
|
||||||
raw_source = manifest.get("source")
|
|
||||||
if isinstance(raw_source, dict):
|
|
||||||
source_url = str(raw_source.get("url") or "")
|
|
||||||
allowed_schemes = ("https://", "ssh://", "git@")
|
|
||||||
if source_url:
|
|
||||||
if not any(source_url.startswith(s) for s in allowed_schemes):
|
|
||||||
err = f"Invalid source.url scheme: must start with {', '.join(allowed_schemes)}"
|
|
||||||
manifest_error = f"{manifest_error}; {err}" if manifest_error else err
|
|
||||||
else:
|
|
||||||
source_config = SourceConfig(
|
|
||||||
type=str(raw_source.get("type") or "git"),
|
|
||||||
url=source_url,
|
|
||||||
ref=str(raw_source.get("ref") or "main"),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
canonical_name = raw_dir_name.replace("homelab-", "")
|
||||||
return SitesApp(
|
return SitesApp(
|
||||||
name=canonical_name,
|
name=canonical_name,
|
||||||
dir_name=raw_dir_name,
|
dir_name=raw_dir_name,
|
||||||
source=source_config,
|
description="",
|
||||||
description=app_desc,
|
domain=f"{canonical_name}.{HOMELAB_DOMAIN}",
|
||||||
domain=app_dom,
|
|
||||||
dir_path=app_dir,
|
dir_path=app_dir,
|
||||||
has_compose=has_compose,
|
manifest_error=manifest_error or "Missing app.yaml manifest",
|
||||||
aliases=aliases,
|
|
||||||
visible=app_vis,
|
|
||||||
auth=app_auth,
|
|
||||||
networks=app_net,
|
|
||||||
env=app_env,
|
|
||||||
homepage=homepage_config,
|
|
||||||
manifest_error=manifest_error,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -256,15 +196,36 @@ def get_sites_apps(sites_dir: str | None = None) -> list[SitesApp]:
|
|||||||
if entry.startswith(".") or not os.path.isdir(app_dir):
|
if entry.startswith(".") or not os.path.isdir(app_dir):
|
||||||
continue
|
continue
|
||||||
manifest_path = os.path.join(app_dir, "app.yaml")
|
manifest_path = os.path.join(app_dir, "app.yaml")
|
||||||
manifest: dict[str, Any] = {}
|
manifest_file = Path(manifest_path)
|
||||||
manifest_error: str | None = None
|
|
||||||
|
|
||||||
if os.path.isfile(manifest_path):
|
if not manifest_file.is_file():
|
||||||
try:
|
apps.append(
|
||||||
manifest = load_manifest(manifest_path=manifest_path)
|
sites_app_from_manifest(
|
||||||
except ManifestError as err:
|
app_dir=app_dir,
|
||||||
manifest_error = str(err)
|
manifest=None,
|
||||||
apps.append(sites_app_from_manifest(app_dir, manifest, manifest_error))
|
manifest_error="Missing app.yaml manifest",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
manifest_obj = parse_manifest(manifest_file)
|
||||||
|
apps.append(sites_app_from_manifest(app_dir=app_dir, manifest=manifest_obj))
|
||||||
|
except (ManifestValidationError, yaml.YAMLError, OSError, ValueError, KeyError) as err:
|
||||||
|
raw_data = None
|
||||||
|
with (
|
||||||
|
contextlib.suppress(Exception),
|
||||||
|
open(manifest_path, "r", encoding="utf-8") as f,
|
||||||
|
):
|
||||||
|
raw_data = yaml.safe_load(f)
|
||||||
|
app_dict = raw_data if isinstance(raw_data, dict) else {}
|
||||||
|
apps.append(
|
||||||
|
sites_app_from_manifest(
|
||||||
|
app_dir=app_dir,
|
||||||
|
manifest=app_dict,
|
||||||
|
manifest_error=str(err),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
return apps
|
return apps
|
||||||
|
|
||||||
@@ -728,24 +689,19 @@ def cmd_list(args: list[str]) -> None:
|
|||||||
app_path = Path(app.dir_path)
|
app_path = Path(app.dir_path)
|
||||||
docker_status = get_docker_status(app_path)
|
docker_status = get_docker_status(app_path)
|
||||||
|
|
||||||
manifest_file = app_path / "app.yaml"
|
if app.manifest_error:
|
||||||
if manifest_file.is_file():
|
dep_str = "⚠️ Manifest Error"
|
||||||
try:
|
prov_str = "⚠️ Invalid Manifest"
|
||||||
manifest_obj = parse_manifest(manifest_file)
|
|
||||||
except (ManifestValidationError, yaml.YAMLError, OSError, ValueError, KeyError):
|
|
||||||
manifest_obj = Manifest(name=app.name, domain=app.domain)
|
|
||||||
else:
|
else:
|
||||||
manifest_obj = Manifest(name=app.name, domain=app.domain)
|
manifest_obj = app.manifest_obj or Manifest(name=app.name, domain=app.domain)
|
||||||
|
two_axis = inspect_workload_two_axis(
|
||||||
two_axis = inspect_workload_two_axis(
|
app_dir=app_path,
|
||||||
app_dir=app_path,
|
manifest=manifest_obj,
|
||||||
manifest=manifest_obj,
|
fetch_upstream=should_fetch,
|
||||||
fetch_upstream=should_fetch,
|
docker_status=docker_status,
|
||||||
docker_status=docker_status,
|
)
|
||||||
)
|
dep_str = two_axis.checkout.status_label
|
||||||
|
prov_str = two_axis.provenance.status.value
|
||||||
dep_str = two_axis.checkout.status_label
|
|
||||||
prov_str = two_axis.provenance.status.value
|
|
||||||
|
|
||||||
if show_ssl:
|
if show_ssl:
|
||||||
cert_info = ssl_data.get(app.domain, check_ssl_cert(app.domain))
|
cert_info = ssl_data.get(app.domain, check_ssl_cert(app.domain))
|
||||||
@@ -816,15 +772,12 @@ def cmd_info(args: list[str]) -> None:
|
|||||||
print(f"Auth Protected: {app.auth}")
|
print(f"Auth Protected: {app.auth}")
|
||||||
print(f"Dashboard: {'Visible' if app.visible else 'Hidden'}")
|
print(f"Dashboard: {'Visible' if app.visible else 'Hidden'}")
|
||||||
|
|
||||||
|
if app.manifest_error:
|
||||||
|
print(f"\n⚠️ Manifest Validation Error:\n {app.manifest_error}")
|
||||||
|
return
|
||||||
|
|
||||||
app_path = Path(app.dir_path)
|
app_path = Path(app.dir_path)
|
||||||
manifest_file = app_path / "app.yaml"
|
manifest_obj = app.manifest_obj or Manifest(name=app.name, domain=app.domain)
|
||||||
if manifest_file.is_file():
|
|
||||||
try:
|
|
||||||
manifest_obj = parse_manifest(manifest_file)
|
|
||||||
except (ManifestValidationError, yaml.YAMLError, OSError, ValueError, KeyError):
|
|
||||||
manifest_obj = Manifest(name=app.name, domain=app.domain)
|
|
||||||
else:
|
|
||||||
manifest_obj = Manifest(name=app.name, domain=app.domain)
|
|
||||||
|
|
||||||
two_axis = inspect_workload_two_axis(
|
two_axis = inspect_workload_two_axis(
|
||||||
app_dir=app_path,
|
app_dir=app_path,
|
||||||
@@ -869,6 +822,9 @@ def cmd_resolve(args: list[str]) -> None:
|
|||||||
app = resolve_app(args[0])
|
app = resolve_app(args[0])
|
||||||
if not app:
|
if not app:
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
if isinstance(app, SitesApp) and app.manifest_error:
|
||||||
|
print(f"❌ Error: Workload '{app.name}' has invalid manifest: {app.manifest_error}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
print(json.dumps(app.to_dict()))
|
print(json.dumps(app.to_dict()))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -102,7 +102,7 @@ def validate_transport(url: str) -> tuple[TransportScheme, str]:
|
|||||||
raise ManifestValidationError(f"Insecure HTTP source URL rejected (HTTPS or SSH required): '{clean_url}'")
|
raise ManifestValidationError(f"Insecure HTTP source URL rejected (HTTPS or SSH required): '{clean_url}'")
|
||||||
|
|
||||||
raise ManifestValidationError(
|
raise ManifestValidationError(
|
||||||
f"Unsupported source URL scheme: '{clean_url}'. "
|
f"Invalid source.url scheme: '{clean_url}'. "
|
||||||
"Allowed transports are https://, ssh://, or git@<host>:<path>."
|
"Allowed transports are https://, ssh://, or git@<host>:<path>."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -378,3 +378,88 @@ def test_resolve_core_stack_type():
|
|||||||
assert traefik is not None
|
assert traefik is not None
|
||||||
assert traefik.to_dict()["type"] == "core_service"
|
assert traefik.to_dict()["type"] == "core_service"
|
||||||
assert traefik.container == "traefik"
|
assert traefik.container == "traefik"
|
||||||
|
|
||||||
|
|
||||||
|
def test_manifest_parsing_delegates_to_core_manifest_and_validates_env(app_factory: AppFactory):
|
||||||
|
"""Ensure manifest parsing uses core_manifest and catches invalid env keys."""
|
||||||
|
app_factory.create(
|
||||||
|
dir_name="homelab-badenv",
|
||||||
|
manifest_yaml="""
|
||||||
|
name: badenv
|
||||||
|
env:
|
||||||
|
PATH: /override/bin
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
apps = engine.get_sites_apps()
|
||||||
|
app = engine.resolve_app("badenv", apps)
|
||||||
|
assert app is not None
|
||||||
|
assert app.manifest_error is not None
|
||||||
|
assert "Invalid or reserved environment variable key" in app.manifest_error
|
||||||
|
|
||||||
|
|
||||||
|
def test_cmd_resolve_fails_closed_on_manifest_error(app_factory: AppFactory, capsys: pytest.CaptureFixture):
|
||||||
|
"""Ensure cmd_resolve exits with non-zero on workload with manifest errors."""
|
||||||
|
app_factory.create(
|
||||||
|
dir_name="homelab-corrupt",
|
||||||
|
manifest_yaml="""
|
||||||
|
name: corrupt
|
||||||
|
env:
|
||||||
|
ILLEGAL-KEY: forbidden
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
with pytest.raises(SystemExit) as exc_info:
|
||||||
|
engine.cmd_resolve(["corrupt"])
|
||||||
|
assert exc_info.value.code != 0
|
||||||
|
captured = capsys.readouterr()
|
||||||
|
assert "invalid manifest" in captured.err.lower() or "error" in captured.err.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def test_cmd_resolve_fails_closed_on_missing_app_yaml(mock_sites_dir: Path):
|
||||||
|
"""Ensure cmd_resolve exits with non-zero if workload has no app.yaml."""
|
||||||
|
no_manifest_dir = mock_sites_dir / "homelab-nomanifest"
|
||||||
|
no_manifest_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
with pytest.raises(SystemExit) as exc_info:
|
||||||
|
engine.cmd_resolve(["nomanifest"])
|
||||||
|
assert exc_info.value.code != 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_unification_uses_core_manifest_dataclasses(app_factory: AppFactory):
|
||||||
|
"""Ensure SitesApp uses core_manifest SourceConfig and HomepageConfig."""
|
||||||
|
import core_manifest
|
||||||
|
|
||||||
|
app_factory.create(
|
||||||
|
dir_name="homelab-unified",
|
||||||
|
manifest_yaml="""
|
||||||
|
name: unified
|
||||||
|
source:
|
||||||
|
url: https://git.roadtotech.me/kiskaadee/unified.git
|
||||||
|
ref: v1.0.0
|
||||||
|
homepage:
|
||||||
|
title: Unified App
|
||||||
|
weight: 30
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
apps = engine.get_sites_apps()
|
||||||
|
app = engine.resolve_app("unified", apps)
|
||||||
|
assert app is not None
|
||||||
|
assert isinstance(app.source, core_manifest.SourceConfig)
|
||||||
|
assert isinstance(app.homepage, core_manifest.HomepageConfig)
|
||||||
|
assert app.source.ref_type == core_manifest.RefType.TAG
|
||||||
|
assert app.source.transport == core_manifest.TransportScheme.HTTPS
|
||||||
|
|
||||||
|
|
||||||
|
def test_cmd_list_flags_manifest_error(app_factory: AppFactory, capsys: pytest.CaptureFixture):
|
||||||
|
"""Ensure cmd_list flags workloads with manifest errors instead of swallowing them."""
|
||||||
|
app_factory.create(
|
||||||
|
dir_name="homelab-broken",
|
||||||
|
manifest_yaml="""
|
||||||
|
name: broken
|
||||||
|
env:
|
||||||
|
SHELL: /bin/sh
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
engine.cmd_list([])
|
||||||
|
captured = capsys.readouterr()
|
||||||
|
assert "Manifest Error" in captured.out
|
||||||
|
|
||||||
Reference in new issue
Block a user