YongGoose commented on code in PR #946:
URL: https://github.com/apache/burr/pull/946#discussion_r4718694287


##########
burr/tracking/common/identifiers.py:
##########
@@ -0,0 +1,108 @@
+# 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.
+
+"""Validation for the identifiers (project names, application ids) that the 
tracking
+layer turns into filesystem paths, plus a helper that keeps the resulting 
paths inside
+the storage directory."""
+
+import os
+import re
+from typing import Optional
+
+from burr import system
+
+# Any character except the path separators ("/" and "\") and the control 
characters
+# (NUL through unit separator, and DEL). Checked with ``fullmatch`` so the 
whole value
+# has to satisfy it; a trailing newline is a control character and is refused 
like any
+# other.
+IDENTIFIER_PATTERN = re.compile(r"[^/\\\x00-\x1f\x7f]+")
+MAX_IDENTIFIER_LENGTH = 255
+
+
+class InvalidIdentifier(ValueError):
+    """An identifier cannot be used as a path segment under the storage 
directory, or a
+    joined path would not stay inside it.
+
+    Subclasses :class:`ValueError` so existing ``except ValueError`` handlers 
keep working;
+    callers that want to report the problem specifically (for instance as an 
HTTP 400) can
+    catch this class instead.
+    """
+
+
+def validate_identifier(value: str, what: str, *, on_windows: Optional[bool] = 
None) -> str:
+    """Checks that ``value`` can be used as any single path segment under the 
storage directory.
+
+    The rule: a non-empty string of at most 255 characters that is not the 
special directory
+    name ``.`` or ``..`` and contains no ``/``, ``\\``, NUL or other control 
character. On
+    Windows ``:`` is also refused, as it is a drive/stream separator there. 
Everything else --
+    spaces, ``@``, dots, unicode letters -- is an ordinary filename character 
and is accepted,
+    so ids such as ``[email protected]`` or ``chat session 1`` keep working.
+
+    :param value: the identifier to check
+    :param what: short label for the error message, e.g. ``"app_id"`` or 
``"project"``
+    :param on_windows: platform override, defaults to the current platform; 
exposed for tests
+    :return: ``value`` unchanged, so the call can be used inline
+    :raises InvalidIdentifier: if the identifier does not meet the rule
+    """
+    if on_windows is None:
+        on_windows = system.IS_WINDOWS
+    if not isinstance(value, str):
+        raise InvalidIdentifier(f"{what} must be a string, got 
{type(value).__name__}: {value!r}")
+    if not value:
+        raise InvalidIdentifier(f"{what} must not be empty")
+    if len(value) > MAX_IDENTIFIER_LENGTH:
+        raise InvalidIdentifier(
+            f"{what} must be at most {MAX_IDENTIFIER_LENGTH} characters, got 
{len(value)}"
+        )
+    if value in (".", ".."):
+        raise InvalidIdentifier(f"{what} must not be '.' or '..', got 
{value!r}")
+    if IDENTIFIER_PATTERN.fullmatch(value) is None:
+        raise InvalidIdentifier(
+            f"{what} must be a single path segment: it may not contain '/', 
'\\' or control "
+            f"characters, got {value!r}"
+        )
+    if on_windows and ":" in value:
+        raise InvalidIdentifier(f"{what} may not contain ':' on Windows, got 
{value!r}")
+    return value
+
+
+def join_within(base: str, *parts: str) -> str:
+    """Joins ``parts`` onto ``base`` and checks that the result stays strictly 
inside ``base``.
+
+    Both sides are resolved with :func:`os.path.realpath` before comparing, so 
``..`` segments
+    and symlinks are accounted for. The path returned is the plain join (not 
the resolved
+    form) so callers see the same spelling they would get from 
:func:`os.path.join`.
+
+    :param base: the directory the result must stay inside
+    :param parts: path components to join onto ``base``
+    :return: ``os.path.join(base, *parts)``
+    :raises InvalidIdentifier: if the joined path would land outside ``base``
+    """
+    joined = os.path.join(base, *parts)
+    base_resolved = os.path.realpath(base)
+    target_resolved = os.path.realpath(joined)

Review Comment:
   Because both sides go through `realpath`, a project or app directory that is 
a symlink to another disk is now refused, even though its path is lexically 
inside the storage dir. On `main`, these layouts work:
   
   - `storage/proj -> /bigdisk/proj`: `main` writes the run into 
`/bigdisk/proj/app1/`. This PR raises `InvalidIdentifier: Path 
'.../storage/proj' is not inside the storage directory '.../storage'` from 
`LocalTrackingClient(...)`.
   - `storage/proj2/app1 -> /archive/app1`: `main` writes into 
`/archive/app1/`. This PR raises the same error at `build()`.
   - A symlinked `storage_dir` itself works on both.
   
   With #948 also merged, the server returns 400 for such a project. #948's 
`test_symlinked_project_outside_storage_is_rejected` shows that's intended 
there. `validate_identifier` already guarantees a single segment, so lexically 
nothing can escape, and `realpath` only adds the symlink rule.
   
   If the rule is intended for the client too, two small things would help 
someone who hits it after upgrading: a release-note line, and an error that 
says the path resolves outside the storage dir through a symlink. As it stands, 
the message names a path that is visibly inside the storage dir.



##########
burr/tracking/client.py:
##########
@@ -190,11 +192,7 @@ def __init__(
         """
 
         self.f = None
-        if not _allowed_project_name(project, on_windows=system.IS_WINDOWS):
-            raise ValueError(
-                f"Project: {project} is not valid. Project name cannot contain 
non-alphanumeric (except _ and -) characters."
-                "We will be relaxing this restriction later but for now please 
rename your project!"
-            )
+        validate_identifier(project, "project")

Review Comment:
   Widening project names to "any single segment" also lets in `#`, `?` and 
`%`. `main` rejected all of these for projects (`a#b`, `a?b`, `my project`, 
`a.b`, `日本語` → `ValueError`). With this PR, all of them build and write.
   
   The server handles them when the path is percent-encoded. On main + #946 + 
#948, `GET /api/v0/a%23b/__none__/apps`, `.../a%3Fb/...` and `.../100%25/...` 
all returned 200.
   
   The UI's generated client, though, encodes path params with `encodeURI` 
(`telemetry/ui/src/api/core/request.ts:106`), and `encodeURI("a#b")` returns 
`a#b` unchanged. A request for that unescaped path turns into `GET /api/v0/a` → 
404, and `a?b` is split into a query string → 404. I didn't load the UI in a 
browser; this is the client function plus the server's response to the 
unescaped path.
   
   App ids already allowed these characters on `main`, so this only newly 
affects projects. #1047's description lists this `encodeURI` behavior as one of 
the things it fixes. Until it lands, would you keep `#`, `?` and `%` out of 
project names, or is it fine to depend on #1047?



##########
burr/tracking/common/identifiers.py:
##########
@@ -0,0 +1,108 @@
+# 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.
+
+"""Validation for the identifiers (project names, application ids) that the 
tracking
+layer turns into filesystem paths, plus a helper that keeps the resulting 
paths inside
+the storage directory."""
+
+import os
+import re
+from typing import Optional
+
+from burr import system
+
+# Any character except the path separators ("/" and "\") and the control 
characters
+# (NUL through unit separator, and DEL). Checked with ``fullmatch`` so the 
whole value
+# has to satisfy it; a trailing newline is a control character and is refused 
like any
+# other.
+IDENTIFIER_PATTERN = re.compile(r"[^/\\\x00-\x1f\x7f]+")
+MAX_IDENTIFIER_LENGTH = 255
+
+
+class InvalidIdentifier(ValueError):
+    """An identifier cannot be used as a path segment under the storage 
directory, or a
+    joined path would not stay inside it.
+
+    Subclasses :class:`ValueError` so existing ``except ValueError`` handlers 
keep working;
+    callers that want to report the problem specifically (for instance as an 
HTTP 400) can
+    catch this class instead.
+    """
+
+
+def validate_identifier(value: str, what: str, *, on_windows: Optional[bool] = 
None) -> str:
+    """Checks that ``value`` can be used as any single path segment under the 
storage directory.
+
+    The rule: a non-empty string of at most 255 characters that is not the 
special directory
+    name ``.`` or ``..`` and contains no ``/``, ``\\``, NUL or other control 
character. On
+    Windows ``:`` is also refused, as it is a drive/stream separator there. 
Everything else --
+    spaces, ``@``, dots, unicode letters -- is an ordinary filename character 
and is accepted,
+    so ids such as ``[email protected]`` or ``chat session 1`` keep working.
+
+    :param value: the identifier to check
+    :param what: short label for the error message, e.g. ``"app_id"`` or 
``"project"``
+    :param on_windows: platform override, defaults to the current platform; 
exposed for tests
+    :return: ``value`` unchanged, so the call can be used inline
+    :raises InvalidIdentifier: if the identifier does not meet the rule
+    """
+    if on_windows is None:
+        on_windows = system.IS_WINDOWS
+    if not isinstance(value, str):
+        raise InvalidIdentifier(f"{what} must be a string, got 
{type(value).__name__}: {value!r}")
+    if not value:
+        raise InvalidIdentifier(f"{what} must not be empty")
+    if len(value) > MAX_IDENTIFIER_LENGTH:
+        raise InvalidIdentifier(
+            f"{what} must be at most {MAX_IDENTIFIER_LENGTH} characters, got 
{len(value)}"
+        )
+    if value in (".", ".."):
+        raise InvalidIdentifier(f"{what} must not be '.' or '..', got 
{value!r}")
+    if IDENTIFIER_PATTERN.fullmatch(value) is None:
+        raise InvalidIdentifier(
+            f"{what} must be a single path segment: it may not contain '/', 
'\\' or control "
+            f"characters, got {value!r}"
+        )
+    if on_windows and ":" in value:

Review Comment:
   Question: on Windows, `<>"|?*` are reserved filename characters as well as 
`:`. `main` rejected `*` (and everything but `[A-Za-z0-9_-:]`) in project names 
on every platform, and `test__allowed_project_name` now expects `"Chars*"` to 
pass. On Linux, `a*b` now builds and writes. I couldn't run Windows, but going 
by the naming rules, a name like that would get past this check and fail inside 
`os.makedirs` with an `OSError` instead of an `InvalidIdentifier`. If the 
Windows branch is meant to catch what the filesystem refuses, the full reserved 
set may be worth checking here.



##########
burr/tracking/client.py:
##########
@@ -109,13 +109,15 @@ def _filter_inputs(d: dict) -> dict:
 
 
 def _allowed_project_name(project_name: str, on_windows: bool) -> bool:
-    allowed_chars = r"a-zA-Z0-9_\-"
-    if not on_windows:
-        allowed_chars += ":"
-    pattern = f"^[{allowed_chars}]+$"
+    """Whether ``project_name`` passes the identifier rule shared with app ids.
 
-    # Use regular expression to check if the string is valid
-    return bool(re.match(pattern, project_name))
+    Kept as a boolean wrapper around :func:`validate_identifier` for existing 
callers.

Review Comment:
   Nit: within the repo, the only remaining caller is 
`test__allowed_project_name`. `burr/tracking/s3client.py:100` has its own copy 
with the old regex, and nothing calls that one either. Unless this is meant as 
public API, both could go, with the test pointed at `validate_identifier`.



##########
burr/tracking/client.py:
##########
@@ -370,14 +383,16 @@ def load_state(
         prior_state["__SEQUENCE_ID"] = line_seq  # add the sequence id back
         return prior_state, entry_point
 
-    def _ensure_dir_structure(self, app_id: str):
+    def _ensure_dir_structure(self, app_id: str) -> str:
+        # Validate the id before anything is created on disk
+        application_path = self._application_directory(app_id)
         if not os.path.exists(self.storage_dir):
             logger.info(f"Creating storage directory: {self.storage_dir}")
             os.makedirs(self.storage_dir)
-        application_path = os.path.join(self.storage_dir, app_id)
         if not os.path.exists(application_path):
             logger.info(f"Creating application directory: {application_path}")
             os.makedirs(application_path)

Review Comment:
   This check-then-create predates the PR, but the PR touches this function and 
it shows up under concurrency. When several apps in the same project are built 
at once, two threads both see the directory missing, and the second 
`os.makedirs` raises `FileExistsError` out of `build()`.
   
   I ran the scenario from the 2026-10-31 comment on Linux: 8 threads × 3 apps 
each, in one fresh project, 20 rounds. Rounds that hit `FileExistsError: [Errno 
17] File exists: '.../proj'`:
   
   | | container-local disk | bind mount |
   |---|---|---|
   | `main` | 20 / 20 | 11 / 20 |
   | this PR | 4 / 20 | 11 / 20 |
   | this PR + the change below | 0 / 20 | 0 / 20 |
   
   `join_within` never raised in those runs. I applied exactly this change to 
the PR:
   
   ```suggestion
               os.makedirs(self.storage_dir, exist_ok=True)
           if not os.path.exists(application_path):
               logger.info(f"Creating application directory: 
{application_path}")
               os.makedirs(application_path, exist_ok=True)
   ```



-- 
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