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
use streamdal_gjson as gjson;

#[derive(Debug)]
pub enum TransformError {
    Generic(String),
}

pub struct Request {
    pub data: Vec<u8>,
    pub path: String,
    pub value: String,
}

pub fn overwrite(req: &Request) -> Result<String, TransformError> {
    validate_request(req, true)?;

    let data = gjson::set_overwrite(
        convert_bytes_to_string(&req.data)?,
        req.path.as_str(),
        req.value.as_str(),
    )
    .map_err(|e| TransformError::Generic(format!("unable to overwrite data: {}", e)))?;

    Ok(data)
}

pub fn obfuscate(req: &Request) -> Result<String, TransformError> {
    validate_request(req, false)?;

    let data_as_str = convert_bytes_to_string(&req.data)?;
    let value = gjson::get(data_as_str, req.path.as_str());

    match value.kind() {
        gjson::Kind::String => _obfuscate(data_as_str, req.path.as_str()),
        _ => Err(TransformError::Generic(format!(
            "unable to mask data: path '{}' is not a string or number",
            req.path
        ))),
    }
}

fn _obfuscate(data: &str, path: &str) -> Result<String, TransformError> {
    let contents = gjson::get(data, path);
    let hashed = sha256::digest(contents.str().as_bytes());

    let obfuscated = format!("\"sha256:{}\"", hashed);

    gjson::set_overwrite(data, path, &obfuscated)
        .map_err(|e| TransformError::Generic(format!("unable to obfuscate data: {}", e)))
}

pub fn mask(req: &Request) -> Result<String, TransformError> {
    validate_request(req, false)?;

    let data_as_str = convert_bytes_to_string(&req.data)?;
    let value = gjson::get(data_as_str, req.path.as_str());

    match value.kind() {
        gjson::Kind::String => _mask(data_as_str, req.path.as_str(), '*', true),
        gjson::Kind::Number => _mask(data_as_str, req.path.as_str(), '0', false),
        _ => Err(TransformError::Generic(format!(
            "unable to mask data: path '{}' is not a string or number",
            req.path
        ))),
    }
}

fn _mask(data: &str, path: &str, mask_char: char, quote: bool) -> Result<String, TransformError> {
    let contents = gjson::get(data, path);
    let num_chars_to_mask = (0.8 * contents.str().len() as f64).round() as usize;
    let num_chars_to_skip = contents.str().len() - num_chars_to_mask;

    let mut masked = contents.str()[0..num_chars_to_skip].to_string()
        + mask_char.to_string().repeat(num_chars_to_mask).as_str();

    if quote {
        masked = format!("\"{}\"", masked);
    }

    gjson::set_overwrite(data, path, &masked)
        .map_err(|e| TransformError::Generic(format!("unable to mask data: {}", e)))
}

fn validate_request(req: &Request, value_check: bool) -> Result<(), TransformError> {
    if req.path.is_empty() {
        return Err(TransformError::Generic("path cannot be empty".to_string()));
    }

    if req.data.is_empty() {
        return Err(TransformError::Generic("data cannot be empty".to_string()));
    }

    if value_check && req.value.is_empty() {
        return Err(TransformError::Generic("value cannot be empty".to_string()));
    }

    // Is this valid JSON?
    if !gjson::valid(convert_bytes_to_string(&req.data)?) {
        return Err(TransformError::Generic(
            "data is not valid JSON".to_string(),
        ));
    }

    // Valid path?
    if !gjson::get(convert_bytes_to_string(&req.data)?, req.path.as_str()).exists() {
        return Err(TransformError::Generic(format!(
            "path '{}' not found in data",
            req.path
        )));
    }

    Ok(())
}

fn convert_bytes_to_string(bytes: &Vec<u8>) -> Result<&str, TransformError> {
    Ok(std::str::from_utf8(bytes.as_slice())
        .map_err(|e| TransformError::Generic(format!("unable to parse data as UTF-8: {}", e))))?
}

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

    const TEST_DATA: &str = r#"{
    "foo": "bar",
    "baz": {
        "qux": "quux"
    },
    "bool": true
}"#;

    #[test]
    fn test_overwrite() {
        let mut req = Request {
            data: TEST_DATA.as_bytes().to_vec(),
            path: "baz.qux".to_string(),
            value: "\"test\"".to_string(),
        };

        let result = overwrite(&req).unwrap();

        assert!(gjson::valid(&TEST_DATA));
        assert!(gjson::valid(&result));
        assert_eq!(result, TEST_DATA.replace("quux", "test"));

        let v = gjson::get(TEST_DATA, "baz.qux");
        assert_eq!(v.str(), "quux");

        let v = gjson::get(result.as_str(), "baz.qux");
        assert_eq!(v.str(), "test");

        req.path = "does-not-exist".to_string();
        assert!(
            overwrite(&req).is_err(),
            "should error when path does not exist"
        );

        // Can overwrite anything
        req.path = "bool".to_string();
        assert!(
            overwrite(&req).is_ok(),
            "should be able to replace any value, regardless of type"
        );
    }

    #[test]
    fn test_obfuscate() {
        let mut req = Request {
            data: TEST_DATA.as_bytes().to_vec(),
            path: "baz.qux".to_string(),
            value: "".to_string(), // needs a default
        };

        let result = obfuscate(&req).unwrap();
        let hashed_value = sha256::digest("quux".as_bytes());

        assert!(gjson::valid(&TEST_DATA));
        assert!(gjson::valid(&result));

        let v = gjson::get(TEST_DATA, "baz.qux");
        assert_eq!(v.str(), "quux");

        let v = gjson::get(result.as_str(), "baz.qux");
        assert_eq!(v.str(), format!("sha256:{}", hashed_value));

        // path does not exist
        req.path = "does-not-exist".to_string();
        assert!(mask(&req).is_err());

        // path not a string
        req.path = "bool".to_string();
        assert!(mask(&req).is_err());
    }

    #[test]
    fn test_mask() {
        let mut req = Request {
            data: TEST_DATA.as_bytes().to_vec(),
            path: "baz.qux".to_string(),
            value: "".to_string(), // needs a default
        };

        let result = mask(&req).unwrap();

        assert!(gjson::valid(TEST_DATA));
        assert!(gjson::valid(&result));

        let v = gjson::get(TEST_DATA, "baz.qux");
        assert_eq!(v.str(), "quux");

        let v = gjson::get(result.as_str(), "baz.qux");
        assert_eq!(v.str(), "q***");

        // path does not exist
        req.path = "does-not-exist".to_string();
        assert!(mask(&req).is_err());

        // path not a string
        req.path = "bool".to_string();
        assert!(mask(&req).is_err());
    }
}