use crate::error::is_secret_key;
use http::Method;
use serde_json::Value;
use std::fmt;
fn redact<'a>(key: &str, value: &'a str) -> &'a str {
if is_secret_key(key) {
"<redacted>"
} else {
value
}
}
fn redacted_pairs(pairs: &[(String, String)]) -> Vec<(&str, &str)> {
pairs
.iter()
.map(|(key, value)| (key.as_str(), redact(key, value)))
.collect()
}
#[derive(Clone)]
#[non_exhaustive]
pub enum Body {
None,
Form(Vec<(String, String)>),
Json(Value),
}
impl fmt::Debug for Body {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::None => f.write_str("None"),
Self::Form(pairs) => f.debug_tuple("Form").field(&redacted_pairs(pairs)).finish(),
Self::Json(_) => f.write_str("Json(<redacted>)"),
}
}
}
#[derive(Clone)]
#[must_use]
pub struct Request {
method: Method,
path: String,
query: Vec<(String, String)>,
body: Body,
kite_version: &'static str,
}
impl Request {
pub fn new(method: Method, path: impl Into<String>) -> Self {
Self {
method,
path: path.into(),
query: Vec::new(),
body: Body::None,
kite_version: "3",
}
}
pub fn get(path: impl Into<String>) -> Self {
Self::new(Method::GET, path)
}
pub fn post(path: impl Into<String>) -> Self {
Self::new(Method::POST, path)
}
pub fn put(path: impl Into<String>) -> Self {
Self::new(Method::PUT, path)
}
pub fn delete(path: impl Into<String>) -> Self {
Self::new(Method::DELETE, path)
}
pub fn query<K: Into<String>, V: Into<String>>(
mut self,
pairs: impl IntoIterator<Item = (K, V)>,
) -> Self {
self.query.extend(
pairs
.into_iter()
.map(|(key, value)| (key.into(), value.into())),
);
self
}
pub fn form<K: Into<String>, V: Into<String>>(
self,
pairs: impl IntoIterator<Item = (K, V)>,
) -> Self {
self.with_body(Body::Form(
pairs
.into_iter()
.map(|(key, value)| (key.into(), value.into()))
.collect(),
))
}
pub fn json(self, value: Value) -> Self {
self.with_body(Body::Json(value))
}
pub fn with_body(mut self, body: Body) -> Self {
self.body = body;
self
}
pub fn kite_version(mut self, version: &'static str) -> Self {
self.kite_version = version;
self
}
#[must_use]
pub fn method(&self) -> &Method {
&self.method
}
#[must_use]
pub fn path(&self) -> &str {
&self.path
}
#[must_use]
pub fn query_pairs(&self) -> &[(String, String)] {
&self.query
}
#[must_use]
pub fn body(&self) -> &Body {
&self.body
}
pub(crate) fn kite_version_header(&self) -> &'static str {
self.kite_version
}
}
impl fmt::Debug for Request {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Request")
.field("method", &self.method)
.field("path", &self.path.split('?').next().unwrap_or_default())
.field("query", &redacted_pairs(&self.query))
.field("body", &self.body)
.field("kite_version", &self.kite_version)
.finish()
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct RawResponse {
pub(crate) status: u16,
pub(crate) content_type: Option<String>,
pub(crate) body: Vec<u8>,
}
impl RawResponse {
#[must_use]
pub fn status(&self) -> u16 {
self.status
}
#[must_use]
pub fn content_type(&self) -> Option<&str> {
self.content_type.as_deref()
}
#[must_use]
pub fn body(&self) -> &[u8] {
&self.body
}
}
#[cfg(test)]
mod tests {
use super::*;
const SECRETS: [(&str, &str); 7] = [
("api_secret", "SENTINEL-SECRET"),
("ACCESS_TOKEN", "SENTINEL-ACCESS"),
("refresh_token", "SENTINEL-REFRESH"),
("request_token", "SENTINEL-REQUEST"),
("password", "SENTINEL-PASSWORD"),
("checksum", "SENTINEL-CHECKSUM"),
("twofa_value", "SENTINEL-OTP"),
];
#[test]
fn query_debug_redacts_every_secret_key() {
let request = Request::get("/session/token?access_token=SENTINEL-PATH")
.query(SECRETS)
.query([("i", "NSE:INFY")]);
let debug = format!("{request:?}");
assert!(!debug.contains("SENTINEL"), "{debug}");
assert!(debug.contains("NSE:INFY"), "{debug}");
}
#[test]
fn form_debug_redacts_every_secret_key() {
let request = Request::post("/session/token")
.form(SECRETS.into_iter().chain([("tradingsymbol", "INFY")]));
let debug = format!("{request:?}");
assert!(!debug.contains("SENTINEL"), "{debug}");
assert!(debug.contains("INFY"), "{debug}");
}
}