Module connpy.auth_utils

Pure authentication, composition, masking, sanitization, and rate-limit helpers.

Functions

def clear_exception_frames(exc: BaseException | None) ‑> None
Expand source code
def clear_exception_frames(exc: BaseException | None) -> None:
    """Clear local variables on all frames in an exception's traceback chain."""
    seen: set[int] = set()
    stack: list[BaseException] = []
    if exc is not None:
        stack.append(exc)
    while stack:
        cur = stack.pop()
        obj_id = id(cur)
        if obj_id in seen:
            continue
        seen.add(obj_id)
        cause = getattr(cur, "__cause__", None)
        ctx = getattr(cur, "__context__", None)
        if cause is not None:
            stack.append(cause)
        if ctx is not None:
            stack.append(ctx)

        tb = getattr(cur, "__traceback__", None)
        if tb is not None:
            with suppress(RuntimeError):
                traceback.clear_frames(tb)

        with suppress(AttributeError, TypeError):
            cur.__traceback__ = None
        with suppress(AttributeError, TypeError):
            cur.__cause__ = None
        with suppress(AttributeError, TypeError):
            cur.__context__ = None

Clear local variables on all frames in an exception's traceback chain.

def compile_active_context_patterns(cfg_dict: Any, *, strict: bool = False) ‑> list[re.Pattern[str]]
Expand source code
def compile_active_context_patterns(
    cfg_dict: Any,
    *,
    strict: bool = False,
) -> list[re.Pattern[str]]:
    """Compile active context regexes purely respecting cfg_dict['case']."""
    patterns, _ = compile_active_context_patterns_with_status(cfg_dict, strict=strict)
    return patterns

Compile active context regexes purely respecting cfg_dict['case'].

def compile_active_context_patterns_with_status(cfg_dict: Any, *, strict: bool = False) ‑> tuple[list[re.Pattern[str]], bool]
Expand source code
def compile_active_context_patterns_with_status(
    cfg_dict: Any,
    *,
    strict: bool = False,
) -> tuple[list[re.Pattern[str]], bool]:
    """Compile active context regexes purely, returning (patterns, had_error)."""
    if is_default_all_context_cfg(cfg_dict):
        return ([re.compile(".*")], False)

    current_ctx = cfg_dict.get("current_context", "all")
    contexts = cfg_dict.get("contexts", {"all": [".*"]})
    raw_patterns = contexts.get(current_ctx, [".*"]) if isinstance(contexts, dict) else [".*"]
    flags = 0 if cfg_dict.get("case", False) else re.IGNORECASE

    if not isinstance(raw_patterns, list):
        if strict:
            raise ValueError("Context regexes must be a list")
        return ([], True)

    had_error = False
    if len(raw_patterns) > MAX_CONTEXT_REGEXES:
        if strict:
            raise ValueError(f"Context exceeds maximum of {MAX_CONTEXT_REGEXES} regexes")
        had_error = True
        raw_patterns = raw_patterns[:MAX_CONTEXT_REGEXES]

    patterns: list[re.Pattern[str]] = []
    for pat in raw_patterns:
        if not isinstance(pat, str) or not pat or len(pat) > MAX_CONTEXT_PATTERN_LEN:
            if strict:
                raise ValueError(
                    f"Context pattern must be a non-empty string up to {MAX_CONTEXT_PATTERN_LEN} chars"
                )
            had_error = True
            continue
        try:
            patterns.append(re.compile(pat, flags))
        except re.error as exc:
            if strict:
                raise ValueError(f"Invalid context regex {pat!r}: {exc}") from None
            had_error = True
    return (patterns, had_error)

Compile active context regexes purely, returning (patterns, had_error).

def extract_compose_profile_refs(expr: str) ‑> set[str]
Expand source code
def extract_compose_profile_refs(expr: str) -> set[str]:
    """Return profile names referenced via @profile tokens in a compose: expression."""
    if not isinstance(expr, str) or not expr.startswith("compose:"):
        return set()
    if len(expr) > MAX_COMPOSE_EXPR_LEN:
        return set()
    body = expr[len("compose:") :]
    if not body or not body.strip():
        return set()
    try:
        tokens = _tokenize_compose_body(body)
    except SanitizedAuthError:
        return set()
    return {tok_val for tok_type, tok_val in tokens if tok_type == "profile_ref"}

Return profile names referenced via @profile tokens in a compose: expression.

def extract_profile_refs_from_value(value: Any) ‑> set[str]
Expand source code
def extract_profile_refs_from_value(value: Any) -> set[str]:
    """Extract all @profile names referenced directly or via compose:/fallback in a value."""
    return _extract_profile_refs_internal(value, set())

Extract all @profile names referenced directly or via compose:/fallback in a value.

def has_insecure_hostkey_checking(options: str = '', tags: Any = None, hop_metas: Iterable[dict[str, Any]] = ()) ‑> bool
Expand source code
def has_insecure_hostkey_checking(
    options: str = "",
    tags: Any = None,
    hop_metas: Iterable[dict[str, Any]] = (),
) -> bool:
    """Return True if StrictHostKeyChecking=no/off or UserKnownHostsFile=/dev/null is configured."""
    candidates: list[str] = []
    if options:
        candidates.append(str(options))
    if isinstance(tags, dict):
        for k in ("mosh_ssh_options", "ssh_options"):
            v = tags.get(k)
            if v:
                candidates.append(str(v))
    for hop in hop_metas or ():
        if isinstance(hop, dict):
            h_opts = hop.get("options", "")
            if h_opts:
                candidates.append(str(h_opts))
            h_tags = hop.get("tags")
            if isinstance(h_tags, dict):
                for k in ("mosh_ssh_options", "ssh_options"):
                    v = h_tags.get(k)
                    if v:
                        candidates.append(str(v))
    return any(_has_insecure_ssh_options(c) for c in candidates)

