Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion crates/api-types/src/error_conv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,7 @@ impl From<CatalogProviderError> for KeystoneApiError {
impl From<ApplicationCredentialProviderError> for KeystoneApiError {
fn from(value: ApplicationCredentialProviderError) -> Self {
match value {
ApplicationCredentialProviderError::AuthenticationFailed => Self::UnauthorizedNoContext,
ApplicationCredentialProviderError::ApplicationCredentialNotFound(x) => {
Self::NotFound {
resource: "application_credential".into(),
Expand All @@ -319,7 +320,7 @@ impl From<ApplicationCredentialProviderError> for KeystoneApiError {
Self::BadRequest(err.to_string())
}
ApplicationCredentialProviderError::ApplicationCredentialExpired => {
Self::BadRequest("application credential has expired".into())
Self::UnauthorizedNoContext
}
ApplicationCredentialProviderError::AccessRuleInUse(_) => {
Self::Conflict("application credential access rule is in use".into())
Expand Down
91 changes: 91 additions & 0 deletions crates/api-types/src/v3/auth/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,13 @@ pub struct Identity {
#[cfg_attr(feature = "validate", validate(nested))]
pub totp: Option<TotpAuth>,

/// The application credential object, contains the authentication
/// information for application credential authentication.
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "builder", builder(default))]
#[cfg_attr(feature = "validate", validate(nested))]
pub application_credential: Option<ApplicationCredentialAuth>,

/// Catch-all for a method name not among the builtins above - e.g.
/// `identity.<plugin_name>` for a `mode = full_auth` dynamic auth
/// plugin (ADR 0025 §4). Bounded by the same overall request
Expand Down Expand Up @@ -395,6 +402,90 @@ fn validate_token_auth_secret(value: &TokenAuth) -> Result<(), validator::Valida
crate::common::validate_secret_length(&value.id, 1024)
}

/// The application credential object for authentication.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(
feature = "builder",
derive(derive_builder::Builder),
builder(
build_fn(error = "crate::error::BuilderError"),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also as mentioned below I would add here a Builder validator (https://docs.rs/derive_builder/latest/derive_builder/#pre-build-validation) to ensure id or name are present

setter(strip_option, into)
)
)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "validate", derive(validator::Validate))]
#[cfg_attr(
feature = "validate",
validate(schema(function = "validate_application_credential_auth_secret"))
)]
pub struct ApplicationCredentialAuth {
/// Application credential ID.
#[cfg_attr(feature = "builder", builder(default))]
#[cfg_attr(feature = "validate", validate(length(max = 64)))]
pub id: Option<String>,
/// Application credential name (alternative to ID, requires `user`).
#[cfg_attr(feature = "builder", builder(default))]
#[cfg_attr(feature = "validate", validate(length(max = 255)))]
pub name: Option<String>,
/// Application credential secret. Required for direct authentication,
/// absent when the payload is relabeled by a route-mode plugin.
/// Application credential secret.
#[cfg_attr(feature = "openapi", schema(value_type = String))]
#[serde(serialize_with = "crate::common::serialize_secret_string")]
pub secret: SecretString,
/// User reference, required when authenticating by name.
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "builder", builder(default))]
#[cfg_attr(feature = "validate", validate(nested))]
pub user: Option<ApplicationCredentialUser>,
}

#[cfg(feature = "validate")]
fn validate_application_credential_auth_secret(
value: &ApplicationCredentialAuth,
) -> Result<(), validator::ValidationError> {
crate::common::validate_secret_length(&value.secret, 255)
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(
feature = "builder",
derive(derive_builder::Builder),
builder(
build_fn(error = "crate::error::BuilderError", validate = "Self::validate"),
setter(strip_option, into)
)
)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "validate", derive(validator::Validate))]
pub struct ApplicationCredentialUser {
/// User ID.
#[cfg_attr(feature = "builder", builder(default))]
#[cfg_attr(feature = "validate", validate(length(max = 64)))]
pub id: Option<String>,
/// User name.
#[cfg_attr(feature = "builder", builder(default))]
#[cfg_attr(feature = "validate", validate(length(max = 255)))]
pub name: Option<String>,
/// User domain (needed when resolving by name).
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "builder", builder(default))]
#[cfg_attr(feature = "validate", validate(nested))]
pub domain: Option<Domain>,
}

