domain-status 0.2.1

Concurrent URL status checker that captures comprehensive metadata in SQLite.
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
//! Category loading operations for fingerprint rulesets.
//!
//! This module handles fetching and loading categories from URLs and local paths.

use anyhow::{Context, Result};
use std::collections::HashMap;
use std::path::Path;
use std::time::Duration;
use tokio::fs;

use crate::fingerprint::models::Category;

/// Fetches categories.json from a URL
pub(crate) async fn fetch_categories_from_url(url: &str) -> Result<HashMap<u32, String>> {
    use crate::config::TCP_CONNECT_TIMEOUT_SECS;

    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(60))
        .connect_timeout(Duration::from_secs(TCP_CONNECT_TIMEOUT_SECS)) // FIX: Enforce TCP connect timeout
        .build()?;

    // Convert technologies URL to categories URL
    // e.g., https://raw.githubusercontent.com/HTTPArchive/wappalyzer/main/src/technologies
    // -> https://raw.githubusercontent.com/HTTPArchive/wappalyzer/main/src/categories.json
    let categories_url = if url.contains("raw.githubusercontent.com")
        && !std::path::Path::new(url)
            .extension()
            .is_some_and(|ext| ext.eq_ignore_ascii_case("json"))
    {
        // It's a directory - construct categories.json URL in parent directory
        // e.g., .../src/technologies -> .../src/categories.json
        let trimmed = url.trim_end_matches('/');
        if trimmed.ends_with("/technologies") {
            // Remove "/technologies" and add "/categories.json"
            let base = &trimmed[..trimmed.len() - 12];
            format!("{}/categories.json", base.trim_end_matches('/'))
        } else {
            format!("{trimmed}/../categories.json")
        }
    } else if std::path::Path::new(url)
        .extension()
        .is_some_and(|ext| ext.eq_ignore_ascii_case("json"))
    {
        // Single file - replace with categories.json in same directory
        let mut parts: Vec<&str> = url.split('/').collect();
        if let Some(last) = parts.last_mut() {
            *last = "categories.json";
        }
        parts.join("/")
    } else {
        // Fallback: try appending ../categories.json
        format!("{}/../categories.json", url.trim_end_matches('/'))
    };

    log::debug!("Fetching categories from: {categories_url}");
    let response = client.get(&categories_url).send().await?;
    if !response.status().is_success() {
        return Err(anyhow::anyhow!(
            "Failed to fetch categories: {}",
            response.status()
        ));
    }

    let json_text = response.text().await?;
    // Parse as a map of category ID (string) -> Category
    let categories_map: HashMap<String, Category> =
        serde_json::from_str(&json_text).context("Failed to parse categories JSON")?;

    // Convert to HashMap<u32, String> (ID -> name)
    let mut result = HashMap::new();
    for (id_str, category) in categories_map {
        if let Ok(id) = id_str.parse::<u32>() {
            result.insert(id, category.name);
        }
    }

    log::info!("Loaded {} categories", result.len());
    Ok(result)
}