Return True if StrictHostKeyChecking=no/off or UserKnownHostsFile=/dev/null is configured.

def host_exact_re(host: str) ‑> re.Pattern[str]
Expand source code
def host_exact_re(host: str) -> re.Pattern[str]:
    """Compile an exact host boundary regex with zero FQDN subdomain wildcard risk."""
    escaped = re.escape(str(host))
    return re.compile(
        rf"(?<![A-Za-z0-9._-]){escaped}(?![A-Za-z0-9._-])(?=$|[\s:\]'\"#>$),])",
        re.IGNORECASE | re.ASCII,
    )

Compile an exact host boundary regex with zero FQDN subdomain wildcard risk.

def is_compose_expression(value: Any) ‑> bool
Expand source code
def is_compose_expression(value: Any) -> bool:
    """Return True if value is a string with the explicit compose: prefix."""
    return isinstance(value, str) and value.startswith("compose:")

Return True if value is a string with the explicit compose: prefix.

def is_default_all_context_cfg(cfg_dict: Any) ‑> bool
Expand source code
def is_default_all_context_cfg(cfg_dict: Any) -> bool:
    """Return True when config uses the default unrestricted 'all' context."""
    if not isinstance(cfg_dict, dict):
        return True
    current_ctx = cfg_dict.get("current_context", "all")
    if current_ctx != "all":
        return False
    contexts = cfg_dict.get("contexts", {"all": [".*"]})
    if not isinstance(contexts, dict):
        return True
    return contexts.get("all", [".*"]) == [".*"]

Return True when config uses the default unrestricted 'all' context.

def is_rsa_blob(value: Any) ‑> bool
Expand source code
def is_rsa_blob(value: Any) -> bool:
    """Return True if value matches an encrypted RSA bytes literal string."""
    return isinstance(value, str) and bool(_RSA_BLOB_RE.match(value))

Return True if value matches an encrypted RSA bytes literal string.

def mask_node_secrets(obj: Any) ‑> Any
Expand source code
def mask_node_secrets(obj: Any) -> Any:
    """Recursively mask sensitive node/profile credentials with '***' using a closed key list."""
    visiting: set[int] = set()

    def _recurse(val: Any, *, in_fallback_list: bool = False) -> Any:
        if isinstance(val, dict):
            obj_id = id(val)
            if obj_id in visiting:
                return "***"
            visiting.add(obj_id)
            try:
                out: dict[Any, Any] = {}
                for k, v in val.items():
                    k_lower = k.lower() if isinstance(k, str) else str(k).lower()
                    if _mask_secret_key(k_lower):
                        out[k] = "***"
                    elif k_lower in ("fallback", "_fallback"):
                        if isinstance(v, (dict, list, tuple)):
                            out[k] = _recurse(v, in_fallback_list=True)
                        elif v in ("", None):
                            out[k] = v
                        else:
                            out[k] = "***"
                    else:
                        out[k] = _recurse(v, in_fallback_list=False)
                return out
            finally:
                visiting.discard(obj_id)

        if isinstance(val, list):
            obj_id = id(val)
            if obj_id in visiting:
                return "***"
            visiting.add(obj_id)
            try:
                return [
                    "***"
                    if (in_fallback_list and isinstance(item, str) and item != "")
                    else _recurse(item, in_fallback_list=in_fallback_list)
                    for item in val
                ]
            finally:
                visiting.discard(obj_id)

        if isinstance(val, tuple):
            obj_id = id(val)
            if obj_id in visiting:
                return "***"
            visiting.add(obj_id)
            try:
                return tuple(
                    "***"
                    if (in_fallback_list and isinstance(item, str) and item != "")
                    else _recurse(item, in_fallback_list=in_fallback_list)
                    for item in val
                )
            finally:
                visiting.discard(obj_id)

        return val

    return _recurse(obj)

Recursively mask sensitive node/profile credentials with '***' using a closed key list.

def match_active_context_patterns(name: Any, patterns: Iterable[re.Pattern[str]]) ‑> bool
Expand source code
def match_active_context_patterns(name: Any, patterns: Iterable[re.Pattern[str]]) -> bool:
    """Return True if non-empty string name matches at least one compiled context regex."""
    if not isinstance(name, str) or not name:
        return False
    return any(p.match(name) for p in patterns)

Return True if non-empty string name matches at least one compiled context regex.

def normalize_prompt_line(before_bytes: bytes, after_bytes: bytes) ‑> str
Expand source code
def normalize_prompt_line(before_bytes: bytes, after_bytes: bytes) -> str:
    """Return the normalized final prompt line stripped of ANSI and control sequences."""
    combined = (before_bytes or b"") + (after_bytes or b"")
    text = combined.decode("utf-8", errors="replace")
    text = _ANSI_OSC_RE.sub("", text)
    text = _ANSI_CSI_RE.sub("", text)
    text = text.replace("\r\n", "\n").replace("\r", "\n")
    lines = [line.strip() for line in text.split("\n") if line.strip()]
    if not lines:
        return ""
    return _CONTROL_CHAR_RE.sub("", lines[-1]).strip()

Return the normalized final prompt line stripped of ANSI and control sequences.

