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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

use std::cmp;
use std::io::Write;
use std::time::{Duration, Instant};

use anyhow::{anyhow, bail, Context};
use async_trait::async_trait;
use aws_sdk_s3::error::{CreateBucketError, CreateBucketErrorKind};
use aws_sdk_s3::model::{
    BucketLocationConstraint, CreateBucketConfiguration, Delete, NotificationConfiguration,
    ObjectIdentifier, QueueConfiguration,
};
use aws_sdk_s3::{ByteStream, SdkError};
use aws_sdk_sqs::model::{DeleteMessageBatchRequestEntry, QueueAttributeName};
use flate2::write::GzEncoder;
use flate2::Compression as Flate2Compression;

use crate::action::file::{build_compression, Compression};
use crate::action::{Action, State};
use crate::parser::BuiltinCommand;

pub struct CreateBucketAction {
    bucket_prefix: String,
}

pub fn build_create_bucket(mut cmd: BuiltinCommand) -> Result<CreateBucketAction, anyhow::Error> {
    let bucket_prefix = format!("testdrive-{}", cmd.args.string("bucket")?);
    cmd.args.done()?;
    Ok(CreateBucketAction { bucket_prefix })
}

#[async_trait]
impl Action for CreateBucketAction {
    async fn undo(&self, _state: &mut State) -> Result<(), anyhow::Error> {
        Ok(())
    }

    async fn redo(&self, state: &mut State) -> Result<(), anyhow::Error> {
        let bucket = format!("{}-{}", self.bucket_prefix, state.seed);
        println!("Creating S3 bucket {}", bucket);

        match state
            .s3_client
            .create_bucket()
            .bucket(&bucket)
            .set_create_bucket_configuration(match state.aws_region() {
                "us-east-1" => None,
                name => Some(
                    CreateBucketConfiguration::builder()
                        .location_constraint(BucketLocationConstraint::from(name))
                        .build(),
                ),
            })
            .send()
            .await
        {
            Ok(_)
            | Err(SdkError::ServiceError {
                err:
                    CreateBucketError {
                        kind: CreateBucketErrorKind::BucketAlreadyOwnedByYou(_),
                        ..
                    },
                ..
            }) => {
                state.s3_buckets_created.insert(bucket);
                Ok(())
            }
            Err(e) => Err(e).context("creating bucket"),
        }
    }
}

pub struct PutObjectAction {
    bucket_prefix: String,
    key: String,
    compression: Compression,
    contents: String,
}

pub fn build_put_object(mut cmd: BuiltinCommand) -> Result<PutObjectAction, anyhow::Error> {
    let bucket_prefix = format!("testdrive-{}", cmd.args.string("bucket")?);
    let key = cmd.args.string("key")?;
    let compression = build_compression(&mut cmd)?;
    let contents = cmd.input.join("\n");
    cmd.args.done()?;
    Ok(PutObjectAction {
        bucket_prefix,
        key,
        compression,
        contents,
    })
}

#[async_trait]
impl Action for PutObjectAction {
    async fn undo(&self, _state: &mut State) -> Result<(), anyhow::Error> {
        Ok(())
    }

    async fn redo(&self, state: &mut State) -> Result<(), anyhow::Error> {
        let bucket = format!("{}-{}", self.bucket_prefix, state.seed);
        println!("Put S3 object {}/{}", bucket, self.key);

        let buffer = self.contents.clone().into_bytes();
        let contents = match self.compression {
            Compression::None => Ok(buffer),
            Compression::Gzip => {
                let mut encoder = GzEncoder::new(Vec::new(), Flate2Compression::default());
                encoder
                    .write_all(buffer.as_ref())
                    .context("writing to gzip encoder")?;
                encoder.finish().context("writing to gzip encoder")
            }
        }?;

        state
            .s3_client
            .put_object()
            .bucket(bucket)
            .body(ByteStream::from(contents))
            .content_type("application/octet-stream")
            .set_content_encoding(match self.compression {
                Compression::None => None,
                Compression::Gzip => Some("gzip".to_string()),
            })
            .key(&self.key)
            .send()
            .await
            .map(|_| ())
            .context("putting to S3")
    }
}

pub struct DeleteObjectAction {
    bucket_prefix: String,
    keys: Vec<String>,
}

