nginx-discovery 0.4.0

Parse, analyze, and extract information from NGINX configurations
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
//! High-level discovery API for NGINX configurations
//!
//! This module provides a convenient API for discovering and analyzing NGINX configurations.
//!
//! # Examples
//!
//! ## Parse from text
//!
//! ```
//! use nginx_discovery::NginxDiscovery;
//!
//! let config = r"
//! http {
//!     access_log /var/log/nginx/access.log;
//! }
//! ";
//!
//! let discovery = NginxDiscovery::from_config_text(config)?;
//! let logs = discovery.access_logs();
//! assert_eq!(logs.len(), 1);
//! # Ok::<(), nginx_discovery::Error>(())
//! ```
//!
//! ## Parse from file
//!
//! ```no_run
//! use nginx_discovery::NginxDiscovery;
//!
//! let discovery = NginxDiscovery::from_config_file("/etc/nginx/nginx.conf")?;
//! let logs = discovery.access_logs();
//! let formats = discovery.log_formats();
//! # Ok::<(), nginx_discovery::Error>(())
//! ```

use crate::ast::Config;
use crate::error::Result;
use crate::extract;
use crate::prelude::Server;
use crate::types::{AccessLog, LogFormat};
use std::path::{Path, PathBuf};

/// High-level NGINX configuration discovery
///
/// Provides convenient methods to discover and analyze NGINX configurations.
#[derive(Debug, Clone)]
pub struct NginxDiscovery {
    /// Parsed configuration
    config: Config,
    /// Path to the configuration file (if loaded from file)
    config_path: Option<PathBuf>,
}

impl NginxDiscovery {
    /// Create a discovery instance from configuration text
    ///
    /// # Arguments
    ///
    /// * `text` - NGINX configuration as a string
    ///
    /// # Errors
    ///
    /// Returns an error if the configuration cannot be parsed.
    ///
    /// # Examples
    ///
    /// ```
    /// use nginx_discovery::NginxDiscovery;
    ///
    /// let config = "user nginx;";
    /// let discovery = NginxDiscovery::from_config_text(config)?;
    /// # Ok::<(), nginx_discovery::Error>(())
    /// ```
    pub fn from_config_text(text: &str) -> Result<Self> {
        let config = crate::parse(text)?;
        Ok(Self {
            config,
            config_path: None,
        })
    }

    /// Create a discovery instance from a configuration file
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the NGINX configuration file
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The file cannot be read
    /// - The configuration cannot be parsed
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nginx_discovery::NginxDiscovery;
    ///
    /// let discovery = NginxDiscovery::from_config_file("/etc/nginx/nginx.conf")?;
    /// # Ok::<(), nginx_discovery::Error>(())
    /// ```
    pub fn from_config_file(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        let text = std::fs::read_to_string(path)?;
        let config = crate::parse(&text)?;
        Ok(Self {
            config,
            config_path: Some(path.to_path_buf()),
        })
    }

    /// Create a discovery instance from a running NGINX instance
    ///
    /// This attempts to:
    /// 1. Find the nginx binary
    /// 2. Run `nginx -T` to dump the configuration
    /// 3. Parse the dumped configuration
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - nginx binary cannot be found
    /// - nginx -T fails to execute
    /// - The configuration cannot be parsed
    /// - Insufficient permissions to run nginx -T
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nginx_discovery::NginxDiscovery;
    ///
    /// let discovery = NginxDiscovery::from_running_instance()?;
    /// let logs = discovery.access_logs();
    /// # Ok::<(), nginx_discovery::Error>(())
    /// ```
    #[cfg(feature = "system")]
    pub fn from_running_instance() -> Result<Self> {
        crate::system::detect_and_parse()
    }

    /// Get all access log configurations
    ///
    /// Returns all `access_log` directives found in the configuration,
    /// including those in http, server, and location contexts.
    ///
    /// # Examples
    ///
    /// ```
    /// use nginx_discovery::NginxDiscovery;
    ///
    /// let config = r"
    /// http {
    ///     access_log /var/log/nginx/access.log;
    ///     server {
    ///         access_log /var/log/nginx/server.log;
    ///     }
    /// }
    /// ";
    ///
    /// let discovery = NginxDiscovery::from_config_text(config)?;
    /// let logs = discovery.access_logs();
    /// assert_eq!(logs.len(), 2);
    /// # Ok::<(), nginx_discovery::Error>(())
    /// ```
    #[must_use]
    pub fn access_logs(&self) -> Vec<AccessLog> {
        extract::access_logs(&self.config).unwrap_or_default()
    }

