-
Notifications
You must be signed in to change notification settings - Fork 7
feat: Add access rule CRD to appcred provider #806
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mashawes
wants to merge
3
commits into
openstack-experimental:main
Choose a base branch
from
mashawes:appcred-access-rule
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
44 changes: 44 additions & 0 deletions
44
crates/appcred-driver-sql/src/application_credential/access_rule.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
| // | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| //! # Application credential access rule database backend. | ||
|
|
||
| mod create; | ||
| mod delete; | ||
| mod get; | ||
| mod list; | ||
|
|
||
| pub use create::create; | ||
| pub use delete::delete; | ||
| pub use get::get; | ||
| pub use list::list; | ||
|
|
||
| #[cfg(test)] | ||
| pub(crate) mod tests { | ||
| use crate::entity::access_rule; | ||
|
|
||
| /// Build a mock `access_rule::Model` for tests. | ||
| pub fn get_access_rule_mock<S: AsRef<str>>( | ||
| internal_id: i32, | ||
| external_id: S, | ||
| ) -> access_rule::Model { | ||
| access_rule::Model { | ||
| id: internal_id, | ||
| external_id: Some(external_id.as_ref().into()), | ||
| path: Some("/v2.1/servers".into()), | ||
| method: Some("POST".into()), | ||
| service: Some("compute".into()), | ||
| user_id: Some("user_id".into()), | ||
| } | ||
| } | ||
| } |
77 changes: 77 additions & 0 deletions
77
crates/appcred-driver-sql/src/application_credential/access_rule/create.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
| // | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| //! # Create access rule | ||
|
|
||
| use sea_orm::ConnectionTrait; | ||
| use sea_orm::entity::*; | ||
| use uuid::Uuid; | ||
|
|
||
| use openstack_keystone_core::application_credential::ApplicationCredentialProviderError; | ||
| use openstack_keystone_core::error::DbContextExt; | ||
| use openstack_keystone_core_types::application_credential::*; | ||
|
|
||
| use crate::entity::access_rule as db_access_rule; | ||
|
|
||
| /// Create a standalone access rule owned by a user. | ||
| /// | ||
| /// # Parameters | ||
| /// - `db`: The database connection. | ||
| /// - `user_id`: The ID of the user owning the access rule. | ||
| /// - `rule`: The access rule to create. | ||
| /// | ||
| /// # Returns | ||
| /// A `Result` containing the created `AccessRule` or an `Error`. | ||
| pub async fn create<U: AsRef<str>>( | ||
| db: &impl ConnectionTrait, | ||
| user_id: U, | ||
| rule: AccessRuleCreate, | ||
| ) -> Result<AccessRule, ApplicationCredentialProviderError> { | ||
| db_access_rule::ActiveModel { | ||
| id: NotSet, | ||
| method: Set(rule.method), | ||
| path: Set(rule.path), | ||
| service: Set(rule.service), | ||
| external_id: Set(Some(rule.id.unwrap_or(Uuid::new_v4().simple().to_string()))), | ||
| user_id: Set(Some(user_id.as_ref().to_string())), | ||
| } | ||
| .insert(db) | ||
| .await | ||
| .context("persisting access rule")? | ||
| .try_into() | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use sea_orm::{DatabaseBackend, MockDatabase}; | ||
|
|
||
| use super::super::tests::get_access_rule_mock; | ||
| use super::*; | ||
|
|
||
| #[tokio::test] | ||
| async fn test_create() { | ||
| let db = MockDatabase::new(DatabaseBackend::Postgres) | ||
| .append_query_results([vec![get_access_rule_mock(1, "rule_id")]]) | ||
| .into_connection(); | ||
|
|
||
| let req = AccessRuleCreate { | ||
| id: Some("rule_id".into()), | ||
| method: Some("POST".into()), | ||
| path: Some("/v2.1/servers".into()), | ||
| service: Some("compute".into()), | ||
| }; | ||
|
|
||
| let result = create(&db, "user_id", req).await; | ||
| assert!(result.is_ok(), "create failed: {:?}", result.err()); | ||
| } | ||
| } | ||
133 changes: 133 additions & 0 deletions
133
crates/appcred-driver-sql/src/application_credential/access_rule/delete.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
| // | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| //! # Delete access rule | ||
|
|
||
| use sea_orm::ConnectionTrait; | ||
| use sea_orm::entity::*; | ||
| use sea_orm::query::*; | ||
|
|
||
| use openstack_keystone_core::application_credential::ApplicationCredentialProviderError; | ||
| use openstack_keystone_core::error::DbContextExt; | ||
|
|
||
| use crate::entity::{ | ||
| access_rule as db_access_rule, | ||
| application_credential_access_rule as db_application_credential_access_rule, | ||
| prelude::{ | ||
| AccessRule as DbAccessRule, | ||
| ApplicationCredentialAccessRule as DbApplicationCredentialAccessRule, | ||
| }, | ||
| }; | ||
|
|
||
| /// Delete a user's access rule by its (external) ID. | ||
| /// | ||
| /// The access rule must not be referenced by any application credential; | ||
| /// otherwise an `AccessRuleInUse` error is returned (deleting it would silently | ||
| /// strip the credential's restriction). | ||
| /// | ||
| /// # Parameters | ||
| /// - `db`: The database connection. | ||
| /// - `user_id`: The ID of the user owning the access rule. | ||
| /// - `id`: The (external) ID of the access rule. | ||
| /// | ||
| /// # Returns | ||
| /// A `Result` containing `()` or an `Error` (`AccessRuleNotFound` if no such | ||
| /// rule exists, `AccessRuleInUse` if it is still attached to a credential). | ||
| pub async fn delete<U: AsRef<str>, I: AsRef<str>>( | ||
|
mashawes marked this conversation as resolved.
|
||
| db: &impl ConnectionTrait, | ||
| user_id: U, | ||
| id: I, | ||
| ) -> Result<(), ApplicationCredentialProviderError> { | ||
| let rule = DbAccessRule::find() | ||
| .filter(db_access_rule::Column::ExternalId.eq(id.as_ref())) | ||
| .filter(db_access_rule::Column::UserId.eq(user_id.as_ref())) | ||
| .one(db) | ||
| .await | ||
| .context("fetching access rule for delete")? | ||
| .ok_or_else(|| { | ||
| ApplicationCredentialProviderError::AccessRuleNotFound(id.as_ref().to_string()) | ||
| })?; | ||
|
|
||
| // Refuse to delete a rule that is still attached to an application | ||
| // credential. | ||
| let in_use = DbApplicationCredentialAccessRule::find() | ||
| .filter(db_application_credential_access_rule::Column::AccessRuleId.eq(rule.id)) | ||
| .all(db) | ||
| .await | ||
| .context("checking whether access rule is in use")?; | ||
| if !in_use.is_empty() { | ||
| return Err(ApplicationCredentialProviderError::AccessRuleInUse( | ||
| id.as_ref().to_string(), | ||
| )); | ||
| } | ||
|
|
||
| rule.delete(db).await.context("deleting access rule")?; | ||
| Ok(()) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use sea_orm::{DatabaseBackend, MockDatabase, MockExecResult}; | ||
|
|
||
| use super::super::tests::get_access_rule_mock; | ||
| use super::*; | ||
| use crate::entity::access_rule; | ||
|
|
||
| #[tokio::test] | ||
| async fn test_delete() { | ||
| let db = MockDatabase::new(DatabaseBackend::Postgres) | ||
| // 1. fetch the existing rule | ||
| .append_query_results([vec![get_access_rule_mock(1, "rule_id")]]) | ||
| // 2. usage check returns no relations | ||
| .append_query_results([Vec::<db_application_credential_access_rule::Model>::new()]) | ||
| // 3. the DELETE | ||
| .append_exec_results([MockExecResult { | ||
| rows_affected: 1, | ||
| ..Default::default() | ||
| }]) | ||
| .into_connection(); | ||
|
|
||
| let result = delete(&db, "user_id", "rule_id").await; | ||
| assert!(result.is_ok(), "delete failed: {:?}", result.err()); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn test_delete_not_found() { | ||
| let db = MockDatabase::new(DatabaseBackend::Postgres) | ||
| .append_query_results([Vec::<access_rule::Model>::new()]) | ||
| .into_connection(); | ||
|
|
||
| let result = delete(&db, "user_id", "missing").await; | ||
| assert!(matches!( | ||
| result, | ||
| Err(ApplicationCredentialProviderError::AccessRuleNotFound(_)) | ||
| )); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn test_delete_in_use() { | ||
| let db = MockDatabase::new(DatabaseBackend::Postgres) | ||
| .append_query_results([vec![get_access_rule_mock(1, "rule_id")]]) | ||
| .append_query_results([vec![db_application_credential_access_rule::Model { | ||
| application_credential_id: 1, | ||
| access_rule_id: 1, | ||
| }]]) | ||
| .into_connection(); | ||
|
|
||
| let result = delete(&db, "user_id", "rule_id").await; | ||
| assert!(matches!( | ||
| result, | ||
| Err(ApplicationCredentialProviderError::AccessRuleInUse(_)) | ||
| )); | ||
| } | ||
| } | ||
86 changes: 86 additions & 0 deletions
86
crates/appcred-driver-sql/src/application_credential/access_rule/get.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
| // | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| //! # Get access rule | ||
|
|
||
| use sea_orm::ConnectionTrait; | ||
| use sea_orm::entity::*; | ||
| use sea_orm::query::*; | ||
|
|
||
| use openstack_keystone_core::application_credential::ApplicationCredentialProviderError; | ||
| use openstack_keystone_core::error::DbContextExt; | ||
| use openstack_keystone_core_types::application_credential::*; | ||
|
|
||
| use crate::entity::{access_rule as db_access_rule, prelude::AccessRule as DbAccessRule}; | ||
|
|
||
| /// Get a user's access rule by its (external) ID. | ||
| /// | ||
| /// # Parameters | ||
| /// - `db`: The database connection. | ||
| /// - `user_id`: The ID of the user owning the access rule. | ||
| /// - `id`: The (external) ID of the access rule. | ||
| /// | ||
| /// # Returns | ||
| /// A `Result` containing an `Option` with the `AccessRule` if found, or an | ||
| /// `Error`. | ||
| pub async fn get<U: AsRef<str>, I: AsRef<str>>( | ||
| db: &impl ConnectionTrait, | ||
| user_id: U, | ||
| id: I, | ||
| ) -> Result<Option<AccessRule>, ApplicationCredentialProviderError> { | ||
| DbAccessRule::find() | ||
| .filter(db_access_rule::Column::ExternalId.eq(id.as_ref())) | ||
| .filter(db_access_rule::Column::UserId.eq(user_id.as_ref())) | ||
| .one(db) | ||
| .await | ||
| .context("fetching access rule by id")? | ||
| .map(TryInto::try_into) | ||
| .transpose() | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use sea_orm::{DatabaseBackend, MockDatabase}; | ||
|
|
||
| use super::super::tests::get_access_rule_mock; | ||
| use super::*; | ||
| use crate::entity::access_rule; | ||
|
|
||
| #[tokio::test] | ||
| async fn test_get() { | ||
| let db = MockDatabase::new(DatabaseBackend::Postgres) | ||
| .append_query_results([vec![get_access_rule_mock(1, "rule_id")]]) | ||
| .into_connection(); | ||
|
|
||
| let result = get(&db, "user_id", "rule_id").await.unwrap(); | ||
| assert_eq!( | ||
| result, | ||
| Some(AccessRule { | ||
| id: "rule_id".into(), | ||
| path: Some("/v2.1/servers".into()), | ||
| method: Some("POST".into()), | ||
| service: Some("compute".into()), | ||
| }) | ||
| ); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn test_get_not_found() { | ||
| let db = MockDatabase::new(DatabaseBackend::Postgres) | ||
| .append_query_results([Vec::<access_rule::Model>::new()]) | ||
| .into_connection(); | ||
|
|
||
| let result = get(&db, "user_id", "missing").await.unwrap(); | ||
| assert_eq!(result, None); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we should extend the AccessRuleCreate to have
user_id: String