Skip to Content
Cloud Engineering Academy
1. Cloud Computing & AWS Fundamentals

Lab: hello, AWS — the Module 1 exercise

Call STS and S3 from a C# console app with SSO credentials, create a locked-down bucket holding a fictional bank statement, deploy a private status page through CloudFront with Terraform, prove it is not public, then tear everything down.

beginner⏱ 2 h 🟡 Low costCLF-C02SAA-C03DVA-C03

Assumes: .NET 10 LTS · AWS SDK for .NET v4 (AWSSDK.S3 4.1.1) · Terraform 1.14 · AWS provider ~> 6.0 · xUnit v3 4.0.3 · Region us-east-1. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lab you can:

  • Run a .NET 10 console app that uses an IAM Identity Center profile, and show which profile, Region and credential type it used (Lab 1.3).
  • Break the credential chain on purpose and read the resulting errors.
  • Create an S3 bucket from C# with Block Public Access, default encryption, a TLS-only bucket policy and the four course tags, then upload, list and delete a fictional statement.
  • Deploy a static status page from a private S3 bucket through CloudFront with Origin Access Control using Terraform, and prove the bucket cannot be read directly.
  • Tear everything down and prove that nothing tagged Project=cea-lab remains.

Prerequisites

Why this matters in banking

Harbourline Bank stores monthly customer statements as files. The first question any reviewer asks about a bucket like that is not "does it work?" but "can anyone outside the bank read it, is it encrypted, can we prove who created it, and will it be deleted when the project ends?". This lab answers each question in code: Block Public Access, default encryption, a policy that refuses plain HTTP, mandatory tags, and a cleanup command that only touches resources it can prove it owns.

The second half deploys something visible: a status page served through CloudFront. The common mistake in real incidents is a bucket made public "just so the website works". Here the bucket stays private and only one CloudFront distribution may read it, which is the pattern you will reuse for every static front end.

The idea in plain language

The lab has three parts, all driven by one console app (Harbourline.HelloAws) and one small Terraform stack:

  1. whoami — call STS GetCallerIdentity and print the profile, Region and credential type the SDK chose.
  2. statement-demo — create a uniquely named bucket, lock it down, upload a fictional October 2026 statement as CSV, list it, show its encryption, then delete it all.
  3. Terraform + status-check — deploy a private bucket and a CloudFront distribution, then use the app to check that CloudFront returns 200 and direct S3 returns 403.

cleanup is the safety net: it finds any leftover bucket by name prefix and tags and deletes it.

Analogy: The statement bucket is a safe-deposit box. Block Public Access welds the outer door shut to the public, encryption locks the contents, the TLS policy says "only through the armoured corridor", and the tags are the label telling the bank whose box it is and when to empty it. CloudFront is the bank's front counter: customers see the status board, but nobody walks into the vault.

What problem the AWS service solves

ServiceRole in this labLimitations to know
AWS STSGetCallerIdentity: "who am I?"Needs no permission, so it proves sign-in, not authorisation
Amazon S3Stores the statement CSV and the status pageBucket names are global; general purpose buckets default to a quota of 10,000 per account ⚠ VERIFY
S3 Block Public AccessOverrides any ACL or policy that would make data publicOn by default for new buckets since April 2023; the lab still sets it explicitly
Amazon CloudFrontServes the page over HTTPS from edge locationsA new distribution takes several minutes to deploy and to delete
Origin Access Control (OAC)Lets CloudFront sign requests to a private bucketReplaces the legacy Origin Access Identity (OAI) for new set-ups

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Storage account + blob containerS3 bucketNo storage-account layer; the bucket name is global across all AWS customers
"Allow Blob anonymous access" = disabledS3 Block Public AccessFour separate switches, available at account and bucket level
Storage Service Encryption (Microsoft-managed keys)SSE-S3 default encryptionAlways on for new objects; SSE-KMS gives you a customer managed key (Module 5)
"Secure transfer required"Bucket policy denying aws:SecureTransport = falseA policy statement, not a checkbox
Azure Front Door / CDN with private origin (Private Link)CloudFront + Origin Access ControlAccess is granted by a bucket policy naming the distribution ARN
Azure resource tags + Azure Policy "require tag"Tags + tag policies / SCPsAWS tag keys are case-sensitive
az group deleteNo single equivalentThere is no resource group to delete: tags plus IaC destroy are how you clean up

Architecture

Security-boundary view. Credentials never leave your PC's SSO cache. Both buckets refuse public access and plain HTTP. The status bucket's policy allows s3:GetObject only for the CloudFront service principal and only when AWS:SourceArn equals your distribution's ARN, so another customer's distribution cannot read it either.

