research/publish: gate approve+reject on Owner role (#4)
ci / gates (push) Successful in 5s
ci / frontend (push) Successful in 24s
ci / rust (push) Successful in 4m5s
ci / e2e (push) Skipped
ci / publish (push) Successful in 4m32s

This commit was merged in pull request #4.
This commit is contained in:
2026-07-15 04:28:01 +00:00
parent dd791061ee
commit 1cb643142c
5 changed files with 149 additions and 5 deletions
+8 -2
View File
@@ -13,8 +13,8 @@
//! POST /api/research/:id/submit-review processing → reviewing //! POST /api/research/:id/submit-review processing → reviewing
//! POST /api/research/:id/request-publish create pending publish approval //! POST /api/research/:id/request-publish create pending publish approval
//! GET /api/research/publish-approvals list workspace's pending approvals //! GET /api/research/publish-approvals list workspace's pending approvals
//! POST /api/research/publish-approvals/:id/approve reviewing → publishing //! POST /api/research/publish-approvals/:id/approve reviewing → publishing (Owner only)
//! POST /api/research/publish-approvals/:id/reject stays in reviewing //! POST /api/research/publish-approvals/:id/reject stays in reviewing (Owner only)
//! POST /api/research/wizard/refine one-shot LLM refine helper //! POST /api/research/wizard/refine one-shot LLM refine helper
use axum::extract::{Path, State}; use axum::extract::{Path, State};
@@ -965,6 +965,12 @@ async fn decide_publish(
approve: bool, approve: bool,
notes: Option<String>, notes: Option<String>,
) -> Result<StatusCode, ApiError> { ) -> Result<StatusCode, ApiError> {
// Publish gate is workspace-owner-only. Members can request review (via
// POST /api/research/:id/publish) but cannot decide it — mirrors the
// billing/access-policy scope described in Role::is_owner (spec §1).
if !user.role.is_owner() {
return Err(ApiError::Forbidden);
}
let approval = let approval =
cm_db::repo::research_publish_approvals::get(&state.pool, id, user.workspace_id.as_uuid()) cm_db::repo::research_publish_approvals::get(&state.pool, id, user.workspace_id.as_uuid())
.await? .await?
@@ -0,0 +1,128 @@
//! Publish gate is Owner-only. The role check must fire before any DB
//! work, so we probe it with a bogus approval id: Members see 403 (role
//! guard), Owners see 404 (row missing) — proving ordering + coverage on
//! both approve and reject.
use std::sync::Arc;
use cm_api::AppState;
use cm_auth::AuthService;
use cm_domain::{Role, User, UserId, Workspace, WorkspaceId};
use cm_llm::ScriptedProvider;
use cm_runtime::{Runtime, RuntimeConfig};
use reqwest::StatusCode;
use serde_json::{json, Value};
use uuid::Uuid;
struct Server {
base: String,
client: reqwest::Client,
}
async fn serve(pool: sqlx::PgPool) -> Server {
let runtime = Runtime::new(
pool.clone(),
Arc::new(ScriptedProvider::from_toml("").unwrap()),
RuntimeConfig::basic("scripted", 1024),
);
let app = cm_api::router(AppState::new(pool, runtime));
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();
});
Server {
base: format!("http://{addr}"),
client: reqwest::Client::new(),
}
}
async fn seed_user(pool: &sqlx::PgPool, ws: WorkspaceId, role: Role, email: &str) -> UserId {
let user = User {
id: UserId::new(),
workspace_id: ws,
email: email.into(),
role,
display_name: format!("{role:?}"),
created_at: time::OffsetDateTime::UNIX_EPOCH,
};
cm_db::repo::users::insert(pool, &user).await.unwrap();
AuthService::new(pool.clone())
.set_password(user.id, "pw")
.await
.unwrap();
user.id
}
async fn login(server: &Server, email: &str) -> String {
server
.client
.post(format!("{}/api/auth/login", server.base))
.json(&json!({"email": email, "password": "pw"}))
.send()
.await
.unwrap()
.json::<Value>()
.await
.unwrap()["token"]
.as_str()
.unwrap()
.to_owned()
}
#[tokio::test]
async fn publish_decide_is_owner_only() {
let pool = cm_testkit::test_pool().await;
let server = serve(pool.clone()).await;
let ws = Workspace {
id: WorkspaceId::new(),
name: "Acme".into(),
plan: "team".into(),
};
cm_db::repo::workspaces::insert(&pool, &ws).await.unwrap();
let owner_email = format!("owner-{}@acme.test", UserId::new());
let member_email = format!("member-{}@acme.test", UserId::new());
seed_user(&pool, ws.id, Role::Owner, &owner_email).await;
seed_user(&pool, ws.id, Role::Member, &member_email).await;
let owner_tok = login(&server, &owner_email).await;
let member_tok = login(&server, &member_email).await;
// Bogus id: role guard should fire before the DB lookup.
let bogus = Uuid::now_v7();
for path in [
format!("/api/research/publish-approvals/{bogus}/approve"),
format!("/api/research/publish-approvals/{bogus}/reject"),
] {
let member_resp = server
.client
.post(format!("{}{path}", server.base))
.bearer_auth(&member_tok)
.json(&json!({}))
.send()
.await
.unwrap();
assert_eq!(
member_resp.status(),
StatusCode::FORBIDDEN,
"member should be forbidden on {path}"
);
let owner_resp = server
.client
.post(format!("{}{path}", server.base))
.bearer_auth(&owner_tok)
.json(&json!({}))
.send()
.await
.unwrap();
assert_eq!(
owner_resp.status(),
StatusCode::NOT_FOUND,
"owner should reach DB lookup + get 404 on {path}"
);
}
}
+1 -1
View File
@@ -19,5 +19,5 @@ export default async function WorkspaceHome() {
if (error instanceof ApiAuthError) redirect("/login"); if (error instanceof ApiAuthError) redirect("/login");
throw error; throw error;
} }
return <Dashboard user={{ display_name: user.display_name, email: user.email }} orgs={workspace.orgs} claws={workspace.claws} />; return <Dashboard user={{ display_name: user.display_name, email: user.email, role: user.role }} orgs={workspace.orgs} claws={workspace.claws} />;
} }
@@ -183,7 +183,7 @@ const EMPTY_ORG: DemoOrg = {
companies: [{ id: "", name: "Direct", topology: "flat", meta: "0 agents", teams: [{ id: "", name: "My Agents", topology: "flat", status: "idle", dot: "#3a3a40", agents: [], groupApps: [] }] }], companies: [{ id: "", name: "Direct", topology: "flat", meta: "0 agents", teams: [{ id: "", name: "My Agents", topology: "flat", status: "idle", dot: "#3a3a40", agents: [], groupApps: [] }] }],
}; };
export function Dashboard({ user, orgs, claws }: { user?: { display_name?: string; email?: string }; orgs: DemoOrg[]; claws: Agent[] }) { export function Dashboard({ user, orgs, claws }: { user?: { display_name?: string; email?: string; role?: "owner" | "member" }; orgs: DemoOrg[]; claws: Agent[] }) {
const agentById = new Map(claws.map((a) => [a.id, a])); const agentById = new Map(claws.map((a) => [a.id, a]));
// Live-data lookups over the workspace passed from the server (real claws + // Live-data lookups over the workspace passed from the server (real claws +
// structure). All scoped to `orgs` so the dashboard reflects the real account. // structure). All scoped to `orgs` so the dashboard reflects the real account.
@@ -762,6 +762,7 @@ export function Dashboard({ user, orgs, claws }: { user?: { display_name?: strin
agents={claws} agents={claws}
refreshKey={researchRefresh} refreshKey={researchRefresh}
onChanged={() => setResearchRefresh((n) => n + 1)} onChanged={() => setResearchRefresh((n) => n + 1)}
canApprovePublish={user?.role === "owner"}
/> />
) : isLoops ? ( ) : isLoops ? (
<LoopsCanvas <LoopsCanvas
@@ -88,11 +88,16 @@ export function ResearchCanvas({
agents, agents,
refreshKey, refreshKey,
onChanged, onChanged,
canApprovePublish = false,
}: { }: {
selectedId: string | null; selectedId: string | null;
agents: Agent[]; agents: Agent[];
refreshKey: number; refreshKey: number;
onChanged: () => void; onChanged: () => void;
/** True when the current user is a workspace Owner. Members can request
* publish but not decide it — matches the server's Role::Owner guard on
* POST /api/research/publish-approvals/:id/{approve,reject}. */
canApprovePublish?: boolean;
}) { }) {
const [topic, setTopic] = useState<TopicDetail | null>(null); const [topic, setTopic] = useState<TopicDetail | null>(null);
const [pendingApproval, setPendingApproval] = useState<PublishApproval | null>(null); const [pendingApproval, setPendingApproval] = useState<PublishApproval | null>(null);
@@ -742,7 +747,9 @@ export function ResearchCanvas({
</span> </span>
</div> </div>
<div style={{ fontFamily: mono, fontSize: 11, color: "#cfcfd5", lineHeight: 1.55 }}> <div style={{ fontFamily: mono, fontSize: 11, color: "#cfcfd5", lineHeight: 1.55 }}>
Any workspace member can decide.{" "} {canApprovePublish
? "Workspace owners decide publish."
: "A workspace owner needs to approve or reject."}{" "}
{boundApproval ? ( {boundApproval ? (
<> <>
Requested{" "} Requested{" "}
@@ -752,6 +759,7 @@ export function ResearchCanvas({
"Loading approval…" "Loading approval…"
)} )}
</div> </div>
{canApprovePublish ? (
<div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}> <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
<button <button
type="button" type="button"
@@ -802,6 +810,7 @@ export function ResearchCanvas({
Reject Reject
</button> </button>
</div> </div>
) : null}
{rejectFormOpen ? ( {rejectFormOpen ? (
<div <div
style={{ style={{