grippo 0.2.3

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/format/cloud/tests.rs
// Purpose:   Conformance tests for the cloud log line parsers
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

use super::*;
use crate::parse::Fields;

const ALB_OLD: &str = concat!(
    "https 2018-07-02T22:23:00.186641Z app/my-lb/50dc6c495c0c9188 ",
    "192.168.131.39:2817 10.0.0.1:80 0.086 0.048 0.037 200 200 0 57 ",
    "\"GET https://www.example.com:443/ HTTP/1.1\" \"curl/7.46.0\" ",
    "ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 ",
    "arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/t/73e2d6bc24d8a067 ",
    "\"Root=1-58337281-1d84f3d73c47ec4e58577259\" \"www.example.com\" \"session-reused\" ",
    "1 2018-07-02T22:22:48.364000Z \"authenticate,forward\" \"-\" \"-\" \"10.0.0.1:80\" ",
    "\"200\" \"-\" \"-\" TID_1234abcd5678ef90 \"m.example.com\" \"-\" \"TransformSuccess\"",
);

const NLB: &str = concat!(
    "tls 3.0 2026-01-15T08:51:42 net/my-nlb/c6e77e28c25b2234 g3d4b5e8bb8464cd ",
    "192.0.2.1:51341 192.0.2.254:443 5 2 98 246 - ",
    "arn:aws:acm:us-east-2:123456789012:certificate/2a108f19 - ",
    "ECDHE-RSA-AES128-SHA tlsv12 - my-nlb.elb.us-east-2.amazonaws.com ",
    "h2 h2 \"h2\",\"http/1.1\" 2026-01-15T08:51:20 Success ",
    "\"CN=client1.example.com,O=Example Corp\" ",
    "NotBefore=2026-01-01T00:00:00Z;NotAfter=2027-01-01T00:00:00Z 5afbadd079a26402",
);

const ELB_TCP: &str = concat!(
    "2015-05-13T23:39:43.945958Z my-lb 192.168.131.39:2817 10.0.0.1:80 ",
    "0.001069 0.000028 0.000041 - - 82 305 \"- - - \" \"-\" - -",
);

const S3: &str = concat!(
    "79a59df900b949e5 bucket1 [06/Feb/2019:00:01:57 +0000] 192.0.2.3 79a59df900b949e5 ",
    "DD6CC733AEXAMPLE REST.PUT.OBJECT s3-dg.pdf \"PUT /bucket1/s3-dg.pdf HTTP/1.1\" ",
    "200 - - 4406583 41754 28 \"-\" \"S3Console/0.4 (say \"hi\")\" - ",
    "10S62Zv81kBW7BB6SX4XJ48o6kpcl6LPwEoizZQQxJd5qDSCTLX0TgS37kYUBKQW3+bPdrg1234= ",
    "SigV4 ECDHE-RSA-AES128-SHA AuthHeader bucket1.s3.us-west-1.amazonaws.com TLSV1.2 ",
    "- Yes us-east-1 a-field-not-yet-documented",
);

/// The fields `p` writes for `line`, by name.
fn read(p: &CloudLog, line: &str) -> Result<Vec<(String, String)>, ParseError> {
    let mut out = Fields::new();
    let got = p.parse(line.as_bytes(), &mut out);
    if got.is_err() {
        assert!(out.is_empty(), "{line}");
    }
    got?;
    Ok(out
        .as_slice()
        .iter()
        .map(|(k, v)| (k.clone(), String::from_utf8(v.bytes.to_vec()).unwrap()))
        .collect())
}