Step-by-step implementation

1. Sign in and run the tests

aws sso login --sso-session cea
cd labs/m01-hello-aws
dotnet test --solution HelloAws.slnx

Expect 72 tests: 71 passed, 1 skipped (the optional real-AWS test, which runs only with RUN_AWS_TESTS=1). The tests use fake S3 and STS clients, so they also run in CI with no AWS account. No .NET SDK? See the README for the Docker command.

2. Lab 1.3: who am I?

dotnet run --project src/Harbourline.HelloAws -- whoami
Profile     : learn-sandbox (lab default)
Region      : us-east-1 (profile in %USERPROFILE%\.aws\config)
Credentials : SSOAWSCredentials
Account     : 111122223333
Caller      : IAM Identity Center permission set 'SandboxAdmin' (session alex.learner)

The app refuses to go further if the caller is the root user.

3. Break the credential chain on purpose

Run each of these, read the error and the hint, then undo it:

# a) Expired / missing sign-in
aws sso logout
dotnet run --project src/Harbourline.HelloAws -- whoami
aws sso login --sso-session cea

# b) Wrong profile name
dotnet run --project src/Harbourline.HelloAws -- whoami --profile learn-sandbx

# c) Stray environment keys beat profiles in the default chain (AWS's documented example values)
$env:AWS_ACCESS_KEY_ID = "AKIAIOSFODNN7EXAMPLE"
$env:AWS_SECRET_ACCESS_KEY = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
$env:AWS_PROFILE = "learn-sandbox"
dotnet run --project src/Harbourline.HelloAws -- whoami --default-chain
Remove-Item Env:AWS_ACCESS_KEY_ID, Env:AWS_SECRET_ACCESS_KEY, Env:AWS_PROFILE

In (a) the SDK never reaches AWS (AmazonClientException). In (b) the profile lookup fails before any call (exit code 2). In (c) AWS rejects the example key with InvalidClientTokenId, even though AWS_PROFILE is set, because environment keys come first in the chain.

4. Create, use and delete a locked-down statement bucket

dotnet run --project src/Harbourline.HelloAws -- statement-demo --owner alex
Creating a private statement bucket in account 111122223333:
  created bucket        hl-m01-statements-111122223333-3f9a1c
  block public access   all four settings ON
  default encryption    SSE-S3 (AES256)
  bucket policy         deny when aws:SecureTransport is false
  tags                  Project=cea-lab, Lab=m01-hello-aws, Environment=learn, Owner=alex
  uploaded              s3://hl-m01-statements-111122223333-3f9a1c/statements/ACC-0000012345/2026-10.csv (1767 bytes)
  listed                statements/ACC-0000012345/2026-10.csv 1767 bytes
  encryption at rest    AES256
  closing balance       GBP 2610.41 (opening 1250.00, 8 lines)

Tearing down:
  deleted objects       1
  deleted bucket        hl-m01-statements-111122223333-3f9a1c

Sizes and the random suffix will differ. Add --keep to leave the bucket for inspection (for example for the Shared Responsibility exercise), then delete it the same day with cleanup --yes.

5. Deploy the status page with Terraform

cd infra/terraform/status
terraform init
terraform apply -var "owner=alex"

Review the plan (about ten resources), type yes, and wait. CloudFront typically takes several minutes. Note the outputs status_page_url and status_bucket_name.

6. Prove it is private

cd ../../..
dotnet run --project src/Harbourline.HelloAws -- status-check --url https://d111111abcdef8.cloudfront.net/ --bucket hl-m01-status-111122223333
[OK] via CloudFront  https://d111111abcdef8.cloudfront.net/ -> 200
[OK] direct from S3  https://hl-m01-status-111122223333.s3.us-east-1.amazonaws.com/index.html -> 403 (expected 403)

Use your own URL and bucket name from the Terraform outputs. A 403 from the direct URL is the good result.

7. Tear down and verify

cd infra/terraform/status
terraform destroy -var "owner=alex"
cd ../../..
dotnet run --project src/Harbourline.HelloAws -- cleanup --yes
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab Key=Lab,Values=m01-hello-aws --profile learn-sandbox

The last command should return an empty ResourceTagMappingList (the tagging index can lag a few minutes behind deletions). Check Billing and Cost Management → Bills the next day.

AWS Console instructions

Use the console to inspect, not to create:

  • S3 → Buckets → your statement bucket (with --keep) → Permissions: Block public access shows On for all four settings; Bucket policy shows the DenyInsecureTransport statement.
  • Properties → Default encryption: Server-side encryption with Amazon S3 managed keys (SSE-S3). Properties → Tags: the four course tags.
  • CloudFront → Distributions → hl-m01-status → Origins: the origin uses the hl-m01-status-oac origin access control.
  • S3 → hl-m01-status-ACCOUNT → Permissions → Bucket policy: the AWS:SourceArn condition names your distribution.

