Add tests for community_inbox and user_inbox

pull/1146/head
Felix Ableitner 2020-09-18 17:45:50 +02:00
parent 9d4973829b
commit db3dcc6fdc
1 changed files with 92 additions and 17 deletions

View File

@ -1,12 +1,15 @@
extern crate lemmy_server; extern crate lemmy_server;
use activitystreams::{ use activitystreams::{
activity::{kind::CreateType, ActorAndObject}, activity::{
kind::{CreateType, FollowType},
ActorAndObject,
},
base::{BaseExt, ExtendsExt}, base::{BaseExt, ExtendsExt},
object::{Note, ObjectExt}, object::{Note, ObjectExt},
}; };
use actix::prelude::*; use actix::prelude::*;
use actix_web::{test::TestRequest, web}; use actix_web::{test::TestRequest, web, web::Path, HttpRequest};
use chrono::Utc; use chrono::Utc;
use diesel::{ use diesel::{
r2d2::{ConnectionManager, Pool}, r2d2::{ConnectionManager, Pool},
@ -14,6 +17,7 @@ use diesel::{
}; };
use http_signature_normalization_actix::PrepareVerifyError; use http_signature_normalization_actix::PrepareVerifyError;
use lemmy_db::{ use lemmy_db::{
community::{Community, CommunityForm},
user::{User_, *}, user::{User_, *},
Crud, Crud,
ListingType, ListingType,
@ -23,13 +27,21 @@ use lemmy_rate_limit::{rate_limiter::RateLimiter, RateLimit};
use lemmy_server::{ use lemmy_server::{
apub::{ apub::{
activity_queue::create_activity_queue, activity_queue::create_activity_queue,
inbox::shared_inbox::{shared_inbox, ValidTypes}, inbox::{
community_inbox,
community_inbox::community_inbox,
shared_inbox,
shared_inbox::shared_inbox,
user_inbox,
user_inbox::user_inbox,
},
}, },
websocket::chat_server::ChatServer, websocket::chat_server::ChatServer,
LemmyContext, LemmyContext,
}; };
use lemmy_utils::{apub::generate_actor_keypair, settings::Settings}; use lemmy_utils::{apub::generate_actor_keypair, settings::Settings};
use reqwest::Client; use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::sync::Arc; use std::sync::Arc;
use tokio::sync::Mutex; use tokio::sync::Mutex;
use url::Url; use url::Url;
@ -61,10 +73,10 @@ fn create_context() -> LemmyContext {
) )
} }
fn create_user(conn: &PgConnection) -> User_ { fn create_user(conn: &PgConnection, name: &str) -> User_ {
let user_keypair = generate_actor_keypair().unwrap(); let user_keypair = generate_actor_keypair().unwrap();
let new_user = UserForm { let new_user = UserForm {
name: "integration_user_1".into(), name: name.into(),
preferred_username: None, preferred_username: None,
password_encrypted: "nope".into(), password_encrypted: "nope".into(),
email: None, email: None,
@ -81,7 +93,7 @@ fn create_user(conn: &PgConnection) -> User_ {
lang: "browser".into(), lang: "browser".into(),
show_avatars: true, show_avatars: true,
send_notifications_to_email: false, send_notifications_to_email: false,
actor_id: Some("http://localhost:8536/u/integration_user_1".to_string()), actor_id: Some(format!("http://localhost:8536/u/{}", name).to_string()),
bio: None, bio: None,
local: true, local: true,
private_key: Some(user_keypair.private_key), private_key: Some(user_keypair.private_key),
@ -92,35 +104,98 @@ fn create_user(conn: &PgConnection) -> User_ {
User_::create(&conn, &new_user).unwrap() User_::create(&conn, &new_user).unwrap()
} }
fn create_activity(user_id: String) -> web::Json<ActorAndObject<ValidTypes>> { fn create_community(conn: &PgConnection, creator_id: i32) -> Community {
let mut activity = let new_community = CommunityForm {
ActorAndObject::<CreateType>::new(user_id, Note::new().into_any_base().unwrap()); name: "test_community".into(),
creator_id,
title: "test_community".to_owned(),
description: None,
category_id: 1,
nsfw: false,
removed: None,
deleted: None,
updated: None,
actor_id: None,
local: true,
private_key: None,
public_key: None,
last_refreshed_at: None,
published: None,
icon: None,
banner: None,
};
Community::create(&conn, &new_community).unwrap()
}
fn create_activity<'a, Activity, Return>(user_id: String) -> web::Json<Return>
where
for<'de> Return: Deserialize<'de> + 'a,
Activity: std::default::Default + Serialize,
{
let mut activity = ActorAndObject::<Activity>::new(user_id, Note::new().into_any_base().unwrap());
activity activity
.set_id(Url::parse("http://localhost:8536/create/1").unwrap()) .set_id(Url::parse("http://localhost:8536/create/1").unwrap())
.set_many_ccs(vec![Url::parse("http://localhost:8536/c/main").unwrap()]); .set_many_ccs(vec![Url::parse("http://localhost:8536/c/main").unwrap()]);
let activity = serde_json::to_value(&activity).unwrap(); let activity = serde_json::to_value(&activity).unwrap();
let activity: ActorAndObject<ValidTypes> = serde_json::from_value(activity).unwrap(); let activity: Return = serde_json::from_value(activity).unwrap();
web::Json(activity) web::Json(activity)
} }
#[actix_rt::test] fn create_http_request() -> HttpRequest {
async fn test_expired_signature() {
let time1 = Utc::now().timestamp(); let time1 = Utc::now().timestamp();
let time2 = Utc::now().timestamp(); let time2 = Utc::now().timestamp();
let signature = format!( let signature = format!(
r#"keyId="my-key-id",algorithm="hs2019",created="{}",expires="{}",headers="(request-target) (created) (expires) date content-type",signature="blah blah blah""#, r#"keyId="my-key-id",algorithm="hs2019",created="{}",expires="{}",headers="(request-target) (created) (expires) date content-type",signature="blah blah blah""#,
time1, time2 time1, time2
); );
let request = TestRequest::post() TestRequest::post()
.uri("http://localhost:8536/inbox") .uri("http://localhost:8536/")
.header("Signature", signature) .header("Signature", signature)
.to_http_request(); .to_http_request()
}
#[actix_rt::test]
async fn test_shared_inbox_expired_signature() {
let request = create_http_request();
let context = create_context(); let context = create_context();
let user = create_user(&context.pool().get().unwrap()); let user = create_user(&context.pool().get().unwrap(), "shared_inbox_rvgfd");
let activity = create_activity(user.actor_id); let activity =
create_activity::<CreateType, ActorAndObject<shared_inbox::ValidTypes>>(user.actor_id);
let response = shared_inbox(request, activity, web::Data::new(context)).await; let response = shared_inbox(request, activity, web::Data::new(context)).await;
assert_eq!( assert_eq!(
format!("{}", response.err().unwrap()), format!("{}", response.err().unwrap()),
format!("{}", PrepareVerifyError::Expired) format!("{}", PrepareVerifyError::Expired)
); );
} }
#[actix_rt::test]
async fn test_user_inbox_expired_signature() {
let request = create_http_request();
let context = create_context();
let user = create_user(&context.pool().get().unwrap(), "user_inbox_cgsax");
let activity =
create_activity::<CreateType, ActorAndObject<user_inbox::ValidTypes>>(user.actor_id);
let path = Path::<String> {
0: "username".to_string(),
};
let response = user_inbox(request, activity, path, web::Data::new(context)).await;
assert_eq!(
format!("{}", response.err().unwrap()),
format!("{}", PrepareVerifyError::Expired)
);
}
#[actix_rt::test]
async fn test_community_inbox_expired_signature() {
let context = create_context();
let user = create_user(&context.pool().get().unwrap(), "community_inbox_hrxa");
let community = create_community(&context.pool().get().unwrap(), user.id);
let request = create_http_request();
let activity =
create_activity::<FollowType, ActorAndObject<community_inbox::ValidTypes>>(user.actor_id);
let path = Path::<String> { 0: community.name };
let response = community_inbox(request, activity, path, web::Data::new(context)).await;
assert_eq!(
format!("{}", response.err().unwrap()),
format!("{}", PrepareVerifyError::Expired)
);
}