#[test]
fn cloud_log_lines() {
    // A parser, a line, then the field count and some fields it writes, or
    // the offset it fails at.
    type Row<'a> = (
        CloudLog,
        &'a str,
        Result<(usize, &'a [(&'a str, &'a str)]), usize>,
    );
    let rows: Vec<Row<'_>> = vec![
        (
            CloudLog::aws_alb(),
            ALB_OLD,
            Ok((
                33,
                &[
                    ("type", "https"),
                    ("client", "192.168.131.39:2817"),
                    ("request", "GET https://www.example.com:443/ HTTP/1.1"),
                    ("user_agent", "curl/7.46.0"),
                    ("actions_executed", "authenticate,forward"),
                    ("conn_trace_id", "TID_1234abcd5678ef90"),
                    ("request_transform_status", "TransformSuccess"),
                ],
            )),
        ),
        (
            CloudLog::aws_alb(),
            &ALB_OLD[..ALB_OLD.find(" arn:").unwrap()],
            Ok((16, &[("ssl_protocol", "TLSv1.2")])),
        ),
        (
            CloudLog::aws_alb(),
            &ALB_OLD[..ALB_OLD.find(" ECDHE").unwrap()],
            Err(ALB_OLD.find(" ECDHE").unwrap()),
        ),
        (
            CloudLog::aws_nlb(),
            NLB,
            Ok((
                26,
                &[
                    ("version", "3.0"),
                    ("incoming_tls_alert", "-"),
                    ("alpn_client_preference_list", "h2\",\"http/1.1"),
                    (
                        "leaf_client_cert_subject",
                        "CN=client1.example.com,O=Example Corp",
                    ),
                    ("leaf_client_cert_serial_number", "5afbadd079a26402"),
                ],
            )),
        ),
        (
            CloudLog::aws_elb(),
            ELB_TCP,
            Ok((
                15,
                &[
                    ("request", "- - - "),
                    ("user_agent", "-"),
                    ("ssl_protocol", "-"),
                ],
            )),
        ),
        (CloudLog::aws_elb(), "2015-05-13T23:39:43Z my-lb", Err(26)),
        (
            CloudLog::aws_s3(),
            S3,
            Ok((
                27,
                &[
                    ("time", "06/Feb/2019:00:01:57 +0000"),
                    ("request_uri", "PUT /bucket1/s3-dg.pdf HTTP/1.1"),
                    ("user_agent", "S3Console/0.4 (say \"hi\")"),
                    ("source_region", "us-east-1"),
                ],
            )),
        ),
        (
            CloudLog::aws_s3(),
            "owner bucket [06/Feb/2019:00:01:57 +0000",
            Err(13),
        ),
        (
            CloudLog::aws_s3(),
            "owner bucket [t] \"GET / HTTP/1.1",
            Err(17),
        ),
        (
            CloudLog::aws_vpc_flow(),
            "2 123456789010 eni-1235b8ca123456789 172.31.16.139 172.31.16.21 20641 22 6 20 4249 1418530010 1418530070 ACCEPT OK\r",
            Ok((
                14,
                &[
                    ("account_id", "123456789010"),
                    ("dstport", "22"),
                    ("log_status", "OK"),
                ],
            )),
        ),
        (
            CloudLog::aws_vpc_flow(),
            "2 123456789010 eni-1235b8ca123456789 - - - - - - - 1431280876 1431280934 - NODATA",
            Ok((14, &[("srcaddr", "-"), ("log_status", "NODATA")])),
        ),
        (CloudLog::aws_vpc_flow(), "2 123456789010 eni-1", Err(20)),
        (CloudLog::aws_vpc_flow(), "", Err(0)),
    ];
    for (p, line, want) in rows {
        match (read(&p, line), want) {
            (Ok(got), Ok((count, some))) => {
                assert_eq!(got.len(), count, "{} {line}", p.name());
                for (name, value) in some {
                    let found = got.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str());
                    assert_eq!(found, Some(*value), "{} {name}", p.name());
                }
                let names: Vec<&str> = p.fields().take(count).collect();
                let written: Vec<&str> = got.iter().map(|(k, _)| k.as_str()).collect();
                assert_eq!(written, names, "{}", p.name());
            }
            (Err(ParseError::Malformed { offset, .. }), Err(at)) => {
                assert_eq!(offset, at, "{} {line}", p.name());
            }
            (got, _) => panic!("{} {line}: {got:?}", p.name()),
        }
    }
}

#[test]
fn a_custom_flow_log_format_names_its_fields() {
    let p = CloudLog::aws_vpc_flow_format("${version} ${vpc-id} ${srcaddr} ${tcp-flags}").unwrap();
    assert_eq!(p.name(), "aws_vpc_flow");
    let got = read(&p, "3 vpc-abcdefab012345678 10.0.0.1 19").unwrap();
    assert_eq!(
        got,
        [
            ("version", "3"),
            ("vpc_id", "vpc-abcdefab012345678"),
            ("srcaddr", "10.0.0.1"),
            ("tcp_flags", "19")
        ]
        .map(|(k, v)| (k.to_owned(), v.to_owned()))
    );
    assert!(read(&p, "3 vpc-1 10.0.0.1").is_err());
    for (format, want) in [
        ("", CloudLogError::Empty),
        ("   ", CloudLogError::Empty),
        (
            "${version} srcaddr",
            CloudLogError::Word("srcaddr".to_owned()),
        ),
        ("${}", CloudLogError::Word("${}".to_owned())),
        ("${a}${b}", CloudLogError::Word("${a}${b}".to_owned())),
    ] {
        assert_eq!(
            CloudLog::aws_vpc_flow_format(format).unwrap_err(),
            want,
            "{format:?}"
        );
    }
}

#[test]
fn every_format_has_a_valid_name_and_distinct_fields() {
    for p in [
        CloudLog::aws_alb(),
        CloudLog::aws_nlb(),
        CloudLog::aws_elb(),
        CloudLog::aws_s3(),
        CloudLog::aws_vpc_flow(),
    ] {
        assert!(crate::parse::valid_parser_name(p.name()), "{}", p.name());
        let mut names: Vec<&str> = p.fields().collect();
        let all = names.len();
        names.sort_unstable();
        names.dedup();
        assert_eq!(names.len(), all, "{}", p.name());
    }
}