    /// Get all log format definitions
    ///
    /// Returns all `log_format` directives found in the configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use nginx_discovery::NginxDiscovery;
    ///
    /// let config = r"
    /// log_format combined '$remote_addr - $remote_user [$time_local]';
    /// log_format main '$request $status';
    /// ";
    ///
    /// let discovery = NginxDiscovery::from_config_text(config)?;
    /// let formats = discovery.log_formats();
    /// assert_eq!(formats.len(), 2);
    /// # Ok::<(), nginx_discovery::Error>(())
    /// ```
    #[must_use]
    pub fn log_formats(&self) -> Vec<LogFormat> {
        extract::log_formats(&self.config).unwrap_or_default()
    }

    /// Get all log file paths (access logs only)
    ///
    /// Returns a deduplicated list of all access log file paths.
    ///
    /// # Examples
    ///
    /// ```
    /// use nginx_discovery::NginxDiscovery;
    ///
    /// let config = r"
    /// access_log /var/log/nginx/access.log;
    /// access_log /var/log/nginx/access.log;  # duplicate
    /// access_log /var/log/nginx/other.log;
    /// ";
    ///
    /// let discovery = NginxDiscovery::from_config_text(config)?;
    /// let files = discovery.all_log_files();
    /// assert_eq!(files.len(), 2); // deduplicated
    /// # Ok::<(), nginx_discovery::Error>(())
    /// ```
    #[must_use]
    pub fn all_log_files(&self) -> Vec<PathBuf> {
        let mut paths: Vec<PathBuf> = self.access_logs().into_iter().map(|log| log.path).collect();

        // Deduplicate
        paths.sort();
        paths.dedup();
        paths
    }

    /// Get all server names from server blocks
    ///
    /// Returns a list of all server names defined in server blocks.
    ///
    /// # Examples
    ///
    /// ```
    /// use nginx_discovery::NginxDiscovery;
    ///
    /// let config = r"
    /// server {
    ///     server_name example.com www.example.com;
    /// }
    /// server {
    ///     server_name test.com;
    /// }
    /// ";
    ///
    /// let discovery = NginxDiscovery::from_config_text(config)?;
    /// let names = discovery.server_names();
    /// assert_eq!(names.len(), 3);
    /// # Ok::<(), nginx_discovery::Error>(())
    /// ```
    #[must_use]
    pub fn server_names(&self) -> Vec<String> {
        let mut names = Vec::new();

        for server in self.config.find_directives_recursive("server") {
            for server_name_directive in server.find_children("server_name") {
                names.extend(server_name_directive.args_as_strings());
            }
        }

        names
    }

    /// Export configuration to JSON
    ///
    /// # Errors
    ///
    /// Returns an error if serialization fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use nginx_discovery::NginxDiscovery;
    ///
    /// let config = "user nginx;";
    /// let discovery = NginxDiscovery::from_config_text(config)?;
    /// let json = discovery.to_json()?;
    /// assert!(json.contains("user"));
    /// # Ok::<(), nginx_discovery::Error>(())
    /// ```
    #[cfg(feature = "serde")]
    pub fn to_json(&self) -> Result<String> {
        serde_json::to_string_pretty(&self.config)
            .map_err(|e| crate::Error::Serialization(e.to_string()))
    }

    /// Export configuration to YAML
    ///
    /// # Errors
    ///
    /// Returns an error if serialization fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use nginx_discovery::NginxDiscovery;
    ///
    /// let config = "user nginx;";
    /// let discovery = NginxDiscovery::from_config_text(config)?;
    /// let yaml = discovery.to_yaml()?;
    /// assert!(yaml.contains("user"));
    /// # Ok::<(), nginx_discovery::Error>(())
    /// ```
    #[cfg(feature = "serde")]
    pub fn to_yaml(&self) -> Result<String> {
        serde_yaml::to_string(&self.config).map_err(|e| crate::Error::Serialization(e.to_string()))
    }

