grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
// Project:   grippo
// File:      src/format/cloud.rs
// Purpose:   Cloud load balancer, object store and flow log lines by position
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A cloud provider's space-separated log line, its fields named by position:
//! AWS's load balancer access logs, S3 server access logs and VPC flow logs.
//!
//! A value runs to the next space, or is quoted (`"GET / HTTP/1.1"`) or
//! bracketed (`[06/Feb/2019:00:00:38 +0000]`) and written without them. A
//! quoted value ends at a `"` followed by a space or the end of the line, so
//! a quote inside it reads as text unless a space follows it. `-` is written
//! as it is.
//!
//! The provider adds fields at the end of a line over time, so a line may
//! hold fewer fields than the current layout names, down to the format's
//! oldest layout, and fields past the last name are dropped.

use std::ops::Range;

use memchr::memchr;
use thiserror::Error;

use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;

/// Application Load Balancer, in the order the access log writes them.
const AWS_ALB: &[&str] = &[
    "type",
    "time",
    "elb",
    "client",
    "target",
    "request_processing_time",
    "target_processing_time",
    "response_processing_time",
    "elb_status_code",
    "target_status_code",
    "received_bytes",
    "sent_bytes",
    "request",
    "user_agent",
    "ssl_cipher",
    "ssl_protocol",
    "target_group_arn",
    "trace_id",
    "domain_name",
    "chosen_cert_arn",
    "matched_rule_priority",
    "request_creation_time",
    "actions_executed",
    "redirect_url",
    "error_reason",
    "target_port_list",
    "target_status_code_list",
    "classification",
    "classification_reason",
    "conn_trace_id",
    "transformed_host",
    "transformed_uri",
    "request_transform_status",
    "ip_address",
    "target_error_code",
    "elb_error_code",
];

/// Network Load Balancer TLS listener access log.
const AWS_NLB: &[&str] = &[
    "type",
    "version",
    "time",
    "elb",
    "listener",
    "client",
    "destination",
    "connection_time",
    "tls_handshake_time",
    "received_bytes",
    "sent_bytes",
    "incoming_tls_alert",
    "chosen_cert_arn",
    "chosen_cert_serial",
    "tls_cipher",
    "tls_protocol_version",
    "tls_keyexchange",
    "domain_name",
    "alpn_fe_protocol",
    "alpn_be_protocol",
    "alpn_client_preference_list",
    "tls_connection_creation_time",
    "tls_verify_status",
    "leaf_client_cert_subject",
    "leaf_client_cert_validity",
    "leaf_client_cert_serial_number",
];

/// Classic Load Balancer access log.
const AWS_ELB: &[&str] = &[
    "time",
    "elb",
    "client",
    "backend",
    "request_processing_time",
    "backend_processing_time",
    "response_processing_time",
    "elb_status_code",
    "backend_status_code",
    "received_bytes",
    "sent_bytes",
    "request",
    "user_agent",
    "ssl_cipher",
    "ssl_protocol",
];

/// S3 server access log.
const AWS_S3: &[&str] = &[
    "bucket_owner",
    "bucket",
    "time",
    "remote_ip",
    "requester",
    "request_id",
    "operation",
    "key",
    "request_uri",
    "http_status",
    "error_code",
    "bytes_sent",
    "object_size",
    "total_time",
    "turn_around_time",
    "referer",
    "user_agent",
    "version_id",
    "host_id",
    "signature_version",
    "cipher_suite",
    "authentication_type",
    "host_header",
    "tls_version",
    "access_point_arn",
    "acl_required",
    "source_region",
];

/// VPC flow log's default format, the version 2 fields.
const AWS_VPC_FLOW: &[&str] = &[
    "version",
    "account_id",
    "interface_id",
    "srcaddr",
    "dstaddr",
    "srcport",
    "dstport",
    "protocol",
    "packets",
    "bytes",
    "start",
    "end",
    "action",
    "log_status",
];

/// Why a VPC flow log format string can't build a parser.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum CloudLogError {
    /// The format names no field.
    #[error("the flow log format names no field")]
    Empty,
    /// A word of the format isn't `${field}`.
    #[error("{0:?} in a flow log format is not ${{field}}")]
    Word(String),
}

/// A cloud log line parser, registered under its format's name: `aws_alb`,
/// `aws_nlb`, `aws_elb`, `aws_s3` or `aws_vpc_flow`.
#[derive(Debug, Clone)]
pub struct CloudLog {
    name: &'static str,
    fields: Box<[Box<str>]>,
    /// The fewest values a line holds: the format's oldest layout.
    least: usize,
    signature: Signature,
}

impl CloudLog {
    fn of(name: &'static str, fields: &[&str], least: usize) -> Self {
        let signature = Signature::builder()
            .build()
            .unwrap_or_else(|_| unreachable!("invariant: an empty signature always builds"));
        Self {
            name,
            fields: fields.iter().map(|&f| Box::from(f)).collect(),
            least,
            signature,
        }
    }