/// Loads categories.json from a local path
pub(crate) async fn load_categories_from_path(path: &Path) -> Result<HashMap<u32, String>> {
    let categories_path = if path.is_dir() {
        // If it's a directory, look for categories.json in the parent or same directory
        path.parent()
            .map(|p| p.join("categories.json"))
            .or_else(|| Some(path.join("categories.json")))
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "Cannot determine categories.json path. Checked: parent directory of '{}' and \
                    same directory. Ensure categories.json exists in the expected location.",
                    path.display()
                )
            })?
    } else {
        // If it's a file, replace filename with categories.json
        path.parent()
            .map(|p| p.join("categories.json"))
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "Cannot determine categories.json path. Checked: parent directory of '{}'. \
                    Ensure categories.json exists in the expected location.",
                    path.display()
                )
            })?
    };

    if !categories_path.exists() {
        return Err(anyhow::anyhow!(
            "categories.json not found at {}",
            categories_path.display()
        ));
    }

    let content = fs::read_to_string(&categories_path).await?;
    let categories_map: HashMap<String, Category> =
        serde_json::from_str(&content).context("Failed to parse categories JSON")?;

    // Convert to HashMap<u32, String> (ID -> name)
    let mut result = HashMap::new();
    for (id_str, category) in categories_map {
        if let Ok(id) = id_str.parse::<u32>() {
            result.insert(id, category.name);
        }
    }

    log::info!(
        "Loaded {} categories from {}",
        result.len(),
        categories_path.display()
    );
    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;
    use httptest::{matchers::*, responders::*, Expectation, Server};
    use tempfile::TempDir;
    use tokio::io::AsyncWriteExt;

    #[tokio::test]
    async fn test_fetch_categories_from_url_success() {
        let server = Server::run();
        server.expect(
            Expectation::matching(request::method_path("GET", "/categories.json")).respond_with(
                status_code(200).body(r#"{"1": {"name": "CMS"}, "2": {"name": "E-commerce"}}"#),
            ),
        );

        let base_url = server.url("/");
        let url = format!("{}categories.json", base_url);
        let result = fetch_categories_from_url(&url).await;
        assert!(result.is_ok());
        let categories = result.unwrap();
        assert_eq!(categories.len(), 2);
        assert_eq!(categories.get(&1), Some(&"CMS".to_string()));
        assert_eq!(categories.get(&2), Some(&"E-commerce".to_string()));
    }

    #[tokio::test]
    async fn test_fetch_categories_from_url_github_directory() {
        let server = Server::run();
        server.expect(
            Expectation::matching(request::method_path("GET", "/src/categories.json"))
                .respond_with(status_code(200).body(r#"{"1": {"name": "CMS"}}"#)),
        );

        let base_url = server.url("/");
        let url = format!("{}src/technologies", base_url);
        let result = fetch_categories_from_url(&url).await;
        assert!(result.is_ok());
        let categories = result.unwrap();
        assert_eq!(categories.get(&1), Some(&"CMS".to_string()));
    }

    #[tokio::test]
    async fn test_fetch_categories_from_url_single_json_file() {
        let server = Server::run();
        server.expect(
            Expectation::matching(request::method_path("GET", "/src/categories.json"))
                .respond_with(status_code(200).body(r#"{"1": {"name": "CMS"}}"#)),
        );

        let base_url = server.url("/");
        let url = format!("{}src/technologies.json", base_url);
        let result = fetch_categories_from_url(&url).await;
        assert!(result.is_ok());
    }

    /// Kills: `fetch_categories_from_url` returning `Err` without
    /// `"Failed to fetch categories"` (e.g. a bare status-only message).
    #[tokio::test]
    async fn test_fetch_categories_from_url_http_error() {
        let server = Server::run();
        server.expect(
            Expectation::matching(request::method_path("GET", "/categories.json"))
                .respond_with(status_code(404)),
        );

        let base_url = server.url("/");
        let url = format!("{}categories.json", base_url);
        let result = fetch_categories_from_url(&url).await;
        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        assert!(
            error_msg.contains("Failed to fetch categories"),
            "expected fetch-failed context, got: {error_msg}"
        );
    }

    /// Kills: `fetch_categories_from_url` dropping the
    /// `"Failed to parse categories JSON"` context on invalid JSON.
    #[tokio::test]
    async fn test_fetch_categories_from_url_invalid_json() {
        let server = Server::run();
        server.expect(
            Expectation::matching(request::method_path("GET", "/categories.json"))
                .respond_with(status_code(200).body("{ invalid json }")),
        );

        let base_url = server.url("/");
        let url = format!("{}categories.json", base_url);
        let result = fetch_categories_from_url(&url).await;
        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        assert!(
            error_msg.contains("Failed to parse categories JSON"),
            "expected parse-context, got: {error_msg}"
        );
    }

    #[tokio::test]
    async fn test_fetch_categories_from_url_non_numeric_id() {
        let server = Server::run();
        server.expect(
            Expectation::matching(request::method_path("GET", "/categories.json")).respond_with(
                status_code(200)
                    .body(r#"{"invalid": {"name": "CMS"}, "1": {"name": "E-commerce"}}"#),
            ),
        );

        let base_url = server.url("/");
        let url = format!("{}categories.json", base_url);
        let result = fetch_categories_from_url(&url).await;
        assert!(result.is_ok());
        let categories = result.unwrap();
        // Non-numeric ID should be skipped
        assert_eq!(categories.len(), 1);
        assert_eq!(categories.get(&1), Some(&"E-commerce".to_string()));
        assert!(!categories.contains_key(&0)); // "invalid" should not be parsed
    }

    /// Kills: `fetch_categories_from_url` flattening a missing `name` field so
    /// the source chain no longer contains serde's `missing field`.
    #[tokio::test]
    async fn test_fetch_categories_from_url_missing_name() {
        let server = Server::run();
        // Category struct requires name field, so missing name will cause deserialization error
        server.expect(
            Expectation::matching(request::method_path("GET", "/categories.json"))
                .respond_with(status_code(200).body(r#"{"1": {}}"#)),
        );

        let base_url = server.url("/");
        let url = format!("{}categories.json", base_url);
        let result = fetch_categories_from_url(&url).await;
        let err = result.expect_err("missing name must fail deserialize");
        assert!(
            err.to_string().contains("Failed to parse categories JSON"),
            "expected parse-context, got: {err}"
        );
        assert!(
            err.chain().any(|e| e.to_string().contains("missing field")),
            "source chain must name the missing field, got: {err:#}"
        );
    }

    /// Contract: `{}` loads as an empty map (`is_ok` then `len() == 0`).
    #[tokio::test]
    async fn test_fetch_categories_from_url_empty_categories() {
        let server = Server::run();
        server.expect(
            Expectation::matching(request::method_path("GET", "/categories.json"))
                .respond_with(status_code(200).body("{}")),
        );

        let base_url = server.url("/");
        let url = format!("{}categories.json", base_url);
        let result = fetch_categories_from_url(&url).await;
        assert!(result.is_ok());
        let categories = result.unwrap();
        assert_eq!(categories.len(), 0);
    }

    #[tokio::test]
    async fn test_load_categories_from_path_success() {
        let temp_dir = TempDir::new().expect("Failed to create temp directory");
        let categories_path = temp_dir.path().join("categories.json");
        let mut file = tokio::fs::File::create(&categories_path)
            .await
            .expect("Failed to create test file");
        file.write_all(r#"{"1": {"name": "CMS"}, "2": {"name": "E-commerce"}}"#.as_bytes())
            .await
            .expect("Failed to write categories JSON");
        file.flush().await.expect("Failed to flush file");
        drop(file);

        let tech_path = temp_dir.path().join("technologies");
        let result = load_categories_from_path(&tech_path).await;
        assert!(result.is_ok());
        let categories = result.unwrap();
        assert_eq!(categories.len(), 2);
        assert_eq!(categories.get(&1), Some(&"CMS".to_string()));
    }

    #[tokio::test]
    async fn test_load_categories_from_path_file_not_found() {
        let temp_dir = TempDir::new().expect("Failed to create temp directory");
        let tech_path = temp_dir.path().join("nonexistent");
        let result = load_categories_from_path(&tech_path).await;
        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        assert!(
            error_msg.contains("not found") || error_msg.contains("No such file"),
            "Expected file not found error, got: {}",
            error_msg
        );
    }

    /// Kills: `load_categories_from_path` dropping the
    /// `"Failed to parse categories JSON"` context on invalid JSON.
    #[tokio::test]
    async fn test_load_categories_from_path_invalid_json() {
        let temp_dir = TempDir::new().expect("Failed to create temp directory");
        let categories_path = temp_dir.path().join("categories.json");
        let mut file = tokio::fs::File::create(&categories_path)
            .await
            .expect("Failed to create test file");
        file.write_all(b"{ invalid json }")
            .await
            .expect("Failed to write invalid JSON");
        file.flush().await.expect("Failed to flush file");
        drop(file);

        let tech_path = temp_dir.path().join("technologies");
        let result = load_categories_from_path(&tech_path).await;
        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        assert!(
            error_msg.contains("Failed to parse categories JSON"),
            "expected parse-context, got: {error_msg}"
        );
    }

    #[tokio::test]
    async fn test_load_categories_from_path_directory() {
        let temp_dir = TempDir::new().expect("Failed to create temp directory");
        let categories_path = temp_dir.path().join("categories.json");
        let mut file = tokio::fs::File::create(&categories_path)
            .await
            .expect("Failed to create test file");
        file.write_all(r#"{"1": {"name": "CMS"}}"#.as_bytes())
            .await
            .expect("Failed to write categories JSON");
        file.flush().await.expect("Failed to flush file");
        drop(file);

        // Test with directory path
        let tech_dir = temp_dir.path().join("technologies");
        tokio::fs::create_dir_all(&tech_dir)
            .await
            .expect("Failed to create technologies directory");
        let result = load_categories_from_path(&tech_dir).await;
        assert!(result.is_ok());
        let categories = result.unwrap();
        assert_eq!(categories.get(&1), Some(&"CMS".to_string()));
    }

    #[tokio::test]
    async fn test_load_categories_from_path_file_path() {
        let temp_dir = TempDir::new().expect("Failed to create temp directory");
        // Create technologies directory
        let tech_dir = temp_dir.path().join("technologies");
        tokio::fs::create_dir_all(&tech_dir)
            .await
            .expect("Failed to create technologies directory");

        // Put categories.json in the technologies directory (parent of tech.json)
        // The function looks in the parent directory of the file
        let categories_path = tech_dir.join("categories.json");
        let mut file = tokio::fs::File::create(&categories_path)
            .await
            .expect("Failed to create test file");
        file.write_all(r#"{"1": {"name": "CMS"}}"#.as_bytes())
            .await
            .expect("Failed to write categories JSON");
        file.flush().await.expect("Failed to flush file");
        drop(file);

        // Test with file path in technologies subdirectory
        // The function should look in parent (tech_dir) for categories.json
        let tech_file = tech_dir.join("tech.json");
        tokio::fs::File::create(&tech_file)
            .await
            .expect("Failed to create tech.json");

        let result = load_categories_from_path(&tech_file).await;
        assert!(result.is_ok());
        let categories = result.unwrap();
        assert_eq!(categories.get(&1), Some(&"CMS".to_string()));
    }
}