AWS SDK를 사용하여 Rust에서 Amazon Verified Permissions 구현 - Amazon Verified Permissions

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

AWS SDK를 사용하여 Rust에서 Amazon Verified Permissions 구현

이 주제에서는 SDK를 사용하여 Rust에서 Amazon Verified Permissions를 구현하는 실제 예제를 AWS 제공합니다. 이 예제에서는 사용자가 사진을 볼 수 있는지 테스트할 수 있는 권한 부여 모델을 개발하는 방법을 보여줍니다. 샘플 코드는의 aws-sdk-verifiedpermissions 크레이트를 사용합니다. AWS SDK for Rust이 크레이트는와 상호 작용하기 위한 강력한 도구 세트를 제공합니다 AWS 서비스.

사전 조건

시작하기 전에 시스템에 AWS CLI가 구성되어 있고 Rust에 익숙해야 합니다.

환경을 준비하면서 Rust에서 Verified Permissions를 구현하는 방법을 살펴보겠습니다.

샘플 코드 테스트

샘플 코드는 다음을 수행합니다.

  • 와 통신할 SDK 클라이언트를 설정합니다. AWS

  • 정책 스토어를 생성합니다.

  • 스키마를 추가하여 정책 스토어의 구조를 정의합니다.

  • 권한 부여 요청을 확인하는 정책을 추가합니다.

  • 테스트 권한 부여 요청을 전송하여 모든 항목이 올바르게 설정되었는지 확인합니다.

샘플 코드를 테스트하려면
  1. Rust 프로젝트를 생성합니다.

  2. 의 기존 코드를 다음 코드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(()) }
  3. 터미널에 cargo run를 입력하여 코드를 실행합니다.

코드가 올바르게 실행되면 터미널에 결정 정책의 정책 ID가 Decision: Allow 표시됩니다. 즉, 정책 스토어를 성공적으로 생성하고 AWS SDK for Rust를 사용하여 테스트했습니다.

리소스 정리

정책 스토어 탐색을 완료한 후 삭제합니다.

정책 저장소 삭제

를 삭제하려는 정책 스토어 IDPSEXAMPLEabcdefg111111로 바꾸는 delete-policy-store 작업을 사용하여 정책 스토어를 삭제할 수 있습니다.

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

성공하면 이 명령은 출력을 생성하지 않습니다.