sutures 1.0.1

Protocol-agnostic API abstraction gateway
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
use super::schema::Direction;
use crate::error::Error;

/// Maximum allowed regex pattern length (between backticks).
const MAX_REGEX_LEN: usize = 200;

/// Allowed characters in terminals (both JSON and struct).
/// Matches schema pattern: `[A-Za-z0-9_$.[\]:?/`^()\-+\\*|]`
fn is_terminal_char(c: char) -> bool {
    c.is_ascii_alphanumeric()
        || matches!(
            c,
            '_' | '$'
                | '.'
                | '['
                | ']'
                | ':'
                | '?'
                | '/'
                | '`'
                | '^'
                | '('
                | ')'
                | '-'
                | '+'
                | '\\'
                | '*'
                | '|'
        )
}

/// Validate a key (read side / LHS).
///
/// - Request keys are struct terminals.
/// - Response keys are JSON terminals.
/// - Regex (`` `pattern` ``) allowed on read side.
/// - Pythonic iterators (`[:]`, `[1:3]`, `[::2]`, etc.) allowed.
pub(super) fn validate_key(key: &str, direction: &Direction) -> Result<(), Error> {
    if key.is_empty() {
        return Err(Error::Suture("key must not be empty".into()));
    }
    // Regex keys (backtick-leading) bypass direction-specific terminal format checks.
    // Response regex keys always start with `/` first, so this only affects request.
    if !key.starts_with('`') {
        match direction {
            Direction::Request => validate_struct_terminal(key, "request key")?,
            Direction::Response => validate_json_terminal(key, "response key")?,
        }
    }
    validate_charset(key)?;
    validate_backticks(key)?;
    validate_brackets(key)?;
    Ok(())
}

/// Validate a value (write side / RHS).
///
/// - Request values are JSON terminals.
/// - Response values are struct terminals.
/// - Regex is **forbidden** on the write side.
/// - Pythonic iterators allowed (zipped with read-side).
pub(super) fn validate_terminal(s: &str, direction: &Direction) -> Result<(), Error> {
    if s.is_empty() {
        return Err(Error::Suture("terminal must not be empty".into()));
    }
    match direction {
        Direction::Request => validate_json_terminal(s, "request value")?,
        Direction::Response => validate_struct_terminal(s, "response value")?,
    }
    validate_charset(s)?;
    if contains_backtick(s) {
        return Err(Error::Suture(format!(
            "regex is not allowed on the write side, got: '{s}'"
        )));
    }
    validate_brackets(s)?;
    Ok(())
}

/// Validate a single constant entry value — only scalars allowed.
pub(super) fn validate_constant(val: &serde_json::Value) -> Result<(), Error> {
    match val {
        serde_json::Value::String(_)
        | serde_json::Value::Number(_)
        | serde_json::Value::Bool(_)
        | serde_json::Value::Null => Ok(()),
        _ => Err(Error::Suture(
            "constant value must be a scalar (string, number, boolean, or null)".into(),
        )),
    }
}

// ===========================================================================
// JSON terminal
// ===========================================================================

fn validate_json_terminal(s: &str, ctx: &str) -> Result<(), Error> {
    if !s.starts_with('/') {
        return Err(Error::Suture(format!(
            "{ctx} must start with '/', got: '{s}'"
        )));
    }
    if s.len() > 1 && s.ends_with('/') {
        return Err(Error::Suture(format!(
            "{ctx} must not end with '/', got: '{s}'"
        )));
    }
    if s.contains("//") {
        return Err(Error::Suture(format!(
            "{ctx} must not contain consecutive '/', got: '{s}'"
        )));
    }
    Ok(())
}

// ===========================================================================
// Struct terminal
// ===========================================================================

fn validate_struct_terminal(s: &str, ctx: &str) -> Result<(), Error> {
    if !s.starts_with(|c: char| c.is_ascii_alphabetic()) {
        return Err(Error::Suture(format!(
            "{ctx} must start with a letter, got: '{s}'"
        )));
    }
    if s.ends_with('.') {
        return Err(Error::Suture(format!(
            "{ctx} must not end with '.', got: '{s}'"
        )));
    }
    if s.contains("..") {
        return Err(Error::Suture(format!(
            "{ctx} must not contain consecutive dots '..', got: '{s}'"
        )));
    }
    Ok(())
}

