gemini-code-assist[bot] commented on code in PR #49:
URL: https://github.com/apache/tvm-ffi/pull/49#discussion_r2373405754


##########
python/tvm_ffi/utils/prototype.py:
##########
@@ -0,0 +1,55 @@
+# 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.
+"""Helpers that mirros registered TypeInfo into Python dataclass syntax."""
+
+from io import StringIO
+
+from ..core import TypeInfo
+
+
+def prototype_py(type_info: TypeInfo) -> str:
+    """Generate a Python prototype of the given TypeInfo."""
+    assert isinstance(type_info, TypeInfo)
+    assert type_info.parent_type_info is not None
+
+    cls_name = type_info.type_key.rsplit(".", maxsplit=1)[-1]
+    parent_type_key = type_info.parent_type_info.type_key
+    io = StringIO()
+    print(
+        f"""
+from typing import Any
+from tvm_ffi import dataclasses as D
+from tvm_ffi import core
+
+PARENT_TYPE = 
core._lookup_type_info_from_type_key({parent_type_key!r}).type_cls
+assert PARENT_TYPE is not None
+
+""",
+        file=io,
+    )
+    print(f"@D.c_class({type_info.type_key!r})", file=io)
+    print(f"class {cls_name}(PARENT_TYPE):", file=io)
+    for field in type_info.fields:
+        print(f"  {field.name}: Any", file=io)
+    for method in type_info.methods:
+        name = method.name
+        if method.is_static:
+            print("  @staticmethod", file=io)
+            print(f"  def {name}(*args): ...", file=io)
+        else:
+            print(f"  def {name}(self, *args): ...", file=io)
+    return io.getvalue().strip()

Review Comment:
   ![high](https://www.gstatic.com/codereviewagent/high-priority.svg)
   
   The `prototype_py` function generates Python source code which is then 
executed using `exec`. This can be a security risk if any of the components 
from `type_info` (like `type_key`, field names, or method names) can be 
controlled by a malicious user to inject arbitrary code.
   
   For example, if a field name is `my_field\n  import os; os.system('echo 
pwned')`, it could lead to arbitrary code execution.
   
   To mitigate this, you should validate that `cls_name`, `field.name`, and 
`method.name` are all valid Python identifiers before embedding them into the 
generated code string. You can use the `str.isidentifier()` method for this 
validation.
   
   Example validation:
   ```python
       cls_name = type_info.type_key.rsplit(".", maxsplit=1)[-1]
       if not cls_name.isidentifier():
           raise ValueError(f"Class name '{cls_name}' is not a valid Python 
identifier.")
   
       # ...
   
       for field in type_info.fields:
           if not field.name.isidentifier():
               raise ValueError(f"Field name '{field.name}' is not a valid 
Python identifier.")
           print(f"  {field.name}: Any", file=io)
   
       for method in type_info.methods:
           name = method.name
           if not name.isidentifier():
               raise ValueError(f"Method name '{name}' is not a valid Python 
identifier.")
           # ...
   ```



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


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to