|
1 | | -"""Listings behind the directory pickers ``/api/browse-dirs`` and ``/api/browse-files``.""" |
| 1 | +"""Listings behind the directory pickers ``/api/browse-dirs`` and ``/api/browse-files``, |
| 2 | +and the project picker's folder create, ``POST /api/browse-dirs/create``.""" |
2 | 3 |
|
3 | 4 | from __future__ import annotations |
4 | 5 |
|
| 6 | +import errno |
| 7 | +import ntpath |
5 | 8 | import os |
6 | 9 | from typing import TYPE_CHECKING |
7 | 10 |
|
| 11 | +from aiohttp import web |
| 12 | + |
8 | 13 | if TYPE_CHECKING: |
9 | 14 | from kiro_crew.dashboard.handlers.files import ( |
10 | 15 | _WIN_DRIVE_ROOT_RE, |
| 16 | + _PathProbeBusy, |
| 17 | + _probe_busy_response, |
| 18 | + _run_path_probe, |
| 19 | + _sel, |
11 | 20 | is_sensitive_canonical_path, |
| 21 | + logger, |
| 22 | + pinned_fs, |
12 | 23 | platform_compat, |
| 24 | + read_bounded_json, |
| 25 | + require_owner_dashboard_request, |
13 | 26 | ) |
14 | 27 |
|
15 | 28 |
|
@@ -138,3 +151,134 @@ def _browse_parent(base: str) -> str: |
138 | 151 | if _is_windows_drive_root(base): |
139 | 152 | return "" |
140 | 153 | return os.path.dirname(base) |
| 154 | + |
| 155 | + |
| 156 | +def _create_browse_dir_sync(parent: str, name: str) -> tuple[str, str]: |
| 157 | + """Make folder *name* inside directory *parent*: ``(outcome, path)``. |
| 158 | +
|
| 159 | + Blocking (``realpath`` then ``mkdir``); the route runs it on the probe pool. |
| 160 | + The target is spelled the way the OS will create it (``abspath``: on Windows |
| 161 | + ``C:x`` leaves *parent* and a trailing dot is dropped) and must sit directly |
| 162 | + in *parent*. It then meets the sensitive-path floor before anything is |
| 163 | + created, so the picker cannot make a protected folder (``~/.aws`` in a home |
| 164 | + without one); a path inside a protected one is protected too, so this also |
| 165 | + refuses a protected *parent*. Outcomes: ``created``, ``sensitive``, |
| 166 | + ``exists``, ``not_found`` (the parent is gone or is not a directory), |
| 167 | + ``parent_changed``, ``permission_denied``, ``invalid_name`` and ``failed``. |
| 168 | +
|
| 169 | + The checked *parent* is pinned before the create, the way uploads pin theirs, |
| 170 | + so an ancestor swapped for a link after the check cannot redirect the folder |
| 171 | + into a protected place: on POSIX the leaf is made relative to a descriptor |
| 172 | + walked with ``O_NOFOLLOW`` (``pinned_fs.pin_parent``); on Windows a handle |
| 173 | + without delete sharing locks the chain against renames while ``mkdir`` runs, |
| 174 | + once its final path is confirmed to be *parent*. A swap is ``parent_changed``. |
| 175 | + """ |
| 176 | + base = os.path.realpath(os.path.expanduser(parent)) |
| 177 | + target = os.path.abspath(os.path.join(base, name)) |
| 178 | + if os.path.normcase(os.path.dirname(target)) != os.path.normcase(base): |
| 179 | + return "invalid_name", target |
| 180 | + if is_sensitive_canonical_path(target): |
| 181 | + return "sensitive", target |
| 182 | + guard_fd: int | None = None |
| 183 | + try: |
| 184 | + if pinned_fs.supports_pinned_walk() and os.mkdir in os.supports_dir_fd: |
| 185 | + guard_fd = pinned_fs.pin_parent(base, what="new folder's parent") |
| 186 | + os.mkdir(os.path.basename(target), dir_fd=guard_fd) |
| 187 | + elif platform_compat.IS_WINDOWS: |
| 188 | + guard_fd = platform_compat.pin_directory(base, links_only=True) |
| 189 | + pinned = pinned_fs.fd_real_path(guard_fd) |
| 190 | + if pinned is None or ntpath.normcase(ntpath.normpath(pinned)) != ntpath.normcase( |
| 191 | + ntpath.normpath(base) |
| 192 | + ): |
| 193 | + return "parent_changed", target |
| 194 | + os.mkdir(target) |
| 195 | + else: |
| 196 | + # Neither pin exists here (unreachable on Linux, macOS and Windows): |
| 197 | + # a by-name mkdir would be the unguarded swap window, so refuse. |
| 198 | + return "failed", target |
| 199 | + except (pinned_fs.PinnedPathRefusal, NotADirectoryError): |
| 200 | + # The POSIX walk and the Windows pin refuse a link and a non-directory alike; |
| 201 | + # a parent that is no directory at all is the plain "gone" case, anything |
| 202 | + # else was swapped. |
| 203 | + return ("parent_changed" if os.path.isdir(base) else "not_found"), target |
| 204 | + except FileExistsError: |
| 205 | + return "exists", target |
| 206 | + except FileNotFoundError: |
| 207 | + # With the parent still there it was the name: Windows reports an overlong |
| 208 | + # one as a missing path. |
| 209 | + return ("invalid_name" if os.path.isdir(base) else "not_found"), target |
| 210 | + except PermissionError: |
| 211 | + return "permission_denied", target |
| 212 | + except ValueError: # a NUL or an unencodable character in the name |
| 213 | + return "invalid_name", target |
| 214 | + except OSError as exc: |
| 215 | + if exc.errno == errno.EROFS: |
| 216 | + return "permission_denied", target |
| 217 | + if exc.errno in (errno.ENAMETOOLONG, errno.EINVAL): |
| 218 | + return "invalid_name", target |
| 219 | + if exc.errno == errno.ELOOP: |
| 220 | + return "parent_changed", target |
| 221 | + logger.warning("browse_create_dir failed for %s: errno %s", target, exc.errno) |
| 222 | + return "failed", target |
| 223 | + finally: |
| 224 | + if guard_fd is not None: |
| 225 | + os.close(guard_fd) |
| 226 | + return "created", target |
| 227 | + |
| 228 | + |
| 229 | +async def api_browse_create_dir(request: web.Request) -> web.Response: |
| 230 | + """POST /api/browse-dirs/create -- make one folder in the directory the picker shows. |
| 231 | +
|
| 232 | + Body ``{"parent": <directory>, "name": <folder name>}``; answers 201 |
| 233 | + ``{"path"}`` with the new folder's path so the picker can list it. Owner-only, |
| 234 | + checked before the body is read, like ``/api/file-write``: it writes to the |
| 235 | + gateway host's filesystem. *name* is one path component, so the route makes |
| 236 | + exactly one folder level. Every refusal carries a ``code`` for the picker. |
| 237 | + """ |
| 238 | + owner_denied = await require_owner_dashboard_request(request, "browse_create_dir") |
| 239 | + if owner_denied is not None: |
| 240 | + return owner_denied |
| 241 | + caller = request.get("user", "dashboard") |
| 242 | + body, body_err = await read_bounded_json(request) |
| 243 | + if body_err is not None: |
| 244 | + return body_err |
| 245 | + assert body is not None # read_bounded_json returns (dict, None) on success |
| 246 | + parent, name = body.get("parent"), body.get("name") |
| 247 | + if not isinstance(parent, str) or not parent.strip(): |
| 248 | + return web.json_response( |
| 249 | + {"error": "A parent directory is required", "code": "parent_required"}, status=400 |
| 250 | + ) |
| 251 | + if not isinstance(name, str) or name in ("", ".", "..") or "/" in name or "\\" in name: |
| 252 | + return web.json_response( |
| 253 | + {"error": "Not a valid folder name", "code": "invalid_name"}, status=400 |
| 254 | + ) |
| 255 | + try: |
| 256 | + outcome, target = await _run_path_probe(_create_browse_dir_sync, parent.strip(), name) |
| 257 | + except _PathProbeBusy: |
| 258 | + return _probe_busy_response(resource=parent, operation="browse_create_dir", caller=caller) |
| 259 | + if outcome == "created": |
| 260 | + _sel().log_api_access( |
| 261 | + caller=caller, operation="browse_create_dir", outcome="allowed", resources=target |
| 262 | + ) |
| 263 | + return web.json_response({"path": target}, status=201) |
| 264 | + status, code, message = { |
| 265 | + "sensitive": (403, "access_denied", "Access denied"), |
| 266 | + "exists": (409, "already_exists", "A file or folder with that name already exists"), |
| 267 | + "not_found": (404, "not_found", "The parent directory no longer exists"), |
| 268 | + "parent_changed": ( |
| 269 | + 409, |
| 270 | + "parent_changed", |
| 271 | + "The parent directory changed while the folder was being created", |
| 272 | + ), |
| 273 | + "permission_denied": (403, "permission_denied", "No permission to create a folder here"), |
| 274 | + "invalid_name": (400, "invalid_name", "Not a valid folder name"), |
| 275 | + "failed": (500, "create_failed", "Could not create the folder"), |
| 276 | + }[outcome] |
| 277 | + _sel().log_api_access( |
| 278 | + caller=caller, |
| 279 | + operation="browse_create_dir", |
| 280 | + outcome="denied" if status < 500 else "failure", |
| 281 | + resources=target, |
| 282 | + error=code, |
| 283 | + ) |
| 284 | + return web.json_response({"error": message, "code": code}, status=status) |
0 commit comments