2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【AWS】Cognitoのトークン交換を活用したRAGにおける権限管理について

2
Posted at

はじめに

Amazon Cognito に OAuth 2.0 のトークン交換 が来たーというアプデについて

エージェントが「誰の代わりに」動いているかをトークンで表せるようになるので、AgentCore Gateway と Managed Knowledge Base の Fine-grained Access Control(FGAC)にどう使えるのかを試してみました。

前提:Managed KB のアクセス制御の基本形

先に、前提となる構成を整理しておきます。

AgentCore Gateway に Managed Knowledge Base をコネクタで繋ぐと、Retrieve ツールの引数に userContext が出てきます。KB の ACL を有効にしておけば、ここに入れたユーザー ID で検索結果が絞られます。

問題は、この userContext をLLM が書けることです。

LLMによるuserContextの書き換えは、私が香港のコミュニティデイで登壇した際も触れています。

また、AWS の ML ブログでも整理されています。

ざっくり言うと、守る場所を2層に分けて、それぞれに一次防御と二次防御を置く考え方です。

一次防御 二次防御
ツール層(Gateway) interceptor が検証済みトークンから userContext を上書き Cedar(AgentCore Policy)でトークンの値と引数を突き合わせる
リソース層(KB) ACL を理解した検索 リソースベースポリシー

どちらの防御も、Gateway に届くトークンを信じるところから始まっています。今回はこの入口に流れてくるトークンのほうに手を入れます。

トークン交換とは

ユーザーのトークンを、別の宛先・別の主体向けのトークンに取り替える仕組みです。Cognito の場合は token endpoint に grant_type=urn:ietf:params:oauth:grant-type:token-exchange で投げます。

今回は、エージェントを AgentCore Runtime に載せて、交換そのものは AgentCore Identity に任せる形にしました。Identity の On-Behalf-Of(OBO)トークン交換を使うと、エージェントのコードにクライアントシークレットを持たせずに済みます。

image.png

交換の仕方は2通りあります。

impersonation(なりすまし) delegation(委任)
渡すもの ユーザーのトークン ユーザーのトークン+エージェント自身のトークン(actor token)
交換後の sub ユーザー ユーザー
交換後の client_id 交換したクライアント(エージェント) 同左
act クレーム なし あり(エージェントの情報)

act が付くかどうかが、後で Cedar を書くときに効いてきます。

MCP の仕様では、受け取ったユーザーのトークンをそのまま下流へ流す「token passthrough」が明確に禁止されています。トークン交換は、これを避けるための正攻法の一つという位置づけです。

検証構成

image.png

要素 設定
AgentCore Runtime エージェントの実行環境。入口は Cognito の JWT(allowedClients は web)。エージェントは LLM を使わず、OBO と Gateway 呼び出しだけをする Python
AgentCore Identity workload identity と credential provider(CustomOauth2、client = agent)。OBO で Cognito に交換を頼む
Cognito Essentials プラン。resource server jy-gateway。アプリクライアントは web(サインイン用)と agent(交換用、secret あり)。ドメインは managed login のバージョン2
Gateway CUSTOM_JWT、allowedAudience=["jy-gateway"]
interceptor REQUEST。userContext.userId を検証済みトークンの email で上書き
Managed KB ACL 有効。4文書(給与系2本は user-a だけ、経費規程など2本は user-a と user-b)
Policy Cedar。ENFORCE

Gateway の中では、入口の JWT 検証 → interceptor → Policy の順に通って、最後に KB を呼びます。この順番は後で Cedar の結果から確かめます。

やってみる

準備:交換を呼べるようにする

アプリクライアントの ExplicitAuthFlows に交換用のフローを足します。

idp.create_user_pool_client(
    UserPoolId=pool_id,
    ClientName="jy-agent",
    GenerateSecret=True,
    ExplicitAuthFlows=[
        "ALLOW_TOKEN_EXCHANGE_IMPERSONATION",
        "ALLOW_TOKEN_EXCHANGE_DELEGATION",
        "ALLOW_REFRESH_TOKEN_AUTH",
    ],
    AllowedOAuthFlows=["client_credentials"],
    AllowedOAuthScopes=["jy-gateway/kb.read"],
    AllowedOAuthFlowsUserPoolClient=True,
)

