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
#![warn(missing_docs)]

//! A start on implementing Splunk-SDK-like-things

use std::env;
use std::str::FromStr;

use reqwest::header::HeaderMap;
use reqwest::{Client, Response, Url};
use search::AuthenticationMethod;
use serde::{Deserialize, Serialize};

#[macro_use]
extern crate lazy_static;

#[allow(unused_imports)]
#[macro_use]
extern crate tokio;

#[cfg(feature = "hec")]
pub mod hec;
#[cfg(feature = "search")]
#[macro_use]
pub mod search;

#[cfg(test)]
mod tests;

#[derive(Clone, Debug, Serialize, Deserialize)]
/// What we're going to use to connect to the server
pub struct ServerConfig {
    /// Server hostname - just something like example.com (or an IP, if you're like that)
    pub hostname: String,
    /// Port - defaults to 8089
    pub port: u16,
    validate_ssl: bool,
    verify_tls: bool,
    auth_method: AuthenticationMethod,
    connection_timeout: u16,
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            hostname: "localhost".to_string(),
            port: 8089,
            validate_ssl: true,
            verify_tls: true,
            auth_method: AuthenticationMethod::Unknown,
            connection_timeout: 30,
        }
    }
}

impl ServerConfig {
    /// build a url based on the server/endpoint
    /// ```
    /// use std::str::FromStr;
    /// use reqwest::Url;
    /// use splunk::hec::HecClient;
    ///
    /// let client = HecClient::new("token", "localhost");
    /// let expected_response = Url::from_str("https://localhost:8088/hello").unwrap();
    /// assert_eq!(client.serverconfig.get_url("/hello").unwrap(), expected_response);
    /// ```
    pub fn get_url(&self, endpoint: &str) -> Result<Url, String> {
        let mut result = String::new();

        result.push_str(match self.verify_tls {
            true => "https",
            false => "http",
        });

        result.push_str("://");
        result.push_str(&self.hostname);
        if (self.verify_tls && self.port != 443) || (!self.verify_tls && self.port != 80) {
            result.push_str(&format!(":{}", self.port));
        }
        result.push_str(endpoint);
        Url::from_str(&result).map_err(|e| format!("{e:?}"))
    }

    /// Point at a server
    pub fn new(hostname: String) -> Self {
        Self {
            hostname,
            ..Default::default()
        }
    }

    /// Set the authentication method to token and set the token
    pub fn with_token(mut self, token: String) -> Self {
        self.auth_method = AuthenticationMethod::Token { token };
        self
    }

    /// Set the authentication method to basic and set the credentials
    pub fn with_username_password(mut self, username: String, password: String) -> Self {
        self.auth_method = AuthenticationMethod::Basic { username, password };
        self
    }

    /// Get the token from the auth method, if it exists
    pub fn token(&self) -> Option<String> {
        match &self.auth_method {
            AuthenticationMethod::Basic {
                username: _,
                password,
            } => Some(password.to_owned()),
            AuthenticationMethod::Token { token } => Some(token.to_owned()),
            AuthenticationMethod::Unknown => None,
            AuthenticationMethod::Cookie { .. } => None,
        }
    }

    /// make a get request to a given endpoint
    pub async fn do_get(&self, endpoint: &str) -> Result<Response, String> {
        let headers = HeaderMap::new();
        self.do_get_with_headers(endpoint, headers).await
    }

    /// make a get request to a given endpoint and set the headers
    pub async fn do_get_with_headers(
        &self,
        endpoint: &str,
        add_headers: HeaderMap,
    ) -> Result<Response, String> {
        let request = Client::new().get(self.get_url(endpoint).unwrap());

        let mut headers = HeaderMap::new();

        // apply the supplied_headers
        add_headers.into_iter().for_each(|(key, val)| {
            headers.insert(key.unwrap(), val);
        });

        let request = match &self.auth_method {
            AuthenticationMethod::Token { token } => {
                headers.insert(
                    "Authorization",
                    format!("Splunk {}", token).parse().unwrap(),
                );
                request.headers(headers)
            }
            _ => todo!("haven't handled all the things yet"),
            // AuthenticatedSessionMode::Cookie { value: _ } => todo!(),
            // AuthenticatedSessionMode::Unset => todo!(),
        };

        // eprintln!("{:#?}", request);
        request.send().await.map_err(|e| format!("{e:?}"))
    }

    /// Set the port
    pub fn with_port(mut self, port: u16) -> Self {
        self.port = port;
        self
    }

    /// Set the hostname
    pub fn with_hostname(mut self, hostname: String) -> Self {
        self.hostname = hostname;
        self
    }

    /// Do we verify TLS on send?
    pub fn with_verify_tls(mut self, verify_tls: bool) -> Self {
        self.verify_tls = verify_tls;
        self
    }

    /// Grabs a [ServerConfig] from environment variables
    pub fn try_from_env(configtype: ServerConfigType) -> Result<ServerConfig, String> {
        let env_prefix = match configtype {
            ServerConfigType::Hec => "SPLUNK_HEC_",
            ServerConfigType::Api => "SPLUNK_API_",
        };

        let hostname = match env::var(format!("{env_prefix}HOSTNAME")) {
            Ok(val) => val,
            Err(_) => {
                let error = format!("Please ensure env var {env_prefix}HOSTNAME is set");
                eprintln!("{}", error);
                return Err(error);
            }
        };
        let port = match env::var(format!("{env_prefix}PORT")) {
            Ok(val) => val,
            Err(_) => 8089.to_string(),
        };
        let port: u16 = port.parse::<u16>().unwrap();

        let config = ServerConfig::new(hostname).with_port(port);
        let config = match configtype {
            ServerConfigType::Hec => {
                let token = env::var(format!("{env_prefix}TOKEN"))
                    .expect("Couldn't get SPLUNK_HEC_TOKEN env var");
                config.with_token(token)
            }
            ServerConfigType::Api => config.with_username_password(
                env::var("SPLUNK_USERNAME").expect("Couldn't get SPLUNK_USERNAME env var!"),
                env::var("SPLUNK_PASSWORD").expect("Couldn't get SPLUNK_PASSWORD env var!"),
            ),
        };
        Ok(config)
    }
}

/// This is just used in get_serverconfig so you can say "I need a HEC or I need an API one!"
pub enum ServerConfigType {
    /// You're using HTTP Event Collector - looks for SPLUNK_HEC_*
    Hec,
    /// You're using API Endpoints - looks for SPLUNK_API_*
    Api,
}