From f86ce21ee0ef919209198b122db81aa81d6fa092 Mon Sep 17 00:00:00 2001 From: Fede Luzzi Date: Tue, 17 Nov 2026 16:31:05 -0300 Subject: [PATCH] feat(spec-05-auth-fallback-chain): worker (eng_flash_medium) implementation --- connpy/auth_utils.py | 16 +++- connpy/cli/forms.py | 15 +++- connpy/cli/validators.py | 16 +++- connpy/tests/test_auth_fallback_chain.py | 96 ++++++++++++++++++++++++ 4 files changed, 134 insertions(+), 9 deletions(-) diff --git a/connpy/auth_utils.py b/connpy/auth_utils.py index b0a22b4..bbaa606 100644 --- a/connpy/auth_utils.py +++ b/connpy/auth_utils.py @@ -852,9 +852,17 @@ def validate_fallback_entries( return [] if stripped.startswith(("[", "{")): parsed = validate_json_depth_and_size(stripped) + elif stripped.startswith("compose:"): + validate_compose_syntax(stripped) + return [stripped] + elif stripped.startswith("@") and not stripped.startswith("@@") and "," in stripped: + parts = [p.strip() for p in stripped.split(",")] + if not parts or any(not _is_profile_ref(p) for p in parts): + raise ValueError( + "Comma-separated fallback entries must be valid @profile references" + ) + parsed = parts else: - if stripped.startswith("compose:"): - validate_compose_syntax(stripped) return [stripped] if isinstance(parsed, dict): @@ -1114,6 +1122,10 @@ def _extract_profile_refs_internal(value: Any, seen: set[int]) -> set[str]: refs.update(extract_compose_profile_refs(stripped)) elif stripped.startswith("@") and _PROFILE_REF_BODY_RE.fullmatch(stripped[1:]): refs.add(stripped[1:]) + elif stripped.startswith("@") and not stripped.startswith("@@") and "," in stripped: + parts = [p.strip() for p in stripped.split(",")] + if parts and all(_is_profile_ref(p) for p in parts): + refs.update(p[1:] for p in parts) elif ( stripped.startswith(("[", "{")) and len(stripped) <= MAX_JSON_INPUT_BYTES diff --git a/connpy/cli/forms.py b/connpy/cli/forms.py index 476f55d..6ee5f23 100644 --- a/connpy/cli/forms.py +++ b/connpy/cli/forms.py @@ -55,7 +55,14 @@ def _parse_fallback_input(raw_fb): max_depth=MAX_JSON_INPUT_DEPTH, ) return validate_fallback_entries(parsed, max_entries=MAX_FALLBACK_ENTRIES) - validate_fallback_entries(stripped, max_entries=MAX_FALLBACK_ENTRIES) + validated = validate_fallback_entries(stripped, max_entries=MAX_FALLBACK_ENTRIES) + if ( + stripped.startswith("@") + and not stripped.startswith("@@") + and "," in stripped + and not stripped.startswith("compose:") + ): + return validated return stripped validate_json_depth_and_size( raw_fb, @@ -166,7 +173,7 @@ class Forms: fbq = [ inquirer.Text( "fallback", - message="Add fallback credentials (JSON list/dict, @profile, or compose:)", + message="Add fallback credentials (@profile, @p1,@p2, JSON list/dict, or compose:)", validate=self.validators.fallback_validation, default=def_fb_str.replace("{", "{{").replace("}", "}}"), ) @@ -238,7 +245,7 @@ class Forms: if edit.get("fallback"): raw_def_fb = defaults.get("fallback", "") def_fb_str = json.dumps(raw_def_fb) if isinstance(raw_def_fb, (list, dict)) else str(raw_def_fb or "") - questions.append(inquirer.Text("fallback", message="Add fallback credentials (JSON list/dict, @profile, or compose:)", validate=self.validators.fallback_validation, default=def_fb_str.replace("{", "{{").replace("}", "}}"))) + questions.append(inquirer.Text("fallback", message="Add fallback credentials (@profile, @p1,@p2, JSON list/dict, or compose:)", validate=self.validators.fallback_validation, default=def_fb_str.replace("{", "{{").replace("}", "}}"))) else: profile["fallback"] = defaults.get("fallback", "") @@ -296,7 +303,7 @@ class Forms: fbq = [ inquirer.Text( "fallback", - message="Add fallback credentials (JSON list/dict, @profile, or compose:)", + message="Add fallback credentials (@profile, @p1,@p2, JSON list/dict, or compose:)", validate=self.validators.fallback_validation, ) ] diff --git a/connpy/cli/validators.py b/connpy/cli/validators.py index 15a03b7..20852a5 100644 --- a/connpy/cli/validators.py +++ b/connpy/cli/validators.py @@ -127,9 +127,19 @@ class Validators: return True if len(stripped.encode("utf-8", errors="replace")) > MAX_JSON_INPUT_BYTES: _raise_val_err(f"Fallback exceeds maximum size of {MAX_JSON_INPUT_BYTES} bytes") - if stripped.startswith("@") and "+" not in stripped: - if stripped[1:] not in self.app.profiles: - _raise_val_err(f"Profile {stripped} don't exist") + if stripped.startswith("@") and not stripped.startswith("@@") and "+" not in stripped: + parts = [p.strip() for p in stripped.split(",")] + if any(not p for p in parts): + _raise_val_err("Fallback profile entry cannot be empty") + if len(parts) > MAX_FALLBACK_ENTRIES: + _raise_val_err(f"Fallback exceeds maximum of {MAX_FALLBACK_ENTRIES} entries") + for p in parts: + if not p.startswith("@") or not re.fullmatch(r"[A-Za-z0-9_.$:/-]+", p[1:]): + _raise_val_err( + "Comma-separated fallback entries must be valid @profile references" + ) + if p[1:] not in self.app.profiles: + _raise_val_err(f"Profile {p} don't exist") return True try: if is_compose_expression(stripped): diff --git a/connpy/tests/test_auth_fallback_chain.py b/connpy/tests/test_auth_fallback_chain.py index 4d03784..ce24602 100644 --- a/connpy/tests/test_auth_fallback_chain.py +++ b/connpy/tests/test_auth_fallback_chain.py @@ -2280,3 +2280,99 @@ def test_profile_service_strict_auth_inheritance_no_options_leak_and_no_non_auth else: assert res_neg["user"] == "" assert res_neg["password"] == "" + + +def test_fallback_comma_separated_profiles_validation_parsing_resolution_and_profileused( + tmp_path: Path, +) -> None: + from types import SimpleNamespace + + import inquirer + + from connpy.cli.forms import _parse_fallback_input + + app = SimpleNamespace( + profiles={ + "sdnc": {"user": "sdnc_u", "password": "sdnc_p"}, + "local": {"user": "local_u", "password": "local_p"}, + "p1": {"user": "u1", "password": "p1"}, + "p2": {"user": "u2", "password": "p2"}, + "p3": {"user": "u3", "password": "p3"}, + "p4": {"user": "u4", "password": "p4"}, + "p5": {"user": "u5", "password": "p5"}, + "p6": {"user": "u6", "password": "p6"}, + } + ) + validators = Validators(app) + + assert validators.fallback_validation({}, "@sdnc, @local") is True + assert validators.fallback_validation({}, "@sdnc,@local") is True + assert validators.fallback_validation({}, "@sdnc") is True + assert validators.fallback_validation({}, "@@Pass,WithComma") is True + + with pytest.raises(inquirer.errors.ValidationError) as exc_missing: + validators.fallback_validation({}, "@sdnc, @nonexistent") + assert "@nonexistent" in str(exc_missing.value.reason) + + with pytest.raises(inquirer.errors.ValidationError) as exc_limit: + validators.fallback_validation({}, "@p1, @p2, @p3, @p4, @p5, @p6") + assert str(MAX_FALLBACK_ENTRIES) in str(exc_limit.value.reason) + + with pytest.raises(inquirer.errors.ValidationError): + validators.fallback_validation({}, "@sdnc,") + + with pytest.raises(inquirer.errors.ValidationError): + validators.fallback_validation({}, "@sdnc, local") + + assert _parse_fallback_input("@sdnc, @local") == ["@sdnc", "@local"] + assert _parse_fallback_input("@sdnc,@local") == ["@sdnc", "@local"] + assert _parse_fallback_input("@sdnc") == "@sdnc" + assert _parse_fallback_input("@@Pass,WithComma") == "@@Pass,WithComma" + + assert validate_fallback_entries("@sdnc, @local") == ["@sdnc", "@local"] + assert validate_fallback_entries("@@Pass,WithComma") == ["@@Pass,WithComma"] + with pytest.raises(ValueError): + validate_fallback_entries("@sdnc,") + with pytest.raises(ValueError): + validate_fallback_entries("@sdnc, local") + with pytest.raises(ValueError): + validate_fallback_entries("@p1, @p2, @p3, @p4, @p5, @p6") + + resolved = resolve_fallback_entries("@sdnc, @local", app.profiles) + assert resolved == [ + {"user": "sdnc_u", "password": "sdnc_p"}, + {"user": "local_u", "password": "local_p"}, + ] + assert resolve_fallback_entries("@@Pass,WithComma", app.profiles) == [ + {"user": "", "password": "@@Pass,WithComma"} + ] + + assert extract_profile_refs_from_value({"fallback": "@sdnc, @local"}) == {"sdnc", "local"} + + cfg = _make_config( + tmp_path, + { + "profiles": { + "sdnc": {"user": "sdnc_u", "password": "sdnc_p"}, + "local": {"user": "local_u", "password": "local_p"}, + }, + "connections": { + "router1": { + "type": "connection", + "host": "10.0.0.1", + "protocol": "ssh", + "port": "", + "user": "tacacs_u", + "password": "tacacs_p", + "options": "", + "logs": "", + "tags": "", + "fallback": "@sdnc, @local", + } + }, + }, + ) + p_svc = ProfileService(cfg) + for used_name in ("sdnc", "local"): + with pytest.raises(InvalidConfigurationError): + p_svc.delete_profile(used_name)