新しい API の GetDerivedToken は、検証時点の botocore(1.44.3)にはまだ入っていませんでした。なので token endpoint を HTTP で直接叩いています。

def exchange(subject_token, audience, actor_token=None):
    data = {
        "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
        "subject_token": subject_token,
        "subject_token_type": "urn:ietf:params:oauth:token-type:access_token",
        "audience": audience,
    }
    if actor_token:  # delegation
        data["actor_token"] = actor_token
        data["actor_token_type"] = "urn:ietf:params:oauth:token-type:access_token"
    return post_form(f"{domain}/oauth2/token", data, basic_auth=(agent_id, agent_secret))

ステップ1:交換したトークンの中身を見る

user-a のトークンを delegation で audience=jy-gateway に交換すると、こうなりました(抜粋)。

{
  "sub": "<user-a の sub>",
  "aud": "jy-gateway",
  "client_id": "<agent のクライアントID>",
  "origin_jti": "<元トークンと同じ>",
  "act": {
    "sub": "<agent のクライアントID>",
    "client_id": "<agent のクライアントID>",
    "iss": "https://cognito-idp.ap-northeast-1.amazonaws.com/<pool>",
    "token_type": "urn:ietf:params:oauth:token-type:access_token"
  }
}

act は delegation のときだけ付きます。ドキュメントの例は sub だけでしたが、実際は client_id や iss まで入っていました。

ほかに気づいた点を表にまとめます。

観点 結果
exp 元トークンの exp のまま。交換しても有効期限は延びない
scope API サインインのトークンを元にするとクレームごと無い
失効 AdminUserGlobalSignOut の後は交換が 400 になる。失効は交換時に効く
audience なし 200 で返るが、aud の無いトークンになる

ステップ2:交換を AgentCore Identity に任せる

ステップ1では token endpoint を直接叩きました。これだとエージェントのコードに agent クライアントのシークレットを持たせることになります。

AgentCore Identity の OBO を使うと、シークレットは credential provider の中に置いたまま、交換だけを頼めます。

credential provider は CustomOauth2 で作り、onBehalfOfTokenExchangeConfig を付けます。delegation にしたいときは actorTokenContent を M2M にします。

ctl.create_oauth2_credential_provider(
    name="jy-obo-m2m",
    credentialProviderVendor="CustomOauth2",
    oauth2ProviderConfigInput={"customOauth2ProviderConfig": {
        "oauthDiscovery": {"discoveryUrl": f"{issuer}/.well-known/openid-configuration"},
        "clientId": agent_id,
        "clientSecret": agent_secret,
        "clientAuthenticationMethod": "CLIENT_SECRET_BASIC",
        "onBehalfOfTokenExchangeConfig": {
            "grantType": "TOKEN_EXCHANGE",
            "tokenExchangeGrantTypeConfig": {
                "actorTokenContent": "M2M",  # impersonation なら "NONE"
                "actorTokenScopes": ["jy-gateway/kb.read"],
            },
        },
    }},
)

エージェント側では、ワークロードトークンを使って交換を頼みます。Runtime の入口を JWT 認証にしておくと、Runtime がユーザーのトークンからワークロードトークンを作って、エージェントに渡してくれます。

from bedrock_agentcore.runtime.context import BedrockAgentCoreContext

wat = BedrockAgentCoreContext.get_workload_access_token()
r = dp.get_resource_oauth2_token(
    workloadIdentityToken=wat,
    resourceCredentialProviderName="jy-obo-m2m",
    oauth2Flow="ON_BEHALF_OF_TOKEN_EXCHANGE",
    scopes=[],
    audiences=["jy-gateway"],
    customParameters={"subject_token_type": "urn:ietf:params:oauth:token-type:access_token"},
)

ここで customParameters の subject_token_type が肝でした。

ケース 結果
既定のまま ValidationException: Token exchange failed with HTTP status 400
subject_token_type を access_token に上書き 成功。aud=jy-gateway、client_id は agent
上書き+audiences=["jy-other"] 成功。aud=jy-other
actor を M2M にして上書き 成功。act 付き(ステップ1の delegation と同じ形)

