mirror of https://github.com/buster-so/buster.git
created api_chats_sharing_list
This commit is contained in:
parent
31cf5beb36
commit
f189c75b49
|
@ -7,6 +7,7 @@ pub mod types;
|
||||||
pub mod streaming_parser;
|
pub mod streaming_parser;
|
||||||
pub mod context_loaders;
|
pub mod context_loaders;
|
||||||
pub mod list_chats_handler;
|
pub mod list_chats_handler;
|
||||||
|
pub mod sharing;
|
||||||
|
|
||||||
pub use get_chat_handler::get_chat_handler;
|
pub use get_chat_handler::get_chat_handler;
|
||||||
pub use get_raw_llm_messages_handler::get_raw_llm_messages_handler;
|
pub use get_raw_llm_messages_handler::get_raw_llm_messages_handler;
|
||||||
|
|
|
@ -0,0 +1,121 @@
|
||||||
|
use anyhow::{anyhow, Result};
|
||||||
|
use database::{
|
||||||
|
enums::{AssetPermissionRole, AssetType, IdentityType},
|
||||||
|
pool::get_pg_pool,
|
||||||
|
schema::chats,
|
||||||
|
};
|
||||||
|
use diesel::{ExpressionMethods, QueryDsl};
|
||||||
|
use diesel_async::RunQueryDsl;
|
||||||
|
use sharing::{
|
||||||
|
check_asset_permission::check_access,
|
||||||
|
list_asset_permissions::list_shares,
|
||||||
|
types::AssetPermissionWithUser,
|
||||||
|
};
|
||||||
|
use tracing::{error, info};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
/// Lists all sharing permissions for a specific chat
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `chat_id` - The unique identifier of the chat
|
||||||
|
/// * `user_id` - The unique identifier of the user requesting the permissions
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// A vector of asset permissions with user information
|
||||||
|
pub async fn list_chat_sharing_handler(
|
||||||
|
chat_id: &Uuid,
|
||||||
|
user_id: &Uuid,
|
||||||
|
) -> Result<Vec<AssetPermissionWithUser>> {
|
||||||
|
info!(
|
||||||
|
chat_id = %chat_id,
|
||||||
|
user_id = %user_id,
|
||||||
|
"Listing chat sharing permissions"
|
||||||
|
);
|
||||||
|
|
||||||
|
// 1. Validate the chat exists
|
||||||
|
let mut conn = get_pg_pool().get().await.map_err(|e| {
|
||||||
|
error!("Database connection error: {}", e);
|
||||||
|
anyhow!("Failed to get database connection: {}", e)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let chat_exists = chats::table
|
||||||
|
.filter(chats::id.eq(chat_id))
|
||||||
|
.filter(chats::deleted_at.is_null())
|
||||||
|
.count()
|
||||||
|
.get_result::<i64>(&mut conn)
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
error!("Error checking if chat exists: {}", e);
|
||||||
|
anyhow!("Database error: {}", e)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
if chat_exists == 0 {
|
||||||
|
error!(
|
||||||
|
chat_id = %chat_id,
|
||||||
|
"Chat not found"
|
||||||
|
);
|
||||||
|
return Err(anyhow!("Chat not found"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Check if user has permission to view the chat
|
||||||
|
let user_role = check_access(
|
||||||
|
*chat_id,
|
||||||
|
AssetType::Chat,
|
||||||
|
*user_id,
|
||||||
|
IdentityType::User,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
error!(
|
||||||
|
chat_id = %chat_id,
|
||||||
|
user_id = %user_id,
|
||||||
|
"Error checking chat access: {}", e
|
||||||
|
);
|
||||||
|
anyhow!("Error checking chat access: {}", e)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
if user_role.is_none() {
|
||||||
|
error!(
|
||||||
|
chat_id = %chat_id,
|
||||||
|
user_id = %user_id,
|
||||||
|
"User does not have permission to view this chat"
|
||||||
|
);
|
||||||
|
return Err(anyhow!("User does not have permission to view this chat"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Get all permissions for the chat
|
||||||
|
let permissions = list_shares(
|
||||||
|
*chat_id,
|
||||||
|
AssetType::Chat,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
error!(
|
||||||
|
chat_id = %chat_id,
|
||||||
|
"Error listing chat permissions: {}", e
|
||||||
|
);
|
||||||
|
anyhow!("Error listing sharing permissions: {}", e)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
info!(
|
||||||
|
chat_id = %chat_id,
|
||||||
|
permission_count = permissions.len(),
|
||||||
|
"Successfully retrieved chat sharing permissions"
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(permissions)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_list_chat_sharing_handler() {
|
||||||
|
// Placeholder test implementation
|
||||||
|
// In a real test, we would set up test data and verify the response
|
||||||
|
assert!(true);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,3 @@
|
||||||
|
mod list_sharing_handler;
|
||||||
|
|
||||||
|
pub use list_sharing_handler::list_chat_sharing_handler;
|
|
@ -1,4 +1,4 @@
|
||||||
# API Chats Sharing - List Endpoint PRD
|
# API Chats Sharing - List Endpoint PRD ✅
|
||||||
|
|
||||||
## Problem Statement
|
## Problem Statement
|
||||||
Users need the ability to view all sharing permissions for a chat via a REST API endpoint.
|
Users need the ability to view all sharing permissions for a chat via a REST API endpoint.
|
||||||
|
|
|
@ -54,10 +54,10 @@ The PRDs can be developed in the following order, with opportunities for paralle
|
||||||
- Update `/src/routes/rest/routes/chats/mod.rs` to include the sharing router
|
- Update `/src/routes/rest/routes/chats/mod.rs` to include the sharing router
|
||||||
- Update `/libs/handlers/src/chats/mod.rs` to export the sharing module
|
- Update `/libs/handlers/src/chats/mod.rs` to export the sharing module
|
||||||
|
|
||||||
### Phase 2: Core Endpoints (Can be Parallelized)
|
### Phase 2: Core Endpoints (Can be Parallelized) ✅
|
||||||
After Phase 1 is complete, the following components can be implemented in parallel by different developers:
|
After Phase 1 is complete, the following components can be implemented in parallel by different developers:
|
||||||
|
|
||||||
- **List Sharing Endpoint**
|
- **List Sharing Endpoint** ✅
|
||||||
- Uses `list_shares` from `@[api/libs/sharing/src]/list_asset_permissions.rs`
|
- Uses `list_shares` from `@[api/libs/sharing/src]/list_asset_permissions.rs`
|
||||||
- Uses `check_access` from `@[api/libs/sharing/src]/check_asset_permission.rs`
|
- Uses `check_access` from `@[api/libs/sharing/src]/check_asset_permission.rs`
|
||||||
|
|
||||||
|
|
|
@ -8,6 +8,7 @@ mod get_chat;
|
||||||
mod get_chat_raw_llm_messages;
|
mod get_chat_raw_llm_messages;
|
||||||
mod list_chats;
|
mod list_chats;
|
||||||
mod post_chat;
|
mod post_chat;
|
||||||
|
mod sharing;
|
||||||
mod update_chats;
|
mod update_chats;
|
||||||
|
|
||||||
pub use delete_chats::delete_chats_route;
|
pub use delete_chats::delete_chats_route;
|
||||||
|
@ -25,4 +26,5 @@ pub fn router() -> Router {
|
||||||
.route("/", delete(delete_chats_route))
|
.route("/", delete(delete_chats_route))
|
||||||
.route("/:id", get(get_chat_route))
|
.route("/:id", get(get_chat_route))
|
||||||
.route("/:id/raw_llm_messages", get(get_chat_raw_llm_messages))
|
.route("/:id/raw_llm_messages", get(get_chat_raw_llm_messages))
|
||||||
|
.nest("/:id/sharing", sharing::router())
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,74 @@
|
||||||
|
use axum::{
|
||||||
|
extract::{Extension, Path},
|
||||||
|
http::StatusCode,
|
||||||
|
};
|
||||||
|
use handlers::chats::sharing::list_chat_sharing_handler;
|
||||||
|
use middleware::AuthenticatedUser;
|
||||||
|
use serde::Serialize;
|
||||||
|
use tracing::info;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::routes::rest::ApiResponse;
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct SharingPermission {
|
||||||
|
pub user_id: Uuid,
|
||||||
|
pub email: String,
|
||||||
|
pub name: Option<String>,
|
||||||
|
pub avatar_url: Option<String>,
|
||||||
|
pub role: database::enums::AssetPermissionRole,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct SharingResponse {
|
||||||
|
pub permissions: Vec<SharingPermission>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// REST handler for listing chat sharing permissions
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `user` - The authenticated user making the request
|
||||||
|
/// * `id` - The unique identifier of the chat
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// A JSON response containing all sharing permissions for the chat
|
||||||
|
pub async fn list_chat_sharing_rest_handler(
|
||||||
|
Extension(user): Extension<AuthenticatedUser>,
|
||||||
|
Path(id): Path<Uuid>,
|
||||||
|
) -> Result<ApiResponse<SharingResponse>, (StatusCode, String)> {
|
||||||
|
info!(
|
||||||
|
chat_id = %id,
|
||||||
|
user_id = %user.id,
|
||||||
|
"Processing GET request for chat sharing permissions"
|
||||||
|
);
|
||||||
|
|
||||||
|
match list_chat_sharing_handler(&id, &user.id).await {
|
||||||
|
Ok(permissions) => {
|
||||||
|
let response = SharingResponse {
|
||||||
|
permissions: permissions
|
||||||
|
.into_iter()
|
||||||
|
.map(|p| SharingPermission {
|
||||||
|
user_id: p.user.as_ref().map(|u| u.id).unwrap_or_default(),
|
||||||
|
email: p.user.as_ref().map(|u| u.email.clone()).unwrap_or_default(),
|
||||||
|
name: p.user.as_ref().and_then(|u| u.name.clone()),
|
||||||
|
avatar_url: p.user.as_ref().and_then(|u| u.avatar_url.clone()),
|
||||||
|
role: p.permission.role,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
};
|
||||||
|
Ok(ApiResponse::JsonData(response))
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Error listing chat sharing permissions: {}", e);
|
||||||
|
if e.to_string().contains("not found") {
|
||||||
|
return Err((StatusCode::NOT_FOUND, format!("Chat not found: {}", e)));
|
||||||
|
} else if e.to_string().contains("permission") {
|
||||||
|
return Err((StatusCode::FORBIDDEN, format!("Permission denied: {}", e)));
|
||||||
|
} else {
|
||||||
|
return Err((StatusCode::INTERNAL_SERVER_ERROR, format!("Failed to list sharing permissions: {}", e)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,13 @@
|
||||||
|
use axum::{
|
||||||
|
routing::get,
|
||||||
|
Router,
|
||||||
|
};
|
||||||
|
|
||||||
|
mod list_sharing;
|
||||||
|
|
||||||
|
pub use list_sharing::list_chat_sharing_rest_handler;
|
||||||
|
|
||||||
|
pub fn router() -> Router {
|
||||||
|
Router::new()
|
||||||
|
.route("/", get(list_chat_sharing_rest_handler))
|
||||||
|
}
|
|
@ -0,0 +1 @@
|
||||||
|
pub mod sharing;
|
|
@ -0,0 +1,170 @@
|
||||||
|
use std::sync::Arc;
|
||||||
|
use axum::{
|
||||||
|
body::Body,
|
||||||
|
extract::connect_info::MockConnectInfo,
|
||||||
|
http::{Request, StatusCode},
|
||||||
|
};
|
||||||
|
use uuid::Uuid;
|
||||||
|
use database::{
|
||||||
|
enums::{AssetPermissionRole, AssetType, IdentityType},
|
||||||
|
models::{AssetPermission, Chat, User},
|
||||||
|
};
|
||||||
|
use crate::common::{
|
||||||
|
assertions::response::{assert_json_response, assert_status},
|
||||||
|
db::setup_test_db,
|
||||||
|
fixtures::{
|
||||||
|
chats::create_test_chat,
|
||||||
|
users::create_test_user,
|
||||||
|
},
|
||||||
|
http::client::TestClient,
|
||||||
|
};
|
||||||
|
use chrono::Utc;
|
||||||
|
|
||||||
|
// Test listing sharing permissions for a chat
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_list_chat_sharing_permissions() {
|
||||||
|
// Setup test database and create test users and chat
|
||||||
|
let pool = setup_test_db().await;
|
||||||
|
let mut conn = pool.get().await.unwrap();
|
||||||
|
|
||||||
|
// Create test users
|
||||||
|
let owner = create_test_user(&mut conn).await;
|
||||||
|
let viewer = create_test_user(&mut conn).await;
|
||||||
|
|
||||||
|
// Create test chat
|
||||||
|
let chat = create_test_chat(&mut conn, &owner.id).await;
|
||||||
|
|
||||||
|
// Create sharing permission for the viewer
|
||||||
|
let permission = AssetPermission {
|
||||||
|
identity_id: viewer.id,
|
||||||
|
identity_type: IdentityType::User,
|
||||||
|
asset_id: chat.id,
|
||||||
|
asset_type: AssetType::Chat,
|
||||||
|
role: AssetPermissionRole::CanView,
|
||||||
|
created_at: Utc::now(),
|
||||||
|
updated_at: Utc::now(),
|
||||||
|
deleted_at: None,
|
||||||
|
created_by: owner.id,
|
||||||
|
updated_by: owner.id,
|
||||||
|
};
|
||||||
|
|
||||||
|
diesel::insert_into(database::schema::asset_permissions::table)
|
||||||
|
.values(&permission)
|
||||||
|
.execute(&mut conn)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// Make request as owner
|
||||||
|
let client = TestClient::new(
|
||||||
|
Arc::new(MockConnectInfo(([127, 0, 0, 1], 8080))),
|
||||||
|
owner,
|
||||||
|
);
|
||||||
|
|
||||||
|
let response = client
|
||||||
|
.get(&format!("/chats/{}/sharing", chat.id))
|
||||||
|
.send()
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// Assert successful response
|
||||||
|
assert_status!(response, StatusCode::OK);
|
||||||
|
|
||||||
|
// Verify response contains the sharing permission
|
||||||
|
let body = response.into_body();
|
||||||
|
let json = hyper::body::to_bytes(body).await.unwrap();
|
||||||
|
let response: serde_json::Value = serde_json::from_slice(&json).unwrap();
|
||||||
|
|
||||||
|
assert!(response["permissions"].is_array());
|
||||||
|
assert_eq!(response["permissions"].as_array().unwrap().len(), 1);
|
||||||
|
assert_eq!(response["permissions"][0]["user_id"], viewer.id.to_string());
|
||||||
|
assert_eq!(response["permissions"][0]["role"], "CanView");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test listing sharing permissions for a chat that doesn't exist
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_list_sharing_nonexistent_chat() {
|
||||||
|
// Setup test database and create test users
|
||||||
|
let pool = setup_test_db().await;
|
||||||
|
let mut conn = pool.get().await.unwrap();
|
||||||
|
|
||||||
|
// Create test user
|
||||||
|
let user = create_test_user(&mut conn).await;
|
||||||
|
|
||||||
|
// Make request with non-existent chat ID
|
||||||
|
let client = TestClient::new(
|
||||||
|
Arc::new(MockConnectInfo(([127, 0, 0, 1], 8080))),
|
||||||
|
user,
|
||||||
|
);
|
||||||
|
|
||||||
|
let response = client
|
||||||
|
.get(&format!("/chats/{}/sharing", Uuid::new_v4()))
|
||||||
|
.send()
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// Assert not found response
|
||||||
|
assert_status!(response, StatusCode::NOT_FOUND);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test listing sharing permissions for a chat without permission
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_list_sharing_without_permission() {
|
||||||
|
// Setup test database and create test users and chat
|
||||||
|
let pool = setup_test_db().await;
|
||||||
|
let mut conn = pool.get().await.unwrap();
|
||||||
|
|
||||||
|
// Create test users
|
||||||
|
let owner = create_test_user(&mut conn).await;
|
||||||
|
let unauthorized_user = create_test_user(&mut conn).await;
|
||||||
|
|
||||||
|
// Create test chat
|
||||||
|
let chat = create_test_chat(&mut conn, &owner.id).await;
|
||||||
|
|
||||||
|
// Make request as unauthorized user
|
||||||
|
let client = TestClient::new(
|
||||||
|
Arc::new(MockConnectInfo(([127, 0, 0, 1], 8080))),
|
||||||
|
unauthorized_user,
|
||||||
|
);
|
||||||
|
|
||||||
|
let response = client
|
||||||
|
.get(&format!("/chats/{}/sharing", chat.id))
|
||||||
|
.send()
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// Assert forbidden response
|
||||||
|
assert_status!(response, StatusCode::FORBIDDEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test listing sharing permissions for a chat with no sharing permissions
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_list_empty_sharing_permissions() {
|
||||||
|
// Setup test database and create test users and chat
|
||||||
|
let pool = setup_test_db().await;
|
||||||
|
let mut conn = pool.get().await.unwrap();
|
||||||
|
|
||||||
|
// Create test user
|
||||||
|
let user = create_test_user(&mut conn).await;
|
||||||
|
|
||||||
|
// Create test chat
|
||||||
|
let chat = create_test_chat(&mut conn, &user.id).await;
|
||||||
|
|
||||||
|
// Make request as owner
|
||||||
|
let client = TestClient::new(
|
||||||
|
Arc::new(MockConnectInfo(([127, 0, 0, 1], 8080))),
|
||||||
|
user,
|
||||||
|
);
|
||||||
|
|
||||||
|
let response = client
|
||||||
|
.get(&format!("/chats/{}/sharing", chat.id))
|
||||||
|
.send()
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// Assert successful response
|
||||||
|
assert_status!(response, StatusCode::OK);
|
||||||
|
|
||||||
|
// Verify response contains empty permissions array
|
||||||
|
let body = response.into_body();
|
||||||
|
let json = hyper::body::to_bytes(body).await.unwrap();
|
||||||
|
let response: serde_json::Value = serde_json::from_slice(&json).unwrap();
|
||||||
|
|
||||||
|
assert!(response["permissions"].is_array());
|
||||||
|
assert_eq!(response["permissions"].as_array().unwrap().len(), 0);
|
||||||
|
}
|
|
@ -0,0 +1 @@
|
||||||
|
mod list_sharing_test;
|
|
@ -1,4 +1,5 @@
|
||||||
// Export test modules
|
// Export test modules
|
||||||
|
pub mod chats;
|
||||||
pub mod dashboards;
|
pub mod dashboards;
|
||||||
pub mod collections;
|
pub mod collections;
|
||||||
pub mod metrics;
|
pub mod metrics;
|
||||||
|
|
Loading…
Reference in New Issue