Files
clawmates/crates/tc-api/tests/p0_endpoints.rs
T
Omar SobhandClaude Fable 5 000b9b3a4b P4 core: broker-held app connections + gated, broker-executed Slack posting
- app_connections repo; POST /api/apps/connect (keys/basic): the credential
  goes to the secret broker over its socket and only the encrypted ref lands
  in the row; disconnect endpoint; /api/apps directory merged with live
  connection status; audit rows for connect/disconnect
- Broker protocol: InvokeHttp carries a JSON body
- slack.post tool (SendsExternally -> gated): marked broker_executed — the
  runtime skips its own grant consumption and the BROKER independently
  verifies + consumes the single-use grant, then calls Slack with the bot
  token injected; the runtime never sees the credential
- Config: [broker] socket_path + [slack] base_url; e2e harness spawns the
  real teamclaw-broker daemon and the server hosts an e2e-only /__slack sink
- SlackApp: Connection tab stores the token via the broker; connected state
- Integration test: blocked while pending -> approved -> sink received
  exactly one post with 'Bearer xoxb-test-token' -> grant replay refused
- E2E journey: connect Slack in the panel -> gated post card with preview ->
  sink empty while pending -> approve -> exactly one post, queue clear

133 Rust + 63 frontend tests + 21 Playwright journeys.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-06-10 05:51:19 -05:00

281 lines
7.7 KiB
Rust