pub fn build_delete_object(mut cmd: BuiltinCommand) -> Result<DeleteObjectAction, anyhow::Error> {
    let bucket_prefix = format!("testdrive-{}", cmd.args.string("bucket")?);
    cmd.args.done()?;
    Ok(DeleteObjectAction {
        bucket_prefix,
        keys: cmd.input,
    })
}

#[async_trait]
impl Action for DeleteObjectAction {
    async fn undo(&self, _state: &mut State) -> Result<(), anyhow::Error> {
        Ok(())
    }

    async fn redo(&self, state: &mut State) -> Result<(), anyhow::Error> {
        let bucket = format!("{}-{}", self.bucket_prefix, state.seed);
        println!("Deleting S3 objects {}: {}", bucket, self.keys.join(", "));
        state
            .s3_client
            .delete_objects()
            .bucket(bucket)
            .delete(
                Delete::builder()
                    .set_objects(Some(
                        self.keys
                            .iter()
                            .cloned()
                            .map(|key| ObjectIdentifier::builder().key(key).build())
                            .collect(),
                    ))
                    .build(),
            )
            .send()
            .await
            .context("deleting S3 objects")?;
        Ok(())
    }
}

pub struct AddBucketNotifications {
    bucket_prefix: String,
    queue_prefix: String,
    events: Vec<String>,
    sqs_validation_timeout: Option<Duration>,
}

pub fn build_add_notifications(
    mut cmd: BuiltinCommand,
) -> Result<AddBucketNotifications, anyhow::Error> {
    let bucket_prefix = format!("testdrive-{}", cmd.args.string("bucket")?);
    let queue_prefix = format!("testdrive-{}", cmd.args.string("queue")?);
    let events = cmd
        .args
        .opt_string("events")
        .map(|a| a.split(',').map(|s| s.to_string()).collect())
        .unwrap_or_else(|| vec!["s3:ObjectCreated:*".to_string()]);
    let sqs_validation_timeout = cmd
        .args
        .opt_string("sqs-validation-timeout")
        .map(|t| repr::util::parse_duration(&t).context("parsing duration"))
        .transpose()?;
    cmd.args.done()?;
    Ok(AddBucketNotifications {
        bucket_prefix,
        queue_prefix,
        events,
        sqs_validation_timeout,
    })
}

#[async_trait]
impl Action for AddBucketNotifications {
    async fn undo(&self, _state: &mut State) -> Result<(), anyhow::Error> {
        Ok(())
    }

