|
| 1 | +//! SSH Key Setup Action |
| 2 | +//! |
| 3 | +//! This module provides an action to setup SSH key authentication inside a container. |
| 4 | +//! The action is decoupled from specific container implementations and can be used |
| 5 | +//! with any container that implements the `ContainerExecutor` trait. |
| 6 | +
|
| 7 | +use std::fs; |
| 8 | +use testcontainers::core::ExecCommand; |
| 9 | +use tracing::info; |
| 10 | + |
| 11 | +use crate::e2e::containers::ContainerExecutor; |
| 12 | +use crate::infrastructure::adapters::ssh::SshCredentials; |
| 13 | + |
| 14 | +/// Specific error types for SSH key setup operations |
| 15 | +#[derive(Debug, thiserror::Error)] |
| 16 | +pub enum SshKeySetupError { |
| 17 | + /// Failed to read SSH public key file |
| 18 | + #[error("Failed to read SSH public key from {path}: {source}")] |
| 19 | + SshKeyFileRead { |
| 20 | + path: String, |
| 21 | + #[source] |
| 22 | + source: std::io::Error, |
| 23 | + }, |
| 24 | + |
| 25 | + /// Failed to execute SSH key setup command in container |
| 26 | + #[error("Failed to setup SSH keys in container: {source}")] |
| 27 | + SshKeySetupFailed { |
| 28 | + #[source] |
| 29 | + source: testcontainers::TestcontainersError, |
| 30 | + }, |
| 31 | +} |
| 32 | + |
| 33 | +/// Result type alias for SSH key setup operations |
| 34 | +pub type Result<T> = std::result::Result<T, SshKeySetupError>; |
| 35 | + |
| 36 | +/// Action to setup SSH key authentication inside a container |
| 37 | +/// |
| 38 | +/// This action configures SSH key authentication by: |
| 39 | +/// 1. Reading the public key from the credentials |
| 40 | +/// 2. Creating the SSH directory for the specified user |
| 41 | +/// 3. Adding the public key to the `authorized_keys` file |
| 42 | +/// 4. Setting appropriate permissions |
| 43 | +/// |
| 44 | +/// ## Usage |
| 45 | +/// |
| 46 | +/// ```rust,no_run |
| 47 | +/// use torrust_tracker_deploy::e2e::containers::{ContainerExecutor, actions::SshKeySetupAction}; |
| 48 | +/// use torrust_tracker_deploy::infrastructure::adapters::ssh::SshCredentials; |
| 49 | +/// |
| 50 | +/// fn setup_ssh<T: ContainerExecutor>( |
| 51 | +/// container: &T, |
| 52 | +/// credentials: &SshCredentials, |
| 53 | +/// ) -> Result<(), Box<dyn std::error::Error>> { |
| 54 | +/// let action = SshKeySetupAction; |
| 55 | +/// action.execute(container, credentials)?; |
| 56 | +/// Ok(()) |
| 57 | +/// } |
| 58 | +/// ``` |
| 59 | +#[derive(Debug, Default)] |
| 60 | +pub struct SshKeySetupAction; |
| 61 | + |
| 62 | +impl SshKeySetupAction { |
| 63 | + /// Create a new SSH key setup action |
| 64 | + #[must_use] |
| 65 | + pub fn new() -> Self { |
| 66 | + Self |
| 67 | + } |
| 68 | + |
| 69 | + /// Execute the SSH key setup action |
| 70 | + /// |
| 71 | + /// # Arguments |
| 72 | + /// |
| 73 | + /// * `container` - Container that implements `ContainerExecutor` |
| 74 | + /// * `ssh_credentials` - SSH credentials containing the public key path and username |
| 75 | + /// |
| 76 | + /// # Errors |
| 77 | + /// |
| 78 | + /// Returns an error if: |
| 79 | + /// - SSH public key file cannot be read |
| 80 | + /// - Container exec command fails |
| 81 | + /// - SSH key file operations fail within the container |
| 82 | + pub fn execute<T: ContainerExecutor>( |
| 83 | + &self, |
| 84 | + container: &T, |
| 85 | + ssh_credentials: &SshCredentials, |
| 86 | + ) -> Result<()> { |
| 87 | + info!("Setting up SSH key authentication"); |
| 88 | + |
| 89 | + // Read the public key from the credentials |
| 90 | + let public_key_content = |
| 91 | + fs::read_to_string(&ssh_credentials.ssh_pub_key_path).map_err(|source| { |
| 92 | + SshKeySetupError::SshKeyFileRead { |
| 93 | + path: ssh_credentials.ssh_pub_key_path.display().to_string(), |
| 94 | + source, |
| 95 | + } |
| 96 | + })?; |
| 97 | + |
| 98 | + // Create the authorized_keys file for the SSH user in the container |
| 99 | + let ssh_user = &ssh_credentials.ssh_username; |
| 100 | + let user_ssh_dir = format!("/home/{ssh_user}/.ssh"); |
| 101 | + let authorized_keys_path = format!("{user_ssh_dir}/authorized_keys"); |
| 102 | + |
| 103 | + // Execute the command to setup SSH keys |
| 104 | + let command = ExecCommand::new([ |
| 105 | + "sh", |
| 106 | + "-c", |
| 107 | + &format!( |
| 108 | + "mkdir -p {} && echo '{}' >> {} && chmod 700 {} && chmod 600 {}", |
| 109 | + user_ssh_dir, |
| 110 | + public_key_content.trim(), |
| 111 | + authorized_keys_path, |
| 112 | + user_ssh_dir, |
| 113 | + authorized_keys_path |
| 114 | + ), |
| 115 | + ]); |
| 116 | + |
| 117 | + container |
| 118 | + .exec(command) |
| 119 | + .map_err(|source| SshKeySetupError::SshKeySetupFailed { source })?; |
| 120 | + |
| 121 | + info!( |
| 122 | + ssh_user = ssh_user, |
| 123 | + authorized_keys = authorized_keys_path, |
| 124 | + "SSH key authentication configured" |
| 125 | + ); |
| 126 | + |
| 127 | + Ok(()) |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +#[cfg(test)] |
| 132 | +mod tests { |
| 133 | + use super::*; |
| 134 | + use std::error::Error; |
| 135 | + use std::path::PathBuf; |
| 136 | + |
| 137 | + #[test] |
| 138 | + fn it_should_create_new_ssh_key_setup_action() { |
| 139 | + let action = SshKeySetupAction::new(); |
| 140 | + assert!(std::ptr::eq( |
| 141 | + std::ptr::addr_of!(action), |
| 142 | + std::ptr::addr_of!(action) |
| 143 | + )); // Just test it exists |
| 144 | + } |
| 145 | + |
| 146 | + #[test] |
| 147 | + fn it_should_create_default_ssh_key_setup_action() { |
| 148 | + let action = SshKeySetupAction; |
| 149 | + assert!(std::ptr::eq( |
| 150 | + std::ptr::addr_of!(action), |
| 151 | + std::ptr::addr_of!(action) |
| 152 | + )); // Just test it exists |
| 153 | + } |
| 154 | + |
| 155 | + #[test] |
| 156 | + fn it_should_have_proper_error_display_messages() { |
| 157 | + let error = SshKeySetupError::SshKeyFileRead { |
| 158 | + path: "/path/to/key".to_string(), |
| 159 | + source: std::io::Error::new(std::io::ErrorKind::NotFound, "file not found"), |
| 160 | + }; |
| 161 | + assert!(error.to_string().contains("Failed to read SSH public key")); |
| 162 | + assert!(error.to_string().contains("/path/to/key")); |
| 163 | + } |
| 164 | + |
| 165 | + #[test] |
| 166 | + fn it_should_preserve_error_chain_for_ssh_key_file_read() { |
| 167 | + let io_error = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found"); |
| 168 | + let error = SshKeySetupError::SshKeyFileRead { |
| 169 | + path: "/path/to/key".to_string(), |
| 170 | + source: io_error, |
| 171 | + }; |
| 172 | + |
| 173 | + assert!(error.source().is_some()); |
| 174 | + } |
| 175 | + |
| 176 | + #[test] |
| 177 | + fn it_should_preserve_error_chain_for_ssh_key_setup_failed() { |
| 178 | + let testcontainers_error = testcontainers::TestcontainersError::other("test error"); |
| 179 | + let error = SshKeySetupError::SshKeySetupFailed { |
| 180 | + source: testcontainers_error, |
| 181 | + }; |
| 182 | + |
| 183 | + assert!(error.source().is_some()); |
| 184 | + } |
| 185 | + |
| 186 | + // Helper function to create mock SSH credentials for testing |
| 187 | + #[allow(dead_code)] |
| 188 | + fn create_mock_ssh_credentials() -> SshCredentials { |
| 189 | + SshCredentials::new( |
| 190 | + PathBuf::from("/mock/path/to/private_key"), |
| 191 | + PathBuf::from("/mock/path/to/public_key.pub"), |
| 192 | + "testuser".to_string(), |
| 193 | + ) |
| 194 | + } |
| 195 | +} |
0 commit comments