use serde_json::{json, Value};
use tc_api::AppState;
use tc_auth::AuthService;
use tc_domain::{
AccessPolicy, Agent, AgentId, AgentStatus, Role, User, UserId, Workspace, WorkspaceId,
};
struct TestServer {
base: String,
client: reqwest::Client,
}
/// Boots the real axum server on an ephemeral port over real TCP.
fn test_runtime(pool: sqlx::PgPool) -> tc_runtime::Runtime {
tc_runtime::Runtime::new(
pool,
std::sync::Arc::new(tc_llm::ScriptedProvider::from_toml("").unwrap()),
tc_runtime::RuntimeConfig::basic("scripted", 1024),
)
}
async fn serve(pool: sqlx::PgPool) -> TestServer {
let state = AppState::new(pool.clone(), test_runtime(pool));
let app = tc_api::router(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
TestServer {
base: format!("http://{addr}"),
client: reqwest::Client::new(),
}
}
async fn seed(pool: &sqlx::PgPool) -> (Workspace, User, Agent) {
let ws = Workspace {
id: WorkspaceId::new(),
name: "Acme".into(),
plan: "team".into(),
};
tc_db::repo::workspaces::insert(pool, &ws).await.unwrap();
let owner = User {
id: UserId::new(),
workspace_id: ws.id,
email: "[email protected]".into(),
role: Role::Owner,
display_name: "Owner".into(),
created_at: time::OffsetDateTime::UNIX_EPOCH,
};
tc_db::repo::users::insert(pool, &owner).await.unwrap();
let agent = Agent {
id: AgentId::new(),
workspace_id: ws.id,
name: "Scout".into(),
job_title: "Research Analyst".into(),
system_prompt: String::new(),
avatar: "scout-1".into(),
accent: "#f96565".into(),
wallpaper: "dunes".into(),
managed_by: owner.id,
status: AgentStatus::Online,
};
tc_db::repo::agents::insert(pool, &agent, &AccessPolicy::default())
.await
.unwrap();
AuthService::new(pool.clone())
.set_password(owner.id, "pw")
.await
.unwrap();
(ws, owner, agent)
}
async fn login(server: &TestServer) -> String {
let res = server
.client
.post(format!("{}/api/auth/login", server.base))
.json(&json!({"email": "[email protected]", "password": "pw"}))
.send()
.await
.unwrap();
assert_eq!(res.status(), 200);
res.json::<Value>().await.unwrap()["token"]
.as_str()
.unwrap()
.to_owned()
}
#[tokio::test]
async fn healthz_needs_no_auth() {
let pool = tc_testkit::test_pool().await;
let server = serve(pool).await;
let res = server
.client
.get(format!("{}/healthz", server.base))
.send()
.await
.unwrap();
assert_eq!(res.status(), 200);
}
#[tokio::test]
async fn protected_routes_reject_missing_or_bad_tokens() {
let pool = tc_testkit::test_pool().await;
let server = serve(pool).await;
for path in ["/api/user/me", "/api/team/claws", "/api/team/credits"] {
let bare = server
.client
.get(format!("{}{path}", server.base))
.send()
.await
.unwrap();
assert_eq!(bare.status(), 401, "{path} without token");
let bad = server
.client
.get(format!("{}{path}", server.base))
.bearer_auth("forged-token")
.send()
.await
.unwrap();
assert_eq!(bad.status(), 401, "{path} with forged token");
}
}
#[tokio::test]
async fn login_rejects_wrong_password() {
let pool = tc_testkit::test_pool().await;
seed(&pool).await;
let server = serve(pool).await;
let res = server
.client
.post(format!("{}/api/auth/login", server.base))
.json(&json!({"email": "[email protected]", "password": "nope"}))
.send()
.await
.unwrap();
assert_eq!(res.status(), 401);
}
#[tokio::test]
async fn user_me_returns_the_authenticated_user() {
let pool = tc_testkit::test_pool().await;
let (ws, owner, _) = seed(&pool).await;
let server = serve(pool).await;
let token = login(&server).await;
let me: Value = server
.client
.get(format!("{}/api/user/me", server.base))
.bearer_auth(&token)
.send()
.await
.unwrap()
.json()
.await
.unwrap();
assert_eq!(me["id"], owner.id.to_string());
assert_eq!(me["workspace_id"], ws.id.to_string());
assert_eq!(me["email"], "[email protected]");
assert_eq!(me["role"], "owner");
}
#[tokio::test]
async fn team_claws_lists_the_roster() {
let pool = tc_testkit::test_pool().await;
let (_, _, agent) = seed(&pool).await;
let server = serve(pool).await;
let token = login(&server).await;
let claws: Value = server
.client
.get(format!("{}/api/team/claws", server.base))
.bearer_auth(&token)
.send()
.await
.unwrap()
.json()
.await
.unwrap();
let list = claws.as_array().unwrap();
assert_eq!(list.len(), 1);
assert_eq!(list[0]["id"], agent.id.to_string());
assert_eq!(list[0]["name"], "Scout");
assert_eq!(list[0]["status"], "online");
}
#[tokio::test]
async fn team_credits_returns_available_balance() {
let pool = tc_testkit::test_pool().await;
let (ws, _, _) = seed(&pool).await;
tc_db::repo::credits::add_lot(&pool, ws.id, 500, "purchase")
.await
.unwrap();
let server = serve(pool).await;
let token = login(&server).await;
let credits: Value = server
.client
.get(format!("{}/api/team/credits", server.base))
.bearer_auth(&token)
.send()
.await
.unwrap()
.json()
.await
.unwrap();
assert_eq!(credits["available"], 500);
}
#[tokio::test]
async fn team_permissions_reflect_role() {
let pool = tc_testkit::test_pool().await;
seed(&pool).await;
let server = serve(pool).await;
let token = login(&server).await;
let perms: Value = server
.client
.get(format!("{}/api/team/permissions", server.base))
.bearer_auth(&token)
.send()
.await
.unwrap()
.json()
.await
.unwrap();
assert_eq!(perms["role"], "owner");
assert_eq!(perms["can_manage_team"], true);
assert_eq!(perms["can_manage_billing"], true);
}
#[tokio::test]
async fn logout_revokes_the_session() {
let pool = tc_testkit::test_pool().await;
seed(&pool).await;
let server = serve(pool).await;
let token = login(&server).await;
let res = server
.client
.post(format!("{}/api/auth/logout", server.base))
.bearer_auth(&token)
.send()
.await
.unwrap();
assert_eq!(res.status(), 204);
let me = server
.client
.get(format!("{}/api/user/me", server.base))
.bearer_auth(&token)
.send()
.await
.unwrap();
assert_eq!(me.status(), 401);
}
#[tokio::test]
async fn team_members_lists_workspace_users() {
let pool = tc_testkit::test_pool().await;
let (_, owner, _) = seed(&pool).await;
let server = serve(pool).await;
let token = login(&server).await;
let members: Value = server
.client
.get(format!("{}/api/team/members", server.base))
.bearer_auth(&token)
.send()
.await
.unwrap()
.json()
.await
.unwrap();
let list = members.as_array().unwrap();
assert_eq!(list.len(), 1);
assert_eq!(list[0]["id"], owner.id.to_string());
assert_eq!(list[0]["role"], "owner");
assert_eq!(list[0]["display_name"], "Owner");
}