    /// Application Load Balancer access log lines, `aws_alb`. A line holds
    /// 16 fields at least, through `ssl_protocol`.
    #[must_use]
    pub fn aws_alb() -> Self {
        Self::of("aws_alb", AWS_ALB, 16)
    }

    /// Network Load Balancer access log lines, `aws_nlb`. A line holds 16
    /// fields at least, through `tls_protocol_version`.
    #[must_use]
    pub fn aws_nlb() -> Self {
        Self::of("aws_nlb", AWS_NLB, 16)
    }

    /// Classic Load Balancer access log lines, `aws_elb`, all 15 fields.
    #[must_use]
    pub fn aws_elb() -> Self {
        Self::of("aws_elb", AWS_ELB, AWS_ELB.len())
    }

    /// S3 server access log lines, `aws_s3`. A line holds 18 fields at
    /// least, through `version_id`.
    #[must_use]
    pub fn aws_s3() -> Self {
        Self::of("aws_s3", AWS_S3, 18)
    }

    /// VPC flow log lines in the default format, `aws_vpc_flow`.
    #[must_use]
    pub fn aws_vpc_flow() -> Self {
        Self::of("aws_vpc_flow", AWS_VPC_FLOW, AWS_VPC_FLOW.len())
    }

    /// VPC flow log lines in a custom format, `aws_vpc_flow`, from the
    /// flow log's format string: `${version} ${vpc-id} ${srcaddr}`. A field
    /// name's `-` is written as `_`, and a line holds every field.
    ///
    /// # Errors
    ///
    /// [`CloudLogError::Empty`] for a format with no field, and
    /// [`CloudLogError::Word`] for a word that isn't `${field}`.
    pub fn aws_vpc_flow_format(format: &str) -> Result<Self, CloudLogError> {
        let fields: Vec<String> = format
            .split_ascii_whitespace()
            .map(|word| {
                word.strip_prefix("${")
                    .and_then(|w| w.strip_suffix('}'))
                    .filter(|w| !w.is_empty() && !w.contains(['$', '{', '}']))
                    .map(|w| w.replace('-', "_"))
                    .ok_or_else(|| CloudLogError::Word(word.to_owned()))
            })
            .collect::<Result<_, _>>()?;
        if fields.is_empty() {
            return Err(CloudLogError::Empty);
        }
        let names: Vec<&str> = fields.iter().map(String::as_str).collect();
        Ok(Self::of("aws_vpc_flow", &names, names.len()))
    }

    /// The field names, in the order a line holds them.
    pub fn fields(&self) -> impl Iterator<Item = &str> {
        self.fields.iter().map(|f| &**f)
    }
}

/// The value starting at `i` and where the next one may start, or `None`
/// for a quote or bracket never closed.
fn value(line: &[u8], i: usize) -> Option<(Range<usize>, usize)> {
    let close = match line[i] {
        b'"' => b'"',
        b'[' => b']',
        _ => {
            let end = memchr(b' ', &line[i..]).map_or(line.len(), |at| i + at);
            return Some((i..end, end));
        }
    };
    let mut at = i + 1;
    loop {
        let end = at + memchr(close, &line[at..])?;
        if matches!(line.get(end + 1), None | Some(b' ')) {
            return Some((i + 1..end, end + 1));
        }
        at = end + 1;
    }
}

impl Parser for CloudLog {
    fn hands_on_body(&self) -> bool {
        false
    }

    fn name(&self) -> &str {
        self.name
    }

    fn tier(&self) -> MatcherTier {
        MatcherTier::Field
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    /// A line with fewer values than the format's oldest layout, or a quote
    /// or bracket never closed, is [`ParseError::Malformed`] and writes
    /// nothing.
    fn parse<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Parsed, ParseError> {
        let line = input.strip_suffix(b"\r").unwrap_or(input);
        let mark = out.mark();
        let mut i = 0;
        let mut written = 0;
        for name in &*self.fields {
            while line.get(i) == Some(&b' ') {
                i += 1;
            }
            if i >= line.len() {
                break;
            }
            let Some((span, next)) = value(line, i) else {
                out.rollback(mark);
                return Err(ParseError::Malformed {
                    offset: i,
                    reason: "a quote or bracket with no close",
                });
            };
            out.field(name, FieldValue::borrowed(&line[span], Hint::Text));
            written += 1;
            i = next;
        }
        if written < self.least {
            out.rollback(mark);
            return Err(ParseError::Malformed {
                offset: line.len(),
                reason: "fewer fields than the format holds",
            });
        }
        Ok(Parsed::Done)
    }
}

#[cfg(test)]
mod tests;