#[cfg(feature = "builder")]
impl ApplicationCredentialUserBuilder {
fn validate(&self) -> Result<(), String> {
let has_id = self.id.as_ref().is_some_and(|v| v.is_some());
let has_name = self.name.as_ref().is_some_and(|v| v.is_some());
if !has_id && !has_name {
return Err("application credential user requires at least id or name".into());
}
Ok(())
}
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::IntoParams))]
#[cfg_attr(feature = "validate", derive(validator::Validate))]
Expand Down
2 changes: 2 additions & 0 deletions crates/appcred-driver-sql/src/application_credential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,12 @@ mod create;
mod delete;
mod get;
mod list;
mod verify;
pub use create::create;
pub use delete::delete;
pub use get::get;
pub use list::list;
pub use verify::verify_secret;
impl TryFrom<db_application_credential::Model> for ApplicationCredentialBuilder {
type Error = ApplicationCredentialProviderError;

Expand Down
138 changes: 138 additions & 0 deletions crates/appcred-driver-sql/src/application_credential/verify.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
// 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
//! # Verify application credential
use sea_orm::DatabaseConnection;
use sea_orm::entity::*;
use sea_orm::query::*;
use secrecy::SecretString;

use openstack_keystone_config::Config;
use openstack_keystone_core::application_credential::ApplicationCredentialProviderError;
use openstack_keystone_core::error::DbContextExt;
use openstack_keystone_password_hashing as password_hashing;

use crate::entity::{
application_credential as db_application_credential,
prelude::ApplicationCredential as DbApplicationCredential,
};

pub async fn verify_secret(
config: &Config,
db: &DatabaseConnection,
credential_id: &str,
secret: &SecretString,
) -> Result<(), ApplicationCredentialProviderError> {
let record = DbApplicationCredential::find()
.filter(db_application_credential::Column::Id.eq(credential_id))
.one(db)
.await
.context("looking up application credential for authentication")?
.ok_or(ApplicationCredentialProviderError::AuthenticationFailed)?;

// record is db_application_credential::Model, which has secret_hash
let matched = password_hashing::verify_password(config, secret, &record.secret_hash)
.await
.map_err(ApplicationCredentialProviderError::password_hash)?;

if !matched {
return Err(ApplicationCredentialProviderError::AuthenticationFailed);
}

Ok(())
}

#[cfg(test)]
mod tests {
use chrono::{DateTime, Utc};
use sea_orm::{DatabaseBackend, MockDatabase, Transaction};

use openstack_keystone_config::PasswordHashingAlgo;

use super::*;
use crate::entity::application_credential as db_application_credential;

fn make_app_cred_model(id: &str, secret_hash: &str) -> db_application_credential::Model {
db_application_credential::Model {
internal_id: 1,
id: id.to_string(),
name: "fake appcred".to_string(),
secret_hash: secret_hash.to_string(),
description: Some("description".to_string()),
user_id: "user_id".to_string(),
project_id: Some("project_id".to_string()),
expires_at: Some(DateTime::<Utc>::MIN_UTC.timestamp_micros()),
system: None,
unrestricted: Some(true),
}
}

#[tokio::test]
async fn test_verify_secret_success() {
let mut config = Config::default();
config.identity.password_hashing_algorithm = PasswordHashingAlgo::None;

let db = MockDatabase::new(DatabaseBackend::Postgres)
.append_query_results([vec![make_app_cred_model("app_cred_id", "test_secret")]])
.into_connection();

let result = verify_secret(&config, &db, "app_cred_id", &"test_secret".into()).await;

assert!(result.is_ok());

assert_eq!(
db.into_transaction_log(),
[Transaction::from_sql_and_values(
DatabaseBackend::Postgres,
r#"SELECT "application_credential"."internal_id", "application_credential"."id", "application_credential"."name", "application_credential"."secret_hash", "application_credential"."description", "application_credential"."user_id", "application_credential"."project_id", "application_credential"."expires_at", "application_credential"."system", "application_credential"."unrestricted" FROM "application_credential" WHERE "application_credential"."id" = $1 LIMIT $2"#,
["app_cred_id".into(), 1u64.into()]
)]
);
}

#[tokio::test]
async fn test_verify_secret_wrong_secret() {
let mut config = Config::default();
config.identity.password_hashing_algorithm = PasswordHashingAlgo::None;

let db = MockDatabase::new(DatabaseBackend::Postgres)
.append_query_results([vec![make_app_cred_model("app_cred_id", "test_secret")]])
.into_connection();

let result = verify_secret(&config, &db, "app_cred_id", &"wrong_secret".into()).await;

assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
ApplicationCredentialProviderError::AuthenticationFailed
));
}

#[tokio::test]
async fn test_verify_secret_not_found() {
let db = MockDatabase::new(DatabaseBackend::Postgres)
.append_query_results([Vec::<db_application_credential::Model>::new()])
.into_connection();

let mut config = Config::default();
config.identity.password_hashing_algorithm = PasswordHashingAlgo::None;

let result = verify_secret(&config, &db, "nonexistent_id", &"test_secret".into()).await;

assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
ApplicationCredentialProviderError::AuthenticationFailed
));
}
}
28 changes: 28 additions & 0 deletions crates/appcred-driver-sql/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
// SPDX-License-Identifier: Apache-2.0
//! # OpenStack Keystone Application Credential SQL driver

use secrecy::SecretString;
use std::sync::Arc;

use async_trait::async_trait;
Expand Down Expand Up @@ -195,6 +196,33 @@ impl ApplicationCredentialBackend for SqlBackend {
) -> Result<Vec<ApplicationCredential>, ApplicationCredentialProviderError> {
Ok(application_credential::list(&state.db.connection(), params).await?)
}

/// Verify an application credential's secret against the stored hash.
///
/// # Parameters
/// - `state`: The current service state.
/// - `credential_id`: The ID of the application credential.
/// - `secret`: The plaintext secret to verify.
///
/// # Returns
/// - `Ok(())` if the secret matches the stored hash.
/// - `Err(ApplicationCredentialProviderError::AuthenticationFailed)` if
/// the credential does not exist or the secret does not match.
async fn verify_application_credential_secret(
&self,
state: &ServiceState,
credential_id: &str,
secret: &SecretString,
) -> Result<(), ApplicationCredentialProviderError> {
let config = state.config_manager.config.read().await;
application_credential::verify_secret(
&config,
&state.db.connection(),
credential_id,
secret,
)
.await
}
}

#[async_trait]
Expand Down
Loading
Loading