diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index b9d22f910..eac4cc0a9 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -4,9 +4,9 @@ on: push: branches: - main - - 'release/**' + - "release/**" tags: - - 'v*' + - "v*" pull_request: concurrency: @@ -31,10 +31,7 @@ jobs: - name: Checkout the code uses: actions/checkout@v4.2.2 - - name: Setup OPA - uses: open-policy-agent/setup-opa@v2.2.0 - with: - version: 0.70.0 + - uses: ./.github/actions/build-policies - name: Setup Regal uses: StyraInc/setup-regal@v1 @@ -73,7 +70,6 @@ jobs: working-directory: ./frontend run: npm run lint - frontend-test: name: Run the frontend test suite runs-on: ubuntu-24.04 @@ -98,7 +94,6 @@ jobs: working-directory: ./frontend run: npm test - frontend-knip: name: Check the frontend for unused dependencies runs-on: ubuntu-24.04 @@ -123,7 +118,6 @@ jobs: working-directory: ./frontend run: npm run knip - rustfmt: name: Check Rust style runs-on: ubuntu-24.04 @@ -143,7 +137,6 @@ jobs: - name: Check style run: cargo fmt --all -- --check - cargo-deny: name: Run `cargo deny` checks runs-on: ubuntu-24.04 @@ -161,7 +154,8 @@ jobs: - name: Run `cargo-deny` uses: EmbarkStudios/cargo-deny-action@v2.0.5 - + with: + rust-version: stable check-schema: name: Check schema @@ -203,7 +197,6 @@ jobs: exit 1 fi - clippy: name: Run Clippy needs: [rustfmt, opa-lint] @@ -217,18 +210,11 @@ jobs: uses: actions/checkout@v4.2.2 - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@1.84.0 + uses: dtolnay/rust-toolchain@1.85.0 with: components: clippy - - name: Setup OPA - uses: open-policy-agent/setup-opa@v2.2.0 - with: - version: 0.64.1 - - - name: Compile OPA policies - working-directory: ./policies - run: make + - uses: ./.github/actions/build-policies - name: Setup sccache uses: mozilla-actions/sccache-action@v0.0.7 @@ -237,7 +223,6 @@ jobs: run: | cargo clippy --workspace --tests --bins --lib -- -D warnings - compile-test-artifacts: name: Compile test artifacts runs-on: ubuntu-24.04 @@ -263,7 +248,7 @@ jobs: - name: Build and archive tests run: cargo nextest archive --workspace --archive-file nextest-archive.tar.zst env: - SQLX_OFFLINE: '1' + SQLX_OFFLINE: "1" - name: Upload archive to workflow uses: actions/upload-artifact@v4.6.0 @@ -271,7 +256,6 @@ jobs: name: nextest-archive path: nextest-archive.tar.zst - test: name: Run test suite with Rust stable needs: [rustfmt, opa-lint, compile-test-artifacts] @@ -303,7 +287,9 @@ jobs: - name: Checkout the code uses: actions/checkout@v4.2.2 - - run: mkdir -p ~/.cargo/bin + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + - name: Install nextest uses: taiki-e/install-action@v2 with: diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index a099dc887..2a6f50c94 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -2,9 +2,9 @@ name: Coverage on: push: - branches: [ main ] + branches: [main] pull_request: - branches: [ main ] + branches: [main] concurrency: group: ${{ github.workflow }}-${{ github.ref }} @@ -26,10 +26,7 @@ jobs: - name: Checkout the code uses: actions/checkout@v4.2.2 - - name: Setup OPA - uses: open-policy-agent/setup-opa@v2.2.0 - with: - version: 0.70.0 + - uses: ./.github/actions/build-policies - name: Run OPA tests with coverage working-directory: ./policies @@ -119,10 +116,10 @@ jobs: run: | cargo test --no-fail-fast --workspace env: - RUSTFLAGS: '-Cinstrument-coverage' + RUSTFLAGS: "-Cinstrument-coverage" LLVM_PROFILE_FILE: "cargo-test-%p-%m.profraw" DATABASE_URL: postgresql://postgres:postgres@localhost/postgres - SQLX_OFFLINE: '1' + SQLX_OFFLINE: "1" - name: Build grcov report run: | diff --git a/.github/workflows/release-branch.yaml b/.github/workflows/release-branch.yaml index 6d4b420f1..4733977a7 100644 --- a/.github/workflows/release-branch.yaml +++ b/.github/workflows/release-branch.yaml @@ -28,7 +28,7 @@ jobs: - name: Compute the new minor RC id: next run: | - CURRENT_VERSION="$(cargo metadata --format-version 1 | jq -r '.packages[] | select(.name == "mas-cli") | .version')" + CURRENT_VERSION="$(cargo metadata --format-version 1 --no-deps | jq -r '.packages[] | select(.name == "mas-cli") | .version')" NEXT_VERSION="$(npx --yes semver@7.5.4 -i preminor --preid rc "${CURRENT_VERSION}")" # compute the short minor version, e.g. 0.1.0-rc.1 -> 0.1 SHORT_VERSION="$(echo "${NEXT_VERSION}" | cut -d. -f1-2)" diff --git a/.github/workflows/release-bump.yaml b/.github/workflows/release-bump.yaml index b2ee17d80..841893d50 100644 --- a/.github/workflows/release-bump.yaml +++ b/.github/workflows/release-bump.yaml @@ -35,7 +35,7 @@ jobs: - name: Extract the current version id: current - run: echo "version=$(cargo metadata --format-version 1 | jq -r '.packages[] | select(.name == "mas-cli") | .version')" >> "$GITHUB_OUTPUT" + run: echo "version=$(cargo metadata --format-version 1 --no-deps | jq -r '.packages[] | select(.name == "mas-cli") | .version')" >> "$GITHUB_OUTPUT" - name: Compute the new minor RC id: next diff --git a/Cargo.toml b/Cargo.toml index ea1bfdf9a..6bb1dbb46 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,18 +1,18 @@ [workspace] default-members = ["crates/cli"] members = ["crates/*"] -resolver = "2" +resolver = "3" # Updated in the CI with a `sed` command package.version = "0.14.1" package.license = "AGPL-3.0-only" package.authors = ["Element Backend Team"] -package.edition = "2021" +package.edition = "2024" package.homepage = "https://element-hq.github.io/matrix-authentication-service/" package.repository = "https://github.com/element-hq/matrix-authentication-service/" [workspace.lints.rust] -unsafe_code = "forbid" +unsafe_code = "deny" [workspace.lints.clippy] # We use groups as good defaults, but with a lower priority so that we can override them diff --git a/Dockerfile b/Dockerfile index dab76c892..bd25b351f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,9 +8,9 @@ # The Debian version and version name must be in sync ARG DEBIAN_VERSION=12 ARG DEBIAN_VERSION_NAME=bookworm -ARG RUSTC_VERSION=1.84.0 +ARG RUSTC_VERSION=1.85.0 ARG NODEJS_VERSION=20.15.0 -ARG OPA_VERSION=0.64.1 +ARG OPA_VERSION=1.1.0 ARG CARGO_AUDITABLE_VERSION=0.6.6 ########################################## diff --git a/crates/axum-utils/src/client_authorization.rs b/crates/axum-utils/src/client_authorization.rs index e89114b0e..a259f1286 100644 --- a/crates/axum-utils/src/client_authorization.rs +++ b/crates/axum-utils/src/client_authorization.rs @@ -7,24 +7,24 @@ use std::collections::HashMap; use axum::{ + BoxError, Json, extract::{ - rejection::{FailedToDeserializeForm, FormRejection}, Form, FromRequest, FromRequestParts, + rejection::{FailedToDeserializeForm, FormRejection}, }, response::IntoResponse, - BoxError, Json, }; use axum_extra::typed_header::{TypedHeader, TypedHeaderRejectionReason}; -use headers::{authorization::Basic, Authorization}; +use headers::{Authorization, authorization::Basic}; use http::{Request, StatusCode}; use mas_data_model::{Client, JwksOrJwksUri}; use mas_http::RequestBuilderExt; use mas_iana::oauth::OAuthClientAuthenticationMethod; use mas_jose::{jwk::PublicJsonWebKeySet, jwt::Jwt}; use mas_keystore::Encrypter; -use mas_storage::{oauth2::OAuth2ClientRepository, RepositoryAccess}; +use mas_storage::{RepositoryAccess, oauth2::OAuth2ClientRepository}; use oauth2_types::errors::{ClientError, ClientErrorCode}; -use serde::{de::DeserializeOwned, Deserialize}; +use serde::{Deserialize, de::DeserializeOwned}; use serde_json::Value; use thiserror::Error; @@ -371,7 +371,7 @@ where Err(FormRejection::InvalidFormContentType(_err)) => (None, None, None, None, None), // If the form could not be read, return a Bad Request error Err(FormRejection::FailedToDeserializeForm(err)) => { - return Err(ClientAuthorizationError::BadForm(err)) + return Err(ClientAuthorizationError::BadForm(err)); } // Other errors (body read twice, byte stream broke) return an internal error Err(e) => return Err(ClientAuthorizationError::Internal(Box::new(e))), diff --git a/crates/axum-utils/src/cookies.rs b/crates/axum-utils/src/cookies.rs index c4f1d8d28..c3572a266 100644 --- a/crates/axum-utils/src/cookies.rs +++ b/crates/axum-utils/src/cookies.rs @@ -14,7 +14,7 @@ use axum::{ }; use axum_extra::extract::cookie::{Cookie, Key, PrivateCookieJar, SameSite}; use http::request::Parts; -use serde::{de::DeserializeOwned, Serialize}; +use serde::{Serialize, de::DeserializeOwned}; use thiserror::Error; use url::Url; diff --git a/crates/axum-utils/src/csrf.rs b/crates/axum-utils/src/csrf.rs index 70373cb1e..1ae1dcae2 100644 --- a/crates/axum-utils/src/csrf.rs +++ b/crates/axum-utils/src/csrf.rs @@ -5,11 +5,11 @@ // Please see LICENSE in the repository root for full details. use chrono::{DateTime, Duration, Utc}; -use data_encoding::{DecodeError, BASE64URL_NOPAD}; +use data_encoding::{BASE64URL_NOPAD, DecodeError}; use mas_storage::Clock; -use rand::{Rng, RngCore}; +use rand::{Rng, RngCore, distributions::Standard, prelude::Distribution as _}; use serde::{Deserialize, Serialize}; -use serde_with::{serde_as, TimestampSeconds}; +use serde_with::{TimestampSeconds, serde_as}; use thiserror::Error; use crate::cookies::{CookieDecodeError, CookieJar}; @@ -56,7 +56,7 @@ impl CsrfToken { /// Generate a new random token valid for a specified duration fn generate(now: DateTime, mut rng: impl Rng, ttl: Duration) -> Self { - let token = rng.gen(); + let token = Standard.sample(&mut rng); Self::new(token, now, ttl) } diff --git a/crates/axum-utils/src/fancy_error.rs b/crates/axum-utils/src/fancy_error.rs index 27fe20f45..50a573bee 100644 --- a/crates/axum-utils/src/fancy_error.rs +++ b/crates/axum-utils/src/fancy_error.rs @@ -5,9 +5,9 @@ // Please see LICENSE in the repository root for full details. use axum::{ + Extension, http::StatusCode, response::{IntoResponse, Response}, - Extension, }; use axum_extra::typed_header::TypedHeader; use headers::ContentType; diff --git a/crates/axum-utils/src/language_detection.rs b/crates/axum-utils/src/language_detection.rs index 9b986dff3..efb148f74 100644 --- a/crates/axum-utils/src/language_detection.rs +++ b/crates/axum-utils/src/language_detection.rs @@ -7,7 +7,7 @@ use std::cmp::Reverse; use headers::{Error, Header}; -use http::{header::ACCEPT_LANGUAGE, HeaderName, HeaderValue}; +use http::{HeaderName, HeaderValue, header::ACCEPT_LANGUAGE}; use icu_locid::Locale; #[derive(PartialEq, Eq, Debug)] @@ -155,7 +155,7 @@ impl Header for AcceptLanguage { #[cfg(test)] mod tests { use headers::HeaderMapExt; - use http::{header::ACCEPT_LANGUAGE, HeaderMap, HeaderValue}; + use http::{HeaderMap, HeaderValue, header::ACCEPT_LANGUAGE}; use icu_locid::locale; use super::*; diff --git a/crates/axum-utils/src/session.rs b/crates/axum-utils/src/session.rs index 7b12d80e9..332ad3c4f 100644 --- a/crates/axum-utils/src/session.rs +++ b/crates/axum-utils/src/session.rs @@ -5,7 +5,7 @@ // Please see LICENSE in the repository root for full details. use mas_data_model::BrowserSession; -use mas_storage::{user::BrowserSessionRepository, RepositoryAccess}; +use mas_storage::{RepositoryAccess, user::BrowserSessionRepository}; use serde::{Deserialize, Serialize}; use ulid::Ulid; diff --git a/crates/axum-utils/src/user_authorization.rs b/crates/axum-utils/src/user_authorization.rs index 1a1822b82..52e901c5c 100644 --- a/crates/axum-utils/src/user_authorization.rs +++ b/crates/axum-utils/src/user_authorization.rs @@ -8,20 +8,20 @@ use std::{collections::HashMap, error::Error}; use axum::{ extract::{ - rejection::{FailedToDeserializeForm, FormRejection}, Form, FromRequest, FromRequestParts, + rejection::{FailedToDeserializeForm, FormRejection}, }, response::{IntoResponse, Response}, }; use axum_extra::typed_header::{TypedHeader, TypedHeaderRejectionReason}; -use headers::{authorization::Bearer, Authorization, Header, HeaderMapExt, HeaderName}; -use http::{header::WWW_AUTHENTICATE, HeaderMap, HeaderValue, Request, StatusCode}; +use headers::{Authorization, Header, HeaderMapExt, HeaderName, authorization::Bearer}; +use http::{HeaderMap, HeaderValue, Request, StatusCode, header::WWW_AUTHENTICATE}; use mas_data_model::Session; use mas_storage::{ - oauth2::{OAuth2AccessTokenRepository, OAuth2SessionRepository}, Clock, RepositoryAccess, + oauth2::{OAuth2AccessTokenRepository, OAuth2SessionRepository}, }; -use serde::{de::DeserializeOwned, Deserialize}; +use serde::{Deserialize, de::DeserializeOwned}; use thiserror::Error; #[derive(Debug, Deserialize)] @@ -319,7 +319,7 @@ where Err(FormRejection::InvalidFormContentType(_err)) => (None, None), // If the form could not be read, return a Bad Request error Err(FormRejection::FailedToDeserializeForm(err)) => { - return Err(UserAuthorizationError::BadForm(err)) + return Err(UserAuthorizationError::BadForm(err)); } // Other errors (body read twice, byte stream broke) return an internal error Err(e) => return Err(UserAuthorizationError::Internal(Box::new(e))), diff --git a/crates/cli/build.rs b/crates/cli/build.rs index 18e64cc21..e2a56ee14 100644 --- a/crates/cli/build.rs +++ b/crates/cli/build.rs @@ -11,7 +11,11 @@ fn main() -> anyhow::Result<()> { // empty, so we unset it here. if let Ok(ver) = std::env::var("VERGEN_GIT_DESCRIBE") { if ver.is_empty() { - std::env::remove_var("VERGEN_GIT_DESCRIBE"); + #[allow(unsafe_code)] + // SAFETY: This is safe because the build script is running a single thread + unsafe { + std::env::remove_var("VERGEN_GIT_DESCRIBE"); + } } } diff --git a/crates/cli/src/app_state.rs b/crates/cli/src/app_state.rs index 8e3ef411b..6f8f059f0 100644 --- a/crates/cli/src/app_state.rs +++ b/crates/cli/src/app_state.rs @@ -10,8 +10,8 @@ use axum::extract::{FromRef, FromRequestParts}; use ipnetwork::IpNetwork; use mas_data_model::SiteConfig; use mas_handlers::{ - passwords::PasswordManager, ActivityTracker, BoundActivityTracker, CookieManager, ErrorWrapper, - GraphQLSchema, Limiter, MetadataCache, RequesterFingerprint, + ActivityTracker, BoundActivityTracker, CookieManager, ErrorWrapper, GraphQLSchema, Limiter, + MetadataCache, RequesterFingerprint, passwords::PasswordManager, }; use mas_i18n::Translator; use mas_keystore::{Encrypter, Keystore}; @@ -22,7 +22,7 @@ use mas_router::UrlBuilder; use mas_storage::{BoxClock, BoxRepository, BoxRng, SystemClock}; use mas_storage_pg::PgRepository; use mas_templates::Templates; -use opentelemetry::{metrics::Histogram, KeyValue}; +use opentelemetry::{KeyValue, metrics::Histogram}; use rand::SeedableRng; use sqlx::PgPool; use tracing::Instrument; @@ -343,7 +343,9 @@ impl FromRequestParts for RequesterFingerprint { } else { // If we can't infer the IP address, we'll just use an empty fingerprint and // warn about it - tracing::warn!("Could not infer client IP address for an operation which rate-limits based on IP addresses"); + tracing::warn!( + "Could not infer client IP address for an operation which rate-limits based on IP addresses" + ); Ok(RequesterFingerprint::EMPTY) } } diff --git a/crates/cli/src/commands/config.rs b/crates/cli/src/commands/config.rs index e3ba7c166..0a246d86c 100644 --- a/crates/cli/src/commands/config.rs +++ b/crates/cli/src/commands/config.rs @@ -15,7 +15,7 @@ use mas_storage::SystemClock; use mas_storage_pg::MIGRATOR; use rand::SeedableRng; use tokio::io::AsyncWriteExt; -use tracing::{info, info_span, Instrument}; +use tracing::{Instrument, info, info_span}; use crate::util::database_connection_from_config; diff --git a/crates/cli/src/commands/database.rs b/crates/cli/src/commands/database.rs index 2afebacfc..0283e5049 100644 --- a/crates/cli/src/commands/database.rs +++ b/crates/cli/src/commands/database.rs @@ -11,7 +11,7 @@ use clap::Parser; use figment::Figment; use mas_config::{ConfigurationSectionExt, DatabaseConfig}; use mas_storage_pg::MIGRATOR; -use tracing::{info_span, Instrument}; +use tracing::{Instrument, info_span}; use crate::util::database_connection_from_config; diff --git a/crates/cli/src/commands/doctor.rs b/crates/cli/src/commands/doctor.rs index c0ce4e261..28ab4e919 100644 --- a/crates/cli/src/commands/doctor.rs +++ b/crates/cli/src/commands/doctor.rs @@ -29,7 +29,9 @@ impl Options { #[allow(clippy::too_many_lines)] pub async fn run(self, figment: &Figment) -> anyhow::Result { let _span = info_span!("cli.doctor").entered(); - info!("💡 Running diagnostics, make sure that both MAS and Synapse are running, and that MAS is using the same configuration files as this tool."); + info!( + "💡 Running diagnostics, make sure that both MAS and Synapse are running, and that MAS is using the same configuration files as this tool." + ); let config = RootConfig::extract(figment)?; diff --git a/crates/cli/src/commands/manage.rs b/crates/cli/src/commands/manage.rs index 93228db39..03df778a8 100644 --- a/crates/cli/src/commands/manage.rs +++ b/crates/cli/src/commands/manage.rs @@ -8,8 +8,8 @@ use std::{collections::BTreeMap, process::ExitCode}; use anyhow::Context; use clap::{ArgAction, CommandFactory, Parser}; -use console::{pad_str, style, Alignment, Style, Term}; -use dialoguer::{theme::ColorfulTheme, Confirm, FuzzySelect, Input, Password}; +use console::{Alignment, Style, Term, pad_str, style}; +use dialoguer::{Confirm, FuzzySelect, Input, Password, theme::ColorfulTheme}; use figment::Figment; use mas_config::{ ConfigurationSection, ConfigurationSectionExt, DatabaseConfig, MatrixConfig, PasswordsConfig, @@ -19,6 +19,7 @@ use mas_email::Address; use mas_matrix::HomeserverConnection; use mas_matrix_synapse::SynapseConnection; use mas_storage::{ + Clock, RepositoryAccess, SystemClock, compat::{CompatAccessTokenRepository, CompatSessionFilter, CompatSessionRepository}, oauth2::OAuth2SessionFilter, queue::{ @@ -26,11 +27,10 @@ use mas_storage::{ SyncDevicesJob, }, user::{BrowserSessionFilter, UserEmailRepository, UserPasswordRepository, UserRepository}, - Clock, RepositoryAccess, SystemClock, }; use mas_storage_pg::{DatabaseError, PgRepository}; use rand::{RngCore, SeedableRng}; -use sqlx::{types::Uuid, Acquire}; +use sqlx::{Acquire, types::Uuid}; use tracing::{error, info, info_span, warn}; use crate::util::{database_connection_from_config, password_manager_from_config}; @@ -266,7 +266,9 @@ impl Options { ) .entered(); - tracing::warn!("The 'verify-email' command is deprecated and will be removed in a future version. Use 'add-email' instead."); + tracing::warn!( + "The 'verify-email' command is deprecated and will be removed in a future version. Use 'add-email' instead." + ); Ok(ExitCode::SUCCESS) } diff --git a/crates/cli/src/commands/mod.rs b/crates/cli/src/commands/mod.rs index ea3178e4e..9f0938083 100644 --- a/crates/cli/src/commands/mod.rs +++ b/crates/cli/src/commands/mod.rs @@ -9,8 +9,8 @@ use std::process::ExitCode; use camino::Utf8PathBuf; use clap::Parser; use figment::{ - providers::{Env, Format, Yaml}, Figment, + providers::{Env, Format, Yaml}, }; mod config; diff --git a/crates/cli/src/commands/server.rs b/crates/cli/src/commands/server.rs index c0f4f5108..d58fcb9da 100644 --- a/crates/cli/src/commands/server.rs +++ b/crates/cli/src/commands/server.rs @@ -20,7 +20,7 @@ use mas_router::UrlBuilder; use mas_storage::SystemClock; use mas_storage_pg::MIGRATOR; use sqlx::migrate::Migrate; -use tracing::{info, info_span, warn, Instrument}; +use tracing::{Instrument, info, info_span, warn}; use crate::{ app_state::AppState, @@ -63,7 +63,9 @@ impl Options { info!(version = crate::VERSION, "Starting up"); if self.migrate { - warn!("The `--migrate` flag is deprecated and will be removed in a future release. Please use `--no-migrate` to disable automatic migrations on startup."); + warn!( + "The `--migrate` flag is deprecated and will be removed in a future release. Please use `--no-migrate` to disable automatic migrations on startup." + ); } // Connect to the database @@ -78,7 +80,9 @@ impl Options { let has_missing_migrations = MIGRATOR.iter().any(|m| !applied.contains(&m.version)); if has_missing_migrations { // Refuse to start if there are pending migrations - return Err(anyhow::anyhow!("The server is running with `--no-migrate` but there are pending. Please run them first with `mas-cli database migrate`, or omit the `--no-migrate` flag to apply them automatically on startup.")); + return Err(anyhow::anyhow!( + "The server is running with `--no-migrate` but there are pending. Please run them first with `mas-cli database migrate`, or omit the `--no-migrate` flag to apply them automatically on startup." + )); } } else { info!("Running pending database migrations"); diff --git a/crates/cli/src/commands/syn2mas.rs b/crates/cli/src/commands/syn2mas.rs index fc145536c..e4b4a88df 100644 --- a/crates/cli/src/commands/syn2mas.rs +++ b/crates/cli/src/commands/syn2mas.rs @@ -11,9 +11,9 @@ use mas_config::{ use mas_storage::SystemClock; use mas_storage_pg::MIGRATOR; use rand::thread_rng; -use sqlx::{postgres::PgConnectOptions, types::Uuid, Connection, Either, PgConnection}; -use syn2mas::{synapse_config, LockedMasDatabase, MasWriter, SynapseReader}; -use tracing::{error, info_span, warn, Instrument}; +use sqlx::{Connection, Either, PgConnection, postgres::PgConnectOptions, types::Uuid}; +use syn2mas::{LockedMasDatabase, MasWriter, SynapseReader, synapse_config}; +use tracing::{Instrument, error, info_span, warn}; use crate::util::database_connection_from_config; @@ -82,7 +82,9 @@ const NUM_WRITER_CONNECTIONS: usize = 8; impl Options { #[allow(clippy::too_many_lines)] pub async fn run(self, figment: &Figment) -> anyhow::Result { - warn!("This version of the syn2mas tool is EXPERIMENTAL and INCOMPLETE. Do not use it, except for TESTING."); + warn!( + "This version of the syn2mas tool is EXPERIMENTAL and INCOMPLETE. Do not use it, except for TESTING." + ); if !self.experimental_accepted { error!("Please agree that you can only use this tool for testing."); return Ok(ExitCode::FAILURE); @@ -179,7 +181,9 @@ impl Options { } if !check_warnings.is_empty() { eprintln!("===== Warnings ====="); - eprintln!("These potential issues should be considered before migrating from Synapse to MAS right now:\n"); + eprintln!( + "These potential issues should be considered before migrating from Synapse to MAS right now:\n" + ); for warning in &check_warnings { eprintln!("• {warning}\n"); } diff --git a/crates/cli/src/lifecycle.rs b/crates/cli/src/lifecycle.rs index aa79d2114..4a2c429d1 100644 --- a/crates/cli/src/lifecycle.rs +++ b/crates/cli/src/lifecycle.rs @@ -3,7 +3,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use std::{future::Future, process::ExitCode, time::Duration}; +use std::{process::ExitCode, time::Duration}; use futures_util::future::{BoxFuture, Either}; use mas_handlers::ActivityTracker; diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 049a2fdc0..42efbd92c 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -13,7 +13,7 @@ use clap::Parser; use mas_config::{ConfigurationSection, TelemetryConfig}; use sentry_tracing::EventFilter; use tracing_subscriber::{ - filter::LevelFilter, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer, Registry, + EnvFilter, Layer, Registry, filter::LevelFilter, layer::SubscriberExt, util::SubscriberInitExt, }; mod app_state; diff --git a/crates/cli/src/server.rs b/crates/cli/src/server.rs index cd7eaf44d..b40cc0d44 100644 --- a/crates/cli/src/server.rs +++ b/crates/cli/src/server.rs @@ -12,22 +12,22 @@ use std::{ use anyhow::Context; use axum::{ + Extension, Router, error_handling::HandleErrorLayer, extract::{FromRef, MatchedPath}, - Extension, Router, }; use hyper::{ - header::{HeaderValue, CACHE_CONTROL, USER_AGENT}, Method, Request, Response, StatusCode, Version, + header::{CACHE_CONTROL, HeaderValue, USER_AGENT}, }; use listenfd::ListenFd; use mas_config::{HttpBindConfig, HttpResource, HttpTlsConfig, UnixOrTcp}; -use mas_listener::{unix_or_tcp::UnixOrTcpListener, ConnectionInfo}; +use mas_listener::{ConnectionInfo, unix_or_tcp::UnixOrTcpListener}; use mas_router::Route; use mas_templates::Templates; use mas_tower::{ - make_span_fn, metrics_attributes_fn, DurationRecorderLayer, InFlightCounterLayer, TraceLayer, - KV, + DurationRecorderLayer, InFlightCounterLayer, KV, TraceLayer, make_span_fn, + metrics_attributes_fn, }; use opentelemetry::{Key, KeyValue}; use opentelemetry_http::HeaderExtractor; @@ -231,7 +231,7 @@ pub fn build_router( // TODO: do a better handler here mas_config::HttpResource::ConnectionInfo => router.route( "/connection-info", - axum::routing::get(|connection: Extension| async move { + axum::routing::get(async |connection: Extension| { format!("{connection:?}") }), ), diff --git a/crates/cli/src/sync.rs b/crates/cli/src/sync.rs index 9cc9b1dd2..7676cecf3 100644 --- a/crates/cli/src/sync.rs +++ b/crates/cli/src/sync.rs @@ -11,11 +11,11 @@ use std::collections::{BTreeMap, BTreeSet}; use mas_config::{ClientsConfig, UpstreamOAuth2Config}; use mas_keystore::Encrypter; use mas_storage::{ - upstream_oauth2::{UpstreamOAuthProviderFilter, UpstreamOAuthProviderParams}, Clock, Pagination, RepositoryAccess, + upstream_oauth2::{UpstreamOAuthProviderFilter, UpstreamOAuthProviderParams}, }; use mas_storage_pg::PgRepository; -use sqlx::{postgres::PgAdvisoryLock, Connection, PgConnection}; +use sqlx::{Connection, PgConnection, postgres::PgAdvisoryLock}; use tracing::{error, info, info_span, warn}; fn map_import_action( @@ -155,9 +155,13 @@ pub async fn config_sync( } else { let len = existing_disabled.len(); match len { - 0 => {}, - 1 => warn!("A provider is soft-deleted in the database. Run `mas-cli config sync --prune` to delete it."), - n => warn!("{n} providers are soft-deleted in the database. Run `mas-cli config sync --prune` to delete them."), + 0 => {} + 1 => warn!( + "A provider is soft-deleted in the database. Run `mas-cli config sync --prune` to delete it." + ), + n => warn!( + "{n} providers are soft-deleted in the database. Run `mas-cli config sync --prune` to delete them." + ), } } @@ -318,9 +322,13 @@ pub async fn config_sync( } else { let len = to_delete.count(); match len { - 0 => {}, - 1 => warn!("A static client in the database is not in the config. Run with `--prune` to delete it."), - n => warn!("{n} static clients in the database are not in the config. Run with `--prune` to delete them."), + 0 => {} + 1 => warn!( + "A static client in the database is not in the config. Run with `--prune` to delete it." + ), + n => warn!( + "{n} static clients in the database are not in the config. Run with `--prune` to delete them." + ), } } diff --git a/crates/cli/src/telemetry.rs b/crates/cli/src/telemetry.rs index d11904ad0..f328d0a17 100644 --- a/crates/cli/src/telemetry.rs +++ b/crates/cli/src/telemetry.rs @@ -12,24 +12,24 @@ use std::{ use anyhow::Context as _; use bytes::Bytes; use http_body_util::Full; -use hyper::{header::CONTENT_TYPE, Response}; +use hyper::{Response, header::CONTENT_TYPE}; use mas_config::{ MetricsConfig, MetricsExporterKind, Propagator, TelemetryConfig, TracingConfig, TracingExporterKind, }; use opentelemetry::{ + InstrumentationScope, KeyValue, metrics::Meter, propagation::{TextMapCompositePropagator, TextMapPropagator}, trace::TracerProvider as _, - InstrumentationScope, KeyValue, }; use opentelemetry_otlp::{WithExportConfig, WithHttpConfig}; use opentelemetry_prometheus::PrometheusExporter; use opentelemetry_sdk::{ + Resource, metrics::{ManualReader, PeriodicReader, SdkMeterProvider}, propagation::{BaggagePropagator, TraceContextPropagator}, trace::{Sampler, Tracer, TracerProvider}, - Resource, }; use opentelemetry_semantic_conventions as semcov; use prometheus::Registry; @@ -80,7 +80,7 @@ fn match_propagator(propagator: Propagator) -> Box impl TextMapPropagator { +fn propagator(propagators: &[Propagator]) -> TextMapCompositePropagator { let propagators = propagators.iter().copied().map(match_propagator).collect(); TextMapCompositePropagator::new(propagators) @@ -185,7 +185,9 @@ fn prometheus_service_fn(_req: T) -> PromServiceFuture { pub fn prometheus_service() -> tower::util::ServiceFn PromServiceFuture> { if PROMETHEUS_REGISTRY.get().is_none() { - tracing::warn!("A Prometheus resource was mounted on a listener, but the Prometheus exporter was not setup in the config"); + tracing::warn!( + "A Prometheus resource was mounted on a listener, but the Prometheus exporter was not setup in the config" + ); } tower::service_fn(prometheus_service_fn as _) diff --git a/crates/cli/src/util.rs b/crates/cli/src/util.rs index b5030eb2f..0f155afc7 100644 --- a/crates/cli/src/util.rs +++ b/crates/cli/src/util.rs @@ -19,10 +19,10 @@ use mas_policy::PolicyFactory; use mas_router::UrlBuilder; use mas_templates::{SiteConfigExt, TemplateLoadingError, Templates}; use sqlx::{ - postgres::{PgConnectOptions, PgPoolOptions}, ConnectOptions, PgConnection, PgPool, + postgres::{PgConnectOptions, PgPoolOptions}, }; -use tracing::{log::LevelFilter, Instrument}; +use tracing::{Instrument, log::LevelFilter}; pub async fn password_manager_from_config( config: &PasswordsConfig, @@ -280,7 +280,9 @@ fn database_connect_options_from_config( (Some(pem), None) => options.ssl_client_cert_from_pem(pem.as_bytes()), (None, Some(path)) => options.ssl_client_cert(path), (Some(_), Some(_)) => { - anyhow::bail!("invalid database configuration: both `ssl_certificate` and `ssl_certificate_file` are set") + anyhow::bail!( + "invalid database configuration: both `ssl_certificate` and `ssl_certificate_file` are set" + ) } }; diff --git a/crates/config/src/bin/schema.rs b/crates/config/src/bin/schema.rs index 5e3429071..3f409d406 100644 --- a/crates/config/src/bin/schema.rs +++ b/crates/config/src/bin/schema.rs @@ -4,15 +4,15 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use schemars::gen::SchemaSettings; +use schemars::r#gen::SchemaSettings; fn main() { let settings = SchemaSettings::draft07().with(|s| { s.option_nullable = false; s.option_add_null_type = false; }); - let gen = settings.into_generator(); - let schema = gen.into_root_schema_for::(); + let generator = settings.into_generator(); + let schema = generator.into_root_schema_for::(); serde_json::to_writer_pretty(std::io::stdout(), &schema).expect("Failed to serialize schema"); } diff --git a/crates/config/src/schema.rs b/crates/config/src/schema.rs index be5c80b5f..2a9aaa914 100644 --- a/crates/config/src/schema.rs +++ b/crates/config/src/schema.rs @@ -7,9 +7,9 @@ //! Useful JSON Schema definitions use schemars::{ - gen::SchemaGenerator, - schema::{InstanceType, Schema, SchemaObject}, JsonSchema, + r#gen::SchemaGenerator, + schema::{InstanceType, Schema, SchemaObject}, }; /// A network hostname @@ -20,8 +20,8 @@ impl JsonSchema for Hostname { "Hostname".to_string() } - fn json_schema(gen: &mut SchemaGenerator) -> Schema { - hostname(gen) + fn json_schema(generator: &mut SchemaGenerator) -> Schema { + hostname(generator) } } diff --git a/crates/config/src/sections/captcha.rs b/crates/config/src/sections/captcha.rs index ce3d11c01..58b30799d 100644 --- a/crates/config/src/sections/captcha.rs +++ b/crates/config/src/sections/captcha.rs @@ -5,7 +5,7 @@ // Please see LICENSE in the repository root for full details. use schemars::JsonSchema; -use serde::{de::Error, Deserialize, Serialize}; +use serde::{Deserialize, Serialize, de::Error}; use crate::ConfigurationSection; diff --git a/crates/config/src/sections/clients.rs b/crates/config/src/sections/clients.rs index 4b106e7ff..84aa55a22 100644 --- a/crates/config/src/sections/clients.rs +++ b/crates/config/src/sections/clients.rs @@ -10,7 +10,7 @@ use figment::Figment; use mas_iana::oauth::OAuthClientAuthenticationMethod; use mas_jose::jwk::PublicJsonWebKeySet; use schemars::JsonSchema; -use serde::{de::Error, Deserialize, Serialize}; +use serde::{Deserialize, Serialize, de::Error}; use ulid::Ulid; use url::Url; @@ -249,8 +249,8 @@ mod tests { use std::str::FromStr; use figment::{ - providers::{Format, Yaml}, Figment, Jail, + providers::{Format, Yaml}, }; use super::*; diff --git a/crates/config/src/sections/database.rs b/crates/config/src/sections/database.rs index cdf7ec940..e2b701c60 100644 --- a/crates/config/src/sections/database.rs +++ b/crates/config/src/sections/database.rs @@ -280,8 +280,8 @@ impl ConfigurationSection for DatabaseConfig { #[cfg(test)] mod tests { use figment::{ - providers::{Format, Yaml}, Figment, Jail, + providers::{Format, Yaml}, }; use super::*; diff --git a/crates/config/src/sections/email.rs b/crates/config/src/sections/email.rs index 23668de3c..18f86df13 100644 --- a/crates/config/src/sections/email.rs +++ b/crates/config/src/sections/email.rs @@ -10,7 +10,7 @@ use std::{num::NonZeroU16, str::FromStr}; use lettre::message::Mailbox; use schemars::JsonSchema; -use serde::{de::Error, Deserialize, Serialize}; +use serde::{Deserialize, Serialize, de::Error}; use super::ConfigurationSection; diff --git a/crates/config/src/sections/matrix.rs b/crates/config/src/sections/matrix.rs index fa52de97b..eb145fa8c 100644 --- a/crates/config/src/sections/matrix.rs +++ b/crates/config/src/sections/matrix.rs @@ -5,8 +5,8 @@ // Please see LICENSE in the repository root for full details. use rand::{ - distributions::{Alphanumeric, DistString}, Rng, + distributions::{Alphanumeric, DistString}, }; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; @@ -67,8 +67,8 @@ impl MatrixConfig { #[cfg(test)] mod tests { use figment::{ - providers::{Format, Yaml}, Figment, Jail, + providers::{Format, Yaml}, }; use super::*; diff --git a/crates/config/src/sections/rate_limiting.rs b/crates/config/src/sections/rate_limiting.rs index 9ee12fd15..d95a2ab28 100644 --- a/crates/config/src/sections/rate_limiting.rs +++ b/crates/config/src/sections/rate_limiting.rs @@ -8,7 +8,7 @@ use std::{num::NonZeroU32, time::Duration}; use governor::Quota; use schemars::JsonSchema; -use serde::{de::Error as _, Deserialize, Serialize}; +use serde::{Deserialize, Serialize, de::Error as _}; use crate::ConfigurationSection; diff --git a/crates/config/src/sections/secrets.rs b/crates/config/src/sections/secrets.rs index 90b9180d4..6a375586b 100644 --- a/crates/config/src/sections/secrets.rs +++ b/crates/config/src/sections/secrets.rs @@ -6,13 +6,14 @@ use std::borrow::Cow; -use anyhow::{bail, Context}; +use anyhow::{Context, bail}; use camino::Utf8PathBuf; use mas_jose::jwk::{JsonWebKey, JsonWebKeySet}; use mas_keystore::{Encrypter, Keystore, PrivateKey}; use rand::{ - distributions::{Alphanumeric, DistString}, Rng, SeedableRng, + distributions::{Alphanumeric, DistString, Standard}, + prelude::Distribution as _, }; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; @@ -245,7 +246,7 @@ impl SecretsConfig { }; Ok(Self { - encryption: rng.gen(), + encryption: Standard.sample(&mut rng), keys: vec![rsa_key, ec_p256_key, ec_p384_key, ec_k256_key], }) } diff --git a/crates/config/src/sections/upstream_oauth2.rs b/crates/config/src/sections/upstream_oauth2.rs index b76e8ddb2..077e8de02 100644 --- a/crates/config/src/sections/upstream_oauth2.rs +++ b/crates/config/src/sections/upstream_oauth2.rs @@ -8,7 +8,7 @@ use std::collections::BTreeMap; use mas_iana::jose::JsonWebSignatureAlg; use schemars::JsonSchema; -use serde::{de::Error, Deserialize, Serialize}; +use serde::{Deserialize, Serialize, de::Error}; use serde_with::skip_serializing_none; use ulid::Ulid; use url::Url; @@ -60,7 +60,9 @@ impl ConfigurationSection for UpstreamOAuth2Config { | TokenAuthMethod::PrivateKeyJwt | TokenAuthMethod::SignInWithApple => { if provider.client_secret.is_some() { - return annotate(figment::Error::custom("Unexpected field `client_secret` for the selected authentication method")); + return annotate(figment::Error::custom( + "Unexpected field `client_secret` for the selected authentication method", + )); } } TokenAuthMethod::ClientSecretBasic diff --git a/crates/config/src/util.rs b/crates/config/src/util.rs index cf9b218c5..c2ffd037b 100644 --- a/crates/config/src/util.rs +++ b/crates/config/src/util.rs @@ -4,7 +4,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use figment::{error::Error as FigmentError, Figment}; +use figment::{Figment, error::Error as FigmentError}; use serde::de::DeserializeOwned; /// Trait implemented by all configuration section to help loading specific part diff --git a/crates/data-model/src/compat/device.rs b/crates/data-model/src/compat/device.rs index 49bdc8960..85c6051d3 100644 --- a/crates/data-model/src/compat/device.rs +++ b/crates/data-model/src/compat/device.rs @@ -6,8 +6,8 @@ use oauth2_types::scope::ScopeToken; use rand::{ - distributions::{Alphanumeric, DistString}, RngCore, + distributions::{Alphanumeric, DistString}, }; use serde::{Deserialize, Serialize}; use thiserror::Error; diff --git a/crates/data-model/src/oauth2/authorization_grant.rs b/crates/data-model/src/oauth2/authorization_grant.rs index 2eb616a47..a1b321e4c 100644 --- a/crates/data-model/src/oauth2/authorization_grant.rs +++ b/crates/data-model/src/oauth2/authorization_grant.rs @@ -11,11 +11,11 @@ use mas_iana::oauth::PkceCodeChallengeMethod; use oauth2_types::{ pkce::{CodeChallengeError, CodeChallengeMethodExt}, requests::ResponseMode, - scope::{Scope, OPENID, PROFILE}, + scope::{OPENID, PROFILE, Scope}, }; use rand::{ - distributions::{Alphanumeric, DistString}, RngCore, + distributions::{Alphanumeric, DistString}, }; use ruma_common::UserId; use serde::Serialize; diff --git a/crates/data-model/src/oauth2/client.rs b/crates/data-model/src/oauth2/client.rs index 73fa0dc0d..ef7b029ba 100644 --- a/crates/data-model/src/oauth2/client.rs +++ b/crates/data-model/src/oauth2/client.rs @@ -121,6 +121,7 @@ impl Client { } /// Create a client metadata object for this client + #[must_use] pub fn into_metadata(self) -> ClientMetadata { let (jwks, jwks_uri) = match self.jwks { Some(JwksOrJwksUri::Jwks(jwks)) => (Some(jwks), None), @@ -130,7 +131,7 @@ impl Client { ClientMetadata { redirect_uris: Some(self.redirect_uris.clone()), response_types: None, - grant_types: Some(self.grant_types.into_iter().map(Into::into).collect()), + grant_types: Some(self.grant_types.clone()), application_type: self.application_type.clone(), client_name: self.client_name.map(|n| Localized::new(n, [])), logo_uri: self.logo_uri.map(|n| Localized::new(n, [])), diff --git a/crates/data-model/src/tokens.rs b/crates/data-model/src/tokens.rs index 44fe8cc48..b8897caf7 100644 --- a/crates/data-model/src/tokens.rs +++ b/crates/data-model/src/tokens.rs @@ -6,9 +6,9 @@ use base64ct::{Base64Url, Encoding}; use chrono::{DateTime, Utc}; -use crc::{Crc, CRC_32_ISO_HDLC}; +use crc::{CRC_32_ISO_HDLC, Crc}; use mas_iana::oauth::OAuthTokenTypeHint; -use rand::{distributions::Alphanumeric, Rng, RngCore}; +use rand::{Rng, RngCore, distributions::Alphanumeric}; use thiserror::Error; use ulid::Ulid; @@ -444,7 +444,9 @@ mod tests { )); // Whilst this is a macaroon, it's not a Synapse macaroon - assert!(! is_likely_synapse_macaroon("MDAxY2xvY2F0aW9uIGh0dHA6Ly9teWJhbmsvCjAwMjZpZGVudGlmaWVyIHdlIHVzZWQgb3VyIHNlY3JldCBrZXkKMDAyZnNpZ25hdHVyZSDj2eApCFJsTAA5rhURQRXZf91ovyujebNCqvD2F9BVLwo")); + assert!(!is_likely_synapse_macaroon( + "MDAxY2xvY2F0aW9uIGh0dHA6Ly9teWJhbmsvCjAwMjZpZGVudGlmaWVyIHdlIHVzZWQgb3VyIHNlY3JldCBrZXkKMDAyZnNpZ25hdHVyZSDj2eApCFJsTAA5rhURQRXZf91ovyujebNCqvD2F9BVLwo" + )); // None of these are macaroons assert!(!is_likely_synapse_macaroon( diff --git a/crates/email/src/lib.rs b/crates/email/src/lib.rs index b493f46d1..49e940638 100644 --- a/crates/email/src/lib.rs +++ b/crates/email/src/lib.rs @@ -12,7 +12,7 @@ mod mailer; mod transport; pub use lettre::{ - message::Mailbox, transport::smtp::authentication::Credentials as SmtpCredentials, Address, + Address, message::Mailbox, transport::smtp::authentication::Credentials as SmtpCredentials, }; pub use mas_templates::EmailVerificationContext; diff --git a/crates/email/src/mailer.rs b/crates/email/src/mailer.rs index 57cf3d385..ed0968269 100644 --- a/crates/email/src/mailer.rs +++ b/crates/email/src/mailer.rs @@ -7,8 +7,8 @@ //! Send emails to users use lettre::{ - message::{Mailbox, MessageBuilder, MultiPart}, AsyncTransport, Message, + message::{Mailbox, MessageBuilder, MultiPart}, }; use mas_templates::{EmailRecoveryContext, EmailVerificationContext, Templates, WithLanguage}; use thiserror::Error; diff --git a/crates/email/src/transport.rs b/crates/email/src/transport.rs index 03bb54257..3675b3792 100644 --- a/crates/email/src/transport.rs +++ b/crates/email/src/transport.rs @@ -10,12 +10,12 @@ use std::{ffi::OsString, num::NonZeroU16, sync::Arc}; use async_trait::async_trait; use lettre::{ + AsyncTransport, Tokio1Executor, address::Envelope, transport::{ sendmail::AsyncSendmailTransport, - smtp::{authentication::Credentials, AsyncSmtpTransport}, + smtp::{AsyncSmtpTransport, authentication::Credentials}, }, - AsyncTransport, Tokio1Executor, }; use thiserror::Error; diff --git a/crates/handlers/src/activity_tracker/worker.rs b/crates/handlers/src/activity_tracker/worker.rs index 7d1f2ec6d..949ab690d 100644 --- a/crates/handlers/src/activity_tracker/worker.rs +++ b/crates/handlers/src/activity_tracker/worker.rs @@ -7,18 +7,18 @@ use std::{collections::HashMap, net::IpAddr}; use chrono::{DateTime, Utc}; -use mas_storage::{user::BrowserSessionRepository, RepositoryAccess}; +use mas_storage::{RepositoryAccess, user::BrowserSessionRepository}; use opentelemetry::{ - metrics::{Counter, Histogram}, Key, KeyValue, + metrics::{Counter, Histogram}, }; use sqlx::PgPool; use tokio_util::sync::CancellationToken; use ulid::Ulid; use crate::{ - activity_tracker::{Message, SessionKind}, METER, + activity_tracker::{Message, SessionKind}, }; /// The maximum number of pending activity records before we flush them to the diff --git a/crates/handlers/src/admin/call_context.rs b/crates/handlers/src/admin/call_context.rs index 30a3bb2ea..0b812db05 100644 --- a/crates/handlers/src/admin/call_context.rs +++ b/crates/handlers/src/admin/call_context.rs @@ -8,12 +8,12 @@ use std::convert::Infallible; use aide::OperationIo; use axum::{ + Json, extract::FromRequestParts, response::{IntoResponse, Response}, - Json, }; use axum_extra::TypedHeader; -use headers::{authorization::Bearer, Authorization}; +use headers::{Authorization, authorization::Bearer}; use hyper::StatusCode; use mas_data_model::{Session, User}; use mas_storage::{BoxClock, BoxRepository, RepositoryError}; diff --git a/crates/handlers/src/admin/mod.rs b/crates/handlers/src/admin/mod.rs index dcd380856..4edc8b2ca 100644 --- a/crates/handlers/src/admin/mod.rs +++ b/crates/handlers/src/admin/mod.rs @@ -10,10 +10,10 @@ use aide::{ transform::TransformOpenApi, }; use axum::{ + Json, Router, extract::{FromRef, FromRequestParts, State}, http::HeaderName, response::Html, - Json, Router, }; use hyper::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE}; use indexmap::IndexMap; @@ -119,7 +119,8 @@ where aide::generate::infer_responses(false); aide::generate::in_context(|ctx| { - ctx.schema = schemars::gen::SchemaGenerator::new(schemars::gen::SchemaSettings::openapi3()); + ctx.schema = + schemars::r#gen::SchemaGenerator::new(schemars::r#gen::SchemaSettings::openapi3()); }); let mut api = OpenApi::default(); diff --git a/crates/handlers/src/admin/params.rs b/crates/handlers/src/admin/params.rs index 0d0473819..749bc62b3 100644 --- a/crates/handlers/src/admin/params.rs +++ b/crates/handlers/src/admin/params.rs @@ -11,12 +11,12 @@ use std::num::NonZeroUsize; use aide::OperationIo; use axum::{ + Json, extract::{ - rejection::{PathRejection, QueryRejection}, FromRequestParts, Path, Query, + rejection::{PathRejection, QueryRejection}, }, response::IntoResponse, - Json, }; use axum_macros::FromRequestParts; use hyper::StatusCode; diff --git a/crates/handlers/src/admin/schema.rs b/crates/handlers/src/admin/schema.rs index d0c6b7f80..99f1c20b7 100644 --- a/crates/handlers/src/admin/schema.rs +++ b/crates/handlers/src/admin/schema.rs @@ -7,9 +7,9 @@ //! Common schema definitions use schemars::{ - gen::SchemaGenerator, - schema::{InstanceType, Metadata, Schema, SchemaObject, StringValidation}, JsonSchema, + r#gen::SchemaGenerator, + schema::{InstanceType, Metadata, Schema, SchemaObject, StringValidation}, }; /// A type to use for schema definitions of ULIDs diff --git a/crates/handlers/src/admin/v1/compat_sessions/get.rs b/crates/handlers/src/admin/v1/compat_sessions/get.rs index ba48f1afd..16a720849 100644 --- a/crates/handlers/src/admin/v1/compat_sessions/get.rs +++ b/crates/handlers/src/admin/v1/compat_sessions/get.rs @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use aide::{transform::TransformOperation, OperationIo}; -use axum::{response::IntoResponse, Json}; +use aide::{OperationIo, transform::TransformOperation}; +use axum::{Json, response::IntoResponse}; use hyper::StatusCode; use ulid::Ulid; @@ -85,7 +85,7 @@ mod tests { use sqlx::PgPool; use ulid::Ulid; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_get(pool: PgPool) { diff --git a/crates/handlers/src/admin/v1/compat_sessions/list.rs b/crates/handlers/src/admin/v1/compat_sessions/list.rs index a27f1c29a..f08fcae1c 100644 --- a/crates/handlers/src/admin/v1/compat_sessions/list.rs +++ b/crates/handlers/src/admin/v1/compat_sessions/list.rs @@ -3,15 +3,15 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use aide::{transform::TransformOperation, OperationIo}; +use aide::{OperationIo, transform::TransformOperation}; use axum::{ - extract::{rejection::QueryRejection, Query}, - response::IntoResponse, Json, + extract::{Query, rejection::QueryRejection}, + response::IntoResponse, }; use axum_macros::FromRequestParts; use hyper::StatusCode; -use mas_storage::{compat::CompatSessionFilter, Page}; +use mas_storage::{Page, compat::CompatSessionFilter}; use schemars::JsonSchema; use serde::Deserialize; use ulid::Ulid; @@ -222,7 +222,7 @@ mod tests { use mas_data_model::Device; use sqlx::PgPool; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_compat_session_list(pool: PgPool) { diff --git a/crates/handlers/src/admin/v1/mod.rs b/crates/handlers/src/admin/v1/mod.rs index dd071e004..02c63e2a5 100644 --- a/crates/handlers/src/admin/v1/mod.rs +++ b/crates/handlers/src/admin/v1/mod.rs @@ -5,8 +5,8 @@ // Please see LICENSE in the repository root for full details. use aide::axum::{ - routing::{get_with, post_with}, ApiRouter, + routing::{get_with, post_with}, }; use axum::extract::{FromRef, FromRequestParts}; use mas_matrix::BoxHomeserverConnection; diff --git a/crates/handlers/src/admin/v1/oauth2_sessions/get.rs b/crates/handlers/src/admin/v1/oauth2_sessions/get.rs index 371cbe065..e8fce4a0a 100644 --- a/crates/handlers/src/admin/v1/oauth2_sessions/get.rs +++ b/crates/handlers/src/admin/v1/oauth2_sessions/get.rs @@ -4,8 +4,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use aide::{transform::TransformOperation, OperationIo}; -use axum::{response::IntoResponse, Json}; +use aide::{OperationIo, transform::TransformOperation}; +use axum::{Json, response::IntoResponse}; use hyper::StatusCode; use ulid::Ulid; @@ -83,7 +83,7 @@ mod tests { use sqlx::PgPool; use ulid::Ulid; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_get(pool: PgPool) { diff --git a/crates/handlers/src/admin/v1/oauth2_sessions/list.rs b/crates/handlers/src/admin/v1/oauth2_sessions/list.rs index 999584f0d..eeccfc12b 100644 --- a/crates/handlers/src/admin/v1/oauth2_sessions/list.rs +++ b/crates/handlers/src/admin/v1/oauth2_sessions/list.rs @@ -6,15 +6,15 @@ use std::str::FromStr; -use aide::{transform::TransformOperation, OperationIo}; +use aide::{OperationIo, transform::TransformOperation}; use axum::{ - extract::{rejection::QueryRejection, Query}, - response::IntoResponse, Json, + extract::{Query, rejection::QueryRejection}, + response::IntoResponse, }; use axum_macros::FromRequestParts; use hyper::StatusCode; -use mas_storage::{oauth2::OAuth2SessionFilter, Page}; +use mas_storage::{Page, oauth2::OAuth2SessionFilter}; use oauth2_types::scope::{Scope, ScopeToken}; use schemars::JsonSchema; use serde::Deserialize; @@ -314,7 +314,7 @@ mod tests { use hyper::{Request, StatusCode}; use sqlx::PgPool; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_oauth2_simple_session_list(pool: PgPool) { diff --git a/crates/handlers/src/admin/v1/upstream_oauth_links/get.rs b/crates/handlers/src/admin/v1/upstream_oauth_links/get.rs index af7b20bc1..eecbb3e4e 100644 --- a/crates/handlers/src/admin/v1/upstream_oauth_links/get.rs +++ b/crates/handlers/src/admin/v1/upstream_oauth_links/get.rs @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use aide::{transform::TransformOperation, OperationIo}; -use axum::{response::IntoResponse, Json}; +use aide::{OperationIo, transform::TransformOperation}; +use axum::{Json, response::IntoResponse}; use hyper::StatusCode; use ulid::Ulid; @@ -83,7 +83,7 @@ mod tests { use ulid::Ulid; use super::super::test_utils; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_get(pool: PgPool) { diff --git a/crates/handlers/src/admin/v1/upstream_oauth_links/list.rs b/crates/handlers/src/admin/v1/upstream_oauth_links/list.rs index 9ba989f3c..e20a975be 100644 --- a/crates/handlers/src/admin/v1/upstream_oauth_links/list.rs +++ b/crates/handlers/src/admin/v1/upstream_oauth_links/list.rs @@ -3,15 +3,15 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use aide::{transform::TransformOperation, OperationIo}; +use aide::{OperationIo, transform::TransformOperation}; use axum::{ - extract::{rejection::QueryRejection, Query}, - response::IntoResponse, Json, + extract::{Query, rejection::QueryRejection}, + response::IntoResponse, }; use axum_macros::FromRequestParts; use hyper::StatusCode; -use mas_storage::{upstream_oauth2::UpstreamOAuthLinkFilter, Page}; +use mas_storage::{Page, upstream_oauth2::UpstreamOAuthLinkFilter}; use schemars::JsonSchema; use serde::Deserialize; use ulid::Ulid; @@ -199,7 +199,7 @@ mod tests { use sqlx::PgPool; use super::super::test_utils; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_list(pool: PgPool) { diff --git a/crates/handlers/src/admin/v1/upstream_oauth_links/mod.rs b/crates/handlers/src/admin/v1/upstream_oauth_links/mod.rs index f6e35476c..b014738ae 100644 --- a/crates/handlers/src/admin/v1/upstream_oauth_links/mod.rs +++ b/crates/handlers/src/admin/v1/upstream_oauth_links/mod.rs @@ -19,7 +19,7 @@ mod test_utils { }; use mas_iana::jose::JsonWebSignatureAlg; use mas_storage::upstream_oauth2::UpstreamOAuthProviderParams; - use oauth2_types::scope::{Scope, OPENID}; + use oauth2_types::scope::{OPENID, Scope}; pub(crate) fn oidc_provider_params(name: &str) -> UpstreamOAuthProviderParams { UpstreamOAuthProviderParams { diff --git a/crates/handlers/src/admin/v1/user_emails/add.rs b/crates/handlers/src/admin/v1/user_emails/add.rs index 98da87063..466d372be 100644 --- a/crates/handlers/src/admin/v1/user_emails/add.rs +++ b/crates/handlers/src/admin/v1/user_emails/add.rs @@ -5,13 +5,13 @@ use std::str::FromStr as _; -use aide::{transform::TransformOperation, NoApi, OperationIo}; -use axum::{response::IntoResponse, Json}; +use aide::{NoApi, OperationIo, transform::TransformOperation}; +use axum::{Json, response::IntoResponse}; use hyper::StatusCode; use mas_storage::{ + BoxRng, queue::{ProvisionUserJob, QueueJobRepositoryExt as _}, user::UserEmailFilter, - BoxRng, }; use schemars::JsonSchema; use serde::Deserialize; @@ -165,7 +165,7 @@ mod tests { use sqlx::PgPool; use ulid::Ulid; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_create(pool: PgPool) { setup(); diff --git a/crates/handlers/src/admin/v1/user_emails/delete.rs b/crates/handlers/src/admin/v1/user_emails/delete.rs index 8ea584be3..65e000111 100644 --- a/crates/handlers/src/admin/v1/user_emails/delete.rs +++ b/crates/handlers/src/admin/v1/user_emails/delete.rs @@ -3,12 +3,12 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use aide::{transform::TransformOperation, NoApi, OperationIo}; -use axum::{response::IntoResponse, Json}; +use aide::{NoApi, OperationIo, transform::TransformOperation}; +use axum::{Json, response::IntoResponse}; use hyper::StatusCode; use mas_storage::{ - queue::{ProvisionUserJob, QueueJobRepositoryExt as _}, BoxRng, + queue::{ProvisionUserJob, QueueJobRepositoryExt as _}, }; use ulid::Ulid; @@ -83,7 +83,7 @@ mod tests { use sqlx::PgPool; use ulid::Ulid; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_delete(pool: PgPool) { setup(); diff --git a/crates/handlers/src/admin/v1/user_emails/get.rs b/crates/handlers/src/admin/v1/user_emails/get.rs index e3c4a9a4c..b5ddfc02a 100644 --- a/crates/handlers/src/admin/v1/user_emails/get.rs +++ b/crates/handlers/src/admin/v1/user_emails/get.rs @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use aide::{transform::TransformOperation, OperationIo}; -use axum::{response::IntoResponse, Json}; +use aide::{OperationIo, transform::TransformOperation}; +use axum::{Json, response::IntoResponse}; use hyper::StatusCode; use ulid::Ulid; @@ -77,7 +77,7 @@ mod tests { use sqlx::PgPool; use ulid::Ulid; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_get(pool: PgPool) { diff --git a/crates/handlers/src/admin/v1/user_emails/list.rs b/crates/handlers/src/admin/v1/user_emails/list.rs index cd12fb6c6..d7ffa9ce5 100644 --- a/crates/handlers/src/admin/v1/user_emails/list.rs +++ b/crates/handlers/src/admin/v1/user_emails/list.rs @@ -3,15 +3,15 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use aide::{transform::TransformOperation, OperationIo}; +use aide::{OperationIo, transform::TransformOperation}; use axum::{ - extract::{rejection::QueryRejection, Query}, - response::IntoResponse, Json, + extract::{Query, rejection::QueryRejection}, + response::IntoResponse, }; use axum_macros::FromRequestParts; use hyper::StatusCode; -use mas_storage::{user::UserEmailFilter, Page}; +use mas_storage::{Page, user::UserEmailFilter}; use schemars::JsonSchema; use serde::Deserialize; use ulid::Ulid; @@ -164,7 +164,7 @@ mod tests { use hyper::{Request, StatusCode}; use sqlx::PgPool; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_list(pool: PgPool) { diff --git a/crates/handlers/src/admin/v1/user_sessions/get.rs b/crates/handlers/src/admin/v1/user_sessions/get.rs index 830f2d0e9..1396beb47 100644 --- a/crates/handlers/src/admin/v1/user_sessions/get.rs +++ b/crates/handlers/src/admin/v1/user_sessions/get.rs @@ -3,8 +3,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use aide::{transform::TransformOperation, OperationIo}; -use axum::{response::IntoResponse, Json}; +use aide::{OperationIo, transform::TransformOperation}; +use axum::{Json, response::IntoResponse}; use hyper::StatusCode; use ulid::Ulid; @@ -80,7 +80,7 @@ mod tests { use insta::assert_json_snapshot; use sqlx::PgPool; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_get(pool: PgPool) { diff --git a/crates/handlers/src/admin/v1/user_sessions/list.rs b/crates/handlers/src/admin/v1/user_sessions/list.rs index 1e154764d..62b72cc50 100644 --- a/crates/handlers/src/admin/v1/user_sessions/list.rs +++ b/crates/handlers/src/admin/v1/user_sessions/list.rs @@ -3,11 +3,11 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use aide::{transform::TransformOperation, OperationIo}; +use aide::{OperationIo, transform::TransformOperation}; use axum::{ - extract::{rejection::QueryRejection, Query}, - response::IntoResponse, Json, + extract::{Query, rejection::QueryRejection}, + response::IntoResponse, }; use axum_macros::FromRequestParts; use hyper::StatusCode; @@ -191,7 +191,7 @@ mod tests { use insta::assert_json_snapshot; use sqlx::PgPool; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_user_session_list(pool: PgPool) { diff --git a/crates/handlers/src/admin/v1/users/add.rs b/crates/handlers/src/admin/v1/users/add.rs index 0a33f2961..b4e0abd7e 100644 --- a/crates/handlers/src/admin/v1/users/add.rs +++ b/crates/handlers/src/admin/v1/users/add.rs @@ -4,13 +4,13 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use aide::{transform::TransformOperation, NoApi, OperationIo}; -use axum::{extract::State, response::IntoResponse, Json}; +use aide::{NoApi, OperationIo, transform::TransformOperation}; +use axum::{Json, extract::State, response::IntoResponse}; use hyper::StatusCode; use mas_matrix::BoxHomeserverConnection; use mas_storage::{ - queue::{ProvisionUserJob, QueueJobRepositoryExt as _}, BoxRng, + queue::{ProvisionUserJob, QueueJobRepositoryExt as _}, }; use schemars::JsonSchema; use serde::Deserialize; @@ -179,10 +179,10 @@ pub async fn handler( #[cfg(test)] mod tests { use hyper::{Request, StatusCode}; - use mas_storage::{user::UserRepository, RepositoryAccess}; + use mas_storage::{RepositoryAccess, user::UserRepository}; use sqlx::PgPool; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_add_user(pool: PgPool) { diff --git a/crates/handlers/src/admin/v1/users/by_username.rs b/crates/handlers/src/admin/v1/users/by_username.rs index b21b56c78..66fc6ff51 100644 --- a/crates/handlers/src/admin/v1/users/by_username.rs +++ b/crates/handlers/src/admin/v1/users/by_username.rs @@ -4,8 +4,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use aide::{transform::TransformOperation, OperationIo}; -use axum::{extract::Path, response::IntoResponse, Json}; +use aide::{OperationIo, transform::TransformOperation}; +use axum::{Json, extract::Path, response::IntoResponse}; use hyper::StatusCode; use schemars::JsonSchema; use serde::Deserialize; diff --git a/crates/handlers/src/admin/v1/users/deactivate.rs b/crates/handlers/src/admin/v1/users/deactivate.rs index ad09a7ca2..25d4a0339 100644 --- a/crates/handlers/src/admin/v1/users/deactivate.rs +++ b/crates/handlers/src/admin/v1/users/deactivate.rs @@ -4,12 +4,12 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use aide::{transform::TransformOperation, NoApi, OperationIo}; -use axum::{response::IntoResponse, Json}; +use aide::{NoApi, OperationIo, transform::TransformOperation}; +use axum::{Json, response::IntoResponse}; use hyper::StatusCode; use mas_storage::{ - queue::{DeactivateUserJob, QueueJobRepositoryExt as _}, BoxRng, + queue::{DeactivateUserJob, QueueJobRepositoryExt as _}, }; use tracing::info; use ulid::Ulid; @@ -103,10 +103,10 @@ pub async fn handler( mod tests { use chrono::Duration; use hyper::{Request, StatusCode}; - use mas_storage::{user::UserRepository, Clock, RepositoryAccess}; - use sqlx::{types::Json, PgPool}; + use mas_storage::{Clock, RepositoryAccess, user::UserRepository}; + use sqlx::{PgPool, types::Json}; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_deactivate_user(pool: PgPool) { diff --git a/crates/handlers/src/admin/v1/users/get.rs b/crates/handlers/src/admin/v1/users/get.rs index 0f3be0867..71763b292 100644 --- a/crates/handlers/src/admin/v1/users/get.rs +++ b/crates/handlers/src/admin/v1/users/get.rs @@ -4,8 +4,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use aide::{transform::TransformOperation, OperationIo}; -use axum::{response::IntoResponse, Json}; +use aide::{OperationIo, transform::TransformOperation}; +use axum::{Json, response::IntoResponse}; use hyper::StatusCode; use ulid::Ulid; diff --git a/crates/handlers/src/admin/v1/users/list.rs b/crates/handlers/src/admin/v1/users/list.rs index f142a30ff..628b56747 100644 --- a/crates/handlers/src/admin/v1/users/list.rs +++ b/crates/handlers/src/admin/v1/users/list.rs @@ -4,15 +4,15 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use aide::{transform::TransformOperation, OperationIo}; +use aide::{OperationIo, transform::TransformOperation}; use axum::{ - extract::{rejection::QueryRejection, Query}, - response::IntoResponse, Json, + extract::{Query, rejection::QueryRejection}, + response::IntoResponse, }; use axum_macros::FromRequestParts; use hyper::StatusCode; -use mas_storage::{user::UserFilter, Page}; +use mas_storage::{Page, user::UserFilter}; use schemars::JsonSchema; use serde::Deserialize; diff --git a/crates/handlers/src/admin/v1/users/lock.rs b/crates/handlers/src/admin/v1/users/lock.rs index 877deb63a..99ae7c5a4 100644 --- a/crates/handlers/src/admin/v1/users/lock.rs +++ b/crates/handlers/src/admin/v1/users/lock.rs @@ -4,8 +4,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use aide::{transform::TransformOperation, OperationIo}; -use axum::{response::IntoResponse, Json}; +use aide::{OperationIo, transform::TransformOperation}; +use axum::{Json, response::IntoResponse}; use hyper::StatusCode; use ulid::Ulid; @@ -92,10 +92,10 @@ pub async fn handler( mod tests { use chrono::Duration; use hyper::{Request, StatusCode}; - use mas_storage::{user::UserRepository, Clock, RepositoryAccess}; + use mas_storage::{Clock, RepositoryAccess, user::UserRepository}; use sqlx::PgPool; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_lock_user(pool: PgPool) { diff --git a/crates/handlers/src/admin/v1/users/set_admin.rs b/crates/handlers/src/admin/v1/users/set_admin.rs index 956d5e101..fae62d5c0 100644 --- a/crates/handlers/src/admin/v1/users/set_admin.rs +++ b/crates/handlers/src/admin/v1/users/set_admin.rs @@ -4,8 +4,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use aide::{transform::TransformOperation, OperationIo}; -use axum::{response::IntoResponse, Json}; +use aide::{OperationIo, transform::TransformOperation}; +use axum::{Json, response::IntoResponse}; use hyper::StatusCode; use schemars::JsonSchema; use serde::Deserialize; @@ -100,10 +100,10 @@ pub async fn handler( #[cfg(test)] mod tests { use hyper::{Request, StatusCode}; - use mas_storage::{user::UserRepository, RepositoryAccess}; + use mas_storage::{RepositoryAccess, user::UserRepository}; use sqlx::PgPool; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_change_can_request_admin(pool: PgPool) { diff --git a/crates/handlers/src/admin/v1/users/set_password.rs b/crates/handlers/src/admin/v1/users/set_password.rs index 84ea35fee..4a0e6d034 100644 --- a/crates/handlers/src/admin/v1/users/set_password.rs +++ b/crates/handlers/src/admin/v1/users/set_password.rs @@ -4,8 +4,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use aide::{transform::TransformOperation, NoApi, OperationIo}; -use axum::{extract::State, response::IntoResponse, Json}; +use aide::{NoApi, OperationIo, transform::TransformOperation}; +use axum::{Json, extract::State, response::IntoResponse}; use hyper::StatusCode; use mas_storage::BoxRng; use schemars::JsonSchema; @@ -138,13 +138,13 @@ pub async fn handler( #[cfg(test)] mod tests { use hyper::{Request, StatusCode}; - use mas_storage::{user::UserPasswordRepository, RepositoryAccess}; + use mas_storage::{RepositoryAccess, user::UserPasswordRepository}; use sqlx::PgPool; use zeroize::Zeroizing; use crate::{ passwords::PasswordManager, - test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}, + test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}, }; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] diff --git a/crates/handlers/src/admin/v1/users/unlock.rs b/crates/handlers/src/admin/v1/users/unlock.rs index 685f2ad28..1626d4f58 100644 --- a/crates/handlers/src/admin/v1/users/unlock.rs +++ b/crates/handlers/src/admin/v1/users/unlock.rs @@ -4,8 +4,8 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use aide::{transform::TransformOperation, OperationIo}; -use axum::{extract::State, response::IntoResponse, Json}; +use aide::{OperationIo, transform::TransformOperation}; +use axum::{Json, extract::State, response::IntoResponse}; use hyper::StatusCode; use mas_matrix::BoxHomeserverConnection; use ulid::Ulid; @@ -99,10 +99,10 @@ pub async fn handler( mod tests { use hyper::{Request, StatusCode}; use mas_matrix::{HomeserverConnection, ProvisionRequest}; - use mas_storage::{user::UserRepository, RepositoryAccess}; + use mas_storage::{RepositoryAccess, user::UserRepository}; use sqlx::PgPool; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_unlock_user(pool: PgPool) { diff --git a/crates/handlers/src/captcha.rs b/crates/handlers/src/captcha.rs index 345d74ef2..fec2a7573 100644 --- a/crates/handlers/src/captcha.rs +++ b/crates/handlers/src/captcha.rs @@ -39,7 +39,9 @@ pub enum Error { #[error("The CAPTCHA provider returned an invalid response")] InvalidResponse, - #[error("The hostname in the CAPTCHA response ({got:?}) does not match the site hostname ({expected:?})")] + #[error( + "The hostname in the CAPTCHA response ({got:?}) does not match the site hostname ({expected:?})" + )] HostnameMismatch { expected: String, got: String }, #[error("The CAPTCHA provider returned an error")] diff --git a/crates/handlers/src/compat/login.rs b/crates/handlers/src/compat/login.rs index d62f33501..f3966357b 100644 --- a/crates/handlers/src/compat/login.rs +++ b/crates/handlers/src/compat/login.rs @@ -5,9 +5,9 @@ // Please see LICENSE in the repository root for full details. use axum::{ - extract::{rejection::JsonRejection, State}, - response::IntoResponse, Json, + extract::{State, rejection::JsonRejection}, + response::IntoResponse, }; use axum_extra::{extract::WithRejection, typed_header::TypedHeader}; use chrono::Duration; @@ -18,23 +18,23 @@ use mas_data_model::{ }; use mas_matrix::BoxHomeserverConnection; use mas_storage::{ + BoxClock, BoxRepository, BoxRng, Clock, RepositoryAccess, compat::{ CompatAccessTokenRepository, CompatRefreshTokenRepository, CompatSessionRepository, CompatSsoLoginRepository, }, user::{UserPasswordRepository, UserRepository}, - BoxClock, BoxRepository, BoxRng, Clock, RepositoryAccess, }; use rand::{CryptoRng, RngCore}; use serde::{Deserialize, Serialize}; -use serde_with::{serde_as, skip_serializing_none, DurationMilliSeconds}; +use serde_with::{DurationMilliSeconds, serde_as, skip_serializing_none}; use thiserror::Error; use zeroize::Zeroizing; use super::MatrixError; use crate::{ - impl_from_error_for_route, passwords::PasswordManager, rate_limit::PasswordCheckLimitedError, - BoundActivityTracker, Limiter, RequesterFingerprint, + BoundActivityTracker, Limiter, RequesterFingerprint, impl_from_error_for_route, + passwords::PasswordManager, rate_limit::PasswordCheckLimitedError, }; #[derive(Debug, Serialize)] @@ -520,7 +520,7 @@ mod tests { use sqlx::PgPool; use super::*; - use crate::test_utils::{setup, test_site_config, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup, test_site_config}; /// Test that the server advertises the right login flows. #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] diff --git a/crates/handlers/src/compat/login_sso_complete.rs b/crates/handlers/src/compat/login_sso_complete.rs index 8ebbaf73c..b436c33c3 100644 --- a/crates/handlers/src/compat/login_sso_complete.rs +++ b/crates/handlers/src/compat/login_sso_complete.rs @@ -13,16 +13,16 @@ use axum::{ }; use chrono::Duration; use mas_axum_utils::{ + FancyError, SessionInfoExt, cookies::CookieJar, csrf::{CsrfExt, ProtectedForm}, - FancyError, SessionInfoExt, }; use mas_data_model::Device; use mas_matrix::BoxHomeserverConnection; use mas_router::{CompatLoginSsoAction, UrlBuilder}; use mas_storage::{ - compat::{CompatSessionRepository, CompatSsoLoginRepository}, BoxClock, BoxRepository, BoxRng, Clock, RepositoryAccess, + compat::{CompatSessionRepository, CompatSsoLoginRepository}, }; use mas_templates::{CompatSsoContext, ErrorContext, TemplateContext, Templates}; use serde::{Deserialize, Serialize}; diff --git a/crates/handlers/src/compat/login_sso_redirect.rs b/crates/handlers/src/compat/login_sso_redirect.rs index 0f004053f..36b065b39 100644 --- a/crates/handlers/src/compat/login_sso_redirect.rs +++ b/crates/handlers/src/compat/login_sso_redirect.rs @@ -11,7 +11,7 @@ use axum::{ use hyper::StatusCode; use mas_axum_utils::sentry::SentryEventID; use mas_router::{CompatLoginSsoAction, CompatLoginSsoComplete, UrlBuilder}; -use mas_storage::{compat::CompatSsoLoginRepository, BoxClock, BoxRepository, BoxRng}; +use mas_storage::{BoxClock, BoxRepository, BoxRng, compat::CompatSsoLoginRepository}; use rand::distributions::{Alphanumeric, DistString}; use serde::Deserialize; use serde_with::serde; diff --git a/crates/handlers/src/compat/logout.rs b/crates/handlers/src/compat/logout.rs index 8ef2dd95b..20df8e682 100644 --- a/crates/handlers/src/compat/logout.rs +++ b/crates/handlers/src/compat/logout.rs @@ -4,21 +4,21 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use axum::{response::IntoResponse, Json}; +use axum::{Json, response::IntoResponse}; use axum_extra::typed_header::TypedHeader; -use headers::{authorization::Bearer, Authorization}; +use headers::{Authorization, authorization::Bearer}; use hyper::StatusCode; use mas_axum_utils::sentry::SentryEventID; use mas_data_model::TokenType; use mas_storage::{ + BoxClock, BoxRepository, BoxRng, Clock, RepositoryAccess, compat::{CompatAccessTokenRepository, CompatSessionRepository}, queue::{QueueJobRepositoryExt as _, SyncDevicesJob}, - BoxClock, BoxRepository, BoxRng, Clock, RepositoryAccess, }; use thiserror::Error; use super::MatrixError; -use crate::{impl_from_error_for_route, BoundActivityTracker}; +use crate::{BoundActivityTracker, impl_from_error_for_route}; #[derive(Error, Debug)] pub enum RouteError { diff --git a/crates/handlers/src/compat/mod.rs b/crates/handlers/src/compat/mod.rs index c36cd16bb..ad7ba4909 100644 --- a/crates/handlers/src/compat/mod.rs +++ b/crates/handlers/src/compat/mod.rs @@ -4,7 +4,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use axum::{response::IntoResponse, Json}; +use axum::{Json, response::IntoResponse}; use hyper::StatusCode; use serde::Serialize; diff --git a/crates/handlers/src/compat/refresh.rs b/crates/handlers/src/compat/refresh.rs index 14d71f1b7..9e3675910 100644 --- a/crates/handlers/src/compat/refresh.rs +++ b/crates/handlers/src/compat/refresh.rs @@ -4,21 +4,21 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use axum::{extract::State, response::IntoResponse, Json}; +use axum::{Json, extract::State, response::IntoResponse}; use chrono::Duration; use hyper::StatusCode; use mas_axum_utils::sentry::SentryEventID; use mas_data_model::{SiteConfig, TokenFormatError, TokenType}; use mas_storage::{ - compat::{CompatAccessTokenRepository, CompatRefreshTokenRepository, CompatSessionRepository}, BoxClock, BoxRepository, BoxRng, Clock, + compat::{CompatAccessTokenRepository, CompatRefreshTokenRepository, CompatSessionRepository}, }; use serde::{Deserialize, Serialize}; -use serde_with::{serde_as, DurationMilliSeconds}; +use serde_with::{DurationMilliSeconds, serde_as}; use thiserror::Error; use super::MatrixError; -use crate::{impl_from_error_for_route, BoundActivityTracker}; +use crate::{BoundActivityTracker, impl_from_error_for_route}; #[derive(Debug, Deserialize)] pub struct RequestBody { diff --git a/crates/handlers/src/graphql/mod.rs b/crates/handlers/src/graphql/mod.rs index 0fc5209c2..306f50cdd 100644 --- a/crates/handlers/src/graphql/mod.rs +++ b/crates/handlers/src/graphql/mod.rs @@ -9,24 +9,24 @@ use std::{net::IpAddr, ops::Deref, sync::Arc}; use async_graphql::{ - extensions::Tracing, - http::{playground_source, GraphQLPlaygroundConfig, MultipartOptions}, EmptySubscription, InputObject, + extensions::Tracing, + http::{GraphQLPlaygroundConfig, MultipartOptions, playground_source}, }; use axum::{ + Extension, Json, body::Body, extract::{RawQuery, State as AxumState}, http::StatusCode, response::{Html, IntoResponse, Response}, - Extension, Json, }; use axum_extra::typed_header::TypedHeader; use chrono::{DateTime, Utc}; use futures_util::TryStreamExt; -use headers::{authorization::Bearer, Authorization, ContentType, HeaderValue}; +use headers::{Authorization, ContentType, HeaderValue, authorization::Bearer}; use hyper::header::CACHE_CONTROL; use mas_axum_utils::{ - cookies::CookieJar, sentry::SentryEventID, FancyError, SessionInfo, SessionInfoExt, + FancyError, SessionInfo, SessionInfoExt, cookies::CookieJar, sentry::SentryEventID, }; use mas_data_model::{BrowserSession, Session, SiteConfig, User}; use mas_matrix::HomeserverConnection; @@ -35,10 +35,10 @@ use mas_router::UrlBuilder; use mas_storage::{BoxClock, BoxRepository, BoxRng, Clock, RepositoryError, SystemClock}; use mas_storage_pg::PgRepository; use opentelemetry_semantic_conventions::trace::{GRAPHQL_DOCUMENT, GRAPHQL_OPERATION_NAME}; -use rand::{thread_rng, SeedableRng}; +use rand::{SeedableRng, thread_rng}; use rand_chacha::ChaChaRng; use sqlx::PgPool; -use tracing::{info_span, Instrument}; +use tracing::{Instrument, info_span}; use ulid::Ulid; mod model; @@ -53,8 +53,8 @@ use self::{ query::Query, }; use crate::{ - impl_from_error_for_route, passwords::PasswordManager, BoundActivityTracker, Limiter, - RequesterFingerprint, + BoundActivityTracker, Limiter, RequesterFingerprint, impl_from_error_for_route, + passwords::PasswordManager, }; #[cfg(test)] @@ -276,7 +276,7 @@ async fn get_requester( }; // If there is a user for this session, check that it is not locked - let user_valid = user.as_ref().map_or(true, User::is_valid); + let user_valid = user.as_ref().is_none_or(User::is_valid); if !token.is_valid(clock.now()) || !session.is_valid() || !user_valid { return Err(RouteError::InvalidToken); diff --git a/crates/handlers/src/graphql/model/browser_sessions.rs b/crates/handlers/src/graphql/model/browser_sessions.rs index 4630b2fc6..15046ebb5 100644 --- a/crates/handlers/src/graphql/model/browser_sessions.rs +++ b/crates/handlers/src/graphql/model/browser_sessions.rs @@ -5,13 +5,13 @@ // Please see LICENSE in the repository root for full details. use async_graphql::{ - connection::{query, Connection, Edge, OpaqueCursor}, - Context, Description, Object, ID, + Context, Description, ID, Object, + connection::{Connection, Edge, OpaqueCursor, query}, }; use chrono::{DateTime, Utc}; use mas_data_model::Device; use mas_storage::{ - app_session::AppSessionFilter, user::BrowserSessionRepository, Pagination, RepositoryAccess, + Pagination, RepositoryAccess, app_session::AppSessionFilter, user::BrowserSessionRepository, }; use super::{ @@ -122,7 +122,7 @@ impl BrowserSession { before, first, last, - |after, before, first, last| async move { + async |after, before, first, last| { let after_id = after .map(|x: OpaqueCursor| { x.extract_for_types(&[NodeType::OAuth2Session, NodeType::CompatSession]) diff --git a/crates/handlers/src/graphql/model/compat_sessions.rs b/crates/handlers/src/graphql/model/compat_sessions.rs index cc5269416..1ac53a558 100644 --- a/crates/handlers/src/graphql/model/compat_sessions.rs +++ b/crates/handlers/src/graphql/model/compat_sessions.rs @@ -5,7 +5,7 @@ // Please see LICENSE in the repository root for full details. use anyhow::Context as _; -use async_graphql::{Context, Description, Enum, Object, ID}; +use async_graphql::{Context, Description, Enum, ID, Object}; use chrono::{DateTime, Utc}; use mas_data_model::Device; use mas_storage::{compat::CompatSessionRepository, user::UserRepository}; diff --git a/crates/handlers/src/graphql/model/mod.rs b/crates/handlers/src/graphql/model/mod.rs index 54bddb2a4..5a3137edf 100644 --- a/crates/handlers/src/graphql/model/mod.rs +++ b/crates/handlers/src/graphql/model/mod.rs @@ -24,7 +24,7 @@ pub use self::{ cursor::{Cursor, NodeCursor}, node::{Node, NodeType}, oauth::{OAuth2Client, OAuth2Session}, - site_config::{SiteConfig, SITE_CONFIG_ID}, + site_config::{SITE_CONFIG_ID, SiteConfig}, upstream_oauth::{UpstreamOAuth2Link, UpstreamOAuth2Provider}, users::{AppSession, User, UserEmail, UserEmailAuthentication, UserRecoveryTicket}, viewer::{Anonymous, Viewer, ViewerSession}, diff --git a/crates/handlers/src/graphql/model/node.rs b/crates/handlers/src/graphql/model/node.rs index 592aae2c7..aa61f4b62 100644 --- a/crates/handlers/src/graphql/model/node.rs +++ b/crates/handlers/src/graphql/model/node.rs @@ -4,7 +4,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use async_graphql::{Interface, ID}; +use async_graphql::{ID, Interface}; use serde::{Deserialize, Serialize}; use thiserror::Error; use ulid::Ulid; diff --git a/crates/handlers/src/graphql/model/oauth.rs b/crates/handlers/src/graphql/model/oauth.rs index 22f9d84ec..fec318eb8 100644 --- a/crates/handlers/src/graphql/model/oauth.rs +++ b/crates/handlers/src/graphql/model/oauth.rs @@ -5,7 +5,7 @@ // Please see LICENSE in the repository root for full details. use anyhow::Context as _; -use async_graphql::{Context, Description, Enum, Object, ID}; +use async_graphql::{Context, Description, Enum, ID, Object}; use chrono::{DateTime, Utc}; use mas_storage::{oauth2::OAuth2ClientRepository, user::BrowserSessionRepository}; use oauth2_types::{oidc::ApplicationType, scope::Scope}; @@ -13,7 +13,7 @@ use ulid::Ulid; use url::Url; use super::{BrowserSession, NodeType, SessionState, User, UserAgent}; -use crate::graphql::{state::ContextExt, UserId}; +use crate::graphql::{UserId, state::ContextExt}; /// An OAuth 2.0 session represents a client session which used the OAuth APIs /// to login. diff --git a/crates/handlers/src/graphql/model/site_config.rs b/crates/handlers/src/graphql/model/site_config.rs index 765ca7547..dc2cae188 100644 --- a/crates/handlers/src/graphql/model/site_config.rs +++ b/crates/handlers/src/graphql/model/site_config.rs @@ -6,7 +6,7 @@ #![allow(clippy::str_to_string)] // ComplexObject macro uses &str.to_string() -use async_graphql::{ComplexObject, Enum, SimpleObject, ID}; +use async_graphql::{ComplexObject, Enum, ID, SimpleObject}; use url::Url; pub const SITE_CONFIG_ID: &str = "site_config"; diff --git a/crates/handlers/src/graphql/model/upstream_oauth.rs b/crates/handlers/src/graphql/model/upstream_oauth.rs index f0a206486..a2061210b 100644 --- a/crates/handlers/src/graphql/model/upstream_oauth.rs +++ b/crates/handlers/src/graphql/model/upstream_oauth.rs @@ -5,7 +5,7 @@ // Please see LICENSE in the repository root for full details. use anyhow::Context as _; -use async_graphql::{Context, Object, ID}; +use async_graphql::{Context, ID, Object}; use chrono::{DateTime, Utc}; use mas_storage::{upstream_oauth2::UpstreamOAuthProviderRepository, user::UserRepository}; use url::Url; diff --git a/crates/handlers/src/graphql/model/users.rs b/crates/handlers/src/graphql/model/users.rs index 15cd95206..9287c62da 100644 --- a/crates/handlers/src/graphql/model/users.rs +++ b/crates/handlers/src/graphql/model/users.rs @@ -6,27 +6,27 @@ use anyhow::Context as _; use async_graphql::{ - connection::{query, Connection, Edge, OpaqueCursor}, - Context, Description, Enum, Object, Union, ID, + Context, Description, Enum, ID, Object, Union, + connection::{Connection, Edge, OpaqueCursor, query}, }; use chrono::{DateTime, Utc}; use mas_data_model::Device; use mas_storage::{ + Pagination, RepositoryAccess, app_session::AppSessionFilter, compat::{CompatSessionFilter, CompatSsoLoginFilter, CompatSsoLoginRepository}, oauth2::{OAuth2SessionFilter, OAuth2SessionRepository}, upstream_oauth2::{UpstreamOAuthLinkFilter, UpstreamOAuthLinkRepository}, user::{BrowserSessionFilter, BrowserSessionRepository, UserEmailFilter, UserEmailRepository}, - Pagination, RepositoryAccess, }; use super::{ - compat_sessions::{CompatSessionType, CompatSsoLogin}, - matrix::MatrixUser, BrowserSession, CompatSession, Cursor, NodeCursor, NodeType, OAuth2Session, PreloadedTotalCount, SessionState, UpstreamOAuth2Link, + compat_sessions::{CompatSessionType, CompatSsoLogin}, + matrix::MatrixUser, }; -use crate::graphql::{state::ContextExt, DateFilter}; +use crate::graphql::{DateFilter, state::ContextExt}; #[derive(Description)] /// A user is an individual's account. @@ -98,7 +98,7 @@ impl User { before, first, last, - |after, before, first, last| async move { + async |after, before, first, last| { let after_id = after .map(|x: OpaqueCursor| x.extract_for_type(NodeType::CompatSsoLogin)) .transpose()?; @@ -172,7 +172,7 @@ impl User { before, first, last, - |after, before, first, last| async move { + async |after, before, first, last| { let after_id = after .map(|x: OpaqueCursor| x.extract_for_type(NodeType::CompatSession)) .transpose()?; @@ -264,7 +264,7 @@ impl User { before, first, last, - |after, before, first, last| async move { + async |after, before, first, last| { let after_id = after .map(|x: OpaqueCursor| x.extract_for_type(NodeType::BrowserSession)) .transpose()?; @@ -346,7 +346,7 @@ impl User { before, first, last, - |after, before, first, last| async move { + async |after, before, first, last| { let after_id = after .map(|x: OpaqueCursor| x.extract_for_type(NodeType::UserEmail)) .transpose()?; @@ -419,7 +419,7 @@ impl User { before, first, last, - |after, before, first, last| async move { + async |after, before, first, last| { let after_id = after .map(|x: OpaqueCursor| x.extract_for_type(NodeType::OAuth2Session)) .transpose()?; @@ -514,7 +514,7 @@ impl User { before, first, last, - |after, before, first, last| async move { + async |after, before, first, last| { let after_id = after .map(|x: OpaqueCursor| { x.extract_for_type(NodeType::UpstreamOAuth2Link) @@ -602,7 +602,7 @@ impl User { before, first, last, - |after, before, first, last| async move { + async |after, before, first, last| { let after_id = after .map(|x: OpaqueCursor| { x.extract_for_types(&[NodeType::OAuth2Session, NodeType::CompatSession]) diff --git a/crates/handlers/src/graphql/model/viewer/anonymous.rs b/crates/handlers/src/graphql/model/viewer/anonymous.rs index 61f6524c1..e3b4e5273 100644 --- a/crates/handlers/src/graphql/model/viewer/anonymous.rs +++ b/crates/handlers/src/graphql/model/viewer/anonymous.rs @@ -4,7 +4,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use async_graphql::{Object, ID}; +use async_graphql::{ID, Object}; /// An anonymous viewer #[derive(Default, Clone, Copy)] diff --git a/crates/handlers/src/graphql/mutations/browser_session.rs b/crates/handlers/src/graphql/mutations/browser_session.rs index 5c3f6f553..8e43e5699 100644 --- a/crates/handlers/src/graphql/mutations/browser_session.rs +++ b/crates/handlers/src/graphql/mutations/browser_session.rs @@ -4,7 +4,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use async_graphql::{Context, Enum, InputObject, Object, ID}; +use async_graphql::{Context, Enum, ID, InputObject, Object}; use mas_storage::RepositoryAccess; use crate::graphql::{ diff --git a/crates/handlers/src/graphql/mutations/compat_session.rs b/crates/handlers/src/graphql/mutations/compat_session.rs index c13c1e559..48bf23f81 100644 --- a/crates/handlers/src/graphql/mutations/compat_session.rs +++ b/crates/handlers/src/graphql/mutations/compat_session.rs @@ -5,11 +5,11 @@ // Please see LICENSE in the repository root for full details. use anyhow::Context as _; -use async_graphql::{Context, Enum, InputObject, Object, ID}; +use async_graphql::{Context, Enum, ID, InputObject, Object}; use mas_storage::{ + RepositoryAccess, compat::CompatSessionRepository, queue::{QueueJobRepositoryExt as _, SyncDevicesJob}, - RepositoryAccess, }; use crate::graphql::{ diff --git a/crates/handlers/src/graphql/mutations/matrix.rs b/crates/handlers/src/graphql/mutations/matrix.rs index 93983b523..8788b493c 100644 --- a/crates/handlers/src/graphql/mutations/matrix.rs +++ b/crates/handlers/src/graphql/mutations/matrix.rs @@ -5,12 +5,12 @@ // Please see LICENSE in the repository root for full details. use anyhow::Context as _; -use async_graphql::{Context, Description, Enum, InputObject, Object, ID}; +use async_graphql::{Context, Description, Enum, ID, InputObject, Object}; use crate::graphql::{ + UserId, model::{NodeType, User}, state::ContextExt, - UserId, }; #[derive(Default)] diff --git a/crates/handlers/src/graphql/mutations/oauth2_session.rs b/crates/handlers/src/graphql/mutations/oauth2_session.rs index 0b1dbe669..4278d20a2 100644 --- a/crates/handlers/src/graphql/mutations/oauth2_session.rs +++ b/crates/handlers/src/graphql/mutations/oauth2_session.rs @@ -5,17 +5,17 @@ // Please see LICENSE in the repository root for full details. use anyhow::Context as _; -use async_graphql::{Context, Description, Enum, InputObject, Object, ID}; +use async_graphql::{Context, Description, Enum, ID, InputObject, Object}; use chrono::Duration; use mas_data_model::{Device, TokenType}; use mas_storage::{ + RepositoryAccess, oauth2::{ OAuth2AccessTokenRepository, OAuth2ClientRepository, OAuth2RefreshTokenRepository, OAuth2SessionRepository, }, queue::{QueueJobRepositoryExt as _, SyncDevicesJob}, user::UserRepository, - RepositoryAccess, }; use oauth2_types::scope::Scope; diff --git a/crates/handlers/src/graphql/mutations/user.rs b/crates/handlers/src/graphql/mutations/user.rs index 311a1dcb7..bb50d1b04 100644 --- a/crates/handlers/src/graphql/mutations/user.rs +++ b/crates/handlers/src/graphql/mutations/user.rs @@ -5,7 +5,7 @@ // Please see LICENSE in the repository root for full details. use anyhow::Context as _; -use async_graphql::{Context, Description, Enum, InputObject, Object, ID}; +use async_graphql::{Context, Description, Enum, ID, InputObject, Object}; use mas_storage::{ queue::{ DeactivateUserJob, ProvisionUserJob, QueueJobRepositoryExt as _, @@ -19,9 +19,9 @@ use url::Url; use zeroize::Zeroizing; use crate::graphql::{ + UserId, model::{NodeType, User}, state::ContextExt, - UserId, }; #[derive(Default)] @@ -679,7 +679,7 @@ impl UserMutations { let Some(current_password_attempt) = input.current_password else { return Err(async_graphql::Error::new( - "You must supply `currentPassword` to change your own password if you are not an administrator" + "You must supply `currentPassword` to change your own password if you are not an administrator", )); }; diff --git a/crates/handlers/src/graphql/mutations/user_email.rs b/crates/handlers/src/graphql/mutations/user_email.rs index ba7aef776..cbbb10142 100644 --- a/crates/handlers/src/graphql/mutations/user_email.rs +++ b/crates/handlers/src/graphql/mutations/user_email.rs @@ -5,12 +5,12 @@ // Please see LICENSE in the repository root for full details. use anyhow::Context as _; -use async_graphql::{Context, Description, Enum, InputObject, Object, ID}; +use async_graphql::{Context, Description, Enum, ID, InputObject, Object}; use mas_i18n::DataLocale; use mas_storage::{ + RepositoryAccess, queue::{ProvisionUserJob, QueueJobRepositoryExt as _, SendEmailAuthenticationCodeJob}, user::{UserEmailFilter, UserEmailRepository, UserRepository}, - RepositoryAccess, }; use crate::graphql::{ diff --git a/crates/handlers/src/graphql/query/mod.rs b/crates/handlers/src/graphql/query/mod.rs index 464657c47..eb86150e5 100644 --- a/crates/handlers/src/graphql/query/mod.rs +++ b/crates/handlers/src/graphql/query/mod.rs @@ -4,7 +4,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use async_graphql::{Context, MergedObject, Object, ID}; +use async_graphql::{Context, ID, MergedObject, Object}; use crate::graphql::{ model::{ diff --git a/crates/handlers/src/graphql/query/session.rs b/crates/handlers/src/graphql/query/session.rs index dba916dff..db1e7eed9 100644 --- a/crates/handlers/src/graphql/query/session.rs +++ b/crates/handlers/src/graphql/query/session.rs @@ -4,19 +4,19 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use async_graphql::{Context, Object, Union, ID}; +use async_graphql::{Context, ID, Object, Union}; use mas_data_model::Device; use mas_storage::{ + Pagination, RepositoryAccess, compat::{CompatSessionFilter, CompatSessionRepository}, oauth2::OAuth2SessionFilter, - Pagination, RepositoryAccess, }; use oauth2_types::scope::Scope; use crate::graphql::{ + UserId, model::{CompatSession, NodeType, OAuth2Session}, state::ContextExt, - UserId, }; #[derive(Default)] diff --git a/crates/handlers/src/graphql/query/upstream_oauth.rs b/crates/handlers/src/graphql/query/upstream_oauth.rs index 94f12be59..b007425aa 100644 --- a/crates/handlers/src/graphql/query/upstream_oauth.rs +++ b/crates/handlers/src/graphql/query/upstream_oauth.rs @@ -5,10 +5,10 @@ // Please see LICENSE in the repository root for full details. use async_graphql::{ - connection::{query, Connection, Edge, OpaqueCursor}, - Context, Object, ID, + Context, ID, Object, + connection::{Connection, Edge, OpaqueCursor, query}, }; -use mas_storage::{upstream_oauth2::UpstreamOAuthProviderFilter, Pagination, RepositoryAccess}; +use mas_storage::{Pagination, RepositoryAccess, upstream_oauth2::UpstreamOAuthProviderFilter}; use crate::graphql::{ model::{ @@ -94,7 +94,7 @@ impl UpstreamOAuthQuery { before, first, last, - |after, before, first, last| async move { + async |after, before, first, last| { let after_id = after .map(|x: OpaqueCursor| { x.extract_for_type(NodeType::UpstreamOAuth2Provider) diff --git a/crates/handlers/src/graphql/query/user.rs b/crates/handlers/src/graphql/query/user.rs index 07ff83646..9a2eeef45 100644 --- a/crates/handlers/src/graphql/query/user.rs +++ b/crates/handlers/src/graphql/query/user.rs @@ -5,15 +5,15 @@ // Please see LICENSE in the repository root for full details. use async_graphql::{ - connection::{query, Connection, Edge, OpaqueCursor}, - Context, Enum, Object, ID, + Context, Enum, ID, Object, + connection::{Connection, Edge, OpaqueCursor, query}, }; -use mas_storage::{user::UserFilter, Pagination}; +use mas_storage::{Pagination, user::UserFilter}; use crate::graphql::{ + UserId, model::{Cursor, NodeCursor, NodeType, PreloadedTotalCount, User}, state::ContextExt as _, - UserId, }; #[derive(Default)] @@ -105,7 +105,7 @@ impl UserQuery { before, first, last, - |after, before, first, last| async move { + async |after, before, first, last| { let after_id = after .map(|x: OpaqueCursor| x.extract_for_type(NodeType::User)) .transpose()?; diff --git a/crates/handlers/src/graphql/state.rs b/crates/handlers/src/graphql/state.rs index 95752c4fd..fe5c07158 100644 --- a/crates/handlers/src/graphql/state.rs +++ b/crates/handlers/src/graphql/state.rs @@ -10,7 +10,7 @@ use mas_policy::Policy; use mas_router::UrlBuilder; use mas_storage::{BoxClock, BoxRepository, BoxRng, RepositoryError}; -use crate::{graphql::Requester, passwords::PasswordManager, Limiter}; +use crate::{Limiter, graphql::Requester, passwords::PasswordManager}; #[async_trait::async_trait] pub trait State { diff --git a/crates/handlers/src/graphql/tests.rs b/crates/handlers/src/graphql/tests.rs index a830f2448..02399884b 100644 --- a/crates/handlers/src/graphql/tests.rs +++ b/crates/handlers/src/graphql/tests.rs @@ -10,19 +10,19 @@ use mas_data_model::{AccessToken, Client, TokenType, User}; use mas_matrix::{HomeserverConnection, ProvisionRequest}; use mas_router::SimpleRoute; use mas_storage::{ - oauth2::{OAuth2AccessTokenRepository, OAuth2ClientRepository}, RepositoryAccess, + oauth2::{OAuth2AccessTokenRepository, OAuth2ClientRepository}, }; use oauth2_types::{ registration::ClientRegistrationResponse, requests::AccessTokenResponse, - scope::{Scope, ScopeToken, OPENID}, + scope::{OPENID, Scope, ScopeToken}, }; use sqlx::PgPool; use crate::{ test_utils, - test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}, + test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}, }; async fn create_test_client(state: &TestState) -> Client { diff --git a/crates/handlers/src/health.rs b/crates/handlers/src/health.rs index ab56ae9c7..f8a2672d7 100644 --- a/crates/handlers/src/health.rs +++ b/crates/handlers/src/health.rs @@ -7,7 +7,7 @@ use axum::{extract::State, response::IntoResponse}; use mas_axum_utils::FancyError; use sqlx::PgPool; -use tracing::{info_span, Instrument}; +use tracing::{Instrument, info_span}; pub async fn get(State(pool): State) -> Result { let mut conn = pool.acquire().await?; @@ -26,7 +26,7 @@ mod tests { use hyper::{Request, StatusCode}; use super::*; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_get_health(pool: PgPool) { diff --git a/crates/handlers/src/lib.rs b/crates/handlers/src/lib.rs index 1dd7b5ef0..5ba623876 100644 --- a/crates/handlers/src/lib.rs +++ b/crates/handlers/src/lib.rs @@ -18,20 +18,20 @@ use std::{convert::Infallible, sync::LazyLock, time::Duration}; use axum::{ + Extension, Router, extract::{FromRef, FromRequestParts, OriginalUri, RawQuery, State}, http::Method, response::{Html, IntoResponse}, routing::{get, post}, - Extension, Router, }; use headers::HeaderName; use hyper::{ + StatusCode, Version, header::{ ACCEPT, ACCEPT_LANGUAGE, AUTHORIZATION, CONTENT_LANGUAGE, CONTENT_LENGTH, CONTENT_TYPE, }, - StatusCode, Version, }; -use mas_axum_utils::{cookies::CookieJar, FancyError}; +use mas_axum_utils::{FancyError, cookies::CookieJar}; use mas_data_model::SiteConfig; use mas_http::CorsLayerExt; use mas_keystore::{Encrypter, Keystore}; @@ -88,13 +88,13 @@ macro_rules! impl_from_error_for_route { }; } -pub use mas_axum_utils::{cookies::CookieManager, ErrorWrapper}; +pub use mas_axum_utils::{ErrorWrapper, cookies::CookieManager}; pub use self::{ activity_tracker::{ActivityTracker, Bound as BoundActivityTracker}, admin::router as admin_api_router, graphql::{ - schema as graphql_schema, schema_builder as graphql_schema_builder, Schema as GraphQLSchema, + Schema as GraphQLSchema, schema as graphql_schema, schema_builder as graphql_schema_builder, }, preferred_language::PreferredLanguage, rate_limit::{Limiter, RequesterFingerprint}, @@ -332,7 +332,7 @@ where .route( "/account", get( - |State(url_builder): State, RawQuery(query): RawQuery| async move { + async |State(url_builder): State, RawQuery(query): RawQuery| { let prefix = url_builder.prefix().unwrap_or_default(); let route = mas_router::Account::route(); let destination = if let Some(query) = query { @@ -356,7 +356,7 @@ where ) .route( mas_router::ChangePasswordDiscovery::route(), - get(|State(url_builder): State| async move { + get(async |State(url_builder): State| { url_builder.redirect(&mas_router::AccountPasswordChange) }), ) @@ -438,7 +438,7 @@ where get(self::oauth2::device::consent::get).post(self::oauth2::device::consent::post), ) .layer(AndThenLayer::new( - move |response: axum::response::Response| async move { + async move |response: axum::response::Response| { if response.status().is_server_error() { // Error responses should have an ErrorContext attached to them let ext = response.extensions().get::(); diff --git a/crates/handlers/src/oauth2/authorization/complete.rs b/crates/handlers/src/oauth2/authorization/complete.rs index 8c3faf5b7..c5aab02cb 100644 --- a/crates/handlers/src/oauth2/authorization/complete.rs +++ b/crates/handlers/src/oauth2/authorization/complete.rs @@ -10,15 +10,15 @@ use axum::{ }; use axum_extra::TypedHeader; use hyper::StatusCode; -use mas_axum_utils::{cookies::CookieJar, csrf::CsrfExt, sentry::SentryEventID, SessionInfoExt}; +use mas_axum_utils::{SessionInfoExt, cookies::CookieJar, csrf::CsrfExt, sentry::SentryEventID}; use mas_data_model::{AuthorizationGrant, BrowserSession, Client, Device}; use mas_keystore::Keystore; use mas_policy::{EvaluationResult, Policy}; use mas_router::{PostAuthAction, UrlBuilder}; use mas_storage::{ + BoxClock, BoxRepository, BoxRng, Clock, RepositoryAccess, oauth2::{OAuth2AuthorizationGrantRepository, OAuth2ClientRepository, OAuth2SessionRepository}, user::BrowserSessionRepository, - BoxClock, BoxRepository, BoxRng, Clock, RepositoryAccess, }; use mas_templates::{PolicyViolationContext, TemplateContext, Templates}; use oauth2_types::requests::AuthorizationResponse; @@ -28,7 +28,7 @@ use ulid::Ulid; use super::callback::CallbackDestination; use crate::{ - impl_from_error_for_route, oauth2::generate_id_token, BoundActivityTracker, PreferredLanguage, + BoundActivityTracker, PreferredLanguage, impl_from_error_for_route, oauth2::generate_id_token, }; #[derive(Debug, Error)] diff --git a/crates/handlers/src/oauth2/authorization/mod.rs b/crates/handlers/src/oauth2/authorization/mod.rs index 27b121e95..bca78ec47 100644 --- a/crates/handlers/src/oauth2/authorization/mod.rs +++ b/crates/handlers/src/oauth2/authorization/mod.rs @@ -10,14 +10,14 @@ use axum::{ }; use axum_extra::TypedHeader; use hyper::StatusCode; -use mas_axum_utils::{cookies::CookieJar, csrf::CsrfExt, sentry::SentryEventID, SessionInfoExt}; +use mas_axum_utils::{SessionInfoExt, cookies::CookieJar, csrf::CsrfExt, sentry::SentryEventID}; use mas_data_model::{AuthorizationCode, Pkce}; use mas_keystore::Keystore; use mas_policy::Policy; use mas_router::{PostAuthAction, UrlBuilder}; use mas_storage::{ - oauth2::{OAuth2AuthorizationGrantRepository, OAuth2ClientRepository}, BoxClock, BoxRepository, BoxRng, + oauth2::{OAuth2AuthorizationGrantRepository, OAuth2ClientRepository}, }; use mas_templates::{PolicyViolationContext, TemplateContext, Templates}; use oauth2_types::{ @@ -26,13 +26,13 @@ use oauth2_types::{ requests::{AuthorizationRequest, GrantType, Prompt, ResponseMode}, response_type::ResponseType, }; -use rand::{distributions::Alphanumeric, Rng}; +use rand::{Rng, distributions::Alphanumeric}; use serde::Deserialize; use thiserror::Error; use tracing::warn; use self::{callback::CallbackDestination, complete::GrantCompletionError}; -use crate::{impl_from_error_for_route, BoundActivityTracker, PreferredLanguage}; +use crate::{BoundActivityTracker, PreferredLanguage, impl_from_error_for_route}; mod callback; pub mod complete; diff --git a/crates/handlers/src/oauth2/consent.rs b/crates/handlers/src/oauth2/consent.rs index f7b4b72fc..264a00583 100644 --- a/crates/handlers/src/oauth2/consent.rs +++ b/crates/handlers/src/oauth2/consent.rs @@ -11,23 +11,23 @@ use axum::{ use axum_extra::TypedHeader; use hyper::StatusCode; use mas_axum_utils::{ + SessionInfoExt, cookies::CookieJar, csrf::{CsrfExt, ProtectedForm}, sentry::SentryEventID, - SessionInfoExt, }; use mas_data_model::{AuthorizationGrantStage, Device}; use mas_policy::Policy; use mas_router::{PostAuthAction, UrlBuilder}; use mas_storage::{ - oauth2::{OAuth2AuthorizationGrantRepository, OAuth2ClientRepository}, BoxClock, BoxRepository, BoxRng, + oauth2::{OAuth2AuthorizationGrantRepository, OAuth2ClientRepository}, }; use mas_templates::{ConsentContext, PolicyViolationContext, TemplateContext, Templates}; use thiserror::Error; use ulid::Ulid; -use crate::{impl_from_error_for_route, BoundActivityTracker, PreferredLanguage}; +use crate::{BoundActivityTracker, PreferredLanguage, impl_from_error_for_route}; #[derive(Debug, Error)] pub enum RouteError { diff --git a/crates/handlers/src/oauth2/device/authorize.rs b/crates/handlers/src/oauth2/device/authorize.rs index 4c4c675d1..e38bf17fd 100644 --- a/crates/handlers/src/oauth2/device/authorize.rs +++ b/crates/handlers/src/oauth2/device/authorize.rs @@ -4,7 +4,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use axum::{extract::State, response::IntoResponse, Json}; +use axum::{Json, extract::State, response::IntoResponse}; use axum_extra::typed_header::TypedHeader; use chrono::Duration; use headers::{CacheControl, Pragma}; @@ -16,7 +16,7 @@ use mas_axum_utils::{ use mas_data_model::UserAgent; use mas_keystore::Encrypter; use mas_router::UrlBuilder; -use mas_storage::{oauth2::OAuth2DeviceCodeGrantParams, BoxClock, BoxRepository, BoxRng}; +use mas_storage::{BoxClock, BoxRepository, BoxRng, oauth2::OAuth2DeviceCodeGrantParams}; use oauth2_types::{ errors::{ClientError, ClientErrorCode}, requests::{DeviceAuthorizationRequest, DeviceAuthorizationResponse, GrantType}, @@ -25,7 +25,7 @@ use oauth2_types::{ use rand::distributions::{Alphanumeric, DistString}; use thiserror::Error; -use crate::{impl_from_error_for_route, BoundActivityTracker}; +use crate::{BoundActivityTracker, impl_from_error_for_route}; #[derive(Debug, Error)] pub(crate) enum RouteError { @@ -164,7 +164,7 @@ mod tests { }; use sqlx::PgPool; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_device_code_request(pool: PgPool) { diff --git a/crates/handlers/src/oauth2/device/consent.rs b/crates/handlers/src/oauth2/device/consent.rs index ac8bdd63b..4b2262bd9 100644 --- a/crates/handlers/src/oauth2/device/consent.rs +++ b/crates/handlers/src/oauth2/device/consent.rs @@ -6,15 +6,15 @@ use anyhow::Context; use axum::{ + Form, extract::{Path, State}, response::{Html, IntoResponse, Response}, - Form, }; use axum_extra::TypedHeader; use mas_axum_utils::{ + FancyError, SessionInfoExt, cookies::CookieJar, csrf::{CsrfExt, ProtectedForm}, - FancyError, SessionInfoExt, }; use mas_policy::Policy; use mas_router::UrlBuilder; diff --git a/crates/handlers/src/oauth2/device/link.rs b/crates/handlers/src/oauth2/device/link.rs index 7d8ffc5eb..389aa858e 100644 --- a/crates/handlers/src/oauth2/device/link.rs +++ b/crates/handlers/src/oauth2/device/link.rs @@ -8,7 +8,7 @@ use axum::{ extract::{Query, State}, response::{Html, IntoResponse}, }; -use mas_axum_utils::{cookies::CookieJar, FancyError}; +use mas_axum_utils::{FancyError, cookies::CookieJar}; use mas_router::UrlBuilder; use mas_storage::{BoxClock, BoxRepository}; use mas_templates::{ diff --git a/crates/handlers/src/oauth2/discovery.rs b/crates/handlers/src/oauth2/discovery.rs index a3a48208e..e72ebb358 100644 --- a/crates/handlers/src/oauth2/discovery.rs +++ b/crates/handlers/src/oauth2/discovery.rs @@ -4,7 +4,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use axum::{extract::State, response::IntoResponse, Json}; +use axum::{Json, extract::State, response::IntoResponse}; use mas_iana::oauth::{ OAuthAuthorizationEndpointResponseType, OAuthClientAuthenticationMethod, PkceCodeChallengeMethod, @@ -198,7 +198,7 @@ mod tests { use oauth2_types::oidc::ProviderMetadata; use sqlx::PgPool; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_valid_discovery_metadata(pool: PgPool) { diff --git a/crates/handlers/src/oauth2/introspection.rs b/crates/handlers/src/oauth2/introspection.rs index 0b187278f..e44f28617 100644 --- a/crates/handlers/src/oauth2/introspection.rs +++ b/crates/handlers/src/oauth2/introspection.rs @@ -4,7 +4,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use axum::{extract::State, response::IntoResponse, Json}; +use axum::{Json, extract::State, response::IntoResponse}; use hyper::StatusCode; use mas_axum_utils::{ client_authorization::{ClientAuthorization, CredentialsVerificationError}, @@ -14,10 +14,10 @@ use mas_data_model::{Device, TokenFormatError, TokenType}; use mas_iana::oauth::{OAuthClientAuthenticationMethod, OAuthTokenTypeHint}; use mas_keystore::Encrypter; use mas_storage::{ + BoxClock, BoxRepository, Clock, compat::{CompatAccessTokenRepository, CompatRefreshTokenRepository, CompatSessionRepository}, oauth2::{OAuth2AccessTokenRepository, OAuth2RefreshTokenRepository, OAuth2SessionRepository}, user::UserRepository, - BoxClock, BoxRepository, Clock, }; use oauth2_types::{ errors::{ClientError, ClientErrorCode}, @@ -26,7 +26,7 @@ use oauth2_types::{ }; use thiserror::Error; -use crate::{impl_from_error_for_route, ActivityTracker}; +use crate::{ActivityTracker, impl_from_error_for_route}; #[derive(Debug, Error)] pub enum RouteError { @@ -470,7 +470,7 @@ mod tests { use oauth2_types::{ registration::ClientRegistrationResponse, requests::IntrospectionResponse, - scope::{Scope, OPENID}, + scope::{OPENID, Scope}, }; use serde_json::json; use sqlx::PgPool; @@ -478,7 +478,7 @@ mod tests { use crate::{ oauth2::generate_token_pair, - test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}, + test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}, }; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] diff --git a/crates/handlers/src/oauth2/keys.rs b/crates/handlers/src/oauth2/keys.rs index 6c6946476..bcb419969 100644 --- a/crates/handlers/src/oauth2/keys.rs +++ b/crates/handlers/src/oauth2/keys.rs @@ -4,7 +4,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use axum::{extract::State, response::IntoResponse, Json}; +use axum::{Json, extract::State, response::IntoResponse}; use mas_keystore::Keystore; #[tracing::instrument(name = "handlers.oauth2.keys.get", skip_all)] diff --git a/crates/handlers/src/oauth2/registration.rs b/crates/handlers/src/oauth2/registration.rs index fca11cf97..a89e4665f 100644 --- a/crates/handlers/src/oauth2/registration.rs +++ b/crates/handlers/src/oauth2/registration.rs @@ -4,14 +4,14 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use axum::{extract::State, response::IntoResponse, Json}; +use axum::{Json, extract::State, response::IntoResponse}; use axum_extra::TypedHeader; use hyper::StatusCode; use mas_axum_utils::sentry::SentryEventID; use mas_iana::oauth::OAuthClientAuthenticationMethod; use mas_keystore::Encrypter; use mas_policy::{Policy, Violation}; -use mas_storage::{oauth2::OAuth2ClientRepository, BoxClock, BoxRepository, BoxRng}; +use mas_storage::{BoxClock, BoxRepository, BoxRng, oauth2::OAuth2ClientRepository}; use oauth2_types::{ errors::{ClientError, ClientErrorCode}, registration::{ @@ -26,7 +26,7 @@ use thiserror::Error; use tracing::info; use url::Url; -use crate::{impl_from_error_for_route, BoundActivityTracker}; +use crate::{BoundActivityTracker, impl_from_error_for_route}; #[derive(Debug, Error)] pub(crate) enum RouteError { @@ -337,7 +337,7 @@ mod tests { use crate::{ oauth2::registration::host_is_public_suffix, - test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}, + test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}, }; #[test] diff --git a/crates/handlers/src/oauth2/revoke.rs b/crates/handlers/src/oauth2/revoke.rs index 557614c5e..bedd8fbf7 100644 --- a/crates/handlers/src/oauth2/revoke.rs +++ b/crates/handlers/src/oauth2/revoke.rs @@ -4,7 +4,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use axum::{extract::State, response::IntoResponse, Json}; +use axum::{Json, extract::State, response::IntoResponse}; use hyper::StatusCode; use mas_axum_utils::{ client_authorization::{ClientAuthorization, CredentialsVerificationError}, @@ -14,8 +14,8 @@ use mas_data_model::TokenType; use mas_iana::oauth::OAuthTokenTypeHint; use mas_keystore::Encrypter; use mas_storage::{ - queue::{QueueJobRepositoryExt as _, SyncDevicesJob}, BoxClock, BoxRepository, BoxRng, RepositoryAccess, + queue::{QueueJobRepositoryExt as _, SyncDevicesJob}, }; use oauth2_types::{ errors::{ClientError, ClientErrorCode}, @@ -23,7 +23,7 @@ use oauth2_types::{ }; use thiserror::Error; -use crate::{impl_from_error_for_route, BoundActivityTracker}; +use crate::{BoundActivityTracker, impl_from_error_for_route}; #[derive(Debug, Error)] pub(crate) enum RouteError { @@ -172,7 +172,7 @@ pub(crate) async fn post( // token type or if the token was a compat access/refresh token. In those cases, we return // an unknown token error. (Some(OAuthTokenTypeHint::AccessToken | OAuthTokenTypeHint::RefreshToken) | None, _) => { - return Err(RouteError::UnknownToken) + return Err(RouteError::UnknownToken); } (Some(_), _) => return Err(RouteError::UnsupportedTokenType), @@ -233,14 +233,14 @@ mod tests { use oauth2_types::{ registration::ClientRegistrationResponse, requests::AccessTokenResponse, - scope::{Scope, OPENID}, + scope::{OPENID, Scope}, }; use sqlx::PgPool; use super::*; use crate::{ oauth2::generate_token_pair, - test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}, + test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}, }; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] diff --git a/crates/handlers/src/oauth2/token.rs b/crates/handlers/src/oauth2/token.rs index 2c68cb782..5846d0d22 100644 --- a/crates/handlers/src/oauth2/token.rs +++ b/crates/handlers/src/oauth2/token.rs @@ -4,7 +4,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use axum::{extract::State, response::IntoResponse, Json}; +use axum::{Json, extract::State, response::IntoResponse}; use axum_extra::typed_header::TypedHeader; use chrono::Duration; use headers::{CacheControl, HeaderMap, HeaderMapExt, Pragma}; @@ -22,12 +22,12 @@ use mas_oidc_client::types::scope::ScopeToken; use mas_policy::Policy; use mas_router::UrlBuilder; use mas_storage::{ + BoxClock, BoxRepository, BoxRng, Clock, RepositoryAccess, oauth2::{ OAuth2AccessTokenRepository, OAuth2AuthorizationGrantRepository, OAuth2RefreshTokenRepository, OAuth2SessionRepository, }, user::BrowserSessionRepository, - BoxClock, BoxRepository, BoxRng, Clock, RepositoryAccess, }; use oauth2_types::{ errors::{ClientError, ClientErrorCode}, @@ -43,7 +43,7 @@ use tracing::{debug, info}; use ulid::Ulid; use super::{generate_id_token, generate_token_pair}; -use crate::{impl_from_error_for_route, BoundActivityTracker}; +use crate::{BoundActivityTracker, impl_from_error_for_route}; #[derive(Debug, Error)] pub(crate) enum RouteError { @@ -103,7 +103,9 @@ pub(crate) enum RouteError { )] NoSuchNextRefreshToken { next: Ulid, previous: Ulid }, - #[error("failed to load the access token ({access_token:?}) associated with the next refresh token ({refresh_token:?})")] + #[error( + "failed to load the access token ({access_token:?}) associated with the next refresh token ({refresh_token:?})" + )] NoSuchNextAccessToken { access_token: Ulid, refresh_token: Ulid, @@ -884,12 +886,12 @@ mod tests { use oauth2_types::{ registration::ClientRegistrationResponse, requests::{DeviceAuthorizationResponse, ResponseMode}, - scope::{Scope, OPENID}, + scope::{OPENID, Scope}, }; use sqlx::PgPool; use super::*; - use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_auth_code_grant(pool: PgPool) { diff --git a/crates/handlers/src/oauth2/userinfo.rs b/crates/handlers/src/oauth2/userinfo.rs index 6e5945376..052892b33 100644 --- a/crates/handlers/src/oauth2/userinfo.rs +++ b/crates/handlers/src/oauth2/userinfo.rs @@ -5,9 +5,9 @@ // Please see LICENSE in the repository root for full details. use axum::{ + Json, extract::State, response::{IntoResponse, Response}, - Json, }; use hyper::StatusCode; use mas_axum_utils::{ @@ -21,12 +21,12 @@ use mas_jose::{ }; use mas_keystore::Keystore; use mas_router::UrlBuilder; -use mas_storage::{oauth2::OAuth2ClientRepository, BoxClock, BoxRepository, BoxRng}; +use mas_storage::{BoxClock, BoxRepository, BoxRng, oauth2::OAuth2ClientRepository}; use serde::Serialize; use serde_with::skip_serializing_none; use thiserror::Error; -use crate::{impl_from_error_for_route, BoundActivityTracker}; +use crate::{BoundActivityTracker, impl_from_error_for_route}; #[skip_serializing_none] #[derive(Serialize)] diff --git a/crates/handlers/src/oauth2/webfinger.rs b/crates/handlers/src/oauth2/webfinger.rs index 39e4eaf34..5c4b3c96b 100644 --- a/crates/handlers/src/oauth2/webfinger.rs +++ b/crates/handlers/src/oauth2/webfinger.rs @@ -5,9 +5,9 @@ // Please see LICENSE in the repository root for full details. use axum::{ + Json, extract::{Query, State}, response::IntoResponse, - Json, }; use axum_extra::typed_header::TypedHeader; use headers::ContentType; diff --git a/crates/handlers/src/passwords.rs b/crates/handlers/src/passwords.rs index e227f4400..a3cd46ff4 100644 --- a/crates/handlers/src/passwords.rs +++ b/crates/handlers/src/passwords.rs @@ -7,10 +7,10 @@ use std::{collections::HashMap, sync::Arc}; use anyhow::Context; -use argon2::{password_hash::SaltString, Argon2, PasswordHash, PasswordHasher, PasswordVerifier}; +use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier, password_hash::SaltString}; use futures_util::future::OptionFuture; use pbkdf2::Pbkdf2; -use rand::{CryptoRng, Rng, RngCore, SeedableRng}; +use rand::{CryptoRng, RngCore, SeedableRng, distributions::Standard, prelude::Distribution}; use thiserror::Error; use zeroize::Zeroizing; use zxcvbn::zxcvbn; @@ -267,7 +267,7 @@ impl Algorithm { password.extend_from_slice(pepper); } - let salt = rng.gen(); + let salt = Standard.sample(&mut rng); let hashed = bcrypt::hash_with_salt(password, cost.unwrap_or(12), salt)?; Ok(hashed.format_for_version(bcrypt::Version::TwoB)) diff --git a/crates/handlers/src/preferred_language.rs b/crates/handlers/src/preferred_language.rs index e107e754d..cfa0e106d 100644 --- a/crates/handlers/src/preferred_language.rs +++ b/crates/handlers/src/preferred_language.rs @@ -12,7 +12,7 @@ use axum::{ }; use headers::HeaderMapExt as _; use mas_axum_utils::language_detection::AcceptLanguage; -use mas_i18n::{locale, DataLocale, Translator}; +use mas_i18n::{DataLocale, Translator, locale}; pub struct PreferredLanguage(pub DataLocale); diff --git a/crates/handlers/src/rate_limit.rs b/crates/handlers/src/rate_limit.rs index eff30d86f..e011214ca 100644 --- a/crates/handlers/src/rate_limit.rs +++ b/crates/handlers/src/rate_limit.rs @@ -6,7 +6,7 @@ use std::{net::IpAddr, sync::Arc, time::Duration}; -use governor::{clock::QuantaClock, state::keyed::DashMapStateStore, RateLimiter}; +use governor::{RateLimiter, clock::QuantaClock, state::keyed::DashMapStateStore}; use mas_config::RateLimitingConfig; use mas_data_model::{User, UserEmailAuthentication}; use ulid::Ulid; @@ -302,7 +302,7 @@ impl Limiter { #[cfg(test)] mod tests { use mas_data_model::User; - use mas_storage::{clock::MockClock, Clock}; + use mas_storage::{Clock, clock::MockClock}; use rand::SeedableRng; use super::*; diff --git a/crates/handlers/src/test_utils.rs b/crates/handlers/src/test_utils.rs index f9e1b5c62..96073301a 100644 --- a/crates/handlers/src/test_utils.rs +++ b/crates/handlers/src/test_utils.rs @@ -20,12 +20,12 @@ use cookie_store::{CookieStore, RawCookie}; use futures_util::future::BoxFuture; use headers::{Authorization, ContentType, HeaderMapExt, HeaderName, HeaderValue}; use hyper::{ - header::{CONTENT_TYPE, COOKIE, SET_COOKIE}, Request, Response, StatusCode, + header::{CONTENT_TYPE, COOKIE, SET_COOKIE}, }; use mas_axum_utils::{ - cookies::{CookieJar, CookieManager}, ErrorWrapper, + cookies::{CookieJar, CookieManager}, }; use mas_config::RateLimitingConfig; use mas_data_model::SiteConfig; @@ -34,13 +34,13 @@ use mas_keystore::{Encrypter, JsonWebKey, JsonWebKeySet, Keystore, PrivateKey}; use mas_matrix::{BoxHomeserverConnection, HomeserverConnection, MockHomeserverConnection}; use mas_policy::{InstantiateError, Policy, PolicyFactory}; use mas_router::{SimpleRoute, UrlBuilder}; -use mas_storage::{clock::MockClock, BoxClock, BoxRepository, BoxRng}; +use mas_storage::{BoxClock, BoxRepository, BoxRng, clock::MockClock}; use mas_storage_pg::{DatabaseError, PgRepository}; use mas_templates::{SiteConfigExt, Templates}; use oauth2_types::{registration::ClientRegistrationResponse, requests::AccessTokenResponse}; use rand::SeedableRng; use rand_chacha::ChaChaRng; -use serde::{de::DeserializeOwned, Serialize}; +use serde::{Serialize, de::DeserializeOwned}; use sqlx::PgPool; use tokio_util::{ sync::{CancellationToken, DropGuard}, @@ -50,10 +50,9 @@ use tower::{Layer, Service, ServiceExt}; use url::Url; use crate::{ - graphql, + ActivityTracker, BoundActivityTracker, Limiter, RequesterFingerprint, graphql, passwords::{Hasher, PasswordManager}, upstream_oauth2::cache::MetadataCache, - ActivityTracker, BoundActivityTracker, Limiter, RequesterFingerprint, }; /// Setup rustcrypto and tracing for tests. diff --git a/crates/handlers/src/upstream_oauth2/authorize.rs b/crates/handlers/src/upstream_oauth2/authorize.rs index c1dd3f342..ca41c236b 100644 --- a/crates/handlers/src/upstream_oauth2/authorize.rs +++ b/crates/handlers/src/upstream_oauth2/authorize.rs @@ -14,13 +14,13 @@ use mas_data_model::UpstreamOAuthProvider; use mas_oidc_client::requests::authorization_code::AuthorizationRequestData; use mas_router::UrlBuilder; use mas_storage::{ - upstream_oauth2::{UpstreamOAuthProviderRepository, UpstreamOAuthSessionRepository}, BoxClock, BoxRepository, BoxRng, + upstream_oauth2::{UpstreamOAuthProviderRepository, UpstreamOAuthSessionRepository}, }; use thiserror::Error; use ulid::Ulid; -use super::{cache::LazyProviderInfos, UpstreamSessionsCookie}; +use super::{UpstreamSessionsCookie, cache::LazyProviderInfos}; use crate::{ impl_from_error_for_route, upstream_oauth2::cache::MetadataCache, views::shared::OptionalPostAuthAction, diff --git a/crates/handlers/src/upstream_oauth2/cache.rs b/crates/handlers/src/upstream_oauth2/cache.rs index 7d63369d7..02a202745 100644 --- a/crates/handlers/src/upstream_oauth2/cache.rs +++ b/crates/handlers/src/upstream_oauth2/cache.rs @@ -11,7 +11,7 @@ use mas_data_model::{ }; use mas_iana::oauth::PkceCodeChallengeMethod; use mas_oidc_client::error::DiscoveryError; -use mas_storage::{upstream_oauth2::UpstreamOAuthProviderRepository, RepositoryAccess}; +use mas_storage::{RepositoryAccess, upstream_oauth2::UpstreamOAuthProviderRepository}; use oauth2_types::oidc::VerifiedProviderMetadata; use tokio::sync::RwLock; use url::Url; @@ -57,7 +57,7 @@ impl<'a> LazyProviderInfos<'a> { UpstreamOAuthProviderDiscoveryMode::Oidc => true, UpstreamOAuthProviderDiscoveryMode::Insecure => false, UpstreamOAuthProviderDiscoveryMode::Disabled => { - return Err(DiscoveryError::Disabled) + return Err(DiscoveryError::Disabled); } }; @@ -296,12 +296,12 @@ mod tests { UpstreamOAuthProviderClaimsImports, UpstreamOAuthProviderTokenAuthMethod, }; use mas_iana::jose::JsonWebSignatureAlg; - use mas_storage::{clock::MockClock, Clock}; - use oauth2_types::scope::{Scope, OPENID}; + use mas_storage::{Clock, clock::MockClock}; + use oauth2_types::scope::{OPENID, Scope}; use ulid::Ulid; use wiremock::{ - matchers::{method, path}, Mock, MockServer, ResponseTemplate, + matchers::{method, path}, }; use super::*; diff --git a/crates/handlers/src/upstream_oauth2/callback.rs b/crates/handlers/src/upstream_oauth2/callback.rs index 8556f7add..b0421c33d 100644 --- a/crates/handlers/src/upstream_oauth2/callback.rs +++ b/crates/handlers/src/upstream_oauth2/callback.rs @@ -5,10 +5,10 @@ // Please see LICENSE in the repository root for full details. use axum::{ + Form, extract::{Path, State}, http::Method, response::{Html, IntoResponse, Response}, - Form, }; use hyper::StatusCode; use mas_axum_utils::{cookies::CookieJar, sentry::SentryEventID}; @@ -18,11 +18,11 @@ use mas_keystore::{Encrypter, Keystore}; use mas_oidc_client::requests::jose::JwtVerificationData; use mas_router::UrlBuilder; use mas_storage::{ + BoxClock, BoxRepository, BoxRng, Clock, upstream_oauth2::{ UpstreamOAuthLinkRepository, UpstreamOAuthProviderRepository, UpstreamOAuthSessionRepository, }, - BoxClock, BoxRepository, BoxRng, Clock, }; use mas_templates::{FormPostContext, Templates}; use oauth2_types::{errors::ClientErrorCode, requests::AccessTokenRequest}; @@ -32,12 +32,12 @@ use thiserror::Error; use ulid::Ulid; use super::{ + UpstreamSessionsCookie, cache::LazyProviderInfos, client_credentials_for_provider, - template::{environment, AttributeMappingContext}, - UpstreamSessionsCookie, + template::{AttributeMappingContext, environment}, }; -use crate::{impl_from_error_for_route, upstream_oauth2::cache::MetadataCache, PreferredLanguage}; +use crate::{PreferredLanguage, impl_from_error_for_route, upstream_oauth2::cache::MetadataCache}; #[derive(Serialize, Deserialize)] pub struct Params { diff --git a/crates/handlers/src/upstream_oauth2/link.rs b/crates/handlers/src/upstream_oauth2/link.rs index 1ba8cfcc8..58153206f 100644 --- a/crates/handlers/src/upstream_oauth2/link.rs +++ b/crates/handlers/src/upstream_oauth2/link.rs @@ -5,17 +5,17 @@ // Please see LICENSE in the repository root for full details. use axum::{ + Form, extract::{Path, State}, response::{Html, IntoResponse, Response}, - Form, }; use axum_extra::typed_header::TypedHeader; use hyper::StatusCode; use mas_axum_utils::{ + FancyError, SessionInfoExt, cookies::CookieJar, csrf::{CsrfExt, ProtectedForm}, sentry::SentryEventID, - FancyError, SessionInfoExt, }; use mas_data_model::{User, UserAgent}; use mas_jose::jwt::Jwt; @@ -23,10 +23,10 @@ use mas_matrix::BoxHomeserverConnection; use mas_policy::Policy; use mas_router::UrlBuilder; use mas_storage::{ + BoxClock, BoxRepository, BoxRng, RepositoryAccess, queue::{ProvisionUserJob, QueueJobRepositoryExt as _}, upstream_oauth2::{UpstreamOAuthLinkRepository, UpstreamOAuthSessionRepository}, user::{BrowserSessionRepository, UserEmailRepository, UserRepository}, - BoxClock, BoxRepository, BoxRng, RepositoryAccess, }; use mas_templates::{ ErrorContext, FieldError, FormError, TemplateContext, Templates, ToFormState, @@ -39,12 +39,12 @@ use tracing::warn; use ulid::Ulid; use super::{ - template::{environment, AttributeMappingContext}, UpstreamSessionsCookie, + template::{AttributeMappingContext, environment}, }; use crate::{ - impl_from_error_for_route, views::shared::OptionalPostAuthAction, BoundActivityTracker, - PreferredLanguage, SiteConfig, + BoundActivityTracker, PreferredLanguage, SiteConfig, impl_from_error_for_route, + views::shared::OptionalPostAuthAction, }; const DEFAULT_LOCALPART_TEMPLATE: &str = "{{ user.preferred_username }}"; @@ -74,7 +74,9 @@ pub(crate) enum RouteError { RequiredAttributeEmpty { template: String }, /// Required claim was missing in `id_token` - #[error("Template {template:?} could not be rendered from the upstream provider's response for required claim")] + #[error( + "Template {template:?} could not be rendered from the upstream provider's response for required claim" + )] RequiredAttributeRender { template: String, @@ -864,7 +866,7 @@ pub(crate) async fn post( #[cfg(test)] mod tests { - use hyper::{header::CONTENT_TYPE, Request, StatusCode}; + use hyper::{Request, StatusCode, header::CONTENT_TYPE}; use mas_data_model::{ UpstreamOAuthProviderClaimsImports, UpstreamOAuthProviderImportPreference, UpstreamOAuthProviderTokenAuthMethod, @@ -873,13 +875,13 @@ mod tests { use mas_jose::jwt::{JsonWebSignatureHeader, Jwt}; use mas_router::Route; use mas_storage::{ - upstream_oauth2::UpstreamOAuthProviderParams, user::UserEmailFilter, Pagination, + Pagination, upstream_oauth2::UpstreamOAuthProviderParams, user::UserEmailFilter, }; - use oauth2_types::scope::{Scope, OPENID}; + use oauth2_types::scope::{OPENID, Scope}; use sqlx::PgPool; use super::UpstreamSessionsCookie; - use crate::test_utils::{setup, CookieHelper, RequestBuilderExt, ResponseExt, TestState}; + use crate::test_utils::{CookieHelper, RequestBuilderExt, ResponseExt, TestState, setup}; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] async fn test_register(pool: PgPool) { diff --git a/crates/handlers/src/upstream_oauth2/template.rs b/crates/handlers/src/upstream_oauth2/template.rs index bd8547968..cdd193f09 100644 --- a/crates/handlers/src/upstream_oauth2/template.rs +++ b/crates/handlers/src/upstream_oauth2/template.rs @@ -8,8 +8,8 @@ use std::{collections::HashMap, sync::Arc}; use base64ct::{Base64, Base64Unpadded, Base64Url, Base64UrlUnpadded, Encoding}; use minijinja::{ - value::{Enumerator, Object}, Environment, Error, ErrorKind, Value, + value::{Enumerator, Object}, }; /// Context passed to the attribute mapping template diff --git a/crates/handlers/src/views/app.rs b/crates/handlers/src/views/app.rs index 235dee093..9640937f6 100644 --- a/crates/handlers/src/views/app.rs +++ b/crates/handlers/src/views/app.rs @@ -8,7 +8,7 @@ use axum::{ extract::{Query, State}, response::{Html, IntoResponse}, }; -use mas_axum_utils::{cookies::CookieJar, FancyError, SessionInfoExt}; +use mas_axum_utils::{FancyError, SessionInfoExt, cookies::CookieJar}; use mas_router::{PostAuthAction, UrlBuilder}; use mas_storage::{BoxClock, BoxRepository}; use mas_templates::{AppContext, TemplateContext, Templates}; diff --git a/crates/handlers/src/views/index.rs b/crates/handlers/src/views/index.rs index 3b3fe43f1..ca671dd89 100644 --- a/crates/handlers/src/views/index.rs +++ b/crates/handlers/src/views/index.rs @@ -8,12 +8,12 @@ use axum::{ extract::State, response::{Html, IntoResponse}, }; -use mas_axum_utils::{cookies::CookieJar, csrf::CsrfExt, FancyError, SessionInfoExt}; +use mas_axum_utils::{FancyError, SessionInfoExt, cookies::CookieJar, csrf::CsrfExt}; use mas_router::UrlBuilder; use mas_storage::{BoxClock, BoxRepository, BoxRng}; use mas_templates::{IndexContext, TemplateContext, Templates}; -use crate::{preferred_language::PreferredLanguage, BoundActivityTracker}; +use crate::{BoundActivityTracker, preferred_language::PreferredLanguage}; #[tracing::instrument(name = "handlers.views.index.get", skip_all, err)] pub async fn get( diff --git a/crates/handlers/src/views/login.rs b/crates/handlers/src/views/login.rs index 1203dc2e0..c1fad0b7f 100644 --- a/crates/handlers/src/views/login.rs +++ b/crates/handlers/src/views/login.rs @@ -11,18 +11,18 @@ use axum::{ use axum_extra::typed_header::TypedHeader; use hyper::StatusCode; use mas_axum_utils::{ + FancyError, SessionInfoExt, cookies::CookieJar, csrf::{CsrfExt, CsrfToken, ProtectedForm}, - FancyError, SessionInfoExt, }; -use mas_data_model::{oauth2::LoginHint, BrowserSession, UserAgent}; +use mas_data_model::{BrowserSession, UserAgent, oauth2::LoginHint}; use mas_i18n::DataLocale; use mas_matrix::BoxHomeserverConnection; use mas_router::{UpstreamOAuth2Authorize, UrlBuilder}; use mas_storage::{ + BoxClock, BoxRepository, BoxRng, Clock, RepositoryAccess, upstream_oauth2::UpstreamOAuthProviderRepository, user::{BrowserSessionRepository, UserPasswordRepository, UserRepository}, - BoxClock, BoxRepository, BoxRng, Clock, RepositoryAccess, }; use mas_templates::{ FieldError, FormError, LoginContext, LoginFormField, PostAuthContext, PostAuthContextInner, @@ -34,8 +34,8 @@ use zeroize::Zeroizing; use super::shared::OptionalPostAuthAction; use crate::{ - passwords::PasswordManager, BoundActivityTracker, Limiter, PreferredLanguage, - RequesterFingerprint, SiteConfig, + BoundActivityTracker, Limiter, PreferredLanguage, RequesterFingerprint, SiteConfig, + passwords::PasswordManager, }; #[derive(Debug, Deserialize, Serialize)] @@ -345,8 +345,8 @@ async fn render( #[cfg(test)] mod test { use hyper::{ - header::{CONTENT_TYPE, LOCATION}, Request, StatusCode, + header::{CONTENT_TYPE, LOCATION}, }; use mas_data_model::{ UpstreamOAuthProviderClaimsImports, UpstreamOAuthProviderTokenAuthMethod, @@ -354,8 +354,8 @@ mod test { use mas_iana::jose::JsonWebSignatureAlg; use mas_router::Route; use mas_storage::{ - upstream_oauth2::{UpstreamOAuthProviderParams, UpstreamOAuthProviderRepository}, RepositoryAccess, + upstream_oauth2::{UpstreamOAuthProviderParams, UpstreamOAuthProviderRepository}, }; use mas_templates::escape_html; use oauth2_types::scope::OPENID; @@ -363,10 +363,10 @@ mod test { use zeroize::Zeroizing; use crate::{ + SiteConfig, test_utils::{ - setup, test_site_config, CookieHelper, RequestBuilderExt, ResponseExt, TestState, + CookieHelper, RequestBuilderExt, ResponseExt, TestState, setup, test_site_config, }, - SiteConfig, }; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] @@ -475,13 +475,17 @@ mod test { response.assert_status(StatusCode::OK); response.assert_header_value(CONTENT_TYPE, "text/html; charset=utf-8"); assert!(response.body().contains(&escape_html("First Ltd."))); - assert!(response - .body() - .contains(&escape_html(&first_provider_login.path_and_query()))); + assert!( + response + .body() + .contains(&escape_html(&first_provider_login.path_and_query())) + ); assert!(response.body().contains(&escape_html("second.com"))); - assert!(response - .body() - .contains(&escape_html(&second_provider_login.path_and_query()))); + assert!( + response + .body() + .contains(&escape_html(&second_provider_login.path_and_query())) + ); } async fn user_with_password(state: &TestState, username: &str, password: &str) { diff --git a/crates/handlers/src/views/logout.rs b/crates/handlers/src/views/logout.rs index aadb7a534..6745e4322 100644 --- a/crates/handlers/src/views/logout.rs +++ b/crates/handlers/src/views/logout.rs @@ -9,12 +9,12 @@ use axum::{ response::IntoResponse, }; use mas_axum_utils::{ + FancyError, SessionInfoExt, cookies::CookieJar, csrf::{CsrfExt, ProtectedForm}, - FancyError, SessionInfoExt, }; use mas_router::{PostAuthAction, UrlBuilder}; -use mas_storage::{user::BrowserSessionRepository, BoxClock, BoxRepository}; +use mas_storage::{BoxClock, BoxRepository, user::BrowserSessionRepository}; use crate::BoundActivityTracker; diff --git a/crates/handlers/src/views/reauth.rs b/crates/handlers/src/views/reauth.rs index 55b48960b..9baf4b73d 100644 --- a/crates/handlers/src/views/reauth.rs +++ b/crates/handlers/src/views/reauth.rs @@ -11,21 +11,21 @@ use axum::{ }; use hyper::StatusCode; use mas_axum_utils::{ + FancyError, SessionInfoExt, cookies::CookieJar, csrf::{CsrfExt, ProtectedForm}, - FancyError, SessionInfoExt, }; use mas_router::UrlBuilder; use mas_storage::{ - user::{BrowserSessionRepository, UserPasswordRepository}, BoxClock, BoxRepository, BoxRng, + user::{BrowserSessionRepository, UserPasswordRepository}, }; use mas_templates::{ReauthContext, TemplateContext, Templates}; use serde::Deserialize; use zeroize::Zeroizing; use super::shared::OptionalPostAuthAction; -use crate::{passwords::PasswordManager, BoundActivityTracker, PreferredLanguage, SiteConfig}; +use crate::{BoundActivityTracker, PreferredLanguage, SiteConfig, passwords::PasswordManager}; #[derive(Deserialize, Debug)] pub(crate) struct ReauthForm { diff --git a/crates/handlers/src/views/recovery/progress.rs b/crates/handlers/src/views/recovery/progress.rs index 3c2a178fa..30df611ef 100644 --- a/crates/handlers/src/views/recovery/progress.rs +++ b/crates/handlers/src/views/recovery/progress.rs @@ -5,21 +5,21 @@ // Please see LICENSE in the repository root for full details. use axum::{ + Form, extract::{Path, State}, response::{Html, IntoResponse, Response}, - Form, }; use hyper::StatusCode; use mas_axum_utils::{ + FancyError, SessionInfoExt, cookies::CookieJar, csrf::{CsrfExt, ProtectedForm}, - FancyError, SessionInfoExt, }; use mas_data_model::SiteConfig; use mas_router::UrlBuilder; use mas_storage::{ - queue::{QueueJobRepositoryExt as _, SendAccountRecoveryEmailsJob}, BoxClock, BoxRepository, BoxRng, + queue::{QueueJobRepositoryExt as _, SendAccountRecoveryEmailsJob}, }; use mas_templates::{EmptyContext, RecoveryProgressContext, TemplateContext, Templates}; use ulid::Ulid; diff --git a/crates/handlers/src/views/recovery/start.rs b/crates/handlers/src/views/recovery/start.rs index 9b5a7a4d5..09e27dea9 100644 --- a/crates/handlers/src/views/recovery/start.rs +++ b/crates/handlers/src/views/recovery/start.rs @@ -7,22 +7,22 @@ use std::str::FromStr; use axum::{ + Form, extract::State, response::{Html, IntoResponse, Response}, - Form, }; use axum_extra::typed_header::TypedHeader; use lettre::Address; use mas_axum_utils::{ + FancyError, SessionInfoExt, cookies::CookieJar, csrf::{CsrfExt, ProtectedForm}, - FancyError, SessionInfoExt, }; use mas_data_model::{SiteConfig, UserAgent}; use mas_router::UrlBuilder; use mas_storage::{ - queue::{QueueJobRepositoryExt as _, SendAccountRecoveryEmailsJob}, BoxClock, BoxRepository, BoxRng, + queue::{QueueJobRepositoryExt as _, SendAccountRecoveryEmailsJob}, }; use mas_templates::{ EmptyContext, FieldError, FormError, FormState, RecoveryStartContext, RecoveryStartFormField, diff --git a/crates/handlers/src/views/register/mod.rs b/crates/handlers/src/views/register/mod.rs index a209a83a4..93d5d93da 100644 --- a/crates/handlers/src/views/register/mod.rs +++ b/crates/handlers/src/views/register/mod.rs @@ -7,7 +7,7 @@ use axum::{ extract::{Query, State}, response::{Html, IntoResponse, Response}, }; -use mas_axum_utils::{cookies::CookieJar, csrf::CsrfExt as _, FancyError, SessionInfoExt}; +use mas_axum_utils::{FancyError, SessionInfoExt, cookies::CookieJar, csrf::CsrfExt as _}; use mas_data_model::SiteConfig; use mas_router::{PasswordRegister, UpstreamOAuth2Authorize, UrlBuilder}; use mas_storage::{BoxClock, BoxRepository, BoxRng}; diff --git a/crates/handlers/src/views/register/password.rs b/crates/handlers/src/views/register/password.rs index 184b98c42..fef85e8d0 100644 --- a/crates/handlers/src/views/register/password.rs +++ b/crates/handlers/src/views/register/password.rs @@ -14,9 +14,9 @@ use axum_extra::typed_header::TypedHeader; use hyper::StatusCode; use lettre::Address; use mas_axum_utils::{ + FancyError, SessionInfoExt, cookies::CookieJar, csrf::{CsrfExt, CsrfToken, ProtectedForm}, - FancyError, SessionInfoExt, }; use mas_data_model::{CaptchaConfig, UserAgent}; use mas_i18n::DataLocale; @@ -24,9 +24,9 @@ use mas_matrix::BoxHomeserverConnection; use mas_policy::Policy; use mas_router::UrlBuilder; use mas_storage::{ + BoxClock, BoxRepository, BoxRng, RepositoryAccess, queue::{QueueJobRepositoryExt as _, SendEmailAuthenticationCodeJob}, user::{UserEmailRepository, UserRepository}, - BoxClock, BoxRepository, BoxRng, RepositoryAccess, }; use mas_templates::{ FieldError, FormError, FormState, PasswordRegisterContext, RegisterFormField, TemplateContext, @@ -37,9 +37,9 @@ use zeroize::Zeroizing; use super::cookie::UserRegistrationSessions; use crate::{ + BoundActivityTracker, Limiter, PreferredLanguage, RequesterFingerprint, SiteConfig, captcha::Form as CaptchaForm, passwords::PasswordManager, - views::shared::OptionalPostAuthAction, BoundActivityTracker, Limiter, PreferredLanguage, - RequesterFingerprint, SiteConfig, + views::shared::OptionalPostAuthAction, }; #[derive(Debug, Deserialize, Serialize)] @@ -409,17 +409,17 @@ async fn render( #[cfg(test)] mod tests { use hyper::{ - header::{CONTENT_TYPE, LOCATION}, Request, StatusCode, + header::{CONTENT_TYPE, LOCATION}, }; use mas_router::Route; use sqlx::PgPool; use crate::{ + SiteConfig, test_utils::{ - setup, test_site_config, CookieHelper, RequestBuilderExt, ResponseExt, TestState, + CookieHelper, RequestBuilderExt, ResponseExt, TestState, setup, test_site_config, }, - SiteConfig, }; #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")] diff --git a/crates/handlers/src/views/register/steps/display_name.rs b/crates/handlers/src/views/register/steps/display_name.rs index 1af314ecf..a9ff90817 100644 --- a/crates/handlers/src/views/register/steps/display_name.rs +++ b/crates/handlers/src/views/register/steps/display_name.rs @@ -5,14 +5,14 @@ use anyhow::Context as _; use axum::{ + Form, extract::{Path, State}, response::{Html, IntoResponse, Response}, - Form, }; use mas_axum_utils::{ + FancyError, cookies::CookieJar, csrf::{CsrfExt as _, ProtectedForm}, - FancyError, }; use mas_router::{PostAuthAction, UrlBuilder}; use mas_storage::{BoxClock, BoxRepository, BoxRng}; @@ -23,7 +23,7 @@ use mas_templates::{ use serde::{Deserialize, Serialize}; use ulid::Ulid; -use crate::{views::shared::OptionalPostAuthAction, PreferredLanguage}; +use crate::{PreferredLanguage, views::shared::OptionalPostAuthAction}; #[derive(Deserialize, Default)] #[serde(rename_all = "snake_case")] diff --git a/crates/handlers/src/views/register/steps/finish.rs b/crates/handlers/src/views/register/steps/finish.rs index b460d6aed..770905491 100644 --- a/crates/handlers/src/views/register/steps/finish.rs +++ b/crates/handlers/src/views/register/steps/finish.rs @@ -10,20 +10,20 @@ use axum::{ }; use axum_extra::TypedHeader; use chrono::Duration; -use mas_axum_utils::{cookies::CookieJar, FancyError, SessionInfoExt as _}; +use mas_axum_utils::{FancyError, SessionInfoExt as _, cookies::CookieJar}; use mas_data_model::UserAgent; use mas_matrix::BoxHomeserverConnection; use mas_router::{PostAuthAction, UrlBuilder}; use mas_storage::{ + BoxClock, BoxRepository, BoxRng, queue::{ProvisionUserJob, QueueJobRepositoryExt as _}, user::UserEmailFilter, - BoxClock, BoxRepository, BoxRng, }; use mas_templates::{RegisterStepsEmailInUseContext, TemplateContext as _, Templates}; use ulid::Ulid; use super::super::cookie::UserRegistrationSessions; -use crate::{views::shared::OptionalPostAuthAction, BoundActivityTracker, PreferredLanguage}; +use crate::{BoundActivityTracker, PreferredLanguage, views::shared::OptionalPostAuthAction}; #[tracing::instrument( name = "handlers.views.register.steps.finish.get", diff --git a/crates/handlers/src/views/register/steps/verify_email.rs b/crates/handlers/src/views/register/steps/verify_email.rs index 9faf347e8..bba5b4728 100644 --- a/crates/handlers/src/views/register/steps/verify_email.rs +++ b/crates/handlers/src/views/register/steps/verify_email.rs @@ -9,12 +9,12 @@ use axum::{ response::{Html, IntoResponse, Response}, }; use mas_axum_utils::{ + FancyError, cookies::CookieJar, csrf::{CsrfExt, ProtectedForm}, - FancyError, }; use mas_router::{PostAuthAction, UrlBuilder}; -use mas_storage::{user::UserEmailRepository, BoxClock, BoxRepository, BoxRng, RepositoryAccess}; +use mas_storage::{BoxClock, BoxRepository, BoxRng, RepositoryAccess, user::UserEmailRepository}; use mas_templates::{ FieldError, RegisterStepsVerifyEmailContext, RegisterStepsVerifyEmailFormField, TemplateContext, Templates, ToFormState, @@ -22,7 +22,7 @@ use mas_templates::{ use serde::{Deserialize, Serialize}; use ulid::Ulid; -use crate::{views::shared::OptionalPostAuthAction, Limiter, PreferredLanguage}; +use crate::{Limiter, PreferredLanguage, views::shared::OptionalPostAuthAction}; #[derive(Serialize, Deserialize, Debug)] pub struct CodeForm { diff --git a/crates/handlers/src/views/shared.rs b/crates/handlers/src/views/shared.rs index 929efce11..8a304ff83 100644 --- a/crates/handlers/src/views/shared.rs +++ b/crates/handlers/src/views/shared.rs @@ -7,10 +7,10 @@ use anyhow::Context; use mas_router::{PostAuthAction, Route, UrlBuilder}; use mas_storage::{ + RepositoryAccess, compat::CompatSsoLoginRepository, oauth2::OAuth2AuthorizationGrantRepository, upstream_oauth2::{UpstreamOAuthLinkRepository, UpstreamOAuthProviderRepository}, - RepositoryAccess, }; use mas_templates::{PostAuthContext, PostAuthContextInner}; use serde::{Deserialize, Serialize}; diff --git a/crates/http/src/lib.rs b/crates/http/src/lib.rs index be631ff87..72c64aaba 100644 --- a/crates/http/src/lib.rs +++ b/crates/http/src/lib.rs @@ -15,8 +15,8 @@ mod ext; mod reqwest; pub use self::{ - ext::{set_propagator, CorsLayerExt}, - reqwest::{client as reqwest_client, RequestBuilderExt}, + ext::{CorsLayerExt, set_propagator}, + reqwest::{RequestBuilderExt, client as reqwest_client}, }; static METER: LazyLock = LazyLock::new(|| { diff --git a/crates/http/src/reqwest.rs b/crates/http/src/reqwest.rs index 677d58394..b75d7fb07 100644 --- a/crates/http/src/reqwest.rs +++ b/crates/http/src/reqwest.rs @@ -4,7 +4,6 @@ // Please see LICENSE in the repository root for full details. use std::{ - future::Future, str::FromStr, sync::{Arc, LazyLock}, time::Duration, @@ -13,12 +12,12 @@ use std::{ use futures_util::FutureExt as _; use headers::{ContentLength, HeaderMapExt as _, UserAgent}; use hyper_util::client::legacy::connect::{ - dns::{GaiResolver, Name}, HttpInfo, + dns::{GaiResolver, Name}, }; use opentelemetry::{ - metrics::{Histogram, UpDownCounter}, KeyValue, + metrics::{Histogram, UpDownCounter}, }; use opentelemetry_http::HeaderInjector; use opentelemetry_semantic_conventions::{ diff --git a/crates/i18n-scan/src/key.rs b/crates/i18n-scan/src/key.rs index 1617dc4a2..8f5663d07 100644 --- a/crates/i18n-scan/src/key.rs +++ b/crates/i18n-scan/src/key.rs @@ -4,7 +4,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use mas_i18n::{translations::TranslationTree, Message}; +use mas_i18n::{Message, translations::TranslationTree}; use minijinja::machinery::Span; pub struct Context { diff --git a/crates/i18n-scan/src/minijinja.rs b/crates/i18n-scan/src/minijinja.rs index 852a54488..51910783a 100644 --- a/crates/i18n-scan/src/minijinja.rs +++ b/crates/i18n-scan/src/minijinja.rs @@ -6,8 +6,8 @@ pub use minijinja::machinery::parse; use minijinja::{ - machinery::ast::{Call, CallArg, Const, Expr, Macro, Spanned, Stmt}, ErrorKind, + machinery::ast::{Call, CallArg, Const, Expr, Macro, Spanned, Stmt}, }; use crate::key::{Context, Key}; diff --git a/crates/i18n/src/sprintf/formatter.rs b/crates/i18n/src/sprintf/formatter.rs index be3a8cdc0..36388361c 100644 --- a/crates/i18n/src/sprintf/formatter.rs +++ b/crates/i18n/src/sprintf/formatter.rs @@ -8,7 +8,7 @@ use std::fmt::Formatter; use pad::{Alignment, PadStr}; use serde::Serialize; -use serde_json::{ser::PrettyFormatter, Value}; +use serde_json::{Value, ser::PrettyFormatter}; use thiserror::Error; use super::{ArgumentList, Message}; diff --git a/crates/i18n/src/sprintf/parser.rs b/crates/i18n/src/sprintf/parser.rs index 7031f9f55..cadb23ed7 100644 --- a/crates/i18n/src/sprintf/parser.rs +++ b/crates/i18n/src/sprintf/parser.rs @@ -8,7 +8,7 @@ use std::str::FromStr; -use pest::{error::ErrorVariant, iterators::Pair, Parser, Span}; +use pest::{Parser, Span, error::ErrorVariant, iterators::Pair}; use super::message::{ ArgumentReference, Message, PaddingSpecifier, Part, Placeholder, TypeSpecifier, @@ -119,7 +119,7 @@ fn interpret_padding_specifier(pair: &Pair) -> Result { message: format!("Unexpected padding specifier: {specifier:?}"), }, pair.as_span(), - )) + )); } }; @@ -177,7 +177,7 @@ fn interpret_type_specifier(pair: &Pair) -> Result { message: String::from("Unexpected type specifier"), }, pair.as_span(), - )) + )); } }; diff --git a/crates/i18n/src/translations.rs b/crates/i18n/src/translations.rs index edbc3bda6..97e10dc9e 100644 --- a/crates/i18n/src/translations.rs +++ b/crates/i18n/src/translations.rs @@ -11,9 +11,9 @@ use std::{ use icu_plurals::PluralCategory; use serde::{ + Deserialize, Deserializer, Serialize, Serializer, de::{MapAccess, Visitor}, ser::SerializeMap, - Deserialize, Deserializer, Serialize, Serializer, }; use crate::sprintf::Message; @@ -300,7 +300,7 @@ impl Value { #[cfg(test)] mod tests { use super::*; - use crate::sprintf::{arg_list, ArgumentList}; + use crate::sprintf::{ArgumentList, arg_list}; #[test] fn test_it_works() { diff --git a/crates/i18n/src/translator.rs b/crates/i18n/src/translator.rs index 6ba81aa32..63182727c 100644 --- a/crates/i18n/src/translator.rs +++ b/crates/i18n/src/translator.rs @@ -14,11 +14,11 @@ use icu_locid_transform::fallback::{ }; use icu_plurals::{PluralRules, PluralsError}; use icu_provider::{ - data_key, fallback::LocaleFallbackConfig, DataError, DataErrorKind, DataKey, DataLocale, - DataRequest, DataRequestMetadata, + DataError, DataErrorKind, DataKey, DataLocale, DataRequest, DataRequestMetadata, data_key, + fallback::LocaleFallbackConfig, }; use icu_provider_adapters::fallback::LocaleFallbackProvider; -use icu_relativetime::{options::Numeric, RelativeTimeFormatter, RelativeTimeFormatterOptions}; +use icu_relativetime::{RelativeTimeFormatter, RelativeTimeFormatterOptions, options::Numeric}; use thiserror::Error; use writeable::Writeable; diff --git a/crates/iana-codegen/src/gen.rs b/crates/iana-codegen/src/generation.rs similarity index 98% rename from crates/iana-codegen/src/gen.rs rename to crates/iana-codegen/src/generation.rs index ea84297f8..4f915c54c 100644 --- a/crates/iana-codegen/src/gen.rs +++ b/crates/iana-codegen/src/generation.rs @@ -171,7 +171,7 @@ impl schemars::JsonSchema for {} {{ }} #[allow(clippy::too_many_lines)] - fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {{ + fn json_schema(_gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {{ let enums = vec!["#, section.key, section.key, )?; diff --git a/crates/iana-codegen/src/jose.rs b/crates/iana-codegen/src/jose.rs index 96397fa70..8015cad41 100644 --- a/crates/iana-codegen/src/jose.rs +++ b/crates/iana-codegen/src/jose.rs @@ -7,8 +7,8 @@ use serde::Deserialize; use crate::{ - traits::{s, Section}, EnumEntry, + traits::{Section, s}, }; #[derive(Debug, Deserialize, PartialEq, Eq)] diff --git a/crates/iana-codegen/src/main.rs b/crates/iana-codegen/src/main.rs index 75d3e660a..b5b1c28eb 100644 --- a/crates/iana-codegen/src/main.rs +++ b/crates/iana-codegen/src/main.rs @@ -11,7 +11,7 @@ use reqwest::Client; use tokio::io::AsyncWriteExt; use tracing::Level; -mod gen; +mod generation; pub mod jose; pub mod oauth; pub mod traits; @@ -98,23 +98,23 @@ impl Display for File { let is_exhaustive = section.key == "OAuthAuthorizationEndpointResponseType"; writeln!(f)?; - self::gen::struct_def(f, section, list, is_exhaustive)?; + self::generation::struct_def(f, section, list, is_exhaustive)?; writeln!(f)?; // Write the Display impl - self::gen::display_impl(f, section, list, is_exhaustive)?; + self::generation::display_impl(f, section, list, is_exhaustive)?; writeln!(f)?; // Write the FromStr impl - self::gen::from_str_impl(f, section, list, is_exhaustive)?; + self::generation::from_str_impl(f, section, list, is_exhaustive)?; writeln!(f)?; // Write the Serialize and Deserialize impls - self::gen::serde_impl(f, section)?; + self::generation::serde_impl(f, section)?; writeln!(f)?; // Write the JsonSchema impl - self::gen::json_schema_impl(f, section, list)?; + self::generation::json_schema_impl(f, section, list)?; } Ok(()) diff --git a/crates/iana-codegen/src/oauth.rs b/crates/iana-codegen/src/oauth.rs index 2ccf266e8..9afc62659 100644 --- a/crates/iana-codegen/src/oauth.rs +++ b/crates/iana-codegen/src/oauth.rs @@ -7,8 +7,8 @@ use serde::Deserialize; use crate::{ - traits::{s, Section}, EnumEntry, + traits::{Section, s}, }; #[allow(dead_code)] diff --git a/crates/iana/src/jose.rs b/crates/iana/src/jose.rs index 270b430de..494d3dcb9 100644 --- a/crates/iana/src/jose.rs +++ b/crates/iana/src/jose.rs @@ -142,7 +142,7 @@ impl schemars::JsonSchema for JsonWebSignatureAlg { } #[allow(clippy::too_many_lines)] - fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + fn json_schema(_gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema { let enums = vec![ // --- schemars::schema::SchemaObject { @@ -508,7 +508,7 @@ impl schemars::JsonSchema for JsonWebEncryptionAlg { } #[allow(clippy::too_many_lines)] - fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + fn json_schema(_gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema { let enums = vec![ // --- schemars::schema::SchemaObject { @@ -861,7 +861,7 @@ impl schemars::JsonSchema for JsonWebEncryptionEnc { } #[allow(clippy::too_many_lines)] - fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + fn json_schema(_gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema { let enums = vec![ // --- schemars::schema::SchemaObject { @@ -1020,7 +1020,7 @@ impl schemars::JsonSchema for JsonWebEncryptionCompressionAlgorithm { } #[allow(clippy::too_many_lines)] - fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + fn json_schema(_gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema { let enums = vec![ // --- schemars::schema::SchemaObject { @@ -1129,7 +1129,7 @@ impl schemars::JsonSchema for JsonWebKeyType { } #[allow(clippy::too_many_lines)] - fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + fn json_schema(_gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema { let enums = vec![ // --- schemars::schema::SchemaObject { @@ -1277,7 +1277,7 @@ impl schemars::JsonSchema for JsonWebKeyEcEllipticCurve { } #[allow(clippy::too_many_lines)] - fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + fn json_schema(_gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema { let enums = vec![ // --- schemars::schema::SchemaObject { @@ -1425,7 +1425,7 @@ impl schemars::JsonSchema for JsonWebKeyOkpEllipticCurve { } #[allow(clippy::too_many_lines)] - fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + fn json_schema(_gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema { let enums = vec![ // --- schemars::schema::SchemaObject { @@ -1563,7 +1563,7 @@ impl schemars::JsonSchema for JsonWebKeyUse { } #[allow(clippy::too_many_lines)] - fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + fn json_schema(_gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema { let enums = vec![ // --- schemars::schema::SchemaObject { @@ -1705,7 +1705,7 @@ impl schemars::JsonSchema for JsonWebKeyOperation { } #[allow(clippy::too_many_lines)] - fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + fn json_schema(_gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema { let enums = vec![ // --- schemars::schema::SchemaObject { diff --git a/crates/iana/src/oauth.rs b/crates/iana/src/oauth.rs index 0125081fa..60a8d7ed0 100644 --- a/crates/iana/src/oauth.rs +++ b/crates/iana/src/oauth.rs @@ -87,7 +87,7 @@ impl schemars::JsonSchema for OAuthAccessTokenType { } #[allow(clippy::too_many_lines)] - fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + fn json_schema(_gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema { let enums = vec![ // --- schemars::schema::SchemaObject { @@ -222,7 +222,7 @@ impl schemars::JsonSchema for OAuthAuthorizationEndpointResponseType { } #[allow(clippy::too_many_lines)] - fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + fn json_schema(_gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema { let enums = vec![ // --- schemars::schema::SchemaObject { @@ -361,7 +361,7 @@ impl schemars::JsonSchema for OAuthTokenTypeHint { } #[allow(clippy::too_many_lines)] - fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + fn json_schema(_gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema { let enums = vec![ // --- schemars::schema::SchemaObject { @@ -490,7 +490,7 @@ impl schemars::JsonSchema for OAuthClientAuthenticationMethod { } #[allow(clippy::too_many_lines)] - fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + fn json_schema(_gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema { let enums = vec![ // --- schemars::schema::SchemaObject { @@ -618,7 +618,7 @@ impl schemars::JsonSchema for PkceCodeChallengeMethod { } #[allow(clippy::too_many_lines)] - fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + fn json_schema(_gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema { let enums = vec![ // --- schemars::schema::SchemaObject { diff --git a/crates/jose/src/base64.rs b/crates/jose/src/base64.rs index 9fb11bc15..b5b0b2386 100644 --- a/crates/jose/src/base64.rs +++ b/crates/jose/src/base64.rs @@ -4,8 +4,8 @@ use std::{borrow::Cow, fmt, marker::PhantomData, str}; use base64ct::Encoding; use serde::{ - de::{self, Unexpected, Visitor}, Deserialize, Deserializer, Serialize, Serializer, + de::{self, Unexpected, Visitor}, }; /// A wrapper around `Vec` that (de)serializes from / to a base64 string. diff --git a/crates/jose/src/claims.rs b/crates/jose/src/claims.rs index 0d1929953..455be2ff9 100644 --- a/crates/jose/src/claims.rs +++ b/crates/jose/src/claims.rs @@ -8,7 +8,7 @@ use std::{collections::HashMap, convert::Infallible, marker::PhantomData, ops::D use base64ct::{Base64UrlUnpadded, Encoding}; use mas_iana::jose::JsonWebSignatureAlg; -use serde::{de::DeserializeOwned, Deserialize, Serialize}; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; use sha2::{Digest, Sha256, Sha384, Sha512}; use thiserror::Error; @@ -640,15 +640,18 @@ mod tests { // so no leeway should be fine as well here let time_options = TimeOptions::new(now).leeway(chrono::Duration::zero()); - assert!(IAT - .extract_required_with_options(&mut claims, &time_options) - .is_ok()); - assert!(NBF - .extract_required_with_options(&mut claims, &time_options) - .is_ok()); - assert!(EXP - .extract_required_with_options(&mut claims, &time_options) - .is_ok()); + assert!( + IAT.extract_required_with_options(&mut claims, &time_options) + .is_ok() + ); + assert!( + NBF.extract_required_with_options(&mut claims, &time_options) + .is_ok() + ); + assert!( + EXP.extract_required_with_options(&mut claims, &time_options) + .is_ok() + ); } // Let's go back in time a bit @@ -668,9 +671,10 @@ mod tests { NBF.extract_required_with_options(&mut claims, &time_options), Err(ClaimError::ValidationError { claim: "nbf", .. }), )); - assert!(EXP - .extract_required_with_options(&mut claims, &time_options) - .is_ok()); + assert!( + EXP.extract_required_with_options(&mut claims, &time_options) + .is_ok() + ); } { @@ -680,15 +684,18 @@ mod tests { // but no time variance is allowed. "iat" and "nbf" validation will fail let time_options = TimeOptions::new(now).leeway(chrono::Duration::microseconds(2 * 60 * 1000 * 1000)); - assert!(IAT - .extract_required_with_options(&mut claims, &time_options) - .is_ok()); - assert!(NBF - .extract_required_with_options(&mut claims, &time_options) - .is_ok()); - assert!(EXP - .extract_required_with_options(&mut claims, &time_options) - .is_ok()); + assert!( + IAT.extract_required_with_options(&mut claims, &time_options) + .is_ok() + ); + assert!( + NBF.extract_required_with_options(&mut claims, &time_options) + .is_ok() + ); + assert!( + EXP.extract_required_with_options(&mut claims, &time_options) + .is_ok() + ); } // Let's wait some time so it expires @@ -700,12 +707,14 @@ mod tests { // but no time variance is allowed. "exp" validation will fail let time_options = TimeOptions::new(now).leeway(chrono::Duration::zero()); - assert!(IAT - .extract_required_with_options(&mut claims, &time_options) - .is_ok()); - assert!(NBF - .extract_required_with_options(&mut claims, &time_options) - .is_ok()); + assert!( + IAT.extract_required_with_options(&mut claims, &time_options) + .is_ok() + ); + assert!( + NBF.extract_required_with_options(&mut claims, &time_options) + .is_ok() + ); assert!(matches!( EXP.extract_required_with_options(&mut claims, &time_options), Err(ClaimError::ValidationError { claim: "exp", .. }), @@ -718,15 +727,18 @@ mod tests { // Same, but with a 2 minutes leeway should be fine then let time_options = TimeOptions::new(now).leeway(chrono::Duration::try_minutes(2).unwrap()); - assert!(IAT - .extract_required_with_options(&mut claims, &time_options) - .is_ok()); - assert!(NBF - .extract_required_with_options(&mut claims, &time_options) - .is_ok()); - assert!(EXP - .extract_required_with_options(&mut claims, &time_options) - .is_ok()); + assert!( + IAT.extract_required_with_options(&mut claims, &time_options) + .is_ok() + ); + assert!( + NBF.extract_required_with_options(&mut claims, &time_options) + .is_ok() + ); + assert!( + EXP.extract_required_with_options(&mut claims, &time_options) + .is_ok() + ); } } diff --git a/crates/jose/src/jwa/hmac.rs b/crates/jose/src/jwa/hmac.rs index ca3d799c3..af7bd59d9 100644 --- a/crates/jose/src/jwa/hmac.rs +++ b/crates/jose/src/jwa/hmac.rs @@ -7,9 +7,9 @@ use std::marker::PhantomData; use digest::{ + Digest, Mac, OutputSizeUser, crypto_common::BlockSizeUser, generic_array::{ArrayLength, GenericArray}, - Digest, Mac, OutputSizeUser, }; use signature::{Signer, Verifier}; use thiserror::Error; diff --git a/crates/jose/src/jwk/private_parameters.rs b/crates/jose/src/jwk/private_parameters.rs index 4067b7f91..d0ac8be87 100644 --- a/crates/jose/src/jwk/private_parameters.rs +++ b/crates/jose/src/jwk/private_parameters.rs @@ -11,7 +11,7 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use thiserror::Error; -use super::{public_parameters::JsonWebKeyPublicParameters, ParametersInfo}; +use super::{ParametersInfo, public_parameters::JsonWebKeyPublicParameters}; use crate::base64::Base64UrlNoPad; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] @@ -273,8 +273,8 @@ impl From for super::public_parameters::EcPublicParameters mod ec_impls { use elliptic_curve::{ - sec1::{Coordinates, FromEncodedPoint, ModulusSize, ToEncodedPoint}, AffinePoint, Curve, SecretKey, + sec1::{Coordinates, FromEncodedPoint, ModulusSize, ToEncodedPoint}, }; use super::{super::JwkEcCurve, EcPrivateParameters}; diff --git a/crates/jose/src/jwk/public_parameters.rs b/crates/jose/src/jwk/public_parameters.rs index 3d545d5ef..1b5eaadbf 100644 --- a/crates/jose/src/jwk/public_parameters.rs +++ b/crates/jose/src/jwk/public_parameters.rs @@ -160,7 +160,7 @@ impl OkpPublicParameters { } mod rsa_impls { - use rsa::{traits::PublicKeyParts, BigUint, RsaPublicKey}; + use rsa::{BigUint, RsaPublicKey, traits::PublicKeyParts}; use super::{JsonWebKeyPublicParameters, RsaPublicParameters}; use crate::base64::Base64UrlNoPad; @@ -214,8 +214,8 @@ mod ec_impls { use digest::typenum::Unsigned; use ecdsa::EncodedPoint; use elliptic_curve::{ - sec1::{Coordinates, FromEncodedPoint, ModulusSize, ToEncodedPoint}, AffinePoint, FieldBytes, PublicKey, + sec1::{Coordinates, FromEncodedPoint, ModulusSize, ToEncodedPoint}, }; use super::{super::JwkEcCurve, EcPublicParameters, JsonWebKeyPublicParameters}; diff --git a/crates/jose/src/jwt/header.rs b/crates/jose/src/jwt/header.rs index db1c3fbca..56aaef6d8 100644 --- a/crates/jose/src/jwt/header.rs +++ b/crates/jose/src/jwt/header.rs @@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize}; use serde_with::skip_serializing_none; use url::Url; -use crate::{base64::Base64UrlNoPad, jwk::PublicJsonWebKey, Base64}; +use crate::{Base64, base64::Base64UrlNoPad, jwk::PublicJsonWebKey}; #[skip_serializing_none] #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)] diff --git a/crates/jose/src/jwt/signed.rs b/crates/jose/src/jwt/signed.rs index 4b9f881fa..ba7a552c8 100644 --- a/crates/jose/src/jwt/signed.rs +++ b/crates/jose/src/jwt/signed.rs @@ -6,8 +6,8 @@ use base64ct::{Base64UrlUnpadded, Encoding}; use rand::thread_rng; -use serde::{de::DeserializeOwned, Serialize}; -use signature::{rand_core::CryptoRngCore, RandomizedSigner, SignatureEncoding, Verifier}; +use serde::{Serialize, de::DeserializeOwned}; +use signature::{RandomizedSigner, SignatureEncoding, Verifier, rand_core::CryptoRngCore}; use thiserror::Error; use super::{header::JsonWebSignatureHeader, raw::RawJwt}; @@ -396,7 +396,10 @@ mod tests { jwt.raw.signature(), "SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" ); - assert_eq!(jwt.raw.signed_part(), "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ"); + assert_eq!( + jwt.raw.signed_part(), + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ" + ); } #[test] diff --git a/crates/keystore/src/lib.rs b/crates/keystore/src/lib.rs index 36e1aaa89..639afcb0d 100644 --- a/crates/keystore/src/lib.rs +++ b/crates/keystore/src/lib.rs @@ -8,7 +8,7 @@ use std::{ops::Deref, sync::Arc}; -use der::{zeroize::Zeroizing, Decode, Encode, EncodePem}; +use der::{Decode, Encode, EncodePem, zeroize::Zeroizing}; use elliptic_curve::{pkcs8::EncodePrivateKey, sec1::ToEncodedPoint}; use mas_iana::jose::{JsonWebKeyType, JsonWebSignatureAlg}; pub use mas_jose::jwk::{JsonWebKey, JsonWebKeySet}; diff --git a/crates/keystore/tests/keystore.rs b/crates/keystore/tests/keystore.rs index a644252e2..6bdbe8286 100644 --- a/crates/keystore/tests/keystore.rs +++ b/crates/keystore/tests/keystore.rs @@ -141,14 +141,18 @@ fn load_encrypted_as_unencrypted_error() { #[test] fn load_unencrypted_as_encrypted_error() { let pem = include_str!("./keys/rsa.pkcs8.pem"); - assert!(PrivateKey::load_encrypted_pem(pem, PASSWORD) - .unwrap_err() - .is_unencrypted()); + assert!( + PrivateKey::load_encrypted_pem(pem, PASSWORD) + .unwrap_err() + .is_unencrypted() + ); let der = include_bytes!("./keys/rsa.pkcs8.der"); - assert!(PrivateKey::load_encrypted_der(der, PASSWORD) - .unwrap_err() - .is_unencrypted()); + assert!( + PrivateKey::load_encrypted_der(der, PASSWORD) + .unwrap_err() + .is_unencrypted() + ); } #[allow(clippy::similar_names)] diff --git a/crates/listener/examples/demo/main.rs b/crates/listener/examples/demo/main.rs index b547d13f1..1a950fa6d 100644 --- a/crates/listener/examples/demo/main.rs +++ b/crates/listener/examples/demo/main.rs @@ -14,8 +14,8 @@ use std::{ use anyhow::Context; use hyper::{Request, Response}; -use mas_listener::{server::Server, ConnectionInfo}; -use tokio_rustls::rustls::{server::WebPkiClientVerifier, RootCertStore, ServerConfig}; +use mas_listener::{ConnectionInfo, server::Server}; +use tokio_rustls::rustls::{RootCertStore, ServerConfig, server::WebPkiClientVerifier}; use tokio_util::sync::CancellationToken; use tower::service_fn; @@ -51,7 +51,9 @@ async fn main() -> Result<(), anyhow::Error> { .with_tls(tls_config.clone()), ]; - tracing::info!("Listening on http://127.0.0.1:3000, http(proxy)://127.0.0.1:3001, https://127.0.0.1:3002 and https(proxy)://127.0.0.1:3003"); + tracing::info!( + "Listening on http://127.0.0.1:3000, http(proxy)://127.0.0.1:3001, https://127.0.0.1:3002 and https(proxy)://127.0.0.1:3003" + ); let hard_shutdown = CancellationToken::new(); let soft_shutdown = hard_shutdown.child_token(); diff --git a/crates/listener/src/maybe_tls.rs b/crates/listener/src/maybe_tls.rs index ad2db89a9..635141cbc 100644 --- a/crates/listener/src/maybe_tls.rs +++ b/crates/listener/src/maybe_tls.rs @@ -12,11 +12,11 @@ use std::{ use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use tokio_rustls::{ + TlsAcceptor, rustls::{ - pki_types::CertificateDer, ProtocolVersion, ServerConfig, ServerConnection, - SupportedCipherSuite, + ProtocolVersion, ServerConfig, ServerConnection, SupportedCipherSuite, + pki_types::CertificateDer, }, - TlsAcceptor, }; #[derive(Debug, Clone)] diff --git a/crates/listener/src/proxy_protocol/maybe.rs b/crates/listener/src/proxy_protocol/maybe.rs index 7e7930686..29e47f047 100644 --- a/crates/listener/src/proxy_protocol/maybe.rs +++ b/crates/listener/src/proxy_protocol/maybe.rs @@ -6,7 +6,7 @@ use tokio::io::AsyncRead; -use super::{acceptor::ProxyAcceptError, ProxyAcceptor, ProxyProtocolV1Info}; +use super::{ProxyAcceptor, ProxyProtocolV1Info, acceptor::ProxyAcceptError}; use crate::rewind::Rewind; #[derive(Clone, Copy)] diff --git a/crates/listener/src/server.rs b/crates/listener/src/server.rs index 823ed1003..b022455bb 100644 --- a/crates/listener/src/server.rs +++ b/crates/listener/src/server.rs @@ -5,14 +5,13 @@ // Please see LICENSE in the repository root for full details. use std::{ - future::Future, pin::Pin, sync::Arc, task::{Context, Poll}, time::Duration, }; -use futures_util::{stream::SelectAll, StreamExt}; +use futures_util::{StreamExt, stream::SelectAll}; use hyper::{Request, Response}; use hyper_util::{ rt::{TokioExecutor, TokioIo}, @@ -28,11 +27,11 @@ use tower_http::add_extension::AddExtension; use tracing::Instrument; use crate::{ + ConnectionInfo, maybe_tls::{MaybeTlsAcceptor, MaybeTlsStream, TlsStreamInfo}, proxy_protocol::{MaybeProxyAcceptor, ProxyAcceptError}, rewind::Rewind, unix_or_tcp::{SocketAddr, UnixOrTcpConnection, UnixOrTcpListener}, - ConnectionInfo, }; /// The timeout for the handshake to complete diff --git a/crates/listener/src/unix_or_tcp.rs b/crates/listener/src/unix_or_tcp.rs index 7b675f1d0..565adec4d 100644 --- a/crates/listener/src/unix_or_tcp.rs +++ b/crates/listener/src/unix_or_tcp.rs @@ -10,7 +10,7 @@ use std::{ pin::Pin, - task::{ready, Context, Poll}, + task::{Context, Poll, ready}, }; use tokio::{ diff --git a/crates/matrix-synapse/src/lib.rs b/crates/matrix-synapse/src/lib.rs index 7c7c09ba5..36f9e97d0 100644 --- a/crates/matrix-synapse/src/lib.rs +++ b/crates/matrix-synapse/src/lib.rs @@ -6,7 +6,7 @@ use std::collections::HashSet; -use anyhow::{bail, Context}; +use anyhow::{Context, bail}; use error::SynapseResponseExt; use http::{Method, StatusCode}; use mas_http::RequestBuilderExt as _; diff --git a/crates/oauth2-types/src/errors.rs b/crates/oauth2-types/src/errors.rs index e8ac2eff8..f5e349c82 100644 --- a/crates/oauth2-types/src/errors.rs +++ b/crates/oauth2-types/src/errors.rs @@ -411,9 +411,7 @@ impl ClientErrorCode { ClientErrorCode::InvalidClientMetadata => { "The value of one of the client metadata fields is invalid" } - ClientErrorCode::AuthorizationPending => { - "The authorization request is still pending" - } + ClientErrorCode::AuthorizationPending => "The authorization request is still pending", ClientErrorCode::SlowDown => { "The interval must be increased by 5 seconds for this and all subsequent requests" } @@ -422,7 +420,7 @@ impl ClientErrorCode { } ClientErrorCode::UnsupportedTokenType => { "The authorization server does not support the revocation of the presented token type." - }, + } ClientErrorCode::Unknown(_) => "", } } diff --git a/crates/oauth2-types/src/oidc.rs b/crates/oauth2-types/src/oidc.rs index 4bcf54539..5cbdf2e4b 100644 --- a/crates/oauth2-types/src/oidc.rs +++ b/crates/oauth2-types/src/oidc.rs @@ -17,8 +17,8 @@ use mas_iana::{ }; use serde::{Deserialize, Serialize}; use serde_with::{ - formats::SpaceSeparator, serde_as, skip_serializing_none, DeserializeFromStr, SerializeDisplay, - StringWithSeparator, + DeserializeFromStr, SerializeDisplay, StringWithSeparator, formats::SpaceSeparator, serde_as, + skip_serializing_none, }; use thiserror::Error; use url::Url; @@ -1276,7 +1276,7 @@ mod tests { token_endpoint: Some(Url::parse("https://localhost/token").unwrap()), jwks_uri: Some(Url::parse("https://localhost/jwks").unwrap()), response_types_supported: Some(vec![ - OAuthAuthorizationEndpointResponseType::Code.into() + OAuthAuthorizationEndpointResponseType::Code.into(), ]), subject_types_supported: Some(vec![SubjectType::Public]), id_token_signing_alg_values_supported: Some(vec![JsonWebSignatureAlg::Rs256]), diff --git a/crates/oauth2-types/src/pkce.rs b/crates/oauth2-types/src/pkce.rs index 0be9baf9a..786026adb 100644 --- a/crates/oauth2-types/src/pkce.rs +++ b/crates/oauth2-types/src/pkce.rs @@ -135,9 +135,10 @@ mod tests { // This challenge comes from the RFC7636 appendices let challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"; - assert!(S256 - .verify(challenge, "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk") - .is_ok()); + assert!( + S256.verify(challenge, "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk") + .is_ok() + ); assert!(Plain.verify(challenge, challenge).is_ok()); diff --git a/crates/oauth2-types/src/registration/client_metadata_serde.rs b/crates/oauth2-types/src/registration/client_metadata_serde.rs index 369c53651..427306ffd 100644 --- a/crates/oauth2-types/src/registration/client_metadata_serde.rs +++ b/crates/oauth2-types/src/registration/client_metadata_serde.rs @@ -14,12 +14,12 @@ use mas_iana::{ }; use mas_jose::jwk::PublicJsonWebKeySet; use serde::{ + Deserialize, Serialize, de::{DeserializeOwned, Error}, ser::SerializeMap, - Deserialize, Serialize, }; use serde_json::Value; -use serde_with::{serde_as, skip_serializing_none, DurationSeconds}; +use serde_with::{DurationSeconds, serde_as, skip_serializing_none}; use url::Url; use super::{ClientMetadata, Localized, VerifiedClientMetadata}; diff --git a/crates/oauth2-types/src/registration/mod.rs b/crates/oauth2-types/src/registration/mod.rs index 40ea147f1..19b462f7c 100644 --- a/crates/oauth2-types/src/registration/mod.rs +++ b/crates/oauth2-types/src/registration/mod.rs @@ -18,7 +18,7 @@ use mas_iana::{ }; use mas_jose::jwk::PublicJsonWebKeySet; use serde::{Deserialize, Serialize}; -use serde_with::{serde_as, skip_serializing_none, TimestampSeconds}; +use serde_with::{TimestampSeconds, serde_as, skip_serializing_none}; use thiserror::Error; use url::Url; @@ -1036,7 +1036,7 @@ mod tests { // id_token token - Ok metadata.response_types = Some(vec![ - OAuthAuthorizationEndpointResponseType::IdTokenToken.into() + OAuthAuthorizationEndpointResponseType::IdTokenToken.into(), ]); metadata.clone().validate().unwrap(); @@ -1056,7 +1056,7 @@ mod tests { // code id_token - Ok metadata.response_types = Some(vec![ - OAuthAuthorizationEndpointResponseType::CodeIdToken.into() + OAuthAuthorizationEndpointResponseType::CodeIdToken.into(), ]); metadata.clone().validate().unwrap(); @@ -1068,7 +1068,7 @@ mod tests { // code token - Ok metadata.response_types = Some(vec![ - OAuthAuthorizationEndpointResponseType::CodeToken.into() + OAuthAuthorizationEndpointResponseType::CodeToken.into(), ]); metadata.clone().validate().unwrap(); @@ -1079,7 +1079,7 @@ mod tests { // id_token token - Ok metadata.response_types = Some(vec![ - OAuthAuthorizationEndpointResponseType::IdTokenToken.into() + OAuthAuthorizationEndpointResponseType::IdTokenToken.into(), ]); metadata.clone().validate().unwrap(); @@ -1246,7 +1246,7 @@ mod tests { // Err - code id_token metadata.response_types = Some(vec![ - OAuthAuthorizationEndpointResponseType::CodeIdToken.into() + OAuthAuthorizationEndpointResponseType::CodeIdToken.into(), ]); assert_matches!( metadata.clone().validate(), @@ -1272,7 +1272,7 @@ mod tests { // Err - id_token token metadata.response_types = Some(vec![ - OAuthAuthorizationEndpointResponseType::IdTokenToken.into() + OAuthAuthorizationEndpointResponseType::IdTokenToken.into(), ]); assert_matches!( metadata.clone().validate(), diff --git a/crates/oauth2-types/src/requests.rs b/crates/oauth2-types/src/requests.rs index dedf6e31e..0201b5613 100644 --- a/crates/oauth2-types/src/requests.rs +++ b/crates/oauth2-types/src/requests.rs @@ -15,8 +15,8 @@ use language_tags::LanguageTag; use mas_iana::oauth::{OAuthAccessTokenType, OAuthTokenTypeHint}; use serde::{Deserialize, Serialize}; use serde_with::{ - formats::SpaceSeparator, serde_as, skip_serializing_none, DeserializeFromStr, DisplayFromStr, - DurationSeconds, SerializeDisplay, StringWithSeparator, TimestampSeconds, + DeserializeFromStr, DisplayFromStr, DurationSeconds, SerializeDisplay, StringWithSeparator, + TimestampSeconds, formats::SpaceSeparator, serde_as, skip_serializing_none, }; use url::Url; diff --git a/crates/oauth2-types/src/response_type.rs b/crates/oauth2-types/src/response_type.rs index fb6a0fb5d..eb6fa7e02 100644 --- a/crates/oauth2-types/src/response_type.rs +++ b/crates/oauth2-types/src/response_type.rs @@ -212,9 +212,11 @@ impl TryFrom for OAuthAuthorizationEndpointResponseType { [ResponseTypeToken::IdToken, ResponseTypeToken::Token] => { OAuthAuthorizationEndpointResponseType::IdTokenToken } - [ResponseTypeToken::Code, ResponseTypeToken::IdToken, ResponseTypeToken::Token] => { - OAuthAuthorizationEndpointResponseType::CodeIdTokenToken - } + [ + ResponseTypeToken::Code, + ResponseTypeToken::IdToken, + ResponseTypeToken::Token, + ] => OAuthAuthorizationEndpointResponseType::CodeIdTokenToken, _ => OAuthAuthorizationEndpointResponseType::None, }; diff --git a/crates/oauth2-types/src/test_utils.rs b/crates/oauth2-types/src/test_utils.rs index 0310748f7..a1bdb30d5 100644 --- a/crates/oauth2-types/src/test_utils.rs +++ b/crates/oauth2-types/src/test_utils.rs @@ -6,7 +6,7 @@ use std::fmt::Debug; -use serde::{de::DeserializeOwned, Serialize}; +use serde::{Serialize, de::DeserializeOwned}; #[track_caller] pub(crate) fn assert_serde_json( diff --git a/crates/oidc-client/src/requests/authorization_code.rs b/crates/oidc-client/src/requests/authorization_code.rs index b11773e8a..198846876 100644 --- a/crates/oidc-client/src/requests/authorization_code.rs +++ b/crates/oidc-client/src/requests/authorization_code.rs @@ -22,11 +22,11 @@ use oauth2_types::{ AccessTokenRequest, AccessTokenResponse, AuthorizationCodeGrant, AuthorizationRequest, Display, Prompt, ResponseMode, }, - scope::{Scope, OPENID}, + scope::{OPENID, Scope}, }; use rand::{ - distributions::{Alphanumeric, DistString}, Rng, + distributions::{Alphanumeric, DistString}, }; use serde::Serialize; use url::Url; @@ -35,7 +35,7 @@ use super::jose::JwtVerificationData; use crate::{ error::{AuthorizationError, IdTokenError, TokenAuthorizationCodeError}, requests::{jose::verify_id_token, token::request_access_token}, - types::{client_credentials::ClientCredentials, IdToken}, + types::{IdToken, client_credentials::ClientCredentials}, }; /// The data necessary to build an authorization request. diff --git a/crates/oidc-client/src/requests/refresh_token.rs b/crates/oidc-client/src/requests/refresh_token.rs index f630caf23..8b9e7719a 100644 --- a/crates/oidc-client/src/requests/refresh_token.rs +++ b/crates/oidc-client/src/requests/refresh_token.rs @@ -21,7 +21,7 @@ use super::jose::JwtVerificationData; use crate::{ error::{IdTokenError, TokenRefreshError}, requests::{jose::verify_id_token, token::request_access_token}, - types::{client_credentials::ClientCredentials, IdToken}, + types::{IdToken, client_credentials::ClientCredentials}, }; /// Exchange an authorization code for an access token. diff --git a/crates/oidc-client/tests/it/main.rs b/crates/oidc-client/tests/it/main.rs index 096cbf199..270ab8a20 100644 --- a/crates/oidc-client/tests/it/main.rs +++ b/crates/oidc-client/tests/it/main.rs @@ -15,10 +15,10 @@ use mas_jose::{ jwt::{JsonWebSignatureHeader, Jwt}, }; use mas_keystore::{JsonWebKey, JsonWebKeySet, Keystore, PrivateKey}; -use mas_oidc_client::types::{client_credentials::ClientCredentials, IdToken}; +use mas_oidc_client::types::{IdToken, client_credentials::ClientCredentials}; use rand::{ - distributions::{Alphanumeric, DistString}, SeedableRng, + distributions::{Alphanumeric, DistString}, }; use url::Url; use wiremock::MockServer; diff --git a/crates/oidc-client/tests/it/requests/authorization_code.rs b/crates/oidc-client/tests/it/requests/authorization_code.rs index eb42ca0ea..131db26e9 100644 --- a/crates/oidc-client/tests/it/requests/authorization_code.rs +++ b/crates/oidc-client/tests/it/requests/authorization_code.rs @@ -15,8 +15,8 @@ use mas_oidc_client::{ error::{IdTokenError, TokenAuthorizationCodeError}, requests::{ authorization_code::{ - access_token_with_authorization_code, build_authorization_url, AuthorizationRequestData, AuthorizationValidationData, + access_token_with_authorization_code, build_authorization_url, }, jose::JwtVerificationData, }, @@ -28,13 +28,13 @@ use oauth2_types::{ use rand::SeedableRng; use url::Url; use wiremock::{ - matchers::{method, path}, Mock, Request, ResponseTemplate, + matchers::{method, path}, }; use crate::{ - client_credentials, id_token, init_test, now, ACCESS_TOKEN, AUTHORIZATION_CODE, CLIENT_ID, - CODE_VERIFIER, ID_TOKEN_SIGNING_ALG, NONCE, REDIRECT_URI, + ACCESS_TOKEN, AUTHORIZATION_CODE, CLIENT_ID, CODE_VERIFIER, ID_TOKEN_SIGNING_ALG, NONCE, + REDIRECT_URI, client_credentials, id_token, init_test, now, }; #[test] diff --git a/crates/oidc-client/tests/it/requests/client_credentials.rs b/crates/oidc-client/tests/it/requests/client_credentials.rs index 5abf0be64..a6da9e0ff 100644 --- a/crates/oidc-client/tests/it/requests/client_credentials.rs +++ b/crates/oidc-client/tests/it/requests/client_credentials.rs @@ -10,15 +10,15 @@ use mas_iana::oauth::{OAuthAccessTokenType, OAuthClientAuthenticationMethod}; use mas_oidc_client::requests::client_credentials::access_token_with_client_credentials; use oauth2_types::{ requests::AccessTokenResponse, - scope::{Scope, PROFILE}, + scope::{PROFILE, Scope}, }; use rand::SeedableRng; use wiremock::{ - matchers::{method, path}, Mock, Request, ResponseTemplate, + matchers::{method, path}, }; -use crate::{client_credentials, init_test, now, ACCESS_TOKEN, CLIENT_ID, CLIENT_SECRET}; +use crate::{ACCESS_TOKEN, CLIENT_ID, CLIENT_SECRET, client_credentials, init_test, now}; #[tokio::test] async fn pass_access_token_with_client_credentials() { diff --git a/crates/oidc-client/tests/it/requests/discovery.rs b/crates/oidc-client/tests/it/requests/discovery.rs index d9b7c3bb2..4b2c9d18c 100644 --- a/crates/oidc-client/tests/it/requests/discovery.rs +++ b/crates/oidc-client/tests/it/requests/discovery.rs @@ -14,8 +14,8 @@ use mas_oidc_client::{ use oauth2_types::oidc::{ProviderMetadata, SubjectType}; use url::Url; use wiremock::{ - matchers::{method, path}, Mock, ResponseTemplate, + matchers::{method, path}, }; use crate::init_test; diff --git a/crates/oidc-client/tests/it/requests/jose.rs b/crates/oidc-client/tests/it/requests/jose.rs index 88bd2ab35..d45358f28 100644 --- a/crates/oidc-client/tests/it/requests/jose.rs +++ b/crates/oidc-client/tests/it/requests/jose.rs @@ -17,11 +17,11 @@ use mas_jose::{ }; use mas_oidc_client::{ error::{IdTokenError, JwtVerificationError}, - requests::jose::{verify_id_token, JwtVerificationData}, + requests::jose::{JwtVerificationData, verify_id_token}, types::IdToken, }; -use crate::{keystore, now, CLIENT_ID, ID_TOKEN_SIGNING_ALG, SUBJECT_IDENTIFIER}; +use crate::{CLIENT_ID, ID_TOKEN_SIGNING_ALG, SUBJECT_IDENTIFIER, keystore, now}; #[derive(Clone, Copy, PartialEq, Eq)] enum IdTokenFlag { diff --git a/crates/oidc-client/tests/it/requests/refresh_token.rs b/crates/oidc-client/tests/it/requests/refresh_token.rs index 16cf4f258..ebda10a10 100644 --- a/crates/oidc-client/tests/it/requests/refresh_token.rs +++ b/crates/oidc-client/tests/it/requests/refresh_token.rs @@ -12,11 +12,11 @@ use mas_oidc_client::requests::refresh_token::refresh_access_token; use oauth2_types::requests::AccessTokenResponse; use rand::SeedableRng; use wiremock::{ - matchers::{method, path}, Mock, Request, ResponseTemplate, + matchers::{method, path}, }; -use crate::{client_credentials, init_test, now, ACCESS_TOKEN, CLIENT_ID, REFRESH_TOKEN}; +use crate::{ACCESS_TOKEN, CLIENT_ID, REFRESH_TOKEN, client_credentials, init_test, now}; #[tokio::test] async fn pass_refresh_access_token() { diff --git a/crates/oidc-client/tests/it/requests/userinfo.rs b/crates/oidc-client/tests/it/requests/userinfo.rs index 4e97eb590..2b3f9cfbd 100644 --- a/crates/oidc-client/tests/it/requests/userinfo.rs +++ b/crates/oidc-client/tests/it/requests/userinfo.rs @@ -7,11 +7,11 @@ use mas_oidc_client::requests::userinfo::fetch_userinfo; use serde_json::json; use wiremock::{ - matchers::{header, method, path}, Mock, ResponseTemplate, + matchers::{header, method, path}, }; -use crate::{init_test, ACCESS_TOKEN, SUBJECT_IDENTIFIER}; +use crate::{ACCESS_TOKEN, SUBJECT_IDENTIFIER, init_test}; #[tokio::test] async fn pass_fetch_userinfo() { diff --git a/crates/oidc-client/tests/it/types/client_credentials.rs b/crates/oidc-client/tests/it/types/client_credentials.rs index f599b2ad5..b1939f40c 100644 --- a/crates/oidc-client/tests/it/types/client_credentials.rs +++ b/crates/oidc-client/tests/it/types/client_credentials.rs @@ -21,11 +21,11 @@ use oauth2_types::requests::AccessTokenResponse; use rand::SeedableRng; use serde_json::Value; use wiremock::{ - matchers::{header, method, path}, Mock, Request, ResponseTemplate, + matchers::{header, method, path}, }; -use crate::{client_credentials, init_test, now, ACCESS_TOKEN, CLIENT_ID, CLIENT_SECRET}; +use crate::{ACCESS_TOKEN, CLIENT_ID, CLIENT_SECRET, client_credentials, init_test, now}; #[tokio::test] async fn pass_none() { diff --git a/crates/policy/src/bin/schema.rs b/crates/policy/src/bin/schema.rs index 5a33a907d..d993cdbe9 100644 --- a/crates/policy/src/bin/schema.rs +++ b/crates/policy/src/bin/schema.rs @@ -9,7 +9,7 @@ use std::path::{Path, PathBuf}; use mas_policy::model::{ AuthorizationGrantInput, ClientRegistrationInput, EmailInput, RegisterInput, }; -use schemars::{gen::SchemaSettings, JsonSchema}; +use schemars::{JsonSchema, r#gen::SchemaSettings}; fn write_schema(out_dir: Option<&Path>, file: &str) { let mut writer: Box = match out_dir { diff --git a/crates/policy/src/lib.rs b/crates/policy/src/lib.rs index 4bc319391..47d54f468 100644 --- a/crates/policy/src/lib.rs +++ b/crates/policy/src/lib.rs @@ -7,8 +7,8 @@ pub mod model; use opa_wasm::{ - wasmtime::{Config, Engine, Module, OptLevel, Store}, Runtime, + wasmtime::{Config, Engine, Module, OptLevel, Store}, }; use serde::Serialize; use thiserror::Error; diff --git a/crates/router/src/endpoints.rs b/crates/router/src/endpoints.rs index 2015d3e22..059dda31e 100644 --- a/crates/router/src/endpoints.rs +++ b/crates/router/src/endpoints.rs @@ -7,8 +7,8 @@ use serde::{Deserialize, Serialize}; use ulid::Ulid; -pub use crate::traits::*; use crate::UrlBuilder; +pub use crate::traits::*; #[derive(Deserialize, Serialize, Clone, Debug)] #[serde(rename_all = "snake_case", tag = "kind")] diff --git a/crates/storage-pg/src/app_session.rs b/crates/storage-pg/src/app_session.rs index b812e37e9..f7b6a0ac6 100644 --- a/crates/storage-pg/src/app_session.rs +++ b/crates/storage-pg/src/app_session.rs @@ -9,10 +9,10 @@ use async_trait::async_trait; use mas_data_model::{CompatSession, CompatSessionState, Device, Session, SessionState, UserAgent}; use mas_storage::{ + Page, Pagination, app_session::{AppSession, AppSessionFilter, AppSessionRepository, AppSessionState}, compat::CompatSessionFilter, oauth2::OAuth2SessionFilter, - Page, Pagination, }; use oauth2_types::scope::{Scope, ScopeToken}; use sea_query::{ @@ -23,11 +23,11 @@ use sqlx::PgConnection; use ulid::Ulid; use crate::{ + DatabaseError, ExecuteExt, errors::DatabaseInconsistencyError, filter::StatementExt, iden::{CompatSessions, OAuth2Sessions}, pagination::QueryBuilderExt, - DatabaseError, ExecuteExt, }; /// An implementation of [`AppSessionRepository`] for a PostgreSQL connection @@ -464,14 +464,14 @@ mod tests { use chrono::Duration; use mas_data_model::Device; use mas_storage::{ + Pagination, RepositoryAccess, app_session::{AppSession, AppSessionFilter}, clock::MockClock, oauth2::OAuth2SessionRepository, - Pagination, RepositoryAccess, }; use oauth2_types::{ requests::GrantType, - scope::{Scope, OPENID}, + scope::{OPENID, Scope}, }; use rand::SeedableRng; use rand_chacha::ChaChaRng; diff --git a/crates/storage-pg/src/compat/access_token.rs b/crates/storage-pg/src/compat/access_token.rs index a4458e475..852b0e934 100644 --- a/crates/storage-pg/src/compat/access_token.rs +++ b/crates/storage-pg/src/compat/access_token.rs @@ -7,13 +7,13 @@ use async_trait::async_trait; use chrono::{DateTime, Duration, Utc}; use mas_data_model::{CompatAccessToken, CompatSession}; -use mas_storage::{compat::CompatAccessTokenRepository, Clock}; +use mas_storage::{Clock, compat::CompatAccessTokenRepository}; use rand::RngCore; use sqlx::PgConnection; use ulid::Ulid; use uuid::Uuid; -use crate::{tracing::ExecuteExt, DatabaseError}; +use crate::{DatabaseError, tracing::ExecuteExt}; /// An implementation of [`CompatAccessTokenRepository`] for a PostgreSQL /// connection diff --git a/crates/storage-pg/src/compat/mod.rs b/crates/storage-pg/src/compat/mod.rs index 93dd38447..4a50cb875 100644 --- a/crates/storage-pg/src/compat/mod.rs +++ b/crates/storage-pg/src/compat/mod.rs @@ -22,13 +22,13 @@ mod tests { use chrono::Duration; use mas_data_model::{Device, UserAgent}; use mas_storage::{ + Clock, Pagination, RepositoryAccess, clock::MockClock, compat::{ CompatAccessTokenRepository, CompatRefreshTokenRepository, CompatSessionFilter, CompatSessionRepository, CompatSsoLoginFilter, }, user::UserRepository, - Clock, Pagination, RepositoryAccess, }; use rand::SeedableRng; use rand_chacha::ChaChaRng; @@ -336,17 +336,18 @@ mod tests { { let mut repo = PgRepository::from_pool(&pool).await.unwrap().boxed(); // Adding the same token a second time should conflict - assert!(repo - .compat_access_token() - .add( - &mut rng, - &clock, - &session, - FIRST_TOKEN.to_owned(), - Some(Duration::try_minutes(1).unwrap()), - ) - .await - .is_err()); + assert!( + repo.compat_access_token() + .add( + &mut rng, + &clock, + &session, + FIRST_TOKEN.to_owned(), + Some(Duration::try_minutes(1).unwrap()), + ) + .await + .is_err() + ); repo.cancel().await.unwrap(); } @@ -507,11 +508,12 @@ mod tests { assert!(refresh_token_lookup.is_consumed()); // Consuming it again should not work - assert!(repo - .compat_refresh_token() - .consume(&clock, refresh_token) - .await - .is_err()); + assert!( + repo.compat_refresh_token() + .consume(&clock, refresh_token) + .await + .is_err() + ); repo.save().await.unwrap(); } diff --git a/crates/storage-pg/src/compat/refresh_token.rs b/crates/storage-pg/src/compat/refresh_token.rs index 2c2939c54..41188e010 100644 --- a/crates/storage-pg/src/compat/refresh_token.rs +++ b/crates/storage-pg/src/compat/refresh_token.rs @@ -9,13 +9,13 @@ use chrono::{DateTime, Utc}; use mas_data_model::{ CompatAccessToken, CompatRefreshToken, CompatRefreshTokenState, CompatSession, }; -use mas_storage::{compat::CompatRefreshTokenRepository, Clock}; +use mas_storage::{Clock, compat::CompatRefreshTokenRepository}; use rand::RngCore; use sqlx::PgConnection; use ulid::Ulid; use uuid::Uuid; -use crate::{tracing::ExecuteExt, DatabaseError}; +use crate::{DatabaseError, tracing::ExecuteExt}; /// An implementation of [`CompatRefreshTokenRepository`] for a PostgreSQL /// connection diff --git a/crates/storage-pg/src/compat/session.rs b/crates/storage-pg/src/compat/session.rs index 7d9fa1264..e3bb48861 100644 --- a/crates/storage-pg/src/compat/session.rs +++ b/crates/storage-pg/src/compat/session.rs @@ -13,11 +13,11 @@ use mas_data_model::{ User, UserAgent, }; use mas_storage::{ - compat::{CompatSessionFilter, CompatSessionRepository}, Clock, Page, Pagination, + compat::{CompatSessionFilter, CompatSessionRepository}, }; use rand::RngCore; -use sea_query::{enum_def, Expr, PostgresQueryBuilder, Query}; +use sea_query::{Expr, PostgresQueryBuilder, Query, enum_def}; use sea_query_binder::SqlxBinder; use sqlx::PgConnection; use ulid::Ulid; @@ -25,11 +25,11 @@ use url::Url; use uuid::Uuid; use crate::{ + DatabaseError, DatabaseInconsistencyError, filter::{Filter, StatementExt, StatementWithJoinsExt}, iden::{CompatSessions, CompatSsoLogins}, pagination::QueryBuilderExt, tracing::ExecuteExt, - DatabaseError, DatabaseInconsistencyError, }; /// An implementation of [`CompatSessionRepository`] for a PostgreSQL connection diff --git a/crates/storage-pg/src/compat/sso_login.rs b/crates/storage-pg/src/compat/sso_login.rs index 8b75ab130..34da9f093 100644 --- a/crates/storage-pg/src/compat/sso_login.rs +++ b/crates/storage-pg/src/compat/sso_login.rs @@ -8,11 +8,11 @@ use async_trait::async_trait; use chrono::{DateTime, Utc}; use mas_data_model::{CompatSession, CompatSsoLogin, CompatSsoLoginState}; use mas_storage::{ - compat::{CompatSsoLoginFilter, CompatSsoLoginRepository}, Clock, Page, Pagination, + compat::{CompatSsoLoginFilter, CompatSsoLoginRepository}, }; use rand::RngCore; -use sea_query::{enum_def, Expr, PostgresQueryBuilder, Query}; +use sea_query::{Expr, PostgresQueryBuilder, Query, enum_def}; use sea_query_binder::SqlxBinder; use sqlx::PgConnection; use ulid::Ulid; @@ -20,11 +20,11 @@ use url::Url; use uuid::Uuid; use crate::{ + DatabaseError, DatabaseInconsistencyError, filter::{Filter, StatementExt}, iden::{CompatSessions, CompatSsoLogins}, pagination::QueryBuilderExt, tracing::ExecuteExt, - DatabaseError, DatabaseInconsistencyError, }; /// An implementation of [`CompatSsoLoginRepository`] for a PostgreSQL diff --git a/crates/storage-pg/src/oauth2/access_token.rs b/crates/storage-pg/src/oauth2/access_token.rs index 48801ead6..de652739f 100644 --- a/crates/storage-pg/src/oauth2/access_token.rs +++ b/crates/storage-pg/src/oauth2/access_token.rs @@ -7,13 +7,13 @@ use async_trait::async_trait; use chrono::{DateTime, Duration, Utc}; use mas_data_model::{AccessToken, AccessTokenState, Session}; -use mas_storage::{oauth2::OAuth2AccessTokenRepository, Clock}; +use mas_storage::{Clock, oauth2::OAuth2AccessTokenRepository}; use rand::RngCore; use sqlx::PgConnection; use ulid::Ulid; use uuid::Uuid; -use crate::{tracing::ExecuteExt, DatabaseError}; +use crate::{DatabaseError, tracing::ExecuteExt}; /// An implementation of [`OAuth2AccessTokenRepository`] for a PostgreSQL /// connection diff --git a/crates/storage-pg/src/oauth2/authorization_grant.rs b/crates/storage-pg/src/oauth2/authorization_grant.rs index 934e08cec..7a6162171 100644 --- a/crates/storage-pg/src/oauth2/authorization_grant.rs +++ b/crates/storage-pg/src/oauth2/authorization_grant.rs @@ -12,7 +12,7 @@ use mas_data_model::{ AuthorizationCode, AuthorizationGrant, AuthorizationGrantStage, Client, Pkce, Session, }; use mas_iana::oauth::PkceCodeChallengeMethod; -use mas_storage::{oauth2::OAuth2AuthorizationGrantRepository, Clock}; +use mas_storage::{Clock, oauth2::OAuth2AuthorizationGrantRepository}; use oauth2_types::{requests::ResponseMode, scope::Scope}; use rand::RngCore; use sqlx::PgConnection; @@ -20,7 +20,7 @@ use ulid::Ulid; use url::Url; use uuid::Uuid; -use crate::{tracing::ExecuteExt, DatabaseError, DatabaseInconsistencyError}; +use crate::{DatabaseError, DatabaseInconsistencyError, tracing::ExecuteExt}; /// An implementation of [`OAuth2AuthorizationGrantRepository`] for a PostgreSQL /// connection diff --git a/crates/storage-pg/src/oauth2/client.rs b/crates/storage-pg/src/oauth2/client.rs index eeb09d0f9..81298fe9d 100644 --- a/crates/storage-pg/src/oauth2/client.rs +++ b/crates/storage-pg/src/oauth2/client.rs @@ -14,7 +14,7 @@ use async_trait::async_trait; use mas_data_model::{Client, JwksOrJwksUri, User}; use mas_iana::{jose::JsonWebSignatureAlg, oauth::OAuthClientAuthenticationMethod}; use mas_jose::jwk::PublicJsonWebKeySet; -use mas_storage::{oauth2::OAuth2ClientRepository, Clock}; +use mas_storage::{Clock, oauth2::OAuth2ClientRepository}; use oauth2_types::{ oidc::ApplicationType, requests::GrantType, @@ -23,12 +23,12 @@ use oauth2_types::{ use opentelemetry_semantic_conventions::attribute::DB_QUERY_TEXT; use rand::RngCore; use sqlx::PgConnection; -use tracing::{info_span, Instrument}; +use tracing::{Instrument, info_span}; use ulid::Ulid; use url::Url; use uuid::Uuid; -use crate::{tracing::ExecuteExt, DatabaseError, DatabaseInconsistencyError}; +use crate::{DatabaseError, DatabaseInconsistencyError, tracing::ExecuteExt}; /// An implementation of [`OAuth2ClientRepository`] for a PostgreSQL connection pub struct PgOAuth2ClientRepository<'c> { @@ -224,7 +224,7 @@ impl TryInto for OAuth2ClientLookup { _ => { return Err(DatabaseInconsistencyError::on("oauth2_clients") .column("jwks(_uri)") - .row(id)) + .row(id)); } }; diff --git a/crates/storage-pg/src/oauth2/device_code_grant.rs b/crates/storage-pg/src/oauth2/device_code_grant.rs index fb8883dd0..409ab3ff9 100644 --- a/crates/storage-pg/src/oauth2/device_code_grant.rs +++ b/crates/storage-pg/src/oauth2/device_code_grant.rs @@ -10,8 +10,8 @@ use async_trait::async_trait; use chrono::{DateTime, Utc}; use mas_data_model::{BrowserSession, DeviceCodeGrant, DeviceCodeGrantState, Session, UserAgent}; use mas_storage::{ - oauth2::{OAuth2DeviceCodeGrantParams, OAuth2DeviceCodeGrantRepository}, Clock, + oauth2::{OAuth2DeviceCodeGrantParams, OAuth2DeviceCodeGrantRepository}, }; use oauth2_types::scope::Scope; use rand::RngCore; @@ -19,7 +19,7 @@ use sqlx::PgConnection; use ulid::Ulid; use uuid::Uuid; -use crate::{errors::DatabaseInconsistencyError, DatabaseError, ExecuteExt}; +use crate::{DatabaseError, ExecuteExt, errors::DatabaseInconsistencyError}; /// An implementation of [`OAuth2DeviceCodeGrantRepository`] for a PostgreSQL /// connection diff --git a/crates/storage-pg/src/oauth2/mod.rs b/crates/storage-pg/src/oauth2/mod.rs index 556d4314d..e94f1e6c6 100644 --- a/crates/storage-pg/src/oauth2/mod.rs +++ b/crates/storage-pg/src/oauth2/mod.rs @@ -26,13 +26,13 @@ mod tests { use chrono::Duration; use mas_data_model::{AuthorizationCode, UserAgent}; use mas_storage::{ + Clock, Pagination, clock::MockClock, oauth2::{OAuth2DeviceCodeGrantParams, OAuth2SessionFilter, OAuth2SessionRepository}, - Clock, Pagination, }; use oauth2_types::{ requests::{GrantType, ResponseMode}, - scope::{Scope, EMAIL, OPENID, PROFILE}, + scope::{EMAIL, OPENID, PROFILE, Scope}, }; use rand::SeedableRng; use rand_chacha::ChaChaRng; diff --git a/crates/storage-pg/src/oauth2/refresh_token.rs b/crates/storage-pg/src/oauth2/refresh_token.rs index ee4412ffd..742d3ae68 100644 --- a/crates/storage-pg/src/oauth2/refresh_token.rs +++ b/crates/storage-pg/src/oauth2/refresh_token.rs @@ -7,13 +7,13 @@ use async_trait::async_trait; use chrono::{DateTime, Utc}; use mas_data_model::{AccessToken, RefreshToken, RefreshTokenState, Session}; -use mas_storage::{oauth2::OAuth2RefreshTokenRepository, Clock}; +use mas_storage::{Clock, oauth2::OAuth2RefreshTokenRepository}; use rand::RngCore; use sqlx::PgConnection; use ulid::Ulid; use uuid::Uuid; -use crate::{tracing::ExecuteExt, DatabaseError, DatabaseInconsistencyError}; +use crate::{DatabaseError, DatabaseInconsistencyError, tracing::ExecuteExt}; /// An implementation of [`OAuth2RefreshTokenRepository`] for a PostgreSQL /// connection @@ -63,7 +63,7 @@ impl TryFrom for RefreshToken { _ => { return Err(DatabaseInconsistencyError::on("oauth2_refresh_tokens") .column("next_oauth2_refresh_token_id") - .row(id)) + .row(id)); } }; diff --git a/crates/storage-pg/src/oauth2/session.rs b/crates/storage-pg/src/oauth2/session.rs index a81771e90..0517f6d98 100644 --- a/crates/storage-pg/src/oauth2/session.rs +++ b/crates/storage-pg/src/oauth2/session.rs @@ -10,23 +10,23 @@ use async_trait::async_trait; use chrono::{DateTime, Utc}; use mas_data_model::{BrowserSession, Client, Session, SessionState, User, UserAgent}; use mas_storage::{ - oauth2::{OAuth2SessionFilter, OAuth2SessionRepository}, Clock, Page, Pagination, + oauth2::{OAuth2SessionFilter, OAuth2SessionRepository}, }; use oauth2_types::scope::{Scope, ScopeToken}; use rand::RngCore; -use sea_query::{enum_def, extension::postgres::PgExpr, Expr, PgFunc, PostgresQueryBuilder, Query}; +use sea_query::{Expr, PgFunc, PostgresQueryBuilder, Query, enum_def, extension::postgres::PgExpr}; use sea_query_binder::SqlxBinder; use sqlx::PgConnection; use ulid::Ulid; use uuid::Uuid; use crate::{ + DatabaseError, DatabaseInconsistencyError, filter::{Filter, StatementExt}, iden::{OAuth2Clients, OAuth2Sessions}, pagination::QueryBuilderExt, tracing::ExecuteExt, - DatabaseError, DatabaseInconsistencyError, }; /// An implementation of [`OAuth2SessionRepository`] for a PostgreSQL connection diff --git a/crates/storage-pg/src/pagination.rs b/crates/storage-pg/src/pagination.rs index 68e95577c..c4c8317f1 100644 --- a/crates/storage-pg/src/pagination.rs +++ b/crates/storage-pg/src/pagination.rs @@ -6,7 +6,7 @@ //! Utilities to manage paginated queries. -use mas_storage::{pagination::PaginationDirection, Pagination}; +use mas_storage::{Pagination, pagination::PaginationDirection}; use sea_query::IntoColumnRef; use uuid::Uuid; diff --git a/crates/storage-pg/src/queue/job.rs b/crates/storage-pg/src/queue/job.rs index be7ed6bb2..6a7d81e01 100644 --- a/crates/storage-pg/src/queue/job.rs +++ b/crates/storage-pg/src/queue/job.rs @@ -9,8 +9,8 @@ use async_trait::async_trait; use chrono::{DateTime, Duration, Utc}; use mas_storage::{ - queue::{Job, QueueJobRepository, Worker}, Clock, + queue::{Job, QueueJobRepository, Worker}, }; use opentelemetry_semantic_conventions::trace::DB_QUERY_TEXT; use rand::RngCore; diff --git a/crates/storage-pg/src/queue/worker.rs b/crates/storage-pg/src/queue/worker.rs index 61b96b5fd..6c4a8e6c5 100644 --- a/crates/storage-pg/src/queue/worker.rs +++ b/crates/storage-pg/src/queue/worker.rs @@ -9,8 +9,8 @@ use async_trait::async_trait; use chrono::Duration; use mas_storage::{ - queue::{QueueWorkerRepository, Worker}, Clock, + queue::{QueueWorkerRepository, Worker}, }; use rand::RngCore; use sqlx::PgConnection; diff --git a/crates/storage-pg/src/repository.rs b/crates/storage-pg/src/repository.rs index fde0f13e3..69ec9980b 100644 --- a/crates/storage-pg/src/repository.rs +++ b/crates/storage-pg/src/repository.rs @@ -6,8 +6,9 @@ use std::ops::{Deref, DerefMut}; -use futures_util::{future::BoxFuture, FutureExt, TryFutureExt}; +use futures_util::{FutureExt, TryFutureExt, future::BoxFuture}; use mas_storage::{ + BoxRepository, MapErr, Repository, RepositoryAccess, RepositoryError, RepositoryTransaction, app_session::AppSessionRepository, compat::{ CompatAccessTokenRepository, CompatRefreshTokenRepository, CompatSessionRepository, @@ -23,12 +24,12 @@ use mas_storage::{ UpstreamOAuthSessionRepository, }, user::{BrowserSessionRepository, UserEmailRepository, UserPasswordRepository, UserRepository}, - BoxRepository, MapErr, Repository, RepositoryAccess, RepositoryError, RepositoryTransaction, }; use sqlx::{PgConnection, PgPool, Postgres, Transaction}; use tracing::Instrument; use crate::{ + DatabaseError, app_session::PgAppSessionRepository, compat::{ PgCompatAccessTokenRepository, PgCompatRefreshTokenRepository, PgCompatSessionRepository, @@ -52,7 +53,6 @@ use crate::{ PgUserRecoveryRepository, PgUserRegistrationRepository, PgUserRepository, PgUserTermsRepository, }, - DatabaseError, }; /// An implementation of the [`Repository`] trait backed by a PostgreSQL diff --git a/crates/storage-pg/src/upstream_oauth2/link.rs b/crates/storage-pg/src/upstream_oauth2/link.rs index 198aae5ad..accbcb8c1 100644 --- a/crates/storage-pg/src/upstream_oauth2/link.rs +++ b/crates/storage-pg/src/upstream_oauth2/link.rs @@ -8,22 +8,22 @@ use async_trait::async_trait; use chrono::{DateTime, Utc}; use mas_data_model::{UpstreamOAuthLink, UpstreamOAuthProvider, User}; use mas_storage::{ - upstream_oauth2::{UpstreamOAuthLinkFilter, UpstreamOAuthLinkRepository}, Clock, Page, Pagination, + upstream_oauth2::{UpstreamOAuthLinkFilter, UpstreamOAuthLinkRepository}, }; use rand::RngCore; -use sea_query::{enum_def, Expr, PostgresQueryBuilder, Query}; +use sea_query::{Expr, PostgresQueryBuilder, Query, enum_def}; use sea_query_binder::SqlxBinder; use sqlx::PgConnection; use ulid::Ulid; use uuid::Uuid; use crate::{ + DatabaseError, filter::{Filter, StatementExt}, iden::{UpstreamOAuthLinks, UpstreamOAuthProviders}, pagination::QueryBuilderExt, tracing::ExecuteExt, - DatabaseError, }; /// An implementation of [`UpstreamOAuthLinkRepository`] for a PostgreSQL diff --git a/crates/storage-pg/src/upstream_oauth2/mod.rs b/crates/storage-pg/src/upstream_oauth2/mod.rs index 918154491..2d0030426 100644 --- a/crates/storage-pg/src/upstream_oauth2/mod.rs +++ b/crates/storage-pg/src/upstream_oauth2/mod.rs @@ -24,6 +24,7 @@ mod tests { }; use mas_iana::jose::JsonWebSignatureAlg; use mas_storage::{ + Pagination, RepositoryAccess, clock::MockClock, upstream_oauth2::{ UpstreamOAuthLinkFilter, UpstreamOAuthLinkRepository, UpstreamOAuthProviderFilter, @@ -31,9 +32,8 @@ mod tests { UpstreamOAuthSessionRepository, }, user::UserRepository, - Pagination, RepositoryAccess, }; - use oauth2_types::scope::{Scope, OPENID}; + use oauth2_types::scope::{OPENID, Scope}; use rand::SeedableRng; use sqlx::PgPool; @@ -407,15 +407,16 @@ mod tests { assert_eq!(&edge_ids, &ids[6..8]); // There should not be any disabled providers - assert!(repo - .upstream_oauth_provider() - .list( - UpstreamOAuthProviderFilter::new().disabled_only(), - Pagination::first(1) - ) - .await - .unwrap() - .edges - .is_empty()); + assert!( + repo.upstream_oauth_provider() + .list( + UpstreamOAuthProviderFilter::new().disabled_only(), + Pagination::first(1) + ) + .await + .unwrap() + .edges + .is_empty() + ); } } diff --git a/crates/storage-pg/src/upstream_oauth2/provider.rs b/crates/storage-pg/src/upstream_oauth2/provider.rs index c9e2b0eca..b65c05e78 100644 --- a/crates/storage-pg/src/upstream_oauth2/provider.rs +++ b/crates/storage-pg/src/upstream_oauth2/provider.rs @@ -8,26 +8,26 @@ use async_trait::async_trait; use chrono::{DateTime, Utc}; use mas_data_model::{UpstreamOAuthProvider, UpstreamOAuthProviderClaimsImports}; use mas_storage::{ + Clock, Page, Pagination, upstream_oauth2::{ UpstreamOAuthProviderFilter, UpstreamOAuthProviderParams, UpstreamOAuthProviderRepository, }, - Clock, Page, Pagination, }; use opentelemetry_semantic_conventions::attribute::DB_QUERY_TEXT; use rand::RngCore; -use sea_query::{enum_def, Expr, PostgresQueryBuilder, Query}; +use sea_query::{Expr, PostgresQueryBuilder, Query, enum_def}; use sea_query_binder::SqlxBinder; -use sqlx::{types::Json, PgConnection}; -use tracing::{info_span, Instrument}; +use sqlx::{PgConnection, types::Json}; +use tracing::{Instrument, info_span}; use ulid::Ulid; use uuid::Uuid; use crate::{ + DatabaseError, DatabaseInconsistencyError, filter::{Filter, StatementExt}, iden::UpstreamOAuthProviders, pagination::QueryBuilderExt, tracing::ExecuteExt, - DatabaseError, DatabaseInconsistencyError, }; /// An implementation of [`UpstreamOAuthProviderRepository`] for a PostgreSQL diff --git a/crates/storage-pg/src/upstream_oauth2/session.rs b/crates/storage-pg/src/upstream_oauth2/session.rs index d866aee4a..fe1510e85 100644 --- a/crates/storage-pg/src/upstream_oauth2/session.rs +++ b/crates/storage-pg/src/upstream_oauth2/session.rs @@ -10,13 +10,13 @@ use mas_data_model::{ UpstreamOAuthAuthorizationSession, UpstreamOAuthAuthorizationSessionState, UpstreamOAuthLink, UpstreamOAuthProvider, }; -use mas_storage::{upstream_oauth2::UpstreamOAuthSessionRepository, Clock}; +use mas_storage::{Clock, upstream_oauth2::UpstreamOAuthSessionRepository}; use rand::RngCore; use sqlx::PgConnection; use ulid::Ulid; use uuid::Uuid; -use crate::{tracing::ExecuteExt, DatabaseError, DatabaseInconsistencyError}; +use crate::{DatabaseError, DatabaseInconsistencyError, tracing::ExecuteExt}; /// An implementation of [`UpstreamOAuthSessionRepository`] for a PostgreSQL /// connection @@ -91,9 +91,10 @@ impl TryFrom for UpstreamOAuthAuthorizationSession { consumed_at, }, _ => { - return Err( - DatabaseInconsistencyError::on("upstream_oauth_authorization_sessions").row(id), + return Err(DatabaseInconsistencyError::on( + "upstream_oauth_authorization_sessions", ) + .row(id)); } }; diff --git a/crates/storage-pg/src/user/email.rs b/crates/storage-pg/src/user/email.rs index 091714f4a..8090f054c 100644 --- a/crates/storage-pg/src/user/email.rs +++ b/crates/storage-pg/src/user/email.rs @@ -11,24 +11,24 @@ use mas_data_model::{ UserRegistration, }; use mas_storage::{ - user::{UserEmailFilter, UserEmailRepository}, Clock, Page, Pagination, + user::{UserEmailFilter, UserEmailRepository}, }; use opentelemetry_semantic_conventions::attribute::DB_QUERY_TEXT; use rand::RngCore; -use sea_query::{enum_def, Expr, PostgresQueryBuilder, Query}; +use sea_query::{Expr, PostgresQueryBuilder, Query, enum_def}; use sea_query_binder::SqlxBinder; use sqlx::PgConnection; -use tracing::{info_span, Instrument}; +use tracing::{Instrument, info_span}; use ulid::Ulid; use uuid::Uuid; use crate::{ + DatabaseError, filter::{Filter, StatementExt}, iden::UserEmails, pagination::QueryBuilderExt, tracing::ExecuteExt, - DatabaseError, }; /// An implementation of [`UserEmailRepository`] for a PostgreSQL connection diff --git a/crates/storage-pg/src/user/mod.rs b/crates/storage-pg/src/user/mod.rs index ff0119c2a..a7a1773d6 100644 --- a/crates/storage-pg/src/user/mod.rs +++ b/crates/storage-pg/src/user/mod.rs @@ -10,8 +10,8 @@ use async_trait::async_trait; use mas_data_model::User; use mas_storage::{ - user::{UserFilter, UserRepository}, Clock, + user::{UserFilter, UserRepository}, }; use rand::RngCore; use sea_query::{Expr, PostgresQueryBuilder, Query}; @@ -21,11 +21,11 @@ use ulid::Ulid; use uuid::Uuid; use crate::{ + DatabaseError, filter::{Filter, StatementExt}, iden::Users, pagination::QueryBuilderExt, tracing::ExecuteExt, - DatabaseError, }; mod email; diff --git a/crates/storage-pg/src/user/password.rs b/crates/storage-pg/src/user/password.rs index 04585e8d9..6a1b19f0a 100644 --- a/crates/storage-pg/src/user/password.rs +++ b/crates/storage-pg/src/user/password.rs @@ -7,13 +7,13 @@ use async_trait::async_trait; use chrono::{DateTime, Utc}; use mas_data_model::{Password, User}; -use mas_storage::{user::UserPasswordRepository, Clock}; +use mas_storage::{Clock, user::UserPasswordRepository}; use rand::RngCore; use sqlx::PgConnection; use ulid::Ulid; use uuid::Uuid; -use crate::{tracing::ExecuteExt, DatabaseError, DatabaseInconsistencyError}; +use crate::{DatabaseError, DatabaseInconsistencyError, tracing::ExecuteExt}; /// An implementation of [`UserPasswordRepository`] for a PostgreSQL connection pub struct PgUserPasswordRepository<'c> { diff --git a/crates/storage-pg/src/user/recovery.rs b/crates/storage-pg/src/user/recovery.rs index fcab3b9e6..d838b2531 100644 --- a/crates/storage-pg/src/user/recovery.rs +++ b/crates/storage-pg/src/user/recovery.rs @@ -9,7 +9,7 @@ use std::net::IpAddr; use async_trait::async_trait; use chrono::{DateTime, Duration, Utc}; use mas_data_model::{UserAgent, UserEmail, UserRecoverySession, UserRecoveryTicket}; -use mas_storage::{user::UserRecoveryRepository, Clock}; +use mas_storage::{Clock, user::UserRecoveryRepository}; use rand::RngCore; use sqlx::PgConnection; use ulid::Ulid; diff --git a/crates/storage-pg/src/user/registration.rs b/crates/storage-pg/src/user/registration.rs index 5087d1d9e..1aa2afe86 100644 --- a/crates/storage-pg/src/user/registration.rs +++ b/crates/storage-pg/src/user/registration.rs @@ -10,7 +10,7 @@ use chrono::{DateTime, Utc}; use mas_data_model::{ UserAgent, UserEmailAuthentication, UserRegistration, UserRegistrationPassword, }; -use mas_storage::{user::UserRegistrationRepository, Clock}; +use mas_storage::{Clock, user::UserRegistrationRepository}; use rand::RngCore; use sqlx::PgConnection; use ulid::Ulid; @@ -395,7 +395,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr}; use mas_data_model::{UserAgent, UserRegistrationPassword}; - use mas_storage::{clock::MockClock, Clock}; + use mas_storage::{Clock, clock::MockClock}; use rand::SeedableRng; use rand_chacha::ChaChaRng; use sqlx::PgPool; diff --git a/crates/storage-pg/src/user/session.rs b/crates/storage-pg/src/user/session.rs index 7d0f6bda7..f90c89b89 100644 --- a/crates/storage-pg/src/user/session.rs +++ b/crates/storage-pg/src/user/session.rs @@ -13,8 +13,8 @@ use mas_data_model::{ UpstreamOAuthAuthorizationSession, User, UserAgent, }; use mas_storage::{ - user::{BrowserSessionFilter, BrowserSessionRepository}, Clock, Page, Pagination, + user::{BrowserSessionFilter, BrowserSessionRepository}, }; use rand::RngCore; use sea_query::{Expr, PostgresQueryBuilder}; @@ -24,11 +24,11 @@ use ulid::Ulid; use uuid::Uuid; use crate::{ + DatabaseError, DatabaseInconsistencyError, filter::StatementExt, iden::{UserSessions, Users}, pagination::QueryBuilderExt, tracing::ExecuteExt, - DatabaseError, DatabaseInconsistencyError, }; /// An implementation of [`BrowserSessionRepository`] for a PostgreSQL diff --git a/crates/storage-pg/src/user/terms.rs b/crates/storage-pg/src/user/terms.rs index f51024606..9efa1f008 100644 --- a/crates/storage-pg/src/user/terms.rs +++ b/crates/storage-pg/src/user/terms.rs @@ -6,14 +6,14 @@ use async_trait::async_trait; use mas_data_model::User; -use mas_storage::{user::UserTermsRepository, Clock}; +use mas_storage::{Clock, user::UserTermsRepository}; use rand::RngCore; use sqlx::PgConnection; use ulid::Ulid; use url::Url; use uuid::Uuid; -use crate::{tracing::ExecuteExt, DatabaseError}; +use crate::{DatabaseError, tracing::ExecuteExt}; /// An implementation of [`UserTermsRepository`] for a PostgreSQL connection pub struct PgUserTermsRepository<'c> { diff --git a/crates/storage-pg/src/user/tests.rs b/crates/storage-pg/src/user/tests.rs index c6371500a..8eb77d633 100644 --- a/crates/storage-pg/src/user/tests.rs +++ b/crates/storage-pg/src/user/tests.rs @@ -6,12 +6,12 @@ use chrono::Duration; use mas_storage::{ + Clock, Pagination, RepositoryAccess, clock::MockClock, user::{ BrowserSessionFilter, BrowserSessionRepository, UserEmailFilter, UserEmailRepository, UserFilter, UserPasswordRepository, UserRepository, }, - Clock, Pagination, RepositoryAccess, }; use rand::SeedableRng; use rand_chacha::ChaChaRng; @@ -36,12 +36,13 @@ async fn test_user_repo(pool: PgPool) { // Initially, the user shouldn't exist assert!(!repo.user().exists(USERNAME).await.unwrap()); - assert!(repo - .user() - .find_by_username(USERNAME) - .await - .unwrap() - .is_none()); + assert!( + repo.user() + .find_by_username(USERNAME) + .await + .unwrap() + .is_none() + ); assert_eq!(repo.user().count(all).await.unwrap(), 0); assert_eq!(repo.user().count(admin).await.unwrap(), 0); @@ -58,12 +59,13 @@ async fn test_user_repo(pool: PgPool) { // And now it should exist assert!(repo.user().exists(USERNAME).await.unwrap()); - assert!(repo - .user() - .find_by_username(USERNAME) - .await - .unwrap() - .is_some()); + assert!( + repo.user() + .find_by_username(USERNAME) + .await + .unwrap() + .is_some() + ); assert!(repo.user().lookup(user.id).await.unwrap().is_some()); assert_eq!(repo.user().count(all).await.unwrap(), 1); @@ -74,11 +76,12 @@ async fn test_user_repo(pool: PgPool) { // Adding a second time should give a conflict // It should not poison the transaction though - assert!(repo - .user() - .add(&mut rng, &clock, USERNAME.to_owned()) - .await - .is_err()); + assert!( + repo.user() + .add(&mut rng, &clock, USERNAME.to_owned()) + .await + .is_err() + ); // Try locking a user assert!(user.is_valid()); @@ -198,12 +201,13 @@ async fn test_user_email_repo(pool: PgPool) { .unwrap(); // The user email should not exist yet - assert!(repo - .user_email() - .find(&user, EMAIL) - .await - .unwrap() - .is_none()); + assert!( + repo.user_email() + .find(&user, EMAIL) + .await + .unwrap() + .is_none() + ); let all = UserEmailFilter::new().for_user(&user); @@ -222,12 +226,13 @@ async fn test_user_email_repo(pool: PgPool) { // Check the counts assert_eq!(repo.user_email().count(all).await.unwrap(), 1); - assert!(repo - .user_email() - .find(&user, EMAIL) - .await - .unwrap() - .is_some()); + assert!( + repo.user_email() + .find(&user, EMAIL) + .await + .unwrap() + .is_some() + ); let user_email = repo .user_email() diff --git a/crates/storage/src/app_session.rs b/crates/storage/src/app_session.rs index 0a9bdfa2b..52fc4483d 100644 --- a/crates/storage/src/app_session.rs +++ b/crates/storage/src/app_session.rs @@ -10,7 +10,7 @@ use async_trait::async_trait; use chrono::{DateTime, Utc}; use mas_data_model::{BrowserSession, CompatSession, Device, Session, User}; -use crate::{repository_impl, Page, Pagination}; +use crate::{Page, Pagination, repository_impl}; /// The state of a session #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/crates/storage/src/clock.rs b/crates/storage/src/clock.rs index c19f54fc9..6af9926e1 100644 --- a/crates/storage/src/clock.rs +++ b/crates/storage/src/clock.rs @@ -10,7 +10,7 @@ //! [`SystemClock`] which uses the system time, and a [`MockClock`], which can //! be used and freely manipulated in tests. -use std::sync::{atomic::AtomicI64, Arc}; +use std::sync::{Arc, atomic::AtomicI64}; use chrono::{DateTime, TimeZone, Utc}; diff --git a/crates/storage/src/compat/access_token.rs b/crates/storage/src/compat/access_token.rs index 4cd804e6d..87d244f4d 100644 --- a/crates/storage/src/compat/access_token.rs +++ b/crates/storage/src/compat/access_token.rs @@ -10,7 +10,7 @@ use mas_data_model::{CompatAccessToken, CompatSession}; use rand_core::RngCore; use ulid::Ulid; -use crate::{repository_impl, Clock}; +use crate::{Clock, repository_impl}; /// A [`CompatAccessTokenRepository`] helps interacting with /// [`CompatAccessToken`] saved in the storage backend diff --git a/crates/storage/src/compat/refresh_token.rs b/crates/storage/src/compat/refresh_token.rs index 4bcbd4d55..ff568ec9f 100644 --- a/crates/storage/src/compat/refresh_token.rs +++ b/crates/storage/src/compat/refresh_token.rs @@ -9,7 +9,7 @@ use mas_data_model::{CompatAccessToken, CompatRefreshToken, CompatSession}; use rand_core::RngCore; use ulid::Ulid; -use crate::{repository_impl, Clock}; +use crate::{Clock, repository_impl}; /// A [`CompatRefreshTokenRepository`] helps interacting with /// [`CompatRefreshToken`] saved in the storage backend diff --git a/crates/storage/src/compat/session.rs b/crates/storage/src/compat/session.rs index 092b12f69..81a417fa6 100644 --- a/crates/storage/src/compat/session.rs +++ b/crates/storage/src/compat/session.rs @@ -12,7 +12,7 @@ use mas_data_model::{BrowserSession, CompatSession, CompatSsoLogin, Device, User use rand_core::RngCore; use ulid::Ulid; -use crate::{repository_impl, Clock, Page, Pagination}; +use crate::{Clock, Page, Pagination, repository_impl}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CompatSessionState { diff --git a/crates/storage/src/compat/sso_login.rs b/crates/storage/src/compat/sso_login.rs index 133ae9db6..425541d65 100644 --- a/crates/storage/src/compat/sso_login.rs +++ b/crates/storage/src/compat/sso_login.rs @@ -10,7 +10,7 @@ use rand_core::RngCore; use ulid::Ulid; use url::Url; -use crate::{pagination::Page, repository_impl, Clock, Pagination}; +use crate::{Clock, Pagination, pagination::Page, repository_impl}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CompatSsoLoginState { diff --git a/crates/storage/src/oauth2/access_token.rs b/crates/storage/src/oauth2/access_token.rs index 989dd9861..9a128bbdb 100644 --- a/crates/storage/src/oauth2/access_token.rs +++ b/crates/storage/src/oauth2/access_token.rs @@ -10,7 +10,7 @@ use mas_data_model::{AccessToken, Session}; use rand_core::RngCore; use ulid::Ulid; -use crate::{repository_impl, Clock}; +use crate::{Clock, repository_impl}; /// An [`OAuth2AccessTokenRepository`] helps interacting with [`AccessToken`] /// saved in the storage backend diff --git a/crates/storage/src/oauth2/authorization_grant.rs b/crates/storage/src/oauth2/authorization_grant.rs index ea18087ea..cff0ba418 100644 --- a/crates/storage/src/oauth2/authorization_grant.rs +++ b/crates/storage/src/oauth2/authorization_grant.rs @@ -13,7 +13,7 @@ use rand_core::RngCore; use ulid::Ulid; use url::Url; -use crate::{repository_impl, Clock}; +use crate::{Clock, repository_impl}; /// An [`OAuth2AuthorizationGrantRepository`] helps interacting with /// [`AuthorizationGrant`] saved in the storage backend @@ -91,7 +91,7 @@ pub trait OAuth2AuthorizationGrantRepository: Send + Sync { /// /// Returns [`Self::Error`] if the underlying repository fails async fn find_by_code(&mut self, code: &str) - -> Result, Self::Error>; + -> Result, Self::Error>; /// Fulfill an authorization grant, by giving the [`Session`] that it /// created diff --git a/crates/storage/src/oauth2/client.rs b/crates/storage/src/oauth2/client.rs index 4f1ea8913..6c8ba61a6 100644 --- a/crates/storage/src/oauth2/client.rs +++ b/crates/storage/src/oauth2/client.rs @@ -15,7 +15,7 @@ use rand_core::RngCore; use ulid::Ulid; use url::Url; -use crate::{repository_impl, Clock}; +use crate::{Clock, repository_impl}; /// An [`OAuth2ClientRepository`] helps interacting with [`Client`] saved in the /// storage backend diff --git a/crates/storage/src/oauth2/device_code_grant.rs b/crates/storage/src/oauth2/device_code_grant.rs index 7e6c85944..9a85a3a75 100644 --- a/crates/storage/src/oauth2/device_code_grant.rs +++ b/crates/storage/src/oauth2/device_code_grant.rs @@ -13,7 +13,7 @@ use oauth2_types::scope::Scope; use rand_core::RngCore; use ulid::Ulid; -use crate::{repository_impl, Clock}; +use crate::{Clock, repository_impl}; /// Parameters used to create a new [`DeviceCodeGrant`] pub struct OAuth2DeviceCodeGrantParams<'a> { diff --git a/crates/storage/src/oauth2/refresh_token.rs b/crates/storage/src/oauth2/refresh_token.rs index 6e240f7b9..7f3928906 100644 --- a/crates/storage/src/oauth2/refresh_token.rs +++ b/crates/storage/src/oauth2/refresh_token.rs @@ -9,7 +9,7 @@ use mas_data_model::{AccessToken, RefreshToken, Session}; use rand_core::RngCore; use ulid::Ulid; -use crate::{repository_impl, Clock}; +use crate::{Clock, repository_impl}; /// An [`OAuth2RefreshTokenRepository`] helps interacting with [`RefreshToken`] /// saved in the storage backend diff --git a/crates/storage/src/oauth2/session.rs b/crates/storage/src/oauth2/session.rs index 71cca8ef3..d53eaa85c 100644 --- a/crates/storage/src/oauth2/session.rs +++ b/crates/storage/src/oauth2/session.rs @@ -13,7 +13,7 @@ use oauth2_types::scope::Scope; use rand_core::RngCore; use ulid::Ulid; -use crate::{pagination::Page, repository_impl, Clock, Pagination}; +use crate::{Clock, Pagination, pagination::Page, repository_impl}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum OAuth2SessionState { @@ -357,7 +357,7 @@ pub trait OAuth2SessionRepository: Send + Sync { /// /// Returns [`Self::Error`] if the underlying repository fails async fn finish(&mut self, clock: &dyn Clock, session: Session) - -> Result; + -> Result; /// Mark all the [`Session`] matching the given filter as finished /// diff --git a/crates/storage/src/queue/job.rs b/crates/storage/src/queue/job.rs index 298d2f758..bc07c3b83 100644 --- a/crates/storage/src/queue/job.rs +++ b/crates/storage/src/queue/job.rs @@ -14,7 +14,7 @@ use tracing_opentelemetry::OpenTelemetrySpanExt; use ulid::Ulid; use super::Worker; -use crate::{repository_impl, Clock}; +use crate::{Clock, repository_impl}; /// Represents a job in the job queue pub struct Job { diff --git a/crates/storage/src/queue/worker.rs b/crates/storage/src/queue/worker.rs index 4916ec1fd..23fa96104 100644 --- a/crates/storage/src/queue/worker.rs +++ b/crates/storage/src/queue/worker.rs @@ -10,7 +10,7 @@ use chrono::Duration; use rand_core::RngCore; use ulid::Ulid; -use crate::{repository_impl, Clock}; +use crate::{Clock, repository_impl}; /// A worker is an entity which can execute jobs. pub struct Worker { diff --git a/crates/storage/src/repository.rs b/crates/storage/src/repository.rs index 4ee86093d..8d1c501ec 100644 --- a/crates/storage/src/repository.rs +++ b/crates/storage/src/repository.rs @@ -123,11 +123,11 @@ pub trait RepositoryAccess: Send { /// Get an [`UserPasswordRepository`] fn user_password<'c>(&'c mut self) - -> Box + 'c>; + -> Box + 'c>; /// Get an [`UserRecoveryRepository`] fn user_recovery<'c>(&'c mut self) - -> Box + 'c>; + -> Box + 'c>; /// Get an [`UserRegistrationRepository`] fn user_registration<'c>( @@ -147,7 +147,7 @@ pub trait RepositoryAccess: Send { /// Get an [`OAuth2ClientRepository`] fn oauth2_client<'c>(&'c mut self) - -> Box + 'c>; + -> Box + 'c>; /// Get an [`OAuth2AuthorizationGrantRepository`] fn oauth2_authorization_grant<'c>( @@ -209,10 +209,11 @@ pub trait RepositoryAccess: Send { /// Implementations of the [`RepositoryAccess`], [`RepositoryTransaction`] and /// [`Repository`] for the [`crate::MapErr`] wrapper and [`Box`] mod impls { - use futures_util::{future::BoxFuture, FutureExt, TryFutureExt}; + use futures_util::{FutureExt, TryFutureExt, future::BoxFuture}; use super::RepositoryAccess; use crate::{ + MapErr, Repository, RepositoryTransaction, app_session::AppSessionRepository, compat::{ CompatAccessTokenRepository, CompatRefreshTokenRepository, CompatSessionRepository, @@ -232,7 +233,6 @@ mod impls { BrowserSessionRepository, UserEmailRepository, UserPasswordRepository, UserRegistrationRepository, UserRepository, UserTermsRepository, }, - MapErr, Repository, RepositoryTransaction, }; // --- Repository --- diff --git a/crates/storage/src/upstream_oauth2/link.rs b/crates/storage/src/upstream_oauth2/link.rs index b281da828..e75959b9a 100644 --- a/crates/storage/src/upstream_oauth2/link.rs +++ b/crates/storage/src/upstream_oauth2/link.rs @@ -9,7 +9,7 @@ use mas_data_model::{UpstreamOAuthLink, UpstreamOAuthProvider, User}; use rand_core::RngCore; use ulid::Ulid; -use crate::{pagination::Page, repository_impl, Clock, Pagination}; +use crate::{Clock, Pagination, pagination::Page, repository_impl}; /// Filter parameters for listing upstream OAuth links #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] diff --git a/crates/storage/src/upstream_oauth2/provider.rs b/crates/storage/src/upstream_oauth2/provider.rs index 3489f9b5c..47a523df4 100644 --- a/crates/storage/src/upstream_oauth2/provider.rs +++ b/crates/storage/src/upstream_oauth2/provider.rs @@ -18,7 +18,7 @@ use rand_core::RngCore; use ulid::Ulid; use url::Url; -use crate::{pagination::Page, repository_impl, Clock, Pagination}; +use crate::{Clock, Pagination, pagination::Page, repository_impl}; /// Structure which holds parameters when inserting or updating an upstream /// OAuth 2.0 provider diff --git a/crates/storage/src/upstream_oauth2/session.rs b/crates/storage/src/upstream_oauth2/session.rs index 827a0f902..d87ee7d3a 100644 --- a/crates/storage/src/upstream_oauth2/session.rs +++ b/crates/storage/src/upstream_oauth2/session.rs @@ -9,7 +9,7 @@ use mas_data_model::{UpstreamOAuthAuthorizationSession, UpstreamOAuthLink, Upstr use rand_core::RngCore; use ulid::Ulid; -use crate::{repository_impl, Clock}; +use crate::{Clock, repository_impl}; /// An [`UpstreamOAuthSessionRepository`] helps interacting with /// [`UpstreamOAuthAuthorizationSession`] saved in the storage backend diff --git a/crates/storage/src/user/email.rs b/crates/storage/src/user/email.rs index 695876a92..b10b7998a 100644 --- a/crates/storage/src/user/email.rs +++ b/crates/storage/src/user/email.rs @@ -12,7 +12,7 @@ use mas_data_model::{ use rand_core::RngCore; use ulid::Ulid; -use crate::{pagination::Page, repository_impl, Clock, Pagination}; +use crate::{Clock, Pagination, pagination::Page, repository_impl}; /// Filter parameters for listing user emails #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] diff --git a/crates/storage/src/user/mod.rs b/crates/storage/src/user/mod.rs index d8d288eb8..0ab559d12 100644 --- a/crates/storage/src/user/mod.rs +++ b/crates/storage/src/user/mod.rs @@ -11,7 +11,7 @@ use mas_data_model::User; use rand_core::RngCore; use ulid::Ulid; -use crate::{repository_impl, Clock, Page, Pagination}; +use crate::{Clock, Page, Pagination, repository_impl}; mod email; mod password; diff --git a/crates/storage/src/user/password.rs b/crates/storage/src/user/password.rs index 5f221743d..fe7115d97 100644 --- a/crates/storage/src/user/password.rs +++ b/crates/storage/src/user/password.rs @@ -8,7 +8,7 @@ use async_trait::async_trait; use mas_data_model::{Password, User}; use rand_core::RngCore; -use crate::{repository_impl, Clock}; +use crate::{Clock, repository_impl}; /// A [`UserPasswordRepository`] helps interacting with [`Password`] saved in /// the storage backend diff --git a/crates/storage/src/user/recovery.rs b/crates/storage/src/user/recovery.rs index b91731cc8..05f2d9333 100644 --- a/crates/storage/src/user/recovery.rs +++ b/crates/storage/src/user/recovery.rs @@ -11,7 +11,7 @@ use mas_data_model::{UserAgent, UserEmail, UserRecoverySession, UserRecoveryTick use rand_core::RngCore; use ulid::Ulid; -use crate::{repository_impl, Clock}; +use crate::{Clock, repository_impl}; /// A [`UserRecoveryRepository`] helps interacting with [`UserRecoverySession`] /// and [`UserRecoveryTicket`] saved in the storage backend diff --git a/crates/storage/src/user/registration.rs b/crates/storage/src/user/registration.rs index f193fa220..8bc4ddcb0 100644 --- a/crates/storage/src/user/registration.rs +++ b/crates/storage/src/user/registration.rs @@ -11,7 +11,7 @@ use rand_core::RngCore; use ulid::Ulid; use url::Url; -use crate::{repository_impl, Clock}; +use crate::{Clock, repository_impl}; /// A [`UserRegistrationRepository`] helps interacting with [`UserRegistration`] /// saved in the storage backend diff --git a/crates/storage/src/user/session.rs b/crates/storage/src/user/session.rs index 491c1da8b..355507530 100644 --- a/crates/storage/src/user/session.rs +++ b/crates/storage/src/user/session.rs @@ -14,7 +14,7 @@ use mas_data_model::{ use rand_core::RngCore; use ulid::Ulid; -use crate::{pagination::Page, repository_impl, Clock, Pagination}; +use crate::{Clock, Pagination, pagination::Page, repository_impl}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum BrowserSessionState { diff --git a/crates/storage/src/user/terms.rs b/crates/storage/src/user/terms.rs index 5813af433..34a6d3a6b 100644 --- a/crates/storage/src/user/terms.rs +++ b/crates/storage/src/user/terms.rs @@ -9,7 +9,7 @@ use mas_data_model::User; use rand_core::RngCore; use url::Url; -use crate::{repository_impl, Clock}; +use crate::{Clock, repository_impl}; /// A [`UserTermsRepository`] helps interacting with the terms of service agreed /// by a [`User`] diff --git a/crates/syn2mas/src/lib.rs b/crates/syn2mas/src/lib.rs index 723ebc869..a7a4b72ca 100644 --- a/crates/syn2mas/src/lib.rs +++ b/crates/syn2mas/src/lib.rs @@ -9,12 +9,13 @@ mod synapse_reader; mod migration; pub use self::{ - mas_writer::{checks::mas_pre_migration_checks, locking::LockedMasDatabase, MasWriter}, + mas_writer::{MasWriter, checks::mas_pre_migration_checks, locking::LockedMasDatabase}, migration::migrate, synapse_reader::{ + SynapseReader, checks::{ synapse_config_check, synapse_config_check_against_mas_config, synapse_database_check, }, - config as synapse_config, SynapseReader, + config as synapse_config, }, }; diff --git a/crates/syn2mas/src/mas_writer/checks.rs b/crates/syn2mas/src/mas_writer/checks.rs index f3e98e57c..64c140bde 100644 --- a/crates/syn2mas/src/mas_writer/checks.rs +++ b/crates/syn2mas/src/mas_writer/checks.rs @@ -11,7 +11,7 @@ use thiserror::Error; use thiserror_ext::ContextInto; -use super::{is_syn2mas_in_progress, locking::LockedMasDatabase, MAS_TABLES_AFFECTED_BY_MIGRATION}; +use super::{MAS_TABLES_AFFECTED_BY_MIGRATION, is_syn2mas_in_progress, locking::LockedMasDatabase}; #[derive(Debug, Error, ContextInto)] pub enum Error { diff --git a/crates/syn2mas/src/mas_writer/locking.rs b/crates/syn2mas/src/mas_writer/locking.rs index 2425ca269..031ca9ac3 100644 --- a/crates/syn2mas/src/mas_writer/locking.rs +++ b/crates/syn2mas/src/mas_writer/locking.rs @@ -6,8 +6,8 @@ use std::sync::LazyLock; use sqlx::{ - postgres::{PgAdvisoryLock, PgAdvisoryLockGuard}, Either, PgConnection, + postgres::{PgAdvisoryLock, PgAdvisoryLockGuard}, }; static SYN2MAS_ADVISORY_LOCK: LazyLock = diff --git a/crates/syn2mas/src/mas_writer/mod.rs b/crates/syn2mas/src/mas_writer/mod.rs index e5260ad4f..a053240f8 100644 --- a/crates/syn2mas/src/mas_writer/mod.rs +++ b/crates/syn2mas/src/mas_writer/mod.rs @@ -10,12 +10,12 @@ use std::{fmt::Display, net::IpAddr}; use chrono::{DateTime, Utc}; -use futures_util::{future::BoxFuture, FutureExt, TryStreamExt}; -use sqlx::{query, query_as, Executor, PgConnection}; +use futures_util::{FutureExt, TryStreamExt, future::BoxFuture}; +use sqlx::{Executor, PgConnection, query, query_as}; use thiserror::Error; use thiserror_ext::{Construct, ContextInto}; use tokio::sync::mpsc::{self, Receiver, Sender}; -use tracing::{error, info, warn, Level}; +use tracing::{Level, error, info, warn}; use uuid::Uuid; use self::{ @@ -175,7 +175,10 @@ impl WriterConnectionPool { } } } - assert_eq!(finished_connections, num_connections, "syn2mas had a bug: connections went missing {finished_connections} != {num_connections}"); + assert_eq!( + finished_connections, num_connections, + "syn2mas had a bug: connections went missing {finished_connections} != {num_connections}" + ); if errors.is_empty() { Ok(()) @@ -1091,12 +1094,12 @@ mod test { use uuid::Uuid; use crate::{ + LockedMasDatabase, MasWriter, mas_writer::{ MasNewCompatAccessToken, MasNewCompatRefreshToken, MasNewCompatSession, MasNewEmailThreepid, MasNewUnsupportedThreepid, MasNewUpstreamOauthLink, MasNewUser, MasNewUserPassword, }, - LockedMasDatabase, MasWriter, }; /// A snapshot of a whole database diff --git a/crates/syn2mas/src/migration.rs b/crates/syn2mas/src/migration.rs index 36dda3a56..4f6b78e0a 100644 --- a/crates/syn2mas/src/migration.rs +++ b/crates/syn2mas/src/migration.rs @@ -25,6 +25,7 @@ use ulid::Ulid; use uuid::Uuid; use crate::{ + SynapseReader, mas_writer::{ self, MasNewCompatAccessToken, MasNewCompatRefreshToken, MasNewCompatSession, MasNewEmailThreepid, MasNewUnsupportedThreepid, MasNewUpstreamOauthLink, MasNewUser, @@ -34,7 +35,6 @@ use crate::{ self, ExtractLocalpartError, FullUserId, SynapseAccessToken, SynapseDevice, SynapseExternalId, SynapseRefreshableTokenPair, SynapseThreepid, SynapseUser, }, - SynapseReader, }; #[derive(Debug, Error, ContextInto)] @@ -56,7 +56,9 @@ pub enum Error { }, #[error("user {user} was not found for migration but a row in {table} was found for them")] MissingUserFromDependentTable { table: String, user: FullUserId }, - #[error("missing a mapping for the auth provider with ID {synapse_id:?} (used by {user} and maybe other users)")] + #[error( + "missing a mapping for the auth provider with ID {synapse_id:?} (used by {user} and maybe other users)" + )] MissingAuthProviderMapping { /// `auth_provider` ID of the provider in Synapse, for which we have no /// mapping diff --git a/crates/syn2mas/src/synapse_reader/checks.rs b/crates/syn2mas/src/synapse_reader/checks.rs index 71d4375b7..b2495f327 100644 --- a/crates/syn2mas/src/synapse_reader/checks.rs +++ b/crates/syn2mas/src/synapse_reader/checks.rs @@ -13,7 +13,7 @@ use mas_config::{ BrandingConfig, CaptchaConfig, ConfigurationSection, ConfigurationSectionExt, MatrixConfig, PasswordAlgorithm, PasswordsConfig, UpstreamOAuth2Config, }; -use sqlx::{prelude::FromRow, query_as, query_scalar, PgConnection}; +use sqlx::{PgConnection, prelude::FromRow, query_as, query_scalar}; use thiserror::Error; use super::config::Config; @@ -38,19 +38,29 @@ pub enum CheckError { #[error("MAS config is missing a password hashing scheme with version '1'")] MissingPasswordScheme, - #[error("Password scheme version '1' in the MAS config must use the Bcrypt algorithm, so that Synapse passwords can be imported and will be compatible.")] + #[error( + "Password scheme version '1' in the MAS config must use the Bcrypt algorithm, so that Synapse passwords can be imported and will be compatible." + )] PasswordSchemeNotBcrypt, - #[error("Password scheme version '1' in the MAS config must have the same secret as the `pepper` value from Synapse, so that Synapse passwords can be imported and will be compatible.")] + #[error( + "Password scheme version '1' in the MAS config must have the same secret as the `pepper` value from Synapse, so that Synapse passwords can be imported and will be compatible." + )] PasswordSchemeWrongPepper, - #[error("Synapse database contains {num_guests} guests which aren't supported by MAS. See https://github.com/element-hq/matrix-authentication-service/issues/1445")] + #[error( + "Synapse database contains {num_guests} guests which aren't supported by MAS. See https://github.com/element-hq/matrix-authentication-service/issues/1445" + )] GuestsInDatabase { num_guests: i64 }, - #[error("Guest support is enabled in the Synapse configuration. Guests aren't supported by MAS, but if you don't have any then you could disable the option. See https://github.com/element-hq/matrix-authentication-service/issues/1445")] + #[error( + "Guest support is enabled in the Synapse configuration. Guests aren't supported by MAS, but if you don't have any then you could disable the option. See https://github.com/element-hq/matrix-authentication-service/issues/1445" + )] GuestsEnabled, - #[error("Synapse database contains {num_non_email_3pids} non-email 3PIDs (probably phone numbers), which are not supported by MAS.")] + #[error( + "Synapse database contains {num_non_email_3pids} non-email 3PIDs (probably phone numbers), which are not supported by MAS." + )] NonEmailThreepidsInDatabase { num_non_email_3pids: i64 }, #[error( @@ -58,16 +68,24 @@ pub enum CheckError { )] ThreepidChangesEnabled, - #[error("Synapse config has `login_via_existing_session.enabled` set to true, which must be disabled.")] + #[error( + "Synapse config has `login_via_existing_session.enabled` set to true, which must be disabled." + )] LoginViaExistingSessionEnabled, - #[error("MAS configuration has the wrong `matrix.homeserver` set ({mas:?}), it should match Synapse's `server_name` ({synapse:?})")] + #[error( + "MAS configuration has the wrong `matrix.homeserver` set ({mas:?}), it should match Synapse's `server_name` ({synapse:?})" + )] ServerNameMismatch { synapse: String, mas: String }, - #[error("Synapse database contains {num_users} users associated to the OpenID Connect or OAuth2 provider '{provider}' but the Synapse configuration does not contain this provider.")] + #[error( + "Synapse database contains {num_users} users associated to the OpenID Connect or OAuth2 provider '{provider}' but the Synapse configuration does not contain this provider." + )] SynapseMissingOAuthProvider { provider: String, num_users: i64 }, - #[error("Synapse config contains an OpenID Connect or OAuth2 provider '{provider}' (issuer: {issuer:?}) used by {num_users} users which must also be configured in the MAS configuration as an upstream provider.")] + #[error( + "Synapse config contains an OpenID Connect or OAuth2 provider '{provider}' (issuer: {issuer:?}) used by {num_users} users which must also be configured in the MAS configuration as an upstream provider." + )] MasMissingOAuthProvider { provider: String, issuer: String, @@ -80,22 +98,32 @@ pub enum CheckError { /// proceeding with the migration. #[derive(Debug, Error)] pub enum CheckWarning { - #[error("Synapse config contains OIDC auth configuration (issuer: {issuer:?}) which will need to be manually mapped to an upstream OpenID Connect Provider during migration.")] + #[error( + "Synapse config contains OIDC auth configuration (issuer: {issuer:?}) which will need to be manually mapped to an upstream OpenID Connect Provider during migration." + )] UpstreamOidcProvider { issuer: String }, - #[error("Synapse config contains {0} auth configuration which will need to be manually mapped as an upstream OAuth 2.0 provider during migration.")] + #[error( + "Synapse config contains {0} auth configuration which will need to be manually mapped as an upstream OAuth 2.0 provider during migration." + )] ExternalAuthSystem(&'static str), - #[error("Synapse config has registration enabled. This must be disabled after migration before bringing Synapse back online.")] + #[error( + "Synapse config has registration enabled. This must be disabled after migration before bringing Synapse back online." + )] DisableRegistrationAfterMigration, #[error("Synapse config has `user_consent` enabled. This should be disabled after migration.")] DisableUserConsentAfterMigration, - #[error("Synapse config has `user_consent` enabled but MAS has not been configured with terms of service. You may wish to set up a `tos_uri` in your MAS branding configuration to replace the user consent.")] + #[error( + "Synapse config has `user_consent` enabled but MAS has not been configured with terms of service. You may wish to set up a `tos_uri` in your MAS branding configuration to replace the user consent." + )] ShouldPortUserConsentAsTerms, - #[error("Synapse config has a registration CAPTCHA enabled, but no CAPTCHA has been configured in MAS. You may wish to manually configure this.")] + #[error( + "Synapse config has a registration CAPTCHA enabled, but no CAPTCHA has been configured in MAS. You may wish to manually configure this." + )] ShouldPortRegistrationCaptcha, } diff --git a/crates/syn2mas/src/synapse_reader/config.rs b/crates/syn2mas/src/synapse_reader/config.rs index 0dca5b6e7..8a542a561 100644 --- a/crates/syn2mas/src/synapse_reader/config.rs +++ b/crates/syn2mas/src/synapse_reader/config.rs @@ -266,12 +266,14 @@ mod test { } // SQLite configs are not accepted - assert!(DatabaseSection { - name: "sqlite3".to_owned(), - args: DatabaseArgsSuboption::default(), - } - .to_sqlx_postgres() - .is_none()); + assert!( + DatabaseSection { + name: "sqlite3".to_owned(), + args: DatabaseArgsSuboption::default(), + } + .to_sqlx_postgres() + .is_none() + ); assert_eq_options( DatabaseSection { diff --git a/crates/syn2mas/src/synapse_reader/mod.rs b/crates/syn2mas/src/synapse_reader/mod.rs index fb145af7c..63e0719b4 100644 --- a/crates/syn2mas/src/synapse_reader/mod.rs +++ b/crates/syn2mas/src/synapse_reader/mod.rs @@ -12,7 +12,7 @@ use std::fmt::Display; use chrono::{DateTime, Utc}; use futures_util::{Stream, TryStreamExt}; -use sqlx::{query, Acquire, FromRow, PgConnection, Postgres, Transaction, Type}; +use sqlx::{Acquire, FromRow, PgConnection, Postgres, Transaction, Type, query}; use thiserror::Error; use thiserror_ext::ContextInto; @@ -474,14 +474,14 @@ mod test { use futures_util::TryStreamExt; use insta::assert_debug_snapshot; - use sqlx::{migrate::Migrator, PgPool}; + use sqlx::{PgPool, migrate::Migrator}; use crate::{ + SynapseReader, synapse_reader::{ SynapseAccessToken, SynapseDevice, SynapseExternalId, SynapseRefreshableTokenPair, SynapseThreepid, SynapseUser, }, - SynapseReader, }; // TODO test me diff --git a/crates/tasks/src/database.rs b/crates/tasks/src/database.rs index 74903fcd1..b68a603b8 100644 --- a/crates/tasks/src/database.rs +++ b/crates/tasks/src/database.rs @@ -11,8 +11,8 @@ use mas_storage::queue::CleanupExpiredTokensJob; use tracing::{debug, info}; use crate::{ - new_queue::{JobContext, JobError, RunnableJob}, State, + new_queue::{JobContext, JobError, RunnableJob}, }; #[async_trait] diff --git a/crates/tasks/src/email.rs b/crates/tasks/src/email.rs index a0e7eaab6..25ab5b7c2 100644 --- a/crates/tasks/src/email.rs +++ b/crates/tasks/src/email.rs @@ -9,12 +9,12 @@ use chrono::Duration; use mas_email::{Address, EmailVerificationContext, Mailbox}; use mas_storage::queue::{SendEmailAuthenticationCodeJob, VerifyEmailJob}; use mas_templates::TemplateContext as _; -use rand::{distributions::Uniform, Rng}; +use rand::{Rng, distributions::Uniform}; use tracing::info; use crate::{ - new_queue::{JobContext, JobError, RunnableJob}, State, + new_queue::{JobContext, JobError, RunnableJob}, }; #[async_trait] diff --git a/crates/tasks/src/matrix.rs b/crates/tasks/src/matrix.rs index a4e831ab4..047666f81 100644 --- a/crates/tasks/src/matrix.rs +++ b/crates/tasks/src/matrix.rs @@ -11,6 +11,7 @@ use async_trait::async_trait; use mas_data_model::Device; use mas_matrix::ProvisionRequest; use mas_storage::{ + Pagination, RepositoryAccess, compat::CompatSessionFilter, oauth2::OAuth2SessionFilter, queue::{ @@ -18,13 +19,12 @@ use mas_storage::{ SyncDevicesJob, }, user::{UserEmailRepository, UserRepository}, - Pagination, RepositoryAccess, }; use tracing::info; use crate::{ - new_queue::{JobContext, JobError, RunnableJob}, State, + new_queue::{JobContext, JobError, RunnableJob}, }; /// Job to provision a user on the Matrix homeserver. diff --git a/crates/tasks/src/new_queue.rs b/crates/tasks/src/new_queue.rs index 4959203e4..6e18144e8 100644 --- a/crates/tasks/src/new_queue.rs +++ b/crates/tasks/src/new_queue.rs @@ -9,20 +9,20 @@ use async_trait::async_trait; use chrono::{DateTime, Duration, Utc}; use cron::Schedule; use mas_storage::{ - queue::{InsertableJob, Job, JobMetadata, Worker}, Clock, RepositoryAccess, RepositoryError, + queue::{InsertableJob, Job, JobMetadata, Worker}, }; use mas_storage_pg::{DatabaseError, PgRepository}; use opentelemetry::{ - metrics::{Counter, Histogram, UpDownCounter}, KeyValue, + metrics::{Counter, Histogram, UpDownCounter}, }; -use rand::{distributions::Uniform, Rng, RngCore}; +use rand::{Rng, RngCore, distributions::Uniform}; use rand_chacha::ChaChaRng; use serde::de::DeserializeOwned; use sqlx::{ - postgres::{PgAdvisoryLock, PgListener}, Acquire, Either, + postgres::{PgAdvisoryLock, PgListener}, }; use thiserror::Error; use tokio::{task::JoinSet, time::Instant}; @@ -31,7 +31,7 @@ use tracing::{Instrument as _, Span}; use tracing_opentelemetry::OpenTelemetrySpanExt as _; use ulid::Ulid; -use crate::{State, METER}; +use crate::{METER, State}; type JobPayload = serde_json::Value; diff --git a/crates/tasks/src/recovery.rs b/crates/tasks/src/recovery.rs index 4a7560ce6..658f1b9f7 100644 --- a/crates/tasks/src/recovery.rs +++ b/crates/tasks/src/recovery.rs @@ -9,17 +9,17 @@ use async_trait::async_trait; use mas_email::{Address, Mailbox}; use mas_i18n::DataLocale; use mas_storage::{ + Pagination, RepositoryAccess, queue::SendAccountRecoveryEmailsJob, user::{UserEmailFilter, UserRecoveryRepository}, - Pagination, RepositoryAccess, }; use mas_templates::{EmailRecoveryContext, TemplateContext}; use rand::distributions::{Alphanumeric, DistString}; use tracing::{error, info}; use crate::{ - new_queue::{JobContext, JobError, RunnableJob}, State, + new_queue::{JobContext, JobError, RunnableJob}, }; /// Job to send account recovery emails for a given recovery session. diff --git a/crates/tasks/src/sessions.rs b/crates/tasks/src/sessions.rs index 677e71b3c..fc7f89796 100644 --- a/crates/tasks/src/sessions.rs +++ b/crates/tasks/src/sessions.rs @@ -18,8 +18,8 @@ use mas_storage::{ }; use crate::{ - new_queue::{JobContext, JobError, RunnableJob}, State, + new_queue::{JobContext, JobError, RunnableJob}, }; #[async_trait] diff --git a/crates/tasks/src/user.rs b/crates/tasks/src/user.rs index eaa9d2b43..9b6893399 100644 --- a/crates/tasks/src/user.rs +++ b/crates/tasks/src/user.rs @@ -7,17 +7,17 @@ use anyhow::Context; use async_trait::async_trait; use mas_storage::{ + RepositoryAccess, compat::CompatSessionFilter, oauth2::OAuth2SessionFilter, queue::{DeactivateUserJob, ReactivateUserJob}, user::{BrowserSessionFilter, UserRepository}, - RepositoryAccess, }; use tracing::info; use crate::{ - new_queue::{JobContext, JobError, RunnableJob}, State, + new_queue::{JobContext, JobError, RunnableJob}, }; /// Job to deactivate a user, both locally and on the Matrix homeserver. diff --git a/crates/templates/src/context.rs b/crates/templates/src/context.rs index 7fcfcf8f6..973a72b35 100644 --- a/crates/templates/src/context.rs +++ b/crates/templates/src/context.rs @@ -28,12 +28,12 @@ use mas_data_model::{ use mas_i18n::DataLocale; use mas_iana::jose::JsonWebSignatureAlg; use mas_router::{Account, GraphQL, PostAuthAction, UrlBuilder}; -use oauth2_types::scope::{Scope, OPENID}; +use oauth2_types::scope::{OPENID, Scope}; use rand::{ - distributions::{Alphanumeric, DistString}, Rng, + distributions::{Alphanumeric, DistString}, }; -use serde::{ser::SerializeStruct, Deserialize, Serialize}; +use serde::{Deserialize, Serialize, ser::SerializeStruct}; use ulid::Ulid; use url::Url; diff --git a/crates/templates/src/context/branding.rs b/crates/templates/src/context/branding.rs index 8a6833548..d9a451c4d 100644 --- a/crates/templates/src/context/branding.rs +++ b/crates/templates/src/context/branding.rs @@ -7,8 +7,8 @@ use std::sync::Arc; use minijinja::{ - value::{Enumerator, Object}, Value, + value::{Enumerator, Object}, }; /// Site branding information. diff --git a/crates/templates/src/context/captcha.rs b/crates/templates/src/context/captcha.rs index ba225dbf3..4e8c9f726 100644 --- a/crates/templates/src/context/captcha.rs +++ b/crates/templates/src/context/captcha.rs @@ -7,8 +7,8 @@ use std::sync::Arc; use minijinja::{ - value::{Enumerator, Object}, Value, + value::{Enumerator, Object}, }; use serde::Serialize; diff --git a/crates/templates/src/context/features.rs b/crates/templates/src/context/features.rs index 13e452811..c9d30095d 100644 --- a/crates/templates/src/context/features.rs +++ b/crates/templates/src/context/features.rs @@ -7,8 +7,8 @@ use std::sync::Arc; use minijinja::{ - value::{Enumerator, Object}, Value, + value::{Enumerator, Object}, }; /// Site features information. diff --git a/crates/templates/src/functions.rs b/crates/templates/src/functions.rs index 713fddcaf..5c2cc8bb4 100644 --- a/crates/templates/src/functions.rs +++ b/crates/templates/src/functions.rs @@ -13,18 +13,17 @@ use std::{ collections::HashMap, fmt::Formatter, str::FromStr, - sync::{atomic::AtomicUsize, Arc}, + sync::{Arc, atomic::AtomicUsize}, }; use camino::Utf8Path; -use mas_i18n::{sprintf::FormattedMessagePart, Argument, ArgumentList, DataLocale, Translator}; +use mas_i18n::{Argument, ArgumentList, DataLocale, Translator, sprintf::FormattedMessagePart}; use mas_router::UrlBuilder; use mas_spa::ViteManifest; use minijinja::{ - escape_formatter, + Error, ErrorKind, State, Value, escape_formatter, machinery::make_string_output, - value::{from_args, Kwargs, Object, ViaDeserialize}, - Error, ErrorKind, State, Value, + value::{Kwargs, Object, ViaDeserialize, from_args}, }; use url::Url; @@ -153,7 +152,7 @@ fn function_add_params_to_url( return Err(Error::new( ErrorKind::InvalidOperation, "Invalid `mode` parameter", - )) + )); } }; diff --git a/crates/tower/src/metrics/duration.rs b/crates/tower/src/metrics/duration.rs index fa876fc70..e0664fb31 100644 --- a/crates/tower/src/metrics/duration.rs +++ b/crates/tower/src/metrics/duration.rs @@ -4,13 +4,13 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use std::{future::Future, time::Instant}; +use std::time::Instant; -use opentelemetry::{metrics::Histogram, KeyValue}; +use opentelemetry::{KeyValue, metrics::Histogram}; use pin_project_lite::pin_project; use tower::{Layer, Service}; -use crate::{utils::FnWrapper, MetricsAttributes, METER}; +use crate::{METER, MetricsAttributes, utils::FnWrapper}; /// A [`Layer`] that records the duration of requests in milliseconds. #[derive(Clone, Debug)] diff --git a/crates/tower/src/metrics/in_flight.rs b/crates/tower/src/metrics/in_flight.rs index 55ebdfe17..8f362c6cb 100644 --- a/crates/tower/src/metrics/in_flight.rs +++ b/crates/tower/src/metrics/in_flight.rs @@ -4,13 +4,11 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use std::future::Future; - -use opentelemetry::{metrics::UpDownCounter, KeyValue}; +use opentelemetry::{KeyValue, metrics::UpDownCounter}; use pin_project_lite::pin_project; use tower::{Layer, Service}; -use crate::{MetricsAttributes, METER}; +use crate::{METER, MetricsAttributes}; /// A [`Layer`] that records the number of in-flight requests. /// diff --git a/crates/tower/src/metrics/make_attributes.rs b/crates/tower/src/metrics/make_attributes.rs index d01b22f07..a6e38378d 100644 --- a/crates/tower/src/metrics/make_attributes.rs +++ b/crates/tower/src/metrics/make_attributes.rs @@ -6,7 +6,7 @@ use opentelemetry::{KeyValue, Value}; -use crate::{utils::KV, FnWrapper}; +use crate::{FnWrapper, utils::KV}; /// Make metrics attributes from a type. pub trait MetricsAttributes { diff --git a/crates/tower/src/metrics/mod.rs b/crates/tower/src/metrics/mod.rs index 0b384a895..da919af01 100644 --- a/crates/tower/src/metrics/mod.rs +++ b/crates/tower/src/metrics/mod.rs @@ -11,5 +11,5 @@ mod make_attributes; pub use self::{ duration::{DurationRecorderFuture, DurationRecorderLayer, DurationRecorderService}, in_flight::{InFlightCounterLayer, InFlightCounterService, InFlightFuture}, - make_attributes::{metrics_attributes_fn, MetricsAttributes}, + make_attributes::{MetricsAttributes, metrics_attributes_fn}, }; diff --git a/crates/tower/src/tracing/future.rs b/crates/tower/src/tracing/future.rs index f116388ef..aeec33f39 100644 --- a/crates/tower/src/tracing/future.rs +++ b/crates/tower/src/tracing/future.rs @@ -4,7 +4,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // Please see LICENSE in the repository root for full details. -use std::{future::Future, task::ready}; +use std::task::ready; use pin_project_lite::pin_project; use tracing::Span; diff --git a/crates/tower/src/tracing/mod.rs b/crates/tower/src/tracing/mod.rs index 8555119d3..bcd34fad8 100644 --- a/crates/tower/src/tracing/mod.rs +++ b/crates/tower/src/tracing/mod.rs @@ -11,9 +11,9 @@ mod make_span; mod service; pub use self::{ - enrich_span::{enrich_span_fn, EnrichSpan}, + enrich_span::{EnrichSpan, enrich_span_fn}, future::TraceFuture, layer::TraceLayer, - make_span::{make_span_fn, MakeSpan}, + make_span::{MakeSpan, make_span_fn}, service::TraceService, };