torc 0.21.0

Workflow management system
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
use bcrypt::hash;
use clap::{Parser, Subcommand};
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::path::PathBuf;
use torc::client::apis::configuration::{Configuration, TlsConfig};
use zxcvbn::Score;

/// Minimum zxcvbn score required for passwords (0-4 scale).
/// Score 3 = "safely unguessable: moderate protection from offline slow-hash scenario"
const MIN_PASSWORD_SCORE: Score = Score::Three;

/// Minimum password length (NIST SP 800-63B recommendation).
const MIN_PASSWORD_LENGTH: usize = 8;

#[derive(Parser)]
#[command(name = "torc-htpasswd")]
#[command(about = "Manage htpasswd files for Torc server authentication")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Add or update a user in the htpasswd file
    Add {
        /// Path to htpasswd file (will be created if it doesn't exist)
        #[arg(short, long)]
        file: PathBuf,

        /// Username to add or update
        username: String,

        /// Password (will be prompted if not provided)
        #[arg(short, long)]
        password: Option<String>,

        /// Bcrypt cost factor (4-31, default: 12, higher = more secure but slower)
        #[arg(short, long, default_value_t = 12)]
        cost: u32,

        /// Reload auth credentials on the server after modifying the file.
        /// Requires --url and credentials (TORC_PASSWORD or --server-password).
        #[arg(long)]
        reload_auth: bool,

        /// Server URL for reload-auth (defaults to TORC_API_URL or http://localhost:8080/torc-service/v1)
        #[arg(long, env = "TORC_API_URL")]
        url: Option<String>,

        /// Password for authenticating with the server (for reload-auth)
        #[arg(long, env = "TORC_PASSWORD")]
        server_password: Option<String>,
    },

    /// Generate a password hash and output to stdout (for sending to admin)
    Hash {
        /// Username (defaults to $USER or $USERNAME from environment)
        username: Option<String>,

        /// Password (will be prompted if not provided)
        #[arg(short, long)]
        password: Option<String>,

        /// Bcrypt cost factor (4-31, default: 12, higher = more secure but slower)
        #[arg(short, long, default_value_t = 12)]
        cost: u32,
    },

    /// Remove a user from the htpasswd file
    Remove {
        /// Path to htpasswd file
        #[arg(short, long)]
        file: PathBuf,

        /// Username to remove
        username: String,

        /// Reload auth credentials on the server after modifying the file.
        /// Requires --url and credentials (TORC_PASSWORD or --server-password).
        #[arg(long)]
        reload_auth: bool,

        /// Server URL for reload-auth (defaults to TORC_API_URL or http://localhost:8080/torc-service/v1)
        #[arg(long, env = "TORC_API_URL")]
        url: Option<String>,

        /// Password for authenticating with the server (for reload-auth)
        #[arg(long, env = "TORC_PASSWORD")]
        server_password: Option<String>,
    },

    /// List all users in the htpasswd file
    List {
        /// Path to htpasswd file
        #[arg(short, long)]
        file: PathBuf,
    },

    /// Verify a password for a user
    Verify {
        /// Path to htpasswd file
        #[arg(short, long)]
        file: PathBuf,

        /// Username to verify
        username: String,

        /// Password to verify (will be prompted if not provided)
        #[arg(short, long)]
        password: Option<String>,
    },
}

/// Validate password strength using zxcvbn. Returns Ok(()) if the password is
/// strong enough, or Err with a user-facing error message.
fn validate_password(password: &str, username: &str) -> Result<(), String> {
    if password.len() < MIN_PASSWORD_LENGTH {
        return Err(format!(
            "Password is too short ({} characters). Minimum length is {}.",
            password.len(),
            MIN_PASSWORD_LENGTH,
        ));
    }

    let estimate = zxcvbn::zxcvbn(password, &[username, "torc"]);
    let score = estimate.score();

    if score >= MIN_PASSWORD_SCORE {
        return Ok(());
    }

    let mut msg = format!(
        "Password is too weak (score {}/4, minimum required: {}/4).",
        score as u8, MIN_PASSWORD_SCORE as u8,
    );

    if let Some(feedback) = estimate.feedback() {
        if let Some(warning) = feedback.warning() {
            msg.push_str(&format!("\n  Warning: {warning}"));
        }
        for suggestion in feedback.suggestions() {
            msg.push_str(&format!("\n  Suggestion: {suggestion}"));
        }
    }

    Err(msg)
}

