-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patherrors.rs
More file actions
511 lines (476 loc) · 21.4 KB
/
errors.rs
File metadata and controls
511 lines (476 loc) · 21.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! Configuration validation errors with actionable help messages
//!
//! This module defines error types for configuration validation failures.
//! All errors follow the project's error handling principles by providing
//! clear, contextual, and actionable error messages with `.help()` methods.
use std::path::PathBuf;
use thiserror::Error;
use crate::domain::EnvironmentNameError;
use crate::domain::ProfileNameError;
use crate::shared::UsernameError;
/// Errors that can occur during configuration validation
///
/// These errors follow the project's error handling principles by providing
/// clear, contextual, and actionable error messages through the `.help()` method.
#[derive(Debug, Error)]
pub enum CreateConfigError {
/// Invalid environment name format
#[error("Invalid environment name: {0}")]
InvalidEnvironmentName(#[from] EnvironmentNameError),
/// Invalid SSH username format
#[error("Invalid SSH username: {0}")]
InvalidUsername(#[from] UsernameError),
/// Invalid profile name format
#[error("Invalid profile name: {0}")]
InvalidProfileName(#[from] ProfileNameError),
/// Invalid instance name format
#[error("Invalid instance name '{name}': {reason}")]
InvalidInstanceName {
/// The invalid instance name that was provided
name: String,
/// The reason why the name is invalid
reason: String,
},
/// SSH private key file not found
#[error("SSH private key file not found: {path}")]
PrivateKeyNotFound { path: PathBuf },
/// SSH public key file not found
#[error("SSH public key file not found: {path}")]
PublicKeyNotFound { path: PathBuf },
/// SSH private key path must be absolute
#[error("SSH private key path must be absolute: {path:?}")]
RelativePrivateKeyPath { path: PathBuf },
/// SSH public key path must be absolute
#[error("SSH public key path must be absolute: {path:?}")]
RelativePublicKeyPath { path: PathBuf },
/// Invalid SSH port (must be 1-65535)
#[error("Invalid SSH port: {port} (must be between 1 and 65535)")]
InvalidPort { port: u16 },
/// Invalid bind address format
#[error("Invalid bind address '{address}': failed to parse as IP:PORT")]
InvalidBindAddress {
/// The invalid bind address that was provided
address: String,
/// The underlying parse error
#[source]
source: std::net::AddrParseError,
},
/// Dynamic port assignment (port 0) is not supported
#[error("Dynamic port assignment (port 0) is not supported in bind address '{bind_address}'")]
DynamicPortNotSupported {
/// The bind address containing port 0
bind_address: String,
},
/// Failed to serialize configuration template to JSON
#[error("Failed to serialize configuration template to JSON")]
TemplateSerializationFailed {
#[source]
source: serde_json::Error,
},
/// Failed to create parent directory for template file
#[error("Failed to create directory: {path}")]
TemplateDirectoryCreationFailed {
path: PathBuf,
#[source]
source: std::io::Error,
},
/// Failed to write template file
#[error("Failed to write template file: {path}")]
TemplateFileWriteFailed {
path: PathBuf,
#[source]
source: std::io::Error,
},
}
impl CreateConfigError {
/// Provides detailed troubleshooting guidance for configuration errors
///
/// Returns context-specific help text that guides users toward resolving
/// the configuration issue. This implements the project's tiered help
/// system pattern for actionable error messages.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::application::command_handlers::create::config::CreateConfigError;
/// use std::path::PathBuf;
///
/// let error = CreateConfigError::PrivateKeyNotFound {
/// path: PathBuf::from("/home/user/.ssh/missing_key"),
/// };
///
/// let help = error.help();
/// assert!(help.contains("private key file"));
/// assert!(help.contains("Check that the file path is correct"));
/// ```
#[must_use]
#[allow(clippy::too_many_lines)]
pub fn help(&self) -> &'static str {
match self {
Self::InvalidEnvironmentName(_) => {
"Environment name validation failed.\n\
\n\
Valid environment names must:\n\
- Contain only lowercase letters (a-z) and numbers (0-9)\n\
- Use dashes (-) as word separators\n\
- Not start or end with separators\n\
- Not start with numbers\n\
\n\
Examples: 'dev', 'staging', 'e2e-config', 'production'\n\
\n\
Fix: Update the environment name in your configuration to follow these rules."
}
Self::InvalidUsername(_) => {
"SSH username validation failed.\n\
\n\
Valid usernames must:\n\
- Be 1-32 characters long\n\
- Start with a letter (a-z, A-Z) or underscore (_)\n\
- Contain only letters, digits, underscores, and hyphens\n\
\n\
Common usernames: 'ubuntu', 'torrust', 'deploy', 'admin'\n\
\n\
Fix: Update the SSH username in your configuration to follow Linux username requirements."
}
Self::InvalidProfileName(_) => {
"LXD profile name validation failed.\n\
\n\
Valid profile names must:\n\
- Be 1-63 characters long\n\
- Contain only ASCII letters, numbers, and dashes\n\
- Not start with a digit or dash\n\
- Not end with a dash\n\
\n\
Examples: 'torrust-profile', 'default', 'dev-profile'\n\
\n\
Fix: Update the profile_name in your provider configuration to follow these rules."
}
Self::InvalidInstanceName { .. } => {
"Instance name validation failed.\n\
\n\
Valid instance names must:\n\
- Be 1-63 characters long\n\
- Contain only ASCII letters, numbers, and dashes\n\
- Not start with a digit or dash\n\
- Not end with a dash\n\
\n\
Examples: 'torrust-tracker-vm-dev', 'my-instance', 'prod-server-01'\n\
\n\
Note: If you omit instance_name, it will be auto-generated as 'torrust-tracker-vm-{env_name}'.\n\
\n\
Fix: Update the instance_name in your environment configuration to follow these rules, or remove it to use auto-generation."
}
Self::PrivateKeyNotFound { .. } => {
"SSH private key file not found.\n\
\n\
The specified private key file does not exist or is not accessible.\n\
\n\
Common causes:\n\
- Incorrect file path in configuration\n\
- File was moved or deleted\n\
- Insufficient permissions to access the file\n\
\n\
Fix:\n\
1. Check that the file path is correct in your configuration\n\
2. Verify the file exists: ls -la <path>\n\
3. Ensure you have read permissions on the file\n\
4. Generate a new SSH key pair if needed: ssh-keygen -t rsa -b 4096"
}
Self::PublicKeyNotFound { .. } => {
"SSH public key file not found.\n\
\n\
The specified public key file does not exist or is not accessible.\n\
\n\
Common causes:\n\
- Incorrect file path in configuration\n\
- File was moved or deleted\n\
- Insufficient permissions to access the file\n\
\n\
Fix:\n\
1. Check that the file path is correct in your configuration\n\
2. Verify the file exists: ls -la <path>\n\
3. Ensure you have read permissions on the file\n\
4. Generate public key from private key if needed: ssh-keygen -y -f <private_key> > <public_key>"
}
Self::RelativePrivateKeyPath { .. } => {
// Note: Can't use format! in const context, so we use a static message
// The actual path will be shown in the error message itself
"SSH private key path must be absolute.\n\
\n\
SSH key paths must be absolute to ensure they work correctly across\n\
different working directories and command invocations.\n\
\n\
Fix:\n\
1. Convert relative path to absolute path:\n\
\n\
Use the `realpath` command to get the absolute path:\n\
\n\
realpath <your-relative-path>\n\
\n\
Example:\n\
- Current (relative): fixtures/testing_rsa\n\
- Command: realpath fixtures/testing_rsa\n\
- Result: /home/user/project/fixtures/testing_rsa\n\
\n\
2. Update your configuration file with the absolute path\n\
\n\
3. Alternative approaches:\n\
- Use ~ for home directory (e.g., ~/.ssh/id_rsa)\n\
- Use environment variables (e.g., $HOME/.ssh/id_rsa)\n\
\n\
Why absolute paths?\n\
- Commands may run from different working directories\n\
- Environment state persists paths that must remain valid\n\
- Multi-command workflows (create → provision → configure)"
}
Self::RelativePublicKeyPath { .. } => {
"SSH public key path must be absolute.\n\
\n\
SSH key paths must be absolute to ensure they work correctly across\n\
different working directories and command invocations.\n\
\n\
Fix:\n\
1. Convert relative path to absolute path:\n\
\n\
Use the `realpath` command to get the absolute path:\n\
\n\
realpath <your-relative-path>\n\
\n\
Example:\n\
- Current (relative): fixtures/testing_rsa.pub\n\
- Command: realpath fixtures/testing_rsa.pub\n\
- Result: /home/user/project/fixtures/testing_rsa.pub\n\
\n\
2. Update your configuration file with the absolute path\n\
\n\
3. Alternative approaches:\n\
- Use ~ for home directory (e.g., ~/.ssh/id_rsa.pub)\n\
- Use environment variables (e.g., $HOME/.ssh/id_rsa.pub)\n\
\n\
Why absolute paths?\n\
- Commands may run from different working directories\n\
- Environment state persists paths that must remain valid\n\
- Multi-command workflows (create → provision → configure)"
}
Self::InvalidPort { .. } => {
"Invalid SSH port number.\n\
\n\
SSH port must be between 1 and 65535.\n\
\n\
Common SSH ports:\n\
- 22 (standard SSH port)\n\
- 2222 (common alternative)\n\
\n\
Fix: Update the SSH port in your configuration to a valid port number (1-65535)."
}
Self::InvalidBindAddress { .. } => {
"Invalid bind address format.\n\
\n\
Bind addresses must be in the format IP:PORT (e.g., '0.0.0.0:8080').\n\
\n\
Valid examples:\n\
- '0.0.0.0:6969' (bind to all interfaces on port 6969)\n\
- '127.0.0.1:7070' (bind to localhost on port 7070)\n\
- '[::]:1212' (bind to all IPv6 interfaces on port 1212)\n\
\n\
Common mistakes:\n\
- Missing port number (e.g., '0.0.0.0')\n\
- Invalid IP address format\n\
- Port number out of range (must be 1-65535)\n\
\n\
Fix: Update the bind_address in your configuration to use valid IP:PORT format."
}
Self::DynamicPortNotSupported { .. } => {
"Dynamic port assignment (port 0) is not supported.\n\
\n\
Port 0 tells the operating system to assign any available port dynamically.\n\
This conflicts with our deployment workflow which requires:\n\
- Firewall rules configured before service starts\n\
- Predictable ports for health checks and monitoring\n\
- Consistent port numbers across deployment phases\n\
\n\
Why:\n\
The 'configure' command must open firewall ports before the tracker starts.\n\
With port 0, we won't know which port to open until after the service runs.\n\
\n\
Solution: Specify an explicit port number in your configuration:\n\
- UDP Tracker: Use a port like 6969 (default)\n\
- HTTP Tracker: Use a port like 7070 (default)\n\
- HTTP API: Use a port like 1212 (default)\n\
\n\
Example:\n\
Instead of: \"bind_address\": \"0.0.0.0:0\"\n\
Use: \"bind_address\": \"0.0.0.0:6969\"\n\
\n\
See docs/decisions/port-zero-not-supported.md for details."
}
Self::TemplateSerializationFailed { .. } => {
"Template serialization failed.\n\
\n\
This indicates an internal error in template generation.\n\
\n\
Common causes:\n\
- Software bug in template generation logic\n\
- Invalid data structure for JSON serialization\n\
\n\
Fix:\n\
1. Report this issue with full error details\n\
2. Check for application updates\n\
\n\
This is likely a software bug that needs to be reported."
}
Self::TemplateDirectoryCreationFailed { .. } => {
"Failed to create directory for template file.\n\
\n\
Common causes:\n\
- Insufficient permissions to create directory\n\
- No disk space available\n\
- A file exists with the same name as the directory\n\
- Path length exceeds system limits\n\
\n\
Fix:\n\
1. Check write permissions for the parent directory\n\
2. Verify disk space is available: df -h\n\
3. Ensure no file exists with the same name as the directory\n\
4. Try using a shorter path"
}
Self::TemplateFileWriteFailed { .. } => {
"Failed to write template file.\n\
\n\
Common causes:\n\
- Insufficient permissions to write file\n\
- No disk space available\n\
- File is open in another application\n\
- Antivirus software blocking file creation\n\
\n\
Fix:\n\
1. Check write permissions for the target file and directory\n\
2. Verify disk space is available: df -h\n\
3. Ensure the file is not open in another application\n\
4. Check if antivirus software is blocking file creation"
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::domain::EnvironmentName;
use crate::shared::Username;
#[test]
fn it_should_return_error_when_environment_name_is_invalid() {
let result = EnvironmentName::new("Invalid_Name");
assert!(result.is_err());
let error = CreateConfigError::from(result.unwrap_err());
assert!(error.to_string().contains("Invalid environment name"));
assert!(error.help().contains("lowercase letters"));
assert!(error.help().contains("dashes"));
}
#[test]
fn it_should_return_error_when_username_is_invalid() {
let result = Username::new("123invalid");
assert!(result.is_err());
let error = CreateConfigError::from(result.unwrap_err());
assert!(error.to_string().contains("Invalid SSH username"));
assert!(error.help().contains("Start with a letter"));
assert!(error.help().contains("1-32 characters"));
}
#[test]
fn it_should_return_error_when_private_key_file_not_found() {
let error = CreateConfigError::PrivateKeyNotFound {
path: PathBuf::from("/nonexistent/key"),
};
assert!(error.to_string().contains("private key file not found"));
assert!(error.to_string().contains("/nonexistent/key"));
assert!(error.help().contains("Check that the file path is correct"));
assert!(error.help().contains("ssh-keygen"));
}
#[test]
fn it_should_return_error_when_public_key_file_not_found() {
let error = CreateConfigError::PublicKeyNotFound {
path: PathBuf::from("/nonexistent/key.pub"),
};
assert!(error.to_string().contains("public key file not found"));
assert!(error.to_string().contains("/nonexistent/key.pub"));
assert!(error.help().contains("Check that the file path is correct"));
assert!(error.help().contains("ssh-keygen -y"));
}
#[test]
fn it_should_return_error_when_port_is_invalid() {
let error = CreateConfigError::InvalidPort { port: 0 };
assert!(error.to_string().contains("Invalid SSH port"));
assert!(error.to_string().contains("must be between 1 and 65535"));
assert!(error.help().contains("22"));
assert!(error.help().contains("2222"));
}
#[test]
fn it_should_provide_help_messages_for_all_errors() {
// Verify all error variants have help text
let errors = vec![
CreateConfigError::PrivateKeyNotFound {
path: PathBuf::from("/test"),
},
CreateConfigError::PublicKeyNotFound {
path: PathBuf::from("/test"),
},
CreateConfigError::InvalidPort { port: 0 },
CreateConfigError::InvalidInstanceName {
name: "invalid-".to_string(),
reason: "ends with dash".to_string(),
},
];
for error in errors {
let help = error.help();
assert!(!help.is_empty(), "Help text should not be empty");
assert!(
help.contains("Fix:") || help.contains("Common"),
"Help should contain actionable guidance"
);
}
}
#[test]
fn it_should_return_error_when_instance_name_is_invalid() {
let error = CreateConfigError::InvalidInstanceName {
name: "invalid-".to_string(),
reason: "Instance name must not end with a dash".to_string(),
};
assert!(error.to_string().contains("Invalid instance name"));
assert!(error.to_string().contains("invalid-"));
assert!(error.help().contains("1-63 characters"));
assert!(error.help().contains("ASCII letters"));
assert!(error.help().contains("auto-generation"));
}
#[test]
fn it_should_return_error_when_template_serialization_fails() {
// Simulate serialization error (hard to create naturally)
let json_error = serde_json::from_str::<serde_json::Value>("invalid").unwrap_err();
let error = CreateConfigError::TemplateSerializationFailed { source: json_error };
assert!(error
.to_string()
.contains("serialize configuration template"));
assert!(error.help().contains("internal error"));
assert!(error.help().contains("Report this issue"));
}
#[test]
fn it_should_return_error_when_template_directory_creation_fails() {
let error = CreateConfigError::TemplateDirectoryCreationFailed {
path: PathBuf::from("/test/path"),
source: std::io::Error::new(std::io::ErrorKind::PermissionDenied, "test"),
};
assert!(error.to_string().contains("Failed to create directory"));
assert!(error.to_string().contains("/test/path"));
assert!(error.help().contains("permissions"));
assert!(error.help().contains("df -h"));
}
#[test]
fn it_should_return_error_when_template_file_write_fails() {
let error = CreateConfigError::TemplateFileWriteFailed {
path: PathBuf::from("/test/file.json"),
source: std::io::Error::new(std::io::ErrorKind::PermissionDenied, "test"),
};
assert!(error.to_string().contains("Failed to write template file"));
assert!(error.to_string().contains("/test/file.json"));
assert!(error.help().contains("permissions"));
assert!(error.help().contains("disk space"));
}
}