osp-cli 1.5.1

CLI and REPL for querying and managing OSP infrastructure data
Documentation
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
//! Small embeddable LDAP service surface with optional DSL pipeline support.
//!
//! This module is intentionally narrow. It currently understands only
//! `ldap user [uid]` and `ldap netgroup [name]`, plus any trailing DSL stages.
//! Passing any other command root to [`crate::services::execute_line`] returns
//! an error immediately.
//!
//! Use this when you want in-process LDAP lookups plus DSL filtering without
//! bootstrapping the full CLI host or REPL runtime.
//!
//! High level flow:
//!
//! - parse a small LDAP command grammar
//! - execute it against abstract [`crate::ports`] traits
//! - optionally apply trailing DSL stages to the returned rows
//!
//! Contract:
//!
//! - this layer is intentionally small and port-driven
//! - richer host concerns like plugin dispatch, prompt handling, and terminal
//!   rendering belong elsewhere
//!
//! Public API shape:
//!
//! - [`crate::services::ServiceContext::new`] is the main construction surface
//! - parsed commands and output values stay plain semantic data
//! - callers that outgrow this surface should move up to [`crate::app`] rather
//!   than rebuilding host machinery here

use crate::config::RuntimeConfig;
use crate::core::output_model::OutputResult;
use crate::core::row::Row;
use crate::dsl::{apply_pipeline, parse_pipeline};
use crate::ports::{LdapDirectory, parse_attributes};
use anyhow::{Result, anyhow};

/// Embeddable execution inputs for the small service-layer command API.
///
/// This keeps the surface intentionally narrow: a default user identity, an
/// abstract LDAP backend, and the resolved runtime config snapshot that the
/// service layer should share with the full host when embedded.
pub struct ServiceContext<L: LdapDirectory> {
    /// Default user identity used when a command omits its explicit subject.
    pub user: Option<String>,
    /// Abstract LDAP backend used by service commands.
    pub ldap: L,
    /// Resolved runtime config snapshot carried alongside service execution.
    pub config: RuntimeConfig,
}

impl<L: LdapDirectory> ServiceContext<L> {
    /// Creates a new service context with the active user, directory port, and
    /// resolved runtime config.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::config::RuntimeConfig;
    /// use osp_cli::ports::mock::MockLdapClient;
    /// use osp_cli::services::ServiceContext;
    ///
    /// // `MockLdapClient::default()` exposes a small fixed fixture set documented
    /// // on `MockLdapClient`, including an `oistes` user and a `ucore` netgroup.
    /// let ctx = ServiceContext::new(
    ///     Some("oistes".to_string()),
    ///     MockLdapClient::default(),
    ///     RuntimeConfig::default(),
    /// );
    ///
    /// assert_eq!(ctx.user.as_deref(), Some("oistes"));
    /// ```
    pub fn new(user: Option<String>, ldap: L, config: RuntimeConfig) -> Self {
        Self { user, ldap, config }
    }
}

/// Parsed subset of commands understood by [`execute_line`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParsedCommand {
    /// Lookup a user entry in LDAP.
    LdapUser {
        /// Explicit user identifier to query.
        uid: Option<String>,
        /// Optional LDAP filter expression.
        filter: Option<String>,
        /// Optional comma-separated attribute selection.
        attributes: Option<String>,
    },
    /// Lookup a netgroup entry in LDAP.
    LdapNetgroup {
        /// Explicit netgroup name to query.
        name: Option<String>,
        /// Optional LDAP filter expression.
        filter: Option<String>,
        /// Optional comma-separated attribute selection.
        attributes: Option<String>,
    },
}

