Hardening a live serverless app with AWS Security Agent

Hardening a live serverless app with AWS Security Agent

What happens when you point AWS’s AI security tooling at a real, live app? In this post I put AWS Security Agent to work on hillfinder.app, a public serverless app ranking Scottish hills. Alongside Security Hub, Inspector and GuardDuty, I ran design review, threat modelling and code review, fixed what they found with Kiro and the AWS Agent Toolkit, and looked honestly at where the reports helped and where they needed a second opinion.

AWS Consultant/ Cloud engineer
In this post, I will be testing the functionality of AWS Security Agent and AI security tooling by running an analysis and assessment of the security of a live, public web app. The app is  hillfinder.app , built by  jcwrightson  (assessed with his permission).

The plan was:
  1. Assess the app's current security posture using a mix of AWS security tooling.
  1. Fix what the tools find, using Kiro and the AWS Agent Toolkit.
  1. Look at what the reports were actually useful for, and where they needed a second opinion.

The tools I used:
  • AWS Security Agent (now part of  AWS Continuum ): design review, threat modelling and code review.
  • AWS Security Hub, with Security Hub CSPM running the AWS Foundational Security Best Practices standard.
  • Amazon Inspector: Lambda and Lambda code scanning.
  • Amazon GuardDuty: Lambda Protection and AI Protection.

The app

Hillfinder ranks Scottish hills using summit-corrected forecasts from Open-Meteo. The backend is Python (FastAPI) on AWS Lambda, the frontend is a static Next.js site served from Amazon S3 through Amazon CloudFront, and the infrastructure is managed in Terraform.
Here's a very simplified architecture of the app.

Everything in the app is public, and that's intentional. Some features may sit behind authentication in future, but the core of the app will stay open to everyone.

AWS Security Agent's preview features and Security Hub

I will be using AWS Security Agent features that are still in preview, which are design review, threat modelling and code review.




Design review

Design review focuses on assessing the architecture and design of the app, not the code itself. I provided a security diagram and architecture documents for this. You select which security requirements AWS Security Agent uses to analyse compliance. The ASA Base Pack (AWS Security Agent's own set of requirements) is added by default, and you can add custom requirements you want your app to be assessed against (which I did).

It returned 13 non-compliant findings out of 24 requirements (plus 6 with insufficient data). An example of non-compliance was secure-by-default-best-practices (no WAF and no access logs enabled).


"Insufficient data" means the docs didn't say enough, so better docs give a better review, which I improved later as part of the fixes.

Threat modelling

Threat modelling is particularly interesting, and personally I found it the most useful. I still provided architecture documentation, but also gave the tool access the GitHub repository.

The agent worked in three stages:
  1. Pre-flight: checks logging and access to the S3 sources.
  1. Implementation analysis: reading the code to determine how the system is really built.
  1. Threat modelling: models threats against that implementation.

The output is a detailed PDF report that consists of:
  • a system description: purpose, architecture, components, trust boundaries, data flows, security posture, sensitive assets and the agent's assumptions
  • a list of threats, each with a severity (High, Medium or Low), so you know which ones should be tackled first.



It found 15 threats: 10 High and 5 Medium.

Code review

Code review scans the source code for security vulnerabilities and (if you give it write access to the repository) it can also open automated remediations. Both code review and threat modelling use access to the repository, but they answer different questions: threat modelling looks at the system and what could go wrong with it, while code review looks at the code and what is actually wrong in it (so system vs code)



It produced 29 findings: 3 High, 18 Medium and 8 Low. One of the High findings was a denial-of-wallet risk: an anonymous endpoint triggered a paid Bedrock call on every cache miss, and there was nothing stopping one caller from forcing a lot of cache misses. With no WAF, no per-client rate limit and no spend alarm, nothing would have stopped or even flagged it.


Running the assessments

All three run inside an Security Agent agent space, which you create once in the Security Agent console. I did the first setup in the console and used the CLI for re-runs.
  1. Create an agent space and connect GitHub under Integrations. I connected it read-only
  1. Upload the design documents to S3. Design review only knows what you give it, so I wrote a redacted architecture doc, with no domains, account IDs or deploy-role details, and uploaded it with the diagram:
  1. Add your own requirements. The ASA Base Pack is on by default. I added a pack for what matters to a public, anonymous app. Each requirement is a name, a description and what the agent should check for:
aws securityagent create-security-requirement-pack \
--name hillfinder-public-app --status ENABLED

aws securityagent batch-create-security-requirements \
--pack-id <pack-id> \
--security-requirements '[{
"name": "disable-debug-endpoints-production",
"domain": "Secure configuration",
"description": "Debug, test and diagnostic parameters or endpoints must not be accessible in production.",
"evaluation": "Check that API docs pages, debug query parameters and test-only event fields are disabled, or rejected at the edge, in production.",
"remediation": "Turn them off in the production configuration, or strip them at the edge."
}]'
  1. Create the design review in the console, picking the S3 documents and both packs. Mine took a few minutes.
  1. Create the code review and the threat model with the GitHub repo as the source. The threat model also takes the same S3 documents. After that, a re-run is one command each:
aws securityagent start-code-review-job \
--agent-space-id <agent-space-id> --code-review-id <code-review-id>

aws securityagent start-threat-model-job \
--agent-space-id <agent-space-id> --threat-model-id <threat-model-id>
The threat model took about 40 minutes and the code review about two hours. You can then pull the findings from the CLI, which is how the agent was able to read and action them later:
aws securityagent list-findings --agent-space-id <agent-space-id> \
--code-review-job-id <job-id> --risk-level HIGH


Security Hub and Inspector

I also enabled the AWS Security Hub CSPM Foundational pack, GuardDuty with Extended Threat Detection and AI Protection for Bedrock, and Amazon Inspector to scan for vulnerabilities. I decided to use them all together because they monitor different things and their results complement each other. The Security Agent assesses design, architecture and code to work out what could go wrong. Security Hub, Inspector and GuardDuty check what is actually deployed and report what is wrong (for example, vulnerabilities).

Inspector found 32 High and Critical findings. That was really 6 vulnerabilities in 3 packages ( certifi ,  urllib3  and  aiohttp ), repeated across every Lambda in both environments.

Remediation and AWS Agent Toolkit

Now that I had compiled all the findings and reports, I implemented the required changes. This includes architectural changes, security patches and config changes.

For this post I used Kiro with the  AWS Agent Toolkit : the managed AWS MCP Server, plus AWS's skills, which load into context only when a task matches. The server gives the agent one authenticated endpoint for 300+ AWS services, sandboxed Python and doc search that needs no credentials. It is particularly useful for services that have changed recently. Security Hub is now two services with separate APIs (Security Hub and Security Hub CSPM), and Security Agent has been folded into Continuum. A model working from memory could get this wrong without MCP. I am also using  Kiro Powers : Deploy infrastructure with Terraform and AWS Security Agent.
I use the Agent Toolkit every day as a cloud engineer - for documentation queries, ensuring review is accurate, also to query existing resources, read CloudWatch Logs and CloudTrail, and check IAM permissions. I mostly use it with read-only permissions, and if you ever give it write access, put restrictions around it.

For this post the agent only had read-only access. This is the MCP configuration in Kiro:
{
"mcpServers": {
"aws-mcp": {
"command": "uvx",
"args": [
"mcp-proxy-for-aws-cli@latest",
"https://aws-mcp.us-east-1.api.aws/mcp",
"--profile", "agent-readonly",
"--region", "eu-west-1",
"--read-only"
]
}
}
}
 agent-readonly  is an IAM Identity Center profile whose permission set only allows read actions, and  --read-only  tells the proxy to stick to read-only operations. The permission set is the real boundary: the agent's shell uses the same profile, so the flag alone wouldn't stop a write. The trade-off was though: the permission set didn't allow reading the threat model's configuration, so I exported those reports by hand.
