Floci × Cognito / IAM ハンズオン — 認証・認可フローのローカル検証【2026年版】
FlociでCognito User Pool・Identity Pool・IAM・STSをローカル再現するハンズオン。ユーザー登録、JWT検証、AssumeRole、ポリシー検証、署名リクエスト、Lambda認可連携を実装例付きで解説。

広告
この記事でわかること
- FlociでSQSキューを作成しメッセージを送受信する基本
- SNSトピックとサブスクリプション、SNS→SQSのFan-out
- FIFOキュー・デッドレターキュー(DLQ)
- EventBridgeのカスタムバス・ルール・ターゲット設定
- Lambda連携によるイベント駆動アーキテクチャの検証
イベント駆動アーキテクチャの心臓部である SQS / SNS / EventBridge。Flociはこの3つをすべてローカル再現でき、本番とほぼ同じメッセージング挙動を開発段階で検証できます。
Flociの基本は 入門記事 を参照してください。
aws sqs create-queue --queue-name tasks --endpoint-url http://localhost:4566
# => "QueueUrl": "http://localhost:4566/000000000000/tasks"
import boto3
sqs = boto3.client(
"sqs", endpoint_url="http://localhost:4566", region_name="us-east-1",
aws_access_key_id="test", aws_secret_access_key="test",
)
url = "http://localhost:4566/000000000000/tasks"
# 送信
sqs.send_message(QueueUrl=url, MessageBody="hello")
# 受信
res = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=1, WaitTimeSeconds=5)
for m in res.get("Messages", []):
print(m["Body"])
sqs.delete_message(QueueUrl=url, ReceiptHandle=m["ReceiptHandle"])
aws sqs create-queue \
--queue-name orders.fifo \
--attributes FifoQueue=true,ContentBasedDeduplication=true \
--endpoint-url http://localhost:4566
sqs.send_message(
QueueUrl="http://localhost:4566/000000000000/orders.fifo",
MessageBody="order-001",
MessageGroupId="user-a",
)
aws sqs create-queue --queue-name tasks-dlq --endpoint-url http://localhost:4566
aws sqs set-queue-attributes \
--queue-url http://localhost:4566/000000000000/tasks \
--attributes '{
"RedrivePolicy": "{\"deadLetterTargetArn\":\"arn:aws:sqs:us-east-1:000000000000:tasks-dlq\",\"maxReceiveCount\":\"3\"}"
}' \
--endpoint-url http://localhost:4566
3回リトライ失敗後、DLQに自動転送されます。
sns = boto3.client("sns", endpoint_url="http://localhost:4566",
region_name="us-east-1",
aws_access_key_id="test", aws_secret_access_key="test")
topic = sns.create_topic(Name="user-events")["TopicArn"]
sns.publish(TopicArn=topic, Subject="Welcome", Message="Hello SNS")
1つのSNSメッセージを複数のSQSキューへ配信する典型パターン:
q1 = sqs.create_queue(QueueName="email-queue")["QueueUrl"]
q2 = sqs.create_queue(QueueName="audit-queue")["QueueUrl"]
def arn_of(url):
return sqs.get_queue_attributes(
QueueUrl=url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
sns.subscribe(TopicArn=topic, Protocol="sqs", Endpoint=arn_of(q1))
sns.subscribe(TopicArn=topic, Protocol="sqs", Endpoint=arn_of(q2))
sns.publish(TopicArn=topic, Message="new user signed up")
両キューに同じメッセージが届きます。
sns.subscribe(
TopicArn=topic, Protocol="sqs", Endpoint=arn_of(q1),
Attributes={"FilterPolicy": '{"event_type": ["signup"]}'},
)
sns.publish(
TopicArn=topic,
Message='{"user": "alice"}',
MessageAttributes={"event_type": {"DataType": "String", "StringValue": "signup"}},
)
aws events create-event-bus --name app-bus --endpoint-url http://localhost:4566
aws events put-rule \
--name order-created-rule \
--event-bus-name app-bus \
--event-pattern '{"source":["myapp.orders"],"detail-type":["OrderCreated"]}' \
--endpoint-url http://localhost:4566
aws events put-targets \
--rule order-created-rule \
--event-bus-name app-bus \
--targets 'Id=1,Arn=arn:aws:lambda:us-east-1:000000000000:function:hello' \
--endpoint-url http://localhost:4566
events = boto3.client("events", endpoint_url="http://localhost:4566",
region_name="us-east-1",
aws_access_key_id="test", aws_secret_access_key="test")
events.put_events(Entries=[{
"Source": "myapp.orders",
"DetailType": "OrderCreated",
"Detail": '{"orderId":"o-001","amount":1500}',
"EventBusName": "app-bus",
}])
パターンに一致したイベントが自動的にLambdaへ配信されます。
aws events put-rule \
--name daily-job \
--schedule-expression "cron(0 9 * * ? *)" \
--endpoint-url http://localhost:4566
定期実行の設定もローカルで検証可能です。
[HTTP Request]
↓
[API Gateway (Floci)]
↓
[Lambda: order-validator]
↓
[SNS: order-events]
↓ (Fan-out)
[SQS: email-queue] [SQS: audit-queue]
↓ ↓
[Lambda: email] [Lambda: audit]
このマイクロサービス構成のE2Eを、Floci 1コンテナだけで検証できます。
import { SQSClient, SendMessageCommand } from "@aws-sdk/client-sqs";
const sqs = new SQSClient({
endpoint: "http://localhost:4566",
region: "us-east-1",
credentials: { accessKeyId: "test", secretAccessKey: "test" },
});
await sqs.send(new SendMessageCommand({
QueueUrl: "http://localhost:4566/000000000000/tasks",
MessageBody: "hello from node",
}));
コンテナ内からは http://floci:4566/000000000000/queue-name のように、FLOCI_HOSTNAME と一致させる。
SQSキューのARNが正しいか、またFIFOキューは FIFOトピック にのみサブスクライブ可能。
EventPattern のJSONが厳密にマッチしていない。source と detail-type を完全一致で確認。
ContentBasedDeduplication=true を有効にするか、MessageDeduplicationId を明示指定。
はい。VisibilityTimeout、WaitTimeSeconds ともに本番同様に機能します。
基本的な確認リクエスト送信に対応。実運用のTLS検証までは再現されません。
基本的なスケジュール機能に対応。フレキシブル時間枠など一部詳細は未対応の可能性あり。
Flociに管理画面はありません。awslocal 系コマンドまたは sqs-admin などの外部ツールを利用してください。
[API Gateway] → [Lambda: validate] → [SQS: orders]
↓
[Lambda: fulfill] → [DynamoDB]
↓ (失敗時)
[SQS: orders-dlq]
SQS FIFO + グループIDでユーザー単位の順序保証を実現:
sqs.send_message(
QueueUrl=fifo_url,
MessageBody='{"orderId":"o-001","amount":1500}',
MessageGroupId="user-001",
MessageDeduplicationId="o-001",
)
ユーザー登録時にメール・Slack・監査ログへ同時配信:
[Lambda: signup] → [SNS: user-events]
↓ (Fan-out)
[SQS: email] [SQS: slack] [SQS: audit]
↓ ↓ ↓
[Lambda] [Lambda] [Lambda]
メッセージフィルタリングで受信側の関心事を限定できます。
events.put_rule(
Name="daily-etl",
ScheduleExpression="cron(0 2 * * ? *)", # 毎日2時
State="ENABLED",
)
events.put_targets(
Rule="daily-etl",
Targets=[{
"Id": "1",
"Arn": "arn:aws:lambda:us-east-1:000000000000:function:etl",
}]
)
大量メッセージで下流が詰まる事態を事前に検証:
# SQS側の Visibility Timeout で処理時間に猶予を
sqs.set_queue_attributes(
QueueUrl=url,
Attributes={"VisibilityTimeout": "120"},
)
# Lambda側の同時実行制限
lam.put_function_concurrency(
FunctionName="fulfill",
ReservedConcurrentExecutions=10,
)
下流への流量制御をFloci上で実測できます。
JSONスキーマで送受信契約を担保する運用例:
import json, jsonschema
SCHEMA = {
"type": "object",
"required": ["orderId", "amount"],
"properties": {
"orderId": {"type": "string"},
"amount": {"type": "number", "minimum": 0},
},
}
def send_order(order):
jsonschema.validate(order, SCHEMA)
sqs.send_message(QueueUrl=url, MessageBody=json.dumps(order))
スキーマ不正なメッセージが送信前に弾かれるため、下流バグを防ぎます。
import time, random
for attempt in range(5):
try:
process_message(msg)
break
except TransientError:
time.sleep((2 ** attempt) + random.random())
dlq = sqs.get_queue_attributes(
QueueUrl="http://localhost:4566/000000000000/tasks-dlq",
AttributeNames=["ApproximateNumberOfMessages"],
)
count = int(dlq["Attributes"]["ApproximateNumberOfMessages"])
if count > 0:
print(f"⚠️ DLQ に {count}件のメッセージ")
CIでDLQ件数をアサーションすることで、デグレを早期検知できます。
本番ではCloudWatch Metricsを使う部分を、ローカルでは:
ApproximateNumberOfMessages で定期ポーリングjq で集計ログ・メトリクスの出力フォーマットをローカルで固めておけば、本番移行時の観測性が下がりません。
import { SQSClient, ReceiveMessageCommand, DeleteMessageCommand }
from "@aws-sdk/client-sqs";
const sqs = new SQSClient({
endpoint: "http://localhost:4566", region: "us-east-1",
credentials: { accessKeyId: "test", secretAccessKey: "test" },
});
while (true) {
const res = await sqs.send(new ReceiveMessageCommand({
QueueUrl: QUEUE_URL, MaxNumberOfMessages: 5, WaitTimeSeconds: 10,
}));
for (const m of res.Messages ?? []) {
await handle(JSON.parse(m.Body));
await sqs.send(new DeleteMessageCommand({
QueueUrl: QUEUE_URL, ReceiptHandle: m.ReceiptHandle,
}));
}
}
広告
広告