iT邦幫忙

2025 iThome 鐵人賽

DAY 7
0

前言

在前面幾天的學習中,我們已經了解了AWS Bedrock和SageMaker的基本概念,也成功建立了AWS帳戶。
今天我們要深入探討一個極其重要但常被忽略的主題:IAM(Identity and Access Management)權限設定與安全性考量。
正確的權限設定不僅能保護我們的AWS資源,更是建構安全AI應用的關鍵。
在AI領域,我們經常處理敏感資料和昂貴的運算資源,因此安全性絕對是需要重點考量的部分!

情境思考

在處理 IAM 需要思考的幾個狀況

  • 情境一 : 開發者意外刪除了正在訓練的機器學習模型
  • 情境二 : 未正確設定的權限導致產生巨額AWS帳單
  • 情境三 : 敏感的訓練資料被未授權的人員存取
  • 情境四 : 惡意攻擊者利用過度寬鬆的權限存取您的AI服務

IAM 基本觀念

  1. 使用者(Users)

代表實際的人員或應用程式
擁有永久的存取憑證

  1. 群組(Groups)

使用者的集合
簡化權限管理

  1. 角色(Roles)

可以被信任的實體暫時承擔
適合跨服務存取

  1. 政策(Policies)

定義權限的JSON文件
指定允許或拒絕的行為

bedrock 基本 policies

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "bedrock:InvokeModel",
                "bedrock:InvokeModelWithResponseStream"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "bedrock:ListFoundationModels",
                "bedrock:GetFoundationModel"
            ],
            "Resource": "*"
        }
    ]
}

如果要限定某些模型存取(我這裡以 claude-v2, titan-text-express-v1做示範)

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "bedrock:InvokeModel"
            ],
            "Resource": [
                "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-v2",
                "arn:aws:bedrock:us-east-1::foundation-model/amazon.titan-text-express-v1"
            ]
        }
    ]
}

sagemaker 基本 policies

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "sagemaker:CreateTrainingJob",
                "sagemaker:DescribeTrainingJob",
                "sagemaker:CreateModel",
                "sagemaker:CreateEndpointConfig",
                "sagemaker:CreateEndpoint"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:PutObject",
                "s3:DeleteObject"
            ],
            "Resource": [
                "arn:aws:s3:::your-sagemaker-bucket/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "*"
        }
    ]
}

實際操作

登入AWS Console,進入IAM服務
->
點選「Groups」→「Create group」
->
群組名稱:AI-Project-Developers

建立自訂的 policies

name : AI-Project-Policies

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "BedrockAccess",
            "Effect": "Allow",
            "Action": [
                "bedrock:InvokeModel",
                "bedrock:InvokeModelWithResponseStream",
                "bedrock:ListFoundationModels"
            ],
            "Resource": "*"
        },
        {
            "Sid": "SageMakerNotebooks",
            "Effect": "Allow",
            "Action": [
                "sagemaker:CreateNotebookInstance",
                "sagemaker:DescribeNotebookInstance",
                "sagemaker:StartNotebookInstance",
                "sagemaker:StopNotebookInstance"
            ],
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "sagemaker:InstanceTypes": [
                        "ml.t3.medium",
                        "ml.t3.large"
                    ]
                }
            }
        },
        {
            "Sid": "S3BucketAccess",
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket",
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::your-ai-project-bucket",
                "arn:aws:s3:::your-ai-project-bucket/*"
            ]
        }
    ]
}

再來把 policies 加到剛才創建的 AI-Project-Developers 群組 (Groups)

然後再來建立使用者加入該群組

安全實踐

最小權限原則

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Deny",
            "Action": "*",
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "bedrock:InvokeModel"
            ],
            "Resource": "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-v2",
            "Condition": {
                "DateGreaterThan": {
                    "aws:CurrentTime": "2025-09-21T00:00:00Z"
                },
                "DateLessThan": {
                    "aws:CurrentTime": "2025-12-31T23:59:59Z"
                }
            }
        }
    ]
}

ip 限制

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "bedrock:*",
            "Resource": "*",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": [
                        "203.0.113.0/24",
                        "198.51.100.0/24"
                    ]
                }
            }
        }
    ]
}

限制使用時間

{
    "Condition": {
        "DateGreaterThan": {
            "aws:CurrentTime": "08:00:00Z"
        },
        "DateLessThan": {
            "aws:CurrentTime": "18:00:00Z"
        }
    }
}

監控與稽核 - 導入 cloudwatch 以及 cloudtrail

啟用 cloudtrail 去紀錄所有 api 呼叫

{
    "eventTime": "2025-09-21T10:30:00Z",
    "eventName": "InvokeModel",
    "eventSource": "bedrock.amazonaws.com",
    "userIdentity": {
        "type": "IAMUser",
        "principalId": "AIDAXXXXXXXXXXXXX",
        "arn": "arn:aws:iam::123456789012:user/ai-developer-1"
    },
    "requestParameters": {
        "modelId": "anthropic.claude-v2"
    }
}

利用 cloudwatch 設定成本警報

aws cloudwatch put-metric-alarm \
    --alarm-name "Bedrock-High-Usage" \
    --alarm-description "Alert when Bedrock usage is high" \
    --metric-name EstimatedCharges \
    --namespace AWS/Billing \
    --statistic Maximum \
    --period 86400 \
    --threshold 100 \
    --comparison-operator GreaterThanThreshold

常見問題整理

Q1:權限不足

An error occurred (AccessDeniedException) when calling the InvokeModel operation: 
User is not authorized to perform: bedrock:InvokeModel

A : 檢查使用者是否有正確的Bedrock權限,並確認政策已正確附加

Q2 : 資源ARN錯誤

An error occurred (ValidationException) when calling the InvokeModel operation: 
Invalid model identifier

A : 確認模型ARN格式正確,使用bedrock:ListFoundationModels查看可用模型

Q3 : 跨區域存取問題
A : 確保政策中的區域設定與實際使用區域一致

驗證 IAM

import boto3
import json

def validate_iam_policy(policy_document):
    """驗證IAM政策語法"""
    iam = boto3.client('iam')
    
    try:
        response = iam.simulate_principal_policy(
            PolicySourceArn='arn:aws:iam::123456789012:user/test-user',
            ActionNames=['bedrock:InvokeModel'],
            PolicyInputList=[json.dumps(policy_document)]
        )
        return response
    except Exception as e:
        return f"政策驗證失敗: {e}"

# 使用範例
policy = {
    "Version": "2012-10-17",
    "Statement": [{
        "Effect": "Allow",
        "Action": "bedrock:InvokeModel",
        "Resource": "*"
    }]
}

result = validate_iam_policy(policy)
print(result)

上一篇
SageMaker Studio實作:建立第一個ML專案
系列文
從零開始的AWS AI之路:用Bedrock與SageMaker打造智慧應用的30天實戰7
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言