Identity は既定で subject_token_type に ...:jwt を送るようで、Cognito はこれを受け付けません。しかもエラーには Cognito 側の理由が出てこないので、既定のままだと原因が分かりません...

ドキュメントも少し食い違っていて、OBO のページは「customParameters で上書きできる」と書いている一方、SDK リファレンスの customParameters の説明は「上書きしない」と読めます。実際に試すと、上書きできました。

3つ目のケースも大事です。audiences に何を書いても、そのまま交換できてしまいます。 Identity に任せても宛先を縛ってくれるわけではないので、ステップ4の allowedAudience は外せません。

ステップ3:Runtime に載せて通しで動かす

ここまでのエージェント側のコードを Runtime にデプロイして、ユーザーのトークンで呼び出してみました。Runtime の入口は Cognito の JWT 認証にして、Authorization ヘッダーもエージェントに渡すようにしています。

ctl.create_agent_runtime(
    agentRuntimeName="jy_obo_agent",
    # ...(コードの場所や実行ロールは省略)
    authorizerConfiguration={"customJWTAuthorizer": {
        "discoveryUrl": f"{issuer}/.well-known/openid-configuration",
        "allowedClients": [web_client_id],
    }},
    requestHeaderConfiguration={"requestHeaderAllowlist": ["Authorization"]},
)

実行ロールには、ログの権限に加えて GetWorkloadAccessToken*・GetResourceOauth2Token と、credential provider のシークレット(bedrock-agentcore-identity!*)を読む secretsmanager:GetSecretValue を付けました。workload identity は Runtime を作ると自動でできます。

ケース 結果
user-a(delegation) 200。act 付きのトークンで3文書
user-b(delegation) 200。経費規程だけ
user-a(impersonation) 200。act なしで3文書
subject_token_type を上書きしない 交換で 400(ローカルと同じ)
audiences=["jy-other"] 交換は通り、Gateway が 403
agent クライアントの M2M トークンで Runtime を呼ぶ Runtime の入口で 401

ローカルから API を叩いたときと同じ結果が、Runtime の上でもそのまま出ました。 エージェントには Authorization(ユーザーのトークンそのもの)と WorkloadAccessToken の両方が届いていました。

気になったのは失効です。user-a を AdminUserGlobalSignOut でサインアウトさせてから、同じトークンで Runtime を呼び直しました。

層 失効したトークンへの反応
Runtime の入口(JWT 認証) 通す(署名と client_id しか見ない)
Identity の OBO 前回の交換済みトークンを返す(jti が同じ)
Gateway → KB 200。3文書が返る

Identity は交換の結果をキャッシュしていて、Cognito に問い合わせに行きません。ステップ1で見た「失効は交換時に効く」が、ここでは効かないということになります。別の検証で Gateway の outbound に交換させたときは、交換済みトークンの exp(約1時間)まで渡り続けました。新しくサインインし直したトークンで呼ぶと、新しい交換が走りました。

ステップ4:Gateway の入口で aud を縛る

Gateway は allowedAudience=["jy-gateway"] だけにしました。いろいろなトークンを投げてみます。

入口に来たトークン 結果
元のユーザートークン(aud なし) 403 insufficient_scope
交換済み、aud=jy-gateway 通過
交換済み、aud=jy-other 403 insufficient_scope
エージェントの M2M トークン(ユーザーなし) 403 insufficient_scope
交換済み、aud なし 403 insufficient_scope

allowedAudience 1行で、元トークン・別宛て・ユーザー不在の M2M をまとめて落とせました。

allowedClients=[agent] だけだと、エージェントの M2M トークンも同じ client_id なので入れてしまいます。また、agent クライアントは許可していない resource server 宛てにも交換できてしまったので、宛先は受け取る側で縛るのが前提になります。

ステップ5:interceptor と KB の ACL で絞る

interceptor の中身は、検証済みトークンの email で userContext を上書きするだけです。

args["userContext"] = {"userId": claims.get("email") or "__no_identity__@invalid"}

email はアクセストークンに標準では載らないので、pre token generation トリガー(V3_0)で足しています。このトリガーはトークン交換のときも呼ばれます(triggerSource は TokenGeneration_TokenExchange)。