AWS CLI

Check what the app and Terraform configured, from outside the code:

$b = "hl-m01-statements-111122223333-3f9a1c"   # your bucket, created with --keep

# All four Block Public Access switches should be true
aws s3api get-public-access-block --bucket $b --profile learn-sandbox

# Default encryption should be AES256
aws s3api get-bucket-encryption --bucket $b --profile learn-sandbox

# The TLS-only policy
aws s3api get-bucket-policy --bucket $b --query Policy --output text --profile learn-sandbox

# Tags
aws s3api get-bucket-tagging --bucket $b --profile learn-sandbox

# Is S3 itself saying the bucket is not public?
aws s3api get-bucket-policy-status --bucket $b --profile learn-sandbox

Infrastructure as Code

The status page stack lives in labs/m01-hello-aws/infra/terraform/status/. The heart of it is the bucket policy that trusts exactly one distribution:

main.tf (excerpt)
data "aws_iam_policy_document" "status" {
  statement {
    sid       = "AllowCloudFrontServicePrincipalReadOnly"
    effect    = "Allow"
    actions   = ["s3:GetObject"]
    resources = ["${aws_s3_bucket.status.arn}/*"]

    principals {
      type        = "Service"
      identifiers = ["cloudfront.amazonaws.com"]
    }

    condition {
      test     = "StringEquals"
      variable = "AWS:SourceArn"
      values   = [aws_cloudfront_distribution.status.arn]
    }
  }
}

Other resources in the stack: the bucket with force_destroy (a learning shortcut), ownership controls (ACLs disabled), Block Public Access, SSE-S3, an index.html object, the origin access control (signing_behavior = "always", SigV4) and the distribution (PriceClass_100, redirect-to-https, the managed CachingOptimized cache policy). The provider's default_tags block applies the four course tags to every resource. The stack uses local state; from Module 2 labs use an S3 backend with native locking.

Complete code

The full app is in labs/m01-hello-aws/src/Harbourline.HelloAws/. The core of the S3 part, with comments:

StatementBucketWorkflow.cs (excerpt)
public async Task CreateSecureBucketAsync(string bucketName, IReadOnlyDictionary<string, string> tags, CancellationToken ct = default)
{
    await s3.PutBucketAsync(new PutBucketRequest { BucketName = bucketName, UseClientRegion = true }, ct);

    try
    {
        await s3.PutPublicAccessBlockAsync(new PutPublicAccessBlockRequest
        {
            BucketName = bucketName,
            PublicAccessBlockConfiguration = new PublicAccessBlockConfiguration
            {
                BlockPublicAcls = true,
                IgnorePublicAcls = true,
                BlockPublicPolicy = true,
                RestrictPublicBuckets = true,
            },
        }, ct);

        await s3.PutBucketEncryptionAsync(new PutBucketEncryptionRequest
        {
            BucketName = bucketName,
            ServerSideEncryptionConfiguration = new ServerSideEncryptionConfiguration
            {
                ServerSideEncryptionRules =
                [
                    new ServerSideEncryptionRule
                    {
                        ServerSideEncryptionByDefault = new ServerSideEncryptionByDefault
                        {
                            ServerSideEncryptionAlgorithm = ServerSideEncryptionMethod.AES256,
                        },
                    },
                ],
            },
        }, ct);

        await s3.PutBucketPolicyAsync(new PutBucketPolicyRequest
        {
            BucketName = bucketName,
            Policy = BucketPolicies.DenyInsecureTransport(bucketName),
        }, ct);

        await s3.PutBucketTaggingAsync(new PutBucketTaggingRequest
        {
            BucketName = bucketName,
            TagSet = tags.Select(t => new Tag { Key = t.Key, Value = t.Value }).ToList(),
        }, ct);
    }
    catch
    {
        // Never keep a half-configured bucket.
        await s3.DeleteBucketAsync(new DeleteBucketRequest { BucketName = bucketName }, ct);
        throw;
    }
}

And a unit test that proves the security settings without an AWS account:

S3WorkflowTests.cs (excerpt)
[Fact]
public async Task Half_configured_bucket_is_deleted_when_a_lock_down_step_fails()
{
    var s3 = HappyS3();
    s3.PutBucketEncryptionAsync(Arg.Any<PutBucketEncryptionRequest>(), Arg.Any<CancellationToken>())
        .ThrowsAsync(new AmazonS3Exception("denied") { ErrorCode = "AccessDenied" });
    var workflow = new StatementBucketWorkflow(s3, TextWriter.Null);

    await Assert.ThrowsAsync<AmazonS3Exception>(() => workflow.CreateSecureBucketAsync(Bucket, LabTags.For("alex"), Ct));

    await s3.Received(1).DeleteBucketAsync(Arg.Is<DeleteBucketRequest>(r => r.BucketName == Bucket), Arg.Any<CancellationToken>());
}

Project map:

FileWhat it does
Program.csThe only code that builds real AWS clients; picks profile, Region and command
CommandLine.cs, SettingsResolver.csArgument parsing and CLI-style precedence for profile, Region, Owner
CallerIdentity.csParses STS ARNs into root / IAM user / Identity Center role / assumed role
BucketNaming.cs, LabTags.cs, BucketPolicies.csGlobal-unique names, the four tags, the TLS-only policy
StatementGenerator.csEight fictional transactions in the canonical schema, as CSV
StatementBucketWorkflow.cs, StatementDemo.csThe S3 steps and the demo with guaranteed teardown
LabCleanup.csDeletes only buckets with the right prefix and tags; dry run by default
StatusPageCheck.csHTTPS checks against CloudFront and direct S3

Code explained line by line

  1. UseClientRegion = true — creates the bucket in the client's Region (us-east-1). Setting it explicitly documents the intent: the bucket lives where the client points, and data residency follows that choice.
  2. PutPublicAccessBlockAsync with four true values — blocks new public ACLs, ignores existing ones, blocks public policies and restricts access to buckets that already have public policies.
  3. ServerSideEncryptionMethod.AES256 — SSE-S3: S3 manages the keys, no extra cost. Module 5 replaces it with SSE-KMS and a customer managed key.
  4. BucketPolicies.DenyInsecureTransport — a single Deny statement for s3:* when aws:SecureTransport is false. It grants nothing, so Block Public Access does not object.
  5. PutBucketTaggingAsync — replaces the whole tag set, so all four tags go in one call.
  6. catch { DeleteBucketAsync; throw; } — if any lock-down step fails, the bucket is removed before the error propagates.
  7. In StatementDemo, the teardown sits in a finally block, so an exception during upload still deletes the bucket.
  8. ListAsync loops on NextContinuationToken while IsTruncated == true: S3 returns at most 1,000 keys per page.
  9. LabCleanup lists buckets, keeps those starting with hl-m01-statements-, reads their tags and deletes only when Project=cea-lab and Lab=m01-hello-aws. Two independent checks protect everything else in the account.
  10. StatusPageCheck treats 403 from the direct S3 URL as success: the object exists, and the public cannot read it.

Security considerations

  • Credentials: SSO profile only. The app sets SupportsGettingNewToken = false, so it never opens a browser, and warns if access-key environment variables are set.
  • Data: fictional only. IBANs are published registry examples; names are invented; CARD 4242 is a reference, not a card number.
  • Object metadata and keys must never contain personal data: they appear in logs and listings. The lab uses account IDs in keys only because they are fictional.
  • The app refuses to run as the root user.

⚠ Learning shortcut — not for production

force_destroy = true on the status bucket, local Terraform state, SSE-S3 instead of SSE-KMS, no S3 server access logging or CloudFront access logs, no versioning, and the broad SandboxAdmin permission set. A production statement store would use SSE-KMS with a customer managed key, versioning and Object Lock where retention rules require it, access logging to a separate log-archive account, an S3 backend for Terraform state, and a role allowed only the exact S3 actions needed. Retention periods for statements are a legal and compliance decision, not a developer default.

Banking use case

Harbourline Bank's statement service writes one CSV per account per month to statements/ACC-.../yyyy-MM.csv. The production version of this lab's bucket adds SSE-KMS, versioning, a lifecycle rule to move statements older than a year to a cheaper storage class, and replication to a second Region for resilience. Customers never read the bucket directly: the web banking API generates short-lived presigned URLs after checking the customer owns the account. The status page pattern (private bucket, CloudFront, OAC) is exactly how the bank hosts its public help pages and single-page web apps.

Common mistakes

  • Making the status bucket public "to get it working". → the CloudFront 403 looks like a permissions problem on the bucket → it is usually a missing or wrong OAC bucket policy, or a distribution still deploying. Never disable Block Public Access to fix it.
  • Running statement-demo with --keep and forgetting. → a bucket costs almost nothing, but forgotten resources are how lab accounts get untidy → run cleanup at the end of every session.
  • Adding tags one call at a time. → PutBucketTagging replaces the set → only the last tag survives.
  • Expecting terraform destroy to finish instantly. → CloudFront must disable the distribution before deleting it → wait; it can take several minutes.
  • Using dots in bucket names. → legal in S3, but they break HTTPS virtual-hosted-style URLs because the wildcard certificate covers one label only.