def parse_compose_expression(expr: str,
*,
profiles: dict[str, Any] | None = None,
decrypt_fn: Callable[[str], str] | None = None,
max_depth: int = 5,
max_variants: int = 10) ‑> list[str]
Expand source code
def parse_compose_expression(
    expr: str,
    *,
    profiles: dict[str, Any] | None = None,
    decrypt_fn: Callable[[str], str] | None = None,
    max_depth: int = MAX_PROFILE_DEPTH,
    max_variants: int = MAX_COMPOSE_VARIANTS,
) -> list[str]:
    """Parse and evaluate a compose: password expression into up to max_variants strings."""
    return _resolve_compose_internal(
        expr,
        profiles=profiles,
        decrypt_fn=decrypt_fn,
        depth=0,
        visited=frozenset(),
        max_depth=max_depth,
        max_variants=max_variants,
    )

Parse and evaluate a compose: password expression into up to max_variants strings.

def raise_sanitized_auth_error(orig_exc: BaseException | None = None,
*,
code: str = 'AUTH_FAILED',
secrets: Iterable[str] = (),
context_label: str = '') ‑> NoReturn
Expand source code
def raise_sanitized_auth_error(
    orig_exc: BaseException | None = None,
    *,
    code: str = "AUTH_FAILED",
    secrets: Iterable[str] = (),
    context_label: str = "",
) -> NoReturn:
    """Clear original frames and raise SanitizedAuthError with cause and context suppressed."""
    err: SanitizedAuthError | None = None
    try:
        err = sanitize_exception(
            orig_exc,
            code=code,
            secrets=secrets,
            context_label=context_label,
            clear_orig_frames=True,
        )
    finally:
        if orig_exc is not None:
            clear_exception_frames(orig_exc)
        del orig_exc
        del secrets
    err.__context__ = None
    err.__cause__ = None
    raise err from None

Clear original frames and raise SanitizedAuthError with cause and context suppressed.

def redact_known_secrets(text: str, secrets: Iterable[str] = (), *, min_len: int = 4) ‑> str
Expand source code
def redact_known_secrets(
    text: str,
    secrets: Iterable[str] = (),
    *,
    min_len: int = 4,
) -> str:
    """Replace any non-trivial secret strings in text with '***'."""
    if not text or not secrets:
        return text
    out = str(text)
    unique_secrets = sorted(
        {s for s in secrets if isinstance(s, str) and len(s) >= min_len},
        key=len,
        reverse=True,
    )
    for sec in unique_secrets:
        out = out.replace(sec, "***")
    return out

Replace any non-trivial secret strings in text with '***'.

def resolve_fallback_entries(raw_fallback: Any, profiles: dict[str, Any] | None, *, max_entries: int = 5) ‑> list[dict[str, typing.Any]]
Expand source code
def resolve_fallback_entries(
    raw_fallback: Any,
    profiles: dict[str, Any] | None,
    *,
    max_entries: int = MAX_FALLBACK_ENTRIES,
) -> list[dict[str, Any]]:
    """Normalize fallback entries and resolve any @profile references safely."""
    return _resolve_fallback_entries_internal(
        raw_fallback,
        profiles,
        max_entries=max_entries,
    )

Normalize fallback entries and resolve any @profile references safely.

def sanitize_exception(orig_exc: BaseException | None,
*,
code: str = 'AUTH_FAILED',
secrets: Iterable[str] = (),
context_label: str = '',
clear_orig_frames: bool = True) ‑> SanitizedAuthError
Expand source code
def sanitize_exception(
    orig_exc: BaseException | None,
    *,
    code: str = "AUTH_FAILED",
    secrets: Iterable[str] = (),
    context_label: str = "",
    clear_orig_frames: bool = True,
) -> SanitizedAuthError:
    """Convert any exception into a SanitizedAuthError without leaking secrets or tracebacks."""
    resolved_code = code if code in SAFE_ERROR_TEMPLATES else "AUTH_FAILED"
    try:
        if isinstance(orig_exc, SanitizedAuthError):
            existing_code = (
                orig_exc.code if orig_exc.code in SAFE_ERROR_TEMPLATES else resolved_code
            )
            safe_existing = sanitize_log_message(str(orig_exc), secrets=secrets).strip()
            msg = safe_existing or SAFE_ERROR_TEMPLATES[existing_code]
            return SanitizedAuthError(msg, code=existing_code)

        msg = SAFE_ERROR_TEMPLATES[resolved_code]
        if context_label:
            safe_ctx = sanitize_log_message(context_label, secrets=secrets).strip()
            if safe_ctx:
                msg = f"{msg} ({safe_ctx})"
        return SanitizedAuthError(msg, code=resolved_code)
    finally:
        if clear_orig_frames and orig_exc is not None:
            clear_exception_frames(orig_exc)

Convert any exception into a SanitizedAuthError without leaking secrets or tracebacks.

def sanitize_log_message(message: str, *, secrets: Iterable[str] = ()) ‑> str
Expand source code
def sanitize_log_message(message: str, *, secrets: Iterable[str] = ()) -> str:
    """Strip ANSI sequences, control chars, and known secrets from a log line."""
    text = str(message) if message is not None else ""
    text = redact_known_secrets(text, secrets=secrets, min_len=1)
    text = _ANSI_OSC_RE.sub("", text)
    text = _ANSI_CSI_RE.sub("", text)
    text = _CONTROL_CHAR_RE.sub("", text)
    return redact_known_secrets(text, secrets=secrets, min_len=1)

Strip ANSI sequences, control chars, and known secrets from a log line.

