skrawcz commented on code in PR #687:
URL: https://github.com/apache/burr/pull/687#discussion_r3455158399


##########
burr/tracking/server/workspace.py:
##########
@@ -0,0 +1,700 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Workspace API router for the Burr tracking server.
+
+Provides endpoints for:
+- File browsing and content reading within a workspace directory
+- Python script execution with SSE output streaming
+- Process lifecycle management (start, stop, list)
+- Workspace-to-project linking (stored in ~/.burr/workspace_links.json)
+- Builder project persistence (stored in ~/.burr/builder_projects/)
+- Burr ApplicationBuilder usage scanning across .py files
+"""
+
+import asyncio
+import json as json_module
+import logging
+import os
+import re
+import signal
+import threading
+import time
+from typing import Dict, List, Optional
+
+from fastapi import APIRouter, HTTPException, Query
+from fastapi.responses import StreamingResponse
+from pydantic import BaseModel
+
+logger = logging.getLogger(__name__)
+
+router = APIRouter()
+
+_initialized = True  # Module loaded successfully if we reach this point
+
+MAX_FILE_SIZE = 1_048_576  # 1MB
+
+LANGUAGE_MAP = {
+    ".py": "python",
+    ".js": "javascript",
+    ".ts": "typescript",
+    ".tsx": "tsx",
+    ".jsx": "jsx",
+    ".json": "json",
+    ".yaml": "yaml",
+    ".yml": "yaml",
+    ".toml": "toml",
+    ".md": "markdown",
+    ".html": "html",
+    ".css": "css",
+    ".sql": "sql",
+    ".sh": "bash",
+    ".txt": "text",
+}
+
+BURR_APP_PATTERN = re.compile(r"ApplicationBuilder")
+
+
+# --- Pydantic Models ---
+
+
+class WorkspaceLinkRequest(BaseModel):
+    """Request body for linking a workspace directory to a project."""
+
+    project_id: str
+    workspace_path: str
+
+
+class WorkspaceLinkInfo(BaseModel):
+    """Response for workspace link queries. workspace_path is None if not 
linked."""
+
+    project_id: str
+    workspace_path: Optional[str]
+
+
+class BuilderProjectSave(BaseModel):
+    """Request body for saving a builder project."""
+
+    name: str
+    graph_json: str  # JSON-serialized tree
+
+
+class BuilderProjectSummary(BaseModel):
+    """Summary of a saved builder project (used in list responses)."""
+
+    id: str
+    name: str
+    updated_at: float
+
+
+class BuilderProjectFull(BaseModel):
+    """Full builder project including the serialized graph."""
+
+    id: str
+    name: str
+    graph_json: str
+    updated_at: float
+
+
+class WorkspaceOpenRequest(BaseModel):
+    """Request body for opening/validating a workspace directory."""
+
+    path: str
+
+
+class WorkspaceInfo(BaseModel):
+    """Basic info about an opened workspace."""
+
+    path: str
+    name: str
+
+
+class FileEntry(BaseModel):
+    """A single file or directory entry in a workspace listing."""
+
+    name: str
+    path: str  # relative to workspace root
+    is_dir: bool
+    size: int
+    modified: float
+    is_python: bool
+    has_burr_app: bool
+
+
+class FileContent(BaseModel):
+    """Contents of a single file with detected language."""
+
+    path: str
+    content: str
+    language: str
+    size: int
+
+
+class ProcessInfo(BaseModel):
+    """Status of a running or completed Python process."""
+
+    pid: int
+    script_path: str
+    started_at: float
+    status: str  # "running" | "stopped" | "exited"
+    exit_code: Optional[int]
+
+
+class RunRequest(BaseModel):
+    """Request body to start a Python script."""
+
+    workspace: str
+    script: str
+
+
+# --- Security ---
+
+
+def _validate_path(workspace: str, relative: str) -> str:
+    """Resolve and validate a file path within a workspace.
+
+    Prevents path traversal by ensuring the resolved target stays within
+    the workspace directory. Uses os.sep suffix check to prevent /foo
+    matching /foobar.
+
+    Args:
+        workspace: Absolute path to the workspace root.
+        relative: Relative path within the workspace (may be empty).
+
+    Returns:
+        The resolved absolute path to the target.
+
+    Raises:
+        HTTPException: 403 if path traversal is detected.
+    """
+    workspace_real = os.path.realpath(workspace)
+    if relative:
+        target = os.path.realpath(os.path.join(workspace_real, relative))
+    else:
+        target = workspace_real
+    # Use os.sep suffix to prevent /foo matching /foobar
+    if target != workspace_real and not target.startswith(workspace_real + 
os.sep):
+        raise HTTPException(status_code=403, detail="Path traversal detected")
+    return target
+
+
+def _validate_workspace(workspace: str) -> str:
+    """Validate that a workspace path is registered via the /link endpoint.
+
+    Checks the workspace against ~/.burr/workspace_links.json to ensure
+    only explicitly linked directories can be accessed.
+
+    Args:
+        workspace: Absolute path to validate.
+
+    Returns:
+        The resolved absolute path.
+
+    Raises:
+        HTTPException: 400 if directory doesn't exist, 403 if not registered.
+    """
+    workspace_real = os.path.realpath(workspace)
+    if not os.path.isdir(workspace_real):
+        raise HTTPException(status_code=400, detail="Workspace directory does 
not exist")
+    links = _read_links()
+    allowed = {os.path.realpath(p) for p in links.values()}
+    if workspace_real not in allowed:
+        raise HTTPException(status_code=403, detail="Workspace not registered")
+    return workspace_real
+
+
+def _is_binary(file_path: str) -> bool:
+    """Detect if a file is binary by checking for null bytes in the first 
8KB."""
+    try:
+        with open(file_path, "rb") as f:
+            chunk = f.read(8192)
+            return b"\x00" in chunk
+    except OSError:
+        return True
+
+
+# --- Workspace Links ---
+
+_LINKS_PATH = os.path.join(os.path.expanduser("~/.burr"), 
"workspace_links.json")
+
+# In-process cache for workspace links to avoid disk reads on every request.
+_links_cache: Optional[dict] = None
+_links_cache_lock = threading.Lock()
+
+
+def _read_links() -> dict:
+    """Read workspace-to-project links from ~/.burr/workspace_links.json.
+
+    Uses an in-process cache that is invalidated on writes via _write_links().
+    """
+    global _links_cache
+    with _links_cache_lock:
+        if _links_cache is not None:
+            return _links_cache
+    if os.path.exists(_LINKS_PATH):
+        with open(_LINKS_PATH, "r") as f:
+            data = json_module.load(f)
+    else:
+        data = {}
+    with _links_cache_lock:
+        _links_cache = data
+    return data
+
+
+def _write_links(data: dict):
+    """Write workspace-to-project links to ~/.burr/workspace_links.json.
+
+    Invalidates the in-process cache so subsequent reads pick up changes.
+    """
+    global _links_cache
+    os.makedirs(os.path.dirname(_LINKS_PATH), exist_ok=True)
+    with open(_LINKS_PATH, "w") as f:
+        json_module.dump(data, f, indent=2)
+    with _links_cache_lock:
+        _links_cache = data

Review Comment:
   again we don't need the lock.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to