    /// Get the parsed configuration AST
    ///
    /// Provides direct access to the parsed configuration for custom processing.
    ///
    /// # Examples
    ///
    /// ```
    /// use nginx_discovery::NginxDiscovery;
    ///
    /// let config = "user nginx;";
    /// let discovery = NginxDiscovery::from_config_text(config)?;
    /// let ast = discovery.config();
    /// assert_eq!(ast.directives.len(), 1);
    /// # Ok::<(), nginx_discovery::Error>(())
    /// ```
    #[must_use]
    pub fn config(&self) -> &Config {
        &self.config
    }

    /// Get the configuration file path (if loaded from file)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nginx_discovery::NginxDiscovery;
    ///
    /// let discovery = NginxDiscovery::from_config_file("/etc/nginx/nginx.conf")?;
    /// assert!(discovery.config_path().is_some());
    /// # Ok::<(), nginx_discovery::Error>(())
    /// ```
    #[must_use]
    pub fn config_path(&self) -> Option<&Path> {
        self.config_path.as_deref()
    }

    /// Generate a summary of the configuration
    ///
    /// Returns a human-readable summary including:
    /// - Number of directives
    /// - Number of server blocks
    /// - Number of access logs
    /// - Number of log formats
    ///
    /// # Examples
    ///
    /// ```
    /// use nginx_discovery::NginxDiscovery;
    ///
    /// let config = r"
    /// user nginx;
    /// access_log /var/log/nginx/access.log;
    /// server { listen 80; }
    /// ";
    ///
    /// let discovery = NginxDiscovery::from_config_text(config)?;
    /// let summary = discovery.summary();
    /// assert!(summary.contains("directives"));
    /// # Ok::<(), nginx_discovery::Error>(())
    /// ```
    #[must_use]
    pub fn summary(&self) -> String {
        let directive_count = self.config.count_directives();
        let server_count = self.config.find_directives_recursive("server").len();
        let access_log_count = self.access_logs().len();
        let format_count = self.log_formats().len();

        format!(
            "NGINX Configuration Summary:\n\
            - Total directives: {directive_count}\n\
            - Server blocks: {server_count}\n\
            - Access logs: {access_log_count}\n\
            - Log formats: {format_count}"
        )
    }

    // Add these methods to the NginxDiscovery impl block:

    /// Get all server blocks
    ///
    /// Returns all `server` blocks found in the configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use nginx_discovery::NginxDiscovery;
    ///
    /// let config = r"
    /// server {
    ///     listen 80;
    ///     server_name example.com;
    /// }
    /// ";
    ///
    /// let discovery = NginxDiscovery::from_config_text(config)?;
    /// let servers = discovery.servers();
    /// assert_eq!(servers.len(), 1);
    /// # Ok::<(), nginx_discovery::Error>(())
    /// ```
    #[must_use]
    pub fn servers(&self) -> Vec<crate::types::Server> {
        extract::servers(&self.config).unwrap_or_default()
    }

    /// Get all listening ports
    ///
    /// Returns a deduplicated list of all ports that servers are listening on.
    ///
    /// # Examples
    ///
    /// ```
    /// use nginx_discovery::NginxDiscovery;
    ///
    /// let config = r"
    /// server {
    ///     listen 80;
    ///     listen 443 ssl;
    /// }
    /// ";
    ///
    /// let discovery = NginxDiscovery::from_config_text(config)?;
    /// let ports = discovery.listening_ports();
    /// assert!(ports.contains(&80));
    /// assert!(ports.contains(&443));
    /// # Ok::<(), nginx_discovery::Error>(())
    /// ```
    #[must_use]
    pub fn listening_ports(&self) -> Vec<u16> {
        let mut ports: Vec<u16> = self
            .servers()
            .iter()
            .flat_map(|s| s.listen.iter().map(|l| l.port))
            .collect();

        ports.sort_unstable();
        ports.dedup();
        ports
    }

    /// Get all SSL-enabled servers
    ///
    /// Returns servers that have SSL configured.
    ///
    /// # Examples
    ///
    /// ```
    /// use nginx_discovery::NginxDiscovery;
    ///
    /// let config = r"
    /// server {
    ///     listen 80;
    ///     server_name example.com;
    /// }
    /// server {
    ///     listen 443 ssl;
    ///     server_name secure.example.com;
    /// }
    /// ";
    ///
    /// let discovery = NginxDiscovery::from_config_text(config)?;
    /// let ssl_servers = discovery.ssl_servers();
    /// assert_eq!(ssl_servers.len(), 1);
    /// # Ok::<(), nginx_discovery::Error>(())
    /// ```
    #[must_use]
    pub fn ssl_servers(&self) -> Vec<crate::types::Server> {
        self.servers().into_iter().filter(Server::has_ssl).collect()
    }

