Skip to content
Merged
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
341 changes: 25 additions & 316 deletions src/federation/backends/sql/auth_state.rs

Large diffs are not rendered by default.

98 changes: 98 additions & 0 deletions src/federation/backends/sql/auth_state/create.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// 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

use sea_orm::DatabaseConnection;
use sea_orm::entity::*;

use crate::config::Config;
use crate::db::entity::federated_auth_state as db_federated_auth_state;
use crate::federation::backends::error::FederationDatabaseError;
use crate::federation::types::*;

pub async fn create(
_conf: &Config,
db: &DatabaseConnection,
rec: AuthState,
) -> Result<AuthState, FederationDatabaseError> {
let scope: Option<serde_json::Value> = if let Some(scope) = rec.scope {
Some(serde_json::to_value(&scope)?)
} else {
None
};
let entry = db_federated_auth_state::ActiveModel {
state: Set(rec.state.clone()),
idp_id: Set(rec.idp_id.clone()),
mapping_id: Set(rec.mapping_id.clone()),
nonce: Set(rec.nonce.clone()),
redirect_uri: Set(rec.redirect_uri.clone()),
pkce_verifier: Set(rec.pkce_verifier.clone()),
expires_at: Set(rec.expires_at.naive_utc()),
requested_scope: scope.map(Set).unwrap_or(NotSet).into(),
};

let db_entry: db_federated_auth_state::Model = entry.insert(db).await?;

db_entry.try_into()
}

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

use crate::config::Config;

use super::super::tests::get_auth_state_mock;
use super::*;

#[tokio::test]
async fn test_create() {
let db = MockDatabase::new(DatabaseBackend::Postgres)
.append_query_results([vec![get_auth_state_mock("state")]])
.into_connection();
let config = Config::default();

let req = AuthState {
idp_id: "idp".into(),
mapping_id: "mapping".into(),
state: "state".into(),
nonce: "nonce".into(),
redirect_uri: "redirect_uri".into(),
pkce_verifier: "pkce_verifier".into(),
expires_at: DateTime::<Utc>::default(),
scope: None,
};

assert_eq!(
create(&config, &db, req).await.unwrap(),
get_auth_state_mock("state").try_into().unwrap()
);
assert_eq!(
db.into_transaction_log(),
[Transaction::from_sql_and_values(
DatabaseBackend::Postgres,
r#"INSERT INTO "federated_auth_state" ("idp_id", "mapping_id", "state", "nonce", "redirect_uri", "pkce_verifier", "expires_at") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "idp_id", "mapping_id", "state", "nonce", "redirect_uri", "pkce_verifier", "expires_at", "requested_scope""#,
[
"idp".into(),
"mapping".into(),
"state".into(),
"nonce".into(),
"redirect_uri".into(),
"pkce_verifier".into(),
NaiveDateTime::default().into(),
]
),]
);
}
}
107 changes: 107 additions & 0 deletions src/federation/backends/sql/auth_state/delete.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// 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

use chrono::Utc;
use sea_orm::DatabaseConnection;
use sea_orm::entity::*;
use sea_orm::query::*;

use crate::config::Config;
use crate::db::entity::{
federated_auth_state as db_federated_auth_state,
prelude::FederatedAuthState as DbFederatedAuthState,
};
use crate::federation::backends::error::FederationDatabaseError;

pub async fn delete<S: AsRef<str>>(
_conf: &Config,
db: &DatabaseConnection,
id: S,
) -> Result<(), FederationDatabaseError> {
let res = DbFederatedAuthState::delete_by_id(id.as_ref())
.exec(db)
.await?;
if res.rows_affected == 1 {
Ok(())
} else {
Err(FederationDatabaseError::AuthStateNotFound(
id.as_ref().to_string(),
))
}
}

pub async fn delete_expired(
_conf: &Config,
db: &DatabaseConnection,
) -> Result<(), FederationDatabaseError> {
DbFederatedAuthState::delete_many()
.filter(db_federated_auth_state::Column::ExpiresAt.lt(Utc::now()))
.exec(db)
.await?;
Ok(())
}

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

use crate::config::Config;

use super::*;

#[tokio::test]
async fn test_delete() {
let db = MockDatabase::new(DatabaseBackend::Postgres)
.append_exec_results([MockExecResult {
rows_affected: 1,
..Default::default()
}])
.into_connection();
let config = Config::default();

delete(&config, &db, "state").await.unwrap();
assert_eq!(
db.into_transaction_log(),
[Transaction::from_sql_and_values(
DatabaseBackend::Postgres,
r#"DELETE FROM "federated_auth_state" WHERE "federated_auth_state"."state" = $1"#,
["state".into()]
),]
);
}

#[tokio::test]
async fn test_delete_expired() {
let db = MockDatabase::new(DatabaseBackend::Postgres)
.append_exec_results([MockExecResult {
rows_affected: 1,
..Default::default()
}])
.into_connection();
let config = Config::default();

delete_expired(&config, &db).await.unwrap();
for (l,r) in db.into_transaction_log().iter().zip([Transaction::from_sql_and_values(
DatabaseBackend::Postgres,
r#"DELETE FROM "federated_auth_state" WHERE "federated_auth_state"."expires_at" < $1"#,
[NaiveDateTime::default().into()]
),]) {
assert_eq!(
l.statements().iter().map(|x| x.sql.clone()).collect::<Vec<_>>(),
r.statements().iter().map(|x| x.sql.clone()).collect::<Vec<_>>()
);
}
}
}
76 changes: 76 additions & 0 deletions src/federation/backends/sql/auth_state/get.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// 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

use sea_orm::DatabaseConnection;
use sea_orm::entity::*;

use crate::config::Config;
use crate::db::entity::{
federated_auth_state as db_federated_auth_state,
prelude::FederatedAuthState as DbFederatedAuthState,
};
use crate::federation::backends::error::FederationDatabaseError;
use crate::federation::types::*;

pub async fn get<I: AsRef<str>>(
_conf: &Config,
db: &DatabaseConnection,
state: I,
) -> Result<Option<AuthState>, FederationDatabaseError> {
let select = DbFederatedAuthState::find_by_id(state.as_ref());

let entry: Option<db_federated_auth_state::Model> = select.one(db).await?;
entry.map(TryInto::try_into).transpose()
}

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

use crate::config::Config;

use super::super::tests::get_auth_state_mock;
use super::*;

#[tokio::test]
async fn test_get() {
let db = MockDatabase::new(DatabaseBackend::Postgres)
.append_query_results([vec![get_auth_state_mock("state")]])
.into_connection();
let config = Config::default();
assert_eq!(
get(&config, &db, "state").await.unwrap().unwrap(),
AuthState {
idp_id: "idp".into(),
mapping_id: "mapping".into(),
state: "state".into(),
nonce: "nonce".into(),
redirect_uri: "redirect_uri".into(),
pkce_verifier: "pkce_verifier".into(),
expires_at: DateTime::<Utc>::default(),
scope: None,
}
);

assert_eq!(
db.into_transaction_log(),
[Transaction::from_sql_and_values(
DatabaseBackend::Postgres,
r#"SELECT "federated_auth_state"."idp_id", "federated_auth_state"."mapping_id", "federated_auth_state"."state", "federated_auth_state"."nonce", "federated_auth_state"."redirect_uri", "federated_auth_state"."pkce_verifier", "federated_auth_state"."expires_at", "federated_auth_state"."requested_scope" FROM "federated_auth_state" WHERE "federated_auth_state"."state" = $1 LIMIT $2"#,
["state".into(), 1u64.into()]
),]
);
}
}
Loading
Loading