ssh_bastion_host.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # Copyright Materialize, Inc. and contributors. All rights reserved.
  2. #
  3. # Use of this software is governed by the Business Source License
  4. # included in the LICENSE file at the root of this repository.
  5. #
  6. # As of the Change Date specified in that file, in accordance with
  7. # the Business Source License, use of this software will be governed
  8. # by the Apache License, Version 2.0.
  9. import os
  10. from materialize import MZ_ROOT
  11. from materialize.mzcompose import (
  12. loader,
  13. )
  14. from materialize.mzcompose.composition import Composition
  15. from materialize.mzcompose.service import (
  16. Service,
  17. )
  18. class SshBastionHost(Service):
  19. def __init__(
  20. self,
  21. name: str = "ssh-bastion-host",
  22. max_startups: str | None = None,
  23. aliases: list[str] | None = None,
  24. ) -> None:
  25. setup_path = os.path.relpath(
  26. MZ_ROOT / "misc" / "images" / "sshd" / "setup.sh",
  27. loader.composition_path,
  28. )
  29. if aliases is None:
  30. aliases = ["other_ssh_bastion"]
  31. super().__init__(
  32. name=name,
  33. config={
  34. "mzbuild": "ssh-bastion-host",
  35. "init": True,
  36. "ports": ["22"],
  37. "environment": [
  38. "SSH_USERS=mz:1000:1000",
  39. "TCP_FORWARDING=true",
  40. *([f"MAX_STARTUPS={max_startups}"] if max_startups else []),
  41. ],
  42. "volumes": [f"{setup_path}:/etc/entrypoint.d/setup.sh"],
  43. "networks": {"default": {"aliases": aliases}},
  44. "healthcheck": {
  45. "test": "[ -f /var/run/sshd/sshd.pid ]",
  46. "timeout": "5s",
  47. "interval": "1s",
  48. "start_period": "60s",
  49. },
  50. },
  51. )
  52. def setup_default_ssh_test_connection(
  53. c: Composition, ssh_tunnel_name: str, mz_service: str | None = None
  54. ) -> None:
  55. c.sql(
  56. f"""
  57. CREATE CONNECTION IF NOT EXISTS {ssh_tunnel_name} TO SSH TUNNEL (
  58. HOST 'ssh-bastion-host',
  59. USER 'mz',
  60. PORT 22)
  61. """,
  62. service=mz_service,
  63. )
  64. public_key = c.sql_query(
  65. f"""
  66. select public_key_1 from mz_ssh_tunnel_connections ssh \
  67. join mz_connections c on c.id = ssh.id
  68. where c.name = '{ssh_tunnel_name}';
  69. """,
  70. service=mz_service,
  71. )[0][0]
  72. c.exec(
  73. "ssh-bastion-host",
  74. "bash",
  75. "-c",
  76. f"echo '{public_key}' >> /etc/authorized_keys/mz",
  77. )