def validate_auth_budget_tags(tags: Any) ‑> None
Expand source code
def validate_auth_budget_tags(tags: Any) -> None:
    """Validate optional auth budget and policy keys in a node/profile tags dict."""
    if not isinstance(tags, dict):
        return
    if "max_auth_prompts" in tags and tags["max_auth_prompts"] is not None:
        validate_strict_int_range(
            tags["max_auth_prompts"],
            "tags.max_auth_prompts",
            MIN_AUTH_PROMPTS,
            MAX_AUTH_PROMPTS_CAP,
        )
    if "max_total_auth_attempts" in tags and tags["max_total_auth_attempts"] is not None:
        validate_strict_int_range(
            tags["max_total_auth_attempts"],
            "tags.max_total_auth_attempts",
            MIN_TOTAL_AUTH_ATTEMPTS,
            MAX_TOTAL_AUTH_ATTEMPTS_CAP,
        )
    if "max_hop_host_attempts" in tags and tags["max_hop_host_attempts"] is not None:
        validate_strict_int_range(
            tags["max_hop_host_attempts"],
            "tags.max_hop_host_attempts",
            MIN_HOP_HOST_ATTEMPTS,
            MAX_HOP_HOST_ATTEMPTS_CAP,
        )
    if "max_global_user_attempts" in tags and tags["max_global_user_attempts"] is not None:
        validate_strict_int_range(
            tags["max_global_user_attempts"],
            "tags.max_global_user_attempts",
            1,
            1000,
        )
    for bool_key in (
        "allow_fallback",
        "allow_ambiguous_single_hop_prompt",
        "disable_fallback_on_insecure_hostkey",
    ):
        if bool_key in tags and tags[bool_key] is not None and not isinstance(tags[bool_key], bool):
            raise ValueError(f"Invalid tags.{bool_key}: expected boolean")
    if "fallback" in tags and tags["fallback"] not in (None, "", []):
        validate_fallback_entries(tags["fallback"])

Validate optional auth budget and policy keys in a node/profile tags dict.

def validate_compose_syntax(expr: str) ‑> None
Expand source code
def validate_compose_syntax(expr: str) -> None:
    """Validate compose: syntax and length without resolving profiles or decrypting."""
    if not isinstance(expr, str) or len(expr) > MAX_COMPOSE_EXPR_LEN:
        raise_sanitized_auth_error(
            code="AUTH_FAILED",
            context_label="compose expression exceeds maximum length",
        )
    body = expr.removeprefix("compose:")
    if not body or not body.strip():
        raise_sanitized_auth_error(
            code="AUTH_FAILED",
            context_label="empty compose expression",
        )
    _tokenize_compose_body(body)

Validate compose: syntax and length without resolving profiles or decrypting.

def validate_config_auth_settings(cfg: Any) ‑> None
Expand source code
def validate_config_auth_settings(cfg: Any) -> None:
    """Validate global config auth budget and policy keys."""
    if not isinstance(cfg, dict):
        raise TypeError("Config section must be a dictionary")
    if "max_auth_prompts" in cfg and cfg["max_auth_prompts"] is not None:
        validate_strict_int_range(
            cfg["max_auth_prompts"],
            "config.max_auth_prompts",
            MIN_AUTH_PROMPTS,
            MAX_AUTH_PROMPTS_CAP,
        )
    if "max_total_auth_attempts" in cfg and cfg["max_total_auth_attempts"] is not None:
        validate_strict_int_range(
            cfg["max_total_auth_attempts"],
            "config.max_total_auth_attempts",
            MIN_TOTAL_AUTH_ATTEMPTS,
            MAX_TOTAL_AUTH_ATTEMPTS_CAP,
        )
    if "max_hop_host_attempts" in cfg and cfg["max_hop_host_attempts"] is not None:
        validate_strict_int_range(
            cfg["max_hop_host_attempts"],
            "config.max_hop_host_attempts",
            MIN_HOP_HOST_ATTEMPTS,
            MAX_HOP_HOST_ATTEMPTS_CAP,
        )
    if "max_global_user_attempts" in cfg and cfg["max_global_user_attempts"] is not None:
        validate_strict_int_range(
            cfg["max_global_user_attempts"],
            "config.max_global_user_attempts",
            1,
            1000,
        )
    if (
        "disable_fallback_on_insecure_hostkey" in cfg
        and cfg["disable_fallback_on_insecure_hostkey"] is not None
        and not isinstance(cfg["disable_fallback_on_insecure_hostkey"], bool)
    ):
        raise ValueError("Invalid config.disable_fallback_on_insecure_hostkey: expected boolean")

Validate global config auth budget and policy keys.

