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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ minijinja = { version = "2.1.2", default-features = false }
parking_lot = { version = "0.12.3", default-features = false, features = ["send_guard", "arc_lock"] }
rand = "^0.10.0"
reqwest = { version = "0.13.1", default-features = false, features = ["rustls", "json"] }
rmcp = { version = "3.1.2", features = ["transport-streamable-http-server"] }
rusqlite = { version = "0.40.0", default-features = false, features = ["bundled", "cache", "column_decltype", "functions", "backup", "preupdate_hook"] }
rust-embed = { version = "8.4.0", default-features = false, features = ["mime-guess"] }
serde = { version = "^1.0.203", features = ["derive", "rc"] }
Expand Down
4 changes: 4 additions & 0 deletions crates/cli/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,10 @@ pub struct ServerArgs {
#[arg(long)]
pub demo: bool,

/// Enable the authenticated MCP endpoint at /mcp on the admin server.
#[arg(long, env, default_value_t = false)]
pub mcp: bool,

#[arg(long, default_value_t = false)]
pub stderr_logging: bool,

Expand Down
1 change: 1 addition & 0 deletions crates/cli/src/bin/trail.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ async fn async_main(
tls_key: None,
tls_cert: None,
custom_router: None,
enable_mcp: cmd.mcp,
},
)
.await?;
Expand Down
1 change: 1 addition & 0 deletions crates/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ quick_cache = "0.7.0"
rand = { workspace = true }
regex = "1.11.0"
reqwest = { workspace = true }
rmcp = { workspace = true }
rusqlite = { workspace = true }
rust-embed = { workspace = true }
serde = { workspace = true }
Expand Down
2 changes: 1 addition & 1 deletion crates/core/src/auth/api/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ pub(crate) async fn build_auth_token_flow_response(
///
/// An example using the two-step "authentication code flow" with PKCE can be found in
/// `/examples/blog/flutter`.
async fn build_authorization_code_flow_and_pkce_response(
pub(crate) async fn build_authorization_code_flow_and_pkce_response(
state: &AppState,
db_user: &DbUser,
redirect: String,
Expand Down
6 changes: 3 additions & 3 deletions crates/core/src/auth/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ pub(super) mod change_email;
pub(super) mod change_password;
pub(super) mod change_username;
pub(super) mod delete;
pub(super) mod login;
pub(crate) mod login;
pub(super) mod login_anonymous;
pub(super) mod logout;
pub(super) mod otp;
pub(super) mod promote_anonymous;
pub(super) mod refresh;
pub(crate) mod refresh;
pub(super) mod register;
pub(super) mod reset_password;
pub(super) mod status;
pub(super) mod token;
pub(crate) mod token;
pub(super) mod totp;
pub(super) mod verify_email;
11 changes: 11 additions & 0 deletions crates/core/src/auth/jwt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,17 @@ impl JwtHelper {
.map(|data| data.claims);
}

pub(crate) fn decode_with_audience<T: DeserializeOwned + Clone>(
&self,
token: &str,
audience: &str,
) -> Result<T, JwtError> {
let mut validation = self.validation.clone();
validation.set_audience(&[audience]);
return jsonwebtoken::decode::<T>(token, &self.decoding_key, &validation)
.map(|data| data.claims);
}

pub fn encode<T: Serialize>(&self, claims: &T) -> Result<String, JwtError> {
return jsonwebtoken::encode::<T>(&self.header, claims, &self.encoding_key);
}
Expand Down
56 changes: 47 additions & 9 deletions crates/core/src/extract/ip.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use axum::extract::ConnectInfo;
use axum::http::Request;
use axum::extract::{ConnectInfo, FromRequestParts};
use axum::http::uri::Authority;
use axum::http::{Extensions, HeaderMap, HeaderValue, Request, request::Parts};
use std::convert::Infallible;
use std::net::IpAddr;
use tower_governor::GovernorError;
use tower_governor::key_extractor::KeyExtractor;

pub fn extract_ip<T>(req: &Request<T>) -> Option<std::net::IpAddr> {
let headers = req.headers();

pub fn extract_ip(headers: &HeaderMap<HeaderValue>, ext: &Extensions) -> Option<std::net::IpAddr> {
// NOTE: This code is mimicking axum_client_ip's pre v1 `InsecureClientIp::from`:
return client_ip::rightmost_x_forwarded_for(headers)
.or_else(|_| client_ip::x_real_ip(headers))
Expand All @@ -16,21 +16,22 @@ pub fn extract_ip<T>(req: &Request<T>) -> Option<std::net::IpAddr> {
.or_else(|_| client_ip::cloudfront_viewer_address(headers))
.ok()
.or_else(|| {
req
.extensions()
ext
.get::<ConnectInfo<std::net::SocketAddr>>()
.map(|ConnectInfo(addr)| addr.ip())
});
}

/// Key extractor for the Governor.
#[derive(Debug, Clone)]
pub struct RealIpKeyExtractor;

impl KeyExtractor for RealIpKeyExtractor {
type Key = IpAddr;

fn extract<T>(&self, req: &Request<T>) -> Result<Self::Key, GovernorError> {
return extract_ip(req).ok_or_else(|| GovernorError::UnableToExtractKey);
return extract_ip(req.headers(), req.extensions())
.ok_or_else(|| GovernorError::UnableToExtractKey);
}

// fn name(&self) -> &'static str {
Expand All @@ -42,8 +43,45 @@ impl KeyExtractor for RealIpKeyExtractor {
// }
}

// RealIp extractor for handlers.
#[derive(Debug, Clone, Default)]
pub struct RealIp(pub Option<std::net::IpAddr>);

impl<S> FromRequestParts<S> for RealIp
where
S: Send + Sync,
{
type Rejection = Infallible;

async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
return Ok(Self(extract_ip(&parts.headers, &parts.extensions)));
}
}

// Host extractor for handlers.
#[derive(Debug, Clone, Default)]
pub struct Host(pub Option<Authority>);

impl<S> FromRequestParts<S> for Host
where
S: Send + Sync,
{
type Rejection = Infallible;

async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let header = parts
.headers
.get("X-Forwarded-Host")
.or_else(|| parts.headers.get("host"));

return Ok(Self(
header.and_then(|h| Authority::try_from(h.as_bytes()).ok()),
));
}
}

#[allow(unused)]
pub fn ipv6_privacy_mask(ip: IpAddr) -> IpAddr {
fn ipv6_privacy_mask(ip: IpAddr) -> IpAddr {
return match ip {
IpAddr::V4(ip) => IpAddr::V4(ip),
IpAddr::V6(ip) => IpAddr::V6(From::from(
Expand Down
1 change: 1 addition & 0 deletions crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ mod encryption;
mod extract;
mod init_error;
mod listing;
mod mcp;
mod migrations;
mod scheduler;
mod schema_metadata;
Expand Down
2 changes: 1 addition & 1 deletion crates/core/src/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ pub(super) fn sqlite_logger_make_span(request: &Request<Body>) -> Span {
uri = %request.uri(),
version = ?request.version(),
host = get_header(headers, "host"),
client_ip = extract_ip(request).map(|ip| ip.to_string()),
client_ip = extract_ip(headers, request.extensions()).map(|ip| ip.to_string()),
user_agent = get_header(headers, "user-agent"),
referer = get_header(headers, "referer"),
// Reserve placeholders that may be recorded later.
Expand Down
Loading
Loading