The last post built a knowledge base over my own writing, but I could only ask it questions from a terminal. This post puts a chat box on this site, so a reader can ask “how did I set up the budget alert?” and get an answer with links to the posts it came from.
The interesting part is not the box. It is that the API behind it is public, and that changes the security thinking from the chatbot post.
What We Are Building
- A second CDK stack,
AskBlog, with an HTTP API, one Lambda function and a tight throttle - The function takes a question, calls
RetrieveAndGenerateon the knowledge base from the last post, and returns the answer plus the paths of the posts it used - A Hugo shortcode that draws the box and calls the API from the reader’s browser
The knowledge base stays in its own stack. This stack only needs its ID, so you can destroy this one and keep the other.
Why Not Reuse the Chatbot API?
The chatbot API protects itself with a shared token in a request header. That works when the only caller is me. A chat box on a public page needs the token in the page’s JavaScript, and anything in the page is readable by every visitor, so it is not a secret any more. Hiding it does not help.
So this API has no token, and I have to be straight about what protects it instead:
- A throttle on the API: one request a second, bursts of three. This is the real protection, because it caps the worst case whatever anyone does
- An origin check in the function. Browsers send an
Originheader on cross-site requests, so this stops other websites from using my endpoint through their visitors’ browsers. It does not stop someone usingcurl, who can set any header they like - Small limits on every request: 300 characters in, 300 tokens out, five chunks retrieved
- A kill switch:
cdk destroyremoves the whole thing in a minute
Work out the worst case before you deploy. At one request a second, an attacker could in theory make 86,400 requests a day. Multiply that by what one question costs (see “What It Cost” below) and decide whether you are happy with that number. If not, lower throttling_rate_limit. The budget alert from the first post is your backstop, not your plan.
Before We Start
- The
DocsKnowledgeBasestack from the last post, deployed and synced, and its knowledge base ID:KB_IDin the commands below - The sandbox profile, the CDK bootstrap and the
IAMFullAccesspermission from the chatbot post, as before - The AWS CDK CLI, Python 3 and uv
- This blog’s repository, because the second half edits it
If you added posts since your last sync, run the sync and ingestion job from the last post again, or the box will not know about them.
Create the Project
mkdir ask-blog
cd ask-blog
uv venv
source .venv/bin/activate
mkdir lambdarequirements.txt:
aws-cdk-lib>=2.278.0
constructs>=10.0.0,<11.0.0Then uv pip install -r requirements.txt, and create cdk.json:
{ "app": "python app.py" }and app.py:
import aws_cdk as cdk
from ask_blog_stack import AskBlogStack
app = cdk.App()
AskBlogStack(app, "AskBlog", env=cdk.Environment(region="eu-west-2"))
app.synth()The Lambda Function
Save this as lambda/handler.py. As in the chatbot post, everything that can reject a request runs before the call that costs money:
import json
import os
import boto3
from botocore.exceptions import ClientError
KB_ID = os.environ["KB_ID"]
MODEL_ARN = os.environ["MODEL_ARN"]
ALLOWED_ORIGINS = os.environ["ALLOWED_ORIGINS"].split(",")
MAX_QUESTION_CHARS = 300
client = boto3.client("bedrock-agent-runtime")
def respond(status, body):
return {
"statusCode": status,
"headers": {"content-type": "application/json"},
"body": json.dumps(body),
}
def page_path(uri):
# s3://bucket/blog/aws-bedrock-first-call.md -> /blog/aws-bedrock-first-call/
name = uri.rsplit("/", 1)[-1].removesuffix(".md")
return f"/blog/{name}/"
def lambda_handler(event, context):
# Browsers always send Origin on a cross-site POST. This stops other websites
# using the endpoint from a visitor's browser. It does not stop curl: the
# throttle on the API is what protects the bill.
headers = {k.lower(): v for k, v in (event.get("headers") or {}).items()}
if headers.get("origin") not in ALLOWED_ORIGINS:
return respond(403, {"error": "forbidden"})
try:
question = json.loads(event.get("body") or "{}").get("question")
except json.JSONDecodeError:
return respond(400, {"error": "body must be JSON"})
if not isinstance(question, str) or not question.strip():
return respond(400, {"error": "question is required"})
question = question.strip()
if len(question) > MAX_QUESTION_CHARS:
return respond(400, {"error": f"question must be {MAX_QUESTION_CHARS} characters or fewer"})
try:
response = client.retrieve_and_generate(
input={"text": question},
retrieveAndGenerateConfiguration={
"type": "KNOWLEDGE_BASE",
"knowledgeBaseConfiguration": {
"knowledgeBaseId": KB_ID,
"modelArn": MODEL_ARN,
"retrievalConfiguration": {"vectorSearchConfiguration": {"numberOfResults": 5}},
"generationConfiguration": {
"inferenceConfig": {"textInferenceConfig": {"maxTokens": 300, "temperature": 0.2}}
},
},
},
)
except ClientError as err:
print(json.dumps({"bedrockError": err.response["Error"]["Code"], "detail": str(err)}))
return respond(502, {"error": "the lookup failed, try again later"})
pages = []
for citation in response.get("citations", []):
for ref in citation["retrievedReferences"]:
path = page_path(ref["location"]["s3Location"]["uri"])
if path not in pages:
pages.append(path)
return respond(200, {"answer": response["output"]["text"], "sources": pages})The parts that matter:
- The function turns the S3 path of each source (
blog/aws-bedrock-first-call.md) into the page path on the site (/blog/aws-bedrock-first-call/). The bucket name never reaches the browser - Errors from Bedrock go to the logs with full detail, and the caller only gets a generic message
- This relies on the blog’s file names matching its URLs, which is true here. If your site uses different slugs, you need a lookup instead
The Infrastructure
Save this as ask_blog_stack.py:
from aws_cdk import (
CfnOutput,
Duration,
RemovalPolicy,
Stack,
aws_apigatewayv2 as apigw,
aws_iam as iam,
aws_lambda as _lambda,
aws_logs as logs,
)
from aws_cdk.aws_apigatewayv2_integrations import HttpLambdaIntegration
from constructs import Construct
SITE = "https://renegade.cloud"
DEFAULT_MODEL_ARN = "arn:aws:bedrock:eu-west-2::foundation-model/amazon.nova-micro-v1:0"
class AskBlogStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
# The knowledge base from the last post: cdk deploy -c kb_id=...
kb_id = self.node.try_get_context("kb_id")
if not kb_id:
raise ValueError("Pass the knowledge base ID: cdk deploy -c kb_id=<id>")
model_arn = self.node.try_get_context("model_arn") or DEFAULT_MODEL_ARN
origins = [SITE, "http://localhost:1313"] # the second is `hugo server`
fn = _lambda.Function(
self,
"AskFunction",
runtime=_lambda.Runtime.PYTHON_3_13,
handler="handler.lambda_handler",
code=_lambda.Code.from_asset("lambda"),
timeout=Duration.seconds(30),
memory_size=256,
environment={
"KB_ID": kb_id,
"MODEL_ARN": model_arn,
"ALLOWED_ORIGINS": ",".join(origins),
},
log_group=logs.LogGroup(
self,
"AskLogs",
retention=logs.RetentionDays.ONE_MONTH,
removal_policy=RemovalPolicy.DESTROY,
),
)
# One knowledge base to read, one model to call. RetrieveAndGenerate
# does not support resource-level permissions, so it has to be "*".
fn.add_to_role_policy(
iam.PolicyStatement(
actions=["bedrock:RetrieveAndGenerate"],
resources=["*"],
)
)
fn.add_to_role_policy(
iam.PolicyStatement(
actions=["bedrock:Retrieve"],
resources=[f"arn:aws:bedrock:{self.region}:{self.account}:knowledge-base/{kb_id}"],
)
)
fn.add_to_role_policy(
iam.PolicyStatement(
actions=["bedrock:InvokeModel"],
resources=[model_arn],
)
)
api = apigw.HttpApi(
self,
"AskApi",
cors_preflight=apigw.CorsPreflightOptions(
allow_origins=origins,
allow_methods=[apigw.CorsHttpMethod.POST],
allow_headers=["content-type"],
max_age=Duration.hours(1),
),
)
# A POST-only route, not a catch-all: with a catch-all, the browser's
# OPTIONS preflight is sent to the function instead of being answered
# by API Gateway's CORS handling.
api.add_routes(
path="/",
methods=[apigw.HttpMethod.POST],
integration=HttpLambdaIntegration("AskIntegration", fn),
)
# A public box has no secret to hide, so the throttle is the real
# protection: one request a second, bursts of three.
cfn_stage = api.default_stage.node.default_child
cfn_stage.default_route_settings = apigw.CfnStage.RouteSettingsProperty(
throttling_rate_limit=1,
throttling_burst_limit=3,
)
CfnOutput(self, "AskUrl", value=api.url or "")Four things to check in it:
- IAM.
bedrock:RetrieveAndGeneratehas to be"*", because AWS says the action does not support resource-level permissions. The other two statements are scoped:Retrieveto the one knowledge base andInvokeModelto the one model - The route is
POST /, not a catch-all. My first version used a catch-all$defaultroute, and it broke the browser: the browser’sOPTIONSpreflight request was sent to the function, which rejected it with a 400, and browsers will not send the real request after a failed preflight. With aPOST-only route, API Gateway answers the preflight itself with a 204. I only found this because I tested the preflight withcurl, so do the same (below) - CORS allows
https://renegade.cloudandhttp://localhost:1313, the addresshugo serveruses, so you can test before publishing - Concurrency. I did not set reserved concurrency on the function. New accounts can have a very low Lambda concurrency quota, and reserving some of it can fail the deploy. The throttle does the job here
Deploy It
cdk synth --profile sandbox -c kb_id=$KB_ID
cdk diff --profile sandbox -c kb_id=$KB_ID
cdk deploy --profile sandbox -c kb_id=$KB_IDcdk diff lists the new resources: a log group, the function and its role and policy, and the HTTP API with its route and stage. Nothing existing is changed. The deploy took about 70 seconds, and the generated policy contains exactly the three statements above.
Read the address back, as in the earlier posts:
ASK_URL=$(aws cloudformation describe-stacks --stack-name AskBlog \
--profile sandbox --region eu-west-2 \
--query "Stacks[0].Outputs[?OutputKey=='AskUrl'].OutputValue" --output text)
echo $ASK_URLTry It From the Terminal
First the happy path, pretending to be the site:
curl -X POST "$ASK_URL" \
-H "content-type: application/json" \
-H "origin: https://renegade.cloud" \
-d '{"question": "What did I use as the vector store, and why?"}'Then the ways it should refuse:
# No Origin header: expect 403
curl -X POST "$ASK_URL" -H "content-type: application/json" -d '{"question": "hi"}'
# Wrong origin: expect 403
curl -X POST "$ASK_URL" -H "content-type: application/json" \
-H "origin: https://example.com" -d '{"question": "hi"}'
# Empty question: expect 400
curl -X POST "$ASK_URL" -H "content-type: application/json" \
-H "origin: https://renegade.cloud" -d '{"question": ""}'Here is what I got. The first request took 3.0 seconds, including Lambda’s cold start, and a second question took 2.3 seconds. The answer to the vector store question was correct, and sources came back as ["/blog/aws-bedrock-knowledge-base-rag/"]. The three refusals returned 403, 403 and 400 in about 0.6 seconds each, with no Bedrock call.
Now check the preflight, which is what a browser sends before the real request:
curl -i -X OPTIONS "$ASK_URL" \
-H "origin: https://renegade.cloud" \
-H "access-control-request-method: POST" \
-H "access-control-request-headers: content-type"You want 204 and an access-control-allow-origin header naming your site. A GET to the same address should give 404, because only POST / exists.
Remember the first curl also proves the point from earlier: anyone can type that origin header. That is why the throttle matters more than the check.
Put the Box on the Site
The site is Hugo with the nuno theme, so the box is a shortcode at themes/nuno/layouts/shortcodes/ask-blog.html. It draws a form, posts the question as JSON and shows the answer and the source links. Two details are worth knowing:
- The answer is put on the page with
textContent, neverinnerHTML. It is model output, and I do not want a stray<script>in an answer to run in a reader’s browser - Source links are only shown if they match
/blog/<name>/, so a bad response cannot turn into a link to somewhere else
The shortcode does nothing until the address is set. Add it to hugo.toml:
[params]
askBlogUrl = "https://abc123.execute-api.eu-west-2.amazonaws.com/"Use your own $ASK_URL. Then put the box on any page with:
{{< ask-blog >}}Test it locally first. hugo server runs on localhost:1313, which the stack already allows:
hugo serverI tested it in a real browser from localhost:1313. The POST returned 200 with access-control-allow-origin on the response, so the CORS settings above are all it needs. I asked “How do I set up a billing alarm?” and got an answer with a link to /blog/aws-budgets-billing-alerts/.
Two rough edges, both visible in that answer:
- The answer is plain text. The model writes markdown, but the box shows it as text, so you see literal
**bold**and a code fence. Rendering it safely needs a markdown library plus an HTML sanitiser, which is more than this post needs. A system prompt asking for plain prose would also help - Long answers are cut off. The 300 token limit stops the answer mid-sentence. That limit is part of the cost cap, so I left it. Raise
maxTokensif you would rather have complete answers
Here it is:
What It Cost
I do not have a measured figure to give you. I tried to read token counts from CloudWatch, but the generation model’s metrics did not appear for these calls, and Cost Explorer lags by about a day. TODO(build): a day after your test, read the Bedrock charges in Cost Explorer (they stay there after you destroy the stack), divide by the number of questions you asked, and redo the worst-case sum with your own number.
Cleaning Up
cdk destroy --profile sandbox -c kb_id=$KB_IDThen set askBlogUrl back to "" in hugo.toml so the box disappears from the site instead of showing an error. The knowledge base is a separate stack and is untouched; destroy it as described in the last post when you are done with it.
What I’d Do Next
- Guardrails. This bot will try to answer anything, including questions that have nothing to do with the blog. The next post adds Bedrock Guardrails to keep it on topic
- Re-sync on deploy. The knowledge base only knows what I last uploaded. The deploy script could upload changed posts and start the ingestion job
- Real limits per visitor. A throttle is shared by everyone. A WAF rate rule or a login would let one noisy visitor be blocked without affecting the rest