fn prompt_password(username: &str) -> String {
    let password = match rpassword::prompt_password(format!("Password for '{username}': ")) {
        Ok(pwd) => pwd,
        Err(e) => {
            eprintln!("Error reading password: {e}");
            std::process::exit(1);
        }
    };

    let confirm = match rpassword::prompt_password("Confirm password: ") {
        Ok(pwd) => pwd,
        Err(e) => {
            eprintln!("Error reading password: {e}");
            std::process::exit(1);
        }
    };

    if password != confirm {
        eprintln!("Error: passwords do not match.");
        std::process::exit(1);
    }

    password
}

/// Call the server's reload-auth endpoint if --reload-auth was specified.
fn maybe_reload_auth(reload_auth: bool, url: &Option<String>, server_password: &Option<String>) {
    if !reload_auth {
        return;
    }

    let base_path = url
        .clone()
        .unwrap_or_else(|| "http://localhost:8080/torc-service/v1".to_string());

    let mut config = Configuration::with_tls(TlsConfig::default());
    config.base_path = base_path;

    // Set up auth using the current USER env var and server_password
    if let Some(password) = server_password {
        let username = std::env::var("USER")
            .or_else(|_| std::env::var("USERNAME"))
            .unwrap_or_else(|_| "unknown".to_string());
        config.basic_auth = Some((username, Some(password.clone())));
    }

    match torc::client::apis::default_api::reload_auth(&config) {
        Ok(response) => {
            let message = response
                .get("message")
                .and_then(|v| v.as_str())
                .unwrap_or("Auth reloaded");
            let user_count = response
                .get("user_count")
                .and_then(|v| v.as_u64())
                .unwrap_or(0);
            println!("Server: {} ({} users)", message, user_count);
        }
        Err(e) => {
            eprintln!("Warning: Failed to reload auth on server: {e}");
            eprintln!("The htpasswd file was modified but the server has not reloaded it.");
            eprintln!("Run 'torc admin reload-auth' manually to apply the changes.");
        }
    }
}