/// Executes one LDAP service command line and applies any trailing DSL stages.
///
/// This is the small, embeddable surface for callers that want LDAP command
/// parsing plus pipelines without bootstrapping the full CLI host.
///
/// The full line is parsed as `<command> [| <stage> ...]`. The command is
/// dispatched against the ports in `ctx`; the stages are applied to the
/// returned rows before the result is returned.
///
/// Only the `ldap user ...` and `ldap netgroup ...` roots are supported today.
///
/// # Examples
///
/// ```
/// use osp_cli::config::RuntimeConfig;
/// use osp_cli::ports::mock::MockLdapClient;
/// use osp_cli::services::{ServiceContext, execute_line};
///
/// let ctx = ServiceContext::new(
///     Some("oistes".to_string()),
///     MockLdapClient::default(),
///     RuntimeConfig::default(),
/// );
/// // `MockLdapClient::default()` exposes a fixed `oistes` user fixture.
///
/// let result = execute_line(&ctx, "ldap user oistes | F uid=oistes | P uid cn")
///     .expect("command and pipeline should run");
/// let rows = result.as_rows().expect("expected row output");
///
/// assert_eq!(rows.len(), 1);
/// assert_eq!(rows[0].get("uid").and_then(|value| value.as_str()), Some("oistes"));
/// assert!(rows[0].contains_key("cn"));
/// ```
pub fn execute_line<L: LdapDirectory>(ctx: &ServiceContext<L>, line: &str) -> Result<OutputResult> {
    let parsed_pipeline = parse_pipeline(line)?;
    if parsed_pipeline.command.is_empty() {
        return Ok(OutputResult::from_rows(Vec::new()));
    }

    let tokens = shell_words::split(&parsed_pipeline.command)
        .map_err(|err| anyhow!("failed to parse command: {err}"))?;
    let command = parse_repl_command(&tokens)?;
    apply_pipeline(execute_command(ctx, &command)?, &parsed_pipeline.stages)
}

/// Interprets tokenized service-layer input using the minimal LDAP command grammar.
///
/// Unlike the full CLI parser, this only accepts the LDAP-only subset modeled
/// by [`ParsedCommand`].
///
/// # Examples
///
/// ```
/// use osp_cli::services::{ParsedCommand, parse_repl_command};
///
/// let tokens = vec![
///     "ldap".to_string(),
///     "user".to_string(),
///     "alice".to_string(),
///     "--attributes".to_string(),
///     "uid,mail".to_string(),
/// ];
///
/// let parsed = parse_repl_command(&tokens).unwrap();
/// assert!(matches!(
///     parsed,
///     ParsedCommand::LdapUser {
///         uid: Some(uid),
///         attributes: Some(attributes),
///         ..
///     } if uid == "alice" && attributes == "uid,mail"
/// ));
/// ```
pub fn parse_repl_command(tokens: &[String]) -> Result<ParsedCommand> {
    if tokens.is_empty() {
        return Err(anyhow!("empty command"));
    }
    if tokens[0] != "ldap" {
        return Err(anyhow!("unsupported command: {}", tokens[0]));
    }
    if tokens.len() < 2 {
        return Err(anyhow!("missing ldap subcommand"));
    }

    match tokens[1].as_str() {
        "user" => parse_ldap_user_tokens(tokens),
        "netgroup" => parse_ldap_netgroup_tokens(tokens),
        other => Err(anyhow!("unsupported ldap subcommand: {other}")),
    }
}

fn parse_ldap_user_tokens(tokens: &[String]) -> Result<ParsedCommand> {
    let mut uid: Option<String> = None;
    let mut filter: Option<String> = None;
    let mut attributes: Option<String> = None;

    let mut i = 2usize;
    while i < tokens.len() {
        match tokens[i].as_str() {
            "--filter" => {
                i += 1;
                let value = tokens
                    .get(i)
                    .ok_or_else(|| anyhow!("--filter requires a value"))?;
                filter = Some(value.clone());
            }
            "--attributes" | "-a" => {
                i += 1;
                let value = tokens
                    .get(i)
                    .ok_or_else(|| anyhow!("--attributes requires a value"))?;
                attributes = Some(value.clone());
            }
            token if token.starts_with('-') => return Err(anyhow!("unknown option: {token}")),
            value => {
                if uid.is_some() {
                    return Err(anyhow!("ldap user accepts one uid positional argument"));
                }
                uid = Some(value.to_string());
            }
        }
        i += 1;
    }

    Ok(ParsedCommand::LdapUser {
        uid,
        filter,
        attributes,
    })
}

