feat: Implement WebFinger discovery and ActivityPub user actor endpoint
- Added a new router for handling well-known endpoints, specifically WebFinger. - Implemented the `webfinger` function to respond to WebFinger queries. - Created a new route for WebFinger in the router. - Refactored user retrieval logic to support both user ID and username in a single endpoint. - Updated user router to use the new `get_user_by_param` function. - Added tests for WebFinger discovery and ActivityPub user actor endpoint. - Updated dependencies in Cargo.toml files to include necessary libraries.
This commit is contained in:
726
thoughts-backend/Cargo.lock
generated
726
thoughts-backend/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -19,7 +19,7 @@ axum = { version = "0.8.4", default-features = false }
|
|||||||
sea-orm = { version = "1.1.12" }
|
sea-orm = { version = "1.1.12" }
|
||||||
sea-query = { version = "0.32.6" } # Added sea-query dependency
|
sea-query = { version = "0.32.6" } # Added sea-query dependency
|
||||||
serde = { version = "1.0.219", features = ["derive"] }
|
serde = { version = "1.0.219", features = ["derive"] }
|
||||||
serde_json = { version = "1.0.140" }
|
serde_json = { version = "1.0.140", features = ["raw_value"] }
|
||||||
tracing = "0.1.41"
|
tracing = "0.1.41"
|
||||||
utoipa = { version = "5.4.0", features = ["macros", "chrono"] }
|
utoipa = { version = "5.4.0", features = ["macros", "chrono"] }
|
||||||
validator = { version = "0.20.0", default-features = false }
|
validator = { version = "0.20.0", default-features = false }
|
||||||
|
@@ -22,6 +22,8 @@ tower-http = { version = "0.6.6", features = ["fs", "cors"] }
|
|||||||
tower-cookies = "0.11.0"
|
tower-cookies = "0.11.0"
|
||||||
anyhow = "1.0.98"
|
anyhow = "1.0.98"
|
||||||
dotenvy = "0.15.7"
|
dotenvy = "0.15.7"
|
||||||
|
activitypub_federation = "0.6.5"
|
||||||
|
url = "2.5.7"
|
||||||
|
|
||||||
# db
|
# db
|
||||||
sea-orm = { workspace = true }
|
sea-orm = { workspace = true }
|
||||||
@@ -29,8 +31,11 @@ sea-orm = { workspace = true }
|
|||||||
# doc
|
# doc
|
||||||
utoipa = { workspace = true }
|
utoipa = { workspace = true }
|
||||||
|
|
||||||
|
serde_json = { workspace = true }
|
||||||
|
|
||||||
# local dependencies
|
# local dependencies
|
||||||
app = { path = "../app" }
|
app = { path = "../app" }
|
||||||
models = { path = "../models" }
|
models = { path = "../models" }
|
||||||
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
@@ -5,8 +5,9 @@ pub mod feed;
|
|||||||
pub mod root;
|
pub mod root;
|
||||||
pub mod thought;
|
pub mod thought;
|
||||||
pub mod user;
|
pub mod user;
|
||||||
|
pub mod well_known;
|
||||||
|
|
||||||
use crate::routers::auth::create_auth_router;
|
use crate::routers::{auth::create_auth_router, well_known::create_well_known_router};
|
||||||
use app::state::AppState;
|
use app::state::AppState;
|
||||||
use root::create_root_router;
|
use root::create_root_router;
|
||||||
use tower_http::cors::CorsLayer;
|
use tower_http::cors::CorsLayer;
|
||||||
@@ -19,6 +20,7 @@ pub fn create_router(state: AppState) -> Router {
|
|||||||
|
|
||||||
Router::new()
|
Router::new()
|
||||||
.merge(create_root_router())
|
.merge(create_root_router())
|
||||||
|
.nest("/.well-known", create_well_known_router())
|
||||||
.nest("/auth", create_auth_router())
|
.nest("/auth", create_auth_router())
|
||||||
.nest("/users", create_user_router())
|
.nest("/users", create_user_router())
|
||||||
.nest("/thoughts", create_thought_router())
|
.nest("/thoughts", create_thought_router())
|
||||||
|
@@ -1,10 +1,11 @@
|
|||||||
use axum::{
|
use axum::{
|
||||||
extract::{Path, Query, State},
|
extract::{Path, Query, State},
|
||||||
http::StatusCode,
|
http::StatusCode,
|
||||||
response::IntoResponse,
|
response::{IntoResponse, Response},
|
||||||
routing::{get, post},
|
routing::{get, post},
|
||||||
Router,
|
Router,
|
||||||
};
|
};
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
use app::persistence::{
|
use app::persistence::{
|
||||||
follow,
|
follow,
|
||||||
@@ -44,28 +45,6 @@ async fn users_get(
|
|||||||
Ok(Json(UserListSchema::from(users)))
|
Ok(Json(UserListSchema::from(users)))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[utoipa::path(
|
|
||||||
get,
|
|
||||||
path = "/{id}",
|
|
||||||
params(
|
|
||||||
("id" = i32, Path, description = "User id")
|
|
||||||
),
|
|
||||||
responses(
|
|
||||||
(status = 200, description = "Get user", body = UserSchema),
|
|
||||||
(status = 404, description = "Not found", body = ApiErrorResponse),
|
|
||||||
(status = 500, description = "Internal server error", body = ApiErrorResponse),
|
|
||||||
)
|
|
||||||
)]
|
|
||||||
async fn users_id_get(
|
|
||||||
state: State<AppState>,
|
|
||||||
Path(id): Path<i32>,
|
|
||||||
) -> Result<impl IntoResponse, ApiError> {
|
|
||||||
let user = get_user(&state.conn, id).await.map_err(ApiError::from)?;
|
|
||||||
|
|
||||||
user.map(|user| Json(UserSchema::from(user)))
|
|
||||||
.ok_or_else(|| UserError::NotFound.into())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[utoipa::path(
|
#[utoipa::path(
|
||||||
get,
|
get,
|
||||||
path = "/{username}/thoughts",
|
path = "/{username}/thoughts",
|
||||||
@@ -165,10 +144,84 @@ async fn user_follow_delete(
|
|||||||
Ok(StatusCode::NO_CONTENT)
|
Ok(StatusCode::NO_CONTENT)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/{param}",
|
||||||
|
params(
|
||||||
|
("param" = String, Path, description = "User ID or username")
|
||||||
|
),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "User profile or ActivityPub actor", body = UserSchema, content_type = "application/json"),
|
||||||
|
(status = 200, description = "ActivityPub actor", body = Object, content_type = "application/activity+json"),
|
||||||
|
(status = 404, description = "User not found", body = ApiErrorResponse),
|
||||||
|
(status = 500, description = "Internal server error", body = ApiErrorResponse),
|
||||||
|
),
|
||||||
|
security(
|
||||||
|
("api_key" = []),
|
||||||
|
("bearer_auth" = [])
|
||||||
|
)
|
||||||
|
)]
|
||||||
|
async fn get_user_by_param(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
headers: axum::http::HeaderMap,
|
||||||
|
Path(param): Path<String>,
|
||||||
|
) -> Response {
|
||||||
|
// First, try to handle it as a numeric ID.
|
||||||
|
if let Ok(id) = param.parse::<i32>() {
|
||||||
|
return match get_user(&state.conn, id).await {
|
||||||
|
Ok(Some(user)) => Json(UserSchema::from(user)).into_response(),
|
||||||
|
Ok(None) => ApiError::from(UserError::NotFound).into_response(),
|
||||||
|
Err(db_err) => ApiError::from(db_err).into_response(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// If it's not a number, treat it as a username and perform content negotiation.
|
||||||
|
let username = param;
|
||||||
|
let is_activitypub_request = headers
|
||||||
|
.get(axum::http::header::ACCEPT)
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.map_or(false, |s| s.contains("application/activity+json"));
|
||||||
|
|
||||||
|
if is_activitypub_request {
|
||||||
|
// This is the logic from `user_actor_get`.
|
||||||
|
match get_user_by_username(&state.conn, &username).await {
|
||||||
|
Ok(Some(user)) => {
|
||||||
|
let base_url = "http://localhost:3000";
|
||||||
|
let user_url = format!("{}/users/{}", base_url, user.username);
|
||||||
|
let actor = json!({
|
||||||
|
"@context": [
|
||||||
|
"https://www.w3.org/ns/activitystreams",
|
||||||
|
"https://w3id.org/security/v1"
|
||||||
|
],
|
||||||
|
"id": user_url,
|
||||||
|
"type": "Person",
|
||||||
|
"preferredUsername": user.username,
|
||||||
|
"inbox": format!("{}/inbox", user_url),
|
||||||
|
"outbox": format!("{}/outbox", user_url),
|
||||||
|
});
|
||||||
|
let mut headers = axum::http::HeaderMap::new();
|
||||||
|
headers.insert(
|
||||||
|
axum::http::header::CONTENT_TYPE,
|
||||||
|
"application/activity+json".parse().unwrap(),
|
||||||
|
);
|
||||||
|
(headers, Json(actor)).into_response()
|
||||||
|
}
|
||||||
|
Ok(None) => ApiError::from(UserError::NotFound).into_response(),
|
||||||
|
Err(e) => ApiError::from(e).into_response(),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
match get_user_by_username(&state.conn, &username).await {
|
||||||
|
Ok(Some(user)) => Json(UserSchema::from(user)).into_response(),
|
||||||
|
Ok(None) => ApiError::from(UserError::NotFound).into_response(),
|
||||||
|
Err(e) => ApiError::from(e).into_response(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn create_user_router() -> Router<AppState> {
|
pub fn create_user_router() -> Router<AppState> {
|
||||||
Router::new()
|
Router::new()
|
||||||
.route("/", get(users_get))
|
.route("/", get(users_get))
|
||||||
.route("/{id}", get(users_id_get))
|
.route("/{param}", get(get_user_by_param))
|
||||||
.route("/{username}/thoughts", get(user_thoughts_get))
|
.route("/{username}/thoughts", get(user_thoughts_get))
|
||||||
.route(
|
.route(
|
||||||
"/{username}/follow",
|
"/{username}/follow",
|
||||||
|
71
thoughts-backend/api/src/routers/well_known.rs
Normal file
71
thoughts-backend/api/src/routers/well_known.rs
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
use app::state::AppState;
|
||||||
|
use axum::{
|
||||||
|
extract::{Query, State},
|
||||||
|
response::{IntoResponse, Json},
|
||||||
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct WebFingerQuery {
|
||||||
|
resource: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct WebFingerLink {
|
||||||
|
rel: String,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
type_: String,
|
||||||
|
href: Url,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct WebFingerResponse {
|
||||||
|
subject: String,
|
||||||
|
links: Vec<WebFingerLink>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn webfinger(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Query(query): Query<WebFingerQuery>,
|
||||||
|
) -> Result<impl IntoResponse, impl IntoResponse> {
|
||||||
|
if let Some((scheme, account_info)) = query.resource.split_once(':') {
|
||||||
|
if scheme != "acct" {
|
||||||
|
return Err((
|
||||||
|
axum::http::StatusCode::BAD_REQUEST,
|
||||||
|
"Invalid resource scheme",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let account_parts: Vec<&str> = account_info.split('@').collect();
|
||||||
|
let username = account_parts[0];
|
||||||
|
|
||||||
|
let user = match app::persistence::user::get_user_by_username(&state.conn, username).await {
|
||||||
|
Ok(Some(user)) => user,
|
||||||
|
_ => return Err((axum::http::StatusCode::NOT_FOUND, "User not found")),
|
||||||
|
};
|
||||||
|
|
||||||
|
let base_url = "http://localhost:3000";
|
||||||
|
let user_url = Url::parse(&format!("{}/users/{}", base_url, user.username)).unwrap();
|
||||||
|
|
||||||
|
let response = WebFingerResponse {
|
||||||
|
subject: query.resource,
|
||||||
|
links: vec![WebFingerLink {
|
||||||
|
rel: "self".to_string(),
|
||||||
|
type_: "application/activity+json".to_string(),
|
||||||
|
href: user_url,
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(Json(response))
|
||||||
|
} else {
|
||||||
|
Err((
|
||||||
|
axum::http::StatusCode::BAD_REQUEST,
|
||||||
|
"Invalid resource format",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_well_known_router() -> axum::Router<AppState> {
|
||||||
|
axum::Router::new().route("/webfinger", axum::routing::get(webfinger))
|
||||||
|
}
|
@@ -12,7 +12,7 @@ use models::schemas::{
|
|||||||
#[openapi(
|
#[openapi(
|
||||||
paths(
|
paths(
|
||||||
users_get,
|
users_get,
|
||||||
users_id_get,
|
get_user_by_param,
|
||||||
user_thoughts_get,
|
user_thoughts_get,
|
||||||
user_follow_post,
|
user_follow_post,
|
||||||
user_follow_delete
|
user_follow_delete
|
||||||
|
59
thoughts-backend/tests/api/activitypub.rs
Normal file
59
thoughts-backend/tests/api/activitypub.rs
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
use crate::api::main::{create_user_with_password, setup};
|
||||||
|
use axum::http::{header, StatusCode};
|
||||||
|
use http_body_util::BodyExt;
|
||||||
|
use serde_json::Value;
|
||||||
|
use utils::testing::{make_get_request, make_request_with_headers};
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_webfinger_discovery() {
|
||||||
|
let app = setup().await;
|
||||||
|
create_user_with_password(&app.db, "testuser", "password123").await;
|
||||||
|
|
||||||
|
// 1. Valid WebFinger lookup for existing user
|
||||||
|
let url = "/.well-known/webfinger?resource=acct:testuser@localhost:3000";
|
||||||
|
let response = make_get_request(app.router.clone(), url, None).await;
|
||||||
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
|
let body = response.into_body().collect().await.unwrap().to_bytes();
|
||||||
|
let v: Value = serde_json::from_slice(&body).unwrap();
|
||||||
|
assert_eq!(v["subject"], "acct:testuser@localhost:3000");
|
||||||
|
assert_eq!(
|
||||||
|
v["links"][0]["href"],
|
||||||
|
"http://localhost:3000/users/testuser"
|
||||||
|
);
|
||||||
|
|
||||||
|
// 2. WebFinger lookup for a non-existent user
|
||||||
|
let response = make_get_request(
|
||||||
|
app.router.clone(),
|
||||||
|
"/.well-known/webfinger?resource=acct:nobody@localhost:3000",
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(response.status(), StatusCode::NOT_FOUND);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_user_actor_endpoint() {
|
||||||
|
let app = setup().await;
|
||||||
|
create_user_with_password(&app.db, "testuser", "password123").await;
|
||||||
|
|
||||||
|
let response = make_request_with_headers(
|
||||||
|
app.router.clone(),
|
||||||
|
"/users/testuser",
|
||||||
|
"GET",
|
||||||
|
None,
|
||||||
|
vec![(
|
||||||
|
header::ACCEPT,
|
||||||
|
"application/activity+json, application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"",
|
||||||
|
)],
|
||||||
|
).await;
|
||||||
|
|
||||||
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
|
let content_type = response.headers().get(header::CONTENT_TYPE).unwrap();
|
||||||
|
assert_eq!(content_type, "application/activity+json");
|
||||||
|
|
||||||
|
let body = response.into_body().collect().await.unwrap().to_bytes();
|
||||||
|
let v: Value = serde_json::from_slice(&body).unwrap();
|
||||||
|
assert_eq!(v["type"], "Person");
|
||||||
|
assert_eq!(v["preferredUsername"], "testuser");
|
||||||
|
assert_eq!(v["id"], "http://localhost:3000/users/testuser");
|
||||||
|
}
|
@@ -1,3 +1,4 @@
|
|||||||
|
mod activitypub;
|
||||||
mod auth;
|
mod auth;
|
||||||
mod feed;
|
mod feed;
|
||||||
mod follow;
|
mod follow;
|
||||||
|
@@ -1,4 +1,9 @@
|
|||||||
use axum::{body::Body, http::Request, response::Response, Router};
|
use axum::{
|
||||||
|
body::Body,
|
||||||
|
http::{header, Request},
|
||||||
|
response::Response,
|
||||||
|
Router,
|
||||||
|
};
|
||||||
use tower::ServiceExt;
|
use tower::ServiceExt;
|
||||||
|
|
||||||
pub async fn make_get_request(app: Router, url: &str, user_id: Option<i32>) -> Response {
|
pub async fn make_get_request(app: Router, url: &str, user_id: Option<i32>) -> Response {
|
||||||
@@ -68,3 +73,25 @@ pub async fn make_jwt_request(
|
|||||||
.await
|
.await
|
||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn make_request_with_headers(
|
||||||
|
app: Router,
|
||||||
|
url: &str,
|
||||||
|
method: &str,
|
||||||
|
body: Option<String>,
|
||||||
|
headers: Vec<(header::HeaderName, &str)>,
|
||||||
|
) -> Response {
|
||||||
|
let mut builder = Request::builder()
|
||||||
|
.method(method)
|
||||||
|
.uri(url)
|
||||||
|
.header("Content-Type", "application/json");
|
||||||
|
|
||||||
|
for (key, value) in headers {
|
||||||
|
builder = builder.header(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
let request_body = body.unwrap_or_default();
|
||||||
|
app.oneshot(builder.body(Body::from(request_body)).unwrap())
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
@@ -1,5 +1,8 @@
|
|||||||
mod api;
|
mod api;
|
||||||
mod db;
|
mod db;
|
||||||
|
|
||||||
pub use api::{make_delete_request, make_get_request, make_jwt_request, make_post_request};
|
pub use api::{
|
||||||
|
make_delete_request, make_get_request, make_jwt_request, make_post_request,
|
||||||
|
make_request_with_headers,
|
||||||
|
};
|
||||||
pub use db::setup_test_db;
|
pub use db::setup_test_db;
|
||||||
|
Reference in New Issue
Block a user