fn main() {
    let cli = Cli::parse();

    match cli.command {
        Commands::Add {
            file,
            username,
            password,
            cost,
            reload_auth,
            url,
            server_password,
        } => {
            if !(4..=31).contains(&cost) {
                eprintln!("Error: cost must be between 4 and 31");
                std::process::exit(1);
            }

            let password = password.unwrap_or_else(|| prompt_password(&username));

            if let Err(msg) = validate_password(&password, &username) {
                eprintln!("Error: {msg}");
                std::process::exit(1);
            }

            println!("Hashing password (cost={cost})...");
            let hash = match hash(&password, cost) {
                Ok(h) => h,
                Err(e) => {
                    eprintln!("Error hashing password: {e}");
                    std::process::exit(1);
                }
            };

            // Read existing file or create new entries
            let mut entries = std::collections::HashMap::new();
            if file.exists() {
                let file_handle = match File::open(&file) {
                    Ok(f) => f,
                    Err(e) => {
                        eprintln!("Error opening file: {e}");
                        std::process::exit(1);
                    }
                };
                let reader = BufReader::new(file_handle);
                for line in reader.lines() {
                    let line = line.unwrap();
                    let line = line.trim();
                    if line.is_empty() || line.starts_with('#') {
                        continue;
                    }
                    let parts: Vec<&str> = line.splitn(2, ':').collect();
                    if parts.len() == 2 {
                        entries.insert(parts[0].to_string(), parts[1].to_string());
                    }
                }
            }

            // Add or update user
            let is_update = entries.contains_key(&username);
            entries.insert(username.clone(), hash);

            // Write back to file
            let mut file_handle = match OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(&file)
            {
                Ok(f) => f,
                Err(e) => {
                    eprintln!("Error opening file for writing: {e}");
                    std::process::exit(1);
                }
            };

            writeln!(file_handle, "# Torc htpasswd file").unwrap();
            writeln!(file_handle, "# Format: username:bcrypt_hash").unwrap();
            for (user, hash) in entries {
                writeln!(file_handle, "{user}:{hash}").unwrap();
            }

            if is_update {
                println!("Updated user '{username}' in {file:?}");
            } else {
                println!("Added user '{username}' to {file:?}");
            }

            maybe_reload_auth(reload_auth, &url, &server_password);
        }

        Commands::Hash {
            username,
            password,
            cost,
        } => {
            if !(4..=31).contains(&cost) {
                eprintln!("Error: cost must be between 4 and 31");
                std::process::exit(1);
            }

            // Resolve username from argument or environment
            let username = match username {
                Some(u) => u,
                None => std::env::var("USER")
                    .or_else(|_| std::env::var("USERNAME"))
                    .unwrap_or_else(|_| {
                        eprintln!(
                            "Error: username not provided and could not read from $USER or $USERNAME"
                        );
                        std::process::exit(1);
                    }),
            };

            let password = password.unwrap_or_else(|| prompt_password(&username));

            if let Err(msg) = validate_password(&password, &username) {
                eprintln!("Error: {msg}");
                std::process::exit(1);
            }

            eprintln!("Hashing password (cost={cost})...");
            let hash_result = match hash(&password, cost) {
                Ok(h) => h,
                Err(e) => {
                    eprintln!("Error hashing password: {e}");
                    std::process::exit(1);
                }
            };

            // Output the htpasswd line to stdout (progress messages go to stderr)
            println!("{username}:{hash_result}");
            eprintln!("Send the line above to your server administrator.");
        }

        Commands::Remove {
            file,
            username,
            reload_auth,
            url,
            server_password,
        } => {
            if !file.exists() {
                eprintln!("Error: file {file:?} does not exist");
                std::process::exit(1);
            }

            let mut entries = std::collections::HashMap::new();
            let file_handle = File::open(&file).unwrap();
            let reader = BufReader::new(file_handle);
            for line in reader.lines() {
                let line = line.unwrap();
                let line = line.trim();
                if line.is_empty() || line.starts_with('#') {
                    continue;
                }
                let parts: Vec<&str> = line.splitn(2, ':').collect();
                if parts.len() == 2 {
                    entries.insert(parts[0].to_string(), parts[1].to_string());
                }
            }

            if !entries.contains_key(&username) {
                eprintln!("Error: user '{username}' not found in {file:?}");
                std::process::exit(1);
            }

            entries.remove(&username);

            // Write back to file
            let mut file_handle = OpenOptions::new()
                .write(true)
                .truncate(true)
                .open(&file)
                .unwrap();

            writeln!(file_handle, "# Torc htpasswd file").unwrap();
            writeln!(file_handle, "# Format: username:bcrypt_hash").unwrap();
            for (user, hash) in entries {
                writeln!(file_handle, "{user}:{hash}").unwrap();
            }

            println!("Removed user '{username}' from {file:?}");

            maybe_reload_auth(reload_auth, &url, &server_password);
        }

        Commands::List { file } => {
            if !file.exists() {
                eprintln!("Error: file {file:?} does not exist");
                std::process::exit(1);
            }

            let file_handle = File::open(&file).unwrap();
            let reader = BufReader::new(file_handle);
            let mut users = Vec::new();
            for line in reader.lines() {
                let line = line.unwrap();
                let line = line.trim();
                if line.is_empty() || line.starts_with('#') {
                    continue;
                }
                let parts: Vec<&str> = line.splitn(2, ':').collect();
                if parts.len() == 2 {
                    users.push(parts[0].to_string());
                }
            }

            if users.is_empty() {
                println!("No users found in {file:?}");
            } else {
                println!("Users in {file:?}:");
                for user in users {
                    println!("  - {user}");
                }
            }
        }

        Commands::Verify {
            file,
            username,
            password,
        } => {
            if !file.exists() {
                eprintln!("Error: file {file:?} does not exist");
                std::process::exit(1);
            }

            let password = match password {
                Some(pwd) => pwd,
                None => match rpassword::prompt_password(format!("Password for '{username}': ")) {
                    Ok(pwd) => pwd,
                    Err(e) => {
                        eprintln!("Error reading password: {e}");
                        std::process::exit(1);
                    }
                },
            };

            // Load htpasswd file
            match torc::server::htpasswd::HtpasswdFile::load(&file) {
                Ok(htpasswd) => {
                    if htpasswd.verify(&username, &password) {
                        println!("Password is correct for user '{username}'");
                    } else {
                        println!("Password is incorrect for user '{username}'");
                        std::process::exit(1);
                    }
                }
                Err(e) => {
                    eprintln!("Error loading htpasswd file: {e}");
                    std::process::exit(1);
                }
            }
        }
    }
}