// ===========================================================================
// Character whitelist
// ===========================================================================

fn validate_charset(s: &str) -> Result<(), Error> {
    let mut in_backtick = false;
    for (i, c) in s.char_indices() {
        if c == '`' {
            in_backtick = !in_backtick;
            continue;
        }
        if !in_backtick && !is_terminal_char(c) {
            return Err(Error::Suture(format!(
                "invalid character '{c}' at position {i} in terminal: '{s}'"
            )));
        }
    }
    Ok(())
}

// ===========================================================================
// Backtick / regex validation
// ===========================================================================

fn contains_backtick(s: &str) -> bool {
    s.contains('`')
}

/// Validate all backtick-delimited regex segments in a terminal.
///
/// Checks:
/// - Balanced backticks (even count).
/// - No empty patterns (`` `` is rejected).
/// - Pattern compiles as a valid regex (Rust `regex` crate flavor).
/// - No capturing groups (use `(?:...)` instead).
/// - Pattern length ≤ MAX_REGEX_LEN.
fn validate_backticks(s: &str) -> Result<(), Error> {
    let bytes = s.as_bytes();
    let mut i = 0;

    while i < bytes.len() {
        if bytes[i] == b'`' {
            let open = i;
            i += 1;

            // Find closing backtick.
            let pattern_start = i;
            while i < bytes.len() && bytes[i] != b'`' {
                i += 1;
            }
            if i >= bytes.len() {
                return Err(Error::Suture(format!(
                    "unmatched backtick at position {open} in terminal: '{s}'"
                )));
            }

            let pattern = &s[pattern_start..i];
            i += 1; // skip closing backtick

            // Empty pattern.
            if pattern.is_empty() {
                return Err(Error::Suture(format!(
                    "empty regex pattern not allowed in terminal: '{s}'"
                )));
            }

            // Length limit.
            if pattern.len() > MAX_REGEX_LEN {
                return Err(Error::Suture(format!(
                    "regex pattern exceeds max length ({MAX_REGEX_LEN} chars) in terminal: '{s}'"
                )));
            }

            // No capturing groups — reject unescaped `(` not followed by `?:`.
            validate_no_capturing_groups(pattern, s)?;

            // Must compile as valid regex.
            if let Err(e) = regex::Regex::new(&format!("^{pattern}$")) {
                return Err(Error::Suture(format!(
                    "invalid regex `{pattern}` in terminal '{s}': {e}"
                )));
            }

            continue;
        }

        i += 1;
    }

    Ok(())
}

/// Reject capturing groups — only non-capturing `(?:...)` allowed.
fn validate_no_capturing_groups(pattern: &str, full: &str) -> Result<(), Error> {
    let bytes = pattern.as_bytes();
    let mut i = 0;

    while i < bytes.len() {
        if bytes[i] == b'\\' {
            // Skip escaped character.
            i += 2;
            continue;
        }
        if bytes[i] == b'(' {
            // Check if followed by `?` (non-capturing / assertion).
            if i + 1 < bytes.len() && bytes[i + 1] == b'?' {
                // `(?:...)`, `(?=...)`, `(?!...)`, etc. — allowed.
                i += 2;
                continue;
            }
            return Err(Error::Suture(format!(
                "capturing groups not allowed in regex, use (?:...) instead, in terminal: '{full}'"
            )));
        }
        i += 1;
    }

    Ok(())
}

// ===========================================================================
// Bracket / pythonic iterator validation
//
// Valid forms inside `[...]`:
//   [N]              index      — [0], [-1], [42]
//   [start:end]      slice      — [1:3], [:3], [1:], [:]
//   [start:end:step] extended   — [::2], [1::2], [1:3:2], [::-1]
//
// Rules:
//   - Empty brackets `[]` are invalid.
//   - Parts are optional integers (may be negative).
//   - Step must not be 0.
//   - No whitespace inside brackets.
//   - Max 2 colons (3 parts).
//   - Brackets inside backtick-delimited regex are skipped.
// ===========================================================================