def validate_fallback_entries(raw_fallback: Any, *, max_entries: int = 5) ‑> list[dict[str, typing.Any] | str]
Expand source code
def validate_fallback_entries(
    raw_fallback: Any,
    *,
    max_entries: int = MAX_FALLBACK_ENTRIES,
) -> list[dict[str, Any] | str]:
    """Validate and normalize fallback config entries without expanding profiles."""
    if raw_fallback in (None, "", []):
        return []

    parsed = raw_fallback
    if isinstance(raw_fallback, str):
        stripped = raw_fallback.strip()
        if not stripped:
            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:
            return [stripped]

    if isinstance(parsed, dict):
        items: list[Any] = [parsed]
    elif isinstance(parsed, (list, tuple)):
        items = list(parsed)
    else:
        raise TypeError(
            "Fallback must be a list of credential dicts/strings, a dict, @profile, or JSON"
        )

    if len(items) > max_entries:
        raise ValueError(f"Fallback exceeds maximum of {max_entries} entries")

    normalized: list[dict[str, Any] | str] = []
    allowed_entry_keys = {"user", "password"}
    for idx, entry in enumerate(items):
        if isinstance(entry, str):
            if not entry:
                raise ValueError(f"Fallback entry {idx} cannot be empty")
            if entry.startswith("compose:"):
                validate_compose_syntax(entry)
            normalized.append(entry)
        elif isinstance(entry, dict):
            unknown_keys = set(entry.keys()) - allowed_entry_keys
            if unknown_keys:
                raise ValueError(
                    f"Unsupported keys in fallback entry {idx}: {sorted(unknown_keys)}"
                )
            user_val = entry.get("user", "")
            pw_val = entry.get("password", "")
            if user_val is not None and not isinstance(user_val, str):
                raise ValueError(f"Fallback entry {idx} 'user' must be a string")
            if isinstance(pw_val, (list, tuple)):
                if not pw_val or not all(isinstance(p, str) and p != "" for p in pw_val):
                    raise ValueError(
                        f"Fallback entry {idx} 'password' list must contain non-empty strings"
                    )
                for p in pw_val:
                    if p.startswith("compose:"):
                        validate_compose_syntax(p)
            elif pw_val is not None and not isinstance(pw_val, str):
                raise ValueError(f"Fallback entry {idx} 'password' must be a string or list")
            elif isinstance(pw_val, str) and pw_val.startswith("compose:"):
                validate_compose_syntax(pw_val)

            if not (user_val or pw_val):
                raise ValueError(
                    f"Fallback entry {idx} must specify 'user' and/or 'password'"
                )
            normalized.append(deepcopy(entry))
        else:
            raise TypeError(f"Fallback entry {idx} must be a dict or string")

    return normalized

Validate and normalize fallback config entries without expanding profiles.

def validate_json_depth_and_size(raw_or_obj: Any, *, max_bytes: int = 8192, max_depth: int = 4) ‑> Any
Expand source code
def validate_json_depth_and_size(
    raw_or_obj: Any,
    *,
    max_bytes: int = MAX_JSON_INPUT_BYTES,
    max_depth: int = MAX_JSON_INPUT_DEPTH,
) -> Any:
    """Parse (if str) and enforce byte length and nesting depth limits on JSON inputs."""
    if isinstance(raw_or_obj, str):
        if len(raw_or_obj) > max_bytes or len(raw_or_obj.encode("utf-8", errors="replace")) > max_bytes:
            raise ValueError(f"JSON input exceeds maximum size of {max_bytes} bytes")
        try:
            parsed = json.loads(raw_or_obj)
        except RecursionError:
            raise ValueError(
                f"JSON nesting exceeds maximum depth of {max_depth}"
            ) from None
    else:
        parsed = raw_or_obj
    _check_depth(parsed, max_depth, 0)
    return parsed

Parse (if str) and enforce byte length and nesting depth limits on JSON inputs.

def validate_strict_int_range(value: Any, name: str, min_val: int, max_val: int) ‑> int
Expand source code
def validate_strict_int_range(
    value: Any,
    name: str,
    min_val: int,
    max_val: int,
) -> int:
    """Validate that value is a strict plain int (not bool/float/str) in [min_val, max_val]."""
    if type(value) is not int or value < min_val or value > max_val:
        raise ValueError(
            f"Invalid {name}: expected integer in [{min_val}, {max_val}], got {value!r}"
        )
    return value

Validate that value is a strict plain int (not bool/float/str) in [min_val, max_val].

Classes

