greentic-pack-lib 0.4.124

Greentic pack builder and reader
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
use anyhow::{Result, bail};
use greentic_types::pack_manifest::{ExtensionInline, ExtensionRef};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashSet};

pub const STATIC_ROUTES_EXTENSION_KEY: &str = "greentic.static-routes.v1";

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct StaticRoutesExtensionV1 {
    pub version: u64,
    #[serde(default)]
    pub routes: Vec<StaticRouteV1>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct StaticRouteV1 {
    pub id: String,
    pub public_path: String,
    pub source_root: String,
    #[serde(default)]
    pub scope: StaticRouteScopeV1,
    #[serde(default)]
    pub index_file: Option<String>,
    #[serde(default)]
    pub spa_fallback: Option<String>,
    #[serde(default)]
    pub cache: Option<StaticRouteCacheV1>,
    #[serde(default)]
    pub exports: BTreeMap<String, String>,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct StaticRouteScopeV1 {
    #[serde(default)]
    pub tenant: bool,
    #[serde(default)]
    pub team: bool,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct StaticRouteCacheV1 {
    pub strategy: String,
    #[serde(default)]
    pub max_age_seconds: Option<u64>,
}

pub fn parse_static_routes_extension(
    extensions: &Option<BTreeMap<String, ExtensionRef>>,
) -> Result<Option<StaticRoutesExtensionV1>> {
    let Some(ext) = extensions
        .as_ref()
        .and_then(|all| all.get(STATIC_ROUTES_EXTENSION_KEY))
    else {
        return Ok(None);
    };

    let inline = ext.inline.as_ref().ok_or_else(|| {
        anyhow::anyhow!("extensions[{STATIC_ROUTES_EXTENSION_KEY}] inline is required")
    })?;

    let value = match inline {
        ExtensionInline::Other(value) => value.clone(),
        other => serde_json::to_value(other)?,
    };

    let payload: StaticRoutesExtensionV1 = serde_json::from_value(value)
        .map_err(|err| anyhow::anyhow!("invalid static routes extension payload: {err}"))?;
    Ok(Some(payload))
}

pub fn validate_static_routes_payload<F>(
    payload: &StaticRoutesExtensionV1,
    mut pack_path_exists: F,
) -> Result<()>
where
    F: FnMut(&str) -> bool,
{
    if payload.version != 1 {
        bail!("extensions[{STATIC_ROUTES_EXTENSION_KEY}] version must be 1");
    }
    if payload.routes.is_empty() {
        bail!("extensions[{STATIC_ROUTES_EXTENSION_KEY}] routes must not be empty");
    }

    let mut seen_ids = HashSet::new();
    let mut seen_paths = HashSet::new();
    let mut seen_exports = HashSet::new();

    for route in &payload.routes {
        if route.id.trim().is_empty() {
            bail!("extensions[{STATIC_ROUTES_EXTENSION_KEY}] route id must not be empty");
        }
        if !seen_ids.insert(route.id.as_str()) {
            bail!(
                "extensions[{STATIC_ROUTES_EXTENSION_KEY}] duplicate route id `{}`",
                route.id
            );
        }

        validate_public_path(&route.public_path).map_err(|err| {
            anyhow::anyhow!(
                "extensions[{STATIC_ROUTES_EXTENSION_KEY}] route `{}` public_path invalid: {err}",
                route.id
            )
        })?;
        let normalized_path = normalize_public_path(&route.public_path);
        if seen_paths.contains(normalized_path.as_str()) {
            bail!(
                "extensions[{STATIC_ROUTES_EXTENSION_KEY}] duplicate public_path `{}`",
                normalized_path
            );
        }
        seen_paths.insert(normalized_path);

        validate_source_root(&route.source_root).map_err(|err| {
            anyhow::anyhow!(
                "extensions[{STATIC_ROUTES_EXTENSION_KEY}] route `{}` source_root invalid: {err}",
                route.id
            )
        })?;
        if !pack_path_exists(&route.source_root) {
            bail!(
                "extensions[{STATIC_ROUTES_EXTENSION_KEY}] route `{}` source_root missing: {}",
                route.id,
                route.source_root
            );
        }

        if route.scope.team && !route.scope.tenant {
            bail!(
                "extensions[{STATIC_ROUTES_EXTENSION_KEY}] route `{}` cannot set scope.team=true when scope.tenant=false",
                route.id
            );
        }

        validate_cache(route).map_err(|err| {
            anyhow::anyhow!(
                "extensions[{STATIC_ROUTES_EXTENSION_KEY}] route `{}` cache invalid: {err}",
                route.id
            )
        })?;

        if let Some(index_file) = route.index_file.as_deref() {
            let logical = route_asset_path(&route.source_root, index_file).map_err(|err| {
                anyhow::anyhow!(
                    "extensions[{STATIC_ROUTES_EXTENSION_KEY}] route `{}` index_file invalid: {err}",
                    route.id
                )
            })?;
            if !pack_path_exists(&logical) {
                bail!(
                    "extensions[{STATIC_ROUTES_EXTENSION_KEY}] route `{}` index_file missing: {}",
                    route.id,
                    logical
                );
            }
        }

        if let Some(spa_fallback) = route.spa_fallback.as_deref() {
            let logical = route_asset_path(&route.source_root, spa_fallback).map_err(|err| {
                anyhow::anyhow!(
                    "extensions[{STATIC_ROUTES_EXTENSION_KEY}] route `{}` spa_fallback invalid: {err}",
                    route.id
                )
            })?;
            if !pack_path_exists(&logical) {
                bail!(
                    "extensions[{STATIC_ROUTES_EXTENSION_KEY}] route `{}` spa_fallback missing: {}",
                    route.id,
                    logical
                );
            }
        }

        for (export_key, export_name) in &route.exports {
            if export_key.trim().is_empty() {
                bail!(
                    "extensions[{STATIC_ROUTES_EXTENSION_KEY}] route `{}` export keys must not be empty",
                    route.id
                );
            }
            if export_name.trim().is_empty() {
                bail!(
                    "extensions[{STATIC_ROUTES_EXTENSION_KEY}] route `{}` export `{}` must not be empty",
                    route.id,
                    export_key
                );
            }
            if !seen_exports.insert(export_name.as_str()) {
                bail!(
                    "extensions[{STATIC_ROUTES_EXTENSION_KEY}] duplicate export name `{}`",
                    export_name
                );
            }
        }
    }

    Ok(())
}

pub fn validate_public_path(path: &str) -> Result<()> {
    if !path.starts_with('/') {
        bail!("must start with `/`");
    }
    if !path.starts_with("/v1/web/") {
        bail!("must start with `/v1/web/`");
    }
    if path.contains('?') || path.contains('#') {
        bail!("query strings and fragments are not allowed");
    }

    for segment in path.split('/').skip(1) {
        if segment.is_empty() {
            bail!("empty path segments are not allowed");
        }
        match segment {
            "{tenant}" | "{team}" => continue,
            "." | ".." => bail!("path traversal segments are not allowed"),
            _ => {}
        }
        if !segment
            .chars()
            .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.'))
        {
            bail!("unsupported path segment `{segment}`");
        }
    }

    Ok(())
}

pub fn normalize_public_path(path: &str) -> String {
    if path.len() > 1 {
        path.trim_end_matches('/').to_string()
    } else {
        path.to_string()
    }
}

pub fn validate_source_root(path: &str) -> Result<()> {
    if !path.starts_with("assets/") {
        bail!("must start with `assets/`");
    }
    if path.ends_with('/') {
        bail!("must not end with `/`");
    }
    validate_relative_path(&path["assets/".len()..])
}

pub fn route_asset_path(source_root: &str, relative: &str) -> Result<String> {
    validate_relative_path(relative)?;
    Ok(format!("{source_root}/{relative}"))
}

fn validate_cache(route: &StaticRouteV1) -> Result<()> {
    let Some(cache) = route.cache.as_ref() else {
        return Ok(());
    };

    match cache.strategy.as_str() {
        "none" => {
            if cache.max_age_seconds.is_some() {
                bail!("max_age_seconds is only valid when strategy is `public-max-age`");
            }
        }
        "public-max-age" => {
            if cache.max_age_seconds.is_none() {
                bail!("max_age_seconds is required when strategy is `public-max-age`");
            }
        }
        other => bail!("unknown cache strategy `{other}`"),
    }

    Ok(())
}

fn validate_relative_path(path: &str) -> Result<()> {
    if path.trim().is_empty() {
        bail!("must not be empty");
    }
    if path.starts_with('/') {
        bail!("must be relative");
    }
    for segment in path.split('/') {
        if segment.is_empty() {
            bail!("empty path segments are not allowed");
        }
        if matches!(segment, "." | "..") {
            bail!("path traversal segments are not allowed");
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use greentic_types::pack_manifest::ExtensionRef;
    use serde_json::json;

    #[test]
    fn public_path_rejects_unknown_placeholders() {
        let err = validate_public_path("/v1/web/demo/{pack}").unwrap_err();
        assert!(err.to_string().contains("unsupported path segment"));
    }

    #[test]
    fn payload_validation_enforces_unique_export_names() {
        let payload = StaticRoutesExtensionV1 {
            version: 1,
            routes: vec![
                StaticRouteV1 {
                    id: "a".into(),
                    public_path: "/v1/web/demo".into(),
                    source_root: "assets/demo".into(),
                    scope: StaticRouteScopeV1::default(),
                    index_file: Some("index.html".into()),
                    spa_fallback: None,
                    cache: None,
                    exports: BTreeMap::from([("base_url".into(), "shared_url".into())]),
                },
                StaticRouteV1 {
                    id: "b".into(),
                    public_path: "/v1/web/demo2".into(),
                    source_root: "assets/demo2".into(),
                    scope: StaticRouteScopeV1::default(),
                    index_file: Some("index.html".into()),
                    spa_fallback: None,
                    cache: None,
                    exports: BTreeMap::from([("entry_url".into(), "shared_url".into())]),
                },
            ],
        };

        let err = validate_static_routes_payload(&payload, |path| {
            matches!(
                path,
                "assets/demo"
                    | "assets/demo/index.html"
                    | "assets/demo2"
                    | "assets/demo2/index.html"
            )
        })
        .unwrap_err();
        assert!(err.to_string().contains("duplicate export name"));
    }

    #[test]
    fn parse_extension_requires_inline_payload() {
        let extensions = Some(BTreeMap::from([(
            STATIC_ROUTES_EXTENSION_KEY.to_string(),
            ExtensionRef {
                kind: STATIC_ROUTES_EXTENSION_KEY.to_string(),
                version: "1.0.0".to_string(),
                digest: None,
                location: None,
                inline: None,
            },
        )]));

        let err = parse_static_routes_extension(&extensions).unwrap_err();
        assert!(err.to_string().contains("inline is required"));
    }

    #[test]
    fn parse_extension_reads_other_inline_payload() {
        let extensions = Some(BTreeMap::from([(
            STATIC_ROUTES_EXTENSION_KEY.to_string(),
            ExtensionRef {
                kind: STATIC_ROUTES_EXTENSION_KEY.to_string(),
                version: "1.0.0".to_string(),
                digest: None,
                location: None,
                inline: Some(ExtensionInline::Other(json!({
                    "version": 1,
                    "routes": [{
                        "id": "web",
                        "public_path": "/v1/web/demo",
                        "source_root": "assets/demo"
                    }]
                }))),
            },
        )]));

        let parsed = parse_static_routes_extension(&extensions)
            .expect("parse")
            .expect("extension");
        assert_eq!(parsed.routes.len(), 1);
        assert_eq!(parsed.routes[0].id, "web");
    }

    #[test]
    fn validate_public_path_rejects_query_strings() {
        let err = validate_public_path("/v1/web/demo?x=1").unwrap_err();
        assert!(err.to_string().contains("query strings and fragments"));
    }

    #[test]
    fn validate_source_root_and_route_asset_path_reject_traversal() {
        let err = validate_source_root("assets/../secret").unwrap_err();
        assert!(err.to_string().contains("path traversal"));

        let err = route_asset_path("assets/demo", "../index.html").unwrap_err();
        assert!(err.to_string().contains("path traversal"));
    }

    #[test]
    fn payload_validation_rejects_invalid_cache_settings() {
        let payload = StaticRoutesExtensionV1 {
            version: 1,
            routes: vec![StaticRouteV1 {
                id: "web".into(),
                public_path: "/v1/web/demo".into(),
                source_root: "assets/demo".into(),
                scope: StaticRouteScopeV1::default(),
                index_file: Some("index.html".into()),
                spa_fallback: Some("index.html".into()),
                cache: Some(StaticRouteCacheV1 {
                    strategy: "public-max-age".into(),
                    max_age_seconds: None,
                }),
                exports: BTreeMap::new(),
            }],
        };

        let err = validate_static_routes_payload(&payload, |path| {
            matches!(path, "assets/demo" | "assets/demo/index.html")
        })
        .unwrap_err();
        assert!(err.to_string().contains("max_age_seconds is required"));
    }
}