    /// Get all proxy locations
    ///
    /// Returns all location blocks that have `proxy_pass` configured.
    ///
    /// # Examples
    ///
    /// ```
    /// use nginx_discovery::NginxDiscovery;
    ///
    /// let config = r"
    /// server {
    ///     location / {
    ///         root /var/www;
    ///     }
    ///     location /api {
    ///         proxy_pass http://backend;
    ///     }
    /// }
    /// ";
    ///
    /// let discovery = NginxDiscovery::from_config_text(config)?;
    /// let proxies = discovery.proxy_locations();
    /// assert_eq!(proxies.len(), 1);
    /// # Ok::<(), nginx_discovery::Error>(())
    /// ```
    #[must_use]
    pub fn proxy_locations(&self) -> Vec<crate::types::Location> {
        self.servers()
            .iter()
            .flat_map(|s| s.locations.iter())
            .filter(|l: &&crate::types::Location| l.is_proxy())
            .cloned()
            .collect()
    }

    /// Count total number of location blocks
    #[must_use]
    pub fn location_count(&self) -> usize {
        self.servers().iter().map(|s| s.locations.len()).sum()
    }
}

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

    #[test]
    fn test_from_config_text() {
        let config = "user nginx;";
        let discovery = NginxDiscovery::from_config_text(config).unwrap();
        assert_eq!(discovery.config.directives.len(), 1);
    }

    #[test]
    fn test_access_logs() {
        let config = r"
        http {
            access_log /var/log/nginx/access.log;
            server {
                access_log /var/log/nginx/server.log;
            }
        }
        ";

        let discovery = NginxDiscovery::from_config_text(config).unwrap();
        let logs = discovery.access_logs();
        assert_eq!(logs.len(), 2);
    }

    #[test]
    fn test_log_formats() {
        let config = r"
        log_format combined '$remote_addr';
        log_format main '$request';
        ";

        let discovery = NginxDiscovery::from_config_text(config).unwrap();
        let formats = discovery.log_formats();
        assert_eq!(formats.len(), 2);
    }

    #[test]
    fn test_all_log_files() {
        let config = r"
        access_log /var/log/nginx/access.log;
        access_log /var/log/nginx/access.log;
        access_log /var/log/nginx/other.log;
        ";

        let discovery = NginxDiscovery::from_config_text(config).unwrap();
        let files = discovery.all_log_files();
        assert_eq!(files.len(), 2); // Deduplicated
    }

    #[test]
    fn test_server_names() {
        let config = r"
        server {
            server_name example.com www.example.com;
        }
        server {
            server_name test.com;
        }
        ";

        let discovery = NginxDiscovery::from_config_text(config).unwrap();
        let names = discovery.server_names();
        assert_eq!(names.len(), 3);
        assert!(names.contains(&"example.com".to_string()));
        assert!(names.contains(&"www.example.com".to_string()));
        assert!(names.contains(&"test.com".to_string()));
    }

    #[test]
    fn test_summary() {
        let config = r"
        user nginx;
        access_log /var/log/nginx/access.log;
        server { listen 80; }
        ";

        let discovery = NginxDiscovery::from_config_text(config).unwrap();
        let summary = discovery.summary();
        assert!(summary.contains("directives"));
        assert!(summary.contains("Server blocks: 1"));
    }

    #[test]
    fn test_config_access() {
        let config = "user nginx;";
        let discovery = NginxDiscovery::from_config_text(config).unwrap();
        let ast = discovery.config();
        assert_eq!(ast.directives.len(), 1);
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_to_json() {
        let config = "user nginx;";
        let discovery = NginxDiscovery::from_config_text(config).unwrap();
        let json = discovery.to_json().unwrap();
        assert!(json.contains("user"));
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_to_yaml() {
        let config = "user nginx;";
        let discovery = NginxDiscovery::from_config_text(config).unwrap();
        let yaml = discovery.to_yaml().unwrap();
        assert!(yaml.contains("user"));
    }
}