class AuthAttemptTracker (*,
ttl_seconds: float = 300,
max_entries: int = 10000,
default_max_host_attempts: int = 6,
default_max_hop_attempts: int = 6,
default_max_global_user_attempts: int | None = None,
clock: Callable[[], float] = <built-in function monotonic>)
Expand source code
class AuthAttemptTracker:
    """Thread-safe intra-process authentication attempt tracker with safe anti-flood eviction."""

    def __init__(
        self,
        *,
        ttl_seconds: float = DEFAULT_TRACKER_TTL_SECONDS,
        max_entries: int = MAX_TRACKER_ENTRIES,
        default_max_host_attempts: int = DEFAULT_MAX_TOTAL_AUTH_ATTEMPTS,
        default_max_hop_attempts: int = DEFAULT_MAX_HOP_HOST_ATTEMPTS,
        default_max_global_user_attempts: int | None = None,
        clock: Callable[[], float] = time.monotonic,
    ) -> None:
        if isinstance(ttl_seconds, bool) or not isinstance(ttl_seconds, (int, float)):
            raise TypeError(f"Invalid ttl_seconds: expected number > 0, got {ttl_seconds!r}")
        ttl_val = float(ttl_seconds)
        if not math.isfinite(ttl_val) or ttl_val <= 0:
            raise ValueError(f"Invalid ttl_seconds: expected > 0, got {ttl_seconds!r}")
        if isinstance(max_entries, bool) or not isinstance(max_entries, int):
            raise TypeError(f"Invalid max_entries: expected int >= 1, got {max_entries!r}")
        if max_entries < 1:
            raise ValueError(f"Invalid max_entries: expected >= 1, got {max_entries!r}")
        self._ttl_seconds = ttl_val
        self._max_entries = max_entries
        self._default_max_host_attempts = validate_strict_int_range(
            default_max_host_attempts,
            "default_max_host_attempts",
            MIN_TOTAL_AUTH_ATTEMPTS,
            MAX_TOTAL_AUTH_ATTEMPTS_CAP,
        )
        self._default_max_hop_attempts = validate_strict_int_range(
            default_max_hop_attempts,
            "default_max_hop_attempts",
            MIN_HOP_HOST_ATTEMPTS,
            MAX_HOP_HOST_ATTEMPTS_CAP,
        )
        self._default_max_global_user_attempts: int | None = (
            validate_strict_int_range(
                default_max_global_user_attempts,
                "default_max_global_user_attempts",
                1,
                1000,
            )
            if default_max_global_user_attempts is not None
            else None
        )
        self._clock = clock
        self._lock = threading.Lock()
        self._unblocked: OrderedDict[Any, _BudgetEntry] = OrderedDict()
        self._blocked: OrderedDict[Any, _BudgetEntry] = OrderedDict()

    def _purge_expired_unlocked(self, now: float) -> None:
        for bucket in (self._unblocked, self._blocked):
            expired_keys = [
                k for k, entry in bucket.items() if (now - entry.last_ts) >= self._ttl_seconds
            ]
            for k in expired_keys:
                del bucket[k]

    def _evict_if_full_unlocked(self, now: float) -> None:
        if (len(self._unblocked) + len(self._blocked)) < self._max_entries:
            return
        self._purge_expired_unlocked(now)
        while (len(self._unblocked) + len(self._blocked)) >= self._max_entries:
            if self._unblocked:
                self._unblocked.popitem(last=False)
            elif self._blocked:
                self._blocked.popitem(last=False)
            else:
                break

    def _get_live_entry_unlocked(self, key: Any, now: float) -> _BudgetEntry | None:
        if key in self._unblocked:
            entry = self._unblocked[key]
            if (now - entry.last_ts) >= self._ttl_seconds:
                del self._unblocked[key]
                return None
            return entry
        if key in self._blocked:
            entry = self._blocked[key]
            if (now - entry.last_ts) >= self._ttl_seconds:
                del self._blocked[key]
                return None
            return entry
        return None

    def _can_acquire_unlocked(self, key: Any, limit: int, now: float) -> bool:
        if limit <= 0:
            return False
        entry = self._get_live_entry_unlocked(key, now)
        if entry is None:
            return True
        if entry.count >= limit:
            entry.limit = limit
            if key in self._unblocked:
                del self._unblocked[key]
                self._blocked[key] = entry
            return False
        return True

    def _commit_acquire_unlocked(self, key: Any, limit: int, now: float) -> None:
        entry = self._get_live_entry_unlocked(key, now)
        if entry is None:
            self._evict_if_full_unlocked(now)
            new_entry = _BudgetEntry(count=1, limit=limit, last_ts=now)
            if 1 >= limit:
                self._blocked[key] = new_entry
            else:
                self._unblocked[key] = new_entry
            return

        entry.count += 1
        entry.limit = limit
        entry.last_ts = now
        if entry.count >= limit:
            if key in self._unblocked:
                del self._unblocked[key]
            self._blocked[key] = entry
            self._blocked.move_to_end(key)
        else:
            if key in self._blocked:
                del self._blocked[key]
            self._unblocked[key] = entry
            self._unblocked.move_to_end(key)

    def try_acquire(self, key: Any, *, limit: int) -> bool:
        """Attempt to consume 1 attempt slot for key within limit. Returns False if exhausted."""
        if limit <= 0:
            return False
        now = self._clock()
        with self._lock:
            if not self._can_acquire_unlocked(key, limit, now):
                return False
            self._commit_acquire_unlocked(key, limit, now)
            return True

    def try_acquire_target_attempt(
        self,
        *,
        host: str,
        port: str = "",
        protocol: str = "ssh",
        user: str = "",
        host_limit: int | None = None,
        user_limit: int | None = None,
    ) -> tuple[bool, str | None]:
        """Atomically verify and consume both user and host attempt slots under one lock."""
        eff_host_limit = self._default_max_host_attempts if host_limit is None else int(host_limit)
        eff_user_limit = self._default_max_global_user_attempts if user_limit is None else user_limit
        host_key = self._host_key(host, port, protocol)
        user_key = self._user_key(user) if (user and eff_user_limit is not None) else None
        now = self._clock()
        with self._lock:
            if user_key is not None and not self._can_acquire_unlocked(
                user_key, int(eff_user_limit), now
            ):
                return False, "USER_BUDGET_EXHAUSTED"
            if not self._can_acquire_unlocked(host_key, eff_host_limit, now):
                return False, "HOST_BUDGET_EXHAUSTED"
            if user_key is not None:
                self._commit_acquire_unlocked(user_key, int(eff_user_limit), now)
            self._commit_acquire_unlocked(host_key, eff_host_limit, now)
            return True, None

    def remaining(self, key: Any, *, limit: int) -> int:
        """Return remaining attempt quota for key."""
        now = self._clock()
        with self._lock:
            entry = self._get_live_entry_unlocked(key, now)
            if entry is None:
                return max(0, limit)
            return max(0, limit - entry.count)

    @staticmethod
    def _host_key(host: str, port: str = "", protocol: str = "ssh") -> tuple[str, str, str, str]:
        return ("host", str(host).lower(), str(port or "").strip(), str(protocol or "").lower())

    @staticmethod
    def _hop_key(host: str, port: str = "", protocol: str = "ssh") -> tuple[str, str, str, str]:
        return ("hop", str(host).lower(), str(port or "").strip(), str(protocol or "").lower())

    @staticmethod
    def _user_key(user: str) -> tuple[str, str]:
        return ("user", str(user))

    def try_acquire_host(
        self,
        host: str,
        port: str = "",
        protocol: str = "ssh",
        *,
        limit: int | None = None,
    ) -> bool:
        """Consume 1 target-host authentication attempt if within budget."""
        eff_limit = self._default_max_host_attempts if limit is None else int(limit)
        return self.try_acquire(self._host_key(host, port, protocol), limit=eff_limit)

    def try_acquire_hop(
        self,
        host: str,
        port: str = "",
        protocol: str = "ssh",
        *,
        limit: int | None = None,
    ) -> bool:
        """Consume 1 jumphost authentication attempt if within budget."""
        eff_limit = self._default_max_hop_attempts if limit is None else int(limit)
        return self.try_acquire(self._hop_key(host, port, protocol), limit=eff_limit)

    def try_acquire_user(
        self,
        user: str,
        *,
        limit: int | None = None,
    ) -> bool:
        """Consume 1 global username authentication attempt if a global limit is active."""
        if not user:
            return True
        eff_limit = self._default_max_global_user_attempts if limit is None else limit
        if eff_limit is None:
            return True
        return self.try_acquire(self._user_key(user), limit=int(eff_limit))

    def remaining_host(
        self,
        host: str,
        port: str = "",
        protocol: str = "ssh",
        *,
        limit: int | None = None,
    ) -> int:
        """Return remaining target-host attempt quota."""
        eff_limit = self._default_max_host_attempts if limit is None else int(limit)
        return self.remaining(self._host_key(host, port, protocol), limit=eff_limit)

    def remaining_hop(
        self,
        host: str,
        port: str = "",
        protocol: str = "ssh",
        *,
        limit: int | None = None,
    ) -> int:
        """Return remaining jumphost attempt quota."""
        eff_limit = self._default_max_hop_attempts if limit is None else int(limit)
        return self.remaining(self._hop_key(host, port, protocol), limit=eff_limit)

    def remaining_user(
        self,
        user: str,
        *,
        limit: int | None = None,
    ) -> int | None:
        """Return remaining global username quota, or None if unlimited."""
        eff_limit = self._default_max_global_user_attempts if limit is None else limit
        if eff_limit is None:
            return None
        return self.remaining(self._user_key(user), limit=int(eff_limit))

    def is_blocked(self, key: Any) -> bool:
        """Return True if key currently has an active exhausted budget entry."""
        now = self._clock()
        with self._lock:
            entry = self._get_live_entry_unlocked(key, now)
            return entry is not None and entry.count >= entry.limit

    def entry_count(self) -> int:
        """Return total number of tracked entries (before TTL expiry)."""
        with self._lock:
            return len(self._unblocked) + len(self._blocked)

    def reset(self) -> None:
        """Clear all tracked entries."""
        with self._lock:
            self._unblocked.clear()
            self._blocked.clear()

