Analytics permissions (#761)

* adds test; permissions fix

* clippy

---------

Co-authored-by: Geometrically <18202329+Geometrically@users.noreply.github.com>
This commit is contained in:
Wyatt Verchere
2023-11-21 09:02:07 -08:00
committed by GitHub
parent dfba6c7c91
commit 79e634316d
4 changed files with 301 additions and 25 deletions

View File

@@ -1,8 +1,11 @@
use actix_web::test;
use chrono::{DateTime, Duration, Utc};
use common::database::*;
use common::environment::TestEnvironment;
use common::permissions::PermissionsTest;
use common::{database::*, permissions::PermissionsTestContext};
use itertools::Itertools;
use labrinth::models::ids::base62_impl::parse_base62;
use labrinth::models::teams::ProjectPermissions;
use rust_decimal::{prelude::ToPrimitive, Decimal};
mod common;
@@ -70,6 +73,7 @@ pub async fn analytics_revenue() {
let analytics = api
.get_analytics_revenue_deserialized(
vec![&alpha_project_id],
false,
None,
None,
None,
@@ -99,6 +103,7 @@ pub async fn analytics_revenue() {
let analytics = api
.get_analytics_revenue_deserialized(
vec![&alpha_project_id],
false,
Some(Utc::now() - Duration::days(801)),
None,
None,
@@ -133,3 +138,92 @@ fn to_f64_rounded_up(d: Decimal) -> f64 {
fn to_f64_vec_rounded_up(d: Vec<Decimal>) -> Vec<f64> {
d.into_iter().map(to_f64_rounded_up).collect_vec()
}
#[actix_rt::test]
pub async fn permissions_analytics_revenue() {
let test_env = TestEnvironment::build(None).await;
let alpha_project_id = test_env
.dummy
.as_ref()
.unwrap()
.project_alpha
.project_id
.clone();
let alpha_version_id = test_env
.dummy
.as_ref()
.unwrap()
.project_alpha
.version_id
.clone();
let alpha_team_id = test_env
.dummy
.as_ref()
.unwrap()
.project_alpha
.team_id
.clone();
let view_analytics = ProjectPermissions::VIEW_ANALYTICS;
// first, do check with a project
let req_gen = |ctx: &PermissionsTestContext| {
let projects_string = serde_json::to_string(&vec![ctx.project_id]).unwrap();
let projects_string = urlencoding::encode(&projects_string);
test::TestRequest::get().uri(&format!(
"/v3/analytics/revenue?project_ids={projects_string}&resolution_minutes=5",
))
};
PermissionsTest::new(&test_env)
.with_failure_codes(vec![200, 401])
.with_200_json_checks(
// On failure, should have 0 projects returned
|value: &serde_json::Value| {
let value = value.as_object().unwrap();
assert_eq!(value.len(), 0);
},
// On success, should have 1 project returned
|value: &serde_json::Value| {
let value = value.as_object().unwrap();
assert_eq!(value.len(), 1);
},
)
.simple_project_permissions_test(view_analytics, req_gen)
.await
.unwrap();
// Now with a version
// Need to use alpha
let req_gen = |_: &PermissionsTestContext| {
let versions_string = serde_json::to_string(&vec![alpha_version_id.clone()]).unwrap();
let versions_string = urlencoding::encode(&versions_string);
test::TestRequest::get().uri(&format!(
"/v3/analytics/revenue?version_ids={versions_string}&resolution_minutes=5",
))
};
PermissionsTest::new(&test_env)
.with_failure_codes(vec![200, 401])
.with_existing_project(&alpha_project_id, &alpha_team_id)
.with_user(FRIEND_USER_ID, FRIEND_USER_PAT, true)
.with_200_json_checks(
// On failure, should have 0 versions returned
|value: &serde_json::Value| {
let value = value.as_object().unwrap();
assert_eq!(value.len(), 0);
},
// On success, should have 1 versions returned
|value: &serde_json::Value| {
let value = value.as_object().unwrap();
assert_eq!(value.len(), 1);
},
)
.simple_project_permissions_test(view_analytics, req_gen)
.await
.unwrap();
// Cleanup test db
test_env.cleanup().await;
}

View File

@@ -204,13 +204,21 @@ impl ApiV3 {
pub async fn get_analytics_revenue(
&self,
id_or_slugs: Vec<&str>,
ids_are_version_ids: bool,
start_date: Option<DateTime<Utc>>,
end_date: Option<DateTime<Utc>>,
resolution_minutes: Option<u32>,
pat: &str,
) -> ServiceResponse {
let projects_string = serde_json::to_string(&id_or_slugs).unwrap();
let projects_string = urlencoding::encode(&projects_string);
let pv_string = if ids_are_version_ids {
let version_string: String = serde_json::to_string(&id_or_slugs).unwrap();
let version_string = urlencoding::encode(&version_string);
format!("version_ids={}", version_string)
} else {
let projects_string: String = serde_json::to_string(&id_or_slugs).unwrap();
let projects_string = urlencoding::encode(&projects_string);
format!("project_ids={}", projects_string)
};
let mut extra_args = String::new();
if let Some(start_date) = start_date {
@@ -230,9 +238,7 @@ impl ApiV3 {
}
let req = test::TestRequest::get()
.uri(&format!(
"/v3/analytics/revenue?{projects_string}{extra_args}",
))
.uri(&format!("/v3/analytics/revenue?{pv_string}{extra_args}",))
.append_header(("Authorization", pat))
.to_request();
@@ -242,13 +248,21 @@ impl ApiV3 {
pub async fn get_analytics_revenue_deserialized(
&self,
id_or_slugs: Vec<&str>,
ids_are_version_ids: bool,
start_date: Option<DateTime<Utc>>,
end_date: Option<DateTime<Utc>>,
resolution_minutes: Option<u32>,
pat: &str,
) -> HashMap<String, HashMap<i64, Decimal>> {
let resp = self
.get_analytics_revenue(id_or_slugs, start_date, end_date, resolution_minutes, pat)
.get_analytics_revenue(
id_or_slugs,
ids_are_version_ids,
start_date,
end_date,
resolution_minutes,
pat,
)
.await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await

View File

@@ -1,4 +1,5 @@
#![allow(dead_code)]
use actix_http::StatusCode;
use actix_web::test::{self, TestRequest};
use itertools::Itertools;
use labrinth::models::teams::{OrganizationPermissions, ProjectPermissions};
@@ -45,6 +46,12 @@ pub struct PermissionsTest<'a> {
// The codes that is allow to be returned if the scope is not present.
// (for instance, we might expect a 401, but not a 400)
allowed_failure_codes: Vec<u16>,
// Closures that check the JSON body of the response for failure and success cases.
// These are used to perform more complex tests than just checking the status code.
// (eg: checking that the response contains the correct data)
failure_json_check: Option<Box<dyn Fn(&serde_json::Value) + Send>>,
success_json_check: Option<Box<dyn Fn(&serde_json::Value) + Send>>,
}
pub struct PermissionsTestContext<'a> {
@@ -71,6 +78,8 @@ impl<'a> PermissionsTest<'a> {
project_team_id: None,
organization_team_id: None,
allowed_failure_codes: vec![401, 404],
failure_json_check: None,
success_json_check: None,
}
}
@@ -87,6 +96,20 @@ impl<'a> PermissionsTest<'a> {
self
}
// Set check closures for the JSON body of the response
// These are used to perform more complex tests than just checking the status code.
// If not set, no checks will be performed (and the status code is the only check).
// This is useful if, say, both expected status codes are 200.
pub fn with_200_json_checks(
mut self,
failure_json_check: impl Fn(&serde_json::Value) + Send + 'static,
success_json_check: impl Fn(&serde_json::Value) + Send + 'static,
) -> Self {
self.failure_json_check = Some(Box::new(failure_json_check));
self.success_json_check = Some(Box::new(success_json_check));
self
}
// Set the user ID to use
// (eg: a moderator, or friend)
// remove_user: Whether or not the user ID should be removed from the project/organization team after the test
@@ -181,6 +204,11 @@ impl<'a> PermissionsTest<'a> {
resp.status().as_u16()
));
}
if resp.status() == StatusCode::OK {
if let Some(failure_json_check) = &self.failure_json_check {
failure_json_check(&test::read_body_json(resp).await);
}
}
// Failure test- logged in on a non-team user
let request = req_gen(&PermissionsTestContext {
@@ -202,6 +230,11 @@ impl<'a> PermissionsTest<'a> {
resp.status().as_u16()
));
}
if resp.status() == StatusCode::OK {
if let Some(failure_json_check) = &self.failure_json_check {
failure_json_check(&test::read_body_json(resp).await);
}
}
// Failure test- logged in with EVERY non-relevant permission
let request = req_gen(&PermissionsTestContext {
@@ -223,6 +256,11 @@ impl<'a> PermissionsTest<'a> {
resp.status().as_u16()
));
}
if resp.status() == StatusCode::OK {
if let Some(failure_json_check) = &self.failure_json_check {
failure_json_check(&test::read_body_json(resp).await);
}
}
// Patch user's permissions to success permissions
modify_user_team_permissions(
@@ -250,6 +288,11 @@ impl<'a> PermissionsTest<'a> {
resp.status().as_u16()
));
}
if resp.status() == StatusCode::OK {
if let Some(success_json_check) = &self.success_json_check {
success_json_check(&test::read_body_json(resp).await);
}
}
// If the remove_user flag is set, remove the user from the project
// Relevant for existing projects/users