if src == "TokenGeneration_TokenExchange" and attrs.get("email") == "user-blocked@example.com":
    raise Exception("token exchange denied for this user")
event["response"] = {"claimsAndScopeOverrideDetails": {
    "accessTokenGeneration": {"claimsToAddOrOverride": {"email": attrs.get("email", "")}},
}}

例外を投げれば、そのユーザーの交換だけを止めることもできました。

KB に「engineers の給与レンジ」を検索させた結果です。

ケース 返ってきた文書
user-a を交換 給与系2本+経費規程
user-b を交換 経費規程だけ
user-b を交換し、引数の userContext に user-a のメールを書く 経費規程だけ

3つ目が偽装です。interceptor のログを見ると、引数に書かれた user-a は捨てられ、トークンの user-b に置き換わっていました。

ここで一つ確かめておきたかったのが、KB を呼んでいるのは誰かです。Gateway ロールから bedrock:Retrieve を外すと、こうなりました。

User: arn:aws:sts::<account>:assumed-role/jy-gateway-role/gateway-session-invocation
is not authorized to perform: bedrock:Retrieve on resource: ...knowledge-base/<kb-id>

コネクタは Gateway の実行ロールで KB を呼んでいます。ユーザーのトークンは KB まで届きません。

つまり Managed KB の構成でトークン交換が効くのは「エージェント → Gateway」の1段目だけで、ユーザーの絞り込みは Gateway の中で決めた userContext に任されている、ということになります。

ステップ6:Cedar で act を使う

最後に、AgentCore Policy(Cedar)で交換済みトークンのクレームが使えるかを見ました。

JWT のクレームは principal のタグになります。act のようなオブジェクトは JSON 文字列のタグになるので、like で部分一致を取ります。

// エージェント経由(delegation)のときだけ Retrieve を許可
permit (principal, action == AgentCore::Action::"managedkb___Retrieve", resource == AgentCore::Gateway::"<arn>")
when { principal.hasTag("act") && principal.getTag("act") like "*\"client_id\":\"<agent のクライアントID>\"*" };

// 引数の userContext がトークンの email と違えば拒否
forbid (principal, action == AgentCore::Action::"managedkb___Retrieve", resource == AgentCore::Gateway::"<arn>")
unless { principal.hasTag("email") && context.input has userContext && context.input.userContext has userId
         && context.input.userContext.userId == principal.getTag("email") };

hasTag を先に書いておかないと、タグが無いトークンで評価エラーになるので注意です。

interceptor あり/なしの Gateway を2つ作って比べました。

image.png

ケース interceptor あり interceptor なし
impersonation(act なし) 拒否(denied by default) 拒否(denied by default)
delegation、userContext なし 200(3文書) 拒否(forbid)
delegation の user-b、userContext に user-a(偽装) 200(経費規程だけ) 拒否(forbid)
delegation の user-b、userContext に user-b 200(経費規程だけ) 200(経費規程だけ)
tools/list(impersonation) ツールが0個 ツールが0個

ここから読み取れることは3つです。

  • impersonation は act タグ自体が作られないので、既定拒否に落ちます。 「エージェント経由の呼び出しだけ許可」が Cedar で書けます
  • 評価順は interceptor → Policy です。 interceptor ありの側で、userContext を書かなかった呼び出しが forbid に掛からなかったのは、注入後の値で評価されているからです

あと地味に嬉しかったのが、Policy の拒否メッセージには止めたポリシーの名前が出ることです(exceptionLevel=DEBUG のとき)。入口の insufficient_scope 一択よりだいぶ追いやすいです。

さいごに

トークン交換を挟むと、Gateway の入口で「誰の代わりに・どこ宛てに」を aud と act で判断できるようになります。特に delegation にしておけば、Cedar で「エージェント経由のときだけ」を書けるのが大きいと感じました。

一方で、Managed KB の構成だとユーザーのトークンは KB まで届きません。KB 側の絞り込みは、結局 Gateway の中で決める userContext が頼りです。トークン交換は入口を固めるもので、interceptor と Cedar の二重の守りを置き換えるものではない、と捉えるべきだと思います。

参考

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?