Thread-safe intra-process authentication attempt tracker with safe anti-flood eviction.

Methods

def entry_count(self) ‑> int
Expand source code
def entry_count(self) -> int:
    """Return total number of tracked entries (before TTL expiry)."""
    with self._lock:
        return len(self._unblocked) + len(self._blocked)

Return total number of tracked entries (before TTL expiry).

def is_blocked(self, key: Any) ‑> bool
Expand source code
def is_blocked(self, key: Any) -> bool:
    """Return True if key currently has an active exhausted budget entry."""
    now = self._clock()
    with self._lock:
        entry = self._get_live_entry_unlocked(key, now)
        return entry is not None and entry.count >= entry.limit

Return True if key currently has an active exhausted budget entry.

def remaining(self, key: Any, *, limit: int) ‑> int
Expand source code
def remaining(self, key: Any, *, limit: int) -> int:
    """Return remaining attempt quota for key."""
    now = self._clock()
    with self._lock:
        entry = self._get_live_entry_unlocked(key, now)
        if entry is None:
            return max(0, limit)
        return max(0, limit - entry.count)

Return remaining attempt quota for key.

def remaining_hop(self, host: str, port: str = '', protocol: str = 'ssh', *, limit: int | None = None) ‑> int
Expand source code
def remaining_hop(
    self,
    host: str,
    port: str = "",
    protocol: str = "ssh",
    *,
    limit: int | None = None,
) -> int:
    """Return remaining jumphost attempt quota."""
    eff_limit = self._default_max_hop_attempts if limit is None else int(limit)
    return self.remaining(self._hop_key(host, port, protocol), limit=eff_limit)

Return remaining jumphost attempt quota.

def remaining_host(self, host: str, port: str = '', protocol: str = 'ssh', *, limit: int | None = None) ‑> int
Expand source code
def remaining_host(
    self,
    host: str,
    port: str = "",
    protocol: str = "ssh",
    *,
    limit: int | None = None,
) -> int:
    """Return remaining target-host attempt quota."""
    eff_limit = self._default_max_host_attempts if limit is None else int(limit)
    return self.remaining(self._host_key(host, port, protocol), limit=eff_limit)

Return remaining target-host attempt quota.

def remaining_user(self, user: str, *, limit: int | None = None) ‑> int | None
Expand source code
def remaining_user(
    self,
    user: str,
    *,
    limit: int | None = None,
) -> int | None:
    """Return remaining global username quota, or None if unlimited."""
    eff_limit = self._default_max_global_user_attempts if limit is None else limit
    if eff_limit is None:
        return None
    return self.remaining(self._user_key(user), limit=int(eff_limit))

Return remaining global username quota, or None if unlimited.

def reset(self) ‑> None
Expand source code
def reset(self) -> None:
    """Clear all tracked entries."""
    with self._lock:
        self._unblocked.clear()
        self._blocked.clear()

Clear all tracked entries.

