

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# AWS SDK を使用した Rust での Amazon Verified Permissions の実装
<a name="code-samples-rust"></a>

このトピックでは、 SDK を使用して Rust で Amazon Verified Permissions を実装する AWS 実例を示します。この例では、ユーザーが写真を表示できるかどうかをテストできる認可モデルを開発する方法を示します。サンプルコードは、 の [aws-sdk-verifiedpermissions](https://docs.rs/aws-sdk-verifiedpermissions/latest/aws_sdk_verifiedpermissions/) クレートを使用します。これは[AWS SDK for Rust](https://github.com/awslabs/aws-sdk-rust)、 を操作するための堅牢なツールセットを提供します AWS のサービス。

## 前提条件
<a name="rust-prereqs"></a>

 開始する前に、システムに [AWS CLI](https://aws.amazon.com/cli/) が設定されており、Rust に精通していることを確認してください。
+ のインストール手順については AWS CLI、[AWS 「CLI インストールガイド](https://docs.aws.amazon.com//cli/latest/userguide/getting-started-install.html)」を参照してください。
+ の設定手順については AWS CLI、[「」の「 の設定 AWS CLI](https://docs.aws.amazon.com//cli/latest/userguide/cli-configure-quickstart.html)」および[「 の設定と認証情報ファイルの設定 AWS CLI](https://docs.aws.amazon.com//cli/latest/userguide/cli-configure-profiles.html)」を参照してください。
+ Rust の詳細については、[rust-lang.org](https://www.rust-lang.org/) および [AWS SDK for Rust デベロッパーガイド](https://docs.aws.amazon.com//sdk-for-rust/latest/dg/welcome.html)を参照してください。

環境の準備ができたら、Rust で Verified Permissions を実装する方法について説明します。

## サンプルコードをテストする
<a name="rust-code"></a>

サンプルコードは以下を実行します。
+ と通信するように SDK クライアントを設定します AWS
+ [ポリシーストア](policy-stores.md)を作成します。
+ [スキーマ](schema.md)を追加してポリシーストアの構造を定義します。
+ 承認リクエストをチェックする[ポリシー](policies.md)を追加します
+ テスト[認可リクエスト](authorization.md)を送信して、すべてが正しく設定されていることを確認します

**サンプルコードをテストするには**

1. Rust プロジェクトを作成します。

1. の既存のコードを次のコード`main.rs`に置き換えます。

   ```
   use std::time::Duration;
   use std::thread::sleep;
   use aws_config::BehaviorVersion;
   use aws_sdk_verifiedpermissions::Client;
   use aws_sdk_verifiedpermissions::{
       operation::{
           create_policy::CreatePolicyOutput,
           create_policy_store::CreatePolicyStoreOutput,
           is_authorized::IsAuthorizedOutput,
           put_schema::PutSchemaOutput,
       },
       types::{
           ActionIdentifier, EntityIdentifier, PolicyDefinition, SchemaDefinition, StaticPolicyDefinition, ValidationSettings
       },
   };
   
   //Function that creates a policy store in the client that's passed
   async fn create_policy_store(client: &Client, valid_settings: &ValidationSettings)-> CreatePolicyStoreOutput {
       let policy_store = client.create_policy_store().validation_settings(valid_settings.clone()).send().await;
       return policy_store.unwrap();
   }
   
   //Function that adds a schema to the policy store in the client
   async fn put_schema(client: &Client, ps_id: &str, schema: &str) -> PutSchemaOutput {
       let schema = client.put_schema().definition(SchemaDefinition::CedarJson(schema.to_string())).policy_store_id(ps_id.to_string()).send().await;
       return schema.unwrap();
   }
   
   //Function that creates a policy in the policy store in the client
   async fn create_policy(client: &Client, ps_id: &str, policy_definition:&PolicyDefinition) -> CreatePolicyOutput {
       let create_policy = client.create_policy().definition(policy_definition.clone()).policy_store_id(ps_id).send().await;
       return create_policy.unwrap();
   }
   
   //Function that tests the authorization request to the policy store in the client
   async fn authorize(client: &Client, ps_id: &str, principal: &EntityIdentifier, action: &ActionIdentifier, resource: &EntityIdentifier) -> IsAuthorizedOutput {
       let is_auth = client.is_authorized().principal(principal.to_owned()).action(action.to_owned()).resource(resource.to_owned()).policy_store_id(ps_id).send().await;
       return is_auth.unwrap();
   }
   
   #[::tokio::main]
   async fn main() -> Result<(), aws_sdk_verifiedpermissions::Error> {
   
   //Set up SDK client
       let config = aws_config::load_defaults(BehaviorVersion::latest()).await;
       let client = aws_sdk_verifiedpermissions::Client::new(&config);
   
   //Create a policy store
       let valid_settings = ValidationSettings::builder()
       .mode({aws_sdk_verifiedpermissions::types::ValidationMode::Strict
       })
       .build()
       .unwrap();
       let policy_store = create_policy_store(&client, &valid_settings).await;
       println!(
       "Created Policy store with ID: {:?}",
       policy_store.policy_store_id
       );
   
   //Add schema to policy store
       let schema= r#"{
           "PhotoFlash": {
               "actions": {
                   "ViewPhoto": {
                       "appliesTo": {
                           "context": {
                               "type": "Record",
                               "attributes": {}
                           },
                           "principalTypes": [
                               "User"
                           ],
                           "resourceTypes": [
                               "Photo"
                           ]
                       },
                       "memberOf": []
                   }
               },
               "entityTypes": {
                   "Photo": {
                       "memberOfTypes": [],
                       "shape": {
                           "type": "Record",
                           "attributes": {
                               "IsPrivate": {
                                   "type": "Boolean"
                               }
                           }
                       }
                   },
                   "User": {
                       "memberOfTypes": [],
                       "shape": {
                           "attributes": {},
                           "type": "Record"
                       }
                   }
               }
           }
       }"#;
       let put_schema = put_schema(&client, &policy_store.policy_store_id, schema).await;
       println!(
           "Created Schema with Namespace: {:?}",
           put_schema.namespaces
       ); 
   
   //Create policy
       let policy_text = r#"
           permit (
               principal in PhotoFlash::User::"alice",
               action == PhotoFlash::Action::"ViewPhoto",
               resource == PhotoFlash::Photo::"VacationPhoto94.jpg"
           );
           "#;
       let policy_definition = PolicyDefinition::Static(StaticPolicyDefinition::builder().statement(policy_text).build().unwrap()); 
       let policy = create_policy(&client, &policy_store.policy_store_id, &policy_definition).await;
       println!(
           "Created Policy with ID: {:?}",
           policy.policy_id
       ); 
   
   //Break to make sure the resources are created before testing authorization
       sleep(Duration::new(2, 0));
   
   //Test authorization
       let principal= EntityIdentifier::builder().entity_id("alice").entity_type("PhotoFlash::User").build().unwrap();
       let action = ActionIdentifier::builder().action_type("PhotoFlash::Action").action_id("ViewPhoto").build().unwrap();
       let resource = EntityIdentifier::builder().entity_id("VacationPhoto94.jpg").entity_type("PhotoFlash::Photo").build().unwrap();
       let auth = authorize(&client, &policy_store.policy_store_id, &principal, &action, &resource).await;
       println!(
           "Decision: {:?}",
           auth.decision
           );
           println!(
           "Policy ID: {:?}",
           auth.determining_policies
           );
        Ok(())   
   }
   ```

1. ターミナルに `cargo run` を入力してコードを実行します。

コードが正しく実行されると、ターミナルに決定ポリシーのポリシー ID が`Decision: Allow`続きます。これは、ポリシーストアが正常に作成され、 AWS SDK for Rust を使用してテストされたことを意味します。

## リソースをクリーンアップする
<a name="rust-clean-up"></a>

ポリシーストアの探索が完了したら、削除します。

**ポリシーストアを削除するには**  
`delete-policy-store` オペレーションを使用してポリシーストアを削除し、 を削除するポリシーストア ID `PSEXAMPLEabcdefg111111`に置き換えます。

```
$ aws verifiedpermissions delete-policy-store \
    --policy-store-id PSEXAMPLEabcdefg111111
```

このコマンドが成功した場合、出力は生成されません。