fn parse_ldap_netgroup_tokens(tokens: &[String]) -> Result<ParsedCommand> {
    let mut name: Option<String> = None;
    let mut filter: Option<String> = None;
    let mut attributes: Option<String> = None;

    let mut i = 2usize;
    while i < tokens.len() {
        match tokens[i].as_str() {
            "--filter" => {
                i += 1;
                let value = tokens
                    .get(i)
                    .ok_or_else(|| anyhow!("--filter requires a value"))?;
                filter = Some(value.clone());
            }
            "--attributes" | "-a" => {
                i += 1;
                let value = tokens
                    .get(i)
                    .ok_or_else(|| anyhow!("--attributes requires a value"))?;
                attributes = Some(value.clone());
            }
            token if token.starts_with('-') => return Err(anyhow!("unknown option: {token}")),
            value => {
                if name.is_some() {
                    return Err(anyhow!(
                        "ldap netgroup accepts one name positional argument"
                    ));
                }
                name = Some(value.to_string());
            }
        }
        i += 1;
    }

    Ok(ParsedCommand::LdapNetgroup {
        name,
        filter,
        attributes,
    })
}

/// Executes a parsed service-layer command against the configured LDAP port.
///
/// # Examples
///
/// ```
/// use osp_cli::config::RuntimeConfig;
/// use osp_cli::ports::mock::MockLdapClient;
/// use osp_cli::services::{ParsedCommand, ServiceContext, execute_command};
///
/// let ctx = ServiceContext::new(
///     Some("oistes".to_string()),
///     MockLdapClient::default(),
///     RuntimeConfig::default(),
/// );
/// // `MockLdapClient::default()` exposes a fixed `oistes` user fixture.
/// let rows = execute_command(
///     &ctx,
///     &ParsedCommand::LdapUser {
///         uid: None,
///         filter: Some("uid=oistes".to_string()),
///         attributes: Some("uid,cn".to_string()),
///     },
/// )
/// .unwrap();
///
/// assert_eq!(rows.len(), 1);
/// assert_eq!(rows[0].get("uid").and_then(|value| value.as_str()), Some("oistes"));
/// ```
pub fn execute_command<L: LdapDirectory>(
    ctx: &ServiceContext<L>,
    command: &ParsedCommand,
) -> Result<Vec<Row>> {
    match command {
        ParsedCommand::LdapUser {
            uid,
            filter,
            attributes,
        } => {
            let resolved_uid = uid
                .clone()
                .or_else(|| ctx.user.clone())
                .ok_or_else(|| anyhow!("ldap user requires <uid> or -u/--user"))?;
            let attrs = parse_attributes(attributes.as_deref())?;
            ctx.ldap
                .user(&resolved_uid, filter.as_deref(), attrs.as_deref())
        }
        ParsedCommand::LdapNetgroup {
            name,
            filter,
            attributes,
        } => {
            let resolved_name = name
                .clone()
                .ok_or_else(|| anyhow!("ldap netgroup requires <name>"))?;
            let attrs = parse_attributes(attributes.as_deref())?;
            ctx.ldap
                .netgroup(&resolved_name, filter.as_deref(), attrs.as_deref())
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::core::output_model::OutputResult;
    use crate::ports::mock::MockLdapClient;

    use super::{ParsedCommand, ServiceContext, execute_command, execute_line, parse_repl_command};

    fn output_rows(output: &OutputResult) -> &[crate::core::row::Row] {
        output.as_rows().expect("expected row output")
    }

    fn test_ctx() -> ServiceContext<MockLdapClient> {
        ServiceContext::new(
            Some("oistes".to_string()),
            MockLdapClient::default(),
            crate::config::RuntimeConfig::default(),
        )
    }

    #[test]
    fn parses_repl_user_command_with_options() {
        let cmd = parse_repl_command(&[
            "ldap".to_string(),
            "user".to_string(),
            "oistes".to_string(),
            "--filter".to_string(),
            "uid=oistes".to_string(),
            "--attributes".to_string(),
            "uid,cn".to_string(),
        ])
        .expect("command should parse");

        assert_eq!(
            cmd,
            ParsedCommand::LdapUser {
                uid: Some("oistes".to_string()),
                filter: Some("uid=oistes".to_string()),
                attributes: Some("uid,cn".to_string())
            }
        );
    }

    #[test]
    fn ldap_user_defaults_to_global_user() {
        let ctx = test_ctx();
        let rows = execute_command(
            &ctx,
            &ParsedCommand::LdapUser {
                uid: None,
                filter: None,
                attributes: None,
            },
        )
        .expect("ldap user should default to global user");

        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].get("uid").and_then(|v| v.as_str()), Some("oistes"));
    }

    #[test]
    fn parse_repl_command_rejects_empty_and_unknown_commands() {
        let empty = parse_repl_command(&[]).expect_err("empty command should fail");
        assert!(empty.to_string().contains("empty command"));

        let unsupported = parse_repl_command(&["mreg".to_string()])
            .expect_err("unsupported root command should fail");
        assert!(unsupported.to_string().contains("unsupported command"));

        let missing_subcommand = parse_repl_command(&["ldap".to_string()])
            .expect_err("missing ldap subcommand should fail");
        assert!(
            missing_subcommand
                .to_string()
                .contains("missing ldap subcommand")
        );
    }

    #[test]
    fn parse_repl_command_supports_netgroup_and_short_attribute_flag() {
        let cmd = parse_repl_command(&[
            "ldap".to_string(),
            "netgroup".to_string(),
            "ops".to_string(),
            "-a".to_string(),
            "cn,description".to_string(),
            "--filter".to_string(),
            "ops".to_string(),
        ])
        .expect("netgroup command should parse");

        assert_eq!(
            cmd,
            ParsedCommand::LdapNetgroup {
                name: Some("ops".to_string()),
                filter: Some("ops".to_string()),
                attributes: Some("cn,description".to_string()),
            }
        );
    }

    #[test]
    fn parse_repl_command_rejects_unknown_options_and_extra_positionals() {
        let unknown =
            parse_repl_command(&["ldap".to_string(), "user".to_string(), "--wat".to_string()])
                .expect_err("unknown flag should fail");
        assert!(unknown.to_string().contains("unknown option"));

        let extra = parse_repl_command(&[
            "ldap".to_string(),
            "netgroup".to_string(),
            "ops".to_string(),
            "extra".to_string(),
        ])
        .expect_err("extra positional should fail");
        assert!(
            extra
                .to_string()
                .contains("ldap netgroup accepts one name positional argument")
        );
    }

    #[test]
    fn execute_command_requires_explicit_subject_when_defaults_are_missing() {
        let ctx = ServiceContext::new(
            None,
            MockLdapClient::default(),
            crate::config::RuntimeConfig::default(),
        );
        let err = execute_command(
            &ctx,
            &ParsedCommand::LdapUser {
                uid: None,
                filter: None,
                attributes: None,
            },
        )
        .expect_err("ldap user should require uid when global user is missing");
        assert!(
            err.to_string()
                .contains("ldap user requires <uid> or -u/--user")
        );

        let err = execute_command(
            &ctx,
            &ParsedCommand::LdapNetgroup {
                name: None,
                filter: None,
                attributes: None,
            },
        )
        .expect_err("ldap netgroup should require a name");
        assert!(err.to_string().contains("ldap netgroup requires <name>"));
    }

    #[test]
    fn execute_line_handles_blank_and_shell_parse_errors() {
        let ctx = test_ctx();

        let blank = execute_line(&ctx, "   ").expect("blank line should be a no-op");
        assert!(output_rows(&blank).is_empty());

        let err = execute_line(&ctx, "ldap user \"unterminated")
            .expect_err("invalid shell quoting should fail");
        assert!(err.to_string().contains("unterminated"));
    }
}