fn validate_brackets(s: &str) -> Result<(), Error> {
    let bytes = s.as_bytes();
    let mut i = 0;

    while i < bytes.len() {
        // Skip backtick-delimited regex — don't validate brackets inside.
        if bytes[i] == b'`' {
            i += 1;
            while i < bytes.len() && bytes[i] != b'`' {
                i += 1;
            }
            if i < bytes.len() {
                i += 1; // skip closing backtick
            }
            continue;
        }

        if bytes[i] == b'[' {
            i += 1;
            let bracket_start = i;

            // Find closing bracket — no nesting allowed.
            while i < bytes.len() && bytes[i] != b']' {
                if bytes[i] == b'[' {
                    return Err(Error::Suture(format!(
                        "nested brackets not allowed in terminal: '{s}'"
                    )));
                }
                i += 1;
            }
            if i >= bytes.len() {
                return Err(Error::Suture(format!("unclosed '[' in terminal: '{s}'")));
            }

            let inner = &s[bracket_start..i];
            i += 1; // skip ']'

            validate_bracket_inner(inner, s)?;
            // Reject consecutive brackets (e.g., items[:][0]).
            if i < bytes.len() && bytes[i] == b'[' {
                return Err(Error::Suture(format!(
                    "consecutive brackets not allowed in terminal: '{s}'"
                )));
            }
            continue;
        }

        // Stray closing bracket.
        if bytes[i] == b']' {
            return Err(Error::Suture(format!(
                "unexpected ']' without matching '[' in terminal: '{s}'"
            )));
        }

        i += 1;
    }

    Ok(())
}

/// Validate the contents between `[` and `]`.
fn validate_bracket_inner(inner: &str, full: &str) -> Result<(), Error> {
    // Empty brackets.
    if inner.is_empty() {
        return Err(Error::Suture(format!(
            "empty brackets '[]' not allowed in terminal: '{full}'"
        )));
    }

    // No whitespace.
    if inner.contains(|c: char| c.is_ascii_whitespace()) {
        return Err(Error::Suture(format!(
            "whitespace not allowed inside brackets '[{inner}]' in terminal: '{full}'"
        )));
    }

    let parts: Vec<&str> = inner.split(':').collect();

    match parts.len() {
        // [N] — single index.
        1 => {
            let idx = validate_int_part(parts[0], full, "index")?;
            if idx == i64::MAX {
                return Err(Error::Suture(format!(
                    "index too large in bracket expression '[{inner}]' in terminal: '{full}'"
                )));
            }
        }
        // [start:end] — slice.
        2 => {
            if !parts[0].is_empty() {
                validate_int_part(parts[0], full, "start")?;
            }
            if !parts[1].is_empty() {
                validate_int_part(parts[1], full, "end")?;
            }
        }
        // [start:end:step] — extended slice.
        3 => {
            if !parts[0].is_empty() {
                validate_int_part(parts[0], full, "start")?;
            }
            if !parts[1].is_empty() {
                validate_int_part(parts[1], full, "end")?;
            }
            if !parts[2].is_empty() {
                let step = validate_int_part(parts[2], full, "step")?;
                if step == 0 {
                    return Err(Error::Suture(format!(
                        "step cannot be 0 in bracket expression '[{inner}]' in terminal: '{full}'"
                    )));
                }
            }
        }
        _ => {
            return Err(Error::Suture(format!(
                "too many ':' in bracket expression '[{inner}]' in terminal: '{full}'"
            )));
        }
    }

    Ok(())
}

/// Validate that a slice part is a valid integer. Returns the parsed value.
fn validate_int_part(part: &str, full: &str, label: &str) -> Result<i64, Error> {
    part.parse::<i64>().map_err(|_| {
        Error::Suture(format!(
            "invalid {label} '{part}' in bracket expression, expected integer, in terminal: '{full}'"
        ))
    })
}