mirror of
https://github.com/hansjone/netx.git
synced 2026-10-08 23:33:21 +08:00
feat(managed-ne): add bastion SSH protocol proxy hop type
Support composite-username bastion login for automated connect-test and exec, with bastion-managed or manual target credential modes. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
e62f4f2c74
commit
d3d7f62a02
15 changed files with 348 additions and 19 deletions
|
|
@ -783,6 +783,9 @@ def on_startup() -> None:
|
|||
conn.exec_driver_sql("ALTER TABLE managed_ne ADD COLUMN IF NOT EXISTS hop_password_enc TEXT DEFAULT ''")
|
||||
conn.exec_driver_sql("ALTER TABLE managed_ne ADD COLUMN IF NOT EXISTS hop_command_template TEXT DEFAULT ''")
|
||||
conn.exec_driver_sql("ALTER TABLE managed_ne ADD COLUMN IF NOT EXISTS hop_vrf VARCHAR(128) DEFAULT ''")
|
||||
conn.exec_driver_sql(
|
||||
"ALTER TABLE managed_ne ADD COLUMN IF NOT EXISTS hop_target_auth_mode VARCHAR(32) DEFAULT 'bastion_managed'"
|
||||
)
|
||||
conn.exec_driver_sql("ALTER TABLE managed_ne ADD COLUMN IF NOT EXISTS connect_detail TEXT DEFAULT ''")
|
||||
conn.exec_driver_sql(
|
||||
"ALTER TABLE ne_collection_job ADD COLUMN IF NOT EXISTS last_run_at TIMESTAMP"
|
||||
|
|
|
|||
|
|
@ -254,6 +254,7 @@ class ManagedNE(Base):
|
|||
hop_password_enc: Mapped[str] = mapped_column(Text, default="")
|
||||
hop_command_template: Mapped[str] = mapped_column(Text, default="")
|
||||
hop_vrf: Mapped[str] = mapped_column(String(128), default="")
|
||||
hop_target_auth_mode: Mapped[str] = mapped_column(String(32), default="bastion_managed")
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, index=True)
|
||||
|
||||
|
|
|
|||
|
|
@ -47,6 +47,9 @@ def _connect_context_lines(creds: dict[str, Any]) -> list[str]:
|
|||
tpl = str(creds.get("hop_command_template") or "").strip()
|
||||
if tpl:
|
||||
lines.append(f"hop_command_template={tpl}")
|
||||
auth_mode = str(creds.get("hop_target_auth_mode") or "").strip()
|
||||
if auth_mode:
|
||||
lines.append(f"hop_target_auth_mode={auth_mode}")
|
||||
vrf = str(creds.get("hop_vrf") or "").strip()
|
||||
if vrf:
|
||||
lines.append(f"hop_vrf={vrf}")
|
||||
|
|
@ -150,7 +153,9 @@ def _classify_connect_error(creds: dict[str, Any], exc: BaseException) -> str:
|
|||
return "target_auth_failed: " + detail
|
||||
if "timed out" in raw or "timeout" in raw or "hop_connect_failed" in raw:
|
||||
return "hop_connect_failed: " + detail
|
||||
if hop_v == "linux":
|
||||
if hop_v in ("linux", "bastion"):
|
||||
if "vault" in raw or "bastion" in raw:
|
||||
return "bastion_auth_failed: " + detail
|
||||
return "hop_connect_failed: " + detail
|
||||
return "hop_command_failed: " + detail
|
||||
if "readtimeout" in raw.replace(" ", "") or "pattern not detected" in raw:
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ class ManagedNeCreate(BaseModel):
|
|||
hop_password: str = ""
|
||||
hop_command_template: str = ""
|
||||
hop_vrf: str = ""
|
||||
hop_target_auth_mode: str = "bastion_managed"
|
||||
|
||||
@field_validator("vendor")
|
||||
@classmethod
|
||||
|
|
@ -63,6 +64,7 @@ class ManagedNeUpdate(BaseModel):
|
|||
hop_password: str | None = None
|
||||
hop_command_template: str | None = None
|
||||
hop_vrf: str | None = None
|
||||
hop_target_auth_mode: str | None = None
|
||||
|
||||
@field_validator("vendor")
|
||||
@classmethod
|
||||
|
|
@ -101,6 +103,7 @@ class ManagedNeOut(BaseModel):
|
|||
hop_username: str = ""
|
||||
hop_command_template: str = ""
|
||||
hop_vrf: str = ""
|
||||
hop_target_auth_mode: str = "bastion_managed"
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
|
|
@ -128,6 +131,7 @@ class HopProxyConfig(BaseModel):
|
|||
hop_password: str
|
||||
hop_command_template: str = ""
|
||||
hop_vrf: str = ""
|
||||
hop_target_auth_mode: str = "bastion_managed"
|
||||
|
||||
|
||||
class BatchHopApplyRequest(BaseModel):
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ from .ne_schemas import (
|
|||
ManagedNeOut,
|
||||
ManagedNeUpdate,
|
||||
)
|
||||
from .ne_session_factory import default_hop_command_template
|
||||
from .ne_session_factory import default_bastion_username_template, default_hop_command_template
|
||||
|
||||
IMPORT_COLUMNS = (
|
||||
"device_type",
|
||||
|
|
@ -53,7 +53,12 @@ def _normalize_protocol(protocol: str) -> str:
|
|||
|
||||
def _normalize_hop_vendor(vendor: str) -> str:
|
||||
v = str(vendor or "zte").strip().lower()
|
||||
return v if v in ("zte", "linux", "huawei", "cisco") else "zte"
|
||||
return v if v in ("zte", "linux", "huawei", "cisco", "bastion") else "zte"
|
||||
|
||||
|
||||
def _normalize_hop_target_auth_mode(mode: str) -> str:
|
||||
m = str(mode or "bastion_managed").strip().lower()
|
||||
return m if m in ("bastion_managed", "manual") else "bastion_managed"
|
||||
|
||||
|
||||
def _validate_hop_on_create(body: ManagedNeCreate) -> None:
|
||||
|
|
@ -65,6 +70,18 @@ def _validate_hop_on_create(body: ManagedNeCreate) -> None:
|
|||
raise HTTPException(status_code=400, detail="hop_username_required")
|
||||
if not str(body.hop_password or "").strip():
|
||||
raise HTTPException(status_code=400, detail="hop_password_required")
|
||||
hop_vendor = _normalize_hop_vendor(body.hop_vendor)
|
||||
if hop_vendor == "bastion" and _normalize_hop_target_auth_mode(body.hop_target_auth_mode) == "manual":
|
||||
if not str(body.password or "").strip():
|
||||
raise HTTPException(status_code=400, detail="password_required")
|
||||
|
||||
|
||||
def _target_password_optional(body: ManagedNeCreate) -> bool:
|
||||
return (
|
||||
bool(body.hop_enabled)
|
||||
and _normalize_hop_vendor(body.hop_vendor) == "bastion"
|
||||
and _normalize_hop_target_auth_mode(body.hop_target_auth_mode) == "bastion_managed"
|
||||
)
|
||||
|
||||
|
||||
def _apply_hop_create(row: ManagedNE, body: ManagedNeCreate) -> None:
|
||||
|
|
@ -77,6 +94,7 @@ def _apply_hop_create(row: ManagedNE, body: ManagedNeCreate) -> None:
|
|||
row.hop_password_enc = encrypt_secret(body.hop_password) if body.hop_enabled else ""
|
||||
row.hop_command_template = str(body.hop_command_template or "").strip()
|
||||
row.hop_vrf = str(body.hop_vrf or "").strip()
|
||||
row.hop_target_auth_mode = _normalize_hop_target_auth_mode(body.hop_target_auth_mode)
|
||||
|
||||
|
||||
def _apply_hop_update(row: ManagedNE, data: dict[str, Any]) -> None:
|
||||
|
|
@ -99,6 +117,8 @@ def _apply_hop_update(row: ManagedNE, data: dict[str, Any]) -> None:
|
|||
row.hop_command_template = str(data["hop_command_template"]).strip()
|
||||
if "hop_vrf" in data and data["hop_vrf"] is not None:
|
||||
row.hop_vrf = str(data["hop_vrf"]).strip()
|
||||
if "hop_target_auth_mode" in data and data["hop_target_auth_mode"] is not None:
|
||||
row.hop_target_auth_mode = _normalize_hop_target_auth_mode(data["hop_target_auth_mode"])
|
||||
if row.hop_enabled:
|
||||
if not str(row.hop_host or "").strip():
|
||||
raise HTTPException(status_code=400, detail="hop_host_required")
|
||||
|
|
@ -135,6 +155,7 @@ def row_to_out(row: ManagedNE) -> ManagedNeOut:
|
|||
hop_username=str(row.hop_username or ""),
|
||||
hop_command_template=str(row.hop_command_template or ""),
|
||||
hop_vrf=str(row.hop_vrf or ""),
|
||||
hop_target_auth_mode=str(row.hop_target_auth_mode or "bastion_managed"),
|
||||
created_at=row.created_at,
|
||||
updated_at=row.updated_at,
|
||||
)
|
||||
|
|
@ -189,6 +210,8 @@ def get_managed_ne(db: Session, ne_id: str) -> ManagedNeOut:
|
|||
def create_managed_ne(db: Session, body: ManagedNeCreate) -> ManagedNeOut:
|
||||
_require_crypto()
|
||||
_validate_hop_on_create(body)
|
||||
if not str(body.password or "").strip() and not _target_password_optional(body):
|
||||
raise HTTPException(status_code=400, detail="password_required")
|
||||
ip = _normalize_ip(body.ip_address)
|
||||
if not ip:
|
||||
raise HTTPException(status_code=400, detail="ip_address_required")
|
||||
|
|
@ -206,7 +229,7 @@ def create_managed_ne(db: Session, body: ManagedNeCreate) -> ManagedNeOut:
|
|||
port=int(body.port or 22),
|
||||
protocol=_normalize_protocol(body.protocol),
|
||||
username=str(body.username or "").strip(),
|
||||
password_enc=encrypt_secret(body.password),
|
||||
password_enc=encrypt_secret(body.password) if str(body.password or "").strip() else "",
|
||||
enable_secret_enc="",
|
||||
connect_status="unknown",
|
||||
tags=str(body.tags or "").strip(),
|
||||
|
|
@ -266,6 +289,7 @@ def update_managed_ne(db: Session, ne_id: str, body: ManagedNeUpdate) -> Managed
|
|||
"hop_password",
|
||||
"hop_command_template",
|
||||
"hop_vrf",
|
||||
"hop_target_auth_mode",
|
||||
)
|
||||
if any(k in data for k in hop_keys):
|
||||
_apply_hop_update(row, data)
|
||||
|
|
@ -290,7 +314,9 @@ def batch_apply_hop_proxy(db: Session, ids: list[str], hop: HopProxyConfig) -> d
|
|||
|
||||
hop_vendor = _normalize_hop_vendor(hop.hop_vendor)
|
||||
template = str(hop.hop_command_template or "").strip()
|
||||
if hop_vendor != "linux" and not template:
|
||||
if hop_vendor == "bastion" and not template:
|
||||
template = default_bastion_username_template()
|
||||
elif hop_vendor not in ("linux", "bastion") and not template:
|
||||
template = default_hop_command_template(hop_vendor, hop.hop_protocol, hop.hop_vrf)
|
||||
|
||||
ne_ids = [str(x).strip() for x in ids if str(x).strip()]
|
||||
|
|
@ -315,6 +341,7 @@ def batch_apply_hop_proxy(db: Session, ids: list[str], hop: HopProxyConfig) -> d
|
|||
row.hop_password_enc = enc
|
||||
row.hop_command_template = template
|
||||
row.hop_vrf = str(hop.hop_vrf or "").strip()
|
||||
row.hop_target_auth_mode = _normalize_hop_target_auth_mode(hop.hop_target_auth_mode)
|
||||
row.updated_at = now
|
||||
db.commit()
|
||||
return {"ok": True, "updated": len(rows)}
|
||||
|
|
@ -484,4 +511,5 @@ def get_device_credentials(row: ManagedNE) -> dict[str, Any]:
|
|||
"hop_password": hop_password,
|
||||
"hop_command_template": str(row.hop_command_template or ""),
|
||||
"hop_vrf": str(row.hop_vrf or ""),
|
||||
"hop_target_auth_mode": str(row.hop_target_auth_mode or "bastion_managed"),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ from .ne_netmiko import normalize_netmiko_device_type
|
|||
|
||||
_log = logging.getLogger("netx.ne.session")
|
||||
|
||||
_HOP_PLACEHOLDERS = ("target_ip", "target_port", "target_user", "target_password", "vrf")
|
||||
_HOP_PLACEHOLDERS = ("target_ip", "target_port", "target_user", "target_password", "vrf", "hop_user", "hop_host")
|
||||
|
||||
# ZTE CLI jump: ssh/telnet <ip> [vrf <name>] — target user/password via secondary auth.
|
||||
_LEGACY_HOP_TEMPLATES = frozenset({"ssh {target_user}@{target_ip}", "ssh {target_ip}", "telnet {target_ip}"})
|
||||
|
|
@ -53,8 +53,15 @@ def default_huawei_hop_template(protocol: str, vrf: str = "") -> str:
|
|||
return "stelnet {target_ip}"
|
||||
|
||||
|
||||
def default_bastion_username_template() -> str:
|
||||
"""SSH bastion composite username (JumpServer/CBH/ZTE-TSM style)."""
|
||||
return "{hop_user}@{target_user}@{target_ip}@{hop_host}"
|
||||
|
||||
|
||||
def default_hop_command_template(vendor: str, protocol: str, vrf: str = "") -> str:
|
||||
v = str(vendor or "zte").strip().lower()
|
||||
if v == "bastion":
|
||||
return default_bastion_username_template()
|
||||
if v == "huawei":
|
||||
return default_huawei_hop_template(protocol, vrf)
|
||||
if v == "cisco":
|
||||
|
|
@ -81,6 +88,8 @@ def render_hop_command(template: str, creds: dict[str, Any]) -> str:
|
|||
"target_user": str(creds.get("username") or ""),
|
||||
"target_password": str(creds.get("password") or ""),
|
||||
"vrf": str(creds.get("hop_vrf") or "").strip(),
|
||||
"hop_user": str(creds.get("hop_username") or ""),
|
||||
"hop_host": str(creds.get("hop_host") or "").strip(),
|
||||
}
|
||||
out = tpl
|
||||
for key in _HOP_PLACEHOLDERS:
|
||||
|
|
@ -233,6 +242,42 @@ def _connect_via_cli_hop(creds: dict[str, Any], *, session_timeout: int | None =
|
|||
raise
|
||||
|
||||
|
||||
def _connect_via_bastion(creds: dict[str, Any], *, session_timeout: int | None = None) -> ConnectHandler:
|
||||
"""SSH to bastion with composite username; bastion proxies to target (protocol proxy)."""
|
||||
hop_host = str(creds.get("hop_host") or "").strip()
|
||||
hop_user = str(creds.get("hop_username") or "").strip()
|
||||
hop_pass = str(creds.get("hop_password") or "")
|
||||
if not hop_host or not hop_user or not hop_pass:
|
||||
raise ValueError("hop_credentials_incomplete")
|
||||
|
||||
composite_user = render_hop_command(str(creds.get("hop_command_template") or ""), creds)
|
||||
device_type = normalize_netmiko_device_type(creds["device_type"], creds["protocol"])
|
||||
hop_dev = _base_connect_kwargs(
|
||||
device_type=device_type,
|
||||
host=hop_host,
|
||||
port=int(creds.get("hop_port") or 22),
|
||||
username=composite_user,
|
||||
password=hop_pass,
|
||||
enable_secret=str(creds.get("enable_secret") or ""),
|
||||
session_timeout=session_timeout or 180,
|
||||
)
|
||||
conn = ConnectHandler(**hop_dev)
|
||||
auth_mode = str(creds.get("hop_target_auth_mode") or "bastion_managed").strip().lower()
|
||||
if auth_mode == "manual":
|
||||
target_pass = str(creds.get("password") or "")
|
||||
if target_pass:
|
||||
try:
|
||||
_read_channel(conn, wait=0.5)
|
||||
_interactive_target_auth(conn, str(creds["username"]), target_pass)
|
||||
except Exception:
|
||||
try:
|
||||
conn.disconnect()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
return conn
|
||||
|
||||
|
||||
def _connect_via_linux_hop(creds: dict[str, Any], *, session_timeout: int | None = None) -> ConnectHandler:
|
||||
"""SSH to Linux bastion, then direct-tcpip tunnel to target (classic ProxyJump-style)."""
|
||||
hop_host = str(creds.get("hop_host") or "").strip()
|
||||
|
|
@ -311,7 +356,10 @@ def close_netmiko_connection(conn: ConnectHandler | None) -> None:
|
|||
def open_netmiko_connection(creds: dict[str, Any], *, session_timeout: int | None = None) -> ConnectHandler:
|
||||
"""Open a Netmiko connection to the target NE (direct or via configured hop)."""
|
||||
if creds.get("hop_enabled"):
|
||||
if _hop_vendor(creds) == "linux":
|
||||
vendor = _hop_vendor(creds)
|
||||
if vendor == "linux":
|
||||
return _connect_via_linux_hop(creds, session_timeout=session_timeout)
|
||||
if vendor == "bastion":
|
||||
return _connect_via_bastion(creds, session_timeout=session_timeout)
|
||||
return _connect_via_cli_hop(creds, session_timeout=session_timeout)
|
||||
return _connect_direct(creds, session_timeout=session_timeout)
|
||||
|
|
|
|||
125
tests/test_bastion_hop.py
Normal file
125
tests/test_bastion_hop.py
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from netx_api.ne_session_factory import (
|
||||
default_bastion_username_template,
|
||||
open_netmiko_connection,
|
||||
render_hop_command,
|
||||
)
|
||||
|
||||
|
||||
class BastionTemplateTests(unittest.TestCase):
|
||||
def test_default_bastion_username_template(self) -> None:
|
||||
self.assertEqual(
|
||||
default_bastion_username_template(),
|
||||
"{hop_user}@{target_user}@{target_ip}@{hop_host}",
|
||||
)
|
||||
|
||||
def test_render_bastion_composite_username(self) -> None:
|
||||
creds = {
|
||||
"hop_vendor": "bastion",
|
||||
"hop_username": "ZTE-TSM",
|
||||
"hop_host": "10.34.145.27",
|
||||
"username": "ca-oper",
|
||||
"ip_address": "114.0.44.11",
|
||||
"hop_protocol": "ssh",
|
||||
"hop_vrf": "",
|
||||
}
|
||||
out = render_hop_command("", creds)
|
||||
self.assertEqual(out, "ZTE-TSM@ca-oper@114.0.44.11@10.34.145.27")
|
||||
|
||||
def test_render_custom_bastion_template(self) -> None:
|
||||
creds = {
|
||||
"hop_vendor": "bastion",
|
||||
"hop_username": "admin",
|
||||
"hop_host": "1.2.3.4",
|
||||
"username": "root",
|
||||
"ip_address": "5.6.7.8",
|
||||
"hop_command_template": "{hop_user}#{target_user}@{target_ip}",
|
||||
"hop_protocol": "ssh",
|
||||
"hop_vrf": "",
|
||||
}
|
||||
out = render_hop_command(creds["hop_command_template"], creds)
|
||||
self.assertEqual(out, "admin#root@5.6.7.8")
|
||||
|
||||
|
||||
class BastionConnectRoutingTests(unittest.TestCase):
|
||||
@patch("netx_api.ne_session_factory._connect_via_bastion")
|
||||
@patch("netx_api.ne_session_factory._connect_direct")
|
||||
def test_open_routes_to_bastion_when_enabled(self, direct, bastion) -> None:
|
||||
bastion.return_value = MagicMock()
|
||||
creds = {"hop_enabled": True, "hop_vendor": "bastion"}
|
||||
open_netmiko_connection(creds)
|
||||
bastion.assert_called_once()
|
||||
direct.assert_not_called()
|
||||
|
||||
@patch("netx_api.ne_session_factory._connect_via_bastion")
|
||||
@patch("netx_api.ne_session_factory._connect_via_linux_hop")
|
||||
def test_open_routes_linux_not_bastion(self, linux, bastion) -> None:
|
||||
linux.return_value = MagicMock()
|
||||
creds = {"hop_enabled": True, "hop_vendor": "linux"}
|
||||
open_netmiko_connection(creds)
|
||||
linux.assert_called_once()
|
||||
bastion.assert_not_called()
|
||||
|
||||
|
||||
class BastionConnectImplTests(unittest.TestCase):
|
||||
@patch("netx_api.ne_session_factory.ConnectHandler")
|
||||
def test_bastion_managed_skips_secondary_auth(self, connect_handler) -> None:
|
||||
from netx_api.ne_session_factory import _connect_via_bastion
|
||||
|
||||
conn = MagicMock()
|
||||
connect_handler.return_value = conn
|
||||
creds = {
|
||||
"hop_host": "10.34.145.27",
|
||||
"hop_username": "ZTE-TSM",
|
||||
"hop_password": "vault-pass",
|
||||
"hop_port": 22,
|
||||
"device_type": "zte_zxros",
|
||||
"protocol": "ssh",
|
||||
"username": "ca-oper",
|
||||
"ip_address": "114.0.44.11",
|
||||
"password": "",
|
||||
"hop_target_auth_mode": "bastion_managed",
|
||||
"hop_vendor": "bastion",
|
||||
"hop_protocol": "ssh",
|
||||
"hop_vrf": "",
|
||||
}
|
||||
_connect_via_bastion(creds)
|
||||
kwargs = connect_handler.call_args.kwargs
|
||||
self.assertEqual(kwargs["host"], "10.34.145.27")
|
||||
self.assertEqual(kwargs["username"], "ZTE-TSM@ca-oper@114.0.44.11@10.34.145.27")
|
||||
self.assertEqual(kwargs["password"], "vault-pass")
|
||||
conn.disconnect.assert_not_called()
|
||||
|
||||
@patch("netx_api.ne_session_factory._interactive_target_auth")
|
||||
@patch("netx_api.ne_session_factory._read_channel")
|
||||
@patch("netx_api.ne_session_factory.ConnectHandler")
|
||||
def test_bastion_manual_invokes_secondary_auth(self, connect_handler, _read, interact) -> None:
|
||||
from netx_api.ne_session_factory import _connect_via_bastion
|
||||
|
||||
conn = MagicMock()
|
||||
connect_handler.return_value = conn
|
||||
creds = {
|
||||
"hop_host": "10.0.0.1",
|
||||
"hop_username": "bastion-user",
|
||||
"hop_password": "bastion-pass",
|
||||
"hop_port": 2222,
|
||||
"device_type": "cisco_ios",
|
||||
"protocol": "ssh",
|
||||
"username": "target-user",
|
||||
"ip_address": "10.0.0.2",
|
||||
"password": "target-pass",
|
||||
"hop_target_auth_mode": "manual",
|
||||
"hop_vendor": "bastion",
|
||||
"hop_protocol": "ssh",
|
||||
"hop_vrf": "",
|
||||
}
|
||||
_connect_via_bastion(creds)
|
||||
interact.assert_called_once_with(conn, "target-user", "target-pass")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -4,8 +4,10 @@ import {
|
|||
HOP_VENDORS,
|
||||
defaultHopTemplate,
|
||||
isAutoHopTemplate,
|
||||
isBastionHopVendor,
|
||||
isLinuxHopVendor,
|
||||
patchHopVendorChange,
|
||||
type HopTargetAuthMode,
|
||||
type HopVendor,
|
||||
} from "../utils/hopProxy";
|
||||
|
||||
|
|
@ -18,6 +20,7 @@ export type HopProxyFieldsState = {
|
|||
hop_password: string;
|
||||
hop_command_template: string;
|
||||
hop_vrf: string;
|
||||
hop_target_auth_mode: HopTargetAuthMode;
|
||||
};
|
||||
|
||||
export const emptyHopProxyFields = (): HopProxyFieldsState => ({
|
||||
|
|
@ -29,6 +32,7 @@ export const emptyHopProxyFields = (): HopProxyFieldsState => ({
|
|||
hop_password: "",
|
||||
hop_command_template: defaultHopTemplate("zte", "ssh", ""),
|
||||
hop_vrf: "",
|
||||
hop_target_auth_mode: "bastion_managed",
|
||||
});
|
||||
|
||||
function FormLabel({ children, required }: { children: ReactNode; required?: boolean }) {
|
||||
|
|
@ -59,6 +63,7 @@ function applyHopTemplate(
|
|||
|
||||
function hopHintKey(vendor: string): string {
|
||||
const v = String(vendor || "").toLowerCase();
|
||||
if (v === "bastion") return "managedNe.hop.bastionHint";
|
||||
if (v === "linux") return "managedNe.hop.linuxHint";
|
||||
if (v === "huawei") return "managedNe.hop.huaweiHint";
|
||||
if (v === "cisco") return "managedNe.hop.ciscoHint";
|
||||
|
|
@ -67,6 +72,7 @@ function hopHintKey(vendor: string): string {
|
|||
|
||||
function templateHintKey(vendor: string): string {
|
||||
const v = String(vendor || "").toLowerCase();
|
||||
if (v === "bastion") return "managedNe.hop.templateHintBastion";
|
||||
if (v === "huawei") return "managedNe.hop.templateHintHuawei";
|
||||
if (v === "cisco") return "managedNe.hop.templateHintCisco";
|
||||
return "managedNe.hop.templateHint";
|
||||
|
|
@ -94,7 +100,9 @@ export function HopProxyFields({
|
|||
}: Props) {
|
||||
const { t } = useI18n();
|
||||
const linux = isLinuxHopVendor(value.hop_vendor);
|
||||
const bastion = isBastionHopVendor(value.hop_vendor);
|
||||
const huawei = value.hop_vendor === "huawei";
|
||||
const cliHop = !linux && !bastion;
|
||||
|
||||
const set = (patch: Partial<HopProxyFieldsState>) => onChange(patch);
|
||||
|
||||
|
|
@ -129,7 +137,20 @@ export function HopProxyFields({
|
|||
onChange={(e) => set({ hop_port: Number(e.target.value) || 22 })}
|
||||
/>
|
||||
</label>
|
||||
{!linux ? (
|
||||
{bastion ? (
|
||||
<label className="form-grid__full">
|
||||
<FormLabel>{t("managedNe.hop.targetAuthMode")}</FormLabel>
|
||||
<select
|
||||
value={value.hop_target_auth_mode}
|
||||
onChange={(e) => set({ hop_target_auth_mode: e.target.value as HopTargetAuthMode })}
|
||||
>
|
||||
<option value="bastion_managed">{t("managedNe.hop.targetAuthBastionManaged")}</option>
|
||||
<option value="manual">{t("managedNe.hop.targetAuthManual")}</option>
|
||||
</select>
|
||||
<span className="form-field-hint">{t("managedNe.hop.targetAuthHint")}</span>
|
||||
</label>
|
||||
) : null}
|
||||
{cliHop ? (
|
||||
<label>
|
||||
<FormLabel>{t("managedNe.hop.protocol")}</FormLabel>
|
||||
<select
|
||||
|
|
@ -162,7 +183,18 @@ export function HopProxyFields({
|
|||
onChange={(e) => set({ hop_password: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
{!linux ? (
|
||||
{bastion ? (
|
||||
<label className="form-grid__full">
|
||||
<FormLabel>{t("managedNe.hop.usernameTemplate")}</FormLabel>
|
||||
<input
|
||||
value={value.hop_command_template}
|
||||
onChange={(e) => set({ hop_command_template: e.target.value })}
|
||||
placeholder={defaultHopTemplate(value.hop_vendor, value.hop_protocol, value.hop_vrf)}
|
||||
/>
|
||||
<span className="form-field-hint">{t(templateHintKey(value.hop_vendor))}</span>
|
||||
</label>
|
||||
) : null}
|
||||
{cliHop ? (
|
||||
<>
|
||||
<label>
|
||||
<FormLabel>{t(vrfLabelKey(value.hop_vendor))}</FormLabel>
|
||||
|
|
|
|||
|
|
@ -195,11 +195,21 @@ const en = {
|
|||
huawei: "Huawei device (CLI jump)",
|
||||
cisco: "Cisco device (CLI jump)",
|
||||
linux: "Linux server (SSH tunnel)",
|
||||
bastion: "Bastion host (SSH protocol proxy)",
|
||||
},
|
||||
zteHint: "Run ssh/telnet on the ZTE device to reach the target; target credentials use secondary auth.",
|
||||
huaweiHint: "Run telnet / stelnet (SSH) on the Huawei hop; stelnet is SSH. Target credentials use secondary auth.",
|
||||
ciscoHint: "Run Cisco ssh -vrf / telnet /vrf jump commands; target credentials use secondary auth.",
|
||||
linuxHint: "SSH to the Linux bastion, then direct-tcpip tunnel to target IP:port (ProxyJump-style).",
|
||||
bastionHint:
|
||||
"SSH with composite username via bastion protocol proxy. Example: user@account@target_ip@bastion_host; password is the bastion/Vault password. JumpServer/CBH often use port 2222.",
|
||||
targetAuthMode: "Target credentials",
|
||||
targetAuthBastionManaged: "Bastion-managed (target password optional)",
|
||||
targetAuthManual: "Manual (secondary auth after connect)",
|
||||
targetAuthHint: "Bastion-managed needs only bastion password; manual mode requires target NE password.",
|
||||
usernameTemplate: "SSH username template",
|
||||
templateHintBastion:
|
||||
"Default {hop_user}@{target_user}@{target_ip}@{hop_host}. Same when left blank.",
|
||||
host: "Jump host",
|
||||
port: "Jump port",
|
||||
protocol: "Jump protocol",
|
||||
|
|
@ -221,6 +231,7 @@ const en = {
|
|||
huawei: "Huawei hop",
|
||||
cisco: "Cisco hop",
|
||||
linux: "Linux hop",
|
||||
bastion: "Bastion",
|
||||
},
|
||||
hostRequired: "Jump host is required",
|
||||
userRequired: "Jump username is required",
|
||||
|
|
|
|||
|
|
@ -193,11 +193,21 @@ const zh = {
|
|||
huawei: "华为设备(CLI 跳登)",
|
||||
cisco: "思科设备(CLI 跳登)",
|
||||
linux: "Linux 服务器(SSH 隧道)",
|
||||
bastion: "堡垒机(SSH 协议代理)",
|
||||
},
|
||||
zteHint: "在 ZTE 设备上执行 ssh/telnet 命令跳转到目标,目标账号由二次认证输入。",
|
||||
huaweiHint: "在华为设备上执行 telnet / stelnet(SSH)跳登;stelnet 即 SSH。目标账号由二次认证输入。",
|
||||
ciscoHint: "在思科设备上执行 ssh -vrf / telnet /vrf 跳登,目标账号由二次认证输入。",
|
||||
linuxHint: "先 SSH 登录 Linux 跳板,经 direct-tcpip 隧道连接目标 IP:端口(等同 ProxyJump)。",
|
||||
bastionHint:
|
||||
"SSH 复合用户名直连堡垒机,由堡垒机协议代理到目标。示例:ZTE-TSM@ca-oper@114.0.44.11@10.34.145.27;密码为 Vault/堡垒机密码。JumpServer/CBH 常用端口 2222。",
|
||||
targetAuthMode: "目标凭据",
|
||||
targetAuthBastionManaged: "堡垒机托管(目标密码可留空)",
|
||||
targetAuthManual: "手动输入(连接后二次认证)",
|
||||
targetAuthHint: "堡垒机托管时仅需堡垒机密码;手动模式需填写目标网元密码。",
|
||||
usernameTemplate: "SSH 用户名模板",
|
||||
templateHintBastion:
|
||||
"默认 {hop_user}@{target_user}@{target_ip}@{hop_host}。留空时后端同样规则。示例:ZTE-TSM@ca-oper@114.0.44.11@10.34.145.27。",
|
||||
host: "跳板地址",
|
||||
port: "跳板端口",
|
||||
protocol: "跳板协议",
|
||||
|
|
@ -219,6 +229,7 @@ const zh = {
|
|||
huawei: "华为跳板",
|
||||
cisco: "思科跳板",
|
||||
linux: "Linux跳板",
|
||||
bastion: "堡垒机",
|
||||
},
|
||||
hostRequired: "请填写跳板地址",
|
||||
userRequired: "请填写跳板用户名",
|
||||
|
|
|
|||
|
|
@ -46,6 +46,7 @@ type FormState = {
|
|||
hop_password: string;
|
||||
hop_command_template: string;
|
||||
hop_vrf: string;
|
||||
hop_target_auth_mode: "bastion_managed" | "manual";
|
||||
};
|
||||
|
||||
const emptyForm = (): FormState => ({
|
||||
|
|
@ -68,6 +69,7 @@ const emptyForm = (): FormState => ({
|
|||
hop_password: "",
|
||||
hop_command_template: defaultHopTemplate("zte", "ssh", ""),
|
||||
hop_vrf: "",
|
||||
hop_target_auth_mode: "bastion_managed",
|
||||
});
|
||||
|
||||
function applyHopTemplate(prev: FormState, protocol: string, vrf: string, force = false): Partial<FormState> {
|
||||
|
|
@ -179,9 +181,14 @@ export function NePage() {
|
|||
hop_username: form.hop_username,
|
||||
hop_command_template: form.hop_command_template,
|
||||
hop_vrf: form.hop_vrf,
|
||||
hop_target_auth_mode: form.hop_target_auth_mode,
|
||||
...(form.password ? { password: form.password } : {}),
|
||||
...(form.hop_password ? { hop_password: form.hop_password } : {}),
|
||||
};
|
||||
const bastionManaged =
|
||||
form.hop_enabled &&
|
||||
form.hop_vendor === "bastion" &&
|
||||
form.hop_target_auth_mode === "bastion_managed";
|
||||
if (form.hop_enabled) {
|
||||
if (!form.hop_host.trim()) throw new Error(t("managedNe.hop.hostRequired"));
|
||||
if (!form.hop_username.trim()) throw new Error(t("managedNe.hop.userRequired"));
|
||||
|
|
@ -192,8 +199,8 @@ export function NePage() {
|
|||
if (!form.hop_password) delete (body as { hop_password?: string }).hop_password;
|
||||
return updateManagedNe(editing.id, body);
|
||||
}
|
||||
if (!form.password) throw new Error(t("managedNe.form.passwordRequired"));
|
||||
return createManagedNe({ ...body, password: form.password });
|
||||
if (!form.password && !bastionManaged) throw new Error(t("managedNe.form.passwordRequired"));
|
||||
return createManagedNe({ ...body, password: form.password || "" });
|
||||
},
|
||||
onSuccess: async () => {
|
||||
setModalOpen(false);
|
||||
|
|
@ -244,6 +251,7 @@ export function NePage() {
|
|||
hop_password: batchHop.hop_password,
|
||||
hop_command_template: batchHop.hop_command_template.trim(),
|
||||
hop_vrf: batchHop.hop_vrf.trim(),
|
||||
hop_target_auth_mode: batchHop.hop_target_auth_mode,
|
||||
}),
|
||||
onSuccess: async (res) => {
|
||||
setBatchHopOpen(false);
|
||||
|
|
@ -298,7 +306,7 @@ export function NePage() {
|
|||
tags: row.tags,
|
||||
remark: row.remark,
|
||||
hop_enabled: row.hop_enabled,
|
||||
hop_vendor: (["linux", "huawei", "cisco", "zte"].includes(row.hop_vendor)
|
||||
hop_vendor: (["linux", "huawei", "cisco", "zte", "bastion"].includes(row.hop_vendor)
|
||||
? row.hop_vendor
|
||||
: "zte") as HopVendor,
|
||||
hop_host: row.hop_host,
|
||||
|
|
@ -315,6 +323,8 @@ export function NePage() {
|
|||
? defaultHopTemplate(row.hop_vendor, row.hop_protocol, row.hop_vrf)
|
||||
: row.hop_command_template || defaultHopTemplate(row.hop_vendor, row.hop_protocol, row.hop_vrf),
|
||||
hop_vrf: row.hop_vrf,
|
||||
hop_target_auth_mode:
|
||||
row.hop_target_auth_mode === "manual" ? "manual" : "bastion_managed",
|
||||
});
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
|
@ -489,7 +499,7 @@ export function NePage() {
|
|||
title={`${row.hop_host}:${row.hop_port} (${row.hop_vendor})`}
|
||||
>
|
||||
{t(
|
||||
`managedNe.hop.badge.${["linux", "huawei", "cisco", "zte"].includes(row.hop_vendor) ? row.hop_vendor : "zte"}`,
|
||||
`managedNe.hop.badge.${["linux", "huawei", "cisco", "zte", "bastion"].includes(row.hop_vendor) ? row.hop_vendor : "zte"}`,
|
||||
)}
|
||||
</span>
|
||||
) : null}
|
||||
|
|
@ -628,15 +638,34 @@ export function NePage() {
|
|||
/>
|
||||
</label>
|
||||
<label>
|
||||
<FormLabel required={!editing}>
|
||||
<FormLabel
|
||||
required={
|
||||
!editing &&
|
||||
!(
|
||||
form.hop_enabled &&
|
||||
form.hop_vendor === "bastion" &&
|
||||
form.hop_target_auth_mode === "bastion_managed"
|
||||
)
|
||||
}
|
||||
>
|
||||
{t("managedNe.col.password")}
|
||||
{editing ? (
|
||||
{editing ||
|
||||
(form.hop_enabled &&
|
||||
form.hop_vendor === "bastion" &&
|
||||
form.hop_target_auth_mode === "bastion_managed") ? (
|
||||
<span className="form-label__optional"> ({t("managedNe.form.passwordOptional")})</span>
|
||||
) : null}
|
||||
</FormLabel>
|
||||
<input
|
||||
type="password"
|
||||
required={!editing}
|
||||
required={
|
||||
!editing &&
|
||||
!(
|
||||
form.hop_enabled &&
|
||||
form.hop_vendor === "bastion" &&
|
||||
form.hop_target_auth_mode === "bastion_managed"
|
||||
)
|
||||
}
|
||||
value={form.password}
|
||||
onChange={(e) => setForm({ ...form, password: e.target.value })}
|
||||
/>
|
||||
|
|
@ -684,6 +713,7 @@ export function NePage() {
|
|||
hop_password: form.hop_password,
|
||||
hop_command_template: form.hop_command_template,
|
||||
hop_vrf: form.hop_vrf,
|
||||
hop_target_auth_mode: form.hop_target_auth_mode,
|
||||
}}
|
||||
onChange={(patch) => setForm((prev) => ({ ...prev, ...patch }))}
|
||||
hopPasswordRequired={!editing}
|
||||
|
|
|
|||
|
|
@ -143,6 +143,7 @@ export const batchApplyHopManagedNe = (
|
|||
hop_command_template: string;
|
||||
hop_vrf: string;
|
||||
hop_vendor?: string;
|
||||
hop_target_auth_mode?: string;
|
||||
},
|
||||
) => apiPost<{ ok: boolean; updated: number }>("/v1/managed-ne/batch-hop", { ids, hop });
|
||||
|
||||
|
|
|
|||
|
|
@ -144,6 +144,7 @@ export type ManagedNeItem = {
|
|||
hop_username: string;
|
||||
hop_command_template: string;
|
||||
hop_vrf: string;
|
||||
hop_target_auth_mode: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -2,9 +2,19 @@
|
|||
|
||||
import { ciscoHopTemplate, huaweiHopTemplate, isAutoHopTemplate, zteHopTemplate } from "./zteHop";
|
||||
|
||||
export type HopVendor = "zte" | "huawei" | "cisco" | "linux";
|
||||
export type HopVendor = "zte" | "huawei" | "cisco" | "linux" | "bastion";
|
||||
|
||||
export const HOP_VENDORS: HopVendor[] = ["zte", "huawei", "cisco", "linux"];
|
||||
export type HopTargetAuthMode = "bastion_managed" | "manual";
|
||||
|
||||
export const HOP_VENDORS: HopVendor[] = ["zte", "huawei", "cisco", "linux", "bastion"];
|
||||
|
||||
export function bastionHopTemplate(): string {
|
||||
return "{hop_user}@{target_user}@{target_ip}@{hop_host}";
|
||||
}
|
||||
|
||||
export function isBastionHopVendor(vendor: string): boolean {
|
||||
return String(vendor || "").toLowerCase() === "bastion";
|
||||
}
|
||||
|
||||
export function isLinuxHopVendor(vendor: string): boolean {
|
||||
return String(vendor || "").toLowerCase() === "linux";
|
||||
|
|
@ -20,16 +30,34 @@ export function defaultHopTemplate(vendor: string, protocol: string, vrf: string
|
|||
if (v === "huawei") return huaweiHopTemplate(protocol, vrf);
|
||||
if (v === "cisco") return ciscoHopTemplate(protocol, vrf);
|
||||
if (v === "linux") return "";
|
||||
if (v === "bastion") return bastionHopTemplate();
|
||||
return zteHopTemplate(protocol, vrf);
|
||||
}
|
||||
|
||||
export function patchHopVendorChange(
|
||||
vendor: HopVendor,
|
||||
prev: { hop_protocol: string; hop_vrf: string; hop_command_template: string; hop_vendor?: string },
|
||||
): { hop_vendor: HopVendor; hop_protocol: string; hop_vrf: string; hop_command_template: string } {
|
||||
): {
|
||||
hop_vendor: HopVendor;
|
||||
hop_protocol: string;
|
||||
hop_vrf: string;
|
||||
hop_command_template: string;
|
||||
hop_port?: number;
|
||||
hop_target_auth_mode?: HopTargetAuthMode;
|
||||
} {
|
||||
if (vendor === "linux") {
|
||||
return { hop_vendor: "linux", hop_protocol: "ssh", hop_vrf: "", hop_command_template: "" };
|
||||
}
|
||||
if (vendor === "bastion") {
|
||||
return {
|
||||
hop_vendor: "bastion",
|
||||
hop_protocol: "ssh",
|
||||
hop_port: 22,
|
||||
hop_vrf: "",
|
||||
hop_command_template: bastionHopTemplate(),
|
||||
hop_target_auth_mode: "bastion_managed" as HopTargetAuthMode,
|
||||
};
|
||||
}
|
||||
const protocol = prev.hop_protocol || "ssh";
|
||||
const vrf = prev.hop_vrf || "";
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -42,5 +42,6 @@ export function isAutoHopTemplate(
|
|||
if (v === "huawei") return t === huaweiHopTemplate(protocol, vrf);
|
||||
if (v === "cisco") return t === ciscoHopTemplate(protocol, vrf);
|
||||
if (v === "linux") return t === "";
|
||||
if (v === "bastion") return t === "{hop_user}@{target_user}@{target_ip}@{hop_host}";
|
||||
return t === zteHopTemplate(protocol, vrf);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue