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
//! Utility functions used to validate various argument types on the CLI. The arguments and return
//! type are what the `clap::Arg::validator` expects.

use std::{path::Path, result::Result as StdResult};

use crate::{
    context::{FlightCtx, DEFAULT_IMAGE_REGISTRY_URL},
    error::CliErrorKind,
    ops::formation::Endpoint,
};

pub fn validate_u64(s: &str) -> StdResult<u64, String> {
    match s.parse::<u64>() {
        Err(_) => Err("value must be a valid 64-bit integer".into()),
        Ok(n) => Ok(n),
    }
}

/// Ensures a valid Endpoint
pub fn validate_endpoint(s: &str) -> StdResult<Endpoint, String> {
    match s.parse::<Endpoint>() {
        Err(e) => Err(format!("invalid endpoint SPEC: {e}")),
        Ok(ep) => Ok(ep),
    }
}

/// Ensures a valid Public Endpoint, we must special case Public Endpoints because it only supports
/// the 'http' and 'https' protocol field.
pub fn validate_public_endpoint(s: &str) -> StdResult<Endpoint, String> {
    match s.parse::<Endpoint>() {
        Ok(ep) => Ok(ep),
        Err(mut details) => {
            if details.starts_with("invalid protocol") {
                details = "invalid protocol (valid options: http, https)".into();
            }
            Err(format!("invalid endpoint SPEC: {details}"))
        }
    }
}

/// The arg can be any of:
///
/// - name
/// - Local ID (32byte hex encoded string)
/// - @- (means STDIN)
/// - @path
pub fn validate_name_id_path<F>(name_validator: F, s: &str) -> StdResult<String, String>
where
    F: Fn(&str) -> StdResult<String, &'static str>,
{
    name_validator(s)
        .or_else(|_| validate_id(s))
        .or_else(|_| validate_at_path(s))
        .or_else(|_| validate_at_stdin(s))
        .map_err(|_| {
            "the value must be a NAME|ID|@PATH|@- where @PATH is a valid path or @- opens STDIN"
                .to_owned()
        })
}

/// The arg can be any of:
///
/// - name
/// - Local ID (32byte hex encoded string)
/// - @- (means STDIN)
/// - @path
/// - INLINE-SPEC for Flights
pub fn validate_name_id_path_inline(s: &str) -> StdResult<String, String> {
    validate_flight_name(s)
        .or_else(|_| validate_id(s))
        .or_else(|_| validate_at_path(s))
        .or_else(|_| validate_at_stdin(s))
        .or_else(|_| validate_inline_flight_spec(s))
        .map_err(|s| {
            format!("the value must be a NAME|ID|@PATH|@-|INLINE-SPEC where @PATH is a valid path or @- opens STDIN\n\ncaused by: {s}")
        })
}

/// The arg can be any of:
///
/// - name
/// - Local ID (32byte hex encoded string)
pub fn validate_name_id<F>(name_validator: F, s: &str) -> StdResult<String, &'static str>
where
    F: Fn(&str) -> StdResult<String, &'static str>,
{
    name_validator(s).or_else(|_| validate_id(s))
}

/// Rules:
///
/// - 1-63 alphanumeric characters (only ASCII lowercase) and hyphens ( 0-9, a-z, A-Z, and '-' )
/// (aka, one DNS segment)
pub fn validate_flight_name(name: &str) -> StdResult<String, &'static str> {
    if name.is_empty() {
        return Err("Flight name cannot be empty");
    }
    if name.len() > 63 {
        return Err("Flight name too long, must be <= 63 in length");
    }
    if !name
        .chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
    {
        return Err(
            "illegal character in Flight name; must only contain ASCII lowercase, digit, or hyphen ('-')",
        );
    }
    if name.contains("--") {
        return Err("repeated hyphens ('--') not allowed in Flight name");
    }

    Ok(name.into())
}

/// Current Rules:
///
///  - 1-30 alphanumeric (only ASCII lowercase) characters or hyphen (0-9, a-z, A-Z, and '-' )
///  - hyphens ('-') may not be repeated (i.e. '--')
///  - no more than three (3) total hyphens
///  - no consecutive hyphens
///  - no trailing hyphen
pub fn validate_formation_name(name: &str) -> StdResult<String, &'static str> {
    if name.is_empty() {
        return Err("Formation name cannot be empty");
    }
    if name.len() > 30 {
        return Err("Formation name too long, must be <= 30 in length");
    }
    if !name
        .chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
    {
        return Err(
            "illegal character in Formation name; must only contain ASCII lowercase, digit, or hyphen ('-')",
        );
    }
    if name.chars().filter(|c| *c == '-').count() > 3 {
        return Err("no more than three hyphens ('-') allowed in Formation name");
    }
    if name.contains("--") {
        return Err("repeated hyphens ('--') not allowed in Formation name");
    }
    if name.ends_with('-') {
        return Err("Formation names may not end with a hyphen ('-')");
    }

    Ok(name.into())
}

/// The value may be `@path` where `path` is some path that exists
pub fn validate_at_path(s: &str) -> StdResult<String, String> {
    if let Some(path) = s.strip_prefix('@') {
        if !Path::exists(path.as_ref()) {
            #[cfg(not(any(feature = "semantic_ui_tests", feature = "ui_tests")))]
            return Err(format!("path '{path}' does not exist"));
        }
    } else {
        return Err("the '@<path>'  was not provided".to_owned());
    }

    Ok(s.into())
}

/// The value may be `@-`
pub fn validate_at_stdin(s: &str) -> StdResult<String, &'static str> {
    if s != "@-" {
        return Err("the value '@-' was not provided");
    }

    Ok(s.into())
}

/// The value may be:
///
/// name=NAME,image=IMG,maximum=NUM,minimum=NUM,api-permission[=true|false],architecture=ARCH
///
/// where only image is required, and architecture can be passed multiple times.
pub fn validate_inline_flight_spec(s: &str) -> StdResult<String, String> {
    // We use the default image registry URL regardless of what the user has set because we're only
    // checking validity, not actually using this data
    if let Err(e) = FlightCtx::from_inline_flight(s, DEFAULT_IMAGE_REGISTRY_URL) {
        return Err(format!("invalid INLINE-SPEC: {}", {
            match e.kind() {
                CliErrorKind::InlineFlightUnknownItem(s) => format!("unknown item {s}"),
                CliErrorKind::InlineFlightMissingValue(s) => {
                    format!("key '{s}' is missing the value")
                }
                CliErrorKind::InlineFlightHasSpace => {
                    String::from("inline flight contains a space (' ')")
                }
                CliErrorKind::InlineFlightMissingImage => {
                    String::from("Missing required image=IMAGE-SPEC")
                }
                CliErrorKind::InlineFlightInvalidName(s) => {
                    format!("Flight Plan name '{s}' isn't valid")
                }
                CliErrorKind::ParseInt(e) => format!("failed to parse minimum or maximum: {e}"),
                CliErrorKind::StrumParse(e) => format!("failed to parse architecture: {e}"),
                CliErrorKind::ImageReference(e) => format!("invalid IMAGE-SPEC: {e}"),
                _ => unreachable!(),
            }
        }));
    }
    Ok(s.into())
}

/// The value may be a *up to* a 32byte hex encoded string
pub fn validate_id(s: &str) -> StdResult<String, &'static str> {
    if s.is_empty() {
        return Err("ID cannot be empty");
    }
    if !s.chars().all(is_hex_char) {
        return Err("found non-hex character");
    }
    if s.chars().count() > 64 {
        return Err("ID provided is too long");
    }

    Ok(s.into())
}

fn is_hex_char(c: char) -> bool { matches!(c, 'a'..='f' | 'A'..='F' | '0'..='9') }

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn is_hex_char_valid() {
        for c in ('a'..'g').chain(('A'..'G').chain('0'..='9')) {
            assert!(is_hex_char(c));
        }
    }

    #[test]
    fn is_hex_char_invalid() {
        for c in ('g'..='z').chain('G'..'Z') {
            assert!(!is_hex_char(c));
        }
    }

    #[test]
    fn invalid_flight_names() {
        assert!(validate_flight_name("").is_err());
        assert!(validate_flight_name("no-special-chars!").is_err());
        assert!(validate_flight_name("imwaaaaaytoolongforanythingthatshouldbeanameimwaaaaaytoolongforanythingthatshouldbeaname").is_err());
        assert!(validate_flight_name("noUperCase").is_err());
    }

    #[test]
    fn invalid_formation_names() {
        assert!(validate_formation_name("").is_err());
        assert!(validate_formation_name("no-special-chars!").is_err());
        assert!(validate_formation_name("imwaaaaaytoolongforanythingthatshouldbeaname").is_err());
        assert!(validate_formation_name("too-many-hyphens-in-here").is_err());
        assert!(validate_formation_name("no-ending-hyphen-").is_err());
        assert!(validate_formation_name("noUperCase").is_err());
    }

    #[test]
    fn invalid_id() {
        assert!(validate_id("").is_err());
        assert!(validate_id("imnotahexvalue").is_err());
        // Too long
        assert!(validate_id("abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890").is_err());
    }

    #[test]
    fn invalid_at_path() {
        assert!(validate_id("").is_err());
        assert!(validate_id("@").is_err());
        assert!(validate_id("@-").is_err());
        assert!(validate_id("@foo").is_err());
        assert!(validate_id("foo").is_err());
    }

    #[test]
    fn invalid_at_stdin() {
        assert!(validate_id("").is_err());
        assert!(validate_id("@").is_err());
        assert!(validate_id("@foo").is_err());
        assert!(validate_id("foo").is_err());
    }
}