    async fn redo(&self, state: &mut State) -> Result<(), anyhow::Error> {
        let bucket = format!("{}-{}", self.bucket_prefix, state.seed);
        let queue = format!("{}-{}", self.queue_prefix, state.seed);

        let result = state
            .sqs_client
            .create_queue()
            .queue_name(&queue)
            .send()
            .await;

        // get queue properties used for the rest of the mutations

        let queue_url = match result {
            Ok(r) => r
                .queue_url
                .expect("queue creation should always return the url"),
            Err(SdkError::ServiceError { err, .. }) if err.is_queue_name_exists() => {
                let resp = state
                    .sqs_client
                    .get_queue_url()
                    .queue_name(&queue)
                    .send()
                    .await
                    .context("fetching SQS queue url for existing queue")?;
                resp.queue_url
                    .expect("successfully getting the url gets the url")
            }
            Err(e) => return Err(e.into()),
        };

        let queue_arn: String = state
            .sqs_client
            .get_queue_attributes()
            .queue_url(&queue_url)
            .attribute_names(QueueAttributeName::QueueArn)
            .send()
            .await
            .with_context(|| format!("getting queue {} attributes", queue))?
            .attributes
            .ok_or_else(|| anyhow!("queue attributes missing"))?
            .remove(&QueueAttributeName::QueueArn)
            .ok_or_else(|| anyhow!("queue ARN attribute missing"))?;

        // Configure the queue to allow the S3 bucket to write to this queue
        state
            .sqs_client
            .set_queue_attributes()
            .queue_url(&queue_url)
            .attributes(
                QueueAttributeName::Policy,
                allow_s3_policy(&queue_arn, &bucket, &state.aws_account),
            )
            .send()
            .await
            .context("setting SQS queue policy")?;

        state.sqs_queues_created.insert(queue_url.clone());

        // Configure the s3 bucket to write to the queue, without overwriting any existing configs
        let mut config = state
            .s3_client
            .get_bucket_notification_configuration()
            .bucket(&bucket)
            .send()
            .await
            .context("getting bucket notification_configuration")?;

        {
            let queue_configs = config.queue_configurations.get_or_insert_with(Vec::new);

            queue_configs.push(
                QueueConfiguration::builder()
                    .set_events(Some(self.events.iter().map(|e| e.into()).collect()))
                    .queue_arn(queue_arn)
                    .build(),
            );
        }

        state
            .s3_client
            .put_bucket_notification_configuration()
            .bucket(&bucket)
            .notification_configuration(
                NotificationConfiguration::builder()
                    .set_topic_configurations(config.topic_configurations)
                    .set_queue_configurations(config.queue_configurations)
                    .set_lambda_function_configurations(config.lambda_function_configurations)
                    .build(),
            )
            .send()
            .await
            .context("putting S3 bucket configuration notification")?;

        let sqs_validation_timeout = self
            .sqs_validation_timeout
            .unwrap_or_else(|| cmp::max(state.default_timeout, Duration::from_secs(120)));

        // Wait until we are sure that the configuration has taken effect
        //
        // AWS doesn't specify anywhere how long it should take for
        // newly-configured buckets to start generating sqs notifications, so
        // we continuously put new objects into the bucket and wait for any
        // message to show up.

        let mut attempts = 0;
        let mut success = false;
        print!(
            "Verifying SQS notification configuration for up to {:?} ",
            sqs_validation_timeout
        );
        let start = Instant::now();
        while start.elapsed() < sqs_validation_timeout {
            state
                .s3_client
                .put_object()
                .bucket(&bucket)
                .body(ByteStream::from_static(&[]))
                .key(format!("sqs-test/{}", attempts))
                .send()
                .await
                .context("creating SQS verification object")?;
            attempts += 1;

            let resp = state
                .sqs_client
                .receive_message()
                .queue_url(&queue_url)
                .wait_time_seconds(1)
                .send()
                .await
                .context("receiving verification message from SQS")?;

            if let Some(ms) = resp.messages {
                if !ms.is_empty() {
                    let found_real_message = ms
                        .iter()
                        .any(|m| m.body.as_ref().unwrap().contains("ObjectCreated:Put"));
                    if found_real_message {
                        success = true;
                    }
                    state
                        .sqs_client
                        .delete_message_batch()
                        .queue_url(&queue_url)
                        .set_entries(Some(
                            ms.into_iter()
                                .enumerate()
                                .map(|(i, m)| {
                                    DeleteMessageBatchRequestEntry::builder()
                                        .id(i.to_string())
                                        .receipt_handle(m.receipt_handle.unwrap())
                                        .build()
                                })
                                .collect(),
                        ))
                        .send()
                        .await
                        .context("deleting validation messages from SQS")?;
                }
            }
            if success {
                break;
            }

            print!(".");
        }
        if success {
            println!(
                " Success! (in {} attempts and {:?})",
                attempts + 1,
                start.elapsed()
            );
            Ok(())
        } else {
            println!(
                " Error, never got messages (after {} attempts and {:?})",
                attempts + 1,
                start.elapsed()
            );
            bail!("never received messages on S3 bucket notification queue")
        }
    }
}

fn allow_s3_policy(queue_arn: &str, bucket: &str, self_account: &str) -> String {
    format!(
        r#"{{
 "Version": "2012-10-17",
 "Id": "AllowS3Pushing",
 "Statement": [
  {{
   "Sid": "AllowS3Pushing",
   "Effect": "Allow",
   "Principal": {{
    "AWS":"*"
   }},
   "Action": [
    "SQS:SendMessage"
   ],
   "Resource": "{queue_arn}",
   "Condition": {{
      "ArnLike": {{ "aws:SourceArn": "arn:aws:s3:*:*:{bucket}" }},
      "StringEquals": {{ "aws:SourceAccount": "{self_account}" }}
   }}
  }}
 ]
}}"#,
        queue_arn = queue_arn,
        bucket = bucket,
        self_account = self_account
    )
}