my-homelab-configs/tests/jeannie/test_oci_foundation_resolve.py

242 lines
13 KiB
Python

"""Offline regressions. Execute on Debian, without OCI or SSH access."""
import contextlib
import importlib.util
import io
import json
import os
from pathlib import Path
import subprocess
from types import SimpleNamespace
import tempfile
import unittest
from unittest.mock import patch
SOURCE = Path(__file__).resolve().parents[2] / "scripts/oci-foundation-resolve.py"
SPEC = importlib.util.spec_from_file_location("oci_resolver", SOURCE)
resolver = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(resolver)
class ResolverTests(unittest.TestCase):
def test_unconfigured_remote_client_does_not_create_files(self):
with tempfile.TemporaryDirectory() as directory, patch.dict(os.environ, {}, clear=True):
root = Path(directory)
config = root / ".config/homelab/oci-foundation.env"
with patch.object(Path, "home", return_value=root):
resolver.load(SimpleNamespace(config=config, repo=root), set())
self.assertFalse(config.parent.exists())
def test_legacy_key_and_repeated_saves(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "config.env"
key = "ssh-ed25519" + "\\" * 15 + " AAAA" + "\\" * 15 + " operator"
path.write_text(': "${LAB_OCI_SSH_PUBLIC_KEY:=' + key +
'}"; export LAB_OCI_SSH_PUBLIC_KEY\n')
parsed = resolver.read_config(path, {"LAB_OCI_SSH_PUBLIC_KEY"})
for _ in range(3):
resolver.atomic_write(path, resolver.config_text(parsed))
parsed = resolver.read_config(path, {"LAB_OCI_SSH_PUBLIC_KEY"})
self.assertEqual(parsed["LAB_OCI_SSH_PUBLIC_KEY"], "ssh-ed25519 AAAA operator")
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
def test_config_never_executes(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "config.env"
marker = Path(directory) / "must-not-exist"
path.write_text("touch " + str(marker))
with self.assertRaises(ValueError):
resolver.read_config(path, set())
self.assertFalse(marker.exists())
def test_migration_and_repeat_load(self):
with tempfile.TemporaryDirectory() as directory, patch.dict(os.environ, {}, clear=True):
root = Path(directory)
config = root / ".config/homelab/oci-foundation.env"
config.parent.mkdir(parents=True)
fresh = config.with_name("oci-foundation-fresh.env")
state = root / "fresh.tfstate"
state.write_text(json.dumps({
"version": 4, "resources": [{
"mode": "managed", "type": "oci_core_instance", "name": "edge",
"instances": [{"index_key": 0, "attributes": {
"id": "ocid1.instance.current", "compartment_id": "ocid1.compartment.current",
"availability_domain": "AD-1", "shape": "VM.Standard.E2.1.Micro",
"public_ip": "192.0.2.10",
}}],
}],
}))
old = {"LAB_OCI_COMPUTE_ENABLED": "false", "LAB_EDGE_HOST": "192.0.2.1",
"LAB_OCI_BACKUP_BUCKET_ID": "n/test/b/backup"}
alternate = {"LAB_OCI_FOUNDATION_STATE_FILE": str(state),
"LAB_OCI_EDGE_INSTANCE_ID": "ocid1.instance.current",
"LAB_OCI_COMPUTE_ENABLED": "false"}
config.write_text(resolver.config_text(old))
fresh.write_text(resolver.config_text(alternate))
names = set(old) | set(alternate) | {
"LAB_OCI_EDGE_ENABLED", "LAB_OCI_EDGE_EXISTING_INSTANCE_ID",
"LAB_OCI_EDGE_INSTANCE_MANAGED", "LAB_OCI_EDGE_COMPARTMENT_ID",
"LAB_OCI_EDGE_AVAILABILITY_DOMAIN", "LAB_OCI_EDGE_SHAPE",
}
args = SimpleNamespace(config=config, repo=root)
with patch.object(Path, "home", return_value=root), contextlib.redirect_stdout(io.StringIO()):
resolver.load(args, names)
first = config.read_text()
resolver.load(args, names)
merged = resolver.read_config(config, names)
self.assertEqual(merged["LAB_OCI_FOUNDATION_STATE_FILE"], str(state))
self.assertEqual(merged["LAB_OCI_COMPUTE_ENABLED"], "true")
self.assertEqual(merged["LAB_EDGE_HOST"], "192.0.2.10")
self.assertEqual(merged["LAB_OCI_BACKUP_BUCKET_ID"], "n/test/b/backup")
self.assertFalse(fresh.exists())
self.assertEqual(config.read_text(), first)
self.assertTrue(list(config.parent.glob("oci-foundation-archive-*/oci-foundation.env")))
def test_discovery_rejects_ambiguity_and_access_errors(self):
with self.assertRaises(ValueError):
resolver.OCI.unique([{"id": "one"}, {"id": "two"}], "edge")
response = SimpleNamespace(returncode=1, stderr='{"status": 404, "code": "NotAuthorizedOrNotFound"}')
with patch("subprocess.run", return_value=response), self.assertRaises(ValueError):
resolver.OCI().call("compute", "instance", "get", "--instance-id", "recorded")
def test_managed_bastion_restores_identity_over_stale_scratch_inputs(self):
state = {"resources": [{
"mode": "managed", "type": "oci_bastion_bastion", "name": "homelab",
"instances": [{"index_key": 0, "attributes": {
"id": "ocid1.bastion.current", "name": "homelab-bastion",
"target_subnet_id": "ocid1.subnet.current", "bastion_type": "STANDARD",
}}],
}]}
values = {"LAB_OCI_BASTION_ENABLED": "false",
"LAB_OCI_BASTION_ID": "ocid1.bastion.stale",
"LAB_OCI_BASTION_NAME": "homelab-bastion-yruxcl7q",
"LAB_OCI_BASTION_TARGET_SUBNET_ID": "ocid1.subnet.stale"}
resolver.recorded(values, state)
self.assertEqual(values["LAB_OCI_STATE_BASTION_MANAGED"], "true")
self.assertEqual(values["LAB_OCI_BASTION_ENABLED"], "true")
self.assertEqual(values["LAB_OCI_BASTION_ID"], "ocid1.bastion.current")
self.assertEqual(values["LAB_OCI_BASTION_NAME"], "homelab-bastion")
self.assertEqual(values["LAB_OCI_BASTION_TARGET_SUBNET_ID"], "ocid1.subnet.current")
first = dict(values)
resolver.recorded(values, state)
self.assertEqual(values, first)
def test_notifications_topic_id_is_normalized_for_get_and_list(self):
topic = {"topic-id": "ocid1.onstopic.existing", "name": "homelab-monitoring",
"compartment-id": "ocid1.compartment.existing", "lifecycle-state": "ACTIVE"}
for operation, data in (("get", topic), ("list", [topic])):
with self.subTest(operation=operation):
response = SimpleNamespace(returncode=0, stdout=json.dumps({"data": data}))
with patch("subprocess.run", return_value=response):
result = resolver.OCI().call("ons", "topic", operation)
rows = result if isinstance(result, list) else [result]
selected = resolver.OCI.unique(rows, "monitoring topic")
self.assertEqual(resolver.object_id(selected, "topic"), "ocid1.onstopic.existing")
self.assertEqual(selected["compartment-id"], topic["compartment-id"])
def test_missing_identifier_reports_a_schema_error(self):
response = SimpleNamespace(returncode=0, stdout='{"data": {"name": "invalid-topic"}}')
with patch("subprocess.run", return_value=response), self.assertRaisesRegex(
ValueError, "no resource identifier"
):
resolver.OCI().call("ons", "topic", "get")
with self.assertRaisesRegex(ValueError, "no resource identifier"):
resolver.OCI.unique([{"name": "invalid-resource"}], "resource")
def test_successful_empty_list_output_is_normalized(self):
for output in ("", " \n", '{"data": []}', '{"data": null}',
'{"data": {"items": []}}', '{"opc-total-items": 0}'):
with self.subTest(output=output):
response = SimpleNamespace(returncode=0, stdout=output, stderr="API key label warning")
with patch("subprocess.run", return_value=response) as command:
result = resolver.OCI().call("monitoring", "alarm", "list", "--all")
self.assertEqual(result, [])
self.assertEqual(command.call_args.args[0][-4:], ["--output", "json", "--query", "@"])
def test_empty_get_and_malformed_output_are_errors_with_command_context(self):
for operation, output in (("get", ""), ("list", "<html>gateway error</html>"),
("list", '{"unexpected": []}')):
with self.subTest(operation=operation, output=output):
response = SimpleNamespace(returncode=0, stdout=output, stderr="diagnostic")
with patch("subprocess.run", return_value=response), self.assertRaisesRegex(
ValueError, "monitoring alarm " + operation
):
resolver.OCI().call("monitoring", "alarm", operation)
def test_failed_empty_list_remains_an_error(self):
response = SimpleNamespace(returncode=1, stdout="", stderr="NotAuthorizedOrNotFound")
with patch("subprocess.run", return_value=response), self.assertRaisesRegex(
ValueError, "NotAuthorizedOrNotFound"
):
resolver.OCI().call("monitoring", "alarm", "list")
def test_edge_separates_dns_and_ssh(self):
client = SimpleNamespace(
instance=lambda role: {"id": "ocid1.instance.current", "compartment-id": "owner",
"lifecycle-state": "RUNNING"},
vnic=lambda vm: {"public-ip": "192.0.2.10", "private-ip": "10.50.10.103"},
)
peers = {"Peer": {"peer": {"HostName": "homelab-oci-edge", "Online": True,
"TailscaleIPs": ["100.64.0.10"]}}}
response = SimpleNamespace(stdout=json.dumps(peers))
output = io.StringIO()
with patch.dict(os.environ, {}, clear=True), patch.object(resolver, "OCI", return_value=client), \
patch("subprocess.run", return_value=response), contextlib.redirect_stdout(output):
resolver.resolve_edge()
self.assertIn("export TF_VAR_edge_host=192.0.2.10", output.getvalue())
self.assertIn("export TF_VAR_edge_ssh_host=100.64.0.10", output.getvalue())
def test_shell_tailnet_transport_bypasses_enabled_bastion_and_stale_proxy(self):
# Exercise the actual guard called by edge_apply and route setup.
# Only shell function definitions and argument construction run here.
shell = r"""
set -euo pipefail
source "$1"
LAB_OCI_BASTION_ENABLED=true
LAB_OCI_BASTION_ID=ocid1.bastion.existing
LAB_EDGE_SSH_TRANSPORT=tailscale
LAB_EDGE_TAILSCALE_IP=100.122.188.79
TF_VAR_edge_ssh_host=100.122.188.79
LAB_OCI_EDGE_BASTION_PROXY_COMMAND='ssh stale-bastion'
edge_require_ssh_transport
edge_ssh_args
printf '%s\n' "${EDGE_SSH_ARGS[@]}"
"""
result = subprocess.run(["bash", "-c", shell, "test",
str(SOURCE.parents[1] / "lib/jeannie/pipeline.sh")],
capture_output=True, text=True, check=True)
self.assertIn("ProxyCommand=none", result.stdout)
self.assertIn("ProxyJump=none", result.stdout)
self.assertNotIn("stale-bastion", result.stdout)
def test_shell_bastion_transport_still_requires_a_session(self):
shell = r"""
set -euo pipefail
source "$1"
LAB_EDGE_SSH_TRANSPORT=bastion
TF_VAR_edge_ssh_host=10.50.10.103
unset LAB_OCI_EDGE_BASTION_PROXY_COMMAND
if edge_require_ssh_transport; then exit 99; fi
LAB_OCI_EDGE_BASTION_PROXY_COMMAND='ssh session@bastion -W %h:%p'
edge_require_ssh_transport
edge_ssh_args
printf '%s\n' "${EDGE_SSH_ARGS[@]}"
"""
result = subprocess.run(["bash", "-c", shell, "test",
str(SOURCE.parents[1] / "lib/jeannie/pipeline.sh")],
capture_output=True, text=True, check=True)
self.assertIn("route/session is not ready", result.stderr)
self.assertIn("ProxyCommand=ssh session@bastion", result.stdout)
self.assertNotIn("ProxyCommand=none", result.stdout)
def test_plan_rejects_delete_and_replacement(self):
for actions in (["delete"], ["delete", "create"], ["create", "delete"]):
with self.subTest(actions=actions), self.assertRaises(ValueError):
resolver.validate_plan({"resource_changes": [
{"address": "oci_core_instance.edge[0]", "change": {"actions": actions}}]})
resolver.validate_plan({"resource_changes": [
{"address": "new", "change": {"actions": ["create"]}}]})
if __name__ == "__main__":
unittest.main()