def try_acquire(self, key: Any, *, limit: int) ‑> bool
Expand source code
def try_acquire(self, key: Any, *, limit: int) -> bool:
    """Attempt to consume 1 attempt slot for key within limit. Returns False if exhausted."""
    if limit <= 0:
        return False
    now = self._clock()
    with self._lock:
        if not self._can_acquire_unlocked(key, limit, now):
            return False
        self._commit_acquire_unlocked(key, limit, now)
        return True

Attempt to consume 1 attempt slot for key within limit. Returns False if exhausted.

def try_acquire_hop(self, host: str, port: str = '', protocol: str = 'ssh', *, limit: int | None = None) ‑> bool
Expand source code
def try_acquire_hop(
    self,
    host: str,
    port: str = "",
    protocol: str = "ssh",
    *,
    limit: int | None = None,
) -> bool:
    """Consume 1 jumphost authentication attempt if within budget."""
    eff_limit = self._default_max_hop_attempts if limit is None else int(limit)
    return self.try_acquire(self._hop_key(host, port, protocol), limit=eff_limit)

Consume 1 jumphost authentication attempt if within budget.

def try_acquire_host(self, host: str, port: str = '', protocol: str = 'ssh', *, limit: int | None = None) ‑> bool
Expand source code
def try_acquire_host(
    self,
    host: str,
    port: str = "",
    protocol: str = "ssh",
    *,
    limit: int | None = None,
) -> bool:
    """Consume 1 target-host authentication attempt if within budget."""
    eff_limit = self._default_max_host_attempts if limit is None else int(limit)
    return self.try_acquire(self._host_key(host, port, protocol), limit=eff_limit)

Consume 1 target-host authentication attempt if within budget.

def try_acquire_target_attempt(self,
*,
host: str,
port: str = '',
protocol: str = 'ssh',
user: str = '',
host_limit: int | None = None,
user_limit: int | None = None) ‑> tuple[bool, str | None]
Expand source code
def try_acquire_target_attempt(
    self,
    *,
    host: str,
    port: str = "",
    protocol: str = "ssh",
    user: str = "",
    host_limit: int | None = None,
    user_limit: int | None = None,
) -> tuple[bool, str | None]:
    """Atomically verify and consume both user and host attempt slots under one lock."""
    eff_host_limit = self._default_max_host_attempts if host_limit is None else int(host_limit)
    eff_user_limit = self._default_max_global_user_attempts if user_limit is None else user_limit
    host_key = self._host_key(host, port, protocol)
    user_key = self._user_key(user) if (user and eff_user_limit is not None) else None
    now = self._clock()
    with self._lock:
        if user_key is not None and not self._can_acquire_unlocked(
            user_key, int(eff_user_limit), now
        ):
            return False, "USER_BUDGET_EXHAUSTED"
        if not self._can_acquire_unlocked(host_key, eff_host_limit, now):
            return False, "HOST_BUDGET_EXHAUSTED"
        if user_key is not None:
            self._commit_acquire_unlocked(user_key, int(eff_user_limit), now)
        self._commit_acquire_unlocked(host_key, eff_host_limit, now)
        return True, None

Atomically verify and consume both user and host attempt slots under one lock.

def try_acquire_user(self, user: str, *, limit: int | None = None) ‑> bool
Expand source code
def try_acquire_user(
    self,
    user: str,
    *,
    limit: int | None = None,
) -> bool:
    """Consume 1 global username authentication attempt if a global limit is active."""
    if not user:
        return True
    eff_limit = self._default_max_global_user_attempts if limit is None else limit
    if eff_limit is None:
        return True
    return self.try_acquire(self._user_key(user), limit=int(eff_limit))

Consume 1 global username authentication attempt if a global limit is active.

class AuthCandidate (user: str,
password_spec: str | tuple[str, ...],
is_fallback: bool = False,
label: str = '')
Expand source code
@dataclass(frozen=True)
class AuthCandidate:
    """Immutable credential candidate entry for primary or backup authentication."""

    user: str
    password_spec: str | tuple[str, ...]
    is_fallback: bool = False
    label: str = ""

Immutable credential candidate entry for primary or backup authentication.

Instance variables

var is_fallback : bool
var label : str
var password_spec : str | tuple[str, ...]
var user : str
class RuntimeAuthCandidate (user: str,
password: str,
has_password: bool,
is_fallback: bool = False,
label: str = '')
Expand source code
@dataclass(frozen=True)
class RuntimeAuthCandidate:
    """Per-call resolved credential candidate with decrypted secret."""

    user: str
    password: str
    has_password: bool
    is_fallback: bool = False
    label: str = ""

Per-call resolved credential candidate with decrypted secret.

Instance variables

var has_password : bool
var is_fallback : bool
var label : str
var password : str
var user : str
class SanitizedAuthError (message: str = '', code: str = 'AUTH_FAILED')
Expand source code
class SanitizedAuthError(ConnpyError):
    """Authentication error guaranteed free of secrets and chained tracebacks."""

    __suppress_context__ = True

    def __init__(self, message: str = "", code: str = "AUTH_FAILED") -> None:
        super().__init__(message)
        self.code = code
        self.__suppress_context__ = True
        self.__cause__ = None

    @property
    def __context__(self) -> None:
        """Never retain or expose an underlying exception context."""
        return None

    @__context__.setter
    def __context__(self, _value: BaseException | None) -> None:
        return

    def __reduce__(self) -> tuple[type[SanitizedAuthError], tuple[str, str]]:
        msg = str(self.args[0]) if self.args else ""
        return (self.__class__, (msg, str(self.code)))

Authentication error guaranteed free of secrets and chained tracebacks.

Ancestors

  • ConnpyError
  • builtins.Exception
  • builtins.BaseException