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
//! Docker login command implementation
//!
//! This module provides functionality to authenticate with Docker registries.
//! It supports both Docker Hub and private registries with various authentication methods.
use super::{CommandExecutor, CommandOutput, DockerCommand};
use crate::error::Result;
use async_trait::async_trait;
use std::fmt;
/// Command for authenticating with Docker registries
///
/// The `LoginCommand` provides a builder pattern for constructing Docker login commands
/// with various authentication options including username/password, token-based auth,
/// and different registry endpoints.
///
/// # Examples
///
/// ```rust
/// use docker_wrapper::LoginCommand;
///
/// // Login to Docker Hub
/// let login = LoginCommand::new("myusername", "mypassword");
///
/// // Login to private registry
/// let login = LoginCommand::new("user", "pass")
/// .registry("my-registry.com");
///
/// // Login with stdin password (more secure)
/// let login = LoginCommand::new("user", "")
/// .password_stdin();
/// ```
#[derive(Debug, Clone)]
pub struct LoginCommand {
/// Username for authentication
username: String,
/// Password for authentication (empty if using stdin)
password: String,
/// Registry server URL (defaults to Docker Hub if None)
registry: Option<String>,
/// Whether to read password from stdin
password_stdin: bool,
/// Command executor for running the command
pub executor: CommandExecutor,
}
/// Output from a login command execution
///
/// Contains the raw output from the Docker login command and provides
/// convenience methods for checking authentication status.
#[derive(Debug, Clone)]
pub struct LoginOutput {
/// Raw output from the Docker command
pub output: CommandOutput,
}
impl LoginCommand {
/// Creates a new login command with username and password
///
/// # Arguments
///
/// * `username` - The username for authentication
/// * `password` - The password for authentication (can be empty if using stdin)
///
/// # Examples
///
/// ```rust
/// use docker_wrapper::LoginCommand;
///
/// let login = LoginCommand::new("myuser", "mypass");
/// ```
pub fn new(username: impl Into<String>, password: impl Into<String>) -> Self {
Self {
username: username.into(),
password: password.into(),
registry: None,
password_stdin: false,
executor: CommandExecutor::default(),
}
}
/// Sets the registry server for authentication
///
/// If not specified, defaults to Docker Hub (index.docker.io)
///
/// # Arguments
///
/// * `registry` - The registry server URL
///
/// # Examples
///
/// ```rust
/// use docker_wrapper::LoginCommand;
///
/// let login = LoginCommand::new("user", "pass")
/// .registry("gcr.io");
/// ```
#[must_use]
pub fn registry(mut self, registry: impl Into<String>) -> Self {
self.registry = Some(registry.into());
self
}
/// Enables reading password from stdin for security
///
/// When enabled, the password field is ignored and Docker will
/// prompt for password input via stdin.
///
/// # Examples
///
/// ```rust
/// use docker_wrapper::LoginCommand;
///
/// let login = LoginCommand::new("user", "")
/// .password_stdin();
/// ```
#[must_use]
pub fn password_stdin(mut self) -> Self {
self.password_stdin = true;
self
}
/// Sets a custom command executor
///
/// # Arguments
///
/// * `executor` - Custom command executor
#[must_use]
pub fn executor(mut self, executor: CommandExecutor) -> Self {
self.executor = executor;
self
}
/// Gets the username
#[must_use]
pub fn get_username(&self) -> &str {
&self.username
}
/// Gets the registry (if set)
#[must_use]
pub fn get_registry(&self) -> Option<&str> {
self.registry.as_deref()
}
/// Returns true if password will be read from stdin
#[must_use]
pub fn is_password_stdin(&self) -> bool {
self.password_stdin
}
/// Get a reference to the command executor
#[must_use]
pub fn get_executor(&self) -> &CommandExecutor {
&self.executor
}
/// Get a mutable reference to the command executor
#[must_use]
pub fn get_executor_mut(&mut self) -> &mut CommandExecutor {
&mut self.executor
}
}
impl Default for LoginCommand {
fn default() -> Self {
Self::new("", "")
}
}
impl LoginOutput {
/// Returns true if the login was successful
#[must_use]
pub fn success(&self) -> bool {
self.output.success
}
/// Returns true if the output indicates successful authentication
#[must_use]
pub fn is_authenticated(&self) -> bool {
self.success()
&& (self.output.stdout.contains("Login Succeeded")
|| self.output.stdout.contains("login succeeded"))
}
/// Gets any warning messages from the login output
#[must_use]
pub fn warnings(&self) -> Vec<&str> {
self.output
.stderr
.lines()
.filter(|line| line.to_lowercase().contains("warning"))
.collect()
}
}
#[async_trait]
impl DockerCommand for LoginCommand {
type Output = LoginOutput;
fn get_executor(&self) -> &CommandExecutor {
&self.executor
}
fn get_executor_mut(&mut self) -> &mut CommandExecutor {
&mut self.executor
}
fn build_command_args(&self) -> Vec<String> {
let mut args = vec!["login".to_string()];
// Add username
args.push("--username".to_string());
args.push(self.username.clone());
// Add password option
if self.password_stdin {
args.push("--password-stdin".to_string());
} else {
args.push("--password".to_string());
args.push(self.password.clone());
}
// Add registry if specified
if let Some(ref registry) = self.registry {
args.push(registry.clone());
}
// Add raw args from executor
args.extend(self.executor.raw_args.clone());
args
}
async fn execute(&self) -> Result<Self::Output> {
let args = self.build_command_args();
let output = self.execute_command(args).await?;
Ok(LoginOutput { output })
}
}
impl fmt::Display for LoginCommand {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "docker login")?;
if let Some(ref registry) = self.registry {
write!(f, " {registry}")?;
}
write!(f, " --username {}", self.username)?;
if self.password_stdin {
write!(f, " --password-stdin")?;
} else {
write!(f, " --password [HIDDEN]")?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_login_command_basic() {
let login = LoginCommand::new("testuser", "testpass");
assert_eq!(login.get_username(), "testuser");
assert_eq!(login.get_registry(), None);
assert!(!login.is_password_stdin());
let args = login.build_command_args();
assert_eq!(
args,
vec!["login", "--username", "testuser", "--password", "testpass"]
);
}
#[test]
fn test_login_command_with_registry() {
let login = LoginCommand::new("user", "pass").registry("gcr.io");
assert_eq!(login.get_registry(), Some("gcr.io"));
let args = login.build_command_args();
assert_eq!(
args,
vec![
"login",
"--username",
"user",
"--password",
"pass",
"gcr.io"
]
);
}
#[test]
fn test_login_command_password_stdin() {
let login = LoginCommand::new("user", "ignored").password_stdin();
assert!(login.is_password_stdin());
let args = login.build_command_args();
assert_eq!(
args,
vec!["login", "--username", "user", "--password-stdin"]
);
}
#[test]
fn test_login_command_with_private_registry() {
let login = LoginCommand::new("admin", "secret").registry("my-registry.example.com:5000");
let args = login.build_command_args();
assert_eq!(
args,
vec![
"login",
"--username",
"admin",
"--password",
"secret",
"my-registry.example.com:5000"
]
);
}
#[test]
fn test_login_command_docker_hub_default() {
let login = LoginCommand::new("dockeruser", "dockerpass");
// No registry specified should default to Docker Hub
assert_eq!(login.get_registry(), None);
let args = login.build_command_args();
assert!(!args.contains(&"index.docker.io".to_string()));
}
#[test]
fn test_login_command_display() {
let login = LoginCommand::new("testuser", "testpass").registry("example.com");
let display = format!("{login}");
assert!(display.contains("docker login"));
assert!(display.contains("example.com"));
assert!(display.contains("--username testuser"));
assert!(display.contains("--password [HIDDEN]"));
assert!(!display.contains("testpass"));
}
#[test]
fn test_login_command_display_stdin() {
let login = LoginCommand::new("testuser", "").password_stdin();
let display = format!("{login}");
assert!(display.contains("--password-stdin"));
assert!(!display.contains("[HIDDEN]"));
}
#[test]
fn test_login_command_default() {
let login = LoginCommand::default();
assert_eq!(login.get_username(), "");
assert_eq!(login.get_registry(), None);
assert!(!login.is_password_stdin());
}
#[test]
fn test_login_output_success_detection() {
let output = CommandOutput {
stdout: "Login Succeeded".to_string(),
stderr: String::new(),
exit_code: 0,
success: true,
};
let login_output = LoginOutput { output };
assert!(login_output.success());
assert!(login_output.is_authenticated());
}
#[test]
fn test_login_output_alternative_success_message() {
let output = CommandOutput {
stdout: "login succeeded for user@registry".to_string(),
stderr: String::new(),
exit_code: 0,
success: true,
};
let login_output = LoginOutput { output };
assert!(login_output.is_authenticated());
}
#[test]
fn test_login_output_warnings() {
let output = CommandOutput {
stdout: "Login Succeeded".to_string(),
stderr: "WARNING: login credentials saved in plaintext\ninfo: using default registry"
.to_string(),
exit_code: 0,
success: true,
};
let login_output = LoginOutput { output };
let warnings = login_output.warnings();
assert_eq!(warnings.len(), 1);
assert!(warnings[0].contains("WARNING"));
}
#[test]
fn test_login_output_failure() {
let output = CommandOutput {
stdout: String::new(),
stderr: "Error: authentication failed".to_string(),
exit_code: 1,
success: false,
};
let login_output = LoginOutput { output };
assert!(!login_output.success());
assert!(!login_output.is_authenticated());
}
}