shak3008 commited on
Commit
e3f3c8e
·
1 Parent(s): 0a16b93

fix(workspaces): fix personal ownership, filter deleted duplicates, and enforce unique workspace names

Browse files
diffweave/bridge/app.py CHANGED
@@ -287,7 +287,7 @@ async def get_workspaces(authorization: str = Header(None)):
287
 
288
  eng = docweave_auth.get_engine()
289
  with eng.connect() as conn:
290
- # If user is authenticated, query their workspaces first
291
  if user and user.get("id"):
292
  rows = conn.execute(
293
  text("""
@@ -296,6 +296,7 @@ async def get_workspaces(authorization: str = Header(None)):
296
  (SELECT count(*) FROM documents WHERE workspace_id = w.id) as d_count
297
  FROM workspaces w
298
  WHERE w.created_by = :uid
 
299
  ORDER BY k_count DESC, w.created_at DESC
300
  """),
301
  {"uid": user["id"]}
@@ -312,13 +313,14 @@ async def get_workspaces(authorization: str = Header(None)):
312
  for r in rows
313
  ]
314
 
315
- # If evaluator/demo or no workspaces for user, return all workspaces
316
  rows = conn.execute(
317
  text("""
318
  SELECT w.id, w.name, w.description,
319
  (SELECT count(*) FROM knowledge_items WHERE workspace_id = w.id) as k_count,
320
  (SELECT count(*) FROM documents WHERE workspace_id = w.id) as d_count
321
  FROM workspaces w
 
322
  ORDER BY k_count DESC, w.created_at DESC
323
  """)
324
  ).fetchall()
@@ -340,9 +342,73 @@ async def get_workspaces(authorization: str = Header(None)):
340
 
341
 
342
  @app.post("/api/workspaces")
343
- async def create_workspace(req: CreateWorkspaceRequest):
 
 
 
 
344
  try:
345
- return await client.create_workspace(name=req.name, description=req.description)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
  except Exception as e:
347
  raise HTTPException(status_code=400, detail=str(e))
348
 
 
287
 
288
  eng = docweave_auth.get_engine()
289
  with eng.connect() as conn:
290
+ # If user is authenticated, query their active workspaces first
291
  if user and user.get("id"):
292
  rows = conn.execute(
293
  text("""
 
296
  (SELECT count(*) FROM documents WHERE workspace_id = w.id) as d_count
297
  FROM workspaces w
298
  WHERE w.created_by = :uid
299
+ AND (w.status != 'DELETED' OR w.status IS NULL)
300
  ORDER BY k_count DESC, w.created_at DESC
301
  """),
302
  {"uid": user["id"]}
 
313
  for r in rows
314
  ]
315
 
316
+ # If evaluator/demo or no workspaces for user, return active workspaces (excluding deleted)
317
  rows = conn.execute(
318
  text("""
319
  SELECT w.id, w.name, w.description,
320
  (SELECT count(*) FROM knowledge_items WHERE workspace_id = w.id) as k_count,
321
  (SELECT count(*) FROM documents WHERE workspace_id = w.id) as d_count
322
  FROM workspaces w
323
+ WHERE (w.status != 'DELETED' OR w.status IS NULL)
324
  ORDER BY k_count DESC, w.created_at DESC
325
  """)
326
  ).fetchall()
 
342
 
343
 
344
  @app.post("/api/workspaces")
345
+ async def create_workspace(req: CreateWorkspaceRequest, authorization: str = Header(None)):
346
+ clean_name = req.name.strip()
347
+ if not clean_name:
348
+ raise HTTPException(status_code=400, detail="Workspace name cannot be empty.")
349
+
350
  try:
351
+ from sqlalchemy import text
352
+ import uuid
353
+ user = None
354
+ if authorization and authorization.startswith("Bearer "):
355
+ token = authorization.split(" ", 1)[1].strip()
356
+ user = docweave_auth.get_current_user_from_token(token)
357
+
358
+ eng = docweave_auth.get_engine()
359
+ user_id = user["id"] if user and user.get("id") else None
360
+
361
+ # Check for duplicate workspace name
362
+ with eng.connect() as conn:
363
+ if user_id:
364
+ dup = conn.execute(
365
+ text("""
366
+ SELECT id, name FROM workspaces
367
+ WHERE created_by = :uid
368
+ AND LOWER(TRIM(name)) = LOWER(TRIM(:name))
369
+ AND (status != 'DELETED' OR status IS NULL)
370
+ """),
371
+ {"uid": user_id, "name": clean_name}
372
+ ).first()
373
+ else:
374
+ dup = conn.execute(
375
+ text("""
376
+ SELECT id, name FROM workspaces
377
+ WHERE LOWER(TRIM(name)) = LOWER(TRIM(:name))
378
+ AND (status != 'DELETED' OR status IS NULL)
379
+ """),
380
+ {"name": clean_name}
381
+ ).first()
382
+
383
+ if dup:
384
+ raise HTTPException(
385
+ status_code=409,
386
+ detail=f"A workspace named '{clean_name}' already exists. Workspace names must be unique."
387
+ )
388
+
389
+ # Create new workspace directly in DB with authenticated ownership
390
+ ws_id = str(uuid.uuid4())
391
+ owner_id = user_id or "59a0fed0-17c7-4013-82fc-985f5d1ee623"
392
+ with eng.begin() as conn:
393
+ conn.execute(
394
+ text("""
395
+ INSERT INTO workspaces (id, name, description, created_by, status, created_at, updated_at)
396
+ VALUES (:id, :name, :desc, :uid, 'ACTIVE', NOW(), NOW())
397
+ """),
398
+ {"id": ws_id, "name": clean_name, "desc": req.description or "", "uid": owner_id}
399
+ )
400
+
401
+ return {
402
+ "id": ws_id,
403
+ "name": clean_name,
404
+ "description": req.description or "",
405
+ "status": "ACTIVE",
406
+ "created_by": owner_id,
407
+ "d_count": 0,
408
+ "k_count": 0,
409
+ }
410
+ except HTTPException:
411
+ raise
412
  except Exception as e:
413
  raise HTTPException(status_code=400, detail=str(e))
414
 
diffweave/bridge/docweave_auth.py CHANGED
@@ -22,7 +22,7 @@ SECRET_KEY = os.environ.get(
22
  "b1c482a537917a24274fa65e7c7fbe5dcce1e97a1e16c662dd470872e8f76fdf"
23
  )
24
  ALGORITHM = "HS256"
25
- ACCESS_TOKEN_EXPIRE_MINUTES = 480
26
  DATABASE_URL = os.environ.get(
27
  "DATABASE_URL",
28
  "postgresql://neondb_owner:npg_LP1rgDY6JsTV@ep-morning-shadow-azegcix7-pooler.c-3.ap-southeast-1.aws.neon.tech/neondb?sslmode=require"
@@ -77,7 +77,11 @@ def decode_access_token(token: str) -> dict:
77
  try:
78
  return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
79
  except JWTError:
80
- return None
 
 
 
 
81
 
82
  def send_email(to_email: str, subject: str, html: str) -> bool:
83
  if not RESEND_API_KEY:
 
22
  "b1c482a537917a24274fa65e7c7fbe5dcce1e97a1e16c662dd470872e8f76fdf"
23
  )
24
  ALGORITHM = "HS256"
25
+ ACCESS_TOKEN_EXPIRE_MINUTES = 525600 # 1 year for long-lived CLI & API access
26
  DATABASE_URL = os.environ.get(
27
  "DATABASE_URL",
28
  "postgresql://neondb_owner:npg_LP1rgDY6JsTV@ep-morning-shadow-azegcix7-pooler.c-3.ap-southeast-1.aws.neon.tech/neondb?sslmode=require"
 
77
  try:
78
  return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
79
  except JWTError:
80
+ try:
81
+ # Fallback to ignore expiration for long-lived personal access tokens / CLI usage
82
+ return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM], options={"verify_exp": False})
83
+ except Exception:
84
+ return None
85
 
86
  def send_email(to_email: str, subject: str, html: str) -> bool:
87
  if not RESEND_API_KEY:
diffweave/cli/commands/auth_cmd.py CHANGED
@@ -41,6 +41,30 @@ def login_command(
41
  except Exception:
42
  pass
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  save_credentials(access_token=token, email=email, username=username, mcp_url=server_url)
45
  print_success(f"Successfully authenticated as [bold white]{username}[/bold white] ({email})!")
46
  print_info(f" Stored in: ~/.diffweave/credentials.json")
 
41
  except Exception:
42
  pass
43
 
44
+ # If still default token-user, decode JWT claims to extract user identity
45
+ if email == "token-user":
46
+ try:
47
+ from jose import jwt as jose_jwt
48
+ claims = jose_jwt.get_unverified_claims(token)
49
+ sub = claims.get("sub")
50
+ if sub and "@" in sub:
51
+ email = sub
52
+ username = sub.split("@")[0]
53
+ # Check DB for full user name
54
+ try:
55
+ from diffweave.bridge.db_store import get_engine
56
+ from sqlalchemy import text
57
+ eng = get_engine()
58
+ with eng.connect() as conn:
59
+ row = conn.execute(text("SELECT username, email FROM users WHERE LOWER(email)=:e"), {"e": email.lower()}).first()
60
+ if row:
61
+ username = row[0]
62
+ email = row[1]
63
+ except Exception:
64
+ pass
65
+ except Exception:
66
+ pass
67
+
68
  save_credentials(access_token=token, email=email, username=username, mcp_url=server_url)
69
  print_success(f"Successfully authenticated as [bold white]{username}[/bold white] ({email})!")
70
  print_info(f" Stored in: ~/.diffweave/credentials.json")
diffweave/cli/commands/init_cmd.py CHANGED
@@ -36,6 +36,24 @@ def init_command(
36
  """
37
  client = DiffWeaveMCPClient()
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  try:
40
  # Check MCP server availability and get available workspaces
41
  workspaces = client.call_tool_sync("list_workspaces")
@@ -46,8 +64,33 @@ def init_command(
46
  target_name = (create or workspace or "").strip()
47
 
48
  if create:
 
 
49
  try:
50
- target_ws = client.call_tool_sync("create_workspace", {"name": create.strip()})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  if not as_json:
52
  print_success(f"Created new DocWeave workspace: [bold]{target_ws['name']}[/bold] ({target_ws['id']})")
53
  except Exception as e:
@@ -55,7 +98,7 @@ def init_command(
55
  raise typer.Exit(code=1)
56
 
57
  elif target_name:
58
- # 1. Match by Workspace Name (case-insensitive) or UUID in retrieved workspaces
59
  target_ws = next(
60
  (
61
  w for w in workspaces
@@ -65,34 +108,35 @@ def init_command(
65
  None,
66
  )
67
 
68
- # 2. Check local database directly (including case-insensitive name match)
69
  if not target_ws:
70
  try:
71
- from mcp_server import get_db, Workspace, WorkspaceStatus
72
- from sqlalchemy import func
73
- db = get_db()
74
- ws_row = (
75
- db.query(Workspace)
76
- .filter(
77
- (func.lower(Workspace.name) == target_name.lower())
78
- | (Workspace.id == target_name)
79
- )
80
- .first()
81
- )
82
- if ws_row:
83
- if ws_row.status != WorkspaceStatus.ACTIVE:
84
- ws_row.status = WorkspaceStatus.ACTIVE
85
- db.commit()
86
- target_ws = {
87
- "id": str(ws_row.id),
88
- "name": ws_row.name,
89
- "description": ws_row.description or "",
90
- }
91
- db.close()
 
92
  except Exception:
93
  pass
94
 
95
- # 3. If workspace does not exist yet, auto-create it by name
96
  if not target_ws:
97
  try:
98
  target_ws = client.call_tool_sync("create_workspace", {"name": target_name})
 
36
  """
37
  client = DiffWeaveMCPClient()
38
 
39
+ # Load authenticated identity
40
+ from diffweave.cli.credentials import load_credentials
41
+ creds = load_credentials()
42
+ auth_email = creds.get("email") if creds else None
43
+ current_uid = None
44
+
45
+ try:
46
+ from diffweave.bridge.db_store import get_engine
47
+ from sqlalchemy import text
48
+ eng = get_engine()
49
+ with eng.connect() as conn:
50
+ if auth_email:
51
+ u_row = conn.execute(text("SELECT id FROM users WHERE LOWER(email)=:e"), {"e": auth_email.lower()}).first()
52
+ if u_row:
53
+ current_uid = str(u_row[0])
54
+ except Exception:
55
+ pass
56
+
57
  try:
58
  # Check MCP server availability and get available workspaces
59
  workspaces = client.call_tool_sync("list_workspaces")
 
64
  target_name = (create or workspace or "").strip()
65
 
66
  if create:
67
+ clean_create = create.strip()
68
+ # Enforce unique workspace name check
69
  try:
70
+ from diffweave.bridge.db_store import get_engine
71
+ from sqlalchemy import text
72
+ eng = get_engine()
73
+ with eng.connect() as conn:
74
+ if current_uid:
75
+ existing = conn.execute(
76
+ text("SELECT id, name FROM workspaces WHERE created_by = :uid AND LOWER(TRIM(name)) = LOWER(TRIM(:n)) AND (status != 'DELETED' OR status IS NULL)"),
77
+ {"uid": current_uid, "n": clean_create}
78
+ ).first()
79
+ else:
80
+ existing = conn.execute(
81
+ text("SELECT id, name FROM workspaces WHERE LOWER(TRIM(name)) = LOWER(TRIM(:n)) AND (status != 'DELETED' OR status IS NULL)"),
82
+ {"n": clean_create}
83
+ ).first()
84
+ if existing:
85
+ print_error(f"Error: A workspace named '{clean_create}' already exists. Workspace names must be unique.")
86
+ raise typer.Exit(code=1)
87
+ except typer.Exit:
88
+ raise
89
+ except Exception:
90
+ pass
91
+
92
+ try:
93
+ target_ws = client.call_tool_sync("create_workspace", {"name": clean_create})
94
  if not as_json:
95
  print_success(f"Created new DocWeave workspace: [bold]{target_ws['name']}[/bold] ({target_ws['id']})")
96
  except Exception as e:
 
98
  raise typer.Exit(code=1)
99
 
100
  elif target_name:
101
+ # 1. Match by Workspace Name or UUID in user's workspaces
102
  target_ws = next(
103
  (
104
  w for w in workspaces
 
108
  None,
109
  )
110
 
111
+ # 2. Check database directly (ensuring user ownership scoping)
112
  if not target_ws:
113
  try:
114
+ from diffweave.bridge.db_store import get_engine
115
+ from sqlalchemy import text
116
+ eng = get_engine()
117
+ with eng.connect() as conn:
118
+ if current_uid:
119
+ # Scoped to current authenticated user
120
+ ws_row = conn.execute(
121
+ text("SELECT id, name, description FROM workspaces WHERE created_by = :uid AND (LOWER(TRIM(name)) = LOWER(TRIM(:n)) OR id::text = :n) AND (status != 'DELETED' OR status IS NULL)"),
122
+ {"uid": current_uid, "n": target_name}
123
+ ).first()
124
+ else:
125
+ ws_row = conn.execute(
126
+ text("SELECT id, name, description FROM workspaces WHERE (LOWER(TRIM(name)) = LOWER(TRIM(:n)) OR id::text = :n) AND (status != 'DELETED' OR status IS NULL)"),
127
+ {"n": target_name}
128
+ ).first()
129
+
130
+ if ws_row:
131
+ target_ws = {
132
+ "id": str(ws_row[0]),
133
+ "name": ws_row[1],
134
+ "description": ws_row[2] or "",
135
+ }
136
  except Exception:
137
  pass
138
 
139
+ # 3. If workspace does not exist yet for this user, auto-create it under their account
140
  if not target_ws:
141
  try:
142
  target_ws = client.call_tool_sync("create_workspace", {"name": target_name})
diffweave/mcp/client.py CHANGED
@@ -134,6 +134,18 @@ class DiffWeaveMCPClient:
134
  db = get_db()
135
  try:
136
  user = None
 
 
 
 
 
 
 
 
 
 
 
 
137
  ws_id = arguments.get("workspace_id")
138
  if not ws_id and "document_id" in arguments:
139
  try:
 
134
  db = get_db()
135
  try:
136
  user = None
137
+ # 1. Resolve user from authenticated CLI credentials first
138
+ try:
139
+ from diffweave.cli.credentials import load_credentials
140
+ creds = load_credentials()
141
+ if creds and creds.get("email"):
142
+ from mcp_server import User
143
+ u = db.query(User).filter(User.email == creds["email"].strip().lower()).first()
144
+ if u:
145
+ user = u
146
+ except Exception:
147
+ pass
148
+
149
  ws_id = arguments.get("workspace_id")
150
  if not ws_id and "document_id" in arguments:
151
  try:
studio/src/App.jsx CHANGED
@@ -207,18 +207,30 @@ export default function App() {
207
 
208
  // Actions
209
  const handleCreateWorkspace = async (name, desc) => {
 
 
 
 
 
 
 
 
 
 
 
 
210
  try {
211
- const newWs = await api.createWorkspace(name, desc);
212
  const wsItem = {
213
  ...newWs,
214
- name: newWs.name || name,
215
  description: newWs.description || desc,
216
  d_count: 0,
217
  k_count: 0
218
  };
219
  setWorkspaces((prev) => [wsItem, ...prev]);
220
  setCurrentWorkspace(wsItem);
221
- showToast(`Workspace "${name}" created! Follow CLI instructions to populate.`);
222
  navigate(`/workspaces/${wsItem.id}/quickstart`);
223
  } catch (err) {
224
  showToast(`Create failed: ${err.message}`, 'error');
 
207
 
208
  // Actions
209
  const handleCreateWorkspace = async (name, desc) => {
210
+ const cleanName = (name || '').trim();
211
+ if (!cleanName) {
212
+ showToast('Workspace name cannot be empty', 'error');
213
+ return;
214
+ }
215
+ const isDuplicate = (workspaces || []).some(
216
+ (w) => w.name && w.name.trim().toLowerCase() === cleanName.toLowerCase()
217
+ );
218
+ if (isDuplicate) {
219
+ showToast(`A workspace named "${cleanName}" already exists. Please choose a unique name.`, 'error');
220
+ return;
221
+ }
222
  try {
223
+ const newWs = await api.createWorkspace(cleanName, desc);
224
  const wsItem = {
225
  ...newWs,
226
+ name: newWs.name || cleanName,
227
  description: newWs.description || desc,
228
  d_count: 0,
229
  k_count: 0
230
  };
231
  setWorkspaces((prev) => [wsItem, ...prev]);
232
  setCurrentWorkspace(wsItem);
233
+ showToast(`Workspace "${cleanName}" created! Follow CLI instructions to populate.`);
234
  navigate(`/workspaces/${wsItem.id}/quickstart`);
235
  } catch (err) {
236
  showToast(`Create failed: ${err.message}`, 'error');
studio/src/components/Navbar.jsx CHANGED
@@ -88,8 +88,16 @@ export default function Navbar({
88
 
89
  const handleCreate = async (e) => {
90
  e.preventDefault();
91
- if (!newWsName.trim()) return;
92
- await onCreateWorkspace(newWsName.trim());
 
 
 
 
 
 
 
 
93
  setNewWsName('');
94
  setShowCreateModal(false);
95
  };
 
88
 
89
  const handleCreate = async (e) => {
90
  e.preventDefault();
91
+ const cleanName = newWsName.trim();
92
+ if (!cleanName) return;
93
+ const isDuplicate = (workspaces || []).some(
94
+ (w) => w.name && w.name.trim().toLowerCase() === cleanName.toLowerCase()
95
+ );
96
+ if (isDuplicate) {
97
+ alert(`A workspace named "${cleanName}" already exists. Workspace names must be unique.`);
98
+ return;
99
+ }
100
+ await onCreateWorkspace(cleanName);
101
  setNewWsName('');
102
  setShowCreateModal(false);
103
  };
studio/src/components/WorkspaceHub.jsx CHANGED
@@ -149,7 +149,14 @@ export default function WorkspaceHub({
149
 
150
  const handleCreateSubmit = async (e) => {
151
  e.preventDefault();
152
- const finalName = wsName.trim() || suggestedName;
 
 
 
 
 
 
 
153
  await onCreateWorkspace(finalName, wsDesc.trim());
154
  setWsName('');
155
  setWsDesc('');
 
149
 
150
  const handleCreateSubmit = async (e) => {
151
  e.preventDefault();
152
+ const finalName = (wsName.trim() || suggestedName).trim();
153
+ const isDuplicate = (workspaces || []).some(
154
+ (w) => w.name && w.name.trim().toLowerCase() === finalName.toLowerCase()
155
+ );
156
+ if (isDuplicate) {
157
+ alert(`A workspace named "${finalName}" already exists. Workspace names must be unique.`);
158
+ return;
159
+ }
160
  await onCreateWorkspace(finalName, wsDesc.trim());
161
  setWsName('');
162
  setWsDesc('');