~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/vuln-notif

0
0
main
116 lines · 3.8 KB Raw History
//! Probe an S3-compatible endpoint: create the bucket if needed, then
//! put/get/delete a small object. Example:
//!
//! ```text
//! cargo run --example s3_probe -- \
//!   --endpoint http://127.0.0.1:9000 --bucket vuln-notif \
//!   --access-key rustfs --secret-key rustfs-secret --region us-east-1
//! ```

use anyhow::{Context, Result, anyhow, bail};
use aws_sdk_s3::error::SdkError;
use aws_sdk_s3::primitives::ByteStream;
use vuln_notif::config::S3Config;
use vuln_notif::s3;

const PROBE_KEY: &str = "vuln-notif-probe.txt";
const PROBE_BODY: &[u8] = b"vuln-notif s3 probe\n";
const USAGE: &str = "usage: s3_probe --bucket BUCKET [--endpoint URL] [--access-key KEY] \
[--secret-key SECRET] [--region REGION]";

#[tokio::main]
async fn main() -> Result<()> {
    let mut endpoint = None;
    let mut bucket = None;
    let mut access_key = None;
    let mut secret_key = None;
    let mut region = "us-east-1".to_owned();

    let mut args = std::env::args().skip(1);
    while let Some(arg) = args.next() {
        match arg.as_str() {
            "--endpoint" => endpoint = Some(next_value(&mut args, "--endpoint")?),
            "--bucket" => bucket = Some(next_value(&mut args, "--bucket")?),
            "--access-key" => access_key = Some(next_value(&mut args, "--access-key")?),
            "--secret-key" => secret_key = Some(next_value(&mut args, "--secret-key")?),
            "--region" => region = next_value(&mut args, "--region")?,
            "--help" | "-h" => {
                println!("{USAGE}");
                return Ok(());
            }
            other => bail!("unknown argument {other}; {USAGE}"),
        }
    }

    let cfg = S3Config {
        bucket: bucket.ok_or_else(|| anyhow!("--bucket is required; {USAGE}"))?,
        path: PROBE_KEY.to_owned(),
        endpoint_url: endpoint,
        access_key_id: access_key,
        secret_access_key: secret_key,
        region,
    };
    let client = s3::client(&cfg).await?;

    match client.create_bucket().bucket(&cfg.bucket).send().await {
        Ok(_) => println!("created bucket {}", cfg.bucket),
        Err(err) => {
            let exists = match &err {
                SdkError::ServiceError(ctx) => {
                    ctx.err().is_bucket_already_owned_by_you()
                        || ctx.err().is_bucket_already_exists()
                }
                _ => false,
            };
            if !exists {
                return Err(
                    anyhow::Error::new(err).context(format!("create bucket {}", cfg.bucket))
                );
            }
            println!("bucket {} already exists", cfg.bucket);
        }
    }

    client
        .put_object()
        .bucket(&cfg.bucket)
        .key(&cfg.path)
        .content_type("text/plain")
        .body(ByteStream::from_static(PROBE_BODY))
        .send()
        .await
        .with_context(|| format!("put s3://{}/{}", cfg.bucket, cfg.path))?;
    println!("put {} bytes", PROBE_BODY.len());

    let body = client
        .get_object()
        .bucket(&cfg.bucket)
        .key(&cfg.path)
        .send()
        .await
        .with_context(|| format!("get s3://{}/{}", cfg.bucket, cfg.path))?
        .body
        .collect()
        .await
        .with_context(|| format!("read s3://{}/{} body", cfg.bucket, cfg.path))?
        .into_bytes();
    if body != PROBE_BODY {
        bail!("probe object content mismatch ({} bytes)", body.len());
    }
    println!("got {} bytes", body.len());

    client
        .delete_object()
        .bucket(&cfg.bucket)
        .key(&cfg.path)
        .send()
        .await
        .with_context(|| format!("delete s3://{}/{}", cfg.bucket, cfg.path))?;
    println!("deleted s3://{}/{}", cfg.bucket, cfg.path);
    Ok(())
}

fn next_value(args: &mut impl Iterator<Item = String>, flag: &str) -> Result<String> {
    args.next()
        .ok_or_else(|| anyhow!("{flag} requires a value; {USAGE}"))
}