Troubleshooting

SymptomLikely causeFix
The AWS SDK could not make the request + SSO hintSign-in expiredaws sso login --sso-session cea
No profile named ... was found (exit 2)Typo or missing profileaws configure list-profiles
AccessDenied on PutBucketPermission set or SCP blocks S3 writes, or the Region is denied by an SCPCheck the Region (us-east-1) and the permission set
BucketAlreadyExistsName taken by another customer (very unlikely with the random suffix)Run again
IllegalLocationConstraintExceptionClient Region and bucket Region disagreePass --region matching the bucket
CloudFront returns 403Distribution still deploying, or bucket policy missingWait 5–10 minutes; check terraform apply finished; inspect the bucket policy
Direct S3 URL returns 200Bucket is publicterraform destroy immediately; investigate how Block Public Access was changed
cleanup prints skip ... (PermanentRedirect)Bucket is in another Regioncleanup --yes --region <that region>
Tagging API still lists resources after deletionIndex lagWait a few minutes and re-run
terraform apply fails on the bucket nameA previous run's bucket still existsterraform import it, or delete it and apply again

Cost and cleanup

Label: credits (expect $0.00).

  • STS calls: no charge. S3: a handful of requests and a few kilobytes for minutes cost a tiny fraction of a cent.
  • CloudFront: a few test requests fall within CloudFront's always-free monthly allowance (1 TB of data transfer out and 10,000,000 HTTP/HTTPS requests ⚠ VERIFY on the CloudFront pricing page). The distribution itself has no fixed monthly charge on pay-as-you-go pricing.
  • Free alternative: do parts 1–4 only (no CloudFront), or run terraform plan without apply and review the plan as a design exercise.

Teardown, same day:

cd labs/m01-hello-aws/infra/terraform/status
terraform destroy -var "owner=alex"
cd ../../..
dotnet run --project src/Harbourline.HelloAws -- cleanup --yes
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab --profile learn-sandbox
aws sso logout

Exercises

  • 🟢 Guided: Run statement-demo --keep, then run the six CLI checks above against the bucket and match each output to the line of C# that produced it. Finish with cleanup --yes.
  • 🟡 Challenge: Add a --kms option that uses SSE-KMS with the AWS managed key aws/s3 and S3 Bucket Keys enabled. Write a unit test with the fake IAmazonS3 that proves the encryption request is correct.
  • 🔴 Live problem: A colleague reports: "I deployed the status page, CloudFront shows AccessDenied XML, so I turned off Block Public Access and added a public-read policy, and now it works. Can you approve my PR?" Write your review comment.

Assignment

Publish labs/m01-hello-aws (or your variant of it) to your portfolio repository with a short SECURITY.md listing every control the lab applies, why, and what a production version would add. Include the test output.

Solutions

Knowledge check

Interview questions

  • "How would you serve a static site from S3 securely?" — Private bucket with Block Public Access, CloudFront with Origin Access Control, a bucket policy allowing only the CloudFront service principal with AWS:SourceArn of the distribution, HTTPS-only viewer policy, and a custom domain with an ACM certificate in us-east-1.
  • "What do you put on every S3 bucket by default?" — Block Public Access, default encryption (KMS where data is sensitive), a TLS-only policy, ownership controls with ACLs disabled, tags, and versioning and logging where the data matters.
  • "How do you make sure lab or temporary resources get cleaned up?" — Mandatory tags, IaC so destroy removes everything, tag-based checks after teardown, and budgets as a backstop.

Certification practice

Completion checklist

  • dotnet test shows 71 passed, 1 skipped
  • whoami shows my Identity Center permission set, not root or an IAM user
  • I broke the credential chain three ways and understood each error
  • statement-demo created, used and deleted a locked-down bucket
  • status-check showed CloudFront 200 and direct S3 403 (or I did the design-only alternative)
  • terraform destroy, cleanup --yes and the tagging API check are done, and the Bills page shows no surprise the next day

Key takeaways

  • Every bucket gets Block Public Access, default encryption, a TLS-only policy and tags, set in code and verifiable from outside it.
  • Private bucket + CloudFront + OAC + AWS:SourceArn is the standard way to publish static content.
  • Design teardown into the code: finally blocks, prefix-and-tag cleanup, IaC destroy and a final tag check.
  • Fake the AWS clients in unit tests, so security settings are tested on every build without an account.

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page