In my everyday I use the same setup across a multi-account organisation: one MCP block covers more than 70 accounts. The proxy takes a list of profiles, one read-only role per account, in  AWS_MCP_PROXY_PROFILES . It then adds an  aws_profile  parameter to its tools, so the agent picks the account on each call without restarting anything ( multi-profile support ). Here is an example for how would this look like:
"env": {
"AWS_MCP_PROXY_PROFILES": "shared-readonly prod-readonly staging-readonly dev-readonly"
}
The first profile is the default, and the agent can only use the profiles you list, not anything else in  ~/.aws/config . It needs SigV4 sign-in through the proxy (OAuth doesn't support switching) and proxy version 1.6.0 or later.

Security Reports

A threat model isn't a test you pass: when I ran it again on the hardened app, it found fewer High threats, but more threats overall, because the system had grown and the docs described more of it. I'll also review how accurate and useful the reports were for this use case.

Threat model: the edge defences

What it found: Among its High threats: anyone, or a botnet, could flood the API with no limit, and adding random query parameters to a URL skipped the cache, so every request landed on the Lambda. Another was that the hill and forecast data could be overwritten or deleted with no way back.

What I changed: The biggest change was WAF on both CloudFront distributions. All three reports pointed to this as the biggest gap and the priority. There's one web ACL per environment, shared by the site and the API, and the rules run in this order:
Order
Rule
What it does
0
AWS IP reputation list (managed)
Drops addresses AWS threat intelligence has seen attacking
1
AI endpoint rate limit
A much tighter per-IP limit on the paid AI endpoint
2
API rate limit
300 requests per IP per 5 minutes on the API
3
Site rate limit
1,000 requests per IP per 5 minutes on the site
4
Known bad inputs (managed)
Log4j, Java deserialisation and other known exploit patterns
5
Common rule set (managed)
The OWASP-style baseline: XSS, file inclusion, SSRF, oversized requests

IP reputation goes first because it's the cheapest way to drop known-bad traffic. The AI endpoint limit comes before the general API limit, so its tighter cap wins . I sized the limits from five days of CloudFront metrics: the busiest 5 minutes for all prod visitors together was 402 site requests and 25 API requests. The managed rule groups block from day one instead of starting in count mode: the app only takes short GET requests with a few fixed parameters, and WAF logs every blocked request, so a false positive would show up in one query.

The second fix was a cache key allowlist. CloudFront now only uses the query parameters the app actually reads and drops the rest, so random parameters no longer force a fresh Lambda call.
For data protection, the DynamoDB table can't be deleted by accident and can be restored to any point in time in prod. I also tightened permissions so that only listed functions can write to it, and only the refresh function can publish forecasts to S3. The S3 buckets only accept encrypted connections. So all the findings were valid and required.


Code review: the paid AI endpoint and a safety bug

What it found: Two of its three High findings: the denial-of-wallet risk on the AI endpoint and the detail page sending only one of the four safety limits.

What I changed: The denial-of-wallet finding got fixed in three layers. The paid endpoint has its own WAF rule. This is a simplified version that shows how a rate limit can apply to one path only:

rule {
name = "rate-limit-ai-endpoint"
priority = 1

action {
block {
custom_response { response_code = 429 }
}
}

statement {
rate_based_statement {
limit = 100 # requests per IP per window; size it from your own traffic
evaluation_window_sec = 300
aggregate_key_type = "IP"

scope_down_statement {
byte_match_statement {
search_string = "/endpoint"
positional_constraint = "STARTS_WITH"
field_to_match { uri_path {} }
text_transformation {
priority = 0
type = "LOWERCASE"
}
}
}
}
}
}

The Bedrock call now has timeouts. Before, it used the defaults: 60 seconds to wait, plus retries, and every retry is another paid call. Each attempt gives up after 10 seconds, with at most one retry:

config = Config(
connect_timeout=3,
read_timeout=10,
retries={"max_attempts": 2, "mode": "standard"},
)
client = boto3.client("bedrock-runtime", region_name=region, config=config)

And an alarm notifies me if the number of AI calls suddenly jumps. The safety bug fix was small too: the detail page now sends all four safety limits, the same way the map does, so a day the map marks as unsafe can't show up as fine on the detail page.


Design review: logs and better docs

What it found. No access logs on CloudFront or S3, and monitoring that only covered the forecast refresh, so after an attack I couldn't see who did what. Six requirements also came back as "insufficient data".

What I changed: Both CloudFront distributions now send access logs to CloudWatch, WAF logs every blocked request, and both are kept for 30 days, so if something happens I can see who sent what
Its "insufficient data" results were a documentation problem, not a security one. It said no logs were produced, because my diagram didn't show the Lambda logs. Once the architecture doc described the controls properly, half of those turned into real answers. If you use it, budget time for the docs.

Inspector: dependency patches

What it found. The 6 vulnerabilities behind its 32 findings, all in dependencies.
What I changed. I pinned  certifi  and  urllib3 . The  aiohttp  ones weren't even in the app's code: they came from the AWS-managed pandas layer, and bumping it to a newer version fixed them. Inspector went to 0.

Where the reports needed a second opinion and issues I came across

  • Tools are only aware of things we provided. All three reports said the app needed WAF, but only the code review knew where it could go. API Gateway HTTP APIs can't attach WAF directly and only REST APIs can. The design review missed that and suggested enforcing the origin check "in a WAF rule" on the API, which can't be done with current architecture. The code review got it right though: it noted that an HTTP API can't take WAF, which is why the API has its own CloudFront distribution. To be fair to the design review, it only reads the documents you give it, and the code review had the code and the repo's own comments. So this just shows that we need to have detailed architecture diagrams and documentation to use.

  • Treat architecture remediation as a starting point, not a decision. For code-level findings, the suggested fixes were usually close to what was shipped. For architecture, they weren't. An architecture fix is rarely a black and white choice. The right one depends on what the app is, where it's going, and what you're willing to pay for and run. The remediation guidance doesn't know any of that, but it's written as if it does. One example was how the API checks that traffic came from CloudFront. The code review said:
Fix: replace the static header with a signed-request mechanism (SigV4/OAC or an API Gateway resource policy keyed to the distribution)
The design review said to "migrate the API to a REST API with a resource policy or Lambda authoriser that validates SigV4-signed edge requests". Both read as a fix you can just apply. Neither is, on this architecture: CloudFront's origin access control (OAC) can't sign requests to API Gateway, and a resource policy can't tell the app's CloudFront distribution from anyone else's. Moving to REST doesn't solve it on its own either. When I worked through the real options, each one was a trade-off:
- add Lambda@Edge to sign requests, and keep API Gateway for when the app adds auth, at the cost of another moving part
- replace API Gateway with a Lambda function URL, which OAC can sign, and lose API Gateway's routing and throttling
- keep the header, rotate it, alarm on direct hits, and accept the risk in writing for now
Which one is right depends on where the app is going, not on the finding. And it requires careful planning.

  • The code review findings are easy to check. Each one comes with file and line references, the path from the entry point to the bug, the controls it looked for and didn't find, and any evidence against its own finding. I could confirm most of them straight away. It's also honest about its limits: findings have a confidence level.
  • Automated fixes need write access, and you can't update Github integration. Every code review finding says "No access to remediate any repositories", because I connected GitHub as read-only. You can't edit an existing GitHub connection to make it read and write. You have to remove it and add it again.


Proving it worked

Every fix was checked against the live app, not just applied. I wrote a small smoke test that sends a few requests and reads the AWS config, and runs after every deploy. For WAF, it sends attack-shaped requests and a burst of traffic, then checks the status codes (trimmed):

code() { curl -s -o /dev/null -w '%{http_code}' "$@"; }

# Managed rules: Log4j and XSS probes are blocked at the edge, normal browsing isn't
code "$API/forecast/range?x=%24%7Bjndi%3Aldap%3A%2F%2Fexample.invalid%2Fa%7D" # 403
code "$SITE/?q=%3Cscript%3Ealert(1)%3C%2Fscript%3E" # 404
code "$SITE/" # 200

# Rate limit: about 450 API requests in a minute, each with a unique parameter
for i in $(seq 1 9); do
seq 1 50 | xargs -P 25 -I{} curl -s -o /dev/null -w '%{http_code}\n' \
"$API/forecast/range?cb=$i-{}-$RANDOM"
sleep 5
done | sort | uniq -c # some 200s, then 429s

# Config: each distribution has the web ACL attached
aws cloudfront get-distribution-config --id "$DIST_ID" \
--query DistributionConfig.WebACLId --output text

A blocked request shows up as 404 on the site rather than 403, because the site's CloudFront distribution maps 403 to its 404 page. Running the rate test locks your own IP out of the API for up to 5 minutes. This is where the Agent Toolkit did most of its work. With its read-only role, the agent:
  • read the WAF web ACL to confirm the rules were attached and in the right order
  • read the WAF logs to confirm which rule blocked a request
  • queried Inspector after each deploy to see which findings had closed
  • checked the deployed Lambda configuration on dev and prod, for example that the debug options were on for dev and off for prod
Two lessons from testing the rate limit:
  • Give each test request a unique query parameter, so you can tell the requests apart in the WAF logs.
  • WAF takes a moment to start blocking. The first part of the burst got through, and only then did the 429s start, so don't read an early run of 200s as a failed test.

Going further: Security Agent in the pipeline

Security Agent can now also run a penetration test as a step in your CI/CD pipeline. It tests only what you just deployed, and can block promotion to production if it finds something serious. It's free while in preview ( docs ).

Useful links

Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article