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
use reqwest::header::HeaderMap;
use reqwest::{Client, Response};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use crate::ServerConfig;
#[macro_use]
pub mod searchjob;
pub use searchjob::{SearchJob, SearchResult};
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum AuthenticationMethod {
Basic {
username: String,
password: String,
},
Token {
token: String,
},
Cookie {
cookie: HashMap<String, String>,
},
Unknown,
}
#[derive(Debug, Deserialize, Serialize)]
pub enum AuthenticatedSessionMode {
Cookie {
value: HashMap<String, String>,
},
Token {
value: String,
},
Unset,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct SplunkClient {
#[serde(flatten)]
pub serverconfig: ServerConfig,
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 {
pub fn with_config(self, serverconfig: ServerConfig) -> Self {
Self {
serverconfig,
..self
}
}
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!(),
AuthenticationMethod::Cookie { cookie: _ } => todo!(),
};
eprintln!("About to post this: {req:#?}");
eprintln!("About to post this: {:#?}", payload);
req.send().await.map_err(|e| format!("{e:?}"))
}
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!(),
};
request.send().await.map_err(|e| format!("{e:?}"))
}
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 } => {
payload.insert("username", username.to_owned());
payload.insert("password", password.to_owned());
}
AuthenticationMethod::Unknown => panic!("Please specify an auth method!"),
_ => unimplemented!("Token mode isn't supported!"),
};
let request = self.do_post(endpoint, payload).await?;
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(())
}
#[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:?}"))?;
Ok(res)
}
#[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
}
pub async fn export() -> Result<(), String> {
unimplemented!();
}
}