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
//! Want to search things? Here's your place.

use reqwest::header::HeaderMap;
use reqwest::{Client, Response};
use serde::{Deserialize, Serialize};
// use serde_json::Value;
use std::collections::HashMap;

use crate::ServerConfig;

#[macro_use]
pub mod searchjob;

pub use searchjob::{SearchJob, SearchResult};

#[derive(Clone, Debug, Deserialize, Serialize)]
/// The current auth method for the search client
pub enum AuthenticationMethod {
    /// Basic auth
    Basic {
        /// username
        username: String,
        ///password
        password: String,
    },
    /// Token auth
    Token {
        /// token auth
        token: String,
    },
    /// Cookie based
    Cookie {
        /// cookie store
        cookie: HashMap<String, String>,
    },
    /// we haven't set it yet
    Unknown,
}

#[derive(Debug, Deserialize, Serialize)]
/// the current auth mode - you can auth with username/password then get a cookie and go from there
pub enum AuthenticatedSessionMode {
    /// cookie auth
    Cookie {
        /// cookie value
        value: HashMap<String, String>,
    },
    /// token auth
    Token {
        /// the token
        value: String,
    },
    /// we haven't set it yet
    Unset,
}

#[derive(Debug, Deserialize, Serialize)]
/// Client for splunk enterprise/cloud API things, login, search, manipulate config items etc.
pub struct SplunkClient {
    #[serde(flatten)]
    /// server configuration object
    pub serverconfig: ServerConfig,
    /// what mode we're using for authentication (token, cookie etc)
    pub auth_session_mode: AuthenticatedSessionMode,
    #[serde(skip)]
    client: Client,
}

impl Default for SplunkClient {
    fn default() -> Self {
        Self {
            serverconfig: ServerConfig::default(),
            auth_session_mode: AuthenticatedSessionMode::Unset,
            client: Client::new(),
        }
    }
}

impl SplunkClient {
    /// set the config on build
    pub fn with_config(self, serverconfig: ServerConfig) -> Self {
        Self {
            serverconfig,
            ..self
        }
    }
    /// Make a POST request
    pub async fn do_post(
        &mut self,
        endpoint: &str,
        payload: HashMap<&str, String>,
    ) -> Result<Response, String> {
        let req = self
            .client
            .post(self.serverconfig.get_url(endpoint).unwrap())
            .form(&payload);

        let req = match &self.serverconfig.auth_method {
            AuthenticationMethod::Basic { username, password } => {
                req.basic_auth(username, Some(password))
            }
            AuthenticationMethod::Token { token } => {
                req.header("Authorization", format!("Splunk {}", token))
            }
            AuthenticationMethod::Unknown => todo!(),
            // TODO: handle cookie auth for posts?
            AuthenticationMethod::Cookie { cookie: _ } => todo!(),
        };

        eprintln!("About to post this: {req:#?}");
        eprintln!("About to post this: {:#?}", payload);

        req.send().await.map_err(|e| format!("{e:?}"))
    }

    /// Make a GET request, tries to pass the authentication automagically
    pub async fn do_get(&mut self, endpoint: &str) -> Result<Response, String> {
        let request = self
            .client
            .get(self.serverconfig.get_url(endpoint).unwrap());

        let request = match &self.auth_session_mode {
            AuthenticatedSessionMode::Token { value } => {
                let mut headers = HeaderMap::new();
                headers.insert(
                    "Authorization",
                    format!("Splunk {}", value).parse().unwrap(),
                );
                request.headers(headers)
            }
            AuthenticatedSessionMode::Cookie { value: _ } => todo!(),
            AuthenticatedSessionMode::Unset => todo!(),
        };

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

    /// Login and establish the session
    pub async fn login(&mut self) -> Result<(), String> {
        let endpoint = "/services/auth/login";

        let mut payload: HashMap<&str, String> = HashMap::new();

        match &self.serverconfig.auth_method {
            AuthenticationMethod::Basic { username, password } => {
                // request.basic_auth(username, Some(password)),
                payload.insert("username", username.to_owned());
                payload.insert("password", password.to_owned());
            }
            // AuthenticationMethod::Token { token } => todo!(),
            AuthenticationMethod::Unknown => panic!("Please specify an auth method!"),
            _ => unimplemented!("Token mode isn't supported!"),
        };

        let request = self.do_post(endpoint, payload).await?;

        // eprintln!("Response: {:#?}", request.headers());
        let body = request.text().await.unwrap();
        let res: serde_json::Value = serde_xml_rs::from_str(&body)
            .map_err(|e| format!("{e:?}"))
            .unwrap();
        let res = match res.get("sessionKey") {
            Some(val) => val,
            None => return Err("Couldn't get sessionKey".to_string()),
        };
        let res = match res.get("$value") {
            Some(val) => val.as_str().unwrap().to_string(),
            None => return Err("Couldn't get sessionKey.$value from response".to_string()),
        };
        self.auth_session_mode = AuthenticatedSessionMode::Token { value: res };
        Ok(())
    }

    /// Get the authenticated session owner username.
    /// <https://docs.splunk.com/Documentation/Splunk/9.0.4/RESTREF/RESTaccess#authentication.2Fcurrent-context>
    /// Currently returns just the raw XML result as a string
    #[cfg(feature = "xml_raw")]
    pub async fn get_current_context(&mut self) -> Result<String, String> {
        let endpoint = "/services/authentication/current-context";

        let res = self.do_get(endpoint).await?;
        let res = res.text().await.map_err(|e| format!("{e:?}"))?;
        // serde_xml_rs::from_str(&res).map_err(|e| format!("{e:?}"))
        Ok(res)
    }

    /// Get the authenticated session owner username.
    /// <https://docs.splunk.com/Documentation/Splunk/9.0.4/RESTREF/RESTaccess#authorization.2Fcapabilities>
    ///
    /// Currently returns just the raw XML result as a string
    #[cfg(feature = "xml_raw")]
    pub async fn get_capabilities(&mut self) -> Result<String, String> {
        let endpoint = "/services/authorization/capabilities";

        let res = self.do_get(endpoint).await?;
        let res = res.text().await.map_err(|e| format!("{e:?}"))?;
        res
    }

    /// do an export-search - TODO
    pub async fn export() -> Result<(), String> {
        unimplemented!();
    }
}