サーバーレスを使っているとインフラをAWSが管理してくれるので、開発者・運用者目線からは、すでに “安全・安心” が得られていると言えなくもないですが、そんな中でいろんなサービス運用者やプロダクト開発者と会話してきた経験談を基に さらなる “安全・安心” を目指すお話しをさせて頂きます。
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.© 2023, Amazon Web Services, Inc. or its affiliates.サーバーレスを “安全・安心” に使う(パターン集)J A W S - U G 札 幌 第 2 9 回 勉 強 会Kensuke ShimokawaSnr. Serverless SpecialistAmazon Web Services Japanhttps://speakerdeck.com/_kenshhttps://qiita.com/_kensh
View Slide
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.© 2023, Amazon Web Services, Inc. or its affiliates.About Me…Kensuke ShimokawaAmazon Web Services JapanSnr. Serverless Specialisthttps://speakerdeck.com/_kenshhttps://qiita.com/_kensh
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.© 2023, Amazon Web Services, Inc. or its affiliates.“安全・安心” かどうか
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.安全・安心 ってなに?5安全危険がなく安心なこと。傷病などの生命にかかわる心配、物の盗難・破損などの心配のないこと。また、そのさま。安心気にかかることがなく心が落ち着いていること。また、そのさま。辞書
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.安全と安心を考える6https://www.soumu.go.jp/johotsusintokei/whitepaper/column_uchida.html出典) 総務省有識者コラム
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.© 2023, Amazon Web Services, Inc. or its affiliates.おさらいから、、
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.責任共有モデル - Lambda8https://docs.aws.amazon.com/lambda/latest/dg/lambda-security.html
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.Isolation / 独立環境9functioninstancef(x)=>{ }f(x)deploymentg(x)request to f(x)handlingcold start
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.Isolation / 独立環境10functioninstancef(x)=>{ }f(x)deploymentg(x)response from f(x)
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.Isolation / 独立環境11functioninstancef(x)=>{ }f(x)deploymentg(x)request to f(x)handlingwarm startrequest to f(x)functioninstancef(x)=>{ }handlingcold startrequest to g(x)functioninstanceg(x)=>{ }handlingcold start
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.Isolation / 独立環境12functioninstancef(x)=>{ }f(x)deploymentg(x)request to f(x)handlingwarm startrequest to f(x)functioninstancef(x)=>{ }handlingcold startrequest to g(x)functioninstanceg(x)=>{ }handlingcold startリクエスト単位で Lambdaのinstanceは使いまわされるので、たとえば単一のLambda関数を複数のユースケースで再利用していた場合、その再利用による memoryからの意図しない漏洩はユーザ側での考慮が必要
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.© 2023, Amazon Web Services, Inc. or its affiliates.脆弱性について
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.Amazon Inspector14• 特徴§ ワンクリックで有効化§ リソースの⾃動検出と継続的スキャン§ ダッシュボードによる容易な脆弱性管理§ 独⾃含むスコア算出による優先順位付け§ Organizationとの連携で⼤規模な管理§ Security Hub, EventBridgeとの連携で検知から対応までサポート§ Amazon EC2, Amazon ECR, AWS Lambda に対応 Amazon EC2 Amazon ECRAmazon InspectorAWS Lambdaソフトウェアの脆弱性や意図しないネットワーク露出領域を継続的なスキャンで検知する脆弱性管理サービス
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.© 2023, Amazon Web Services, Inc. or its affiliates.コストについて
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.BillingサービスでBudgetを設定して日毎に検知16意図しない利用額にならないように、BillingサービスでBudgetを設定して翌日には検知 ( SNS通知など )
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.Compute Optimizer の推奨事項の理解 (1/2)17メモリが過剰にプロビジョニングされている(Memory over-provisioned)と認識され、そのため関数が最適化されていない(Not optimized)と判定
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.Compute Optimizer の推奨事項の理解 (2/2)18メモリを大きくすると、呼び出しによる予想利用コストが、5.1% 〜 4.6% 削減見込み
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.AWS Lambda Power Tuning によるチューニング19AWS Lambda Power Tuning は、AWS Step Functions を利⽤したステートマシンであり、Lambda 関数のコストやパフォーマンスを最適化INPUTOUTPUT128 MB256 MB512 MB1024 MBhttps://github.com/alexcasalboni/aws-lambda-power-tuning{"lambdaARN": "arn:aws:lambda: snip","powerValues": [128,256, 512, 1024,1536,2048, 3008],"num": 1000,"payload": { },"parallelInvocation": true,"strategy": "speed | cost"}User functions
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.CPU Intensive な処理系20def lambda_handler(event, context):heavy_CPU_job()return {'statusCode': 200,'body': json.dumps(‘CPU worked’),}コスト = GB秒 x リクエスト件数timecostMB
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.外部 APIコールに依存する処理系def lambda_handler(event, context):external_API_call()return {'statusCode': 200,'body': json.dumps(‘API worked’),}コスト = GB秒 x リクエスト件数timecostMB21
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.© 2023, Amazon Web Services, Inc. or its affiliates.デプロイについて
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.Lambdaのトラフィックシフト機能23AWS LambdaAlias: prod 新機能Lambda エイリアスに 2 つの関数バージョンを指定して、各バージョンにルーティングされるトラフィックの割合を設定できる
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.Lambdaのトラフィックシフト機能24AWS SAM を使用してLambda関数を更新する場合、CodeDeploy が組み込まれているため、Lambda関数を線形にデプロイ可能https://docs.aws.amazon.com/ja_jp/serverless-application-model/latest/developerguide/automating-updates-to-serverless-apps.htmlHelloFunction:Type: AWS::Serverless::FunctionProperties:Runtime: python3.9Handler: index.handlerAutoPublishAlias: !Ref StageDeploymentPreference:Enabled: trueType: Linear10PercentEvery1Minute
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.API Gatewayのカナリアリリース25リクエスト新機能Amazon API Gatewayステージに対して「Canary」を定義すると、APIの「デプロイ」操作でそのステージを指定した際に一旦Canary に対してのみデプロイされるようになる(メインの内容は変わらない)Canaryに対して以下の操作が可能:• 昇格• Canaryのデプロイ内容をメインのステージに反映• 削除• Canaryを削除して、メインステージのみの構成に戻す
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.API Gatewayのカナリアリリース26AWS SAM を使用してAPI Gateway REST APIを更新デプロイする場合は、カナリアの設定を組込めるため、ステージに安全にデプロイ可能HelloWorldApi:Type: AWS::Serverless::ApiProperties:StageName: !Ref StageNameCanarySetting:PercentTraffic: 10UseStageCache: falsehttps://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/canary-release.html
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.AWS AppConfig によるロジックと設定の分離27デプロイ戦略• ベータ環境や本番環境などの論理的なデプロイグループを管理可能• 論理環境ごとに Amazon CloudWatch アラームを設定し AppConfig によってモニタリングすることが可能で、デプロイ中にアラームが発生するとロールバックをトリガー (設定値のValidationも可能)• アプリケーションからは AppConfig のGetConfiguration APIでパラメータを取得できるため、 関数インスタンスごとにユニークなClientIDを振っておけば自動的に戦略に沿ったカナリアが実現• 設定用と関数本体用にCICDパイプラインを分離し2つ用意する• ここでの設定とはLambda サービスの設定ではなく、アプリケーション内のロジックにおける設定のこと (例. フィーチャーフラグ on/off)AWS AppConfighttps://aws.amazon.com/jp/blogs/news/safe-deployment-of-application-configuration-settings-with-aws-appconfig/AWS Lambda新設定初期化時に取得しTTL付きキャッシュしておくPullPull初期化時に取得しTTL付きキャッシュしておくParameter StoreなどParameter Storeなど
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.© 2023, Amazon Web Services, Inc. or its affiliates.観測について
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.embedded metric format / 埋め込みメトリクスフォーマット29{"_aws": {"CloudWatchMetrics": [{"Dimensions": [ [ "functionVersion" ] ],...}]},"functionVersion": "$LATEST"}https://docs.aws.amazon.com/ja_jp/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.htmlCloudWatch 埋め込みメトリクスフォーマットは、• 構造化ログイベントに埋め込まれたメトリクス値を自動的に抽出するように CloudWatch Logs に指示するために使用される JSON 仕様
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.embedded metric format30AmazonAPI GatewayMobile clientAmazonCloudWatch LogsAWSSecrets ManagerAmazonAuroraAWS LambdaAmazonCloudWatch Metrics⾃動的⾮同期embedded metric format 標準出⼒CloudWatch 埋め込みメトリクスフォーマットは、• 構造化ログイベントに埋め込まれたメトリクス値を自動的に抽出するように CloudWatch Logs に指示するために使用される JSON 仕様
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.embedded metric format31from aws_embedded_metrics import metric_scope@metric_scopedef lambda_handler(event, context, metrics):results = conn.runQuery(sql)metrics.set_namespace("Summit2022")metrics.put_dimensions({"dim": "sales"})metrics.put_metric("Conversion", results.Count, "Count"){"LogGroup": "embedded-log",(snip)"_aws": {"Timestamp": 1645369641214,"CloudWatchMetrics": [{"Dimensions": [["LogGroup",”ServiceName", "ServiceType", "dim" ]],"Metrics": [{"Name": "Conversion","Unit": "Count”}],"Namespace": "Summit2022"}]},"Conversion": 100} AmazonCloudWatch LogsCloudWatch Logs に標準出⼒
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates. 32
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.embedded metric format33{…"lambda_function_name":..,"lambda_function_memory_size": 128,"lambda_function_arn": ”…","lambda_request_id": "52fd..","message": ”Aha","cold_start": true}Resultデコレータで関数Context情報も出力可能
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.カスタムメトリックの出力34Result ビジネスKPIを可視化!
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.コールドスタートログのみを抽出 (CloudWatch Logs Insights)35
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.分散トレースを使用 (AWS X-Ray)36X-Ray を使用すると、フロントエンド API からバックエンドのストレージとデータベースまで、アプリケーション内のリソースを横断する際にリクエストをトレースできます
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.トレース / サービスマップ37デコレータでサブセグメントも定義
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.トレース / サービスマップ38関数セグメントを拡張して、そのサブセグメントを表示
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.AWS Lambda Extensions39Lambda Extensionsは、Lambdaをお気に入りの監視、セキュリティツールおよびガバナンスツールと簡単に統合する新しい方法です
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.Lambda Insights Performance monitoring40Lambda Insights
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.Lambda Concurrency Hunt でスパイクを発見41過去7日間のMetricsに対して同時実行数が最も高い期間を見つけ、そのSpikeの前の6分間の情報を出力する。• 関数の呼び出し回数• 平均処理時間• 同時実行数$ curl https://raw.githubusercontent.com/aws-samples/aws-lambda-concurrency-hunt/master/lambda-con-hunt.py -o lambda-con-hunt.py$ python3 lambda-con-hunt.py※ Lambdaの1 分間隔Metricsにおいて、15 日間は1 分の分解能を持つ。以降も使用可能だが、5 分に集約された分解能となるhttps://aws.amazon.com/jp/cloudwatch/faqs/Concurrency Hunt
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.© 2023, Amazon Web Services, Inc. or its affiliates.通信について
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.リソースポリシー43APIGatewayAWS LambdaAWS Cloud{"Version": "2012-10-17","Id": "default","Statement": [{"Sid": ”123456c7-a198-4b2d-b5fc-57fb5fefa0e8","Effect": "Allow","Principal": {"Service": "apigateway.amazonaws.com"},"Action": "lambda:InvokeFunction","Resource": ”LambdaFunctionARN","Condition": {"ArnLike": {"AWS:SourceArn": ”sourceServiceARN"}}}]}{"Version": "2012-10-17","Statement": [{"Effect": "Allow","Principal": "*","Action": "execute-api:Invoke","Resource": "execute-api:/*/*/*"},{"Effect": "Deny","Principal": "*","Action": "execute-api:Invoke","Resource": "execute-api:/*/*/*","Condition": {"NotIpAddress": {"aws:SourceIp": ["sourceIpOrCIDRBlock”]}}}]}
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.VPC Lambdaについて• VPCリソースへのアクセスに、Lambda関数をVPC接続設定する必要がある• VPC Lambdaはデフォルトでインターネットアクセスがない• インターネットアクセスするためには• Public Subnet に NAT Gateway を設置• Internet Gateway を VPC に設置• Route Table でインターネットへの経路を追加44
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.VPC Lambdaについて• VPC Lambdaはデフォルトでリージョナルサービスへのアクセスがない• リージョナルサービスへアクセスするには (以下のいずれかが必要)• インターネットへの経路を確保• サービスごとの VPC Endpoint を利用45
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.ネットワークトラフィックを制御する46Private subnetCustomer VPCAWS CloudAWS Lambda Service VPCAWS Lambda実行環境リージョナルサービスAmazon DynamoDB Amazon SNSHyperplaneNATENISecurity GroupAmazon SQSVPC EndpointENIVPC EndpointGatewayRoute tableVPC EndpointENIインターネットへのアクセスなし
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.VPC接続を強制し、他VPCにも接続不可とする制御47{"Version": "2012-10-17","Statement": [{"Sid": "Stmt159186333251","Action": ["lambda:CreateFunction","lambda:UpdateFunctionConfiguration"],"Effect": "Deny","Resource": "*","Condition": {"ForAllValues:StringNotEquals": {"lambda:VpcIds": ["vpc-0eebf3d0fe63a2db1"]}}}]}IAM UserAWS LambdaCreateFunctionorUpdateFunctionConfigurationPrivate subnetVPC ( vpc-X )ENIVPCに未接続、または指定したVPC以外に接続しようとするとエラーとなる
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.© 2023, Amazon Web Services, Inc. or its affiliates.シークレットについて
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.コードで使用される機密情報を安全に保管する49VPCPrivate subnetAWS Secrets ManagerAWS LambdaシークレットローテーションAmazon AuroraAWS Key ManagementServiceRole暗号化用のKMS鍵ResourcePolicyシークレット情報取得シークレット情報を取得可能なVPCを制限シークレット情報を取得可能なIAM Rolefrom aws_lambda_powertools.utilities import parametersdef handler(event, context):# Retrieve a single secretvalue = parameters.get_secret("my-secret")コード内のハードコードされた認証情報(パスワードを含む) を Secrets Managerへの API コールで置き換えて、プログラムでシークレットを安全に利用することができます
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.© 2023, Amazon Web Services, Inc. or its affiliates.リクエスト検証 について
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.API Gateway REST API のリクエスト検証51リクエストAmazon API Gatewayモデルモデルモデル{"$schema": "http://json-schema.org/draft-04/schema#","title": "User","type": "object","properties": {"UserID": { "type": "string" },"Name": { "type": "string" },"Age": {"description": "Age in years","type": "integer","minimum": 18}},"required": ["UserID", "Name"]}application/json{"UserID": "U0001","Name": "Jhon","Age": 23}HTTP Body検証• リクエストボディはコンテンツタイプとモデルのセットで検証可能。• JSON形式のボディであれば、 application/jsonを設定し、モデルについてはJSON Schemadraft4形式で各JSONのプロパティに対して検証実施JSON Schema draft4
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.© 2023, Amazon Web Services, Inc. or its affiliates.スロットリング について
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.API Gatewayによるスロットリング制御• 閾値を超えるとHTTP 429(Too Many Requests)エラー• リトライ実装はAPIクライアント開発者の責務• Rate/Burstによるスロットリング設定が可能• 使用量プランを使うと• Quota(呼び出し回数制限)の設定が可能• (日/週/月あたりのリクエスト回数)53
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.API Gatewayによるスロットリング制御54EC2上のエンドポイントAWSLambdaAWSサービスインターネットリソースAPIGateway使用量プランThrottling設定 (任意) サーバー側Throttling設定メソッド x RESTリソースAPI x ステージアカウント x リージョンAPI x ステージ (default)Rate: 10000rpsBurst 5000reqRate: ( ) rpsBurst ( ) req緩和可能Rate: ( ) rpsBurst ( ) reqRate: ( ) rpsBurst ( ) req使用量プランを設定したリクエスト使用量プランを設定していないリクエストQuota呼び出し回数制限※ThrottlingとQuota制限は、使用プランのすべての API ステージについて集約される個々の API キーのリクエストに適用されますx-api-key: Ax-api-key: Bx-api-key: C
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.© 2023, Amazon Web Services, Inc. or its affiliates.ダウンストリーム保護 について
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.スケーラブルではないリソースを保護56オンプレミスサーバーや永続層などサーバーレス に対応するスケーラビリティが見込まれないダウンストリームへのアクセスについては、直接行うのではなく、キューやストリーム等のバッファリングによって受け取るトランザクションの数を抑制することでコンポーネントスループットを調整AWS LambdaAmazon API GatewayAmazonSimple Queue ServiceSQS イベントに対する同時実行数を小さくしておくCorporatedata centerオンプレミスサーバーダウンストリームで処理可能な量を処理
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.Lambda の イベントソースで最大同時実行数設定57
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.© 2023, Amazon Web Services, Inc. or its affiliates.まとめ
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.まとめコスト最適化、カナリアデプロイ、セキュリティ、ダウンストリーム保護など様々な観点でユーザーを守る仕組みがあります。ぜひ、明日から開発者が安全・安心に利用できるように!懇親会であれもこれもという話があれば声をかけてください^^59
サーバーレスを “安全・安心” に使う© 2023, Amazon Web Services, Inc. or its affiliates.© 2023, Amazon Web Services, Inc. or its affiliates.Thank you!